From e1029266256fe9d05abfd5e22595249b08fec985 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 1 Oct 2026 08:58:28 +0000 Subject: [PATCH] Web: own missions dialog and Mission Planner for the solo host The solo browser lists the uConsole's own missions, downloads them as share files, uploads files, edits or plans missions on a sector map and starts them; the New game dialog offers own missions too. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_012UHht4zQhR5DrwQWsj4uRM --- data/commander/css/overlays.css | 44 +- data/commander/index.html | 15 +- data/commander/js/main.js | 2 + data/commander/js/net/host.js | 7 +- data/commander/js/net/missions.js | 105 +++++ data/commander/js/state/store.js | 3 + data/commander/js/views/host.js | 47 +- data/commander/js/views/missions.js | 690 ++++++++++++++++++++++++++++ data/i18n/de.json | 138 +++++- data/i18n/en.json | 138 +++++- src/commander/mission_library.py | 5 + src/commander/missions.py | 2 +- tests/test_missions_web.py | 126 +++++ 13 files changed, 1312 insertions(+), 10 deletions(-) create mode 100644 data/commander/js/net/missions.js create mode 100644 data/commander/js/views/missions.js create mode 100644 tests/test_missions_web.py diff --git a/data/commander/css/overlays.css b/data/commander/css/overlays.css index 848b6357..b9e7187a 100644 --- a/data/commander/css/overlays.css +++ b/data/commander/css/overlays.css @@ -167,13 +167,53 @@ dialog h2 { margin-bottom: .5rem; color: var(--live-strong); text-shadow: 0 0 .7 .simlog-map-sidebar ol { display: grid; gap: .2rem; margin: 0; padding: 0; list-style: none; } .simlog-map-sidebar li { padding-left: .5rem; border-left: 3px solid var(--unit-color); color: var(--text-dim); font: var(--font-xs)/1.4 var(--font-mono); } +/* Own missions of the solo host and the browser Mission Planner. */ +#missions-dialog { width: min(96vw, 80rem); max-width: none; max-height: 94dvh; overflow: auto; } +.missions-head { display: flex; justify-content: space-between; align-items: start; gap: 1rem; padding-bottom: .5rem; border-bottom: 1px solid var(--line); } +.missions-head .eyebrow { margin-bottom: .2rem; } +.missions-head-actions, .missions-row-actions, .missions-item-actions { display: flex; flex-wrap: wrap; gap: .4rem; } +.missions-status-row { display: flex; align-items: center; gap: .6rem; min-height: 2rem; margin: .4rem 0; } +.missions-status-row .host-status { flex: 1 1 auto; margin: 0; } +#missions-status[data-status="rejected"] { color: var(--alarm); } +#missions-status[data-status="applied"] { color: var(--live-2); } +.missions-list { display: grid; gap: .45rem; margin: .6rem 0 0; padding: 0; list-style: none; } +.missions-row { display: grid; gap: .3rem; padding: .55rem .7rem; background: var(--bg-1); border: 1px solid var(--line); border-left: 3px solid var(--live); border-radius: var(--radius); } +.missions-row.invalid { border-left-color: var(--alarm); } +.missions-row-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: .3rem .8rem; } +.missions-row-head strong { color: var(--text); } +.missions-row-head span { color: var(--text-dim); font: var(--font-xs)/1.4 var(--font-mono); } +.missions-hint, .missions-issue { margin: 0; font-size: var(--font-xs); } +.missions-hint { color: var(--caution); } +.missions-issue { color: var(--alarm); } +.missions-row-actions button, .missions-item-actions button { min-height: 2rem; font-size: var(--font-xs); } +.missions-editor h3 { margin: .3rem 0 .5rem; color: var(--live); } +.missions-editor-body { display: grid; grid-template-columns: minmax(0, 3fr) minmax(16rem, 2fr); gap: .8rem; min-width: 0; } +.missions-form { min-width: 0; } +.missions-tabs { display: flex; flex-wrap: wrap; gap: .3rem; margin-bottom: .5rem; } +.missions-tabs button { min-height: 2rem; font-size: var(--font-xs); } +.missions-tabs button[aria-selected="true"] { color: var(--on-live); background: var(--live); border-color: var(--live); } +.missions-panel { min-width: 0; max-height: 58dvh; overflow: auto; padding: .6rem; background: var(--bg-1); border: 1px solid var(--line); border-radius: var(--radius); } +.missions-stack { display: grid; gap: .6rem; } +.missions-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(11rem, 1fr)); gap: .4rem .7rem; align-items: end; } +.missions-item { padding: .5rem; border: 1px solid var(--line); border-radius: var(--radius); } +.missions-item-actions, .missions-wide { grid-column: 1 / -1; } +.missions-field { display: flex; flex-direction: column; gap: .15rem; margin: 0; color: var(--text-dim); font-size: var(--font-xs); } +.missions-dialog .missions-field input, .missions-dialog .missions-field select, .missions-dialog .missions-field textarea { width: 100%; min-width: 0; } +.missions-field textarea { min-height: 4rem; resize: vertical; } +.missions-targets { display: flex; flex-wrap: wrap; gap: .3rem .8rem; } +.missions-targets label { display: inline-flex; align-items: center; gap: .3rem; margin: 0; } +.missions-targets input { width: auto; } +.missions-map-pane { display: grid; align-content: start; gap: .4rem; min-width: 0; } +.missions-map { display: block; width: 100%; aspect-ratio: 1; background: var(--scope); border: 1px solid var(--line); border-radius: var(--radius); cursor: crosshair; } +.missions-map-pane p { margin: 0; } + @media (max-width: 899px) { body.workstation-mode .tab-panel:not(#panel-operations):not([hidden]) { inset: 0; border-radius: 0; padding: .8rem; } .lookout-bar { grid-template-columns: minmax(0, 1fr) auto; } .lookout-title { display: none; } - .guide-layout, .analyzer-workspace, .analysis-images, .analysis-component-groups, .weather-grid, .simlog-map-layout { grid-template-columns: minmax(0, 1fr); } + .guide-layout, .analyzer-workspace, .analysis-images, .analysis-component-groups, .weather-grid, .simlog-map-layout, .missions-editor-body { grid-template-columns: minmax(0, 1fr); } .guide-nav { position: static; } .analyzer-workspace { grid-template-rows: minmax(0, .8fr) minmax(0, 1.2fr); } - #weather-dialog, #simlog-map-dialog { width: 100vw; max-height: 100dvh; height: 100dvh; border-width: 0; border-radius: 0; } + #weather-dialog, #simlog-map-dialog, #missions-dialog { width: 100vw; max-height: 100dvh; height: 100dvh; border-width: 0; border-radius: 0; } .simlog-map-layout { grid-template-rows: minmax(12rem, 2fr) minmax(6rem, 1fr); } } diff --git a/data/commander/index.html b/data/commander/index.html index 2ea38b71..fe782cca 100644 --- a/data/commander/index.html +++ b/data/commander/index.html @@ -28,7 +28,7 @@

- +
@@ -336,6 +336,19 @@ + diff --git a/data/commander/js/main.js b/data/commander/js/main.js index 4ef5d3b1..d41cac43 100644 --- a/data/commander/js/main.js +++ b/data/commander/js/main.js @@ -62,6 +62,7 @@ import "./views/lookout.js"; import { init as initInputWiring } from "./input/wiring.js"; import { init as initViewsStationTabs } from "./views/station-tabs.js"; import { init as initViewsHost } from "./views/host.js"; +import { init as initViewsMissions } from "./views/missions.js"; import { init as initViewsDebrief } from "./views/debrief.js"; import { init as initAppBootstrap } from "./app/bootstrap.js"; import { setPageVersion } from "./net/version.js"; @@ -74,5 +75,6 @@ initViewsLayout(); initInputWiring(); initViewsStationTabs(); initViewsHost(); +initViewsMissions(); initViewsDebrief(); initAppBootstrap(); diff --git a/data/commander/js/net/host.js b/data/commander/js/net/host.js index 3c214bcd..9cdc4824 100644 --- a/data/commander/js/net/host.js +++ b/data/commander/js/net/host.js @@ -10,15 +10,17 @@ import { boundedArray, exactKeys } from "../state/schema.js"; // Solo host surface: the published host view and the one host command in // flight. Rendering follows via the "host" topic. const hostResultText = {ok: "host_result_ok", phase_blocked: "host_result_phase_blocked", + no_mission: "host_result_no_mission", mission_rejected: "host_result_mission_rejected", no_save: "host_result_no_save", save_failed: "host_result_save_failed", session_revoked: "host_result_session_revoked", stale_world_session: "host_result_stale", stale_world_epoch: "host_result_stale", stale_generation: "host_result_stale", role_revoked: "host_result_revoked", expired: "host_result_stale", context_invalidated: "host_result_stale"}; function validateHost(value) { - const fields = ["epoch", "difficulty", "difficulty_fields", "phase", "protocol", "scenario", "scenarios", "session", "slots", "world_mode"]; + const fields = ["epoch", "difficulty", "difficulty_fields", "missions_revision", "phase", "protocol", "scenario", "scenarios", "session", "slots", "world_mode"]; if (!exactKeys(value, fields) || value.protocol !== 2 || typeof value.session !== "string" || !Number.isSafeInteger(value.epoch) || value.epoch < 0 || + !Number.isSafeInteger(value.missions_revision) || value.missions_revision < 0 || !Object.hasOwn(phases, value.phase) || !["fixed", "procedural", "real_fixed"].includes(value.world_mode) || typeof value.scenario !== "string" || !boundedArray(value.difficulty_fields, 32) || !value.difficulty_fields.every((row) => @@ -44,7 +46,10 @@ export async function pollHost(context) { const next = await request("/host", {guard: () => context === S.generation}); if (context !== S.generation) return; validateHost(next); + const missionsChanged = S.hostView?.missions_revision !== next.missions_revision; S.hostView = next; + // The own-mission library changed on the host: refresh it when shown. + if (missionsChanged) emit("missions-revision"); } catch (error) { // The host surface can be withdrawn while the session lives: 403 only // means "refresh the session", it is not an expired login. diff --git a/data/commander/js/net/missions.js b/data/commander/js/net/missions.js new file mode 100644 index 00000000..9fe4138e --- /dev/null +++ b/data/commander/js/net/missions.js @@ -0,0 +1,105 @@ +import { S } from "../state/store.js"; +import { secureId } from "./commands.js"; +import { request } from "./request.js"; +import { boundedArray, exactKeys } from "../state/schema.js"; + +// Own-mission library of the solo host (src/commander/missions.py): the +// published library, the static editor catalog, sector coasts and the +// queued save/import/delete requests. Content is validated on the host; +// these checks only bound what the page reads. +export const UPLOAD_MAX_BYTES = 1024 * 1024; +const text = (value, maximum) => typeof value === "string" && value.length <= maximum; +const issueOk = (row) => exactKeys(row, ["path", "code", "en", "de"]) && + text(row.path, 120) && text(row.code, 32) && text(row.en, 300) && text(row.de, 300); + +function validLibrary(value) { + return exactKeys(value, ["protocol", "revision", "missions", "units", "user_profiles", "results", "truncated"]) && + value.protocol === 2 && Number.isSafeInteger(value.revision) && typeof value.truncated === "boolean" && + boundedArray(value.missions, 64) && value.missions.every((row) => + exactKeys(row, ["key", "name", "side", "objective", "valid", "issues", "hints", "units", "data"]) && + text(row.key, 80) && text(row.name, 80) && ["frigate", "uboot"].includes(row.side) && + text(row.objective, 16) && typeof row.valid === "boolean" && + boundedArray(row.issues, 20) && row.issues.every(issueOk) && + boundedArray(row.hints, 8) && row.hints.every((hint) => exactKeys(hint, ["key", "en", "de"]) && + text(hint.key, 64) && text(hint.en, 300) && text(hint.de, 300)) && + boundedArray(row.units, 64) && row.units.every((key) => text(key, 80)) && + row.data && typeof row.data === "object" && !Array.isArray(row.data)) && + boundedArray(value.units, 256) && value.units.every((unit) => unit && typeof unit === "object" && text(unit.key, 80)) && + boundedArray(value.user_profiles, 256) && value.user_profiles.every((row) => + exactKeys(row, ["key", "kind", "name", "warship"]) && text(row.key, 80) && text(row.kind, 16) && + text(row.name, 80) && typeof row.warship === "boolean") && + boundedArray(value.results, 8) && value.results.every((row) => + exactKeys(row, ["id", "status", "reason", "issues"]) && text(row.id, 64) && + ["applied", "rejected"].includes(row.status) && text(row.reason, 16) && + boundedArray(row.issues, 20) && row.issues.every(issueOk)); +} + +function validCatalog(value) { + return exactKeys(value, ["protocol", "world_size_nm", "profiles", "sectors", "sides", "player_sides", + "objectives", "events", "weathers"]) && value.protocol === 2 && Number.isFinite(value.world_size_nm) && + boundedArray(value.profiles, 512) && value.profiles.every((row) => + exactKeys(row, ["key", "kind", "name", "warship"]) && text(row.key, 80) && text(row.kind, 16) && + text(row.name, 80) && typeof row.warship === "boolean") && + boundedArray(value.sectors, 128) && value.sectors.every((row) => + exactKeys(row, ["index", "countries"]) && Number.isSafeInteger(row.index) && + boundedArray(row.countries, 4) && row.countries.every((name) => text(name, 80))) && + ["sides", "player_sides", "objectives", "events", "weathers"].every((field) => + boundedArray(value[field], 8) && value[field].every((item) => text(item, 16))); +} + +export async function fetchLibrary() { + const library = await request("/missions"); + if (!validLibrary(library)) throw new Error("protocol"); + S.missionLibrary = library; + return library; +} + +export async function fetchCatalog() { + if (S.missionCatalog) return S.missionCatalog; + const catalog = await request("/editor/catalog"); + if (!validCatalog(catalog)) throw new Error("protocol"); + S.missionCatalog = catalog; + return catalog; +} + +const coasts = new Map(); +export async function fetchCoast(index) { + if (coasts.has(index)) return coasts.get(index); + const coast = await request(`/editor/sector?i=${index}`); + if (!exactKeys(coast, ["index", "outlines"]) || coast.index !== index || + !boundedArray(coast.outlines, 4096) || !coast.outlines.every((outline) => + Array.isArray(outline) && outline.every((point) => + Array.isArray(point) && point.length === 2 && point.every(Number.isFinite)))) throw new Error("protocol"); + if (coasts.size >= 16) coasts.delete(coasts.keys().next().value); + coasts.set(index, coast); + return coast; +} + +// Queue one library request, then read the library until its result arrives. +export async function missionRequest(op, fields) { + if (!S.session?.host) throw new Error("forbidden"); + const id = secureId(); + const body = {protocol: 2, id, op, ...fields}; + if (JSON.stringify(body).length > UPLOAD_MAX_BYTES + 4000) { + const error = new Error("too_large"); + error.reason = "too_large"; + throw error; + } + await request("/missions", {method: "POST", body, expected: 202, csrf: S.session.csrf}); + for (let attempt = 0; attempt < 24; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, attempt ? 400 : 150)); + const library = await fetchLibrary(); + const result = library.results.find((row) => row.id === id); + if (result) return result; + } + const error = new Error("timeout"); + error.reason = "timeout"; + throw error; +} + +// A shareable file of one mission with the user units it references; the +// same format as the uConsole's exchange folder (u-jagd.editor-bundle). +export function missionBundle(row, library) { + return {format: "u-jagd.editor-bundle", version: 1, missions: [row.data], + units: library.units.filter((unit) => row.units.includes(unit.key))}; +} diff --git a/data/commander/js/state/store.js b/data/commander/js/state/store.js index 5d154e03..3da57fbe 100644 --- a/data/commander/js/state/store.js +++ b/data/commander/js/state/store.js @@ -38,6 +38,9 @@ export const S = { hostPending: null, hostMessage: null, hostMessageTimer: null, + // Own-mission library of the solo host (net/missions.js, views/missions.js). + missionLibrary: null, + missionCatalog: null, stationRenderSignature: null, nextCommandSeq: 0, stationMutation: false, diff --git a/data/commander/js/views/host.js b/data/commander/js/views/host.js index 75afec49..5156dc07 100644 --- a/data/commander/js/views/host.js +++ b/data/commander/js/views/host.js @@ -5,6 +5,7 @@ import { renderDisabledReasons, unavailable } from "./controls.js"; import { node } from "./dom.js"; import { simlogActive } from "./simlog.js"; import { sendHostAction } from "../net/host.js"; +import { fetchLibrary } from "../net/missions.js"; import { mutateStation, switchSoloSide } from "./lobby.js"; import { opforRoles } from "../core/base.js"; @@ -36,7 +37,7 @@ export function renderHost() { const menu = active && S.hostView?.phase === "menu"; $("host-screen").hidden = !menu || simlogActive(); if (!active) { - for (const id of ["host-save", "host-load", "host-new", + for (const id of ["host-save", "host-load", "host-new", "host-missions", "host-instructor", "host-side", "host-screen-new", "host-screen-load", "host-new-start"]) $(id).disabled = true; for (const button of $("host-slot-list").querySelectorAll("button")) @@ -49,6 +50,7 @@ export function renderHost() { $("host-save").disabled = !any; $("host-load").disabled = !replacing; $("host-new").disabled = !replacing; + $("host-missions").disabled = !ready; $("host-instructor").disabled = !any; const boat = opforRoles.has(S.session.station); $("host-side").textContent = t(boat ? "host_play_frigate" : "host_play_opfor"); @@ -93,12 +95,35 @@ function openSlotDialog(mode) { dialog.querySelector("button:not(:disabled)")?.focus(); } function syncNewGameDifficulty() { - const scenario = S.hostView?.scenarios.find((row) => row.key === $("host-new-scenario").value); + const value = $("host-new-scenario").value; + const scenario = S.hostView?.scenarios.find((row) => row.key === value); const free = Boolean(scenario) && !scenario.fixed; for (const input of $("host-new-difficulty").querySelectorAll("input")) input.disabled = !free; - $("host-new-difficulty-note").textContent = scenario + // An own mission brings its own weather, time and length. + const own = value.startsWith(OWN_PREFIX); + for (const id of ["host-new-world", "host-new-weather", "host-new-time", "host-new-length", "host-new-seed"]) + $(id).disabled = own; + $("host-new-difficulty-note").textContent = own ? t("host_new_own_note") : scenario ? t(free ? "host_new_difficulty_free" : "host_new_difficulty_fixed") : ""; } +const OWN_PREFIX = "own:"; +// The library's valid missions of the chosen side, after the built-in ones. +function appendOwnMissions(side, preferred) { + const rows = (S.missionLibrary?.missions ?? []).filter((row) => row.valid && row.side === side); + $("host-new-scenario").querySelector("optgroup")?.remove(); + if (!rows.length) return; + const group = node("optgroup"); + group.label = t("host_new_own_group"); + for (const row of rows) { + const option = node("option", row.name || row.key); + option.value = OWN_PREFIX + row.key; + group.append(option); + } + $("host-new-scenario").append(group); + if (preferred && $("host-new-scenario").querySelector(`option[value="${CSS.escape(preferred)}"]`)) + $("host-new-scenario").value = preferred; + syncNewGameDifficulty(); +} // The scenario list shows only the missions of the chosen side. function fillNewGameScenarios(preferred) { const side = $("host-new-side").value; @@ -109,6 +134,7 @@ function fillNewGameScenarios(preferred) { return option; })); if (rows.some((row) => row.key === preferred)) $("host-new-scenario").value = preferred; + appendOwnMissions(side, preferred); syncNewGameDifficulty(); } function openNewGameDialog() { @@ -138,6 +164,10 @@ function openNewGameDialog() { dialog.hidden = false; if (!dialog.open) dialog.showModal(); $("host-new-side").focus(); + // The own missions arrive with the library; the list grows when it is read. + fetchLibrary().then(() => { + if (dialog.open) appendOwnMissions($("host-new-side").value, $("host-new-scenario").value); + }).catch(() => {}); } export function init() { @@ -154,6 +184,17 @@ export function init() { $("host-new-form").addEventListener("submit", async (event) => { event.preventDefault(); if (!$("host-new-form").reportValidity()) return; + const choice = $("host-new-scenario").value; + if (choice.startsWith(OWN_PREFIX)) { + closeHostDialog($("host-new-dialog")); + const boat = opforRoles.has(S.session?.station); + if (($("host-new-side").value === "uboot") !== boat) { + await mutateStation("/stations/request", {station: boat ? "bridge" : "uboot"}); + if (opforRoles.has(S.session?.station) === boat) return; + } + sendHostAction("host_start_mission", {key: choice.slice(OWN_PREFIX.length)}); + return; + } const params = {scenario: $("host-new-scenario").value, world_mode: $("host-new-world").value, weather: $("host-new-weather").value, time: $("host-new-time").value, length: $("host-new-length").value}; diff --git a/data/commander/js/views/missions.js b/data/commander/js/views/missions.js new file mode 100644 index 00000000..cf2381c6 --- /dev/null +++ b/data/commander/js/views/missions.js @@ -0,0 +1,690 @@ +import { S } from "../state/store.js"; +import { $, opforRoles } from "../core/base.js"; +import { on } from "../core/events.js"; +import { t } from "../core/format.js"; +import { node } from "./dom.js"; +import { sendHostAction } from "../net/host.js"; +import { UPLOAD_MAX_BYTES, fetchCatalog, fetchCoast, fetchLibrary, missionBundle, + missionRequest } from "../net/missions.js"; +import { mutateStation } from "./lobby.js"; + +// Own missions of the solo host: the library (start, edit, download, upload, +// delete) and the Mission Planner, a form editor of the Mission Editor's +// format with a map preview. The host validates and stores every change +// (src/commander/mission_library.py); the page only edits a draft. +const WORLD = 500; +const SIDE_OBJECTIVES = {frigate: ["sink", "survive", "protect", "reach"], uboot: ["sink", "survive", "reach"]}; +const TABS = ["overview", "world", "units", "objective", "events"]; +let draft = null; // the mission being edited +let editingKey = null; // its stored key (null: a new mission) +let tab = "overview"; +let pick = "player"; // what a map click places +let selectedUnit = null; // ["exact" | "random_groups", index] +let pendingOverwrite = null; +let renderedRevision = null; + +const lang = () => (S.language === "de" ? "de" : "en"); +const clone = (value) => JSON.parse(JSON.stringify(value)); +const opt = (value, label) => [value, label]; +const clamp = (value, low, high) => Math.min(high, Math.max(low, value)); + +function defaultMission() { + const stamp = Date.now().toString(36); + return {version: 1, key: `user.web_${stamp}`, name: t("missions_new_name"), description: "", seed: 1, + side: "frigate", boat_id: "", world: {kind: "fixed", size_nm: WORLD, sectors: []}, + player: {x: 250, y: 250, course_deg: 0, speed_kn: 12}, + environment: {sea_state: 3, time_hour: 12, thermocline_depth_m: 80, weather: "clear"}, + units: {exact: [], random_groups: []}, + objective: {type: "survive", target_ids: [], time_limit_s: 3600, reach: {x: 250, y: 250, radius_nm: 2}}, + events: []}; +} + +function setStatus(key, values = {}, status = "") { + $("missions-status").textContent = key ? t(key, values) : ""; + $("missions-status").dataset.status = status; +} +function issueText(issues) { + return issues.slice(0, 6).map((row) => row[lang()]).join(" · "); +} + +// ---- library ---------------------------------------------------------------- +const objectiveText = (type) => t(`missions_objective_${type}`) || type; +const sideText = (side) => t(side === "uboot" ? "missions_side_uboot" : "missions_side_frigate"); + +function libraryBusy() { + // Never rebuild the list under the pointer or the keyboard focus. + const list = $("missions-list"); + return list.contains(document.activeElement) || list.matches(":hover"); +} +function renderLibrary(force = false) { + const library = S.missionLibrary; + if (!library || (!force && library.revision === renderedRevision) || (!force && libraryBusy())) return; + renderedRevision = library.revision; + $("missions-empty").hidden = library.missions.length > 0; + $("missions-truncated").hidden = !library.truncated; + $("missions-list").replaceChildren(...library.missions.map((row) => { + const item = node("li", undefined, `missions-row${row.valid ? "" : " invalid"}`); + const head = node("div", undefined, "missions-row-head"); + head.append(node("strong", row.name || row.key), node("span", `${sideText(row.side)} · ${objectiveText(row.objective)}`, "fine")); + item.append(head); + const notes = row.valid ? row.hints.map((hint) => hint[lang()]) : [issueText(row.issues)]; + for (const note of notes) item.append(node("p", note, row.valid ? "missions-hint" : "missions-issue")); + const actions = node("div", undefined, "missions-row-actions"); + const button = (key, handler, className) => { + const element = node("button", t(key), className); + element.type = "button"; + element.addEventListener("click", () => handler(row)); + actions.append(element); + return element; + }; + const start = button("missions_start", startMission, "primary"); + start.disabled = !row.valid || S.hostPending !== null; + button("missions_edit", openEditor); + button("missions_download", downloadMission); + button("missions_delete", deleteMission, "danger"); + item.append(actions); + return item; + })); +} + +async function refreshLibrary(force = false) { + try { + await fetchLibrary(); + renderLibrary(force); + } catch (error) { + setStatus("missions_result_failed", {}, "rejected"); + } +} + +async function startMission(row) { + closeDialog(); + // The side is the solo session's: switch it first, the new world keeps it. + const boat = opforRoles.has(S.session?.station); + if ((row.side === "uboot") !== boat) { + await mutateStation("/stations/request", {station: boat ? "bridge" : "uboot"}); + if (opforRoles.has(S.session?.station) === boat) return; + } + sendHostAction("host_start_mission", {key: row.key}); +} + +function download(name, value) { + const blob = new Blob([JSON.stringify(value, null, 2)], {type: "application/json"}); + const link = node("a"); + link.href = URL.createObjectURL(blob); + link.download = name; + document.body.append(link); + link.click(); + link.remove(); + setTimeout(() => URL.revokeObjectURL(link.href), 1000); +} +function downloadMission(row) { + download(`${row.key}.json`, missionBundle(row, S.missionLibrary)); + setStatus("missions_downloaded", {name: row.name}, "applied"); +} + +async function runRequest(op, fields, okKey, values = {}) { + setStatus("missions_result_pending", {}, "pending"); + try { + const outcome = await missionRequest(op, fields); + if (outcome.status === "applied") { + setStatus(okKey, values, "applied"); + pendingOverwrite = null; + renderLibrary(true); + return outcome; + } + if (outcome.reason === "exists") { + pendingOverwrite = {op, fields, okKey, values}; + setStatus("missions_result_exists", {}, "rejected"); + $("missions-overwrite").hidden = false; + return outcome; + } + setStatus(outcome.issues.length ? "missions_result_issues" : "missions_result_failed", + {issues: issueText(outcome.issues)}, "rejected"); + return outcome; + } catch (error) { + setStatus(error.reason === "too_large" ? "missions_too_large" : "missions_result_failed", {}, "rejected"); + return null; + } +} + +async function deleteMission(row) { + if (!window.confirm(t("missions_delete_confirm", {name: row.name}))) return; + await runRequest("delete", {key: row.key}, "missions_deleted", {name: row.name}); +} + +function uploadFile(file) { + if (!file) return; + if (file.size > UPLOAD_MAX_BYTES) { setStatus("missions_too_large", {}, "rejected"); return; } + const reader = new FileReader(); + reader.addEventListener("load", () => { + let value; + try { value = JSON.parse(String(reader.result)); } catch (_) { + setStatus("missions_upload_invalid", {}, "rejected"); + return; + } + // A bare mission file is wrapped into the shared bundle format. + const bundle = value && value.format === "u-jagd.editor-bundle" ? value + : {format: "u-jagd.editor-bundle", version: 1, missions: [value], units: []}; + runRequest("import", {bundle, overwrite: false}, "missions_uploaded", {name: file.name}); + }); + reader.addEventListener("error", () => setStatus("missions_upload_invalid", {}, "rejected")); + reader.readAsText(file); +} + +// ---- dialog ----------------------------------------------------------------- +export async function openMissions() { + if (!S.session?.host) return; + const dialog = $("missions-dialog"); + showLibrary(); + setStatus(""); + dialog.hidden = false; + if (!dialog.open) dialog.showModal(); + $("missions-new").focus(); + await refreshLibrary(true); +} +function closeDialog() { + const dialog = $("missions-dialog"); + if (dialog.open) dialog.close(); +} +function showLibrary() { + $("missions-library").hidden = false; + $("missions-editor").hidden = true; + $("missions-head-actions").hidden = false; + $("missions-overwrite").hidden = true; + draft = null; +} + +// ---- editor ----------------------------------------------------------------- +async function openEditor(row) { + try { await fetchCatalog(); } catch (_) { setStatus("missions_result_failed", {}, "rejected"); return; } + draft = row ? clone(row.data) : defaultMission(); + draft.side ??= "frigate"; + draft.boat_id ??= ""; + draft.objective.reach ??= {x: 250, y: 250, radius_nm: 2}; + editingKey = row ? row.key : null; + tab = "overview"; + pick = "player"; + selectedUnit = null; + $("missions-library").hidden = true; + $("missions-head-actions").hidden = true; + $("missions-editor").hidden = false; + $("missions-overwrite").hidden = true; + setStatus(""); + renderEditor(); + $("missions-tab-overview").focus(); +} + +function profiles() { + const own = (S.missionLibrary?.user_profiles ?? []).map((row) => ({...row, own: true})); + return [...S.missionCatalog.profiles, ...own]; +} +function profileOptions(select, value, filter = () => true) { + const groups = new Map(); + for (const profile of profiles().filter(filter)) { + const label = t(`missions_kind_${profile.kind}`) || profile.kind; + if (!groups.has(label)) groups.set(label, node("optgroup")); + groups.get(label).label = label; + const option = node("option", profile.own ? `${profile.name} (${t("missions_own_unit")})` : profile.name); + option.value = profile.key; + groups.get(label).append(option); + } + select.replaceChildren(...groups.values()); + select.value = value; +} + +function field(labelKey, input) { + const wrapper = node("label", undefined, "missions-field"); + wrapper.append(node("span", t(labelKey)), input); + return wrapper; +} +function numberInput(get, set, {min, max, step = "any"} = {}) { + const input = node("input"); + input.type = "number"; + if (min !== undefined) input.min = String(min); + if (max !== undefined) input.max = String(max); + input.step = String(step); + input.value = String(get()); + input.addEventListener("change", () => { + const value = Number(input.value); + if (input.value.trim() === "" || !Number.isFinite(value)) { input.value = String(get()); return; } + set(min !== undefined || max !== undefined ? clamp(value, min ?? -Infinity, max ?? Infinity) : value); + input.value = String(get()); + drawMap(); + }); + return input; +} +function textInput(get, set, maximum, multiline = false) { + const input = node(multiline ? "textarea" : "input"); + if (!multiline) input.type = "text"; + input.maxLength = maximum; + input.value = get(); + input.addEventListener("change", () => { set(input.value); drawMap(); }); + return input; +} +function selectInput(options, get, set, rerender = false) { + const select = node("select"); + for (const [value, label] of options) { + const option = node("option", label); + option.value = value; + select.append(option); + } + select.value = get(); + select.addEventListener("change", () => { + set(select.value); + if (rerender) renderEditor(); + else drawMap(); + }); + return select; +} +function addButton(key, handler, className = "") { + const button = node("button", t(key), className); + button.type = "button"; + button.addEventListener("click", handler); + return button; +} +function nextId(prefix) { + const used = new Set([...draft.units.exact, ...draft.units.random_groups, ...draft.events, + ...draft.world.sectors].map((item) => item.id)); + let number = 1; + while (used.has(`${prefix}${number}`)) number += 1; + return `${prefix}${number}`; +} +function placementFields(target) { + const box = node("div", undefined, "missions-grid"); + const sectorIds = draft.world.sectors.map((sector) => sector.id); + box.append(field("missions_placement", selectInput( + [opt("fixed", t("missions_placement_fixed")), ...(sectorIds.length ? [opt("sector", t("missions_placement_sector"))] : [])], + () => target.placement.kind, + (value) => { + target.placement = value === "sector" ? {kind: "sector", sector: sectorIds[0]} + : {kind: "fixed", x: 250, y: 250}; + }, true))); + if (target.placement.kind === "sector") { + box.append(field("missions_sector", selectInput(sectorIds.map((id) => [id, id]), + () => target.placement.sector, (value) => { target.placement.sector = value; }))); + } else { + box.append(field("missions_x", numberInput(() => target.placement.x, (v) => { target.placement.x = v; }, {min: 0, max: WORLD})), + field("missions_y", numberInput(() => target.placement.y, (v) => { target.placement.y = v; }, {min: 0, max: WORLD}))); + } + return box; +} + +function overviewPanel() { + const panel = node("div", undefined, "missions-grid"); + panel.append( + field("missions_key", textInput(() => draft.key, (v) => { draft.key = v.trim(); }, 69)), + field("missions_name", textInput(() => draft.name, (v) => { draft.name = v; }, 80)), + field("missions_seed", numberInput(() => draft.seed, (v) => { draft.seed = Math.round(v); }, {min: 0, max: 2147483647, step: 1})), + field("missions_player_side", selectInput([opt("frigate", t("missions_side_frigate")), opt("uboot", t("missions_side_uboot_long"))], + () => draft.side, (value) => { + draft.side = value; + if (!SIDE_OBJECTIVES[value].includes(draft.objective.type)) draft.objective.type = "survive"; + }, true))); + if (draft.side === "uboot") { + const boats = draft.units.exact.filter((unit) => unit.side === "hostile" && + profiles().some((profile) => profile.key === unit.profile && profile.kind === "sub")); + panel.append(field("missions_boat", selectInput([["", t("missions_boat_none")], ...boats.map((unit) => [unit.id, unit.id])], + () => draft.boat_id, (value) => { draft.boat_id = value; }))); + panel.append(node("p", t("missions_boat_note"), "fine missions-wide")); + } + const description = field("missions_description", textInput(() => draft.description ?? "", (v) => { draft.description = v; }, 2000, true)); + description.classList.add("missions-wide"); + panel.append(description); + return panel; +} + +function worldPanel(catalog) { + const panel = node("div", undefined, "missions-stack"); + const world = node("div", undefined, "missions-grid"); + world.append(field("missions_world", selectInput( + [opt("fixed", t("missions_world_fixed")), ...catalog.sectors.map((row) => + [`sector:${row.index}`, `${t("missions_world_sector", {index: row.index})} ${row.countries.join(" / ")}`])], + () => (draft.world.kind === "reference" ? draft.world.reference : "fixed"), + (value) => { + if (value === "fixed") { draft.world = {kind: "fixed", size_nm: WORLD, sectors: draft.world.sectors}; } + else { draft.world = {kind: "reference", reference: value, size_nm: WORLD, sectors: draft.world.sectors}; } + }, true))); + world.append( + field("missions_frigate_x", numberInput(() => draft.player.x, (v) => { draft.player.x = v; }, {min: 0, max: WORLD})), + field("missions_frigate_y", numberInput(() => draft.player.y, (v) => { draft.player.y = v; }, {min: 0, max: WORLD})), + field("missions_course", numberInput(() => draft.player.course_deg, (v) => { draft.player.course_deg = v; }, {min: 0, max: 359.999})), + field("missions_speed", numberInput(() => draft.player.speed_kn, (v) => { draft.player.speed_kn = v; }, {min: 0, max: 31})), + field("missions_sea_state", numberInput(() => draft.environment.sea_state, (v) => { draft.environment.sea_state = Math.round(v); }, {min: 0, max: 9, step: 1})), + field("missions_time_hour", numberInput(() => draft.environment.time_hour, (v) => { draft.environment.time_hour = v; }, {min: 0, max: 23.999, step: 0.25})), + field("missions_thermocline", numberInput(() => draft.environment.thermocline_depth_m, (v) => { draft.environment.thermocline_depth_m = v; }, {min: 0, max: 2000})), + field("missions_weather", selectInput(catalog.weathers.map((w) => [w, t(`missions_weather_${w}`)]), + () => draft.environment.weather, (value) => { draft.environment.weather = value; }))); + panel.append(world, node("h3", t("missions_sectors"))); + draft.world.sectors.forEach((sector, index) => { + const row = node("div", undefined, "missions-grid missions-item"); + row.append( + field("missions_id", textInput(() => sector.id, (v) => { sector.id = v.trim(); }, 64)), + field("missions_x", numberInput(() => sector.x, (v) => { sector.x = v; }, {min: 0, max: WORLD})), + field("missions_y", numberInput(() => sector.y, (v) => { sector.y = v; }, {min: 0, max: WORLD})), + field("missions_width", numberInput(() => sector.width, (v) => { sector.width = v; }, {min: 0.01, max: WORLD})), + field("missions_height", numberInput(() => sector.height, (v) => { sector.height = v; }, {min: 0.01, max: WORLD})), + addButton("missions_remove", () => { draft.world.sectors.splice(index, 1); renderEditor(); }, "danger")); + panel.append(row); + }); + panel.append(addButton("missions_add_sector", () => { + draft.world.sectors.push({id: nextId("sector"), x: 200, y: 200, width: 100, height: 100}); + renderEditor(); + })); + return panel; +} + +function unitPanel() { + const panel = node("div", undefined, "missions-stack"); + const sides = [opt("hostile", t("missions_unit_hostile")), opt("neutral", t("missions_unit_neutral")), opt("friendly", t("missions_unit_friendly"))]; + panel.append(node("h3", t("missions_exact_units"))); + draft.units.exact.forEach((unit, index) => { + const row = node("div", undefined, "missions-grid missions-item"); + const profile = node("select"); + profileOptions(profile, unit.profile); + profile.addEventListener("change", () => { unit.profile = profile.value; drawMap(); }); + row.append( + field("missions_id", textInput(() => unit.id, (v) => { unit.id = v.trim(); }, 64)), + field("missions_profile", profile), + field("missions_unit_side", selectInput(sides, () => unit.side, (v) => { unit.side = v; })), + field("missions_course", numberInput(() => unit.course_deg ?? 0, (v) => { unit.course_deg = v; }, {min: 0, max: 359.999})), + field("missions_speed", numberInput(() => unit.speed_kn ?? 0, (v) => { unit.speed_kn = v; }, {min: 0, max: 60})), + field("missions_depth", numberInput(() => unit.depth_m ?? 60, (v) => { unit.depth_m = v; }, {min: 0, max: 2000})), + placementFields(unit)); + const actions = node("div", undefined, "missions-item-actions"); + const place = addButton("missions_pick_unit", () => { pick = "unit"; selectedUnit = ["exact", index]; renderPickHint(); }); + place.setAttribute("aria-pressed", String(pick === "unit" && selectedUnit?.[0] === "exact" && selectedUnit[1] === index)); + actions.append(place, addButton("missions_remove", () => { + draft.units.exact.splice(index, 1); + draft.objective.target_ids = draft.objective.target_ids.filter((id) => id !== unit.id); + if (draft.boat_id === unit.id) draft.boat_id = ""; + selectedUnit = null; + renderEditor(); + }, "danger")); + row.append(actions); + panel.append(row); + }); + panel.append(addButton("missions_add_unit", () => { + const sub = profiles().find((row) => row.kind === "sub"); + draft.units.exact.push({id: nextId("unit"), profile: sub?.key ?? profiles()[0].key, side: "hostile", + placement: {kind: "fixed", x: clamp(draft.player.x + 20, 0, WORLD), y: draft.player.y}, + course_deg: 0, speed_kn: 4, depth_m: 60}); + selectedUnit = ["exact", draft.units.exact.length - 1]; + pick = "unit"; + renderEditor(); + })); + panel.append(node("h3", t("missions_groups"))); + draft.units.random_groups.forEach((group, index) => { + const row = node("div", undefined, "missions-grid missions-item"); + const choices = node("select"); + choices.multiple = true; + choices.size = 5; + profileOptions(choices, null, (profile) => profile.kind !== "torpedo"); + for (const option of choices.querySelectorAll("option")) option.selected = group.profiles.includes(option.value); + choices.addEventListener("change", () => { + const picked = [...choices.selectedOptions].map((option) => option.value); + if (picked.length) group.profiles = picked; + }); + row.append( + field("missions_id", textInput(() => group.id, (v) => { group.id = v.trim(); }, 64)), + field("missions_group_profiles", choices), + field("missions_unit_side", selectInput(sides, () => group.side, (v) => { group.side = v; })), + field("missions_count_min", numberInput(() => group.count[0], (v) => { group.count[0] = Math.round(v); }, {min: 0, max: 100, step: 1})), + field("missions_count_max", numberInput(() => group.count[1], (v) => { group.count[1] = Math.round(v); }, {min: 0, max: 100, step: 1})), + placementFields(group)); + const actions = node("div", undefined, "missions-item-actions"); + actions.append(addButton("missions_pick_unit", () => { pick = "unit"; selectedUnit = ["random_groups", index]; renderPickHint(); }), + addButton("missions_remove", () => { + draft.units.random_groups.splice(index, 1); + draft.objective.target_ids = draft.objective.target_ids.filter((id) => id !== group.id); + draft.events = draft.events.filter((event) => event.target_id !== group.id || event.type !== "spawn"); + selectedUnit = null; + renderEditor(); + }, "danger")); + row.append(actions); + panel.append(row); + }); + panel.append(addButton("missions_add_group", () => { + const sub = profiles().find((row) => row.kind === "sub"); + draft.units.random_groups.push({id: nextId("group"), profiles: [sub?.key ?? profiles()[0].key], side: "hostile", + count: [1, 2], placement: {kind: "fixed", x: clamp(draft.player.x + 40, 0, WORLD), y: draft.player.y}}); + renderEditor(); + })); + return panel; +} + +function objectivePanel() { + const panel = node("div", undefined, "missions-stack"); + const grid = node("div", undefined, "missions-grid"); + const objective = draft.objective; + grid.append( + field("missions_objective", selectInput(SIDE_OBJECTIVES[draft.side].map((type) => [type, objectiveText(type)]), + () => objective.type, (value) => { objective.type = value; }, true)), + field("missions_time_limit", numberInput(() => Math.round(objective.time_limit_s / 60), + (v) => { objective.time_limit_s = Math.max(1, v) * 60; }, {min: 1, max: 10080, step: 1}))); + panel.append(grid, node("p", t(`missions_objective_note_${draft.side}_${objective.type}`), "fine")); + if (objective.type === "reach") { + const reach = node("div", undefined, "missions-grid"); + reach.append( + field("missions_x", numberInput(() => objective.reach.x, (v) => { objective.reach.x = v; }, {min: 0, max: WORLD})), + field("missions_y", numberInput(() => objective.reach.y, (v) => { objective.reach.y = v; }, {min: 0, max: WORLD})), + field("missions_radius", numberInput(() => objective.reach.radius_nm, (v) => { objective.reach.radius_nm = v; }, {min: 0.1, max: 50})), + addButton("missions_pick_reach", () => { pick = "reach"; renderPickHint(); })); + panel.append(reach); + } + if (objective.type === "sink" || objective.type === "protect") { + const list = node("fieldset", undefined, "missions-targets"); + list.append(node("legend", t("missions_targets"))); + for (const item of [...draft.units.exact, ...draft.units.random_groups]) { + if (item.id === draft.boat_id) continue; + const label = node("label"); + const box = node("input"); + box.type = "checkbox"; + box.checked = objective.target_ids.includes(item.id); + box.addEventListener("change", () => { + objective.target_ids = box.checked ? [...new Set([...objective.target_ids, item.id])] + : objective.target_ids.filter((id) => id !== item.id); + }); + label.append(box, node("span", item.id)); + list.append(label); + } + panel.append(list); + } + return panel; +} + +function eventsPanel(catalog) { + const panel = node("div", undefined, "missions-stack"); + const groups = draft.units.random_groups.map((group) => [group.id, group.id]); + draft.events.forEach((event, index) => { + const row = node("div", undefined, "missions-grid missions-item"); + row.append( + field("missions_id", textInput(() => event.id, (v) => { event.id = v.trim(); }, 64)), + field("missions_event_at", numberInput(() => Math.round(event.at_s / 60 * 10) / 10, + (v) => { event.at_s = Math.max(0, v) * 60; }, {min: 0, max: 10080, step: 0.5})), + field("missions_event_type", selectInput(catalog.events.filter((type) => type !== "spawn" || groups.length) + .map((type) => [type, t(`missions_event_${type}`)]), () => event.type, (value) => { + event.type = value; + if (value === "spawn") event.target_id = groups[0]?.[0] ?? ""; + if (value === "weather") event.weather ??= "clear"; + if (value === "objective") event.action ??= "complete"; + }, true))); + const message = field("missions_event_text", textInput(() => event.message ?? "", (v) => { event.message = v; }, 500)); + message.classList.add("missions-wide"); + if (event.type === "spawn") { + row.append(field("missions_event_group", selectInput(groups, () => event.target_id, (v) => { event.target_id = v; }))); + } else if (event.type === "weather") { + row.append(field("missions_weather", selectInput(catalog.weathers.map((w) => [w, t(`missions_weather_${w}`)]), + () => event.weather, (v) => { event.weather = v; }))); + } else if (event.type === "objective") { + row.append(field("missions_event_action", selectInput([opt("complete", t("missions_event_complete")), opt("fail", t("missions_event_fail"))], + () => event.action, (v) => { event.action = v; }))); + } + row.append(message, addButton("missions_remove", () => { draft.events.splice(index, 1); renderEditor(); }, "danger")); + panel.append(row); + }); + panel.append(addButton("missions_add_event", () => { + draft.events.push({id: nextId("event"), at_s: 0, type: "message", message: t("missions_event_default")}); + renderEditor(); + })); + return panel; +} + +function renderPickHint() { + const what = pick === "unit" && selectedUnit + ? draft.units[selectedUnit[0]][selectedUnit[1]]?.id ?? "" : t(`missions_pick_${pick}_label`); + $("missions-pick").textContent = t("missions_pick_hint", {what}); +} + +function renderEditor() { + const catalog = S.missionCatalog; + $("missions-editor-title").textContent = t(editingKey ? "missions_edit_title" : "missions_new_title", {name: draft.name}); + for (const name of TABS) { + const button = $(`missions-tab-${name}`); + button.setAttribute("aria-selected", String(name === tab)); + button.tabIndex = name === tab ? 0 : -1; + } + const panel = {overview: overviewPanel, world: () => worldPanel(catalog), units: unitPanel, + objective: objectivePanel, events: () => eventsPanel(catalog)}[tab](); + $("missions-panel").replaceChildren(panel); + renderPickHint(); + drawMap(); +} + +function mapPoint(event) { + const canvas = $("missions-map"); + const rect = canvas.getBoundingClientRect(); + return [clamp((event.clientX - rect.left) / rect.width * WORLD, 0, WORLD), + clamp((event.clientY - rect.top) / rect.height * WORLD, 0, WORLD)]; +} +function placeAt(x, y) { + const round = (value) => Math.round(value * 10) / 10; + if (pick === "reach") Object.assign(draft.objective.reach, {x: round(x), y: round(y)}); + else if (pick === "unit" && selectedUnit) { + const target = draft.units[selectedUnit[0]][selectedUnit[1]]; + if (target) target.placement = {kind: "fixed", x: round(x), y: round(y)}; + } else Object.assign(draft.player, {x: round(x), y: round(y)}); + renderEditor(); +} + +let mapToken = 0; +async function drawMap() { + const canvas = $("missions-map"); + if (!draft || canvas.hidden) return; + const token = ++mapToken; + const size = canvas.clientWidth || 360; + const ratio = window.devicePixelRatio || 1; + canvas.width = Math.round(size * ratio); + canvas.height = Math.round(size * ratio); + const context = canvas.getContext("2d"); + const style = getComputedStyle(document.documentElement); + const color = (name) => style.getPropertyValue(name).trim(); + const scale = canvas.width / WORLD; + let coast = null; + if (draft.world.kind === "reference") { + const index = Number(String(draft.world.reference).split(":")[1]); + try { coast = await fetchCoast(index); } catch (_) { coast = null; } + if (token !== mapToken) return; + } + context.fillStyle = color("--scope"); + context.fillRect(0, 0, canvas.width, canvas.height); + if (coast) { + context.fillStyle = color("--bg-4"); + context.strokeStyle = color("--text-faint"); + for (const outline of coast.outlines) { + context.beginPath(); + outline.forEach(([x, y], index) => (index ? context.lineTo(x * scale, y * scale) : context.moveTo(x * scale, y * scale))); + context.closePath(); + context.fill(); + context.stroke(); + } + } + context.strokeStyle = color("--line-strong"); + context.lineWidth = ratio; + for (const sector of draft.world.sectors) { + context.strokeRect(sector.x * scale, sector.y * scale, sector.width * scale, sector.height * scale); + } + const sideColor = {hostile: color("--aff-hostile"), neutral: color("--aff-neutral"), friendly: color("--aff-friend")}; + const sectors = new Map(draft.world.sectors.map((sector) => [sector.id, sector])); + const where = (placement) => placement.kind === "sector" && sectors.has(placement.sector) + ? [sectors.get(placement.sector).x + sectors.get(placement.sector).width / 2, + sectors.get(placement.sector).y + sectors.get(placement.sector).height / 2] : [placement.x, placement.y]; + const mark = (x, y, fill, radius, own) => { + context.beginPath(); + context.arc(x * scale, y * scale, radius * ratio, 0, Math.PI * 2); + context.fillStyle = fill; + context.fill(); + if (own) { context.strokeStyle = color("--live-strong"); context.lineWidth = 2 * ratio; context.stroke(); } + }; + if (draft.objective.type === "reach") { + const reach = draft.objective.reach; + context.beginPath(); + context.arc(reach.x * scale, reach.y * scale, Math.max(3 * ratio, reach.radius_nm * scale), 0, Math.PI * 2); + context.strokeStyle = color("--caution"); + context.lineWidth = 2 * ratio; + context.stroke(); + } + for (const group of draft.units.random_groups) { + const [x, y] = where(group.placement); + context.strokeStyle = sideColor[group.side]; + context.lineWidth = ratio; + context.strokeRect(x * scale - 6 * ratio, y * scale - 6 * ratio, 12 * ratio, 12 * ratio); + } + for (const unit of draft.units.exact) { + const [x, y] = where(unit.placement); + mark(x, y, sideColor[unit.side] ?? color("--text"), 4, unit.id === draft.boat_id && draft.side === "uboot"); + } + mark(draft.player.x, draft.player.y, color("--aff-friend"), 5, draft.side === "frigate"); +} + +async function saveDraft(start) { + const key = draft.key; + const result = await runRequest("save", {mission: draft, overwrite: editingKey === key}, + "missions_saved", {name: draft.name}); + if (result?.status !== "applied") return; + editingKey = key; + if (start) { + const row = S.missionLibrary?.missions.find((item) => item.key === key); + if (row?.valid) startMission(row); + } +} + +export function init() { + const dialog = $("missions-dialog"); + dialog.addEventListener("close", () => { dialog.hidden = true; draft = null; }); + $("host-missions").addEventListener("click", openMissions); + $("missions-close").addEventListener("click", closeDialog); + $("missions-new").addEventListener("click", () => openEditor(null)); + $("missions-upload").addEventListener("click", () => $("missions-upload-input").click()); + $("missions-upload-input").addEventListener("change", () => { + uploadFile($("missions-upload-input").files[0]); + $("missions-upload-input").value = ""; + }); + $("missions-overwrite").addEventListener("click", () => { + $("missions-overwrite").hidden = true; + if (!pendingOverwrite) return; + const {op, fields, okKey, values} = pendingOverwrite; + runRequest(op, {...fields, overwrite: true}, okKey, values); + }); + for (const name of TABS) { + $(`missions-tab-${name}`).addEventListener("click", () => { tab = name; renderEditor(); }); + } + $("missions-tabs").addEventListener("keydown", (event) => { + if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return; + const step = event.key === "ArrowRight" ? 1 : -1; + tab = TABS[(TABS.indexOf(tab) + step + TABS.length) % TABS.length]; + renderEditor(); + $(`missions-tab-${tab}`).focus(); + }); + $("missions-map").addEventListener("click", (event) => { if (draft) placeAt(...mapPoint(event)); }); + $("missions-pick-player").addEventListener("click", () => { pick = "player"; renderPickHint(); }); + $("missions-save").addEventListener("click", () => saveDraft(false)); + $("missions-save-start").addEventListener("click", () => saveDraft(true)); + $("missions-export-draft").addEventListener("click", () => { + if (draft) download(`${draft.key}.json`, {format: "u-jagd.editor-bundle", version: 1, missions: [draft], + units: (S.missionLibrary?.units ?? []).filter((unit) => JSON.stringify(draft.units).includes(`"${unit.key}"`))}); + }); + $("missions-back").addEventListener("click", () => { showLibrary(); renderLibrary(true); }); + on("missions-revision", () => { if (dialog.open && !draft) refreshLibrary(); }); + on("host", () => { if (dialog.open && !draft) renderLibrary(); }); + window.addEventListener("resize", () => { if (draft) drawMap(); }); +} diff --git a/data/i18n/de.json b/data/i18n/de.json index c74a0657..938913d3 100644 --- a/data/i18n/de.json +++ b/data/i18n/de.json @@ -6543,5 +6543,141 @@ "menu.custom.title.uboot": "Eigene Missionen des U-Boots - Enter: Start | Esc/Q: zurück", "menu.custom.empty": "Noch keine eigenen Missionen für diese Seite. Im Missionsplaner (Hauptmenü) eine bauen oder dort mit Strg+I eine geteilte Datei importieren.", "menu.custom.hint": "Auf/Ab wählen · Enter Start · Esc zurück", - "menu.custom.start_failed": "Diese Mission kann nicht starten: im Missionsplaner öffnen und prüfen" + "menu.custom.start_failed": "Diese Mission kann nicht starten: im Missionsplaner öffnen und prüfen", + "commander.web.host_missions": "Eigene Missionen", + "commander.web.host_new_own_group": "Eigene Missionen", + "commander.web.host_new_own_note": "Eine eigene Mission bringt Welt, Wetter, Uhrzeit und Dauer selbst mit.", + "commander.web.host_result_no_mission": "Mission auf dem Gastgeber nicht gefunden", + "commander.web.host_result_mission_rejected": "Diese Mission kann nicht starten: im Planer prüfen", + "commander.web.missions_eyebrow": "Missionsplaner", + "commander.web.missions_title": "Eigene Missionen", + "commander.web.missions_note": "Missionen aus dem Missionsplaner des Gastgebers. Zum Teilen herunterladen; die Datei lässt sich hier hochladen oder in den Austauschordner der uConsole kopieren.", + "commander.web.missions_empty": "Noch keine eigenen Missionen. Mit Neu eine anlegen oder eine geteilte Datei hochladen.", + "commander.web.missions_truncated": "Nur die ersten 64 Missionen werden gezeigt.", + "commander.web.missions_new": "Neu", + "commander.web.missions_upload": "Datei hochladen", + "commander.web.missions_close": "Schließen", + "commander.web.missions_overwrite": "Überschreiben", + "commander.web.missions_start": "Starten", + "commander.web.missions_edit": "Bearbeiten", + "commander.web.missions_download": "Herunterladen", + "commander.web.missions_delete": "Löschen", + "commander.web.missions_delete_confirm": "Die Mission „{name}“ auf dem Gastgeber löschen?", + "commander.web.missions_deleted": "Gelöscht: {name}", + "commander.web.missions_downloaded": "Heruntergeladen: {name}", + "commander.web.missions_uploaded": "Hochgeladen: {name}", + "commander.web.missions_saved": "Gespeichert: {name}", + "commander.web.missions_upload_invalid": "Diese Datei ist keine Missionsdatei", + "commander.web.missions_too_large": "Die Datei ist zu groß (höchstens 1 MB)", + "commander.web.missions_result_pending": "Wird an den Gastgeber gesendet ...", + "commander.web.missions_result_failed": "Der Gastgeber konnte das nicht ausführen", + "commander.web.missions_result_exists": "Eine andere Mission mit diesem Schlüssel ist schon vorhanden", + "commander.web.missions_result_issues": "Nicht gespeichert: {issues}", + "commander.web.missions_side_frigate": "Fregatte", + "commander.web.missions_side_uboot": "U-Boot", + "commander.web.missions_side_uboot_long": "U-Boot (die KI-Fregatte jagt es)", + "commander.web.missions_objective_sink": "Versenken", + "commander.web.missions_objective_survive": "Durchhalten", + "commander.web.missions_objective_protect": "Schützen", + "commander.web.missions_objective_reach": "Punkt erreichen", + "commander.web.missions_objective_note_frigate_sink": "Die Fregatte muss alle platzierten feindlichen U-Boote versenken (alle sind Ziele).", + "commander.web.missions_objective_note_frigate_survive": "Die Fregatte gewinnt, wenn sie zum Zeitlimit noch schwimmt.", + "commander.web.missions_objective_note_frigate_protect": "Die Fregatte gewinnt, wenn alle geschützten eigenen oder neutralen Einheiten zum Zeitlimit noch schwimmen.", + "commander.web.missions_objective_note_frigate_reach": "Die Fregatte gewinnt im Radius des Punkts vor dem Zeitlimit.", + "commander.web.missions_objective_note_uboot_sink": "Das U-Boot muss die gewählten Handelsschiffe versenken (Geleitschiffe können keine Ziele sein).", + "commander.web.missions_objective_note_uboot_survive": "Das U-Boot gewinnt, wenn es zum Zeitlimit noch schwimmt.", + "commander.web.missions_objective_note_uboot_reach": "Das U-Boot gewinnt im Radius des Punkts vor dem Zeitlimit.", + "commander.web.missions_tabs": "Missionsbereiche", + "commander.web.missions_tab_overview": "Übersicht", + "commander.web.missions_tab_world": "Welt", + "commander.web.missions_tab_units": "Einheiten", + "commander.web.missions_tab_objective": "Ziel", + "commander.web.missions_tab_events": "Ereignisse", + "commander.web.missions_map": "Kartenvorschau: zum Platzieren klicken", + "commander.web.missions_pick_player": "Fregatte platzieren", + "commander.web.missions_pick_unit": "Auf Karte setzen", + "commander.web.missions_pick_reach": "Punkt auf der Karte setzen", + "commander.web.missions_pick_hint": "Ein Klick auf die Karte setzt: {what}", + "commander.web.missions_pick_player_label": "die Fregatte", + "commander.web.missions_pick_reach_label": "den Zielpunkt", + "commander.web.missions_pick_unit_label": "die Einheit", + "commander.web.missions_back": "Zurück zur Liste", + "commander.web.missions_export_draft": "Entwurf herunterladen", + "commander.web.missions_save": "Speichern", + "commander.web.missions_save_start": "Speichern und starten", + "commander.web.missions_new_title": "Neue Mission: {name}", + "commander.web.missions_edit_title": "Mission bearbeiten: {name}", + "commander.web.missions_new_name": "Neue Mission", + "commander.web.missions_key": "Schlüssel (user.…)", + "commander.web.missions_name": "Name", + "commander.web.missions_description": "Einweisung", + "commander.web.missions_seed": "Startwert", + "commander.web.missions_player_side": "Spielerseite", + "commander.web.missions_boat": "Eigenes U-Boot", + "commander.web.missions_boat_none": "(ein platziertes feindliches U-Boot wählen)", + "commander.web.missions_boat_note": "Zuerst unter Einheiten ein feindliches U-Boot platzieren; der Spieler führt es.", + "commander.web.missions_world": "Seegebiet", + "commander.web.missions_world_fixed": "Offene See (ohne Küste)", + "commander.web.missions_world_sector": "Sektor {index}:", + "commander.web.missions_frigate_x": "Fregatte X (sm)", + "commander.web.missions_frigate_y": "Fregatte Y (sm)", + "commander.web.missions_course": "Kurs (°)", + "commander.web.missions_speed": "Fahrt (kn)", + "commander.web.missions_depth": "Tiefe (m)", + "commander.web.missions_sea_state": "Seegang", + "commander.web.missions_time_hour": "Uhrzeit (h)", + "commander.web.missions_thermocline": "Sprungschicht (m)", + "commander.web.missions_weather": "Wetter", + "commander.web.missions_weather_clear": "Klar", + "commander.web.missions_weather_rain": "Regen", + "commander.web.missions_weather_storm": "Sturm", + "commander.web.missions_weather_fog": "Nebel", + "commander.web.missions_sectors": "Gebiete (für Zufallsplatzierung)", + "commander.web.missions_add_sector": "Gebiet hinzufügen", + "commander.web.missions_id": "Kennung", + "commander.web.missions_x": "X (sm)", + "commander.web.missions_y": "Y (sm)", + "commander.web.missions_width": "Breite (sm)", + "commander.web.missions_height": "Höhe (sm)", + "commander.web.missions_radius": "Radius (sm)", + "commander.web.missions_remove": "Entfernen", + "commander.web.missions_exact_units": "Platzierte Einheiten", + "commander.web.missions_groups": "Zufallsgruppen", + "commander.web.missions_add_unit": "Einheit hinzufügen", + "commander.web.missions_add_group": "Gruppe hinzufügen", + "commander.web.missions_profile": "Typ", + "commander.web.missions_group_profiles": "Typen (je Mitglied wird einer gezogen)", + "commander.web.missions_own_unit": "eigene", + "commander.web.missions_unit_side": "Seite", + "commander.web.missions_unit_hostile": "Feindlich", + "commander.web.missions_unit_neutral": "Neutral", + "commander.web.missions_unit_friendly": "Eigen", + "commander.web.missions_count_min": "Anzahl von", + "commander.web.missions_count_max": "Anzahl bis", + "commander.web.missions_placement": "Platzierung", + "commander.web.missions_placement_fixed": "Fester Punkt", + "commander.web.missions_placement_sector": "Zufällig in einem Gebiet", + "commander.web.missions_sector": "Gebiet", + "commander.web.missions_kind_sub": "U-Boote", + "commander.web.missions_kind_surface": "Überwasserschiffe", + "commander.web.missions_kind_aircraft": "Flugzeuge", + "commander.web.missions_kind_animal": "Tiere", + "commander.web.missions_kind_decoy": "Täuschkörper", + "commander.web.missions_kind_torpedo": "Laufende Torpedos", + "commander.web.missions_objective": "Ziel", + "commander.web.missions_time_limit": "Zeitlimit (min)", + "commander.web.missions_targets": "Ziele", + "commander.web.missions_add_event": "Ereignis hinzufügen", + "commander.web.missions_event_at": "Zeitpunkt (min)", + "commander.web.missions_event_type": "Ereignis", + "commander.web.missions_event_message": "Funkspruch", + "commander.web.missions_event_spawn": "Gruppe erscheint", + "commander.web.missions_event_weather": "Wetterwechsel", + "commander.web.missions_event_objective": "Mission entschieden", + "commander.web.missions_event_text": "Text", + "commander.web.missions_event_group": "Gruppe", + "commander.web.missions_event_action": "Ergebnis", + "commander.web.missions_event_complete": "Auftrag erfüllt", + "commander.web.missions_event_fail": "Auftrag gescheitert", + "commander.web.missions_event_default": "Neue Befehle vom Hauptquartier." } diff --git a/data/i18n/en.json b/data/i18n/en.json index 04568653..52a7f22c 100644 --- a/data/i18n/en.json +++ b/data/i18n/en.json @@ -6543,5 +6543,141 @@ "menu.custom.title.uboot": "Own submarine missions - Enter: start | Esc/Q: back", "menu.custom.empty": "No own missions for this side yet. Build one in the Mission Editor (main menu) or import a shared file there with Ctrl+I.", "menu.custom.hint": "Up/Down choose · Enter start · Esc back", - "menu.custom.start_failed": "This mission cannot start: open it in the Mission Editor and check it" + "menu.custom.start_failed": "This mission cannot start: open it in the Mission Editor and check it", + "commander.web.host_missions": "Own missions", + "commander.web.host_new_own_group": "Own missions", + "commander.web.host_new_own_note": "An own mission brings its own world, weather, time and length.", + "commander.web.host_result_no_mission": "Mission not found on the host", + "commander.web.host_result_mission_rejected": "This mission cannot start: check it in the planner", + "commander.web.missions_eyebrow": "Mission Editor", + "commander.web.missions_title": "Own missions", + "commander.web.missions_note": "Missions of the host's Mission Editor. Download one to share it; a downloaded file can be uploaded here or copied into the uConsole's exchange folder.", + "commander.web.missions_empty": "No own missions yet. Create one with New or upload a shared file.", + "commander.web.missions_truncated": "Only the first 64 missions are shown.", + "commander.web.missions_new": "New", + "commander.web.missions_upload": "Upload file", + "commander.web.missions_close": "Close", + "commander.web.missions_overwrite": "Overwrite", + "commander.web.missions_start": "Start", + "commander.web.missions_edit": "Edit", + "commander.web.missions_download": "Download", + "commander.web.missions_delete": "Delete", + "commander.web.missions_delete_confirm": "Delete the mission “{name}” on the host?", + "commander.web.missions_deleted": "Deleted: {name}", + "commander.web.missions_downloaded": "Downloaded: {name}", + "commander.web.missions_uploaded": "Uploaded: {name}", + "commander.web.missions_saved": "Saved: {name}", + "commander.web.missions_upload_invalid": "This file is not a mission file", + "commander.web.missions_too_large": "The file is too large (at most 1 MB)", + "commander.web.missions_result_pending": "Sending to the host ...", + "commander.web.missions_result_failed": "The host could not do that", + "commander.web.missions_result_exists": "A different mission with this key is already there", + "commander.web.missions_result_issues": "Not saved: {issues}", + "commander.web.missions_side_frigate": "Frigate", + "commander.web.missions_side_uboot": "Submarine", + "commander.web.missions_side_uboot_long": "Submarine (the AI frigate hunts it)", + "commander.web.missions_objective_sink": "Sink", + "commander.web.missions_objective_survive": "Hold out", + "commander.web.missions_objective_protect": "Protect", + "commander.web.missions_objective_reach": "Reach a point", + "commander.web.missions_objective_note_frigate_sink": "The frigate must sink every placed hostile submarine (all of them are the targets).", + "commander.web.missions_objective_note_frigate_survive": "The frigate wins when it is still afloat at the time limit.", + "commander.web.missions_objective_note_frigate_protect": "The frigate wins when every protected friendly or neutral unit is still afloat at the time limit.", + "commander.web.missions_objective_note_frigate_reach": "The frigate wins inside the point's radius before the time limit.", + "commander.web.missions_objective_note_uboot_sink": "The submarine must sink the chosen merchant ships (escorts cannot be targets).", + "commander.web.missions_objective_note_uboot_survive": "The submarine wins when it is still afloat at the time limit.", + "commander.web.missions_objective_note_uboot_reach": "The submarine wins inside the point's radius before the time limit.", + "commander.web.missions_tabs": "Mission sections", + "commander.web.missions_tab_overview": "Overview", + "commander.web.missions_tab_world": "World", + "commander.web.missions_tab_units": "Units", + "commander.web.missions_tab_objective": "Objective", + "commander.web.missions_tab_events": "Events", + "commander.web.missions_map": "Map preview: click to place", + "commander.web.missions_pick_player": "Place the frigate", + "commander.web.missions_pick_unit": "Place on map", + "commander.web.missions_pick_reach": "Place the point on the map", + "commander.web.missions_pick_hint": "A map click places: {what}", + "commander.web.missions_pick_player_label": "the frigate", + "commander.web.missions_pick_reach_label": "the objective point", + "commander.web.missions_pick_unit_label": "the unit", + "commander.web.missions_back": "Back to the list", + "commander.web.missions_export_draft": "Download draft", + "commander.web.missions_save": "Save", + "commander.web.missions_save_start": "Save and start", + "commander.web.missions_new_title": "New mission: {name}", + "commander.web.missions_edit_title": "Edit mission: {name}", + "commander.web.missions_new_name": "New mission", + "commander.web.missions_key": "Key (user.…)", + "commander.web.missions_name": "Name", + "commander.web.missions_description": "Briefing", + "commander.web.missions_seed": "Seed", + "commander.web.missions_player_side": "Player side", + "commander.web.missions_boat": "Player's submarine", + "commander.web.missions_boat_none": "(choose a placed hostile submarine)", + "commander.web.missions_boat_note": "Place a hostile submarine under Units first; the player commands it.", + "commander.web.missions_world": "Sea area", + "commander.web.missions_world_fixed": "Open sea (no coast)", + "commander.web.missions_world_sector": "Sector {index}:", + "commander.web.missions_frigate_x": "Frigate X (nm)", + "commander.web.missions_frigate_y": "Frigate Y (nm)", + "commander.web.missions_course": "Course (°)", + "commander.web.missions_speed": "Speed (kn)", + "commander.web.missions_depth": "Depth (m)", + "commander.web.missions_sea_state": "Sea state", + "commander.web.missions_time_hour": "Time of day (h)", + "commander.web.missions_thermocline": "Layer depth (m)", + "commander.web.missions_weather": "Weather", + "commander.web.missions_weather_clear": "Clear", + "commander.web.missions_weather_rain": "Rain", + "commander.web.missions_weather_storm": "Storm", + "commander.web.missions_weather_fog": "Fog", + "commander.web.missions_sectors": "Areas (for random placement)", + "commander.web.missions_add_sector": "Add area", + "commander.web.missions_id": "ID", + "commander.web.missions_x": "X (nm)", + "commander.web.missions_y": "Y (nm)", + "commander.web.missions_width": "Width (nm)", + "commander.web.missions_height": "Height (nm)", + "commander.web.missions_radius": "Radius (nm)", + "commander.web.missions_remove": "Remove", + "commander.web.missions_exact_units": "Placed units", + "commander.web.missions_groups": "Random groups", + "commander.web.missions_add_unit": "Add unit", + "commander.web.missions_add_group": "Add group", + "commander.web.missions_profile": "Type", + "commander.web.missions_group_profiles": "Types (one is drawn per member)", + "commander.web.missions_own_unit": "own", + "commander.web.missions_unit_side": "Side", + "commander.web.missions_unit_hostile": "Hostile", + "commander.web.missions_unit_neutral": "Neutral", + "commander.web.missions_unit_friendly": "Friendly", + "commander.web.missions_count_min": "Count from", + "commander.web.missions_count_max": "Count to", + "commander.web.missions_placement": "Placement", + "commander.web.missions_placement_fixed": "Fixed point", + "commander.web.missions_placement_sector": "Random in an area", + "commander.web.missions_sector": "Area", + "commander.web.missions_kind_sub": "Submarines", + "commander.web.missions_kind_surface": "Surface ships", + "commander.web.missions_kind_aircraft": "Aircraft", + "commander.web.missions_kind_animal": "Animals", + "commander.web.missions_kind_decoy": "Decoys", + "commander.web.missions_kind_torpedo": "Running torpedoes", + "commander.web.missions_objective": "Objective", + "commander.web.missions_time_limit": "Time limit (min)", + "commander.web.missions_targets": "Targets", + "commander.web.missions_add_event": "Add event", + "commander.web.missions_event_at": "At (min)", + "commander.web.missions_event_type": "Event", + "commander.web.missions_event_message": "Radio message", + "commander.web.missions_event_spawn": "Group appears", + "commander.web.missions_event_weather": "Weather change", + "commander.web.missions_event_objective": "Mission decided", + "commander.web.missions_event_text": "Text", + "commander.web.missions_event_group": "Group", + "commander.web.missions_event_action": "Result", + "commander.web.missions_event_complete": "Objective achieved", + "commander.web.missions_event_fail": "Objective failed", + "commander.web.missions_event_default": "New orders from HQ." } diff --git a/src/commander/mission_library.py b/src/commander/mission_library.py index e7b67ec0..78aef121 100644 --- a/src/commander/mission_library.py +++ b/src/commander/mission_library.py @@ -128,8 +128,13 @@ class MissionLibrary: "units": referenced, "data": data, }) + user_profiles = [{"key": key, "kind": str(data.get("profile_kind", "")), + "name": str(data.get("name", key))[:80], + "warship": data.get("category") == "KAMPFSCHIFF"} + for key, data in sorted(units.items())][:4 * LIBRARY_MAX_MISSIONS] return {"protocol": 2, "revision": self.revision, "missions": missions, "units": [units[key] for key in sorted(wanted)], + "user_profiles": user_profiles, "results": list(self._results), "truncated": truncated} def apply(self, op) -> dict: diff --git a/src/commander/missions.py b/src/commander/missions.py index 39ed2871..0ac040be 100644 --- a/src/commander/missions.py +++ b/src/commander/missions.py @@ -29,7 +29,7 @@ SECTOR_MAX_BYTES = 64 * 1024 MISSION_OPS_PENDING_MAX = 4 MISSION_OPS = ("save", "import", "delete") _BLANK = _json_bytes({"protocol": 2, "revision": 0, "missions": [], "units": [], - "results": [], "truncated": False}) + "user_profiles": [], "results": [], "truncated": False}) def _text_id(value) -> bool: diff --git a/tests/test_missions_web.py b/tests/test_missions_web.py new file mode 100644 index 00000000..7d5d1da3 --- /dev/null +++ b/tests/test_missions_web.py @@ -0,0 +1,126 @@ +"""Own missions in the Remote Crew browser: the solo host plans a mission, +saves it to the uConsole's library, finds it in the list and starts it.""" + +import json +from pathlib import Path +import shutil +import subprocess +import time + +import pytest +from commander_web import copy_assets, index_html, inject_probe + +from src.commander import server +from src.core.game import Game +from test_commander_assets import Document, PREFIX, catalogs + +PROBE = r''' +(() => { + const $ = (id) => document.getElementById(id); + const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + async function until(check, message, limit = 900) { + for (let index = 0; index < limit; index++) { + if (check()) return; + await sleep(20); + } + throw new Error(message); + } + const errors = []; + window.addEventListener('error', (event) => errors.push(String(event.message))); + window.addEventListener('unhandledrejection', (event) => errors.push(String(event.reason))); + const overflow = (element) => element.scrollWidth > element.clientWidth + 1; + async function run() { + await until(() => !$('shell').hidden, 'translations'); + $('name').value = 'Planner'; $('code').value = __CODE__; + $('pair-form').requestSubmit(); + await until(() => !$('host-bar').hidden && !$('host-missions').disabled, 'missions button', 3000); + $('host-missions').click(); + const dialog = $('missions-dialog'); + await until(() => dialog.open && !$('missions-empty').hidden, 'empty library'); + $('missions-new').click(); + await until(() => !$('missions-editor').hidden && $('missions-panel').querySelector('input'), 'editor'); + const key = $('missions-panel').querySelector('input'); + key.value = 'user.browser_plan'; + key.dispatchEvent(new Event('change')); + const name = $('missions-panel').querySelectorAll('input')[1]; + name.value = 'Browser plan'; + name.dispatchEvent(new Event('change')); + for (const tab of ['world', 'units', 'objective', 'events', 'overview']) { + $(`missions-tab-${tab}`).click(); + await until(() => $(`missions-tab-${tab}`).getAttribute('aria-selected') === 'true', `tab ${tab}`); + if (overflow(dialog)) throw new Error(`horizontal overflow on ${tab}`); + } + const canvas = $('missions-map'); + await until(() => canvas.width > 50 && canvas.height > 50, 'map size'); + $('missions-save').click(); + await until(() => $('missions-status').dataset.status === 'applied', 'saved', 1500); + $('missions-back').click(); + await until(() => $('missions-list').querySelectorAll('li').length === 1, 'listed', 1500); + const row = $('missions-list').querySelector('li'); + if (!row.textContent.includes('Browser plan')) throw new Error('row name'); + const start = row.querySelector('.missions-row-actions button.primary'); + if (start.disabled) throw new Error('start disabled'); + start.click(); + await until(() => !dialog.open, 'dialog closes on start', 1500); + } + run().then(() => document.documentElement.dataset.missionsTest = 'passed', (error) => { + document.documentElement.dataset.missionsTest = 'failed'; + document.documentElement.dataset.failure = String(error.stack || error) + ' ' + errors.join(' | '); + }); +})(); +''' + + +@pytest.mark.parametrize("width,height", [(1600, 1000), (420, 900)]) +def test_solo_host_plans_saves_and_starts_an_own_mission(tmp_path, monkeypatch, width, height): + chromium = (shutil.which("chromium") or shutil.which("chromium-browser") + or shutil.which("google-chrome")) + if not chromium: + pytest.skip("Optional browser contract: no Chromium") + en, de = catalogs() + game = Game(seed=4242, start_menu=False, audio_enabled=False, language="en") + console = game.commander + console.solo = True + console.port = 0 + console._translations = { + "en": {key: value for key, value in en.items() if key.startswith(PREFIX)}, + "de": {key: value for key, value in de.items() if key.startswith(PREFIX)}, + } + console._contact_analysis_assets = {} + console._manual_pages = {} + html = inject_probe(index_html(), "missions-test.js") + copy_assets(tmp_path, html) + # Only the web client is served from the copy; catalogs and coasts stay packaged. + original = server.resources.files + monkeypatch.setattr(server.resources, "files", + lambda package: tmp_path if package == "data.commander" else original(package)) + console.activate(game) + console.server._http.assets["/missions-test.js"] = ( + "text/javascript; charset=utf-8", + PROBE.replace("__CODE__", json.dumps(console.pairing_code)).encode("utf-8")) + console.bridge.allowed = True + process = subprocess.Popen([ + chromium, "--headless", "--no-sandbox", "--disable-gpu", + "--disable-background-networking", "--no-first-run", + "--no-default-browser-check", "--disable-dev-shm-usage", + f"--user-data-dir={tmp_path / 'browser'}", "--virtual-time-budget=150000", + f"--window-size={width},{height}", "--dump-dom", + f"http://{console.address[0]}:{console.address[1]}/", + ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + started = time.monotonic() + try: + while process.poll() is None and time.monotonic() - started < 90: + console.pump(game) + game.update(.02) + time.sleep(.02) + stdout, stderr = process.communicate(timeout=5) + finally: + if process.poll() is None: + process.kill() + stdout, stderr = process.communicate(timeout=5) + console.stop() + game.audio.shutdown() + assert process.returncode == 0, stderr + root = next((attrs for tag, attrs in Document(stdout).elements if tag == "html"), {}) + assert root.get("data-missions-test") == "passed", root.get("data-failure", stderr[-2000:]) + assert (game.custom_mission_definition or {}).get("key") == "user.browser_plan"