From 2642552891cf10f1294a498520d40f3f0460b907 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sun, 15 Nov 2026 23:01:45 +0300 Subject: [PATCH] - Fix Readme - Fix co-op so it actually works --- README.md | 9 +- public/css/base.css | 94 +- public/css/components.css | 170 ++- public/css/hud.css | 559 +++++++-- public/css/screens.css | 1090 ++++++++++++++--- src/client/api.ts | 125 +- src/client/app.ts | 25 +- src/client/router.ts | 42 +- src/client/screens/auth.ts | 185 ++- src/client/screens/builder/context.ts | 2 + src/client/screens/builder/engineeringBar.ts | 84 +- src/client/screens/builder/payloadTab.ts | 515 ++++---- src/client/screens/builder/stagesTab.ts | 2 +- .../screens/builder/valueAndComplianceTabs.ts | 78 +- src/client/screens/builder/viewportAndDrag.ts | 12 +- src/client/screens/contracts.ts | 25 +- src/client/screens/contracts/offersPanel.ts | 15 +- src/client/screens/dashboard.ts | 376 +++--- src/client/screens/dashboard/sidebarCards.ts | 67 +- src/client/screens/dashboard/techLabModal.ts | 10 + src/client/screens/launchSequence.ts | 83 +- src/client/screens/mainMenu.ts | 15 +- src/client/screens/missionConfig.ts | 232 +++- src/client/screens/missionConfig/prelaunch.ts | 14 +- src/client/screens/rocketBuilder.ts | 279 ++++- src/client/screens/worldMap.ts | 88 +- src/client/session.ts | 130 +- src/client/state.ts | 15 + src/client/theme.ts | 12 +- src/client/ui/coopBar.ts | 606 +++++++++ src/client/wiki/wikiData.ts | 3 +- src/server/auth.ts | 162 ++- src/server/coopPresence.ts | 282 +++++ src/server/events.ts | 17 +- src/server/index.ts | 53 +- src/server/routes/agencyRoutes.ts | 33 +- src/server/routes/authRoutes.ts | 80 +- src/server/routes/contractRoutes.ts | 5 + src/server/routes/designRoutes.ts | 293 +++-- src/server/routes/helpers.ts | 75 ++ src/server/routes/missionRoutes.ts | 60 +- src/server/store.ts | 18 + src/shared/coop.ts | 235 ++++ src/shared/types/agency.ts | 1 + src/shared/types/spacecraft.ts | 18 + 45 files changed, 5069 insertions(+), 1225 deletions(-) create mode 100644 src/client/ui/coopBar.ts create mode 100644 src/server/coopPresence.ts create mode 100644 src/shared/coop.ts diff --git a/README.md b/README.md index cb70364..f3d9790 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,14 @@ Space mission simulation game where you choose a contractor and finish space fli ## How to run ```bash +# Install dependencies npm ci +# Build and start the server npm run bs ``` -``` -``` +# Dependencies + +- Node.js +- GMAT 2026a (Linux x64) - path to GMAT binary is configured as GMAT_PATH and is optional. +- Python 3.x? (For ML-AI players) diff --git a/public/css/base.css b/public/css/base.css index 80ce8c7..4ca261c 100644 --- a/public/css/base.css +++ b/public/css/base.css @@ -1,32 +1,88 @@ /* Ace of base */ .screen { - position: absolute; inset: 0; - display: flex; flex-direction: column; + position: absolute; + inset: 0; + display: flex; + flex-direction: column; } .screen-center { - display: flex; align-items: center; justify-content: center; - height: 100%; padding: 20px; + display: flex; + flex-direction: row; + align-items: flex-start; + justify-content: center; + height: 100%; + padding: 20px 20px 64px; + overflow-y: auto; +} +.screen-center > * { + margin: auto 0; } -.row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; } -.col { display: flex; flex-direction: column; gap: 12px; } -.spread { display: flex; justify-content: space-between; align-items: center; gap: 10px; } -.grow { flex: 1; } +.row { + display: flex; + gap: 10px; + align-items: center; + flex-wrap: wrap; + min-width: 0; +} +.col { + display: flex; + flex-direction: column; + gap: 12px; + min-width: 0; +} +.spread { + display: flex; + justify-content: space-between; + align-items: center; + gap: 10px; + flex-wrap: wrap; + min-width: 0; +} +.grow { + flex: 1; + min-width: 0; +} -h1, h2, h3 { +h1, +h2, +h3 { font-family: var(--mono); letter-spacing: 0.1em; text-transform: uppercase; font-weight: 700; + overflow-wrap: anywhere; + max-width: 100%; +} +h2 { + font-size: 16px; +} +h3 { + font-size: 13px; } -h2 { font-size: 16px; } -h3 { font-size: 13px; } -.mono { font-family: var(--mono); } -.dim { color: var(--text-dim); } -.faint { color: var(--text-faint); } -.accent { color: var(--sim-accent); transition: color 0.4s ease; } -.brand { color: var(--brand-blue); } -.amber { color: var(--amber); } -.green { color: var(--green); } -.red { color: var(--red); } +.mono { + font-family: var(--mono); +} +.dim { + color: var(--text-dim); +} +.faint { + color: var(--text-faint); +} +.accent { + color: var(--sim-accent); + transition: color 0.4s ease; +} +.brand { + color: var(--brand-blue); +} +.amber { + color: var(--amber); +} +.green { + color: var(--green); +} +.red { + color: var(--red); +} diff --git a/public/css/components.css b/public/css/components.css index 2bfa5b7..5511e8b 100644 --- a/public/css/components.css +++ b/public/css/components.css @@ -10,13 +10,17 @@ transition: border-color 0.35s ease; } .panel::before { - content: ''; - display: block; height: 2px; + content: ""; + display: block; + height: 2px; background: linear-gradient(90deg, var(--sim-accent), transparent 70%); opacity: 0.7; } -.card-grid { display: grid; gap: 12px; } +.card-grid { + display: grid; + gap: 12px; +} .card { padding: 14px 16px; border: 1px solid var(--border); @@ -25,36 +29,79 @@ background-color: var(--bg-panel); background-image: var(--panel-gradient); cursor: pointer; - transition: border-color 0.16s ease, background-color 0.16s ease, transform 0.12s ease; + transition: + border-color 0.16s ease, + background-color 0.16s ease, + transform 0.12s ease; position: relative; } .card::before { - content: ''; - position: absolute; top: 0; left: 0; right: 0; height: 2px; + content: ""; + position: absolute; + top: 0; + left: 0; + right: 0; + height: 2px; background: var(--border); transition: background 0.16s ease; } -.card:hover { border-color: var(--sim-accent); background: var(--bg-elevated); } -.card:hover::before { background: var(--sim-accent); } -.card.selected { border-color: var(--brand-blue); background: var(--bg-elevated); box-shadow: inset 0 0 18px var(--sim-glow); } -.card.selected::before { background: var(--brand-blue); } -.card h3 { margin-bottom: 6px; } -.card .sub { color: var(--text-dim); font-size: 12px; line-height: 1.5; } -.card .meta { margin-top: 10px; display: flex; flex-wrap: wrap; gap: 8px 14px; font-size: 11px; color: var(--text-dim); font-family: var(--mono); } +.card:hover { + border-color: var(--sim-accent); + background: var(--bg-elevated); +} +.card:hover::before { + background: var(--sim-accent); +} +.card.selected { + border-color: var(--brand-blue); + background: var(--bg-elevated); + box-shadow: inset 0 0 18px var(--sim-glow); +} +.card.selected::before { + background: var(--brand-blue); +} +.card h3 { + margin-bottom: 6px; +} +.card .sub { + color: var(--text-dim); + font-size: 12px; + line-height: 1.5; +} +.card .meta { + margin-top: 10px; + display: flex; + flex-wrap: wrap; + gap: 8px 14px; + font-size: 11px; + color: var(--text-dim); + font-family: var(--mono); +} .btn { - display: inline-flex; align-items: center; justify-content: center; gap: 8px; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; padding: 10px 20px; + max-width: 100%; + text-align: center; background: var(--bg-elevated); border: 1px solid var(--border-bright); border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); color: var(--text); font-family: var(--mono); - font-size: 11px; font-weight: 700; letter-spacing: 0.12em; + font-size: 11px; + font-weight: 700; + letter-spacing: 0.12em; text-transform: uppercase; cursor: pointer; - transition: border-color 0.15s ease, color 0.15s ease, background-color 0.15s ease, transform 0.08s ease; + transition: + border-color 0.15s ease, + color 0.15s ease, + background-color 0.15s ease, + transform 0.08s ease; user-select: none; } .btn:hover:not(:disabled) { @@ -62,8 +109,13 @@ color: var(--sim-accent); background: var(--bg-hover); } -.btn:active:not(:disabled) { transform: translateY(1px); } -.btn:disabled { opacity: 0.35; cursor: not-allowed; } +.btn:active:not(:disabled) { + transform: translateY(1px); +} +.btn:disabled { + opacity: 0.35; + cursor: not-allowed; +} .btn.primary { background: var(--btn-primary-bg); @@ -85,18 +137,37 @@ border-color: var(--red); color: var(--btn-danger-text); } -.btn.danger:hover:not(:disabled) { border-color: var(--red); color: var(--red); background: var(--btn-danger-bg); } -.btn.ghost { background: var(--btn-ghost-bg); border-color: var(--border); color: var(--text-dim); } -.btn.ghost:hover:not(:disabled) { border-color: var(--border-bright); color: var(--text); } -.btn.sm { padding: 6px 12px; font-size: 10px; } -.btn.xs { padding: 4px 8px; font-size: 9px; letter-spacing: 0.08em; } +.btn.danger:hover:not(:disabled) { + border-color: var(--red); + color: var(--red); + background: var(--btn-danger-bg); +} +.btn.ghost { + background: var(--btn-ghost-bg); + border-color: var(--border); + color: var(--text-dim); +} +.btn.ghost:hover:not(:disabled) { + border-color: var(--border-bright); + color: var(--text); +} +.btn.sm { + padding: 6px 12px; + font-size: 10px; +} +.btn.xs { + padding: 4px 8px; + font-size: 9px; + letter-spacing: 0.08em; +} .btn.selected { border-color: var(--sim-accent); color: var(--sim-accent); background: var(--sim-glow); } -.input, select.input { +.input, +select.input { width: 100%; padding: 9px 12px; background: var(--bg-deep); @@ -109,8 +180,12 @@ outline: none; transition: border-color 0.15s; } -.input:focus { border-color: var(--brand-blue); } -.input::placeholder { color: var(--text-faint); } +.input:focus { + border-color: var(--brand-blue); +} +.input::placeholder { + color: var(--text-faint); +} input[type="range"].slider { width: 100%; @@ -119,22 +194,45 @@ input[type="range"].slider { } .field { - display: flex; flex-direction: column; gap: 6px; - font-family: var(--mono); font-size: 10px; color: var(--text-dim); - text-transform: uppercase; letter-spacing: 0.12em; + display: flex; + flex-direction: column; + gap: 6px; + font-family: var(--mono); + font-size: 10px; + color: var(--text-dim); + text-transform: uppercase; + letter-spacing: 0.12em; } .badge { - display: inline-flex; align-items: center; gap: 5px; + display: inline-flex; + align-items: center; + gap: 5px; padding: 2px 8px; - font-family: var(--mono); font-size: 9px; font-weight: 700; letter-spacing: 0.1em; + font-family: var(--mono); + font-size: 9px; + font-weight: 700; + letter-spacing: 0.1em; text-transform: uppercase; - border: 1px solid var(--border-bright); color: var(--text-dim); + border: 1px solid var(--border-bright); + color: var(--text-dim); background: var(--badge-bg); border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); } -.badge.ok { color: var(--green); border-color: rgba(52, 211, 153, 0.5); } -.badge.warn { color: var(--amber); border-color: rgba(245, 158, 11, 0.55); } -.badge.err { color: var(--red); border-color: rgba(248, 113, 113, 0.55); } -.badge.info { color: var(--sim-accent); border-color: var(--sim-accent-dim); } +.badge.ok { + color: var(--green); + border-color: rgba(52, 211, 153, 0.5); +} +.badge.warn { + color: var(--amber); + border-color: rgba(245, 158, 11, 0.55); +} +.badge.err { + color: var(--red); + border-color: rgba(248, 113, 113, 0.55); +} +.badge.info { + color: var(--sim-accent); + border-color: var(--sim-accent-dim); +} diff --git a/public/css/hud.css b/public/css/hud.css index f8a6d10..de256ba 100644 --- a/public/css/hud.css +++ b/public/css/hud.css @@ -1,120 +1,334 @@ /* Modals, toasts, notification window, co-op toggle vicodins, value chart, grid (forgot which one), and toggles. */ .modal-overlay { - position: fixed; inset: 0; background: var(--overlay-scrim); backdrop-filter: blur(4px); - display: flex; align-items: center; justify-content: center; z-index: 100; padding: 16px; + position: fixed; + inset: 0; + background: var(--overlay-scrim); + backdrop-filter: blur(4px); + display: flex; + align-items: center; + justify-content: center; + z-index: 100; + padding: 16px; +} +.modal { + width: min(500px, 100%); + max-height: min(86dvh, calc(100dvh - 32px)); + overflow-y: auto; + padding: 22px; +} +.modal h3 { + font-size: 14px; + margin-bottom: 14px; + color: var(--brand-blue); } -.modal { width: min(500px, 100%); max-height: 85vh; overflow-y: auto; padding: 24px; } -.modal h3 { font-size: 14px; margin-bottom: 14px; color: var(--brand-blue); } -#toast-root, .toast-root { - position: fixed; bottom: 64px; right: 20px; z-index: 200; - display: flex; flex-direction: column; gap: 8px; pointer-events: none; +#toast-root, +.toast-root { + position: fixed; + bottom: 64px; + right: calc(20px + var(--right-sidebar-offset, 0px)); + z-index: 200; + display: flex; + flex-direction: column; + gap: 8px; + pointer-events: none; + max-width: calc(100vw - var(--right-sidebar-offset, 0px) - 32px); } .toast { - padding: 11px 16px; border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); - font-family: var(--mono); font-size: 11px; letter-spacing: 0.04em; max-width: 380px; - background: var(--bg-elevated); border: 1px solid var(--border-bright); + padding: 11px 16px; + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + font-family: var(--mono); + font-size: 11px; + letter-spacing: 0.04em; + max-width: min(380px, 100%); + background: var(--bg-elevated); + border: 1px solid var(--border-bright); box-shadow: var(--shadow-elevated); animation: slideIn 0.2s ease; } -.toast.ok { border-color: var(--green); } -.toast.err { border-color: var(--red); } -.toast.info { border-color: var(--brand-blue); } -@keyframes slideIn { from { transform: translateX(40px); opacity: 0; } to { transform: none; opacity: 1; } } +.toast.ok { + border-color: var(--green); +} +.toast.err { + border-color: var(--red); +} +.toast.info { + border-color: var(--brand-blue); +} +@keyframes slideIn { + from { + transform: translateX(40px); + opacity: 0; + } + to { + transform: none; + opacity: 1; + } +} #notif-drawer-root { - position: fixed; bottom: 14px; right: 16px; z-index: 180; + position: fixed; + bottom: 14px; + right: 16px; + z-index: 180; pointer-events: none; } .notif-drawer-wrap { - display: flex; flex-direction: column; align-items: flex-end; gap: 8px; + display: flex; + flex-direction: column; + align-items: flex-end; + gap: 8px; +} +.notif-drawer-wrap > * { + pointer-events: auto; } -.notif-drawer-wrap > * { pointer-events: auto; } .notif-toggle-bar { - display: flex; align-items: center; - background: var(--bg-glass); backdrop-filter: blur(8px); - border: 1px solid var(--border-bright); border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); + display: flex; + align-items: center; + background: var(--bg-glass); + backdrop-filter: blur(8px); + border: 1px solid var(--border-bright); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); box-shadow: var(--shadow-elevated); - max-width: 360px; overflow: hidden; + max-width: 360px; + overflow: hidden; } .notif-toggle-main { - display: flex; align-items: center; gap: 8px; padding: 7px 11px; - background: none; border: none; color: var(--text); cursor: pointer; - min-width: 0; text-align: left; + display: flex; + align-items: center; + gap: 8px; + padding: 7px 11px; + background: none; + border: none; + color: var(--text); + cursor: pointer; + min-width: 0; + text-align: left; +} +.notif-toggle-main:hover { + background: var(--bg-hover); } -.notif-toggle-main:hover { background: var(--bg-hover); } .notif-preview { - font-size: 10px; max-width: 170px; overflow: hidden; - text-overflow: ellipsis; white-space: nowrap; + font-size: 10px; + max-width: 135px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .notif-hide-btn { - padding: 7px 9px; background: var(--bg-inset); border: none; - border-left: 1px solid var(--border); color: var(--text-dim); cursor: pointer; - font-family: var(--mono); font-size: 12px; line-height: 1; + padding: 7px 9px; + background: var(--bg-inset); + border: none; + border-left: 1px solid var(--border); + color: var(--text-dim); + cursor: pointer; + font-family: var(--mono); + font-size: 12px; + line-height: 1; +} +.notif-hide-btn:hover { + color: var(--text); + background: var(--bg-hover); } -.notif-hide-btn:hover { color: var(--text); background: var(--bg-hover); } .notif-mini-pill { - padding: 6px 10px; background: var(--bg-glass); + padding: 6px 10px; + background: var(--bg-glass); box-shadow: var(--shadow-elevated); } .notif-drawer { - width: min(370px, calc(100vw - var(--right-sidebar-offset, 0px) - 32px)); max-height: 340px; - display: flex; flex-direction: column; padding: 10px 12px; gap: 8px; + width: min(370px, calc(100vw - var(--right-sidebar-offset, 0px) - 32px)); + max-height: 340px; + display: flex; + flex-direction: column; + padding: 10px 12px; + gap: 8px; box-shadow: var(--shadow-modal); } -.notif-header { padding-bottom: 4px; border-bottom: 1px solid var(--border-subtle); } -.notif-tabs { display: flex; gap: 5px; flex-wrap: wrap; } +.notif-header { + padding-bottom: 4px; + border-bottom: 1px solid var(--border-subtle); +} +.notif-tabs { + display: flex; + gap: 5px; + flex-wrap: wrap; +} .notif-list { - flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; - max-height: 230px; padding-right: 3px; + flex: 1; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 6px; + max-height: 230px; + padding-right: 3px; } .notif-item { - padding: 7px 9px; background: var(--bg-deep); border: 1px solid var(--border); - border-left-width: 3px; border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); - font-family: var(--mono); font-size: 11px; line-height: 1.35; + padding: 7px 9px; + background: var(--bg-deep); + border: 1px solid var(--border); + border-left-width: 3px; + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + font-family: var(--mono); + font-size: 11px; + line-height: 1.35; +} +.notif-item.ok { + border-left-color: var(--green); +} +.notif-item.err { + border-left-color: var(--red); +} +.notif-item.warn { + border-left-color: var(--amber); +} +.notif-item.info { + border-left-color: var(--brand-blue); +} +.notif-msg { + color: var(--text); + word-break: break-word; } -.notif-item.ok { border-left-color: var(--green); } -.notif-item.err { border-left-color: var(--red); } -.notif-item.warn { border-left-color: var(--amber); } -.notif-item.info { border-left-color: var(--brand-blue); } -.notif-msg { color: var(--text); word-break: break-word; } .list-page { padding-bottom: 58px; } -::-webkit-scrollbar { width: 7px; height: 7px; } -::-webkit-scrollbar-thumb { background: var(--border-bright); } -::-webkit-scrollbar-track { background: transparent; } +::-webkit-scrollbar { + width: 7px; + height: 7px; +} +::-webkit-scrollbar-thumb { + background: var(--border-bright); +} +::-webkit-scrollbar-track { + background: transparent; +} .loading { - display: flex; align-items: center; justify-content: center; - color: var(--text-dim); font-family: var(--mono); font-size: 11px; - letter-spacing: 0.18em; text-transform: uppercase; padding: 16px; + display: flex; + align-items: center; + justify-content: center; + color: var(--text-dim); + font-family: var(--mono); + font-size: 11px; + letter-spacing: 0.18em; + text-transform: uppercase; + padding: 16px; +} +.loading::after { + content: "..."; + animation: dots 1.2s steps(4) infinite; +} +@keyframes dots { + 0% { + content: ""; + } + 25% { + content: "."; + } + 50% { + content: ".."; + } + 75% { + content: "..."; + } +} + +.dash-sidebar, +.builder-sidebar, +.param-side, +.map-sidebar { + min-width: 0; + min-height: 0; +} + +@media (min-width: 961px) and (max-width: 1240px) { + .dash-root { + grid-template-columns: 1fr 310px; + } + .builder-root, + .param-root { + grid-template-columns: 1fr 360px; + } + .map-root { + grid-template-columns: 1fr 290px; + } + .list-page .cols { + grid-template-columns: 1fr 0.85fr; + gap: 14px; + } } -.loading::after { content: '...'; animation: dots 1.2s steps(4) infinite; } -@keyframes dots { 0% { content: ''; } 25% { content: '.'; } 50% { content: '..'; } 75% { content: '...'; } } @media (max-width: 960px) { - .dash-root, .builder-root, .param-root, .map-root, .onboard-layout, .list-page .cols { + .dash-root, + .builder-root, + .map-root { grid-template-columns: 1fr; - grid-template-rows: 45vh 1fr; + grid-template-rows: clamp(220px, 38dvh, 360px) minmax(0, 1fr); } - .dash-sidebar, .builder-body, .param-side, .map-sidebar { - padding-bottom: 58px; + .param-root { + grid-template-columns: 1fr; + grid-auto-rows: max-content; + overflow-y: auto; + padding-bottom: 64px; + } + .param-main, + .param-side { + overflow: visible; + border-left: none; + padding-bottom: 14px; + } + .param-side { + border-top: 1px solid var(--border); + } + .onboard-layout { + grid-template-columns: 1fr; + grid-auto-rows: max-content; + overflow-y: auto; + height: 100%; + padding: 16px 16px 64px; + } + .onboard-scroll { + overflow: visible; + padding-right: 0; + } + .list-page .cols { + grid-template-columns: 1fr; + grid-auto-rows: max-content; + } + .dash-sidebar, + .builder-sidebar, + .map-sidebar { + padding-bottom: 62px; + border-left: none; + border-top: 1px solid var(--border); + } + .builder-viewport { + border-right: none; + border-bottom: 1px solid var(--border); } #hud-bottom-right { right: 16px !important; max-width: calc(100vw - 32px) !important; } + #walkthrough-coach-root { + left: 16px; + right: 16px; + top: 12px; + transform: none; + max-width: calc(100vw - 32px); + } .notif-drawer { width: min(370px, calc(100vw - 32px)) !important; } .wiki-layout { grid-template-columns: 1fr; - grid-template-rows: auto 1fr; + grid-template-rows: auto minmax(0, 1fr); } .wiki-sidebar { max-height: 210px; @@ -124,6 +338,21 @@ } } +@media (max-width: 640px) { + .modal-overlay { + padding: 10px; + } + .modal { + padding: 16px; + } + .card-grid { + grid-template-columns: 1fr !important; + } + .bus-power-grid { + grid-template-columns: 1fr; + } +} + .builder-summary-bar { padding: 8px 12px; border-bottom: 1px solid var(--border); @@ -141,9 +370,9 @@ } .builder-coop-bar { - padding: 6px 12px; - border-bottom: 1px solid var(--border); - background: var(--bg-glass); + padding: 4px 10px; + border-bottom: 1px solid var(--border-subtle); + background: transparent; display: flex; flex-wrap: wrap; gap: 5px; @@ -162,7 +391,10 @@ border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); cursor: pointer; - transition: border-color 0.15s, color 0.15s, background-color 0.15s; + transition: + border-color 0.15s, + color 0.15s, + background-color 0.15s; } .station-pill:hover { border-color: var(--brand-blue); @@ -202,13 +434,27 @@ transition: width 0.25s ease; min-width: 2px; } -.value-seg.base { background: var(--brand-strong); } -.value-seg.science { background: var(--green); } -.value-seg.eff { background: var(--violet); } -.value-seg.bonus { background: var(--amber); } -.value-seg.hw { background: #ef4444; } -.value-seg.bus { background: #f97316; } -.value-seg.ops { background: #eab308; } +.value-seg.base { + background: var(--brand-strong); +} +.value-seg.science { + background: var(--green); +} +.value-seg.eff { + background: var(--violet); +} +.value-seg.bonus { + background: var(--amber); +} +.value-seg.hw { + background: #ef4444; +} +.value-seg.bus { + background: #f97316; +} +.value-seg.ops { + background: #eab308; +} .bus-power-grid { display: grid; @@ -248,7 +494,6 @@ flex-wrap: wrap-reverse; gap: 8px; max-width: calc(100vw - var(--right-sidebar-offset, 0px) - 32px); - transition: right 0.18s ease, max-width 0.18s ease; pointer-events: none; } #hud-bottom-right > * { @@ -309,3 +554,175 @@ line-height: 1.45; color: var(--text-dim); } + +/* Shared Co-op Mission Control bar, station locking, and roster helpers */ +.panel-inset { + padding: 9px 11px; + background: var(--bg-deep); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); +} + +.coop-mission-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px; + padding: 2px 4px; + pointer-events: auto; + max-width: 100%; +} +.coop-mission-bar.compact { + padding: 1px 4px; + gap: 4px; +} + +.dash-coop-bar, +.contracts-coop-bar, +.param-coop-bar, +.launch-coop-strip { + max-width: 100%; + pointer-events: auto; +} + +.coop-pill { + display: inline-flex; + align-items: center; + gap: 5px; + padding: 2px 7px; + background: color-mix(in srgb, var(--bg-deep) 55%, transparent); + border: 1px solid var(--border-bright); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + color: var(--text); + font-family: var(--mono); + font-size: 9px; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; + cursor: pointer; +} +.coop-pill:hover { + border-color: var(--sim-accent); + color: var(--sim-accent); +} +.coop-pill.online { + border-color: rgba(52, 211, 153, 0.55); +} +.coop-pill.invite { + border-color: var(--brand-blue); + color: var(--brand-blue); +} + +.coop-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--text-faint); +} +.coop-dot.on { + background: var(--green); + box-shadow: 0 0 8px var(--green); +} +.coop-code-tag { + color: var(--sim-accent); + font-weight: 700; +} + +.coop-stations-row { + display: flex; + flex-wrap: wrap; + gap: 5px; + align-items: center; +} + +.coop-station-group { + display: inline-flex; + align-items: stretch; + border: 1px solid var(--border); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + background: color-mix(in srgb, var(--bg-deep) 50%, transparent); + overflow: hidden; +} +.coop-station-group.mine { + border-color: var(--sim-accent-dim); + background: var(--sim-glow); +} +.coop-station-group.ready { + border-color: rgba(52, 211, 153, 0.65); + background: rgba(52, 211, 153, 0.1); +} +.coop-station-group.locked { + border-color: rgba(245, 158, 11, 0.45); + opacity: 0.9; +} + +.coop-station-btn, +.coop-station-rel { + background: transparent; + border: none; + color: var(--text); + font-family: var(--mono); + font-size: 9px; + font-weight: 700; + letter-spacing: 0.05em; + padding: 3px 6px; + cursor: pointer; +} +.coop-station-group.open .coop-station-btn { + color: var(--text-dim); +} +.coop-station-group.ready .coop-station-btn { + color: var(--green); +} +.coop-station-group.locked .coop-station-btn { + color: var(--amber); + cursor: not-allowed; +} +.coop-station-btn:hover:not(:disabled) { + background: var(--bg-hover); +} +.coop-station-rel { + border-left: 1px solid var(--border); + color: var(--text-dim); + padding: 3px 5px; +} +.coop-station-rel:hover { + background: rgba(248, 113, 113, 0.18); + color: var(--red); +} + +.coop-lock-banner { + display: flex; + align-items: center; + gap: 8px; + padding: 7px 10px; + margin-bottom: 4px; + background: rgba(245, 158, 11, 0.08); + border: 1px solid rgba(245, 158, 11, 0.48); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + font-family: var(--mono); + font-size: 10px; + line-height: 1.4; + color: var(--amber); +} +.coop-lock-icon { + padding: 2px 5px; + background: rgba(245, 158, 11, 0.2); + border: 1px solid rgba(245, 158, 11, 0.6); + font-size: 9px; + font-weight: 800; + letter-spacing: 0.08em; + flex-shrink: 0; +} +.coop-section-locked { + border-color: rgba(245, 158, 11, 0.35); +} +.coop-section-locked input:disabled, +.coop-section-locked select:disabled, +.coop-section-locked button:disabled { + opacity: 0.52; +} diff --git a/public/css/screens.css b/public/css/screens.css index 8302f71..476c44c 100644 --- a/public/css/screens.css +++ b/public/css/screens.css @@ -1,294 +1,1000 @@ /* Screen-specific layouts for menu, auth, onboarding, dashboard, builder, config, map, launch, and debrief. Not much to say about this one I suppose :( #whatthehellisexpress.js */ .menu-root { - position: absolute; inset: 0; z-index: 2; - display: flex; flex-direction: column; align-items: center; justify-content: center; - pointer-events: none; padding: 24px; + position: absolute; + inset: 0; + z-index: 2; + display: flex; + flex-direction: column; + align-items: center; + pointer-events: none; + padding: 24px 24px 58px; + overflow-y: auto; +} +.menu-root .btn, +.menu-root .menu-card { + pointer-events: auto; } -.menu-root .btn, .menu-root .menu-card { pointer-events: auto; } .menu-brand-pill { - font-family: var(--mono); font-size: 10px; letter-spacing: 0.25em; - text-transform: uppercase; color: var(--brand-blue); - border: 1px solid var(--sim-accent-dim); background: var(--badge-bg); - padding: 5px 14px; margin-bottom: 18px; border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); + font-family: var(--mono); + font-size: 10px; + letter-spacing: 0.25em; + text-transform: uppercase; + color: var(--brand-blue); + border: 1px solid var(--sim-accent-dim); + background: var(--badge-bg); + padding: 5px 14px; + margin-top: auto; + margin-bottom: 18px; + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); } .menu-title { font-family: var(--mono); font-size: clamp(32px, 5.5vw, 66px); - font-weight: 800; letter-spacing: 0.16em; text-transform: uppercase; - text-align: center; color: var(--title-color); - text-shadow: 0 0 36px var(--sim-glow), 0 0 12px var(--sim-accent-dim); + font-weight: 800; + letter-spacing: 0.16em; + text-transform: uppercase; + text-align: center; + color: var(--title-color); + text-shadow: + 0 0 36px var(--sim-glow), + 0 0 12px var(--sim-accent-dim); } .menu-title::after { - content: ''; display: block; height: 2px; margin: 12px auto 0; width: 72%; - background: linear-gradient(90deg, transparent, var(--brand-blue), transparent); + content: ""; + display: block; + height: 2px; + margin: 12px auto 0; + width: 72%; + background: linear-gradient( + 90deg, + transparent, + var(--brand-blue), + transparent + ); } .menu-subtitle { - color: var(--text-dim); letter-spacing: 0.42em; text-transform: uppercase; - font-size: 11px; font-family: var(--mono); margin: 14px 0 42px; text-align: center; + color: var(--text-dim); + letter-spacing: 0.42em; + text-transform: uppercase; + font-size: 11px; + font-family: var(--mono); + margin: 14px 0 36px; + text-align: center; +} +.menu-buttons { + display: flex; + gap: 14px; + flex-wrap: wrap; + justify-content: center; + margin-bottom: auto; +} +.menu-buttons .btn { + min-width: 190px; + padding: 14px 28px; + font-size: 12px; } -.menu-buttons { display: flex; gap: 14px; flex-wrap: wrap; justify-content: center; } -.menu-buttons .btn { min-width: 190px; padding: 14px 28px; font-size: 12px; } .menu-footer { - position: absolute; bottom: 18px; font-size: 10px; color: var(--text-faint); - letter-spacing: 0.16em; font-family: var(--mono); text-align: center; + position: relative; + bottom: auto; + margin-top: 22px; + flex-shrink: 0; + font-size: 10px; + color: var(--text-faint); + letter-spacing: 0.16em; + font-family: var(--mono); + text-align: center; } -.auth-card { width: min(580px, 100%); padding: 28px; } -.auth-card h2 { font-size: 18px; margin-bottom: 6px; } -.auth-card .sub { color: var(--text-dim); font-size: 12px; margin-bottom: 22px; line-height: 1.5; } -.auth-error { color: var(--red); font-size: 12px; min-height: 16px; font-family: var(--mono); } +.auth-card { + width: min(580px, 100%); + padding: 28px; +} +.auth-card h2 { + font-size: 18px; + margin-bottom: 6px; +} +.auth-card .sub { + color: var(--text-dim); + font-size: 12px; + margin-bottom: 22px; + line-height: 1.5; +} +.auth-error { + color: var(--red); + font-size: 12px; + min-height: 16px; + font-family: var(--mono); +} -.diff-picker { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; } +.diff-picker { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 8px; +} .diff-card { - display: flex; flex-direction: column; gap: 4px; text-align: left; - padding: 10px 12px; text-transform: none; letter-spacing: 0.02em; font-weight: 500; + display: flex; + flex-direction: column; + gap: 4px; + text-align: left; + padding: 10px 12px; + text-transform: none; + letter-spacing: 0.02em; + font-weight: 500; } .diff-card .dc-head { - display: flex; justify-content: space-between; align-items: center; width: 100%; - font-family: var(--mono); font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; + display: flex; + justify-content: space-between; + align-items: center; + width: 100%; + font-family: var(--mono); + font-size: 11px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.08em; +} +.diff-card .dc-sub { + font-size: 11px; + color: var(--text-dim); + line-height: 1.35; +} +.diff-card .dc-meta { + font-family: var(--mono); + font-size: 10px; + color: var(--text-faint); } -.diff-card .dc-sub { font-size: 11px; color: var(--text-dim); line-height: 1.35; } -.diff-card .dc-meta { font-family: var(--mono); font-size: 10px; color: var(--text-faint); } .onboard-layout { - display: grid; grid-template-columns: 1fr 340px; gap: 20px; height: 100%; padding: 22px; overflow: hidden; + display: grid; + grid-template-columns: 1fr 340px; + gap: 20px; + height: 100%; + padding: 22px; + overflow: hidden; +} +.onboard-scroll { + overflow-y: auto; + padding-right: 6px; + min-width: 0; +} +.onboard-preview { + display: flex; + flex-direction: column; + gap: 12px; + min-width: 0; } -.onboard-scroll { overflow-y: auto; padding-right: 6px; } -.onboard-preview { display: flex; flex-direction: column; gap: 12px; } .onboard-preview-box { - height: 280px; position: relative; border: 1px solid var(--border); - background: var(--bg-deep); border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); overflow: hidden; + height: 280px; + position: relative; + border: 1px solid var(--border); + background: var(--bg-deep); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + overflow: hidden; } -.dash-root { display: grid; grid-template-columns: 1fr 370px; height: 100%; } -.dash-viewport { position: relative; overflow: hidden; } -.dash-viewport canvas { display: block; } -.dash-header { - position: absolute; top: 0; left: 0; right: 0; - display: flex; justify-content: space-between; align-items: center; gap: 12px; - padding: 14px 20px; z-index: 5; - background: linear-gradient(180deg, var(--bg-header-fade), transparent); +.dash-root { + display: grid; + grid-template-columns: 1fr 370px; + height: 100%; +} +.dash-viewport { + position: relative; + overflow: hidden; +} +.dash-viewport canvas { + display: block; +} +.viewport-hud { + position: absolute; + inset: 0; + z-index: 6; + display: flex; + flex-direction: column; + justify-content: space-between; + gap: 8px; + padding: 12px 14px; pointer-events: none; } -.dash-header > * { pointer-events: auto; } -.dash-header h1 { font-size: 15px; } +.viewport-hud-top { + display: flex; + flex-direction: column; + gap: 8px; + min-width: 0; + pointer-events: none; +} +.viewport-hud-top > * { + pointer-events: auto; +} +.dash-header { + position: relative; + top: auto; + left: auto; + right: auto; + display: flex; + justify-content: space-between; + align-items: center; + gap: 10px 12px; + flex-wrap: wrap; + padding: 10px 14px; + z-index: 5; + background: linear-gradient( + 180deg, + var(--bg-header-fade), + rgba(10, 15, 24, 0.45) + ); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + pointer-events: auto; +} +.dash-header > * { + pointer-events: auto; + min-width: 0; +} +.dash-header h1 { + font-size: 15px; +} .dash-overlay-bottom { - position: absolute; bottom: 16px; left: 20px; right: 20px; z-index: 5; - display: flex; justify-content: space-between; align-items: flex-end; gap: 12px; + position: relative; + bottom: auto; + left: auto; + right: auto; + z-index: 5; + display: flex; + justify-content: space-between; + align-items: flex-end; + gap: 12px; + flex-wrap: wrap; pointer-events: none; } -.dash-overlay-bottom > * { pointer-events: auto; } +.dash-overlay-bottom > * { + pointer-events: auto; +} .dash-sidebar { border-left: 1px solid var(--border); background: var(--bg-panel-solid); - padding: 18px; overflow-y: auto; - display: flex; flex-direction: column; gap: 14px; + padding: 18px; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 14px; +} +.dash-nav { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; + margin-top: auto; + padding-top: 8px; +} +.dash-nav .btn { + justify-content: flex-start; + padding: 11px 12px; + font-size: 10px; +} +.dash-nav .btn.full-span { + grid-column: 1 / -1; + justify-content: center; + padding: 13px 16px; + font-size: 12px; } -.dash-nav { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: auto; padding-top: 8px; } -.dash-nav .btn { justify-content: flex-start; padding: 11px 12px; font-size: 10px; } -.dash-nav .btn.full-span { grid-column: 1 / -1; justify-content: center; padding: 13px 16px; font-size: 12px; } .stat-row { - display: flex; justify-content: space-between; align-items: center; gap: 8px; - font-size: 12px; padding: 6px 0; border-bottom: 1px solid var(--border-subtle); + display: flex; + justify-content: space-between; + align-items: center; + gap: 8px; + font-size: 12px; + padding: 6px 0; + border-bottom: 1px solid var(--border-subtle); font-family: var(--mono); } -.stat-row .k { color: var(--text-dim); text-transform: uppercase; font-size: 10px; letter-spacing: 0.08em; } -.stat-row .v { font-size: 12px; text-align: right; } +.stat-row .k { + color: var(--text-dim); + text-transform: uppercase; + font-size: 10px; + letter-spacing: 0.08em; +} +.stat-row .v { + font-size: 12px; + text-align: right; +} -.builder-root { display: grid; grid-template-columns: 1fr 440px; height: 100%; } -.builder-viewport { position: relative; border-right: 1px solid var(--border); overflow: hidden; } +.builder-root { + display: grid; + grid-template-columns: 1fr 440px; + height: 100%; +} +.builder-viewport { + position: relative; + border-right: 1px solid var(--border); + overflow: hidden; +} .builder-sidebar { background: var(--bg-panel-solid); - display: flex; flex-direction: column; overflow: hidden; + display: flex; + flex-direction: column; + overflow: hidden; } .builder-tier-bar { - display: flex; gap: 6px; padding: 10px 12px; - border-bottom: 1px solid var(--border); background: var(--bg-deep); align-items: center; + display: flex; + gap: 6px; + padding: 10px 12px; + border-bottom: 1px solid var(--border); + background: var(--bg-deep); + align-items: center; +} +.builder-tabs { + display: flex; + border-bottom: 1px solid var(--border); + background: var(--bg-inset); } -.builder-tabs { display: flex; border-bottom: 1px solid var(--border); background: var(--bg-inset); } .builder-tabs button { - flex: 1; padding: 11px 6px; background: none; border: none; color: var(--text-dim); - font-family: var(--mono); font-size: 10px; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; - cursor: pointer; border-bottom: 2px solid transparent; transition: color 0.15s, border-color 0.15s; + flex: 1; + padding: 11px 6px; + background: none; + border: none; + color: var(--text-dim); + font-family: var(--mono); + font-size: 10px; + font-weight: 700; + letter-spacing: 0.1em; + text-transform: uppercase; + cursor: pointer; + border-bottom: 2px solid transparent; + transition: + color 0.15s, + border-color 0.15s; +} +.builder-tabs button.active { + color: var(--sim-accent); + border-bottom-color: var(--sim-accent); +} +.builder-body { + flex: 1; + overflow-y: auto; + padding: 12px; + display: flex; + flex-direction: column; + gap: 12px; } -.builder-tabs button.active { color: var(--sim-accent); border-bottom-color: var(--sim-accent); } -.builder-body { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 12px; } .stage-card { - border: 1px solid var(--border); border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); - padding: 12px; background: var(--bg-elevated); display: flex; flex-direction: column; gap: 9px; + border: 1px solid var(--border); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + padding: 12px; + background: var(--bg-elevated); + display: flex; + flex-direction: column; + gap: 9px; +} +.stage-card.active { + border-color: var(--brand-blue); } -.stage-card.active { border-color: var(--brand-blue); } .slot-group { - background: var(--bg-inset); border: 1px solid var(--border); + background: var(--bg-inset); + border: 1px solid var(--border); border-radius: var(--radius-sm); - padding: 8px 10px; display: flex; flex-direction: column; gap: 6px; + padding: 8px 10px; + display: flex; + flex-direction: column; + gap: 6px; } .slot-title { - font-family: var(--mono); font-size: 9px; font-weight: 700; letter-spacing: 0.12em; - text-transform: uppercase; color: var(--sim-accent); + font-family: var(--mono); + font-size: 9px; + font-weight: 700; + letter-spacing: 0.12em; + text-transform: uppercase; + color: var(--sim-accent); } -.stat-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; } -.stat-box { background: var(--bg-deep); border: 1px solid var(--border); border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); padding: 9px 11px; } -.stat-box .k { font-family: var(--mono); font-size: 9px; color: var(--text-faint); text-transform: uppercase; letter-spacing: 0.1em; } -.stat-box .v { font-family: var(--mono); font-size: 13px; margin-top: 3px; font-weight: 700; } -.stat-box .v.good { color: var(--green); } -.stat-box .v.bad { color: var(--red); } -.stat-box .v.warn { color: var(--amber); } +.stat-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; +} +.stat-box { + background: var(--bg-deep); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + padding: 9px 11px; +} +.stat-box .k { + font-family: var(--mono); + font-size: 9px; + color: var(--text-faint); + text-transform: uppercase; + letter-spacing: 0.1em; +} +.stat-box .v { + font-family: var(--mono); + font-size: 13px; + margin-top: 3px; + font-weight: 700; +} +.stat-box .v.good { + color: var(--green); +} +.stat-box .v.bad { + color: var(--red); +} +.stat-box .v.warn { + color: var(--amber); +} .rule-item { - border: 1px solid var(--border); padding: 8px 10px; background: var(--bg-deep); - border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); display: flex; flex-direction: column; gap: 4px; font-size: 11px; + border: 1px solid var(--border); + padding: 8px 10px; + background: var(--bg-deep); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + display: flex; + flex-direction: column; + gap: 4px; + font-size: 11px; +} +.rule-item.fail { + border-color: rgba(248, 113, 113, 0.5); +} +.rule-item.waived { + border-color: rgba(245, 158, 11, 0.55); +} +.rule-item.pass { + border-color: rgba(52, 211, 153, 0.25); } -.rule-item.fail { border-color: rgba(248, 113, 113, 0.5); } -.rule-item.waived { border-color: rgba(245, 158, 11, 0.55); } -.rule-item.pass { border-color: rgba(52, 211, 153, 0.25); } .builder-hud-bottom { - position: absolute; left: 16px; bottom: 16px; z-index: 4; - display: flex; gap: 8px; flex-wrap: wrap; pointer-events: none; -} -.builder-hud-bottom > * { pointer-events: auto; } - -.param-root { display: grid; grid-template-columns: 1fr 440px; height: 100%; overflow: hidden; } -.param-main { padding: 20px; overflow-y: auto; display: flex; flex-direction: column; gap: 16px; } -.param-side { - border-left: 1px solid var(--border); background: var(--bg-panel-solid); - padding: 18px; overflow-y: auto; display: flex; flex-direction: column; gap: 14px; -} -.canvas-box { - width: 100%; background: var(--bg-deep); border: 1px solid var(--border); - border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); display: block; -} - -.map-root { display: grid; grid-template-columns: 1fr 340px; height: 100%; } -.map-viewport { position: relative; overflow: hidden; } -.map-sidebar { - border-left: 1px solid var(--border); background: var(--bg-panel-solid); - padding: 16px; overflow-y: auto; display: flex; flex-direction: column; gap: 10px; -} -.map-sidebar h3 { font-size: 11px; color: var(--text-dim); margin-top: 8px; } -.legend-item { display: flex; align-items: center; gap: 8px; font-size: 11px; padding: 3px 0; font-family: var(--mono); cursor: pointer; } -.legend-item:hover { color: var(--sim-accent); } -.legend-dot { width: 8px; height: 8px; display: inline-block; } - -.launch-root { display: flex; flex-direction: column; height: 100%; } -.launch-viewport { flex: 1; position: relative; overflow: hidden; } -.launch-hud-stack { - position: absolute; left: 20px; bottom: 20px; z-index: 5; - display: flex; flex-direction: column; gap: 10px; align-items: flex-start; - max-height: calc(100vh - 110px); + position: relative; + left: auto; + bottom: auto; + z-index: 4; + display: flex; + gap: 8px; + flex-wrap: wrap; pointer-events: none; } -.launch-hud-stack > * { pointer-events: auto; } +.builder-hud-bottom > * { + pointer-events: auto; +} +@media (min-width: 961px) { + .viewport-hud .builder-hud-bottom, + .viewport-hud .dash-overlay-bottom { + align-self: flex-start; + max-width: calc(100% - 340px); + } +} + +.param-root { + display: grid; + grid-template-columns: 1fr 440px; + height: 100%; + overflow: hidden; +} +.param-main { + padding: 20px; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 16px; +} +.param-side { + border-left: 1px solid var(--border); + background: var(--bg-panel-solid); + padding: 18px; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 14px; +} +.canvas-box { + width: 100%; + background: var(--bg-deep); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + display: block; +} + +.map-root { + display: grid; + grid-template-columns: 1fr 340px; + height: 100%; +} +.map-viewport { + position: relative; + overflow: hidden; +} +.map-sidebar { + border-left: 1px solid var(--border); + background: var(--bg-panel-solid); + padding: 16px; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 10px; +} +.map-sidebar h3 { + font-size: 11px; + color: var(--text-dim); + margin-top: 8px; +} +.legend-item { + display: flex; + align-items: center; + gap: 8px; + font-size: 11px; + padding: 3px 0; + font-family: var(--mono); + cursor: pointer; +} +.legend-item:hover { + color: var(--sim-accent); +} +.legend-dot { + width: 8px; + height: 8px; + display: inline-block; +} + +.launch-root { + display: flex; + flex-direction: column; + height: 100%; +} +.launch-viewport { + flex: 1; + position: relative; + overflow: hidden; +} +.launch-overlay { + position: absolute; + inset: 0; + z-index: 5; + display: flex; + flex-direction: column; + justify-content: space-between; + gap: 8px; + padding: 14px 16px; + pointer-events: none; +} +.launch-topbar { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 10px 14px; + flex-wrap: wrap; + pointer-events: none; + min-width: 0; +} +.launch-hud-stack { + position: relative; + left: auto; + bottom: auto; + z-index: 5; + display: flex; + flex-direction: column; + gap: 8px; + align-items: flex-start; + max-height: min(56dvh, calc(100dvh - 150px)); + min-height: 0; + overflow-y: auto; + width: min(350px, 100%); + pointer-events: none; + margin-top: auto; +} +.launch-hud-stack > * { + pointer-events: auto; + flex-shrink: 0; +} .launch-hud { - background: var(--bg-glass); backdrop-filter: blur(8px); - border: 1px solid var(--border); border-radius: var(--radius-panel); clip-path: var(--chamfer); - padding: 14px 16px; min-width: 310px; width: min(335px, calc(100vw - 40px)); - font-family: var(--mono); font-size: 11px; + background: var(--bg-glass); + backdrop-filter: blur(8px); + border: 1px solid var(--border); + border-radius: var(--radius-panel); + clip-path: var(--chamfer); + padding: 12px 14px; + min-width: 0; + width: min(335px, 100%); + font-family: var(--mono); + font-size: 11px; } .launch-events { - background: var(--bg-glass); backdrop-filter: blur(8px); - border: 1px solid var(--border); border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); - padding: 12px 14px; width: min(335px, calc(100vw - 40px)); - max-height: 185px; overflow-y: auto; - font-family: var(--mono); font-size: 11px; + background: var(--bg-glass); + backdrop-filter: blur(8px); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + padding: 10px 12px; + width: min(335px, 100%); + max-height: 150px; + overflow-y: auto; + font-family: var(--mono); + font-size: 11px; } .launch-banner { - position: absolute; top: 24px; left: 50%; transform: translateX(-50%); - font-family: var(--mono); font-size: 22px; font-weight: 800; letter-spacing: 0.32em; - text-transform: uppercase; color: var(--sim-accent); - text-shadow: 0 0 28px var(--sim-glow); z-index: 6; pointer-events: none; + position: relative; + top: auto; + left: auto; + transform: none; + flex: 1 1 220px; + pointer-events: none; + font-family: var(--mono); + font-size: clamp(13px, 2vw, 22px); + font-weight: 800; + letter-spacing: clamp(0.1em, 0.25vw, 0.28em); + text-transform: uppercase; + color: var(--sim-accent); + text-shadow: 0 0 28px var(--sim-glow); + z-index: 6; text-align: center; + align-self: center; +} +.launch-controls { + position: relative; + top: auto; + right: auto; + display: flex; + gap: 8px; + flex-wrap: wrap; + align-items: center; + z-index: 6; + pointer-events: auto; +} +.launch-title-left { + position: relative; + top: auto; + left: auto; + z-index: 6; + display: flex; + flex-direction: column; + gap: 4px; + align-items: flex-start; + pointer-events: auto; + min-width: 0; + max-width: min(360px, 100%); +} +.launch-coop-strip:empty { + display: none; } -.launch-controls { position: absolute; top: 18px; right: 20px; display: flex; gap: 8px; z-index: 6; } -.launch-title-left { position: absolute; top: 18px; left: 20px; z-index: 6; display: flex; flex-direction: column; gap: 4px; } -.list-page { padding: 22px; overflow-y: auto; height: 100%; display: flex; flex-direction: column; gap: 16px; } -.list-page .cols { display: grid; grid-template-columns: 1.15fr 0.85fr; gap: 20px; } +.list-page { + padding: 22px; + overflow-y: auto; + height: 100%; + display: flex; + flex-direction: column; + gap: 16px; +} +.list-page .cols { + display: grid; + grid-template-columns: 1.15fr 0.85fr; + gap: 20px; +} -.debrief-root { display: flex; align-items: center; justify-content: center; height: 100%; padding: 20px; overflow-y: auto; } -.debrief-card { width: min(640px, 100%); padding: 30px; } -.score-ring { display: flex; align-items: center; gap: 22px; margin: 18px 0; } -.grade { font-size: 68px; font-weight: 800; font-family: var(--mono); line-height: 1; } -.grade.s { color: var(--brand-blue); } .grade.a { color: var(--green); } -.grade.b { color: var(--amber); } .grade.c { color: var(--red); } .grade.f { color: var(--red); } +.debrief-root { + display: flex; + flex-direction: row; + align-items: flex-start; + justify-content: center; + height: 100%; + padding: 20px 20px 64px; + overflow-y: auto; +} +.debrief-card { + width: min(640px, 100%); + padding: 30px; + margin: auto 0; +} +.score-ring { + display: flex; + align-items: center; + gap: 22px; + margin: 18px 0; +} +.grade { + font-size: 68px; + font-weight: 800; + font-family: var(--mono); + line-height: 1; +} +.grade.s { + color: var(--brand-blue); +} +.grade.a { + color: var(--green); +} +.grade.b { + color: var(--amber); +} +.grade.c { + color: var(--red); +} +.grade.f { + color: var(--red); +} -.wiki-page { display: flex; flex-direction: column; height: 100%; overflow: hidden; background: var(--bg-deep); } +.wiki-page { + display: flex; + flex-direction: column; + height: 100%; + overflow: hidden; + background: var(--bg-deep); +} .wiki-topbar { - padding: 12px 20px; border-bottom: 1px solid var(--border); background: var(--bg-panel-solid); - display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; flex-shrink: 0; + padding: 12px 20px; + border-bottom: 1px solid var(--border); + background: var(--bg-panel-solid); + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + flex-wrap: wrap; + flex-shrink: 0; +} +.wiki-topbar-controls { + flex-wrap: wrap; + align-items: center; +} +.wiki-search-input { + width: clamp(210px, 24vw, 300px); + min-width: 180px; } -.wiki-topbar-controls { flex-wrap: wrap; align-items: center; } -.wiki-search-input { width: clamp(210px, 24vw, 300px); min-width: 180px; } .wiki-layout { - display: grid; grid-template-columns: 270px 1fr; flex: 1; min-height: 0; overflow: hidden; + display: grid; + grid-template-columns: 270px 1fr; + flex: 1; + min-height: 0; + overflow: hidden; } .wiki-sidebar { - border-right: 1px solid var(--border); background: var(--bg-panel-solid); - padding: 14px; overflow-y: auto; display: flex; flex-direction: column; gap: 14px; padding-bottom: 64px; + border-right: 1px solid var(--border); + background: var(--bg-panel-solid); + padding: 14px; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 14px; + padding-bottom: 64px; +} +.wiki-nav-group { + display: flex; + flex-direction: column; + gap: 4px; } -.wiki-nav-group { display: flex; flex-direction: column; gap: 4px; } .wiki-nav-cat { - font-family: var(--mono); font-size: 9px; font-weight: 700; letter-spacing: 0.14em; - text-transform: uppercase; color: var(--text-faint); padding: 4px 6px; + font-family: var(--mono); + font-size: 9px; + font-weight: 700; + letter-spacing: 0.14em; + text-transform: uppercase; + color: var(--text-faint); + padding: 4px 6px; } .wiki-nav-item { - display: flex; align-items: center; justify-content: space-between; gap: 6px; width: 100%; - padding: 8px 10px; background: transparent; border: 1px solid transparent; border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); - color: var(--text-dim); font-family: var(--mono); font-size: 11px; text-align: left; cursor: pointer; - transition: background-color 0.14s, border-color 0.14s, color 0.14s; + display: flex; + align-items: center; + justify-content: space-between; + gap: 6px; + width: 100%; + padding: 8px 10px; + background: transparent; + border: 1px solid transparent; + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + color: var(--text-dim); + font-family: var(--mono); + font-size: 11px; + text-align: left; + cursor: pointer; + transition: + background-color 0.14s, + border-color 0.14s, + color 0.14s; +} +.wiki-nav-item:hover { + background: var(--bg-elevated); + color: var(--text); + border-color: var(--border); +} +.wiki-nav-item.active { + background: var(--sim-glow); + color: var(--sim-accent); + border-color: var(--sim-accent); } -.wiki-nav-item:hover { background: var(--bg-elevated); color: var(--text); border-color: var(--border); } -.wiki-nav-item.active { background: var(--sim-glow); color: var(--sim-accent); border-color: var(--sim-accent); } .wiki-search-hit { - display: flex; flex-direction: column; gap: 3px; width: 100%; padding: 8px 10px; - background: var(--bg-deep); border: 1px solid var(--border); border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); - color: var(--text); text-align: left; cursor: pointer; + display: flex; + flex-direction: column; + gap: 3px; + width: 100%; + padding: 8px 10px; + background: var(--bg-deep); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + color: var(--text); + text-align: left; + cursor: pointer; +} +.wiki-search-hit:hover { + border-color: var(--sim-accent); + background: var(--bg-elevated); } -.wiki-search-hit:hover { border-color: var(--sim-accent); background: var(--bg-elevated); } .wiki-main { - overflow-y: auto; padding: 22px 26px 86px; display: flex; flex-direction: column; gap: 16px; + overflow-y: auto; + padding: 22px 26px 86px; + display: flex; + flex-direction: column; + gap: 16px; +} +.wiki-main > * { + max-width: 980px; +} +.wiki-article-header h2 { + font-size: 20px; + color: var(--text); } -.wiki-main > * { max-width: 980px; } -.wiki-article-header h2 { font-size: 20px; color: var(--text); } .wiki-callout { - display: flex; align-items: flex-start; gap: 10px; padding: 11px 14px; - background: rgba(52, 211, 153, 0.08); border: 1px solid rgba(52, 211, 153, 0.35); - border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); color: var(--text); + display: flex; + align-items: flex-start; + gap: 10px; + padding: 11px 14px; + background: rgba(52, 211, 153, 0.08); + border: 1px solid rgba(52, 211, 153, 0.35); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + color: var(--text); +} +.wiki-section { + padding: 16px 18px; + display: flex; + flex-direction: column; + gap: 10px; +} +.wiki-prose { + font-size: 13px; + line-height: 1.62; + color: var(--text-dim); } -.wiki-section { padding: 16px 18px; display: flex; flex-direction: column; gap: 10px; } -.wiki-prose { font-size: 13px; line-height: 1.62; color: var(--text-dim); } .wiki-bullets { - padding-left: 18px; display: flex; flex-direction: column; gap: 6px; - font-size: 12px; line-height: 1.55; color: var(--text); + padding-left: 18px; + display: flex; + flex-direction: column; + gap: 6px; + font-size: 12px; + line-height: 1.55; + color: var(--text); } .wiki-formula { - padding: 8px 12px; background: var(--bg-deep); border: 1px solid var(--border-bright); - border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); font-family: var(--mono); font-size: 12px; color: var(--brand-blue); + padding: 8px 12px; + background: var(--bg-deep); + border: 1px solid var(--border-bright); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + font-family: var(--mono); + font-size: 12px; + color: var(--brand-blue); +} +.wiki-lab-card { + padding: 16px 18px; +} +.wiki-lab-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 8px; } -.wiki-lab-card { padding: 16px 18px; } -.wiki-lab-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 8px; } .wiki-checklist-item { - padding: 10px 12px; background: var(--bg-deep); border: 1px solid var(--border); - border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); transition: border-color 0.15s; + padding: 10px 12px; + background: var(--bg-deep); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + transition: border-color 0.15s; +} +.wiki-checklist-item.done { + border-color: rgba(52, 211, 153, 0.45); +} +.wiki-glossary-card { + padding: 12px 14px; + display: flex; + flex-direction: column; + gap: 4px; +} +.wiki-glossary-card.highlighted { + border-color: var(--sim-accent); + box-shadow: 0 0 18px var(--sim-glow); +} +.wiki-refs-section { + margin-top: 4px; +} +.wiki-ref-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); + gap: 10px; } -.wiki-checklist-item.done { border-color: rgba(52, 211, 153, 0.45); } -.wiki-glossary-card { padding: 12px 14px; display: flex; flex-direction: column; gap: 4px; } -.wiki-glossary-card.highlighted { border-color: var(--sim-accent); box-shadow: 0 0 18px var(--sim-glow); } -.wiki-refs-section { margin-top: 4px; } -.wiki-ref-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 10px; } .wiki-ref-card { - display: block; text-decoration: none; color: inherit; padding: 12px 14px; - background: var(--bg-panel-solid); border: 1px solid var(--border); border-radius: var(--radius-sm); clip-path: var(--chamfer-sm); - transition: border-color 0.15s, background-color 0.15s; + display: block; + text-decoration: none; + color: inherit; + padding: 12px 14px; + background: var(--bg-panel-solid); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + clip-path: var(--chamfer-sm); + transition: + border-color 0.15s, + background-color 0.15s; +} +.wiki-ref-card:hover { + border-color: var(--brand-blue); + background: var(--bg-elevated); +} +.wiki-ext-link { + text-decoration: none; +} +.wiki-footer-nav { + padding-top: 8px; + border-top: 1px solid var(--border); +} + +@media (max-height: 680px), (max-width: 960px) { + .launch-overlay { + padding: 10px 12px; + gap: 6px; + } + .launch-events { + max-height: 105px; + } + .launch-hud-stack { + max-height: min(62dvh, calc(100dvh - 165px)); + } +} + +@media (max-width: 640px) { + .diff-picker { + grid-template-columns: 1fr; + } + .debrief-root .stat-grid { + grid-template-columns: 1fr; + } + .score-ring { + flex-direction: column; + align-items: flex-start; + gap: 10px; + } + .auth-card, + .debrief-card { + padding: 18px; + } + .onboard-preview-box { + height: 210px; + } + .dash-header h1 { + font-size: 13px; + } + .viewport-hud { + padding: 8px 10px; + } + .list-page { + padding: 14px 12px 64px; + } + .launch-controls { + width: 100%; + justify-content: flex-start; + } + .launch-hud-stack { + padding-bottom: 46px; + } + .wiki-topbar { + padding: 10px 12px; + } + .wiki-main { + padding: 14px 14px 86px; + } } -.wiki-ref-card:hover { border-color: var(--brand-blue); background: var(--bg-elevated); } -.wiki-ext-link { text-decoration: none; } -.wiki-footer-nav { padding-top: 8px; border-top: 1px solid var(--border); } diff --git a/src/client/api.ts b/src/client/api.ts index 3e4a52a..2b6110c 100644 --- a/src/client/api.ts +++ b/src/client/api.ts @@ -1,8 +1,13 @@ // Client HTTP API wrapper, token/settings localStorage helpers -> (this fails half the time but oh well), and SSE stream connection. import type { + AgencyState, + CoopStateSnapshot, LockedDesignItemInfo, RocketDesign, + RocketPatchSection, SavedRocketBlueprint, + TeamStationAssignment, + TeamStationId, } from "../shared/types.js"; export type ShapeSet = "chamfered" | "smooth" | "sharp"; @@ -91,7 +96,7 @@ export const DEFAULT_CUSTOM_TOKENS: CustomThemeTokens = { }; export const DEFAULT_THEME_CONFIG: ThemeConfig = { - shapeSet: "chamfered", + shapeSet: "sharp", colorSet: "catppuccin-mocha", uiEffects: true, motionEffects: true, @@ -135,7 +140,7 @@ export function normalizeThemeConfig( if (!rawTheme) { return { - shapeSet: legacyReduced ? "smooth" : "chamfered", + shapeSet: legacyReduced ? "smooth" : "sharp", colorSet: legacyLight ? "daylight" : legacyReduced @@ -174,7 +179,7 @@ export function normalizeThemeConfig( return { shapeSet: VALID_SHAPE_SETS.has(rawTheme.shapeSet as ShapeSet) ? (rawTheme.shapeSet as ShapeSet) - : "chamfered", + : "sharp", colorSet: VALID_COLOR_SETS.has(rawTheme.colorSet as ColorSet) ? (rawTheme.colorSet as ColorSet) : "catppuccin-mocha", @@ -232,9 +237,24 @@ export function normalizeThemeConfig( } const TOKEN_KEY = "spacegaem_proto_token"; +const CALLSIGN_KEY = "spacegaem_coop_callsign"; const SETTINGS_KEY = "spacegaem_proto_settings"; const SERVER_JOIN_KEY = "spacegaem_server_join_ok"; +export class ApiError extends Error { + status: number; + code?: string; + data?: any; + + constructor(message: string, status: number, code?: string, data?: any) { + super(message); + this.name = "ApiError"; + this.status = status; + this.code = code; + this.data = data; + } +} + export function getServerJoinOk(): boolean { return sessionStorage.getItem(SERVER_JOIN_KEY) === "1"; } @@ -245,12 +265,51 @@ export function setServerJoinOk(ok: boolean): void { } export function getToken(): string | null { - return localStorage.getItem(TOKEN_KEY); + return sessionStorage.getItem(TOKEN_KEY) ?? localStorage.getItem(TOKEN_KEY); } -export function setToken(t: string | null): void { - if (t) localStorage.setItem(TOKEN_KEY, t); - else localStorage.removeItem(TOKEN_KEY); +export function setToken( + t: string | null, + options: { tabOnly?: boolean } = {}, +): void { + if (t) { + sessionStorage.setItem(TOKEN_KEY, t); + if (!options.tabOnly || !localStorage.getItem(TOKEN_KEY)) { + localStorage.setItem(TOKEN_KEY, t); + } + } else { + const active = getToken(); + sessionStorage.removeItem(TOKEN_KEY); + if ( + !options.tabOnly && + active && + localStorage.getItem(TOKEN_KEY) === active + ) { + localStorage.removeItem(TOKEN_KEY); + } else if (!options.tabOnly && !active) { + localStorage.removeItem(TOKEN_KEY); + } + } +} + +export function clearTabToken(): void { + sessionStorage.removeItem(TOKEN_KEY); +} + +export function getSavedCallsign(): string { + return ( + sessionStorage.getItem(CALLSIGN_KEY) ?? + localStorage.getItem(CALLSIGN_KEY) ?? + "" + ); +} + +export function setSavedCallsign(callsign: string): void { + const clean = callsign.trim().slice(0, 24); + if (clean) { + sessionStorage.setItem(CALLSIGN_KEY, clean); + localStorage.setItem(CALLSIGN_KEY, clean); + } } let cachedSettings: ClientSettings | null = null; @@ -309,7 +368,12 @@ async function request( data = { error: text }; } if (!res.ok) { - throw new Error(data?.error ?? `HTTP ${res.status}`); + throw new ApiError( + data?.error ?? `HTTP ${res.status}`, + res.status, + data?.code, + data, + ); } return data as T; } @@ -319,8 +383,46 @@ export const api = { request("GET", url, undefined, auth), post: (url: string, body: unknown, auth = true) => request("POST", url, body, auth), + patch: (url: string, body: unknown, auth = true) => + request("PATCH", url, body, auth), delete: (url: string, auth = true) => request("DELETE", url, undefined, auth), + coopJoin: (joinCode: string, callsign: string) => + request<{ + token: string; + account: { name: string }; + operator: { operatorId: string; callsign: string }; + agency: AgencyState; + coopPresence: CoopStateSnapshot; + }>("POST", "/api/auth/coop-join", { joinCode, callsign }, false), + rotateCoopCode: () => + request<{ ok: boolean; coopJoinCode: string; agency: AgencyState }>( + "POST", + "/api/agency/coop-code", + {}, + true, + ), + updateCoopStation: (payload: { + stationId: TeamStationId; + action: "claim" | "release" | "ready" | "fd_release"; + ready?: boolean; + }) => + request<{ + ok: boolean; + teamStations: Record; + agency: AgencyState; + coopPresence: CoopStateSnapshot; + }>("POST", "/api/agency/station", payload, true), + patchRocketSection: ( + section: RocketPatchSection, + design: Partial, + ) => + request<{ + ok: boolean; + design: RocketDesign; + agency: AgencyState; + changedSection: RocketPatchSection; + }>("PATCH", "/api/agency/rocket", { section, design }, true), getMlStatus: () => request("GET", "/api/ml-status", undefined, false), toggleMlBridge: (enabled?: boolean) => request("POST", "/api/ml-toggle", { enabled }, true), @@ -383,8 +485,11 @@ export interface LiveEvent { at?: number; } -export function connectEvents(onEvent: (ev: LiveEvent) => void): EventSource { - const es = new EventSource("/api/events"); +export function connectEvents( + token: string, + onEvent: (ev: LiveEvent) => void, +): EventSource { + const es = new EventSource(`/api/events?token=${encodeURIComponent(token)}`); es.onmessage = (msg) => { try { const parsed = JSON.parse(msg.data) as LiveEvent; diff --git a/src/client/app.ts b/src/client/app.ts index 65c4b4f..3846154 100644 --- a/src/client/app.ts +++ b/src/client/app.ts @@ -1,5 +1,11 @@ // Literally everything (pls help me my autocorrect is trying to insult me how does this even work) -import { api, getSettings, saveSettings, setServerJoinOk } from "./api.js"; +import { + api, + clearTabToken, + getSettings, + saveSettings, + setServerJoinOk, +} from "./api.js"; import { navigate, registerScreenRenderers } from "./router.js"; import { loadCatalogs, @@ -15,6 +21,7 @@ import { state, type WikiScreenParams, } from "./state.js"; +import { normalizeJoinCode } from "../shared/coop.js"; import { applyVisualPreferences } from "./theme.js"; import { initNotificationDrawer, initTooltipController, toast } from "./ui.js"; import { renderAuth } from "./screens/auth.js"; @@ -118,11 +125,16 @@ async function boot(): Promise { } catch (err) { toast(`Failed to load mission catalogs: ${(err as Error).message}`, "err"); } - const passParam = new URLSearchParams(window.location.search).get("pass"); - if (passParam) { + const urlParams = new URLSearchParams(window.location.search); + const passParam = urlParams.get("pass"); + const joinParam = urlParams.get("join"); + if (passParam || joinParam) { const url = new URL(window.location.href); url.searchParams.delete("pass"); + url.searchParams.delete("join"); window.history.replaceState(null, "", url.toString()); + } + if (passParam) { if (state.serverInfo?.serverPasswordRequired) { try { await api.post("/api/join", { password: passParam }, false); @@ -133,6 +145,13 @@ async function boot(): Promise { } } } + if (joinParam) { + state.pendingJoinCode = normalizeJoinCode(joinParam); + clearTabToken(); + await readyPromise; + navigate("auth"); + return; + } await refreshMe(); if (state.agency) { await refreshWorld(); diff --git a/src/client/router.ts b/src/client/router.ts index 5781d0e..7cd9bf1 100644 --- a/src/client/router.ts +++ b/src/client/router.ts @@ -11,6 +11,7 @@ export type ScreenRenderer = ( const appEl = document.getElementById("app") as HTMLElement; let activeCleanup: (() => void) | null = null; +let activeScreen: ScreenName | null = null; let screenRenderers: Partial> = {}; const RIGHT_SIDEBAR_OFFSET_PX: Partial> = { @@ -20,6 +21,35 @@ const RIGHT_SIDEBAR_OFFSET_PX: Partial> = { worldMap: 340, }; +function syncRightSidebarOffset(): void { + if (!activeScreen || window.innerWidth <= 960) { + document.documentElement.style.setProperty("--right-sidebar-offset", "0px"); + document.documentElement.classList.remove("has-right-sidebar"); + return; + } + const fallback = RIGHT_SIDEBAR_OFFSET_PX[activeScreen] ?? 0; + let sidebarWidth = 0; + if (fallback > 0) { + const sidebarEl = appEl.querySelector( + ".dash-sidebar, .builder-sidebar, .param-side, .map-sidebar", + ); + const measured = sidebarEl + ? Math.round(sidebarEl.getBoundingClientRect().width) + : 0; + sidebarWidth = measured > 0 ? measured : fallback; + } + document.documentElement.style.setProperty( + "--right-sidebar-offset", + `${sidebarWidth}px`, + ); + document.documentElement.classList.toggle( + "has-right-sidebar", + sidebarWidth > 0, + ); +} + +window.addEventListener("resize", syncRightSidebarOffset); + export function registerScreenRenderers( renderers: Partial>, ): void { @@ -38,22 +68,16 @@ export function navigate( } activeCleanup = null; } + activeScreen = screen; setCurrentScreen(screen); - const sidebarOffset = RIGHT_SIDEBAR_OFFSET_PX[screen] ?? 0; - document.documentElement.style.setProperty( - "--right-sidebar-offset", - `${sidebarOffset}px`, - ); - document.documentElement.classList.toggle( - "has-right-sidebar", - sidebarOffset > 0, - ); + syncRightSidebarOffset(); clear(appEl); hideTooltip(); const cleanup = screenRenderers[screen]?.(appEl, params); if (typeof cleanup === "function") { activeCleanup = cleanup; } + requestAnimationFrame(syncRightSidebarOffset); window.dispatchEvent( new CustomEvent("sgywftp:screen-changed", { detail: { screen } }), ); diff --git a/src/client/screens/auth.ts b/src/client/screens/auth.ts index 5a19de4..6bc9b10 100644 --- a/src/client/screens/auth.ts +++ b/src/client/screens/auth.ts @@ -1,18 +1,26 @@ -// Login, registration, and difficulty selector screen. -import { api, setToken } from "../api.js"; +// Login, registration, co-op join, and difficulty selector screen. +import { api, getSavedCallsign, setSavedCallsign, setToken } from "../api.js"; import { navigate } from "../router.js"; -import { refreshMe, refreshWorld, startEvents } from "../session.js"; +import { refreshMe, refreshWorld, restartEvents } from "../session.js"; import { state } from "../state.js"; +import { normalizeJoinCode } from "../../shared/coop.js"; import { DIFFICULTY_PROFILES } from "../../shared/physics.js"; -import type { AgencyState, CanonicalDifficulty } from "../../shared/types.js"; +import type { + AgencyState, + CanonicalDifficulty, + CoopStateSnapshot, +} from "../../shared/types.js"; import { h, toast } from "../ui.js"; export function renderAuth(root: HTMLElement): void { - let mode: "login" | "register" = "register"; + const initialJoin = state.pendingJoinCode ?? ""; + let mode: "login" | "register" | "coop" = initialJoin ? "coop" : "register"; let difficulty: CanonicalDifficulty = "enthusiast"; + const fromInviteLink = Boolean(initialJoin); + const nameInput = h("input", { class: "input", - placeholder: "e.g. Aether Aerospace", + placeholder: "e.g. Nuga Stasiyon", autocomplete: "organization", }); const pwdInput = h("input", { @@ -21,16 +29,50 @@ export function renderAuth(root: HTMLElement): void { placeholder: "Account passphrase (min 4 chars)", autocomplete: "current-password", }); - const errEl = h("div", { class: "auth-error" }); - const tabLogin = h( - "button", - { class: "btn sm ghost" }, - "Existing Agency Login", + const joinCodeInput = h("input", { + class: "input mono", + value: initialJoin, + placeholder: "6-char join code (e.g. K7M2P9)", + style: { textTransform: "uppercase", letterSpacing: "0.08em" }, + }); + const callsignInput = h("input", { + class: "input", + value: getSavedCallsign(), + placeholder: "e.g. Cheeselord14 (used in Co-op)", + maxlength: "24", + }); + + const nameField = h("label", { class: "field" }, "Agency Name", nameInput); + const pwdField = h("label", { class: "field" }, "Passphrase", pwdInput); + const joinCodeField = h( + "label", + { class: "field" }, + "Co-op Agency Join Code", + joinCodeInput, ); + const callsignLabelSpan = h("span", {}, "Operator Callsign (Optional)"); + const callsignField = h( + "label", + { class: "field" }, + callsignLabelSpan, + callsignInput, + ); + + const errEl = h("div", { class: "auth-error" }); const tabRegister = h( "button", - { class: "btn sm primary" }, - "Register New Agency", + { class: "btn sm primary", type: "button" }, + "Register Agency", + ); + const tabLogin = h( + "button", + { class: "btn sm ghost", type: "button" }, + "Agency Login", + ); + const tabCoop = h( + "button", + { class: "btn sm ghost", type: "button" }, + "Join Co-op", ); const diffKeys: CanonicalDifficulty[] = [ "sandbox", @@ -79,9 +121,22 @@ export function renderAuth(root: HTMLElement): void { function syncMode() { tabLogin.className = `btn sm ${mode === "login" ? "primary" : "ghost"}`; tabRegister.className = `btn sm ${mode === "register" ? "primary" : "ghost"}`; + tabCoop.className = `btn sm ${mode === "coop" ? "primary" : "ghost"}`; + + const isCoop = mode === "coop"; + nameField.style.display = isCoop ? "none" : "flex"; + pwdField.style.display = isCoop ? "none" : "flex"; + joinCodeField.style.display = isCoop ? "flex" : "none"; diffGroup.style.display = mode === "register" ? "flex" : "none"; + callsignLabelSpan.textContent = isCoop + ? "Your Operator Callsign (Required)" + : "Your Operator Callsign (Optional)"; submitBtn.textContent = - mode === "register" ? "Establish Agency" : "Authenticate & Enter"; + mode === "register" + ? "Establish Agency" + : isCoop + ? "Join Mission Control" + : "Authenticate & Enter"; errEl.textContent = ""; } tabLogin.addEventListener("click", () => { @@ -92,6 +147,10 @@ export function renderAuth(root: HTMLElement): void { mode = "register"; syncMode(); }); + tabCoop.addEventListener("click", () => { + mode = "coop"; + syncMode(); + }); diffKeys.forEach((d) => { diffButtons[d].addEventListener("click", () => { difficulty = d; @@ -107,6 +166,49 @@ export function renderAuth(root: HTMLElement): void { onSubmit: async (ev: Event) => { ev.preventDefault(); errEl.textContent = ""; + const callsign = callsignInput.value.trim(); + + if (mode === "coop") { + const code = normalizeJoinCode(joinCodeInput.value); + if (code.length < 4) { + errEl.textContent = "Enter the 6-character co-op join code."; + return; + } + if (callsign.length < 2) { + errEl.textContent = + "Enter a 2-24 character callsign so teammates recognize you."; + return; + } + submitBtn.disabled = true; + try { + const res = await api.coopJoin(code, callsign); + setSavedCallsign(res.operator.callsign); + setToken(res.token, { + tabOnly: + fromInviteLink || + Boolean(localStorage.getItem("spacegaem_proto_token")), + }); + state.pendingJoinCode = null; + state.agency = res.agency; + state.account = res.account; + state.operator = res.operator; + state.coopPresence = res.coopPresence; + await refreshMe(); + await refreshWorld(); + restartEvents(); + toast( + `Joined ${res.agency.name} Mission Control as ${res.operator.callsign}.`, + "ok", + ); + if (!res.agency.sponsorId) navigate("onboarding"); + else navigate("dashboard"); + } catch (err) { + errEl.textContent = (err as Error).message; + submitBtn.disabled = false; + } + return; + } + const name = nameInput.value.trim(); const password = pwdInput.value; if (name.length < 2) { @@ -123,23 +225,29 @@ export function renderAuth(root: HTMLElement): void { mode === "register" ? "/api/auth/register" : "/api/auth/login"; const payload = mode === "register" - ? { name, password, difficulty } - : { name, password }; - const res = await api.post<{ token: string; agency: AgencyState }>( - endpoint, - payload, - false, - ); + ? { name, password, difficulty, callsign: callsign || undefined } + : { name, password, callsign: callsign || undefined }; + const res = await api.post<{ + token: string; + account: { name: string }; + operator?: { operatorId: string; callsign: string }; + agency: AgencyState; + coopPresence?: CoopStateSnapshot; + }>(endpoint, payload, false); + if (callsign) setSavedCallsign(callsign); setToken(res.token); + state.pendingJoinCode = null; state.agency = res.agency; - state.account = { name: res.agency.name }; + state.account = res.account ?? { name: res.agency.name }; + state.operator = res.operator ?? null; + state.coopPresence = res.coopPresence ?? null; await refreshMe(); await refreshWorld(); - startEvents(); + restartEvents(); toast( mode === "register" ? `Welcome aboard, ${res.agency.name}.` - : `Authenticated as ${res.agency.name}.`, + : `Authenticated as ${res.agency.name}${res.operator?.callsign ? ` (${res.operator.callsign})` : ""}.`, "ok", ); if (!res.agency.sponsorId) navigate("onboarding"); @@ -150,19 +258,24 @@ export function renderAuth(root: HTMLElement): void { } }, }, - h("label", { class: "field" }, "Agency Name", nameInput), - h("label", { class: "field" }, "Passphrase", pwdInput), + joinCodeField, + nameField, + pwdField, + callsignField, diffGroup, errEl, h( "div", - { class: "row spread", style: { marginTop: "6px" } }, + { class: "row spread", style: { marginTop: "6px", flexWrap: "wrap" } }, h( "button", { class: "btn ghost sm", type: "button", - onClick: () => navigate("mainMenu"), + onClick: () => { + state.pendingJoinCode = null; + navigate("mainMenu"); + }, }, "Back", ), @@ -174,19 +287,27 @@ export function renderAuth(root: HTMLElement): void { { class: "panel auth-card col" }, h( "div", - { class: "row", style: { marginBottom: "4px" } }, + { class: "row wrap", style: { marginBottom: "4px", gap: "6px" } }, tabRegister, tabLogin, + tabCoop, ), - h("h2", {}, "Agency Credentials"), + h("h2", {}, "Mission Control Access"), h( "p", { class: "sub" }, - "Register a new launch provider (agency name is public on the leaderboard) or log into an existing agency.", + "Register a launch provider, log into an existing agency, or enter a co-op join code to staff a live mission control station.", ), form, ); syncMode(); root.appendChild(h("div", { class: "screen screen-center" }, card)); - setTimeout(() => nameInput.focus(), 40); + setTimeout(() => { + if (mode === "coop") { + if (joinCodeInput.value.trim()) callsignInput.focus(); + else joinCodeInput.focus(); + } else { + nameInput.focus(); + } + }, 40); } diff --git a/src/client/screens/builder/context.ts b/src/client/screens/builder/context.ts index 1bda470..cff2122 100644 --- a/src/client/screens/builder/context.ts +++ b/src/client/screens/builder/context.ts @@ -92,6 +92,8 @@ export interface BuilderContext { latestReliability: DesignReliabilityReport | null; latestValueEstimate: ContractValueEstimate | null; latestCoach: CoachDiagnostic[]; + suppressSync: boolean; + syncOwnedSectionsNow: () => Promise; refreshEngineering: (refitCamera?: boolean, immediate?: boolean) => void; renderSidebarBody: () => void; renderAll: () => void; diff --git a/src/client/screens/builder/engineeringBar.ts b/src/client/screens/builder/engineeringBar.ts index 4573df8..52eda41 100644 --- a/src/client/screens/builder/engineeringBar.ts +++ b/src/client/screens/builder/engineeringBar.ts @@ -1,24 +1,19 @@ -// Rocket Builder tier selector, tabs, evaluation pipeline, summary vicodins, and co-op thingies -import { api } from "../../api.js"; +// Rocket Builder tier selector, tabs, evaluation pipeline, summary vicodins, and co-op bar import { state } from "../../state.js"; import { buildRocket, computeDesignReliability, convertStagesToProParts, - createDefaultTeamStations, estimateContractValue, generateCoachDiagnostics, - TEAM_STATION_DEFS, validateDesign, } from "../../../shared/physics.js"; -import type { - AgencyState, - DesignTier, - MaterialSpec, - Part, - TeamStationId, -} from "../../../shared/types.js"; -import { clear, fmtMoney, h, term, toast } from "../../ui.js"; +import type { DesignTier, MaterialSpec, Part } from "../../../shared/types.js"; +import { clear, fmtMoney, h, term } from "../../ui.js"; +import { + applyStationControlLock, + renderCoopMissionBar, +} from "../../ui/coopBar.js"; import { curAgency, priceOfPart, type BuilderContext } from "./context.js"; export function renderTierAndTabs(ctx: BuilderContext): void { @@ -65,6 +60,7 @@ export function renderTierAndTabs(ctx: BuilderContext): void { ), ); }); + applyStationControlLock(ctx.tierBar, "director"); clear(ctx.tabsBar); const tabs: Array<{ id: typeof ctx.activeTab; label: string }> = [ { @@ -274,64 +270,8 @@ export function renderSummaryAndCoopBars(ctx: BuilderContext): void { ), ); clear(ctx.coopBar); - const ag = curAgency(ctx); - const stations = ag.teamStations ?? createDefaultTeamStations(); - const readyCount = TEAM_STATION_DEFS.filter( - (d) => stations[d.id]?.ready, - ).length; - ctx.coopBar.appendChild( - h( - "span", - { class: "mono dim", style: { fontSize: "9px", marginRight: "4px" } }, - `CO-OP (${readyCount}/4)`, - ), - ); - for (const def of TEAM_STATION_DEFS) { - const st = stations[def.id] ?? { - stationId: def.id as TeamStationId, - title: def.title, - operatorName: "Unassigned", - ready: false, - updatedAt: 0, - }; - const cls = st.ready - ? "ready" - : st.operatorName !== "Unassigned" - ? "occupied" - : ""; - const shortOp = - st.operatorName === "Unassigned" ? "OPEN" : st.operatorName.slice(0, 10); - ctx.coopBar.appendChild( - h( - "button", - { - class: `station-pill ${cls}`, - title: `${def.title}: ${def.scope} (Click to claim / toggle Ready)`, - onClick: async () => { - try { - const opName = state.account?.name || ag.name; - const nextReady = st.operatorName === opName ? !st.ready : false; - const res = await api.post<{ - teamStations: AgencyState["teamStations"]; - agency: AgencyState; - }>("/api/agency/station", { - stationId: def.id, - operatorName: opName, - ready: nextReady, - }); - if (state.agency) state.agency.teamStations = res.teamStations; - renderSummaryAndCoopBars(ctx); - toast( - `${def.title}: ${opName} (${nextReady ? "READY" : "ACTIVE"})`, - "info", - ); - } catch (err) { - toast((err as Error).message, "err"); - } - }, - }, - `${def.id.toUpperCase()}: ${shortOp} ${st.ready ? "✓" : "○"}`, - ), - ); - } + renderCoopMissionBar(ctx.coopBar, { + compact: true, + onStationChanged: () => ctx.renderAll(), + }); } diff --git a/src/client/screens/builder/payloadTab.ts b/src/client/screens/builder/payloadTab.ts index d1663c3..f41564a 100644 --- a/src/client/screens/builder/payloadTab.ts +++ b/src/client/screens/builder/payloadTab.ts @@ -9,6 +9,10 @@ import { } from "../../../shared/physics.js"; import type { GroundNetworkTier } from "../../../shared/types.js"; import { fmtMoney, fmtNum, h, term } from "../../ui.js"; +import { + applyStationControlLock, + renderStationLockBanner, +} from "../../ui/coopBar.js"; import { partLockTag, type BuilderContext } from "./context.js"; export function renderPayloadTab(ctx: BuilderContext): void { @@ -154,6 +158,9 @@ export function renderPayloadTab(ctx: BuilderContext): void { "CRITICAL: Vehicle has no Flight Computer! Select avionics above to enable GNC & pass AVN-01.", ), ); + const sysLock = renderStationLockBanner("systems"); + if (sysLock) computerCard.prepend(sysLock); + applyStationControlLock(computerCard, "systems"); bodyEl.appendChild(computerCard); const activeHazards = state.world?.activeHazards ?? []; if (activeHazards.length > 0) { @@ -258,26 +265,28 @@ export function renderPayloadTab(ctx: BuilderContext): void { ctx.refreshEngineering(false, false); }, }); - bodyEl.appendChild( + const proPayloadCard = h( + "div", + { class: "stage-card active" }, + h("h3", {}, "Pro Payload & Mission Mass"), h( "div", - { class: "stage-card active" }, - h("h3", {}, "Pro Payload & Mission Mass"), - h( - "div", - { class: "dim", style: { fontSize: "11px", marginBottom: "6px" } }, - "In Pro mode, mount or reposition Fairings, Payloads, and LAS Towers inside the Pro Assembly tab.", - ), - h("label", { class: "field" }, "Payload Mass Override (kg)", massInput), - contract - ? h( - "div", - { class: "mono dim", style: { fontSize: "10px" } }, - `Contract payload requirement: ${fmtNum(contract.payloadMass)} kg`, - ) - : null, + { class: "dim", style: { fontSize: "11px", marginBottom: "6px" } }, + "In Pro mode, mount or reposition Fairings, Payloads, and LAS Towers inside the Pro Assembly tab.", ), + h("label", { class: "field" }, "Payload Mass Override (kg)", massInput), + contract + ? h( + "div", + { class: "mono dim", style: { fontSize: "10px" } }, + `Contract payload requirement: ${fmtNum(contract.payloadMass)} kg`, + ) + : null, ); + const sciLock = renderStationLockBanner("science"); + if (sciLock) proPayloadCard.prepend(sciLock); + applyStationControlLock(proPayloadCard, "science"); + bodyEl.appendChild(proPayloadCard); renderSpacecraftBusSection(ctx); return; } @@ -343,63 +352,65 @@ export function renderPayloadTab(ctx: BuilderContext): void { ctx.refreshEngineering(false, false); }, }); - bodyEl.appendChild( + const fairingPayloadCard = h( + "div", + { class: "stage-card active" }, + h("h3", {}, "Fairing & NASA Spacecraft Integration"), h( "div", - { class: "stage-card active" }, - h("h3", {}, "Fairing & NASA Spacecraft Integration"), + { class: "slot-group" }, h( - "div", - { class: "slot-group" }, - h( - "label", - { class: "field" }, - term("Payload Fairing Shroud", "fairing"), - fairingSel, - ), + "label", + { class: "field" }, + term("Payload Fairing Shroud", "fairing"), + fairingSel, ), + ), + h( + "div", + { class: "slot-group" }, h( - "div", - { class: "slot-group" }, - h( - "label", - { class: "field" }, - "NASA 3D Spacecraft / Capsule", - payloadSel, - ), + "label", + { class: "field" }, + "NASA 3D Spacecraft / Capsule", + payloadSel, ), + ), + h( + "div", + { class: "slot-group" }, h( - "div", - { class: "slot-group" }, - h( - "label", - { class: "field" }, - "Payload Bus Mass (kg)", - contractMassInput, - ), - contract - ? h( - "div", - { class: "mono dim", style: { fontSize: "10px" } }, - `Contract payload requirement: ${fmtNum(contract.payloadMass)} kg`, - ) - : null, + "label", + { class: "field" }, + "Payload Bus Mass (kg)", + contractMassInput, ), + contract + ? h( + "div", + { class: "mono dim", style: { fontSize: "10px" } }, + `Contract payload requirement: ${fmtNum(contract.payloadMass)} kg`, + ) + : null, + ), + h( + "div", + { class: "slot-group" }, h( - "div", - { class: "slot-group" }, - h( - "label", - { class: "row", style: { cursor: "pointer", fontSize: "12px" } }, - lasChk, - term( - "Mount Launch Abort Escape Tower (+1,400 kg, mandatory for crewed missions)", - "las", - ), + "label", + { class: "row", style: { cursor: "pointer", fontSize: "12px" } }, + lasChk, + term( + "Mount Launch Abort Escape Tower (+1,400 kg, mandatory for crewed missions)", + "las", ), ), ), ); + const sciStdLock = renderStationLockBanner("science"); + if (sciStdLock) fairingPayloadCard.prepend(sciStdLock); + applyStationControlLock(fairingPayloadCard, "science"); + bodyEl.appendChild(fairingPayloadCard); renderSpacecraftBusSection(ctx); } @@ -540,194 +551,204 @@ export function renderSpacecraftBusSection(ctx: BuilderContext): void { ); }), ); - bodyEl.appendChild( + const pwrGroup = h( + "div", + { class: "slot-group" }, h( - "div", - { class: "stage-card active", style: { marginTop: "10px" } }, - h( - "div", - { class: "spread" }, - h( - "h3", - {}, - term("Spacecraft Bus, Ground Control & Science", "spacecraft_bus"), - ), - h( - "span", - { class: `badge ${sigOk && pwrMarginOk ? "ok" : "warn"}` }, - `Eff Grade ${bus.efficiencyGrade}`, - ), - ), - h( - "div", - { class: "slot-group" }, - h( - "label", - { class: "field" }, - term("Power Generation Subsystem", "power_margin"), - pwrSel, - ), - ), - h( - "div", - { class: "slot-group" }, - h( - "label", - { class: "field" }, - term("Onboard Comms Transponder", "comms_link"), - commSel, - ), - ), - h( - "div", - { class: "slot-group" }, - h( - "label", - { class: "field" }, - term("Ground Control Antenna Network", "ground_network"), - netSel, - ), - ), - h( - "div", - { class: "slot-group" }, - h( - "label", - { class: "field" }, - "Planned Mission Lifetime (Years)", - lifeInput, - ), - ), - h( - "div", - { class: "slot-title", style: { marginTop: "4px" } }, - `Power Budget Breakdown (Solar Flux ${Math.round(bus.solarFluxFactor * 100)}%)`, - ), - h( - "div", - { class: "bus-power-grid" }, - h( - "div", - { class: "bus-power-cell" }, - h("span", { class: "k" }, "EOL Supply"), - h("span", { class: "v accent" }, `${bus.endOfLifePowerWatts} W`), - ), - h( - "div", - { class: "bus-power-cell" }, - h("span", { class: "k" }, "Total Load"), - h("span", { class: "v" }, `${bus.requiredPowerWatts} W`), - ), - h( - "div", - { class: "bus-power-cell" }, - h("span", { class: "k" }, "Avionics & ADCS"), - h("span", { class: "v" }, `${bus.avionicsPowerWatts} W`), - ), - h( - "div", - { class: "bus-power-cell" }, - h("span", { class: "k" }, "Comms RF/Laser"), - h("span", { class: "v" }, `${bus.commsPowerWatts} W`), - ), - h( - "div", - { class: "bus-power-cell" }, - h("span", { class: "k" }, "Science Suite"), - h("span", { class: "v" }, `${bus.instrumentsPowerWatts} W`), - ), - h( - "div", - { class: "bus-power-cell" }, - h("span", { class: "k" }, "Thermal + ECLSS"), - h( - "span", - { class: "v" }, - `${bus.thermalEclipsePowerWatts + bus.eclssPowerWatts} W`, - ), - ), - ), - h( - "div", - { class: "stat-row" }, - h( - "span", - { class: "k" }, - term( - `Power Margin (Req >= ${contract?.minPowerMarginPct ?? 10}%)`, - "power_margin", - ), - ), - h( - "span", - { - class: `v ${pwrMarginOk ? "green" : bus.powerMarginPct >= 0 ? "amber" : "red"}`, - }, - `${bus.powerMarginWatts >= 0 ? "+" : ""}${bus.powerMarginWatts} W (${bus.powerMarginPct >= 0 ? "+" : ""}${bus.powerMarginPct}%)`, - ), - ), - h( - "div", - { class: "slot-title", style: { marginTop: "4px" } }, - term("Ground Control Telemetry & Link Health", "comms_link"), - ), - h( - "div", - { class: "stat-row" }, - h( - "span", - { class: "k" }, - `Link Health (Req >= ${contract?.minSignalHealthPct ?? 60}%)`, - ), - h( - "span", - { class: `v ${sigOk ? "green" : "red"}` }, - `${bus.signalHealthPct}% (${bus.linkStatus})`, - ), - ), - h( - "div", - { class: "stat-row" }, - h("span", { class: "k" }, "RF/Optical Link Margin"), - h( - "span", - { - class: `v ${bus.linkMarginDb >= 3 ? "green" : bus.linkMarginDb >= 0 ? "amber" : "red"}`, - }, - `${bus.linkMarginDb >= 0 ? "+" : ""}${bus.linkMarginDb.toFixed(1)} dB`, - ), - ), - h( - "div", - { class: "stat-row" }, - h("span", { class: "k" }, "Ground Station Coverage"), - h("span", { class: "v" }, `${bus.groundStationCoveragePct}%`), - ), - h( - "div", - { class: "stat-row" }, - h("span", { class: "k" }, "Downlink vs Data Load"), - h( - "span", - { class: `v ${dataOk ? "green" : "red"}` }, - `${bus.downlinkCapacityMbps.toFixed(1)} / ${bus.requiredDataRateMbps.toFixed(1)} Mbps`, - ), - ), - h( - "div", - { class: "spread", style: { marginTop: "6px" } }, - h( - "div", - { class: "slot-title" }, - `Science Instruments (${sc.instrumentIds.length}/4)`, - ), - h( - "span", - { class: "mono dim", style: { fontSize: "10px" } }, - `Req Min: ${contract?.requiredInstrumentsMin ?? 0}`, - ), - ), - instList, + "label", + { class: "field" }, + term("Power Generation Subsystem", "power_margin"), + pwrSel, ), ); + const commGroup = h( + "div", + { class: "slot-group" }, + h( + "label", + { class: "field" }, + term("Onboard Comms Transponder", "comms_link"), + commSel, + ), + ); + const netGroup = h( + "div", + { class: "slot-group" }, + h( + "label", + { class: "field" }, + term("Ground Control Antenna Network", "ground_network"), + netSel, + ), + ); + const lifeGroup = h( + "div", + { class: "slot-group" }, + h( + "label", + { class: "field" }, + "Planned Mission Lifetime (Years)", + lifeInput, + ), + ); + applyStationControlLock(pwrGroup, "science"); + applyStationControlLock(lifeGroup, "science"); + applyStationControlLock(instList, "science"); + applyStationControlLock(commGroup, "systems"); + applyStationControlLock(netGroup, "systems"); + const busCard = h( + "div", + { class: "stage-card active", style: { marginTop: "10px" } }, + renderStationLockBanner("science"), + renderStationLockBanner("systems"), + h( + "div", + { class: "spread" }, + h( + "h3", + {}, + term("Spacecraft Bus, Ground Control & Science", "spacecraft_bus"), + ), + h( + "span", + { class: `badge ${sigOk && pwrMarginOk ? "ok" : "warn"}` }, + `Eff Grade ${bus.efficiencyGrade}`, + ), + ), + pwrGroup, + commGroup, + netGroup, + lifeGroup, + h( + "div", + { class: "slot-title", style: { marginTop: "4px" } }, + `Power Budget Breakdown (Solar Flux ${Math.round(bus.solarFluxFactor * 100)}%)`, + ), + h( + "div", + { class: "bus-power-grid" }, + h( + "div", + { class: "bus-power-cell" }, + h("span", { class: "k" }, "EOL Supply"), + h("span", { class: "v accent" }, `${bus.endOfLifePowerWatts} W`), + ), + h( + "div", + { class: "bus-power-cell" }, + h("span", { class: "k" }, "Total Load"), + h("span", { class: "v" }, `${bus.requiredPowerWatts} W`), + ), + h( + "div", + { class: "bus-power-cell" }, + h("span", { class: "k" }, "Avionics & ADCS"), + h("span", { class: "v" }, `${bus.avionicsPowerWatts} W`), + ), + h( + "div", + { class: "bus-power-cell" }, + h("span", { class: "k" }, "Comms RF/Laser"), + h("span", { class: "v" }, `${bus.commsPowerWatts} W`), + ), + h( + "div", + { class: "bus-power-cell" }, + h("span", { class: "k" }, "Science Suite"), + h("span", { class: "v" }, `${bus.instrumentsPowerWatts} W`), + ), + h( + "div", + { class: "bus-power-cell" }, + h("span", { class: "k" }, "Thermal + ECLSS"), + h( + "span", + { class: "v" }, + `${bus.thermalEclipsePowerWatts + bus.eclssPowerWatts} W`, + ), + ), + ), + h( + "div", + { class: "stat-row" }, + h( + "span", + { class: "k" }, + term( + `Power Margin (Req >= ${contract?.minPowerMarginPct ?? 10}%)`, + "power_margin", + ), + ), + h( + "span", + { + class: `v ${pwrMarginOk ? "green" : bus.powerMarginPct >= 0 ? "amber" : "red"}`, + }, + `${bus.powerMarginWatts >= 0 ? "+" : ""}${bus.powerMarginWatts} W (${bus.powerMarginPct >= 0 ? "+" : ""}${bus.powerMarginPct}%)`, + ), + ), + h( + "div", + { class: "slot-title", style: { marginTop: "4px" } }, + term("Ground Control Telemetry & Link Health", "comms_link"), + ), + h( + "div", + { class: "stat-row" }, + h( + "span", + { class: "k" }, + `Link Health (Req >= ${contract?.minSignalHealthPct ?? 60}%)`, + ), + h( + "span", + { class: `v ${sigOk ? "green" : "red"}` }, + `${bus.signalHealthPct}% (${bus.linkStatus})`, + ), + ), + h( + "div", + { class: "stat-row" }, + h("span", { class: "k" }, "RF/Optical Link Margin"), + h( + "span", + { + class: `v ${bus.linkMarginDb >= 3 ? "green" : bus.linkMarginDb >= 0 ? "amber" : "red"}`, + }, + `${bus.linkMarginDb >= 0 ? "+" : ""}${bus.linkMarginDb.toFixed(1)} dB`, + ), + ), + h( + "div", + { class: "stat-row" }, + h("span", { class: "k" }, "Ground Station Coverage"), + h("span", { class: "v" }, `${bus.groundStationCoveragePct}%`), + ), + h( + "div", + { class: "stat-row" }, + h("span", { class: "k" }, "Downlink vs Data Load"), + h( + "span", + { class: `v ${dataOk ? "green" : "red"}` }, + `${bus.downlinkCapacityMbps.toFixed(1)} / ${bus.requiredDataRateMbps.toFixed(1)} Mbps`, + ), + ), + h( + "div", + { class: "spread", style: { marginTop: "6px" } }, + h( + "div", + { class: "slot-title" }, + `Science Instruments (${sc.instrumentIds.length}/4)`, + ), + h( + "span", + { class: "mono dim", style: { fontSize: "10px" } }, + `Req Min: ${contract?.requiredInstrumentsMin ?? 0}`, + ), + ), + instList, + ); + bodyEl.appendChild(busCard); } diff --git a/src/client/screens/builder/stagesTab.ts b/src/client/screens/builder/stagesTab.ts index eff3ba1..920a7e7 100644 --- a/src/client/screens/builder/stagesTab.ts +++ b/src/client/screens/builder/stagesTab.ts @@ -22,7 +22,7 @@ export function renderStagesTab(ctx: BuilderContext): void { const diags = ctx.latestValidation?.stageDiagnostics ?? []; const stageTabs = h( "div", - { class: "row", style: { flexWrap: "wrap", gap: "4px" } }, + { class: "row coop-bar-exempt", style: { flexWrap: "wrap", gap: "4px" } }, ...ctx.design.stages.map((_st, idx) => { const sErrs = diags.filter( (d) => d.stageIndex === idx && d.severity === "error", diff --git a/src/client/screens/builder/valueAndComplianceTabs.ts b/src/client/screens/builder/valueAndComplianceTabs.ts index a503b9c..3d4cc6e 100644 --- a/src/client/screens/builder/valueAndComplianceTabs.ts +++ b/src/client/screens/builder/valueAndComplianceTabs.ts @@ -5,12 +5,12 @@ import { navigate } from "../../router.js"; import { refreshMe } from "../../session.js"; import { state } from "../../state.js"; import { simulateAscent } from "../../../shared/ascent_sim.js"; -import type { - MaturityLevel, - RocketDesign, - SimResult, -} from "../../../shared/types.js"; +import type { MaturityLevel, SimResult } from "../../../shared/types.js"; import { clear, fmtMoney, fmtNum, h, modal, term, toast } from "../../ui.js"; +import { + applyStationControlLock, + renderStationLockBanner, +} from "../../ui/coopBar.js"; import { curAgency, MATURITY_ORDER, type BuilderContext } from "./context.js"; export function renderContractValueTab(ctx: BuilderContext): void { @@ -420,11 +420,7 @@ export function renderComplianceTab(ctx: BuilderContext): void { disabled: !canAdvance, onClick: async () => { try { - const saved = await api.post<{ design: RocketDesign }>( - "/api/agency/rocket", - { design: ctx.design }, - ); - ctx.design = saved.design; + await ctx.syncOwnedSectionsNow(); const res = await api.post<{ maturity: MaturityLevel }>( "/api/agency/maturity", { @@ -451,7 +447,12 @@ export function renderComplianceTab(ctx: BuilderContext): void { "Vehicle certified FLIGHT-READY for pad integration.", ), ); + const sysBanner = renderStationLockBanner("systems"); + if (sysBanner) maturityPanel.prepend(sysBanner); + applyStationControlLock(maturityPanel, "systems"); bodyEl.appendChild(maturityPanel); + const dirBanner = renderStationLockBanner("director"); + if (dirBanner) bodyEl.appendChild(dirBanner); const sortedRules = [...comp.rules].sort((a, b) => { const rank = (r: typeof a) => !r.passed && !r.waived ? 0 : !r.passed && r.waived ? 1 : 2; @@ -459,24 +460,7 @@ export function renderComplianceTab(ctx: BuilderContext): void { }); for (const r of sortedRules) { const cls = r.passed ? "pass" : r.waived ? "waived" : "fail"; - const item = h( - "div", - { class: `rule-item ${cls}` }, - h( - "div", - { class: "spread" }, - h( - "span", - { class: "mono", style: { fontWeight: "700" } }, - `${r.code} • ${r.title}`, - ), - h( - "span", - { class: `badge ${r.passed ? "ok" : r.waived ? "warn" : "err"}` }, - r.passed ? "PASS" : r.waived ? "WAIVED" : r.severity.toUpperCase(), - ), - ), - h("div", { class: "dim", style: { fontSize: "11px" } }, r.detail), + const waiverRow = !r.passed && r.severity === "waiverable" ? h( "div", @@ -505,7 +489,27 @@ export function renderComplianceTab(ctx: BuilderContext): void { waivedSet.has(r.id) ? "Revoke Waiver" : "Grant Waiver", ), ) - : null, + : null; + if (waiverRow) applyStationControlLock(waiverRow, "director"); + const item = h( + "div", + { class: `rule-item ${cls}` }, + h( + "div", + { class: "spread" }, + h( + "span", + { class: "mono", style: { fontWeight: "700" } }, + `${r.code} • ${r.title}`, + ), + h( + "span", + { class: `badge ${r.passed ? "ok" : r.waived ? "warn" : "err"}` }, + r.passed ? "PASS" : r.waived ? "WAIVED" : r.severity.toUpperCase(), + ), + ), + h("div", { class: "dim", style: { fontSize: "11px" } }, r.detail), + waiverRow, ); bodyEl.appendChild(item); } @@ -521,14 +525,10 @@ export function renderFooter(ctx: BuilderContext): void { class: "btn sm ghost", onClick: async () => { try { - const saved = await api.post<{ design: RocketDesign }>( - "/api/agency/rocket", - { design: ctx.design }, - ); - ctx.design = saved.design; + await ctx.syncOwnedSectionsNow(); await refreshMe(); ctx.renderAll(); - toast("Design saved to hangar.", "ok"); + toast("Your station edits synced to hangar.", "ok"); } catch (err) { toast((err as Error).message, "err"); } @@ -542,7 +542,7 @@ export function renderFooter(ctx: BuilderContext): void { class: "btn sm", onClick: async () => { try { - await api.post("/api/agency/rocket", { design: ctx.design }); + await ctx.syncOwnedSectionsNow(); const sim = await api.post("/api/simulate", { design: ctx.design, previewOnly: false, @@ -639,11 +639,7 @@ export function renderFooter(ctx: BuilderContext): void { class: "btn sm primary grow", onClick: async () => { try { - const saved = await api.post<{ design: RocketDesign }>( - "/api/agency/rocket", - { design: ctx.design }, - ); - ctx.design = saved.design; + await ctx.syncOwnedSectionsNow(); await refreshMe(); navigate("config"); } catch (err) { diff --git a/src/client/screens/builder/viewportAndDrag.ts b/src/client/screens/builder/viewportAndDrag.ts index 92efa10..f1d02b2 100644 --- a/src/client/screens/builder/viewportAndDrag.ts +++ b/src/client/screens/builder/viewportAndDrag.ts @@ -3,7 +3,8 @@ import * as THREE from "three"; import { buildRocketMesh, disposeRocketMesh } from "../../three/rocketMesh.js"; import { buildRocket } from "../../../shared/physics.js"; import type { GlossaryKey } from "../../glossary.js"; -import { clear, fmtMoney, fmtNum, h, term } from "../../ui.js"; +import { clear, fmtMoney, fmtNum, h, term, toast } from "../../ui.js"; +import { getStationLockInfo } from "../../ui/coopBar.js"; import type { BuilderContext } from "./context.js"; export async function rebuild3D( @@ -198,6 +199,15 @@ export function attachProDragHandlers(ctx: BuilderContext): () => void { const part = ctx.design.proParts.find((p) => p.uid === uid); if (!part) return; ctx.selectedProUid = uid; + const lockInfo = getStationLockInfo("propulsion"); + if (lockInfo.lockedByOther) { + if (ctx.activeTab === "stages") ctx.renderSidebarBody(); + toast( + `Propulsion & Stages locked by ${lockInfo.ownerCallsign || "teammate"}.`, + "warn", + ); + return; + } ctx.dragPlane.visible = true; ctx.dragPlane.position.copy(hits[0].point); ctx.dragPlane.lookAt(ctx.view.camera.position); diff --git a/src/client/screens/contracts.ts b/src/client/screens/contracts.ts index 2fae080..874a062 100644 --- a/src/client/screens/contracts.ts +++ b/src/client/screens/contracts.ts @@ -4,6 +4,7 @@ import { navigate } from "../router.js"; import { state } from "../state.js"; import type { ContractOffer } from "../../shared/types.js"; import { h, toast } from "../ui.js"; +import { renderCoopMissionBar } from "../ui/coopBar.js"; import { openCustomMissionModal, type LeaderboardRow, @@ -23,6 +24,7 @@ export function renderContracts(root: HTMLElement): () => void { } const offersCol = h("div", { class: "col" }); const boardCol = h("div", { class: "col" }); + const coopHost = h("div", { class: "contracts-coop-bar" }); const marketState: { rightTab: "leaderboard" | "market" } = { rightTab: "leaderboard", }; @@ -31,6 +33,13 @@ export function renderContracts(root: HTMLElement): () => void { offerFilter: "all", contractorFilter: "all", }; + const rerenderCoopAndOffers = () => { + renderCoopMissionBar(coopHost, { + onStationChanged: () => + renderOffersPanel(offersCol, offersState, openCustomMissionModal), + }); + renderOffersPanel(offersCol, offersState, openCustomMissionModal); + }; async function refreshAll(): Promise { try { const [offers, leaderboard, prices] = await Promise.all([ @@ -40,7 +49,7 @@ export function renderContracts(root: HTMLElement): () => void { ]); state.contracts = offers; offersState.offers = offers; - renderOffersPanel(offersCol, offersState, openCustomMissionModal); + rerenderCoopAndOffers(); renderMarketPanel(boardCol, leaderboard, prices, marketState); } catch (err) { toast((err as Error).message, "err"); @@ -65,15 +74,27 @@ export function renderContracts(root: HTMLElement): () => void { "Refresh Feed", ), ); + renderCoopMissionBar(coopHost, { + onStationChanged: () => + renderOffersPanel(offersCol, offersState, openCustomMissionModal), + }); root.appendChild( h( "div", { class: "screen list-page" }, header, + coopHost, h("div", { class: "cols" }, offersCol, boardCol), ), ); + const handleSync = () => rerenderCoopAndOffers(); + window.addEventListener("sgywftp:agency-sync", handleSync); + window.addEventListener("sgywftp:coop-presence", handleSync); void refreshAll(); const timer = window.setInterval(() => void refreshAll(), 8000); - return () => window.clearInterval(timer); + return () => { + window.clearInterval(timer); + window.removeEventListener("sgywftp:agency-sync", handleSync); + window.removeEventListener("sgywftp:coop-presence", handleSync); + }; } diff --git a/src/client/screens/contracts/offersPanel.ts b/src/client/screens/contracts/offersPanel.ts index cb6381d..c8aa3c2 100644 --- a/src/client/screens/contracts/offersPanel.ts +++ b/src/client/screens/contracts/offersPanel.ts @@ -13,6 +13,10 @@ import { term, toast, } from "../../ui.js"; +import { + getStationLockInfo, + renderStationLockBanner, +} from "../../ui/coopBar.js"; export interface OffersPanelState { offers: ContractOffer[]; @@ -30,8 +34,17 @@ export function renderOffersPanel( clear(offersCol); const active = currentContract(); const hasInFlight = (agency!.activeMissions ?? []).some((m) => !m.settled); + const directorLocked = getStationLockInfo("director").lockedByOther; const canSignNew = - !active && !hasInFlight && !agency!.bankrupt && !agency!.terminatedReason; + !active && + !hasInFlight && + !agency!.bankrupt && + !agency!.terminatedReason && + !directorLocked; + if (directorLocked) { + const lockBanner = renderStationLockBanner("director"); + if (lockBanner) offersCol.appendChild(lockBanner); + } offersCol.appendChild( h( "div", diff --git a/src/client/screens/dashboard.ts b/src/client/screens/dashboard.ts index aa3de80..7e16cf8 100644 --- a/src/client/screens/dashboard.ts +++ b/src/client/screens/dashboard.ts @@ -13,7 +13,8 @@ import { isPartUnlocked, validateDesign, } from "../../shared/physics.js"; -import { h, openThemeSettingsModal } from "../ui.js"; +import { h, clear, openThemeSettingsModal } from "../ui.js"; +import { renderCoopMissionBar } from "../ui/coopBar.js"; import { createFlightsPanel, createHazardPanel, @@ -195,181 +196,228 @@ export function renderDashboard(root: HTMLElement): () => void { ), ), ); - viewportEl.appendChild(headerBar); - const padStatusCard = h( + const coopBarHost = h("div", { class: "dash-coop-bar" }); + const padOverlayBottom = h("div", { class: "dash-overlay-bottom" }); + const hudTop = h( "div", - { class: "panel", style: { padding: "10px 14px" } }, - hasRocket + { class: "viewport-hud-top" }, + headerBar, + coopBarHost, + ); + const hudOverlay = h( + "div", + { class: "viewport-hud" }, + hudTop, + padOverlayBottom, + ); + viewportEl.appendChild(hudOverlay); + + const renderPadOverlay = () => { + const liveAgency = state.agency; + if (!liveAgency) return; + const liveHasRocket = !!liveAgency.rocketDesign?.stages?.length; + clear(padOverlayBottom); + padOverlayBottom.appendChild( + h( + "div", + { class: "panel", style: { padding: "10px 14px" } }, + liveHasRocket + ? h( + "div", + { class: "mono", style: { fontSize: "11px" } }, + `Pad Vehicle: ${liveAgency.rocketDesign!.name} (${liveAgency.rocketDesign!.stages.length} stage${liveAgency.rocketDesign!.stages.length > 1 ? "s" : ""}) • Maturity: `, + h( + "span", + { class: "accent" }, + liveAgency.rocketDesign!.maturity.toUpperCase(), + ), + ) + : h( + "div", + { class: "mono dim", style: { fontSize: "11px" } }, + "Pad Status: Empty Launch Mount — Pad Mascot Holding Pad (cat_3d_model_free.glb). Open Rocket Builder to design a vehicle.", + ), + ), + ); + }; + + let refreshFlightsRef: (() => void) | null = null; + const renderDashboardSidebar = () => { + const liveAgency = state.agency; + if (!liveAgency) return; + const liveContract = currentContract(); + const liveHasRocket = !!liveAgency.rocketDesign?.stages?.length; + const liveWeather = state.world?.weather ?? weather; + const profile = getDifficultyProfile(liveAgency.difficulty); + const nowSim = state.world?.simTime ?? 0; + const bailoutsUsed = liveAgency.bailoutsTaken ?? 0; + const bailoutsRem = Math.max(0, profile.maxBailouts - bailoutsUsed); + const unlockedSet = new Set(liveAgency.unlockedTechs ?? ["starter"]); + const padDamagedRem = Math.max( + 0, + Math.ceil((liveAgency.padDamagedUntilSimTime ?? 0) - nowSim), + ); + const groundedRem = Math.max( + 0, + Math.ceil((liveAgency.groundedUntilSimTime ?? 0) - nowSim), + ); + let validationSummary: ReturnType | null = null; + let hasLockedDesignParts = false; + if (liveHasRocket && liveAgency.rocketDesign) { + try { + validationSummary = validateDesign( + liveAgency.rocketDesign, + state.parts, + state.materials, + { + mission: liveContract, + simTime: state.world?.simTime ?? 0, + weather: liveWeather, + activeHazards: state.world?.activeHazards ?? [], + unlockedTechs: liveAgency.unlockedTechs ?? [], + difficulty: liveAgency.difficulty, + crewedSeats: liveAgency.crewConfig?.crewSize ?? 0, + eclssLevel: liveAgency.crewConfig?.lifeSupport ?? 0, + }, + ); + hasLockedDesignParts = + liveAgency.rocketDesign.stages.some( + (st) => + !isPartUnlocked(st.engineId, liveAgency) || + !isPartUnlocked(st.tankId, liveAgency) || + !isPartUnlocked(st.structureId, liveAgency) || + !isPartUnlocked(st.materialId, liveAgency) || + (!!st.interstageId && + !isPartUnlocked(st.interstageId, liveAgency)) || + (!!st.dropTankId && + (st.dropTankCount ?? 0) > 0 && + !isPartUnlocked(st.dropTankId, liveAgency)), + ) || + !isPartUnlocked(liveAgency.rocketDesign.fairingId, liveAgency) || + (!!liveAgency.rocketDesign.computerId && + !isPartUnlocked(liveAgency.rocketDesign.computerId, liveAgency)) || + (liveAgency.rocketDesign.proParts ?? []).some( + (pp) => + !isPartUnlocked(pp.partId, liveAgency) || + (!!pp.materialId && !isPartUnlocked(pp.materialId, liveAgency)), + ); + } catch { + validationSummary = null; + } + } + const flights = createFlightsPanel(); + refreshFlightsRef = flights.renderFlights; + const deps: DashboardSidebarDeps = { + agency: liveAgency, + contract: liveContract, + weather: liveWeather, + profile, + unlockedSet, + bailoutsRem, + padDamagedRem, + groundedRem, + validationSummary, + hasLockedDesignParts, + onOpenTechLab: () => openTechLabModal(unlockedSet), + }; + const { terminatedBanner, standdownBanner, bailoutBanner } = + createAlertBanners(deps); + const { agencyStatsPanel, contractPanel } = + createTelemetryAndContractCards(deps); + const hazardPanel = createHazardPanel(); + const lastSettlementCard = createLastSettlementCard(liveAgency); + const navGrid = createNavGrid(deps); + const tutorialOfferBanner = shouldShowFirstRunTutorialOffer(liveAgency) ? h( "div", - { class: "mono", style: { fontSize: "11px" } }, - `Pad Vehicle: ${agency.rocketDesign!.name} (${agency.rocketDesign!.stages.length} stage${agency.rocketDesign!.stages.length > 1 ? "s" : ""}) • Maturity: `, + { + class: "panel", + style: { padding: "12px", borderColor: "var(--sim-accent)" }, + }, h( - "span", - { class: "accent" }, - agency.rocketDesign!.maturity.toUpperCase(), + "div", + { class: "col", style: { gap: "8px" } }, + h( + "div", + { class: "spread" }, + h("h3", { class: "accent" }, "New Flight Director?"), + h("span", { class: "badge info" }, "TUTORIAL"), + ), + h( + "p", + { class: "dim", style: { fontSize: "11px", lineHeight: "1.45" } }, + "Open the Flight Wiki for interactive Δv, CG/CP & Gravity Turn labs, or launch the step-by-step Walkthrough.", + ), + h( + "div", + { class: "row", style: { gap: "6px" } }, + h( + "button", + { + class: "btn xs primary", + onClick: () => { + tutorialOfferBanner?.remove(); + startWalkthrough(0); + }, + }, + "Start Walkthrough", + ), + h( + "button", + { + class: "btn xs", + onClick: () => navigate("wiki", { returnTo: "dashboard" }), + }, + "Open Wiki", + ), + h( + "button", + { + class: "btn xs ghost", + onClick: () => { + dismissFirstRunTutorialOffer(); + tutorialOfferBanner?.remove(); + }, + }, + "Dismiss", + ), + ), ), ) - : h( - "div", - { class: "mono dim", style: { fontSize: "11px" } }, - "Pad Status: Empty Launch Mount — Pad Mascot Holding Pad (cat_3d_model_free.glb). Open Rocket Builder to design a vehicle.", - ), - ); - viewportEl.appendChild( - h("div", { class: "dash-overlay-bottom" }, padStatusCard), - ); - const profile = getDifficultyProfile(agency.difficulty); - const nowSim = state.world?.simTime ?? 0; - const bailoutsUsed = agency.bailoutsTaken ?? 0; - const bailoutsRem = Math.max(0, profile.maxBailouts - bailoutsUsed); - const unlockedSet = new Set(agency.unlockedTechs ?? ["starter"]); - const padDamagedRem = Math.max( - 0, - Math.ceil((agency.padDamagedUntilSimTime ?? 0) - nowSim), - ); - const groundedRem = Math.max( - 0, - Math.ceil((agency.groundedUntilSimTime ?? 0) - nowSim), - ); - let validationSummary: ReturnType | null = null; - let hasLockedDesignParts = false; - if (hasRocket && agency.rocketDesign) { - try { - validationSummary = validateDesign( - agency.rocketDesign, - state.parts, - state.materials, - { - mission: contract, - simTime: state.world?.simTime ?? 0, - weather, - activeHazards: state.world?.activeHazards ?? [], - unlockedTechs: agency.unlockedTechs ?? [], - difficulty: agency.difficulty, - crewedSeats: agency.crewConfig?.crewSize ?? 0, - eclssLevel: agency.crewConfig?.lifeSupport ?? 0, - }, - ); - hasLockedDesignParts = - agency.rocketDesign.stages.some( - (st) => - !isPartUnlocked(st.engineId, agency) || - !isPartUnlocked(st.tankId, agency) || - !isPartUnlocked(st.structureId, agency) || - !isPartUnlocked(st.materialId, agency) || - (!!st.interstageId && !isPartUnlocked(st.interstageId, agency)) || - (!!st.dropTankId && - (st.dropTankCount ?? 0) > 0 && - !isPartUnlocked(st.dropTankId, agency)), - ) || - !isPartUnlocked(agency.rocketDesign.fairingId, agency) || - (!!agency.rocketDesign.computerId && - !isPartUnlocked(agency.rocketDesign.computerId, agency)) || - (agency.rocketDesign.proParts ?? []).some( - (pp) => - !isPartUnlocked(pp.partId, agency) || - (!!pp.materialId && !isPartUnlocked(pp.materialId, agency)), - ); - } catch { - validationSummary = null; - } - } - const flights = createFlightsPanel(); - const deps: DashboardSidebarDeps = { - agency, - contract, - weather, - profile, - unlockedSet, - bailoutsRem, - padDamagedRem, - groundedRem, - validationSummary, - hasLockedDesignParts, - onOpenTechLab: () => openTechLabModal(unlockedSet), + : null; + clear(sidebarEl); + if (terminatedBanner) sidebarEl.appendChild(terminatedBanner); + if (standdownBanner) sidebarEl.appendChild(standdownBanner); + if (bailoutBanner) sidebarEl.appendChild(bailoutBanner); + if (tutorialOfferBanner) sidebarEl.appendChild(tutorialOfferBanner); + sidebarEl.append(agencyStatsPanel, contractPanel); + if (hazardPanel) sidebarEl.appendChild(hazardPanel); + if (lastSettlementCard) sidebarEl.appendChild(lastSettlementCard); + sidebarEl.append(flights.panel, navGrid); }; - const { terminatedBanner, standdownBanner, bailoutBanner } = - createAlertBanners(deps); - const { agencyStatsPanel, contractPanel } = - createTelemetryAndContractCards(deps); - const hazardPanel = createHazardPanel(); - const lastSettlementCard = createLastSettlementCard(agency); - const navGrid = createNavGrid(deps); - const tutorialOfferBanner = shouldShowFirstRunTutorialOffer(agency) - ? h( - "div", - { - class: "panel", - style: { padding: "12px", borderColor: "var(--sim-accent)" }, - }, - h( - "div", - { class: "col", style: { gap: "8px" } }, - h( - "div", - { class: "spread" }, - h("h3", { class: "accent" }, "New Flight Director?"), - h("span", { class: "badge info" }, "TUTORIAL"), - ), - h( - "p", - { class: "dim", style: { fontSize: "11px", lineHeight: "1.45" } }, - "Open the Flight Wiki for interactive Δv, CG/CP & Gravity Turn labs, or launch the step-by-step Walkthrough.", - ), - h( - "div", - { class: "row", style: { gap: "6px" } }, - h( - "button", - { - class: "btn xs primary", - onClick: () => { - tutorialOfferBanner?.remove(); - startWalkthrough(0); - }, - }, - "Start Walkthrough", - ), - h( - "button", - { - class: "btn xs", - onClick: () => navigate("wiki", { returnTo: "dashboard" }), - }, - "Open Wiki", - ), - h( - "button", - { - class: "btn xs ghost", - onClick: () => { - dismissFirstRunTutorialOffer(); - tutorialOfferBanner?.remove(); - }, - }, - "Dismiss", - ), - ), - ), - ) - : null; - if (terminatedBanner) sidebarEl.appendChild(terminatedBanner); - if (standdownBanner) sidebarEl.appendChild(standdownBanner); - if (bailoutBanner) sidebarEl.appendChild(bailoutBanner); - if (tutorialOfferBanner) sidebarEl.appendChild(tutorialOfferBanner); - sidebarEl.append(agencyStatsPanel, contractPanel); - if (hazardPanel) sidebarEl.appendChild(hazardPanel); - if (lastSettlementCard) sidebarEl.appendChild(lastSettlementCard); - sidebarEl.append(flights.panel, navGrid); + + const refreshCoopAndDashboard = () => { + renderCoopMissionBar(coopBarHost, { + onStationChanged: renderDashboardSidebar, + }); + renderPadOverlay(); + renderDashboardSidebar(); + }; + refreshCoopAndDashboard(); + root.appendChild( h("div", { class: "screen dash-root" }, viewportEl, sidebarEl), ); + const handleSync = () => refreshCoopAndDashboard(); + window.addEventListener("sgywftp:agency-sync", handleSync); + window.addEventListener("sgywftp:coop-presence", handleSync); const poll = window.setInterval(async () => { await refreshWorld(); - flights.renderFlights(); + refreshFlightsRef?.(); }, 5000); - void refreshMe(); + void refreshMe().then(() => { + if (!disposed) refreshCoopAndDashboard(); + }); return () => { disposed = true; window.clearInterval(poll); @@ -377,6 +425,8 @@ export function renderDashboard(root: HTMLElement): () => void { "sgywftp:theme-changed", syncDashboardAtmosphere, ); + window.removeEventListener("sgywftp:agency-sync", handleSync); + window.removeEventListener("sgywftp:coop-presence", handleSync); view.dispose(); }; } diff --git a/src/client/screens/dashboard/sidebarCards.ts b/src/client/screens/dashboard/sidebarCards.ts index e65aabd..bd53cd8 100644 --- a/src/client/screens/dashboard/sidebarCards.ts +++ b/src/client/screens/dashboard/sidebarCards.ts @@ -13,6 +13,11 @@ import type { MissionTemplate, } from "../../../shared/types.js"; import { fmtMoney, fmtNum, h, modal, term, toast } from "../../ui.js"; +import { + commitAgencyLaunch, + getStationLockInfo, + renderStationLockBanner, +} from "../../ui/coopBar.js"; export interface DashboardSidebarDeps { agency: AgencyState; @@ -34,6 +39,7 @@ export function createAlertBanners(deps: DashboardSidebarDeps): { bailoutBanner: HTMLElement | null; } { const { agency, profile, bailoutsRem, padDamagedRem, groundedRem } = deps; + const directorLocked = getStationLockInfo("director").lockedByOther; const terminatedBanner = agency.terminatedReason ? h( "div", @@ -45,6 +51,7 @@ export function createAlertBanners(deps: DashboardSidebarDeps): { "div", { class: "col", style: { gap: "8px" } }, h("h3", { class: "red" }, "AGENCY LICENSE REVOKED"), + directorLocked ? renderStationLockBanner("director") : null, h( "p", { class: "dim", style: { fontSize: "11px", lineHeight: "1.45" } }, @@ -54,13 +61,18 @@ export function createAlertBanners(deps: DashboardSidebarDeps): { "button", { class: "btn sm danger", + disabled: directorLocked, onClick: async () => { - const res = await api.post<{ agency: AgencyState }>( - "/api/agency/reset", - {}, - ); - state.agency = res.agency; - navigate("onboarding"); + try { + const res = await api.post<{ agency: AgencyState }>( + "/api/agency/reset", + {}, + ); + state.agency = res.agency; + navigate("onboarding"); + } catch (err) { + toast((err as Error).message, "err"); + } }, }, "Reset Agency & Start New Program", @@ -80,6 +92,7 @@ export function createAlertBanners(deps: DashboardSidebarDeps): { "div", { class: "col", style: { gap: "8px" } }, h("h3", { class: "amber" }, "OPERATIONAL STAND-DOWN ACTIVE"), + directorLocked ? renderStationLockBanner("director") : null, groundedRem > 0 ? h( "p", @@ -98,6 +111,7 @@ export function createAlertBanners(deps: DashboardSidebarDeps): { "button", { class: "btn sm warn", + disabled: directorLocked, onClick: async () => { try { const res = await api.post<{ @@ -151,7 +165,7 @@ export function createAlertBanners(deps: DashboardSidebarDeps): { "button", { class: "btn sm warn grow", - disabled: bailoutsRem <= 0, + disabled: bailoutsRem <= 0 || directorLocked, onClick: async () => { try { const res = await api.post<{ @@ -177,6 +191,7 @@ export function createAlertBanners(deps: DashboardSidebarDeps): { "button", { class: "btn sm danger", + disabled: directorLocked, onClick: () => { modal( "Reset Agency Program?", @@ -191,12 +206,15 @@ export function createAlertBanners(deps: DashboardSidebarDeps): { label: "Confirm Reset", kind: "danger", onClick: async () => { - const res = await api.post<{ agency: AgencyState }>( - "/api/agency/reset", - {}, - ); - state.agency = res.agency; - navigate("onboarding"); + try { + const res = await api.post<{ + agency: AgencyState; + }>("/api/agency/reset", {}); + state.agency = res.agency; + navigate("onboarding"); + } catch (err) { + toast((err as Error).message, "err"); + } }, }, ], @@ -396,6 +414,7 @@ export function createNavGrid(deps: DashboardSidebarDeps): HTMLElement { const hasActiveOwnFlight = (agency.activeMissions ?? []).some( (m) => !m.settled, ); + const directorLock = getStationLockInfo("director"); const canLaunch = !agency.terminatedReason && !agency.bankrupt && @@ -411,11 +430,13 @@ export function createNavGrid(deps: DashboardSidebarDeps): HTMLElement { agency.treasury >= (validationSummary?.totalMissionCost ?? 0); const launchBtnLabel = hasActiveOwnFlight ? "Mission In Flight — Spectate" - : padDamagedRem > 0 || groundedRem > 0 - ? "Launch Stand-Down Active" - : canLaunch - ? `Launch Mission (${fmtMoney(validationSummary!.totalMissionCost)})` - : "Launch Mission (Needs Flight-Ready Vehicle)"; + : directorLock.lockedByOther + ? `Launch Locked (${directorLock.ownerCallsign ?? "FD"})` + : padDamagedRem > 0 || groundedRem > 0 + ? "Launch Stand-Down Active" + : canLaunch + ? `Launch Mission (${fmtMoney(validationSummary!.totalMissionCost)})` + : "Launch Mission (Needs Flight-Ready Vehicle)"; const navGrid = h( "div", { class: "dash-nav" }, @@ -443,6 +464,7 @@ export function createNavGrid(deps: DashboardSidebarDeps): HTMLElement { "button", { class: `btn full-span ${canLaunch || hasActiveOwnFlight ? "primary" : "warn"}`, + disabled: !hasActiveOwnFlight && directorLock.lockedByOther, onClick: () => { if (hasActiveOwnFlight) { const openFlight = (agency.activeMissions ?? []).find( @@ -451,6 +473,13 @@ export function createNavGrid(deps: DashboardSidebarDeps): HTMLElement { if (openFlight) navigate("launch", { spectateId: openFlight.id }); return; } + if (directorLock.lockedByOther) { + toast( + `Launch locked by Flight Director (${directorLock.ownerCallsign ?? "teammate"}).`, + "warn", + ); + return; + } if (agency.terminatedReason) { toast(agency.terminatedReason, "err"); return; @@ -504,7 +533,7 @@ export function createNavGrid(deps: DashboardSidebarDeps): HTMLElement { toast("Insufficient treasury funds for vehicle + waivers.", "err"); return; } - navigate("launch"); + void commitAgencyLaunch(); }, }, launchBtnLabel, diff --git a/src/client/screens/dashboard/techLabModal.ts b/src/client/screens/dashboard/techLabModal.ts index a092cfc..1f133be 100644 --- a/src/client/screens/dashboard/techLabModal.ts +++ b/src/client/screens/dashboard/techLabModal.ts @@ -5,13 +5,22 @@ import { state } from "../../state.js"; import { TECH_TREE } from "../../../shared/physics.js"; import type { AgencyState } from "../../../shared/types.js"; import { fmtMoney, h, modal, toast } from "../../ui.js"; +import { + getStationLockInfo, + renderStationLockBanner, +} from "../../ui/coopBar.js"; export function openTechLabModal(unlockedSet: Set): void { const agency = state.agency; + const directorLocked = getStationLockInfo("director").lockedByOther; const listEl = h("div", { class: "col", style: { gap: "8px", maxHeight: "60vh", overflowY: "auto" }, }); + if (directorLocked) { + const lockBanner = renderStationLockBanner("director"); + if (lockBanner) listEl.appendChild(lockBanner); + } for (const node of TECH_TREE) { const unlocked = unlockedSet.has(node.id); const repMet = (agency!.reputation ?? 0) >= node.minReputation; @@ -60,6 +69,7 @@ export function openTechLabModal(unlockedSet: Set): void { { class: "btn xs primary", disabled: + directorLocked || !repMet || agency!.treasury < node.cost || !!agency!.terminatedReason, diff --git a/src/client/screens/launchSequence.ts b/src/client/screens/launchSequence.ts index 4037657..60cf66c 100644 --- a/src/client/screens/launchSequence.ts +++ b/src/client/screens/launchSequence.ts @@ -1,6 +1,6 @@ // 3D launch ascent & orbit sequence screen import * as THREE from "three"; -import { api } from "../api.js"; +import { ApiError, api } from "../api.js"; import { navigate } from "../router.js"; import { refreshMe } from "../session.js"; import { @@ -24,6 +24,11 @@ import type { MissionSettlement, } from "../../shared/types.js"; import { clear, h, toast } from "../ui.js"; +import { + confirmLaunchWithUnreadyStations, + type ReadyGateStation, + renderCoopMissionBar, +} from "../ui/coopBar.js"; import { stepParticlesAndDebris, updateAscentVisuals, @@ -56,11 +61,26 @@ export function renderLaunchSequence( ); const titleLeft = h("div", { class: "launch-title-left" }); const controlsTop = h("div", { class: "launch-controls" }); + const coopStrip = h("div", { class: "launch-coop-strip" }); + const topBar = h( + "div", + { class: "launch-topbar" }, + titleLeft, + bannerEl, + controlsTop, + ); const hudStackEl = h("div", { class: "launch-hud-stack" }); const hudEl = h("div", { class: "launch-hud" }); const eventsEl = h("div", { class: "launch-events" }); hudStackEl.append(eventsEl, hudEl); - viewportEl.append(titleLeft, controlsTop, bannerEl, hudStackEl); + const overlayEl = h( + "div", + { class: "launch-overlay" }, + topBar, + coopStrip, + hudStackEl, + ); + viewportEl.append(overlayEl); root.appendChild(h("div", { class: "screen launch-root" }, viewportEl)); const view = createView(viewportEl, { fov: 46, far: 120000 }); view.addStars(3200, 30000); @@ -145,14 +165,47 @@ export function renderLaunchSequence( incDeg: ctx.designUsed.flightParams.targetInclinationDeg, }, ); + } else if (params.coopMission) { + const cm = params.coopMission; + ctx.activeMission = cm.mission; + ctx.settlement = cm.settlement ?? cm.mission.settlement; + ctx.simResult = cm.mission.ascent; + ctx.trajectory = cm.mission.trajectory; + ctx.designUsed = cm.mission.rocketDesign; } else { - const res = await api.post<{ - ok: boolean; - mission: ActiveMission; - settlement?: MissionSettlement; - remainingTreasury: number; - agency?: AgencyState; - }>("/api/mission/launch", {}); + const attemptDirectLaunch = (overrideReady = false) => + api.post<{ + ok: boolean; + mission: ActiveMission; + settlement?: MissionSettlement; + remainingTreasury: number; + agency?: AgencyState; + }>( + "/api/mission/launch", + overrideReady ? { overrideReady: true } : {}, + ); + let res; + try { + res = await attemptDirectLaunch(false); + } catch (err) { + if ( + err instanceof ApiError && + err.status === 409 && + err.code === "STATIONS_NOT_READY" + ) { + const unready = Array.isArray(err.data?.unreadyStations) + ? (err.data.unreadyStations as ReadyGateStation[]) + : []; + const override = await confirmLaunchWithUnreadyStations(unready); + if (!override) { + navigate("dashboard"); + return; + } + res = await attemptDirectLaunch(true); + } else { + throw err; + } + } if (ctx.disposed) return; ctx.activeMission = res.mission; ctx.settlement = res.settlement ?? res.mission.settlement; @@ -304,10 +357,22 @@ export function renderLaunchSequence( updateOrbitMarker(ctx); } } + const syncLaunchCoop = () => { + if (!state.agency || ctx.isSpectating) { + clear(coopStrip); + return; + } + renderCoopMissionBar(coopStrip); + }; + syncLaunchCoop(); + window.addEventListener("sgywftp:coop-presence", syncLaunchCoop); + window.addEventListener("sgywftp:agency-sync", syncLaunchCoop); void initLaunch(); raf = requestAnimationFrame(tick); return () => { ctx.disposed = true; + window.removeEventListener("sgywftp:coop-presence", syncLaunchCoop); + window.removeEventListener("sgywftp:agency-sync", syncLaunchCoop); cancelAnimationFrame(raf); disposeRocketMesh(ctx.rocketHandle); ctx.view.dispose(); diff --git a/src/client/screens/mainMenu.ts b/src/client/screens/mainMenu.ts index 8206db9..e85e302 100644 --- a/src/client/screens/mainMenu.ts +++ b/src/client/screens/mainMenu.ts @@ -3,13 +3,20 @@ import { api, + clearTabToken, getServerJoinOk, getSettings, saveSettings, setServerJoinOk, + setToken, } from "../api.js"; import { navigate } from "../router.js"; -import { refreshMe, refreshWorld, startEvents } from "../session.js"; +import { + refreshMe, + refreshWorld, + startEvents, + stopEvents, +} from "../session.js"; import { state } from "../state.js"; import { COLOR_SET_OPTIONS, @@ -323,9 +330,13 @@ export function renderMainMenu(root: HTMLElement): () => void { try { await api.post("/api/auth/logout", {}); } catch {} - localStorage.removeItem("spacegaem_proto_token"); + setToken(null); + clearTabToken(); + stopEvents(); state.agency = null; state.account = null; + state.operator = null; + state.coopPresence = null; navigate("auth"); }, }, diff --git a/src/client/screens/missionConfig.ts b/src/client/screens/missionConfig.ts index 55fa587..9e119ef 100644 --- a/src/client/screens/missionConfig.ts +++ b/src/client/screens/missionConfig.ts @@ -14,7 +14,14 @@ import { normalizeDesign, } from "../../shared/physics.js"; import type { CrewConfig, FlightParams } from "../../shared/types.js"; -import { h, term, toast } from "../ui.js"; +import { clear, h, term, toast } from "../ui.js"; +import { + applyStationControlLock, + commitAgencyLaunch, + getStationLockInfo, + renderCoopMissionBar, + renderStationLockBanner, +} from "../ui/coopBar.js"; import type { GlossaryKey } from "../glossary.js"; import { renderDiagPanel, @@ -46,6 +53,8 @@ export function renderMissionConfig(root: HTMLElement): () => void { crewSize: agency.crewConfig?.crewSize ?? (contract?.crewed ? 2 : 0), lifeSupport: agency.crewConfig?.lifeSupport ?? (contract?.crewed ? 2 : 1), }; + let propDirty = false; + let crewDirty = false; const sliderSyncers: Array<() => void> = []; function recomputePreview(): void { workingDesign.flightParams = { ...fp }; @@ -119,6 +128,7 @@ export function renderMissionConfig(root: HTMLElement): () => void { step, value: fp[key], onInput: () => { + propDirty = true; fp[key] = Number(input.value); valEl.textContent = `${fp[key]} ${unit}`; recomputePreview(); @@ -152,6 +162,7 @@ export function renderMissionConfig(root: HTMLElement): () => void { step: 1, value: crew.crewSize, onInput: () => { + crewDirty = true; crew.crewSize = Number(crewSizeInput.value); crewVal.textContent = `${crew.crewSize} crew (+${crew.crewSize * (85 + 15 * crew.lifeSupport) + (crew.crewSize > 0 ? 500 * crew.lifeSupport : 0)} kg)`; }, @@ -164,6 +175,7 @@ export function renderMissionConfig(root: HTMLElement): () => void { step: 1, value: crew.lifeSupport, onInput: () => { + crewDirty = true; crew.lifeSupport = Number(eclssInput.value); eclssVal.textContent = `Tier ${crew.lifeSupport}`; crewVal.textContent = `${crew.crewSize} crew (+${crew.crewSize * (85 + 15 * crew.lifeSupport) + (crew.crewSize > 0 ? 500 * crew.lifeSupport : 0)} kg)`; @@ -176,16 +188,33 @@ export function renderMissionConfig(root: HTMLElement): () => void { `Tier ${crew.lifeSupport}`, ); async function saveParameters() { - if (!agency?.rocketDesign) { + const liveAgency = state.agency; + if (!liveAgency?.rocketDesign) { toast("Save a rocket design in Rocket Builder first.", "warn"); navigate("builder"); return false; } - await api.post("/api/agency/flight-params", { flightParams: fp }); - await api.post("/api/agency/crew", { crew }); + const canProp = getStationLockInfo("propulsion").canOperate; + const canSci = getStationLockInfo("science").canOperate; + if (!canProp && !canSci) { + toast( + "Both Propulsion & Science stations are locked by teammates.", + "warn", + ); + return false; + } + if (canProp) { + await api.post("/api/agency/flight-params", { flightParams: fp }); + propDirty = false; + } + if (canSci) { + await api.post("/api/agency/crew", { crew }); + crewDirty = false; + } await refreshMe(); return true; } + const coopHost = h("div", { class: "param-coop-bar" }); const mainCol = h( "div", { class: "param-main" }, @@ -208,16 +237,15 @@ export function renderMissionConfig(root: HTMLElement): () => void { agency.rocketDesign?.name ?? "Reference Trajectory Preview", ), ), + coopHost, ctx.diagTabsEl, ctx.diagPanelEl, ); - const sideCol = h( + const propLockHost = h("div"); + const propControlsBox = h( "div", - { class: "param-side" }, - ctx.simSummaryEl, - ctx.windowBoxEl, - ctx.hazardsBoxEl, - ctx.prelaunchBoxEl, + { class: "col", style: { gap: "8px" } }, + propLockHost, h( "button", { @@ -231,6 +259,7 @@ export function renderMissionConfig(root: HTMLElement): () => void { ); const tuned = autoTuneFlightParams(workingDesign, asm, contract); Object.assign(fp, tuned); + propDirty = true; sliderSyncers.forEach((sync) => sync()); recomputePreview(); toast( @@ -316,71 +345,150 @@ export function renderMissionConfig(root: HTMLElement): () => void { "ratio", "meco_seco", ), + ); + const crewLockHost = h("div"); + const crewControlsBox = h( + "div", + { class: "slot-group" }, + crewLockHost, h( "div", - { class: "slot-group" }, - h( - "div", - { class: "spread" }, - h( - "span", - { class: "slot-title" }, - term("Crew Complement", "crew_eclss"), - ), - crewVal, - ), - crewSizeInput, - h( - "div", - { class: "spread" }, - h( - "span", - { class: "slot-title" }, - term("ECLSS Life Support", "crew_eclss"), - ), - eclssVal, - ), - eclssInput, + { class: "spread" }, + h("span", { class: "slot-title" }, term("Crew Complement", "crew_eclss")), + crewVal, ), + crewSizeInput, + h( + "div", + { class: "spread" }, + h( + "span", + { class: "slot-title" }, + term("ECLSS Life Support", "crew_eclss"), + ), + eclssVal, + ), + eclssInput, + ); + const saveProfileBtn = h( + "button", + { + class: "btn sm ghost", + onClick: async () => { + try { + if (await saveParameters()) + toast("Owned parameter domain saved.", "ok"); + } catch (err) { + toast((err as Error).message, "err"); + } + }, + }, + "Save Profile", + ) as HTMLButtonElement; + const proceedPadBtn = h( + "button", + { + class: "btn sm primary grow", + onClick: async () => { + try { + const canProp = getStationLockInfo("propulsion").canOperate; + const canSci = getStationLockInfo("science").canOperate; + if (canProp || canSci) { + const ok = await saveParameters(); + if (!ok) return; + } + await commitAgencyLaunch(); + } catch (err) { + toast((err as Error).message, "err"); + } + }, + }, + "Save & Proceed to Pad →", + ) as HTMLButtonElement; + const sideCol = h( + "div", + { class: "param-side" }, + ctx.simSummaryEl, + ctx.windowBoxEl, + ctx.hazardsBoxEl, + ctx.prelaunchBoxEl, + propControlsBox, + crewControlsBox, h( "div", { class: "row", style: { marginTop: "auto", paddingTop: "8px" } }, - h( - "button", - { - class: "btn sm ghost", - onClick: async () => { - try { - if (await saveParameters()) - toast("Flight parameters & ECLSS saved.", "ok"); - } catch (err) { - toast((err as Error).message, "err"); - } - }, - }, - "Save Profile", - ), - h( - "button", - { - class: "btn sm primary grow", - onClick: async () => { - try { - if (await saveParameters()) navigate("launch"); - } catch (err) { - toast((err as Error).message, "err"); - } - }, - }, - "Save & Proceed to Pad →", - ), + saveProfileBtn, + proceedPadBtn, ), ); + const syncLocksAndCoopBar = () => { + renderCoopMissionBar(coopHost, { + onStationChanged: () => { + syncLocksAndCoopBar(); + if (ctx.latestSimResult) renderForecastBoxes(ctx, ctx.latestSimResult); + }, + }); + const propLock = getStationLockInfo("propulsion"); + const sciLock = getStationLockInfo("science"); + const dirLock = getStationLockInfo("director"); + clear(propLockHost); + if (propLock.lockedByOther) { + const propBanner = renderStationLockBanner("propulsion"); + if (propBanner) propLockHost.appendChild(propBanner); + } + applyStationControlLock(propControlsBox, "propulsion"); + clear(crewLockHost); + if (sciLock.lockedByOther) { + const crewBanner = renderStationLockBanner("science"); + if (crewBanner) crewLockHost.appendChild(crewBanner); + } + applyStationControlLock(crewControlsBox, "science"); + saveProfileBtn.disabled = !propLock.canOperate && !sciLock.canOperate; + proceedPadBtn.disabled = dirLock.lockedByOther; + proceedPadBtn.textContent = dirLock.lockedByOther + ? `Launch Locked (${dirLock.ownerCallsign ?? "FD"})` + : "Save & Proceed to Pad →"; + }; + const onAgencySync = () => { + const liveAgency = state.agency; + if (!liveAgency) return; + ctx.agency = liveAgency; + if ( + liveAgency.rocketDesign?.flightParams && + (!propDirty || getStationLockInfo("propulsion").lockedByOther) + ) { + Object.assign(fp, liveAgency.rocketDesign.flightParams); + workingDesign.flightParams = { ...fp }; + sliderSyncers.forEach((sync) => sync()); + } + if ( + liveAgency.crewConfig && + (!crewDirty || getStationLockInfo("science").lockedByOther) + ) { + crew.crewSize = liveAgency.crewConfig.crewSize ?? 0; + crew.lifeSupport = liveAgency.crewConfig.lifeSupport ?? 0; + crewSizeInput.value = String(crew.crewSize); + eclssInput.value = String(crew.lifeSupport); + eclssVal.textContent = `Tier ${crew.lifeSupport}`; + crewVal.textContent = `${crew.crewSize} crew (+${crew.crewSize * (85 + 15 * crew.lifeSupport) + (crew.crewSize > 0 ? 500 * crew.lifeSupport : 0)} kg)`; + } + recomputePreview(); + syncLocksAndCoopBar(); + }; + const onPresenceSync = () => { + syncLocksAndCoopBar(); + if (ctx.latestSimResult) renderForecastBoxes(ctx, ctx.latestSimResult); + }; recomputePreview(); + syncLocksAndCoopBar(); const onThemeChanged = () => renderDiagPanel(ctx); window.addEventListener("sgywftp:theme-changed", onThemeChanged); + window.addEventListener("sgywftp:agency-sync", onAgencySync); + window.addEventListener("sgywftp:coop-presence", onPresenceSync); root.appendChild(h("div", { class: "screen param-root" }, mainCol, sideCol)); return () => { window.removeEventListener("sgywftp:theme-changed", onThemeChanged); + window.removeEventListener("sgywftp:agency-sync", onAgencySync); + window.removeEventListener("sgywftp:coop-presence", onPresenceSync); }; } diff --git a/src/client/screens/missionConfig/prelaunch.ts b/src/client/screens/missionConfig/prelaunch.ts index e1267fe..ffb2c24 100644 --- a/src/client/screens/missionConfig/prelaunch.ts +++ b/src/client/screens/missionConfig/prelaunch.ts @@ -29,6 +29,10 @@ import { term, toast, } from "../../ui.js"; +import { + getStationLockInfo, + renderStationLockBanner, +} from "../../ui/coopBar.js"; import { drawAscentChart, drawMultiTelemetryChart, @@ -154,6 +158,10 @@ export function renderPrelaunchBox( ), ] : []), + ...[ + renderStationLockBanner("systems"), + renderStationLockBanner("director"), + ].filter((el): el is HTMLElement => !!el), h( "div", { class: "row", style: { marginTop: "8px", gap: "6px" } }, @@ -161,7 +169,10 @@ export function renderPrelaunchBox( "button", { class: `btn xs ${rel?.staticFired ? "ghost" : "primary"} grow`, - disabled: !agency?.rocketDesign || !!rel?.staticFired, + disabled: + !agency?.rocketDesign || + !!rel?.staticFired || + getStationLockInfo("systems").lockedByOther, onClick: async () => { try { const res = await api.post<{ fee: number; agency: AgencyState }>( @@ -187,6 +198,7 @@ export function renderPrelaunchBox( "button", { class: `btn xs ${curAgency.launchInsured ? "warn" : "ghost"} grow`, + disabled: getStationLockInfo("director").lockedByOther, onClick: async () => { try { const res = await api.post<{ diff --git a/src/client/screens/rocketBuilder.ts b/src/client/screens/rocketBuilder.ts index ab80aa2..f089a75 100644 --- a/src/client/screens/rocketBuilder.ts +++ b/src/client/screens/rocketBuilder.ts @@ -5,14 +5,20 @@ import { navigate } from "../router.js"; import { currentContract, state } from "../state.js"; import { disposeRocketMesh } from "../three/rocketMesh.js"; import { createView } from "../three/sceneManager.js"; +import { inferTouchedStations, mergeRocketSection } from "../../shared/coop.js"; import { convertStagesToProParts, createDefaultSpacecraftConfig, createStarterDesign, normalizeDesign, } from "../../shared/physics.js"; -import type { RocketDesign } from "../../shared/types.js"; +import type { RocketDesign, TeamStationId } from "../../shared/types.js"; import { clear, h, term, toast } from "../ui.js"; +import { + applyStationControlLock, + getStationLockInfo, + renderStationLockBanner, +} from "../ui/coopBar.js"; import { openBlueprintsModal } from "./builder/blueprintsModal.js"; import { curAgency, type BuilderContext } from "./builder/context.js"; import { renderDiagnosticsSection } from "./builder/diagnosticsBar.js"; @@ -189,13 +195,18 @@ export function renderRocketBuilder(root: HTMLElement): () => void { cutawayBtn, ), ); - viewportEl.appendChild(topLeftOverlay); const hudStatsRow = h("div", { class: "builder-hud-bottom" }); - viewportEl.appendChild(hudStatsRow); + const viewportHud = h( + "div", + { class: "viewport-hud" }, + topLeftOverlay, + hudStatsRow, + ); + viewportEl.appendChild(viewportHud); const tierBar = h("div", { class: "builder-tier-bar" }); const summaryBar = h("div", { class: "builder-summary-bar" }); - const coopBar = h("div", { class: "builder-coop-bar" }); - const tabsBar = h("div", { class: "builder-tabs" }); + const coopBar = h("div", { class: "builder-coop-bar coop-bar-exempt" }); + const tabsBar = h("div", { class: "builder-tabs coop-bar-exempt" }); const bodyEl = h("div", { class: "builder-body" }); const footerBar = h("div", { class: "row", @@ -253,6 +264,8 @@ export function renderRocketBuilder(root: HTMLElement): () => void { latestReliability: null, latestValueEstimate: null, latestCoach: [], + suppressSync: false, + syncOwnedSectionsNow: () => syncOwnedSectionsNow(), refreshEngineering: (refitCamera, immediate) => refreshEngineering(refitCamera, immediate), renderSidebarBody: () => renderSidebarBody(), @@ -275,6 +288,106 @@ export function renderRocketBuilder(root: HTMLElement): () => void { refreshEngineering(false, true); }) .catch(() => {}); + let lastSyncedDesign: RocketDesign = structuredClone(initialDesign); + const syncTimers = new Map>(); + const lastToastAtBySender = new Map(); + + async function syncSectionNow(section: TeamStationId): Promise { + const t = syncTimers.get(section); + if (t) { + clearTimeout(t); + syncTimers.delete(section); + } + const lock = getStationLockInfo(section); + if (lock.lockedByOther) { + ctx.design = normalizeDesign( + mergeRocketSection(ctx.design, lastSyncedDesign, section), + state.parts, + state.materials, + ); + state.dirtyBuilderSections.delete(section); + toast( + `${lock.title} locked by ${lock.ownerCallsign || "teammate"}.`, + "warn", + ); + ctx.suppressSync = true; + renderAll(); + ctx.suppressSync = false; + return; + } + state.dirtyBuilderSections.add(section); + try { + const snapshot = structuredClone(ctx.design); + const res = await api.patchRocketSection(section, snapshot); + lastSyncedDesign = mergeRocketSection( + lastSyncedDesign, + res.design, + section, + ); + if (state.agency) { + state.agency.rocketDesign = res.agency.rocketDesign; + state.agency.teamStations = res.agency.teamStations; + } + renderSummaryAndCoopBars(ctx); + if ( + !inferTouchedStations(lastSyncedDesign, ctx.design).includes(section) + ) { + state.dirtyBuilderSections.delete(section); + } else { + scheduleBuilderAutoSync(); + } + } catch (err) { + state.dirtyBuilderSections.delete(section); + const fallback = state.agency?.rocketDesign ?? lastSyncedDesign; + ctx.design = normalizeDesign( + mergeRocketSection(ctx.design, fallback, section), + state.parts, + state.materials, + ); + toast((err as Error).message, "err"); + ctx.suppressSync = true; + renderAll(); + ctx.suppressSync = false; + } + } + + function scheduleBuilderAutoSync(): void { + if (ctx.suppressSync) return; + const touched = inferTouchedStations(lastSyncedDesign, ctx.design); + for (const sec of touched) { + const lock = getStationLockInfo(sec); + if (lock.lockedByOther) { + ctx.design = normalizeDesign( + mergeRocketSection(ctx.design, lastSyncedDesign, sec), + state.parts, + state.materials, + ); + state.dirtyBuilderSections.delete(sec); + toast( + `${lock.title} locked by ${lock.ownerCallsign || "teammate"}.`, + "warn", + ); + continue; + } + state.dirtyBuilderSections.add(sec); + const prev = syncTimers.get(sec); + if (prev) clearTimeout(prev); + syncTimers.set( + sec, + setTimeout(() => { + void syncSectionNow(sec); + }, 300), + ); + } + } + + async function syncOwnedSectionsNow(): Promise { + const touched = inferTouchedStations(lastSyncedDesign, ctx.design).filter( + (sec) => getStationLockInfo(sec).canOperate, + ); + await Promise.all(touched.map((sec) => syncSectionNow(sec))); + } + function renderSidebarBody(): void { clear(ctx.bodyEl); if (!ctx.latestAssembly || !ctx.latestValidation) return; @@ -283,56 +396,66 @@ export function renderRocketBuilder(root: HTMLElement): () => void { value: ctx.design.name, onInput: () => { ctx.design.name = nameInput.value.trim() || "Custom Launcher"; + scheduleBuilderAutoSync(); }, onChange: () => { recordHistory(ctx, "Rename vehicle", "rename"); + scheduleBuilderAutoSync(); }, }) as HTMLInputElement; - ctx.bodyEl.appendChild( + const nameRow = h( + "div", + { class: "row", style: { alignItems: "flex-end" } }, + h("label", { class: "field grow" }, "Vehicle Designation", nameInput), h( - "div", - { class: "row", style: { alignItems: "flex-end" } }, - h("label", { class: "field grow" }, "Vehicle Designation", nameInput), - h( - "button", - { - class: "btn xs ghost", - title: "Reset to contract-appropriate starter launch vehicle", - onClick: () => { - const keepPro = ctx.design.designTier === "pro"; - ctx.design = normalizeDesign( - createStarterDesign(contract, curAgency(ctx).difficulty), + "button", + { + class: "btn xs ghost", + title: "Reset to contract-appropriate starter launch vehicle", + onClick: () => { + const keepPro = ctx.design.designTier === "pro"; + ctx.design = normalizeDesign( + createStarterDesign(contract, curAgency(ctx).difficulty), + state.parts, + state.materials, + ); + if (contract?.recommendedPayloadId) + ctx.design.payloadPartId = contract.recommendedPayloadId; + if (keepPro) { + ctx.design.designTier = "pro"; + ctx.design.proParts = convertStagesToProParts( + ctx.design, state.parts, - state.materials, ); - if (contract?.recommendedPayloadId) - ctx.design.payloadPartId = contract.recommendedPayloadId; - if (keepPro) { - ctx.design.designTier = "pro"; - ctx.design.proParts = convertStagesToProParts( - ctx.design, - state.parts, - ); - ctx.selectedProUid = ctx.design.proParts[0]?.uid ?? null; - } - ctx.activeStageIdx = 0; - recordHistory(ctx, "Load starter reference"); - refreshEngineering(true, true); - renderAll(); - toast( - "Loaded reference architecture for current contract.", - "info", - ); - }, + ctx.selectedProUid = ctx.design.proParts[0]?.uid ?? null; + } + ctx.activeStageIdx = 0; + recordHistory(ctx, "Load starter reference"); + refreshEngineering(true, true); + renderAll(); + toast( + "Loaded reference architecture for current contract.", + "info", + ); }, - "Load Reference", - ), + }, + "Load Reference", ), ); + applyStationControlLock(nameRow, "director"); + ctx.bodyEl.appendChild(nameRow); renderDiagnosticsSection(ctx); if (ctx.activeTab === "stages") { + const stageLock = renderStationLockBanner("propulsion"); + if (stageLock) ctx.bodyEl.appendChild(stageLock); + const wrap = h("div", { class: "col", style: { gap: "8px" } }); + const prevBody = ctx.bodyEl; + ctx.bodyEl = wrap; if (ctx.design.designTier === "pro") renderProTab(ctx); else renderStagesTab(ctx); + ctx.bodyEl = prevBody; + applyStationControlLock(wrap, "propulsion"); + ctx.bodyEl.appendChild(wrap); } else if (ctx.activeTab === "payload") { renderPayloadTab(ctx); } else if (ctx.activeTab === "value") { @@ -351,35 +474,79 @@ export function renderRocketBuilder(root: HTMLElement): () => void { renderSummaryAndCoopBars(ctx); if (ctx.latestAssembly) scheduleRebuild3D(ctx, ctx.latestAssembly, refitCamera, immediate); + scheduleBuilderAutoSync(); } function renderAll(): void { updateHistoryButtons(ctx); + ctx.suppressSync = true; refreshEngineering(false, true); + ctx.suppressSync = false; renderSidebarBody(); renderFooter(ctx); } const detachDrag = attachProDragHandlers(ctx); const onAgencySync = (ev: Event) => { const detail = (ev as CustomEvent>).detail ?? {}; - const myAccount = state.account?.name; - if ( - detail.rocketDesign && - detail.sender && - detail.sender !== myAccount && - !ctx.isDragging3D - ) { - ctx.design = normalizeDesign( - structuredClone(detail.rocketDesign), + const incomingDesign = + (detail.rocketDesign as RocketDesign | undefined) ?? + (detail.agencyState?.rocketDesign as RocketDesign | undefined); + const isSelf = + Boolean(detail.senderOperatorId) && + detail.senderOperatorId === state.operator?.operatorId; + + if (incomingDesign && !isSelf && !ctx.isDragging3D) { + let merged = normalizeDesign( + structuredClone(incomingDesign), state.parts, state.materials, ); - recordHistory(ctx, `Sync update from ${detail.sender}`); - renderAll(); - toast(`Synced rocket update from ${detail.sender}`, "info"); + lastSyncedDesign = structuredClone(merged); + for (const dirtySec of state.dirtyBuilderSections) { + if (dirtySec !== detail.changedSection) { + merged = mergeRocketSection(merged, ctx.design, dirtySec); + } + } + ctx.design = normalizeDesign(merged, state.parts, state.materials); + const senderLabel = String( + detail.senderCallsign || detail.sender || "Teammate", + ); + ctx.suppressSync = true; + recordHistory(ctx, `Sync update from ${senderLabel}`); + evaluateNow(ctx); + renderHudOverlay(ctx); + renderTierAndTabs(ctx); + renderSummaryAndCoopBars(ctx); + if (ctx.latestAssembly) { + scheduleRebuild3D(ctx, ctx.latestAssembly, false, true); + } + const activeEl = document.activeElement as HTMLElement | null; + const editingInputInsideBody = + Boolean(activeEl && ctx.bodyEl.contains(activeEl)) && + ["INPUT", "TEXTAREA", "SELECT"].includes(activeEl?.tagName ?? ""); + if (!editingInputInsideBody) { + renderSidebarBody(); + } + renderFooter(ctx); + ctx.suppressSync = false; + + const now = Date.now(); + const prevAt = lastToastAtBySender.get(senderLabel) ?? 0; + if (now - prevAt > 4000) { + lastToastAtBySender.set(senderLabel, now); + toast(`Live sync from ${senderLabel}`, "info"); + } } else { renderSummaryAndCoopBars(ctx); + renderTierAndTabs(ctx); + renderFooter(ctx); } }; + const onCoopPresence = () => { + renderSummaryAndCoopBars(ctx); + renderTierAndTabs(ctx); + renderSidebarBody(); + renderFooter(ctx); + }; const onKeyDown = (ev: KeyboardEvent) => { const targetTag = (ev.target as HTMLElement | null)?.tagName; if ( @@ -401,6 +568,7 @@ export function renderRocketBuilder(root: HTMLElement): () => void { } }; window.addEventListener("sgywftp:agency-sync", onAgencySync); + window.addEventListener("sgywftp:coop-presence", onCoopPresence); window.addEventListener("keydown", onKeyDown); renderAll(); root.appendChild( @@ -409,7 +577,14 @@ export function renderRocketBuilder(root: HTMLElement): () => void { return () => { ctx.buildToken++; if (ctx.rebuildTimer) clearTimeout(ctx.rebuildTimer); + for (const sec of Array.from(syncTimers.keys())) { + const timer = syncTimers.get(sec); + if (timer) clearTimeout(timer); + syncTimers.delete(sec); + } + state.dirtyBuilderSections.clear(); window.removeEventListener("sgywftp:agency-sync", onAgencySync); + window.removeEventListener("sgywftp:coop-presence", onCoopPresence); window.removeEventListener("keydown", onKeyDown); detachDrag(); if (ctx.currentMesh) { diff --git a/src/client/screens/worldMap.ts b/src/client/screens/worldMap.ts index f104794..6ce003f 100644 --- a/src/client/screens/worldMap.ts +++ b/src/client/screens/worldMap.ts @@ -45,56 +45,60 @@ export function renderWorldMap(root: HTMLElement): () => void { viewportEl.appendChild( h( "div", - { class: "dash-header" }, + { class: "viewport-hud" }, h( "div", - { class: "row" }, + { class: "dash-header" }, h( - "button", - { class: "btn xs ghost", onClick: () => navigate("dashboard") }, - "← Dashboard", + "div", + { class: "row" }, + h( + "button", + { class: "btn xs ghost", onClick: () => navigate("dashboard") }, + "← Dashboard", + ), + h("h1", {}, "Solar System & NASA Asset Tracker"), + h( + "span", + { class: "badge info" }, + `WX: ${(state.world?.weather ?? "nominal").toUpperCase()}`, + ), ), - h("h1", {}, "Solar System & NASA Asset Tracker"), h( - "span", - { class: "badge info" }, - `WX: ${(state.world?.weather ?? "nominal").toUpperCase()}`, - ), - ), - h( - "div", - { class: "row" }, - h( - "button", - { - class: "btn xs", - onClick: () => { - speedMult = 1; + "div", + { class: "row" }, + h( + "button", + { + class: "btn xs", + onClick: () => { + speedMult = 1; + }, }, - }, - "30× Sim", - ), - h( - "button", - { - class: "btn xs", - onClick: () => { - speedMult = 2500; + "30× Sim", + ), + h( + "button", + { + class: "btn xs", + onClick: () => { + speedMult = 2500; + }, }, - }, - "Orbit Fast", - ), - h( - "button", - { - class: "btn xs", - onClick: () => { - focusBodyId = "sun"; - selectedAssetId = null; - view.controls.target.set(0, 0, 0); + "Orbit Fast", + ), + h( + "button", + { + class: "btn xs", + onClick: () => { + focusBodyId = "sun"; + selectedAssetId = null; + view.controls.target.set(0, 0, 0); + }, }, - }, - "Heliocentric", + "Heliocentric", + ), ), ), ), diff --git a/src/client/session.ts b/src/client/session.ts index fe5529c..f2504bc 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -1,5 +1,6 @@ // Handles server catalog population (Lesbian geckos), agency/world polling, and SSE dispatch. import { api, connectEvents, getSettings, getToken, setToken } from "./api.js"; +import { navigate } from "./router.js"; import { applyThemeFromState, getCurrentScreen, @@ -7,18 +8,24 @@ import { type ServerInfo, state, } from "./state.js"; +import { mergeRocketSection } from "../shared/coop.js"; import { pushNotification, toast } from "./ui.js"; import type { + ActiveMission, AgencyState, ContractOffer, + CoopStateSnapshot, MaterialSpec, + MissionSettlement, MissionTemplate, Part, + RocketPatchSection, Sponsor, WorldSnapshot, } from "../shared/types.js"; let eventSource: EventSource | null = null; +let eventSourceToken: string | null = null; let worldTimer: number | null = null; export async function loadCatalogs(): Promise { @@ -44,10 +51,14 @@ export async function refreshMe(): Promise { try { const me = await api.get<{ account: { name: string }; + operator?: { operatorId: string; callsign: string }; agency: AgencyState; + coopPresence?: CoopStateSnapshot; }>("/api/me", true); state.account = me.account; + state.operator = me.operator ?? null; state.agency = me.agency; + state.coopPresence = me.coopPresence ?? null; try { state.contracts = await api.get("/api/contracts", true); } catch {} @@ -56,7 +67,9 @@ export async function refreshMe(): Promise { } catch { setToken(null); state.account = null; + state.operator = null; state.agency = null; + state.coopPresence = null; return null; } } @@ -79,7 +92,13 @@ function handleLiveEvent(ev: { const d = ev.data ?? {}; const notify = getSettings().notifications; const myName = state.agency?.name; - const isMine = Boolean(myName && d.agency === myName); + const eventAgencyName = + typeof d.agencyName === "string" + ? d.agencyName + : typeof d.agency === "string" + ? d.agency + : ""; + const isMine = Boolean(myName && eventAgencyName === myName); if (ev.type === "world.weather") { if (state.world && d.weather) { state.world.weather = d.weather; @@ -191,25 +210,105 @@ function handleLiveEvent(ev: { pushNotification(msg, "warn", "world", false); } void refreshWorld(); - } else if (ev.type === "agency.updated" && isMine) { - if (state.agency && d.rocketDesign) { - state.agency.rocketDesign = d.rocketDesign; + } else if (ev.type === "hello" && d.coopPresence) { + state.coopPresence = d.coopPresence as CoopStateSnapshot; + window.dispatchEvent( + new CustomEvent("sgywftp:coop-presence", { detail: d.coopPresence }), + ); + } else if (ev.type === "coop.presence" && isMine) { + if (d.coopPresence) { + state.coopPresence = d.coopPresence as CoopStateSnapshot; + window.dispatchEvent( + new CustomEvent("sgywftp:coop-presence", { detail: d.coopPresence }), + ); } - if (state.agency && d.teamStations) { - state.agency.teamStations = d.teamStations; + } else if (ev.type === "coop.mission_launched" && isMine) { + if (d.agencyState) { + state.agency = d.agencyState as AgencyState; + } + const launchedByOther = + d.launchedByOperatorId && + d.launchedByOperatorId !== state.operator?.operatorId; + if (launchedByOther && d.mission) { + toast( + `Launch initiated by ${String(d.launchedByCallsign || "Flight Director")}!`, + "info", + ); + navigate("launch", { + coopMission: { + mission: d.mission as ActiveMission, + settlement: d.settlement as MissionSettlement | undefined, + launchedByCallsign: d.launchedByCallsign as string | undefined, + }, + }); + } + } else if (ev.type === "agency.updated" && isMine) { + const incomingAgency = (d.agencyState as AgencyState | undefined) ?? null; + const isSelfEcho = + Boolean(d.senderOperatorId) && + d.senderOperatorId === state.operator?.operatorId; + if (incomingAgency && state.agency) { + let nextDesign = incomingAgency.rocketDesign; + if ( + !isSelfEcho && + nextDesign && + state.agency.rocketDesign && + state.dirtyBuilderSections.size > 0 + ) { + let preserved = nextDesign; + for (const sec of state.dirtyBuilderSections) { + if (sec !== d.changedSection) { + preserved = mergeRocketSection( + preserved, + state.agency.rocketDesign, + sec as RocketPatchSection, + ); + } + } + nextDesign = preserved; + } + if (!isSelfEcho || !state.dirtyBuilderSections.size) { + state.agency = { + ...incomingAgency, + rocketDesign: nextDesign, + }; + } else if (d.teamStations) { + state.agency.teamStations = d.teamStations; + } + } else if (state.agency) { + if (d.rocketDesign) { + state.agency.rocketDesign = d.rocketDesign; + } + if (d.teamStations) { + state.agency.teamStations = d.teamStations; + } } window.dispatchEvent(new CustomEvent("sgywftp:agency-sync", { detail: d })); - void refreshMe().then(() => { - window.dispatchEvent( - new CustomEvent("sgywftp:agency-sync", { detail: d }), - ); - }); + if (!incomingAgency && !isSelfEcho) { + void refreshMe().then(() => { + window.dispatchEvent( + new CustomEvent("sgywftp:agency-sync", { detail: d }), + ); + }); + } + } +} + +export function stopEvents(): void { + if (eventSource) { + eventSource.close(); + eventSource = null; + eventSourceToken = null; } } export function startEvents(): void { - if (eventSource) return; - eventSource = connectEvents(handleLiveEvent); + const token = getToken(); + if (!token) return; + if (eventSource && eventSourceToken === token) return; + stopEvents(); + eventSourceToken = token; + eventSource = connectEvents(token, handleLiveEvent); if (worldTimer === null) { worldTimer = window.setInterval(() => { if ( @@ -222,3 +321,8 @@ export function startEvents(): void { }, 6000); } } + +export function restartEvents(): void { + stopEvents(); + startEvents(); +} diff --git a/src/client/state.ts b/src/client/state.ts index 8d58ece..d68c629 100644 --- a/src/client/state.ts +++ b/src/client/state.ts @@ -5,10 +5,12 @@ import type { ActiveMission, AgencyState, ContractOffer, + CoopStateSnapshot, MaterialSpec, MissionSettlement, MissionTemplate, Part, + RocketPatchSection, SimResult, Sponsor, WorldSnapshot, @@ -42,7 +44,11 @@ export interface ServerInfo { export interface AppState { serverInfo: ServerInfo | null; account: { name: string } | null; + operator: { operatorId: string; callsign: string } | null; agency: AgencyState | null; + coopPresence: CoopStateSnapshot | null; + pendingJoinCode: string | null; + dirtyBuilderSections: Set; parts: Part[]; materials: MaterialSpec[]; missions: MissionTemplate[]; @@ -55,7 +61,11 @@ export interface AppState { export const state: AppState = { serverInfo: null, account: null, + operator: null, agency: null, + coopPresence: null, + pendingJoinCode: null, + dirtyBuilderSections: new Set(), parts: [], materials: [], missions: [], @@ -78,6 +88,11 @@ export function setCurrentScreen(screen: ScreenName): void { export interface LaunchScreenParams { testResult?: SimResult; spectateId?: string; + coopMission?: { + mission: ActiveMission; + settlement?: MissionSettlement; + launchedByCallsign?: string; + }; } export interface DebriefScreenParams { diff --git a/src/client/theme.ts b/src/client/theme.ts index 20dcaea..9a17915 100644 --- a/src/client/theme.ts +++ b/src/client/theme.ts @@ -27,21 +27,21 @@ export interface PresetDescriptor { } export const SHAPE_SET_OPTIONS: PresetDescriptor[] = [ + { + id: "sharp", + label: "Sharp / Square", + tagline: "Crisp 90° edges, zero corner radius (Default)", + }, { id: "chamfered", label: "Chamfered", - tagline: "Angled telemetry corner cuts (Default)", + tagline: "Angled telemetry corner cuts", }, { id: "smooth", label: "Smooth", tagline: "Soft rounded corners (Eye-Saver style)", }, - { - id: "sharp", - label: "Sharp / Square", - tagline: "Crisp 90° edges, zero corner radius", - }, ]; export interface ColorSetPreset extends PresetDescriptor { diff --git a/src/client/ui/coopBar.ts b/src/client/ui/coopBar.ts new file mode 100644 index 0000000..f766305 --- /dev/null +++ b/src/client/ui/coopBar.ts @@ -0,0 +1,606 @@ +// Shared Co-op Mission Control bar, station permission locking helpers, and crew invite modal. +import { ApiError, api } from "../api.js"; +import { navigate } from "../router.js"; +import { state } from "../state.js"; +import { STATION_DOMAIN_HINTS, TEAM_STATION_ORDER } from "../../shared/coop.js"; +import { TEAM_STATION_DEFS } from "../../shared/physics.js"; +import type { + ActiveMission, + AgencyState, + MissionSettlement, + TeamStationId, +} from "../../shared/types.js"; +import { clear, h, modal, toast } from "../ui.js"; + +const SHORT_STATION_LABEL: Record = { + director: "FD", + propulsion: "PROP", + science: "SCI", + systems: "SYS", +}; + +export interface StationLockInfo { + stationId: TeamStationId; + title: string; + claimed: boolean; + ownedByMe: boolean; + lockedByOther: boolean; + ownerCallsign: string | null; + ready: boolean; + canOperate: boolean; + solo: boolean; +} + +/** True when 2+ operators are active on this agency or any station is claimed by someone else. */ +export function isCoopMultiOperator(): boolean { + if ((state.coopPresence?.activeCount ?? 0) >= 2) return true; + const myOpId = state.operator?.operatorId; + const stations = state.agency?.teamStations; + if (!stations || !myOpId) return false; + return TEAM_STATION_ORDER.some((id) => { + const owner = stations[id]?.operatorId; + return Boolean(owner && owner !== myOpId); + }); +} + +/** Inspect lock & ready state for a mission control station for the current operator. */ +export function getStationLockInfo(stationId: TeamStationId): StationLockInfo { + const def = TEAM_STATION_DEFS.find((d) => d.id === stationId)!; + const st = state.agency?.teamStations?.[stationId]; + const myOpId = state.operator?.operatorId; + const multi = isCoopMultiOperator(); + const claimed = Boolean(st?.operatorId); + const ownedByMe = Boolean(st?.operatorId && st.operatorId === myOpId); + const lockedByOther = Boolean( + multi && st?.operatorId && st.operatorId !== myOpId, + ); + return { + stationId, + title: st?.title || def.title, + claimed, + ownedByMe, + lockedByOther, + ownerCallsign: st?.operatorName || null, + ready: Boolean(st?.ready), + canOperate: !lockedByOther, + solo: !multi, + }; +} + +/** Check if the current operator is Flight Director (or uncontested/solo). */ +export function canForceReleaseStations(): boolean { + const director = getStationLockInfo("director"); + return director.ownedByMe || !director.claimed || director.solo; +} + +/** Render a concise inline banner explaining why a station's controls are view-only. */ +export function renderStationLockBanner( + stationId: TeamStationId, +): HTMLElement | null { + const info = getStationLockInfo(stationId); + if (!info.lockedByOther) return null; + return h( + "div", + { class: "coop-lock-banner" }, + h("span", { class: "coop-lock-icon" }, "LOCKED"), + h( + "span", + {}, + `${info.title} controls are owned by ${info.ownerCallsign || "a teammate"} (${STATION_DOMAIN_HINTS[stationId]}). View-only until released.`, + ), + ); +} + +/** + * Lock interactive controls inside `container` when `stationId` belongs to another operator. + * Elements with `.coop-bar-exempt` remain interactive (e.g., navigation / inspection tabs). + */ +export function applyStationControlLock( + container: HTMLElement, + stationId: TeamStationId, +): StationLockInfo { + const info = getStationLockInfo(stationId); + container.classList.toggle("coop-section-locked", info.lockedByOther); + const controls = container.querySelectorAll< + | HTMLButtonElement + | HTMLInputElement + | HTMLSelectElement + | HTMLTextAreaElement + >("button, input, select, textarea"); + for (const el of controls) { + if (el.closest(".coop-bar-exempt")) continue; + if (info.lockedByOther) { + if (!el.disabled) el.setAttribute("data-coop-was-enabled", "1"); + el.disabled = true; + } else if (el.getAttribute("data-coop-was-enabled") === "1") { + el.removeAttribute("data-coop-was-enabled"); + el.disabled = false; + } + } + return info; +} + +async function copyTextWithToast(text: string, label: string): Promise { + try { + await navigator.clipboard.writeText(text); + toast(`${label} copied to clipboard.`, "ok"); + } catch { + toast(`${label}: ${text}`, "info"); + } +} + +export function openCoopRosterModal(onChanged?: () => void): void { + const wrap = h("div", { class: "col", style: { gap: "10px" } }); + + function renderBody() { + clear(wrap); + const ag = state.agency; + if (!ag) return; + const code = ag.coopJoinCode ?? ""; + const inviteUrl = `${window.location.origin}/?join=${encodeURIComponent(code)}`; + const presence = state.coopPresence; + const canManageCode = canForceReleaseStations(); + + wrap.append( + h( + "div", + { class: "panel-inset col", style: { gap: "6px" } }, + h( + "div", + { class: "spread" }, + h( + "span", + { class: "mono", style: { fontWeight: "700" } }, + "CO-OP INVITE", + ), + h("span", { class: "badge info" }, `Code: ${code || "N/A"}`), + ), + h( + "div", + { + class: "mono dim", + style: { fontSize: "11px", wordBreak: "break-all" }, + }, + inviteUrl, + ), + h( + "div", + { class: "row wrap", style: { gap: "6px" } }, + h( + "button", + { + class: "btn xs primary", + type: "button", + onClick: () => void copyTextWithToast(inviteUrl, "Invite link"), + }, + "Copy Invite Link", + ), + h( + "button", + { + class: "btn xs ghost", + type: "button", + onClick: () => void copyTextWithToast(code, "Join code"), + }, + "Copy Code", + ), + canManageCode + ? h( + "button", + { + class: "btn xs warn", + type: "button", + onClick: async () => { + try { + const res = await api.rotateCoopCode(); + state.agency = res.agency; + toast(`New co-op code: ${res.coopJoinCode}`, "ok"); + renderBody(); + onChanged?.(); + } catch (err) { + toast((err as Error).message, "err"); + } + }, + }, + "Rotate Code", + ) + : null, + ), + ), + h( + "div", + { class: "panel-inset col", style: { gap: "6px" } }, + h( + "div", + { class: "spread" }, + h( + "span", + { class: "mono", style: { fontWeight: "700" } }, + "ONLINE OPERATORS", + ), + h( + "span", + { class: "badge ok" }, + `${presence?.activeCount ?? 1} Connected`, + ), + ), + ...(presence?.operators?.length + ? presence.operators.map((op) => + h( + "div", + { class: "spread", style: { fontSize: "12px" } }, + h( + "span", + {}, + op.callsign, + op.operatorId === state.operator?.operatorId ? " (You)" : "", + ), + h( + "span", + { class: "mono dim", style: { fontSize: "11px" } }, + op.stations.length + ? op.stations.map((s) => SHORT_STATION_LABEL[s]).join(", ") + : "Observer", + ), + ), + ) + : [ + h( + "div", + { class: "dim", style: { fontSize: "12px" } }, + `${state.operator?.callsign ?? ag.name} (Solo Session — all controls unlocked)`, + ), + ]), + ), + h( + "div", + { class: "panel-inset col", style: { gap: "6px" } }, + h( + "span", + { class: "mono", style: { fontWeight: "700" } }, + "STATION ASSIGNMENTS", + ), + ...TEAM_STATION_ORDER.map((id) => { + const info = getStationLockInfo(id); + return h( + "div", + { class: "spread", style: { fontSize: "12px", gap: "8px" } }, + h( + "div", + { class: "col", style: { gap: "1px", minWidth: "0" } }, + h("span", { style: { fontWeight: "600" } }, info.title), + h( + "span", + { class: "dim", style: { fontSize: "10px" } }, + STATION_DOMAIN_HINTS[id], + ), + ), + h( + "div", + { class: "row", style: { gap: "4px", flexShrink: "0" } }, + h( + "span", + { + class: `badge ${info.ready ? "ok" : info.claimed ? "info" : "ghost"}`, + }, + info.claimed + ? `${info.ownerCallsign ?? "Op"}${info.ready ? " ✓" : ""}` + : "Open", + ), + info.lockedByOther && canManageCode + ? h( + "button", + { + class: "btn xs warn", + type: "button", + onClick: async () => { + try { + const res = await api.updateCoopStation({ + stationId: id, + action: "fd_release", + }); + if (state.agency) { + state.agency.teamStations = res.teamStations; + } + state.coopPresence = res.coopPresence; + toast(`Released ${info.title}.`, "info"); + renderBody(); + onChanged?.(); + } catch (err) { + toast((err as Error).message, "err"); + } + }, + }, + "Force Release", + ) + : null, + ), + ); + }), + ), + ); + } + + renderBody(); + modal("Co-op Mission Control Roster", wrap, [ + { label: "Close", kind: "primary" }, + ]); +} + +export interface CoopBarOptions { + compact?: boolean; + onStationChanged?: () => void; +} + +/** Render the reusable Co-op Mission Control Bar into `hostEl`. */ +export function renderCoopMissionBar( + hostEl: HTMLElement, + options: CoopBarOptions = {}, +): void { + clear(hostEl); + const ag = state.agency; + if (!ag) return; + + const activeCount = state.coopPresence?.activeCount ?? 1; + const multi = isCoopMultiOperator(); + const code = ag.coopJoinCode ?? ""; + const canFdRelease = canForceReleaseStations(); + + const bar = h("div", { + class: `coop-mission-bar coop-bar-exempt ${options.compact ? "compact" : ""}`, + }); + + const presenceBtn = h( + "button", + { + class: `coop-pill ${multi ? "online" : "solo"}`, + type: "button", + title: "View connected operators, stations & invite link", + onClick: () => openCoopRosterModal(options.onStationChanged), + }, + h("span", { class: `coop-dot ${multi ? "on" : ""}` }), + h("span", { class: "mono" }, `${activeCount} ONLINE`), + code ? h("span", { class: "coop-code-tag mono" }, `#${code}`) : null, + ); + + const inviteBtn = code + ? h( + "button", + { + class: "coop-pill invite", + type: "button", + title: "Copy co-op invite link to share with teammates", + onClick: () => + void copyTextWithToast( + `${window.location.origin}/?join=${encodeURIComponent(code)}`, + "Invite link", + ), + }, + "Invite", + ) + : null; + + const stationsRow = h("div", { class: "coop-stations-row" }); + for (const id of TEAM_STATION_ORDER) { + const info = getStationLockInfo(id); + const pillWrap = h("div", { + class: `coop-station-group ${info.ready ? "ready" : ""} ${info.ownedByMe ? "mine" : info.lockedByOther ? "locked" : "open"}`, + }); + + const labelText = info.claimed + ? `${SHORT_STATION_LABEL[id]}: ${info.ownerCallsign ?? "Op"}${info.ownedByMe ? (info.ready ? " ✓" : " •") : " 🔒"}` + : `${SHORT_STATION_LABEL[id]}: Open`; + + const mainBtn = h( + "button", + { + class: "coop-station-btn", + type: "button", + disabled: info.lockedByOther, + title: info.lockedByOther + ? `${info.title} locked to ${info.ownerCallsign}. ${STATION_DOMAIN_HINTS[id]}` + : info.ownedByMe + ? `Click to toggle ${info.title} Ready (GO/NO-GO). ${STATION_DOMAIN_HINTS[id]}` + : `Claim ${info.title}. ${STATION_DOMAIN_HINTS[id]}`, + onClick: async () => { + try { + const action = info.ownedByMe ? "ready" : "claim"; + const res = await api.updateCoopStation({ + stationId: id, + action, + ready: action === "ready" ? !info.ready : undefined, + }); + if (state.agency) state.agency.teamStations = res.teamStations; + state.coopPresence = res.coopPresence; + renderCoopMissionBar(hostEl, options); + options.onStationChanged?.(); + } catch (err) { + toast((err as Error).message, "err"); + } + }, + }, + labelText, + ); + pillWrap.appendChild(mainBtn); + + if (info.ownedByMe || (info.lockedByOther && canFdRelease)) { + const action: "release" | "fd_release" = info.ownedByMe + ? "release" + : "fd_release"; + const relBtn = h( + "button", + { + class: "coop-station-rel", + type: "button", + title: info.ownedByMe + ? `Release ${info.title}` + : `Flight Director: Force release ${info.title} (${info.ownerCallsign})`, + onClick: async () => { + try { + const res = await api.updateCoopStation({ + stationId: id, + action, + }); + if (state.agency) state.agency.teamStations = res.teamStations; + state.coopPresence = res.coopPresence; + toast( + info.ownedByMe + ? `Released ${info.title}.` + : `Force-released ${info.title}.`, + "info", + ); + renderCoopMissionBar(hostEl, options); + options.onStationChanged?.(); + } catch (err) { + toast((err as Error).message, "err"); + } + }, + }, + "×", + ); + pillWrap.appendChild(relBtn); + } + + stationsRow.appendChild(pillWrap); + } + + bar.append(presenceBtn); + if (inviteBtn) bar.append(inviteBtn); + bar.append(stationsRow); + hostEl.appendChild(bar); +} + +export type ReadyGateStation = { + stationId: TeamStationId | string; + title: string; + operatorName: string; +}; + +/** + * Show FD Go/No-Go confirmation modal when claimed teammates have not marked Ready. + * Returns a Promise resolving to `true` if FD chooses Override & Launch Anyway, else `false`. + */ +export function confirmLaunchWithUnreadyStations( + unreadyStations: ReadyGateStation[], +): Promise { + return new Promise((resolve) => { + let settled = false; + const finish = (decision: boolean) => { + if (settled) return; + settled = true; + resolve(decision); + }; + const body = h( + "div", + { class: "col", style: { gap: "10px" } }, + h( + "p", + { class: "sub" }, + "The following claimed Mission Control stations have not toggled Ready (✓ GO):", + ), + h( + "div", + { class: "panel-inset col", style: { gap: "6px" } }, + ...unreadyStations.map((st) => + h( + "div", + { class: "spread", style: { fontSize: "12px" } }, + h("span", { style: { fontWeight: "600" } }, st.title), + h( + "span", + { class: "badge warn" }, + `${st.operatorName} — NOT READY`, + ), + ), + ), + ), + h( + "p", + { class: "dim", style: { fontSize: "12px" } }, + "As Flight Director, you may wait for stations to poll GO, or override Ready checks and commit to launch now.", + ), + ); + modal("Flight Director Go / No-Go Check", body, [ + { + label: "Wait for Crew", + kind: "ghost", + onClick: () => { + finish(false); + }, + }, + { + label: "Override & Launch Anyway", + kind: "danger", + onClick: () => { + finish(true); + }, + }, + ]); + }); +} + +let launchCommitInFlight = false; + +interface LaunchApiResponse { + mission: ActiveMission; + settlement: MissionSettlement; + agency: AgencyState; +} + +/** + * Commit an agency launch from any Co-op screen. + * Handles the Flight Director Ready-check gate (409 STATIONS_NOT_READY) with an override modal + * before entering the synchronized Launch Sequence screen with the authoritative mission result. + */ +export async function commitAgencyLaunch(): Promise { + const dirLock = getStationLockInfo("director"); + if (dirLock.lockedByOther) { + toast( + `Launch locked by Flight Director (${dirLock.ownerCallsign ?? "teammate"}).`, + "warn", + ); + return false; + } + if (launchCommitInFlight) return false; + launchCommitInFlight = true; + try { + const attemptLaunch = (overrideReady = false) => + api.post( + "/api/mission/launch", + overrideReady ? { overrideReady: true } : {}, + ); + let res: LaunchApiResponse; + try { + res = await attemptLaunch(false); + } catch (err) { + if ( + err instanceof ApiError && + err.status === 409 && + err.code === "STATIONS_NOT_READY" + ) { + const unready = Array.isArray(err.data?.unreadyStations) + ? (err.data.unreadyStations as ReadyGateStation[]) + : []; + const override = await confirmLaunchWithUnreadyStations(unready); + if (!override) return false; + res = await attemptLaunch(true); + } else { + throw err; + } + } + if (res.agency) state.agency = res.agency; + navigate("launch", { + coopMission: { + mission: res.mission, + settlement: res.settlement, + launchedByCallsign: state.operator?.callsign ?? undefined, + }, + }); + return true; + } catch (err) { + toast((err as Error).message, "err"); + return false; + } finally { + launchCommitInFlight = false; + } +} diff --git a/src/client/wiki/wikiData.ts b/src/client/wiki/wikiData.ts index 9b1a5be..993b0a1 100644 --- a/src/client/wiki/wikiData.ts +++ b/src/client/wiki/wikiData.ts @@ -574,7 +574,8 @@ export const WIKI_ARTICLES: WikiArticle[] = [ { heading: "3. Multi-Operator Co-Op Stations", paragraphs: [ - "Multiple users logged into the same agency synchronize Rocket Builder edits live over SSE. Claim one of the 4 mission control stations—PROP (Propulsion), STRC (Structures), GUID (Guidance), PAYL (Payload/Comms)—and toggle Ready status together.", + "Multiple operators can join the same Mission Control agency using a Co-op Join Code or shared ?join= invite link and an Operator Callsign. Live edits across Rocket Builder, Param Config, Contracts, and Prelaunch auto-sync over SSE within ~300 ms.", + "Claim stations across Flight Director (FD — Contracts, Research, Finance, Launch Commit & Override), Propulsion & Guidance (PROP — Stages, Engines, Tanks & Flight Params), Science & Crew (SCI — Payload, Experiments, Crew & ECLSS), and Systems & Safety (SYS — Fairings, Avionics, Compliance & Static Fire). In multi-operator mode, claimed stations strictly lock their domain controls to the holding operator while unclaimed stations stay open; solo operators retain full unlocked control.", ], }, ], diff --git a/src/server/auth.ts b/src/server/auth.ts index a8ce927..7832b19 100644 --- a/src/server/auth.ts +++ b/src/server/auth.ts @@ -3,6 +3,7 @@ import crypto from "node:crypto"; import type { NextFunction, Request, Response } from "express"; import { deleteToken, + findAgencyByJoinCode, getAccount, getAgency, getTokenRecord, @@ -11,15 +12,37 @@ import { putToken, saveDb, } from "./store.js"; -import type { AgencyState, DifficultyLevel } from "../shared/types.js"; +import type { + AgencyState, + CoopStateSnapshot, + DifficultyLevel, +} from "../shared/types.js"; import { getDifficultyProfile, normalizeDifficulty, TECH_TREE, } from "../shared/physics.js"; +import { + normalizeCallsign, + normalizeJoinCode, + normalizeTeamStations, +} from "../shared/coop.js"; +import { + allocateUniqueCoopJoinCode, + disconnectTokenStreams, + ensureAgencyCoopState, + getAgencyPresence, +} from "./coopPresence.js"; + +export interface OperatorIdentity { + operatorId: string; + callsign: string; +} export interface AuthedRequest extends Request { accountName?: string; + operatorId?: string; + callsign?: string; agency?: AgencyState; } @@ -40,18 +63,42 @@ function verifyPassword(password: string, stored: string): boolean { ); } -function issueToken(name: string): string { +function issueToken( + name: string, + callsign?: string, + operatorId?: string, +): { token: string; operator: OperatorIdentity } { const token = crypto.randomBytes(24).toString("hex"); - putToken(token, { name, createdAt: Date.now() }); + const cleanOperatorId = + operatorId?.trim() || `op-${crypto.randomBytes(6).toString("hex")}`; + const cleanCallsign = normalizeCallsign(callsign, name); + putToken(token, { + name, + operatorId: cleanOperatorId, + callsign: cleanCallsign, + createdAt: Date.now(), + }); saveDb(true); - return token; + return { + token, + operator: { operatorId: cleanOperatorId, callsign: cleanCallsign }, + }; +} + +export interface AuthSessionResponse { + token: string; + account: { name: string }; + operator: OperatorIdentity; + agency: AgencyState; + coopPresence: CoopStateSnapshot; } export function registerAgency( name: string, password: string, difficulty: DifficultyLevel = "enthusiast", -): { token: string; account: { name: string }; agency: AgencyState } { + callsign?: string, +): AuthSessionResponse { const clean = (name ?? "").trim(); if (clean.length < 2 || clean.length > 32) { throw new Error("Agency name must be 2-32 characters."); @@ -101,16 +148,25 @@ export function registerAgency( casualtiesTotal: 0, lastSettlement: null, terminatedReason: null, + teamStations: normalizeTeamStations(), + coopJoinCode: allocateUniqueCoopJoinCode(), }; putAgency(clean, agency); - const token = issueToken(clean); - return { token, account: { name: clean }, agency }; + const { token, operator } = issueToken(clean, callsign || clean); + return { + token, + account: { name: clean }, + operator, + agency, + coopPresence: getAgencyPresence(clean), + }; } export function loginAgency( name: string, password: string, -): { token: string; account: { name: string }; agency: AgencyState } { + callsign?: string, +): AuthSessionResponse { const clean = (name ?? "").trim(); const acc = getAccount(clean); if (!acc || !verifyPassword(password ?? "", acc.hash)) { @@ -120,12 +176,83 @@ export function loginAgency( if (!agency) { throw new Error("Agency record missing."); } - const token = issueToken(clean); - return { token, account: { name: clean }, agency }; + if (ensureAgencyCoopState(agency)) { + putAgency(agency.name, agency); + } + const { token, operator } = issueToken(clean, callsign || clean); + return { + token, + account: { name: clean }, + operator, + agency, + coopPresence: getAgencyPresence(clean), + }; +} + +export function joinAgencyByCode( + rawJoinCode: string, + rawCallsign: string, +): AuthSessionResponse { + const code = normalizeJoinCode(rawJoinCode); + if (!code || code.length < 4) { + throw new Error("Enter a valid co-op join code."); + } + const callsign = normalizeCallsign(rawCallsign, ""); + if (callsign.length < 2) { + throw new Error("Operator callsign must be 2-24 characters."); + } + const agency = findAgencyByJoinCode(code); + if (!agency) { + throw new Error("No active agency matches that co-op join code."); + } + if (ensureAgencyCoopState(agency)) { + putAgency(agency.name, agency); + } + const { token, operator } = issueToken(agency.name, callsign); + return { + token, + account: { name: agency.name }, + operator, + agency, + coopPresence: getAgencyPresence(agency.name), + }; +} + +export function resolveTokenSession(token: string): { + token: string; + accountName: string; + operatorId: string; + callsign: string; + agency: AgencyState; +} | null { + if (!token) return null; + const sess = getTokenRecord(token); + if (!sess) return null; + const agency = getAgency(sess.name); + if (!agency) return null; + let dirty = ensureAgencyCoopState(agency); + if (!sess.operatorId || !sess.callsign) { + sess.operatorId = sess.operatorId || `op-legacy-${sess.name}`; + sess.callsign = normalizeCallsign(sess.callsign, sess.name); + putToken(token, sess); + dirty = true; + } + if (dirty) { + putAgency(agency.name, agency); + saveDb(); + } + return { + token, + accountName: sess.name, + operatorId: sess.operatorId, + callsign: sess.callsign, + agency, + }; } export function logoutToken(token: string): void { if (!token) return; + disconnectTokenStreams(token); deleteToken(token); saveDb(true); } @@ -137,17 +264,14 @@ export function requireAuth( ): void { const header = req.headers.authorization ?? ""; const token = header.startsWith("Bearer ") ? header.slice(7) : ""; - const sess = token ? getTokenRecord(token) : null; - if (!sess) { + const resolved = resolveTokenSession(token); + if (!resolved) { res.status(401).json({ error: "Not authenticated." }); return; } - const agency = getAgency(sess.name); - if (!agency) { - res.status(401).json({ error: "Agency not found." }); - return; - } - req.accountName = sess.name; - req.agency = agency; + req.accountName = resolved.accountName; + req.operatorId = resolved.operatorId; + req.callsign = resolved.callsign; + req.agency = resolved.agency; next(); } diff --git a/src/server/coopPresence.ts b/src/server/coopPresence.ts new file mode 100644 index 0000000..cf896c6 --- /dev/null +++ b/src/server/coopPresence.ts @@ -0,0 +1,282 @@ +// Agency-scoped SSE client delivery, live operator presence tracking, and disconnect station release. +import type { Response } from "express"; +import { + generateCoopJoinCode, + normalizeTeamStations, + TEAM_STATION_ORDER, +} from "../shared/coop.js"; +import type { + AgencyState, + CoopOperatorPresence, + CoopStateSnapshot, + TeamStationId, +} from "../shared/types.js"; +import { emitToAgency, type ServerEvent } from "./events.js"; +import { getAgency, listAgencies, putAgency, saveDb } from "./store.js"; + +export interface SseClientEntry { + res: Response; + token: string; + agencyName: string; + operatorId: string; + callsign: string; + connectedAt: number; + lastSeenAt: number; +} + +const DISCONNECT_GRACE_MS = 8000; + +const sseClients = new Set(); +const disconnectTimers = new Map(); + +function presenceKey(agencyName: string, operatorId: string): string { + return `${agencyName}\0${operatorId}`; +} + +/** Generate a join code unique across all existing player agencies. */ +export function allocateUniqueCoopJoinCode(): string { + const existing = new Set( + listAgencies() + .map((a) => a.coopJoinCode) + .filter((c): c is string => Boolean(c)), + ); + for (let i = 0; i < 32; i++) { + const candidate = generateCoopJoinCode(6); + if (!existing.has(candidate)) return candidate; + } + return generateCoopJoinCode(8); +} + +/** Ensure an agency has initialized teamStations and a persistent coopJoinCode. Returns true if mutated. */ +export function ensureAgencyCoopState(agency: AgencyState): boolean { + let dirty = false; + if (!agency.teamStations) { + agency.teamStations = normalizeTeamStations(); + dirty = true; + } else { + const normalized = normalizeTeamStations(agency.teamStations); + for (const id of TEAM_STATION_ORDER) { + const cur = agency.teamStations[id]; + if (!cur || cur.operatorId === undefined) { + agency.teamStations = normalized; + dirty = true; + break; + } + } + } + if (!agency.isAI && !agency.coopJoinCode) { + agency.coopJoinCode = allocateUniqueCoopJoinCode(); + dirty = true; + } + return dirty; +} + +/** Release all stations held by `operatorId` on `agency`. Returns true if any changed. */ +export function releaseOperatorStations( + agency: AgencyState, + operatorId: string, +): boolean { + if (!agency.teamStations || !operatorId) return false; + let changed = false; + for (const id of TEAM_STATION_ORDER) { + const st = agency.teamStations[id]; + if (st && st.operatorId === operatorId) { + st.operatorId = ""; + st.operatorName = ""; + st.ready = false; + st.updatedAt = Date.now(); + changed = true; + } + } + return changed; +} + +/** Snapshot active operators connected via SSE for `agencyName`. */ +export function getAgencyPresence(agencyName: string): CoopStateSnapshot { + const agency = getAgency(agencyName); + const stations = agency?.teamStations; + const byOp = new Map(); + + for (const client of sseClients) { + if (client.agencyName !== agencyName) continue; + const existing = byOp.get(client.operatorId); + if (existing) { + existing.connectedAt = Math.min(existing.connectedAt, client.connectedAt); + existing.lastSeenAt = Math.max(existing.lastSeenAt, client.lastSeenAt); + continue; + } + const owned: TeamStationId[] = []; + if (stations) { + for (const id of TEAM_STATION_ORDER) { + if (stations[id]?.operatorId === client.operatorId) { + owned.push(id); + } + } + } + byOp.set(client.operatorId, { + operatorId: client.operatorId, + callsign: client.callsign, + connectedAt: client.connectedAt, + lastSeenAt: client.lastSeenAt, + stations: owned, + }); + } + + const operators = Array.from(byOp.values()).sort( + (a, b) => a.connectedAt - b.connectedAt, + ); + return { + operators, + activeCount: operators.length, + coopMode: operators.length >= 2, + }; +} + +/** Broadcast current presence snapshot to all SSE subscribers of `agencyName`. */ +export function broadcastAgencyPresence(agencyName: string): void { + const snapshot = getAgencyPresence(agencyName); + emitToAgency(agencyName, "coop.presence", { coopPresence: snapshot }); +} + +/** Deliver an SSE event only to `targetAgency` when specified, or all authenticated clients for global events. */ +export function deliverSseEvent( + event: ServerEvent, + targetAgency?: string, +): void { + const payload = `data: ${JSON.stringify(event)}\n\n`; + for (const client of sseClients) { + if (targetAgency && client.agencyName !== targetAgency) continue; + try { + client.res.write(payload); + } catch { + unregisterSseClient(client, false); + } + } +} + +export function registerSseClient( + res: Response, + session: { + token: string; + agencyName: string; + operatorId: string; + callsign: string; + }, +): SseClientEntry { + const key = presenceKey(session.agencyName, session.operatorId); + const pending = disconnectTimers.get(key); + if (pending) { + clearTimeout(pending); + disconnectTimers.delete(key); + } + + const now = Date.now(); + const entry: SseClientEntry = { + res, + token: session.token, + agencyName: session.agencyName, + operatorId: session.operatorId, + callsign: session.callsign, + connectedAt: now, + lastSeenAt: now, + }; + sseClients.add(entry); + + // Sync updated callsign onto any already-claimed stations held by this operator. + const agency = getAgency(session.agencyName); + if (agency?.teamStations) { + let stationDirty = false; + for (const id of TEAM_STATION_ORDER) { + const st = agency.teamStations[id]; + if ( + st?.operatorId === session.operatorId && + st.operatorName !== session.callsign + ) { + st.operatorName = session.callsign; + stationDirty = true; + } + } + if (stationDirty) { + putAgency(agency.name, agency); + saveDb(); + emitToAgency(agency.name, "agency.updated", { + teamStations: agency.teamStations, + senderOperatorId: session.operatorId, + senderCallsign: session.callsign, + }); + } + } + + broadcastAgencyPresence(session.agencyName); + return entry; +} + +export function unregisterSseClient( + entry: SseClientEntry, + useGrace = true, +): void { + if (!sseClients.has(entry)) return; + sseClients.delete(entry); + + let remainingForOperator = false; + for (const other of sseClients) { + if ( + other.agencyName === entry.agencyName && + other.operatorId === entry.operatorId + ) { + remainingForOperator = true; + break; + } + } + if (remainingForOperator) return; + + const finalizeDisconnect = () => { + disconnectTimers.delete(presenceKey(entry.agencyName, entry.operatorId)); + // Re-check in case another socket connected right as timer fired. + for (const other of sseClients) { + if ( + other.agencyName === entry.agencyName && + other.operatorId === entry.operatorId + ) { + return; + } + } + const agency = getAgency(entry.agencyName); + if (agency && releaseOperatorStations(agency, entry.operatorId)) { + putAgency(agency.name, agency); + saveDb(); + emitToAgency(agency.name, "agency.updated", { + teamStations: agency.teamStations, + senderOperatorId: entry.operatorId, + senderCallsign: entry.callsign, + }); + } + broadcastAgencyPresence(entry.agencyName); + }; + + if (!useGrace) { + finalizeDisconnect(); + return; + } + + const key = presenceKey(entry.agencyName, entry.operatorId); + const existing = disconnectTimers.get(key); + if (existing) clearTimeout(existing); + disconnectTimers.set( + key, + setTimeout(finalizeDisconnect, DISCONNECT_GRACE_MS), + ); +} + +/** Immediately close any SSE streams tied to `token` (e.g. explicit logout) and release stations. */ +export function disconnectTokenStreams(token: string): void { + if (!token) return; + for (const client of Array.from(sseClients)) { + if (client.token === token) { + try { + client.res.end(); + } catch {} + unregisterSseClient(client, false); + } + } +} diff --git a/src/server/events.ts b/src/server/events.ts index 2ecace3..1883a31 100644 --- a/src/server/events.ts +++ b/src/server/events.ts @@ -5,7 +5,7 @@ export interface ServerEvent { at: number; } -type Broadcaster = (ev: ServerEvent) => void; +type Broadcaster = (ev: ServerEvent, targetAgency?: string) => void; let broadcaster: Broadcaster | null = null; @@ -16,3 +16,18 @@ export function setBroadcaster(fn: Broadcaster): void { export function emit(type: string, data: Record = {}): void { broadcaster?.({ type, data, at: Date.now() }); } + +export function emitToAgency( + agencyName: string, + type: string, + data: Record = {}, +): void { + broadcaster?.( + { + type, + data: { agency: agencyName, agencyName, ...data }, + at: Date.now(), + }, + agencyName, + ); +} diff --git a/src/server/index.ts b/src/server/index.ts index e01c6bd..fb0f8b9 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -1,9 +1,16 @@ // HTTP and Express server entrypoint mounting API routes, static bundles/assets, and starting background loops. -import express, { type Response } from "express"; +import express from "express"; import fs from "node:fs"; import path from "node:path"; import { seedAI } from "./ai.js"; +import { resolveTokenSession } from "./auth.js"; import { APP_ROOT, config } from "./config.js"; +import { + deliverSseEvent, + getAgencyPresence, + registerSseClient, + unregisterSseClient, +} from "./coopPresence.js"; import { initEconomy } from "./economy.js"; import { setBroadcaster } from "./events.js"; import { resolveGmatConsoleBin } from "./gmat_runner.js"; @@ -16,28 +23,44 @@ app.use(express.json({ limit: "4mb" })); app.use("/api", apiRouter); -const sseClients = new Set(); -setBroadcaster((event) => { - const payload = `data: ${JSON.stringify(event)}\n\n`; - for (const res of sseClients) { - try { - res.write(payload); - } catch { - sseClients.delete(res); - } - } -}); +setBroadcaster((event, targetAgency) => deliverSseEvent(event, targetAgency)); app.get("/api/events", (req, res) => { + const queryToken = typeof req.query.token === "string" ? req.query.token : ""; + const header = req.headers.authorization ?? ""; + const token = + queryToken || (header.startsWith("Bearer ") ? header.slice(7) : ""); + const resolved = resolveTokenSession(token); + if (!resolved) { + res.status(401).json({ error: "Not authenticated." }); + return; + } + res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", "X-Accel-Buffering": "no", }); - res.write(`data: ${JSON.stringify({ type: "hello", at: Date.now() })}\n\n`); - sseClients.add(res); - req.on("close", () => sseClients.delete(res)); + const entry = registerSseClient(res, { + token: resolved.token, + agencyName: resolved.accountName, + operatorId: resolved.operatorId, + callsign: resolved.callsign, + }); + res.write( + `data: ${JSON.stringify({ + type: "hello", + at: Date.now(), + data: { + agencyName: resolved.accountName, + operatorId: resolved.operatorId, + callsign: resolved.callsign, + coopPresence: getAgencyPresence(resolved.accountName), + }, + })}\n\n`, + ); + req.on("close", () => unregisterSseClient(entry, true)); }); app.use("/bundle", express.static(path.join(APP_ROOT, "dist", "bundle"))); diff --git a/src/server/routes/agencyRoutes.ts b/src/server/routes/agencyRoutes.ts index 8a90552..dd169b7 100644 --- a/src/server/routes/agencyRoutes.ts +++ b/src/server/routes/agencyRoutes.ts @@ -18,13 +18,19 @@ import { TECH_TREE, } from "../../shared/physics.js"; import type { ContractOffer, RocketDesign } from "../../shared/types.js"; -import { resolveContract } from "./helpers.js"; +import { + emitAgencySync, + requireStationAccess, + resetStationsReadyOnEdit, + resolveContract, +} from "./helpers.js"; export function registerAgencyRoutes(router: Router): void { router.post( "/agency/onboard", requireAuth, (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "director")) return; const { sponsorId, missionId } = (req.body ?? {}) as { sponsorId?: string; missionId?: string; @@ -81,6 +87,7 @@ export function registerAgencyRoutes(router: Router): void { missionId: contract.id, sponsorId, }); + emitAgencySync(req, agency, { changedSection: "director" }); res.json({ agency, contract }); }, ); @@ -88,6 +95,7 @@ export function registerAgencyRoutes(router: Router): void { "/agency/crew", requireAuth, (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "science")) return; const crew = req.body?.crew as { crewSize?: number; lifeSupport?: number } | undefined; if (!crew || typeof crew.crewSize !== "number") { @@ -102,15 +110,18 @@ export function registerAgencyRoutes(router: Router): void { Math.min(3, Math.floor(crew.lifeSupport ?? 1)), ), }; + resetStationsReadyOnEdit(agency, ["science"]); putAgency(agency.name, agency); saveDb(true); - res.json({ ok: true, crew: agency.crewConfig }); + emitAgencySync(req, agency, { changedSection: "science" }); + res.json({ ok: true, crew: agency.crewConfig, agency }); }, ); router.post( "/agency/bailout", requireAuth, (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "director")) return; const agency = req.agency!; if (agency.terminatedReason) { res.status(400).json({ @@ -148,6 +159,7 @@ export function registerAgencyRoutes(router: Router): void { putAgency(agency.name, agency); saveDb(true); emit("agency.bailout", { agency: agency.name, grant }); + emitAgencySync(req, agency, { changedSection: "director" }); res.json({ ok: true, grant, agency }); }, ); @@ -155,6 +167,7 @@ export function registerAgencyRoutes(router: Router): void { "/agency/reset", requireAuth, (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "director")) return; const agency = req.agency!; const canonDiff = normalizeDifficulty(agency.difficulty); const profile = getDifficultyProfile(canonDiff); @@ -189,8 +202,15 @@ export function registerAgencyRoutes(router: Router): void { agency.casualtiesTotal = 0; agency.lastSettlement = null; agency.terminatedReason = null; + if (agency.teamStations) { + for (const st of Object.values(agency.teamStations)) { + st.ready = false; + st.updatedAt = Date.now(); + } + } putAgency(agency.name, agency); saveDb(true); + emitAgencySync(req, agency); res.json({ ok: true, agency }); }, ); @@ -198,6 +218,7 @@ export function registerAgencyRoutes(router: Router): void { "/agency/unlock-tech", requireAuth, (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "director")) return; const agency = req.agency!; if (agency.terminatedReason) { res.status(409).json({ error: agency.terminatedReason }); @@ -237,6 +258,7 @@ export function registerAgencyRoutes(router: Router): void { agency.unlockedTechs = Array.from(unlocked); putAgency(agency.name, agency); saveDb(true); + emitAgencySync(req, agency, { changedSection: "director" }); res.json({ ok: true, tech: node, @@ -250,6 +272,7 @@ export function registerAgencyRoutes(router: Router): void { "/agency/static-fire", requireAuth, (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "systems")) return; const agency = req.agency!; if (agency.terminatedReason) { res.status(409).json({ error: agency.terminatedReason }); @@ -306,6 +329,7 @@ export function registerAgencyRoutes(router: Router): void { agency.staticFiredDesignHash = hash; putAgency(agency.name, agency); saveDb(true); + emitAgencySync(req, agency, { changedSection: "systems" }); const reliability = computeDesignReliability(design, assembly, agency); res.json({ ok: true, @@ -323,6 +347,7 @@ export function registerAgencyRoutes(router: Router): void { "/agency/insurance", requireAuth, (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "director")) return; const agency = req.agency!; const canonDiff = normalizeDifficulty(agency.difficulty); const enabled = Boolean(req.body?.enabled); @@ -347,6 +372,7 @@ export function registerAgencyRoutes(router: Router): void { } putAgency(agency.name, agency); saveDb(true); + emitAgencySync(req, agency, { changedSection: "director" }); res.json({ ok: true, launchInsured: agency.launchInsured, @@ -359,6 +385,7 @@ export function registerAgencyRoutes(router: Router): void { "/agency/clear-standdown", requireAuth, (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "director")) return; const agency = req.agency!; if (agency.terminatedReason) { res.status(409).json({ error: agency.terminatedReason }); @@ -372,6 +399,7 @@ export function registerAgencyRoutes(router: Router): void { agency.groundedUntilSimTime = null; putAgency(agency.name, agency); saveDb(true); + emitAgencySync(req, agency, { changedSection: "director" }); res.json({ ok: true, fee: 0, agency }); return; } @@ -387,6 +415,7 @@ export function registerAgencyRoutes(router: Router): void { agency.groundedUntilSimTime = null; putAgency(agency.name, agency); saveDb(true); + emitAgencySync(req, agency, { changedSection: "director" }); res.json({ ok: true, fee, treasury: agency.treasury, agency }); }, ); diff --git a/src/server/routes/authRoutes.ts b/src/server/routes/authRoutes.ts index b826fb8..a55d335 100644 --- a/src/server/routes/authRoutes.ts +++ b/src/server/routes/authRoutes.ts @@ -2,16 +2,22 @@ import type { Response, Router } from "express"; import { type AuthedRequest, + joinAgencyByCode, loginAgency, logoutToken, registerAgency, requireAuth, } from "../auth.js"; import { clearActiveContract } from "../contracts.js"; +import { + allocateUniqueCoopJoinCode, + ensureAgencyCoopState, + getAgencyPresence, +} from "../coopPresence.js"; +import { emitToAgency } from "../events.js"; import { putAgency, saveDb } from "../store.js"; import { worldSnapshot } from "../world.js"; import { - createDefaultTeamStations, getDifficultyProfile, normalizeDifficulty, TECH_TREE, @@ -21,12 +27,18 @@ import type { DifficultyLevel } from "../../shared/types.js"; export function registerAuthRoutes(router: Router): void { router.post("/auth/register", (req, res) => { try { - const { name, password, difficulty } = (req.body ?? {}) as { + const { name, password, difficulty, callsign } = (req.body ?? {}) as { name?: string; password?: string; difficulty?: DifficultyLevel; + callsign?: string; }; - const result = registerAgency(name ?? "", password ?? "", difficulty); + const result = registerAgency( + name ?? "", + password ?? "", + difficulty, + callsign, + ); res.json(result); } catch (err) { res.status(400).json({ error: String((err as Error).message ?? err) }); @@ -34,15 +46,60 @@ export function registerAuthRoutes(router: Router): void { }); router.post("/auth/login", (req, res) => { try { - const { name, password } = (req.body ?? {}) as { + const { name, password, callsign } = (req.body ?? {}) as { name?: string; password?: string; + callsign?: string; }; - res.json(loginAgency(name ?? "", password ?? "")); + res.json(loginAgency(name ?? "", password ?? "", callsign)); } catch (err) { res.status(401).json({ error: String((err as Error).message ?? err) }); } }); + router.post("/auth/coop-join", (req, res) => { + try { + const { joinCode, callsign } = (req.body ?? {}) as { + joinCode?: string; + callsign?: string; + }; + res.json(joinAgencyByCode(joinCode ?? "", callsign ?? "")); + } catch (err) { + res.status(400).json({ error: String((err as Error).message ?? err) }); + } + }); + router.post( + "/agency/coop-code", + requireAuth, + (req: AuthedRequest, res: Response) => { + const a = req.agency!; + const presence = getAgencyPresence(a.name); + const director = a.teamStations?.director; + const directorHeldByOther = + Boolean(director?.operatorId) && + director?.operatorId !== req.operatorId && + presence.coopMode; + if (directorHeldByOther) { + res.status(403).json({ + error: `Only Flight Director (${director?.operatorName || "owner"}) can rotate the join code.`, + stationId: "director", + ownerCallsign: director?.operatorName, + }); + return; + } + a.coopJoinCode = allocateUniqueCoopJoinCode(); + putAgency(a.name, a); + saveDb(); + emitToAgency(a.name, "agency.updated", { + agency: a.name, + agencyName: a.name, + agencyState: a, + teamStations: a.teamStations, + senderOperatorId: req.operatorId, + senderCallsign: req.callsign, + }); + res.json({ ok: true, coopJoinCode: a.coopJoinCode, agency: a }); + }, + ); router.post( "/auth/logout", requireAuth, @@ -73,15 +130,22 @@ export function registerAuthRoutes(router: Router): void { : ["starter"]; dirty = true; } - if (!a.teamStations) { - a.teamStations = createDefaultTeamStations(); + if (ensureAgencyCoopState(a)) { dirty = true; } if (dirty) { putAgency(a.name, a); saveDb(); } - res.json({ account: { name: req.accountName }, agency: a }); + res.json({ + account: { name: req.accountName }, + operator: { + operatorId: req.operatorId ?? `op-legacy-${req.accountName}`, + callsign: req.callsign ?? req.accountName, + }, + agency: a, + coopPresence: getAgencyPresence(a.name), + }); }); router.get("/world", requireAuth, (_req, res) => { res.json(worldSnapshot()); diff --git a/src/server/routes/contractRoutes.ts b/src/server/routes/contractRoutes.ts index 7dd5568..537628f 100644 --- a/src/server/routes/contractRoutes.ts +++ b/src/server/routes/contractRoutes.ts @@ -11,6 +11,7 @@ import { import { emit } from "../events.js"; import { putAgency, saveDb } from "../store.js"; import type { ContractOffer } from "../../shared/types.js"; +import { emitAgencySync, requireStationAccess } from "./helpers.js"; export function registerContractRoutes(router: Router): void { router.get("/contracts", requireAuth, (req: AuthedRequest, res: Response) => { @@ -21,6 +22,7 @@ export function registerContractRoutes(router: Router): void { "/contracts/custom", requireAuth, (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "director")) return; const agency = req.agency!; if (agency.terminatedReason) { res.status(409).json({ error: agency.terminatedReason }); @@ -59,6 +61,7 @@ export function registerContractRoutes(router: Router): void { missionId: contract.id, isCustom: true, }); + emitAgencySync(req, agency, { changedSection: "director" }); res.json({ ok: true, agency, contract, advance }); }, ); @@ -66,6 +69,7 @@ export function registerContractRoutes(router: Router): void { "/contracts/:id/accept", requireAuth, (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "director")) return; const agency = req.agency!; if (agency.terminatedReason) { res.status(409).json({ error: agency.terminatedReason }); @@ -105,6 +109,7 @@ export function registerContractRoutes(router: Router): void { putAgency(agency.name, agency); saveDb(true); emit("contract.claimed", { agency: agency.name, missionId: contract.id }); + emitAgencySync(req, agency, { changedSection: "director" }); res.json({ ok: true, agency, contract, advance }); }, ); diff --git a/src/server/routes/designRoutes.ts b/src/server/routes/designRoutes.ts index bcb4494..0b8efae 100644 --- a/src/server/routes/designRoutes.ts +++ b/src/server/routes/designRoutes.ts @@ -2,8 +2,12 @@ import type { Response, Router } from "express"; import { type AuthedRequest, requireAuth } from "../auth.js"; import { MATERIALS, PARTS } from "../catalogs.js"; +import { + broadcastAgencyPresence, + ensureAgencyCoopState, + getAgencyPresence, +} from "../coopPresence.js"; import { partUnitPrice } from "../economy.js"; -import { emit } from "../events.js"; import { getWeather } from "../hazards.js"; import { deleteSharedBlueprint, @@ -13,13 +17,17 @@ import { saveDb, } from "../store.js"; import { simulateAscent } from "../../shared/ascent_sim.js"; +import { + inferTouchedStations, + mergeRocketSection, + TEAM_STATION_ORDER, +} from "../../shared/coop.js"; import { autoTuneFlightParams, buildRocket, computeDesignHash, computeDesignReliability, computeEffectivePayloadMass, - createDefaultTeamStations, decodeRocketShareCode, encodeRocketShareCode, findLockedDesignItemsDetailed, @@ -30,53 +38,103 @@ import { import type { MaturityLevel, RocketDesign, + RocketPatchSection, SavedRocketBlueprint, TeamStationId, } from "../../shared/types.js"; -import { resolveContract, validateAgencyDesign } from "./helpers.js"; +import { + emitAgencySync, + requireStationAccess, + resolveContract, + resetStationsReadyOnEdit, + validateAgencyDesign, +} from "./helpers.js"; + +const VALID_SECTIONS = new Set([ + "director", + "propulsion", + "science", + "systems", + "all", +]); + +function handleRocketSaveOrPatch(req: AuthedRequest, res: Response): void { + const raw = req.body?.design as Partial | undefined; + const rawSection = String(req.body?.section ?? "all") as RocketPatchSection; + const section: RocketPatchSection = VALID_SECTIONS.has(rawSection) + ? rawSection + : "all"; + + if (!raw || (section === "all" && !raw.stages?.length)) { + res.status(400).json({ error: "design.stages required" }); + return; + } + + try { + const agency = req.agency!; + ensureAgencyCoopState(agency); + const mergedRaw = agency.rocketDesign + ? mergeRocketSection(agency.rocketDesign, raw, section) + : (raw as RocketDesign); + if (!mergedRaw?.stages?.length) { + res.status(400).json({ error: "design.stages required" }); + return; + } + + const clean = normalizeDesign(mergedRaw, PARTS, MATERIALS); + const touchedStations = + section === "all" + ? inferTouchedStations(agency.rocketDesign ?? undefined, clean) + : [section]; + + if ( + touchedStations.length > 0 && + !requireStationAccess(req, res, touchedStations) + ) { + return; + } + + const mission = resolveContract(agency); + buildRocket(clean, PARTS, MATERIALS, { + priceOf: partUnitPrice, + mission, + difficulty: agency.difficulty, + weather: getWeather(), + unlockedTechs: agency.unlockedTechs ?? [], + }); + + agency.rocketDesign = clean; + if ( + agency.staticFiredDesignHash && + agency.staticFiredDesignHash !== computeDesignHash(clean) + ) { + agency.staticFiredDesignHash = null; + } + if (touchedStations.length > 0) { + resetStationsReadyOnEdit(agency, touchedStations); + } + + putAgency(agency.name, agency); + saveDb(true); + emitAgencySync(req, agency, { + changedSection: section, + touchedStations, + }); + res.json({ + ok: true, + design: clean, + agency, + changedSection: section, + touchedStations, + }); + } catch (err) { + res.status(400).json({ error: String((err as Error).message ?? err) }); + } +} export function registerDesignRoutes(router: Router): void { - router.post( - "/agency/rocket", - requireAuth, - (req: AuthedRequest, res: Response) => { - const raw = req.body?.design as RocketDesign | undefined; - if (!raw?.stages?.length) { - res.status(400).json({ error: "design.stages required" }); - return; - } - try { - const agency = req.agency!; - const clean = normalizeDesign(raw, PARTS, MATERIALS); - const mission = resolveContract(agency); - buildRocket(clean, PARTS, MATERIALS, { - priceOf: partUnitPrice, - mission, - difficulty: agency.difficulty, - weather: getWeather(), - unlockedTechs: agency.unlockedTechs ?? [], - }); - agency.rocketDesign = clean; - if ( - agency.staticFiredDesignHash && - agency.staticFiredDesignHash !== computeDesignHash(clean) - ) { - agency.staticFiredDesignHash = null; - } - putAgency(agency.name, agency); - saveDb(true); - emit("agency.updated", { - agency: agency.name, - sender: req.accountName, - rocketDesign: clean, - teamStations: agency.teamStations, - }); - res.json({ ok: true, design: clean }); - } catch (err) { - res.status(400).json({ error: String((err as Error).message ?? err) }); - } - }, - ); + router.post("/agency/rocket", requireAuth, handleRocketSaveOrPatch); + router.patch("/agency/rocket", requireAuth, handleRocketSaveOrPatch); router.get( "/agency/designs", requireAuth, @@ -276,46 +334,133 @@ export function registerDesignRoutes(router: Router): void { requireAuth, (req: AuthedRequest, res: Response) => { const agency = req.agency!; + ensureAgencyCoopState(agency); const stationId = String(req.body?.stationId ?? "") as TeamStationId; const def = TEAM_STATION_DEFS.find((s) => s.id === stationId); if (!def) { res.status(400).json({ error: "Unknown mission control station." }); return; } - agency.teamStations = agency.teamStations ?? createDefaultTeamStations(); - const cur = agency.teamStations[stationId]; - const operatorName = - typeof req.body?.operatorName === "string" && - req.body.operatorName.trim() - ? req.body.operatorName.trim().slice(0, 32) - : cur?.operatorName === "Unassigned" - ? req.accountName || agency.name - : cur?.operatorName || req.accountName || agency.name; - const ready = - typeof req.body?.ready === "boolean" - ? req.body.ready - : !(cur?.ready ?? false); - agency.teamStations[stationId] = { - stationId, - title: def.title, - operatorName, - ready, - updatedAt: Date.now(), - }; + + const action = String( + req.body?.action ?? + (typeof req.body?.ready === "boolean" ? "ready" : "claim"), + ); + const presence = getAgencyPresence(agency.name); + const activeIds = new Set(presence.operators.map((o) => o.operatorId)); + const cur = agency.teamStations![stationId]; + const myOpId = req.operatorId ?? `op-legacy-${req.accountName}`; + const myCallsign = req.callsign || req.accountName || agency.name; + + if (action === "claim") { + if ( + cur.operatorId && + cur.operatorId !== myOpId && + (presence.coopMode || activeIds.has(cur.operatorId)) + ) { + res.status(409).json({ + error: `${def.title} is currently operated by ${cur.operatorName || "another teammate"}.`, + code: "STATION_OCCUPIED", + stationId, + ownerCallsign: cur.operatorName, + }); + return; + } + agency.teamStations![stationId] = { + stationId, + title: def.title, + operatorId: myOpId, + operatorName: myCallsign, + ready: false, + updatedAt: Date.now(), + }; + } else if (action === "release") { + if ( + cur.operatorId && + cur.operatorId !== myOpId && + (presence.coopMode || activeIds.has(cur.operatorId)) + ) { + res.status(403).json({ + error: `Only ${cur.operatorName || "the assigned operator"} or Flight Director can release ${def.title}.`, + code: "STATION_LOCKED", + }); + return; + } + agency.teamStations![stationId] = { + stationId, + title: def.title, + operatorId: "", + operatorName: "", + ready: false, + updatedAt: Date.now(), + }; + } else if (action === "fd_release") { + const director = agency.teamStations!.director; + const dirOpId = director.operatorId; + const directorOwnedByOther = Boolean( + dirOpId && dirOpId !== myOpId && activeIds.has(dirOpId), + ); + if (directorOwnedByOther) { + res.status(403).json({ + error: `Only Flight Director (${director.operatorName || "owner"}) can force-release another station.`, + code: "STATION_LOCKED", + }); + return; + } + agency.teamStations![stationId] = { + stationId, + title: def.title, + operatorId: "", + operatorName: "", + ready: false, + updatedAt: Date.now(), + }; + } else { + // Toggle or explicitly set Ready state for claimed (or solo/unclaimed -> auto-claim). + if ( + cur.operatorId && + cur.operatorId !== myOpId && + (presence.coopMode || activeIds.has(cur.operatorId)) + ) { + res.status(403).json({ + error: `${def.title} is claimed by ${cur.operatorName || "another teammate"}.`, + code: "STATION_LOCKED", + stationId, + ownerCallsign: cur.operatorName, + }); + return; + } + const ready = + typeof req.body?.ready === "boolean" + ? req.body.ready + : !(cur?.ready ?? false); + agency.teamStations![stationId] = { + stationId, + title: def.title, + operatorId: myOpId, + operatorName: myCallsign, + ready, + updatedAt: Date.now(), + }; + } + putAgency(agency.name, agency); saveDb(true); - emit("agency.updated", { - agency: agency.name, - sender: req.accountName, + emitAgencySync(req, agency); + broadcastAgencyPresence(agency.name); + res.json({ + ok: true, teamStations: agency.teamStations, + agency, + coopPresence: getAgencyPresence(agency.name), }); - res.json({ ok: true, teamStations: agency.teamStations, agency }); }, ); router.post( "/agency/flight-params", requireAuth, (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "propulsion")) return; const agency = req.agency!; if (!agency.rocketDesign) { res @@ -334,15 +479,18 @@ export function registerDesignRoutes(router: Router): void { MATERIALS, ); agency.rocketDesign = updated; + resetStationsReadyOnEdit(agency, ["propulsion"]); putAgency(agency.name, agency); saveDb(true); - res.json({ ok: true, flightParams: updated.flightParams }); + emitAgencySync(req, agency, { changedSection: "propulsion" }); + res.json({ ok: true, flightParams: updated.flightParams, agency }); }, ); router.post( "/agency/maturity", requireAuth, (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "systems")) return; const agency = req.agency!; if (!agency.rocketDesign) { res.status(400).json({ error: "No rocket design saved." }); @@ -377,15 +525,18 @@ export function registerDesignRoutes(router: Router): void { return; } agency.rocketDesign.maturity = targetMaturity; + resetStationsReadyOnEdit(agency, ["systems"]); putAgency(agency.name, agency); saveDb(true); - res.json({ ok: true, maturity: targetMaturity, validation: val }); + emitAgencySync(req, agency, { changedSection: "systems" }); + res.json({ ok: true, maturity: targetMaturity, validation: val, agency }); }, ); router.post( "/agency/autotune", requireAuth, (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "propulsion")) return; const agency = req.agency!; if (!agency.rocketDesign) { res @@ -415,8 +566,10 @@ export function registerDesignRoutes(router: Router): void { const tuned = autoTuneFlightParams(design, assembly, effectiveMission); design.flightParams = tuned; agency.rocketDesign = design; + resetStationsReadyOnEdit(agency, ["propulsion"]); putAgency(agency.name, agency); saveDb(true); + emitAgencySync(req, agency, { changedSection: "propulsion" }); const reliability = computeDesignReliability(design, assembly, agency); const preview = simulateAscent(design, PARTS, MATERIALS, { weather: getWeather(), diff --git a/src/server/routes/helpers.ts b/src/server/routes/helpers.ts index 6e20b05..df33427 100644 --- a/src/server/routes/helpers.ts +++ b/src/server/routes/helpers.ts @@ -1,8 +1,11 @@ // Self explanatory. +import type { Response } from "express"; import { type AuthedRequest } from "../auth.js"; import { MATERIALS, MISSIONS, PARTS, SPONSORS } from "../catalogs.js"; import { deriveContract } from "../contracts.js"; +import { ensureAgencyCoopState, getAgencyPresence } from "../coopPresence.js"; import { partUnitPrice } from "../economy.js"; +import { emitToAgency } from "../events.js"; import { getActiveHazards, getSimTime, getWeather } from "../hazards.js"; import { buildRocket, @@ -16,6 +19,7 @@ import type { AgencyState, ContractOffer, RocketDesign, + TeamStationId, } from "../../shared/types.js"; export function validateAgencyDesign( @@ -97,3 +101,74 @@ export function resolveContract( const contractorId = wanted.includes(":") ? wanted.split(":")[0] : undefined; return deriveContract(agency, tpl, contractorId); } + +/** + * Enforce station locking in co-op: + * - Solo (`activeCount <= 1` and station not claimed by another operator): unlocked. + * - Co-op: unclaimed or owned by `req.operatorId` is allowed; claimed by another active operator returns 403. + */ +export function requireStationAccess( + req: AuthedRequest, + res: Response, + stations: TeamStationId | TeamStationId[], +): boolean { + const agency = req.agency!; + ensureAgencyCoopState(agency); + const presence = getAgencyPresence(agency.name); + const activeIds = new Set(presence.operators.map((o) => o.operatorId)); + const list = Array.isArray(stations) ? stations : [stations]; + + for (const stationId of list) { + const st = agency.teamStations?.[stationId]; + if (!st?.operatorId) continue; + if (st.operatorId === req.operatorId) continue; + const ownerOnline = activeIds.has(st.operatorId); + if (!presence.coopMode && !ownerOnline) continue; + res.status(403).json({ + error: `Station "${st.title}" is locked to ${st.operatorName || "another operator"}.`, + code: "STATION_LOCKED", + stationId, + ownerCallsign: st.operatorName || "Operator", + }); + return false; + } + return true; +} + +/** Clear `ready` flag on stations after their domain parameters change so crew re-confirms Go/No-Go. */ +export function resetStationsReadyOnEdit( + agency: AgencyState, + stations: TeamStationId[], +): boolean { + if (!agency.teamStations) return false; + let changed = false; + const now = Date.now(); + for (const stationId of stations) { + const st = agency.teamStations[stationId]; + if (st && st.ready) { + st.ready = false; + st.updatedAt = now; + changed = true; + } + } + return changed; +} + +/** Broadcast full agency sync state exclusively to online teammates of this agency. */ +export function emitAgencySync( + req: AuthedRequest, + agency: AgencyState, + extra: Record = {}, +): void { + emitToAgency(agency.name, "agency.updated", { + agency: agency.name, + agencyName: agency.name, + agencyState: agency, + rocketDesign: agency.rocketDesign, + teamStations: agency.teamStations, + senderOperatorId: req.operatorId, + senderCallsign: req.callsign, + sender: req.callsign ?? req.accountName, + ...extra, + }); +} diff --git a/src/server/routes/missionRoutes.ts b/src/server/routes/missionRoutes.ts index 2df495b..3b6c103 100644 --- a/src/server/routes/missionRoutes.ts +++ b/src/server/routes/missionRoutes.ts @@ -10,12 +10,21 @@ import { getActiveHazards, getSimTime, getWeather } from "../hazards.js"; import { settleMissionOutcome } from "../settlement.js"; import { findActiveMission, putAgency, saveDb } from "../store.js"; import { simulateAscent } from "../../shared/ascent_sim.js"; +import { getAgencyPresence } from "../coopPresence.js"; +import { emitToAgency } from "../events.js"; +import { TEAM_STATION_ORDER } from "../../shared/coop.js"; import { generateCoachDiagnostics, getDifficultyProfile, } from "../../shared/physics.js"; import type { ActiveMission, RocketDesign } from "../../shared/types.js"; -import { resolveContract, validateAgencyDesign } from "./helpers.js"; +import { + emitAgencySync, + requireStationAccess, + resetStationsReadyOnEdit, + resolveContract, + validateAgencyDesign, +} from "./helpers.js"; export function registerMissionRoutes(router: Router): void { router.post("/simulate", requireAuth, (req: AuthedRequest, res: Response) => { @@ -38,6 +47,7 @@ export function registerMissionRoutes(router: Router): void { agency.treasury -= testFee; putAgency(agency.name, agency); saveDb(); + emitAgencySync(req, agency); } const result = simulateAscent(design, PARTS, MATERIALS, { weather: getWeather(), @@ -83,7 +93,40 @@ export function registerMissionRoutes(router: Router): void { "/mission/launch", requireAuth, async (req: AuthedRequest, res: Response) => { + if (!requireStationAccess(req, res, "director")) return; const agency = req.agency!; + const presence = getAgencyPresence(agency.name); + const overrideReady = Boolean(req.body?.overrideReady); + if (agency.teamStations) { + const unreadyStations: Array<{ + stationId: string; + title: string; + operatorName: string; + }> = []; + for (const id of TEAM_STATION_ORDER) { + const st = agency.teamStations[id]; + if (!st?.operatorId) continue; + const isSelfDirector = + id === "director" && st.operatorId === req.operatorId; + if (isSelfDirector) continue; + const heldByTeammate = st.operatorId !== req.operatorId; + if ((presence.coopMode || heldByTeammate) && !st.ready) { + unreadyStations.push({ + stationId: st.stationId, + title: st.title, + operatorName: st.operatorName || "Operator", + }); + } + } + if (unreadyStations.length > 0 && !overrideReady) { + res.status(409).json({ + error: `Waiting for Go/No-Go Ready check from: ${unreadyStations.map((u) => `${u.title} (${u.operatorName})`).join(", ")}.`, + code: "STATIONS_NOT_READY", + unreadyStations, + }); + return; + } + } if (agency.terminatedReason) { res.status(409).json({ error: agency.terminatedReason }); return; @@ -199,6 +242,7 @@ export function registerMissionRoutes(router: Router): void { const settlement = settleMissionOutcome(agency, active, nowSim); clearActiveContract(agency); agency.activeMissions = ascent.success ? [active] : []; + resetStationsReadyOnEdit(agency, TEAM_STATION_ORDER); putAgency(agency.name, agency); saveDb(true); emit("mission.launched", { @@ -207,6 +251,20 @@ export function registerMissionRoutes(router: Router): void { missionId: contract.id, target: contract.target, }); + emitAgencySync(req, agency, { changedSection: "director" }); + emitToAgency(agency.name, "coop.mission_launched", { + missionId: active.id, + mission: active, + settlement, + contract, + flightParams: design.flightParams, + rocketDesign: design, + remainingTreasury: agency.treasury, + launchedByOperatorId: req.operatorId, + launchedByCallsign: req.callsign, + overrideUsed: overrideReady, + agencyState: agency, + }); res.json({ ok: true, mission: active, diff --git a/src/server/store.ts b/src/server/store.ts index 3137672..aca342a 100644 --- a/src/server/store.ts +++ b/src/server/store.ts @@ -3,6 +3,7 @@ import fs from "node:fs"; import path from "node:path"; import { config } from "./config.js"; +import { normalizeJoinCode } from "../shared/coop.js"; import type { ActiveMission, AgencyState, @@ -18,6 +19,8 @@ export interface AccountRecord { export interface TokenRecord { name: string; + operatorId?: string; + callsign?: string; createdAt: number; } @@ -203,6 +206,21 @@ export function listAgencies(): AgencyState[] { return Object.values(db.agencies); } +export function findAgencyByJoinCode(rawCode: string): AgencyState | null { + const code = normalizeJoinCode(rawCode); + if (!code) return null; + for (const agency of Object.values(db.agencies)) { + if (agency.isAI) continue; + if ( + agency.coopJoinCode && + normalizeJoinCode(agency.coopJoinCode) === code + ) { + return agency; + } + } + return null; +} + export function getTokenRecord(token: string): TokenRecord | null { return db.tokens[token] ?? null; } diff --git a/src/shared/coop.ts b/src/shared/coop.ts new file mode 100644 index 0000000..8a002ac --- /dev/null +++ b/src/shared/coop.ts @@ -0,0 +1,235 @@ +// Shared co-op helpers: join code normalization, station defaults, domain locking map, and section-scoped design merging. +import { TEAM_STATION_DEFS } from "./physics/spacecraftCatalogs.js"; +import type { RocketDesign } from "./types/design.js"; +import type { + RocketPatchSection, + SpacecraftConfig, + TeamStationAssignment, + TeamStationId, +} from "./types/spacecraft.js"; + +const JOIN_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + +export const TEAM_STATION_ORDER: TeamStationId[] = [ + "director", + "propulsion", + "science", + "systems", +]; + +export const STATION_DOMAIN_HINTS: Record = { + director: "Contracts, Budget, Rocket Tier/Name, Waivers & Launch", + propulsion: "Stages, Engines, Tanks, Pro Parts & Flight Profile", + science: "Fairing, Payload, LAS, Power, Instruments & Crew", + systems: "Avionics Computer, Comms, Ground Net, Maturity & Static Fire", +}; + +/** Generate an unambiguous 6-character uppercase alphanumeric co-op join code. */ +export function generateCoopJoinCode(length = 6): string { + let code = ""; + for (let i = 0; i < length; i++) { + const idx = Math.floor(Math.random() * JOIN_CODE_ALPHABET.length); + code += JOIN_CODE_ALPHABET[idx]; + } + return code; +} + +/** Normalize user-entered join codes (strip non-alphanumeric whitespace/hyphens, uppercase). */ +export function normalizeJoinCode(raw: unknown): string { + if (typeof raw !== "string") return ""; + return raw + .trim() + .toUpperCase() + .replace(/[^A-Z0-9]/g, ""); +} + +/** Normalize operator callsign for mission control telemetry and station headers. */ +export function normalizeCallsign(raw: unknown, fallback = "Operator"): string { + if (typeof raw !== "string") return fallback; + const cleaned = raw.trim().replace(/\s+/g, " ").slice(0, 24); + return cleaned || fallback; +} + +/** Ensure every station entry exists with valid structure (preserving legacy saves). */ +export function normalizeTeamStations( + raw?: Partial>>, +): Record { + const out = {} as Record; + for (const def of TEAM_STATION_DEFS) { + const existing = raw?.[def.id]; + out[def.id] = { + stationId: def.id, + title: existing?.title || def.title, + operatorId: existing?.operatorId ?? "", + operatorName: existing?.operatorName ?? "", + ready: Boolean(existing?.ready), + updatedAt: Number(existing?.updatedAt) || 0, + }; + } + return out; +} + +function canonicalStringify(value: unknown): string { + if (value === null || value === undefined) return String(value); + if (typeof value !== "object") return JSON.stringify(value); + if (Array.isArray(value)) { + return `[${value.map((item) => canonicalStringify(item)).join(",")}]`; + } + const entries = Object.entries(value as Record) + .filter(([, v]) => v !== undefined) + .sort(([a], [b]) => a.localeCompare(b)); + return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalStringify(v)}`).join(",")}}`; +} + +function mergeSpacecraftSection( + base: SpacecraftConfig | undefined, + incoming: SpacecraftConfig | undefined, + section: TeamStationId, +): SpacecraftConfig | undefined { + if (!base && !incoming) return undefined; + const seed: SpacecraftConfig = { + powerSystemId: base?.powerSystemId ?? incoming?.powerSystemId ?? "", + commsSystemId: base?.commsSystemId ?? incoming?.commsSystemId ?? "", + groundNetworkTier: base?.groundNetworkTier ?? incoming?.groundNetworkTier, + instrumentIds: [...(base?.instrumentIds ?? incoming?.instrumentIds ?? [])], + missionLifetimeYears: + base?.missionLifetimeYears ?? incoming?.missionLifetimeYears ?? 1, + }; + if (!incoming) return seed; + + if (section === "science") { + return { + ...seed, + powerSystemId: incoming.powerSystemId ?? seed.powerSystemId, + instrumentIds: Array.isArray(incoming.instrumentIds) + ? [...incoming.instrumentIds] + : seed.instrumentIds, + missionLifetimeYears: + incoming.missionLifetimeYears ?? seed.missionLifetimeYears, + }; + } + if (section === "systems") { + return { + ...seed, + commsSystemId: incoming.commsSystemId ?? seed.commsSystemId, + groundNetworkTier: incoming.groundNetworkTier ?? seed.groundNetworkTier, + }; + } + return seed; +} + +function extractDomainSlice( + design: RocketDesign, + station: TeamStationId, +): unknown { + const sc = design.spacecraftConfig; + switch (station) { + case "director": + return { + name: design.name, + designTier: design.designTier, + waivedRuleIds: design.waivedRuleIds ?? [], + }; + case "propulsion": + return { + stages: design.stages, + flightParams: design.flightParams, + proParts: design.proParts ?? [], + customMeshName: design.customMeshName ?? "", + }; + case "science": + return { + fairingId: design.fairingId, + payloadPartId: design.payloadPartId ?? null, + payloadMass: design.payloadMass, + hasLaunchAbort: Boolean(design.hasLaunchAbort), + powerSystemId: sc?.powerSystemId ?? "", + instrumentIds: sc?.instrumentIds ?? [], + missionLifetimeYears: sc?.missionLifetimeYears ?? 1, + }; + case "systems": + return { + computerId: design.computerId ?? "", + maturity: design.maturity, + commsSystemId: sc?.commsSystemId ?? "", + groundNetworkTier: sc?.groundNetworkTier ?? "", + }; + } +} + +/** Return the list of station domains whose owned fields differ between base and incoming designs. */ +export function inferTouchedStations( + base: RocketDesign | undefined, + incoming: RocketDesign, +): TeamStationId[] { + if (!base) return [...TEAM_STATION_ORDER]; + const touched: TeamStationId[] = []; + for (const stationId of TEAM_STATION_ORDER) { + const a = canonicalStringify(extractDomainSlice(base, stationId)); + const b = canonicalStringify(extractDomainSlice(incoming, stationId)); + if (a !== b) touched.push(stationId); + } + return touched; +} + +/** Merge only the fields owned by `section` from `incoming` onto `base`, preventing cross-station clobbering. */ +export function mergeRocketSection( + base: RocketDesign, + incoming: Partial, + section: RocketPatchSection, +): RocketDesign { + if (section === "all") { + return structuredClone(incoming as RocketDesign); + } + const next = structuredClone(base); + if (section === "director") { + if (typeof incoming.name === "string") next.name = incoming.name; + if (incoming.designTier !== undefined) + next.designTier = incoming.designTier; + if (incoming.waivedRuleIds !== undefined) + next.waivedRuleIds = [...incoming.waivedRuleIds]; + return next; + } + if (section === "propulsion") { + if (Array.isArray(incoming.stages)) + next.stages = structuredClone(incoming.stages); + if (incoming.flightParams) + next.flightParams = structuredClone(incoming.flightParams); + if (incoming.proParts !== undefined) + next.proParts = structuredClone(incoming.proParts); + if (incoming.customMeshName !== undefined) + next.customMeshName = incoming.customMeshName; + return next; + } + if (section === "science") { + if (incoming.fairingId !== undefined) next.fairingId = incoming.fairingId; + if (incoming.payloadPartId !== undefined) + next.payloadPartId = incoming.payloadPartId; + if (typeof incoming.payloadMass === "number") + next.payloadMass = incoming.payloadMass; + if (incoming.hasLaunchAbort !== undefined) + next.hasLaunchAbort = incoming.hasLaunchAbort; + if (incoming.spacecraftConfig !== undefined) { + next.spacecraftConfig = mergeSpacecraftSection( + next.spacecraftConfig, + incoming.spacecraftConfig, + "science", + ); + } + return next; + } + if (section === "systems") { + if (incoming.computerId !== undefined) + next.computerId = incoming.computerId; + if (incoming.maturity !== undefined) next.maturity = incoming.maturity; + if (incoming.spacecraftConfig !== undefined) { + next.spacecraftConfig = mergeSpacecraftSection( + next.spacecraftConfig, + incoming.spacecraftConfig, + "systems", + ); + } + return next; + } + return next; +} diff --git a/src/shared/types/agency.ts b/src/shared/types/agency.ts index 2ac293b..7f2541d 100644 --- a/src/shared/types/agency.ts +++ b/src/shared/types/agency.ts @@ -82,6 +82,7 @@ export interface AgencyState { lastSettlement?: MissionSettlement | null; terminatedReason?: string | null; teamStations?: Record; + coopJoinCode?: string; savedDesigns?: SavedRocketBlueprint[]; isAI?: boolean; aiType?: "standard" | "ml"; diff --git a/src/shared/types/spacecraft.ts b/src/shared/types/spacecraft.ts index 7263c05..8395b62 100644 --- a/src/shared/types/spacecraft.ts +++ b/src/shared/types/spacecraft.ts @@ -125,10 +125,28 @@ export interface ContractValueEstimate { export type TeamStationId = "director" | "propulsion" | "science" | "systems"; +export type RocketPatchSection = + "director" | "propulsion" | "science" | "systems" | "all"; + export interface TeamStationAssignment { stationId: TeamStationId; title: string; + operatorId?: string; operatorName: string; ready: boolean; updatedAt: number; } + +export interface CoopOperatorPresence { + operatorId: string; + callsign: string; + connectedAt: number; + lastSeenAt: number; + stations: TeamStationId[]; +} + +export interface CoopStateSnapshot { + operators: CoopOperatorPresence[]; + activeCount: number; + coopMode: boolean; +}