- Fix Readme
- Fix co-op so it actually works
This commit is contained in:
parent
d2645e6a26
commit
2642552891
45 changed files with 5069 additions and 1225 deletions
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -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<T = any>(
|
|||
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<T>("GET", url, undefined, auth),
|
||||
post: <T = any>(url: string, body: unknown, auth = true) =>
|
||||
request<T>("POST", url, body, auth),
|
||||
patch: <T = any>(url: string, body: unknown, auth = true) =>
|
||||
request<T>("PATCH", url, body, auth),
|
||||
delete: <T = any>(url: string, auth = true) =>
|
||||
request<T>("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<TeamStationId, TeamStationAssignment>;
|
||||
agency: AgencyState;
|
||||
coopPresence: CoopStateSnapshot;
|
||||
}>("POST", "/api/agency/station", payload, true),
|
||||
patchRocketSection: (
|
||||
section: RocketPatchSection,
|
||||
design: Partial<RocketDesign>,
|
||||
) =>
|
||||
request<{
|
||||
ok: boolean;
|
||||
design: RocketDesign;
|
||||
agency: AgencyState;
|
||||
changedSection: RocketPatchSection;
|
||||
}>("PATCH", "/api/agency/rocket", { section, design }, true),
|
||||
getMlStatus: () => request<any>("GET", "/api/ml-status", undefined, false),
|
||||
toggleMlBridge: (enabled?: boolean) =>
|
||||
request<any>("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;
|
||||
|
|
|
|||
|
|
@ -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<void> {
|
|||
} 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<void> {
|
|||
}
|
||||
}
|
||||
}
|
||||
if (joinParam) {
|
||||
state.pendingJoinCode = normalizeJoinCode(joinParam);
|
||||
clearTabToken();
|
||||
await readyPromise;
|
||||
navigate("auth");
|
||||
return;
|
||||
}
|
||||
await refreshMe();
|
||||
if (state.agency) {
|
||||
await refreshWorld();
|
||||
|
|
|
|||
|
|
@ -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<Record<ScreenName, ScreenRenderer>> = {};
|
||||
|
||||
const RIGHT_SIDEBAR_OFFSET_PX: Partial<Record<ScreenName, number>> = {
|
||||
|
|
@ -20,6 +21,35 @@ const RIGHT_SIDEBAR_OFFSET_PX: Partial<Record<ScreenName, number>> = {
|
|||
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<HTMLElement>(
|
||||
".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<Record<ScreenName, ScreenRenderer>>,
|
||||
): 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 } }),
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -92,6 +92,8 @@ export interface BuilderContext {
|
|||
latestReliability: DesignReliabilityReport | null;
|
||||
latestValueEstimate: ContractValueEstimate | null;
|
||||
latestCoach: CoachDiagnostic[];
|
||||
suppressSync: boolean;
|
||||
syncOwnedSectionsNow: () => Promise<void>;
|
||||
refreshEngineering: (refitCamera?: boolean, immediate?: boolean) => void;
|
||||
renderSidebarBody: () => void;
|
||||
renderAll: () => void;
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
renderCoopMissionBar(ctx.coopBar, {
|
||||
compact: true,
|
||||
onStationChanged: () => ctx.renderAll(),
|
||||
});
|
||||
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 ? "✓" : "○"}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,8 +265,7 @@ export function renderPayloadTab(ctx: BuilderContext): void {
|
|||
ctx.refreshEngineering(false, false);
|
||||
},
|
||||
});
|
||||
bodyEl.appendChild(
|
||||
h(
|
||||
const proPayloadCard = h(
|
||||
"div",
|
||||
{ class: "stage-card active" },
|
||||
h("h3", {}, "Pro Payload & Mission Mass"),
|
||||
|
|
@ -276,8 +282,11 @@ export function renderPayloadTab(ctx: BuilderContext): void {
|
|||
`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,8 +352,7 @@ export function renderPayloadTab(ctx: BuilderContext): void {
|
|||
ctx.refreshEngineering(false, false);
|
||||
},
|
||||
});
|
||||
bodyEl.appendChild(
|
||||
h(
|
||||
const fairingPayloadCard = h(
|
||||
"div",
|
||||
{ class: "stage-card active" },
|
||||
h("h3", {}, "Fairing & NASA Spacecraft Integration"),
|
||||
|
|
@ -398,8 +406,11 @@ export function renderPayloadTab(ctx: BuilderContext): void {
|
|||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const sciStdLock = renderStationLockBanner("science");
|
||||
if (sciStdLock) fairingPayloadCard.prepend(sciStdLock);
|
||||
applyStationControlLock(fairingPayloadCard, "science");
|
||||
bodyEl.appendChild(fairingPayloadCard);
|
||||
renderSpacecraftBusSection(ctx);
|
||||
}
|
||||
|
||||
|
|
@ -540,10 +551,56 @@ export function renderSpacecraftBusSection(ctx: BuilderContext): void {
|
|||
);
|
||||
}),
|
||||
);
|
||||
bodyEl.appendChild(
|
||||
const pwrGroup = h(
|
||||
"div",
|
||||
{ class: "slot-group" },
|
||||
h(
|
||||
"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" },
|
||||
|
|
@ -558,46 +615,10 @@ export function renderSpacecraftBusSection(ctx: BuilderContext): void {
|
|||
`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,
|
||||
),
|
||||
),
|
||||
pwrGroup,
|
||||
commGroup,
|
||||
netGroup,
|
||||
lifeGroup,
|
||||
h(
|
||||
"div",
|
||||
{ class: "slot-title", style: { marginTop: "4px" } },
|
||||
|
|
@ -728,6 +749,6 @@ export function renderSpacecraftBusSection(ctx: BuilderContext): void {
|
|||
),
|
||||
),
|
||||
instList,
|
||||
),
|
||||
);
|
||||
bodyEl.appendChild(busCard);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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<SimResult>("/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) {
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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<void> {
|
||||
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);
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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,19 +196,40 @@ 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: "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" } },
|
||||
hasRocket
|
||||
liveHasRocket
|
||||
? h(
|
||||
"div",
|
||||
{ class: "mono", style: { fontSize: "11px" } },
|
||||
`Pad Vehicle: ${agency.rocketDesign!.name} (${agency.rocketDesign!.stages.length} stage${agency.rocketDesign!.stages.length > 1 ? "s" : ""}) • Maturity: `,
|
||||
`Pad Vehicle: ${liveAgency.rocketDesign!.name} (${liveAgency.rocketDesign!.stages.length} stage${liveAgency.rocketDesign!.stages.length > 1 ? "s" : ""}) • Maturity: `,
|
||||
h(
|
||||
"span",
|
||||
{ class: "accent" },
|
||||
agency.rocketDesign!.maturity.toUpperCase(),
|
||||
liveAgency.rocketDesign!.maturity.toUpperCase(),
|
||||
),
|
||||
)
|
||||
: h(
|
||||
|
|
@ -215,71 +237,80 @@ export function renderDashboard(root: HTMLElement): () => void {
|
|||
{ 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);
|
||||
};
|
||||
|
||||
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 = agency.bailoutsTaken ?? 0;
|
||||
const bailoutsUsed = liveAgency.bailoutsTaken ?? 0;
|
||||
const bailoutsRem = Math.max(0, profile.maxBailouts - bailoutsUsed);
|
||||
const unlockedSet = new Set(agency.unlockedTechs ?? ["starter"]);
|
||||
const unlockedSet = new Set(liveAgency.unlockedTechs ?? ["starter"]);
|
||||
const padDamagedRem = Math.max(
|
||||
0,
|
||||
Math.ceil((agency.padDamagedUntilSimTime ?? 0) - nowSim),
|
||||
Math.ceil((liveAgency.padDamagedUntilSimTime ?? 0) - nowSim),
|
||||
);
|
||||
const groundedRem = Math.max(
|
||||
0,
|
||||
Math.ceil((agency.groundedUntilSimTime ?? 0) - nowSim),
|
||||
Math.ceil((liveAgency.groundedUntilSimTime ?? 0) - nowSim),
|
||||
);
|
||||
let validationSummary: ReturnType<typeof validateDesign> | null = null;
|
||||
let hasLockedDesignParts = false;
|
||||
if (hasRocket && agency.rocketDesign) {
|
||||
if (liveHasRocket && liveAgency.rocketDesign) {
|
||||
try {
|
||||
validationSummary = validateDesign(
|
||||
agency.rocketDesign,
|
||||
liveAgency.rocketDesign,
|
||||
state.parts,
|
||||
state.materials,
|
||||
{
|
||||
mission: contract,
|
||||
mission: liveContract,
|
||||
simTime: state.world?.simTime ?? 0,
|
||||
weather,
|
||||
weather: liveWeather,
|
||||
activeHazards: state.world?.activeHazards ?? [],
|
||||
unlockedTechs: agency.unlockedTechs ?? [],
|
||||
difficulty: agency.difficulty,
|
||||
crewedSeats: agency.crewConfig?.crewSize ?? 0,
|
||||
eclssLevel: agency.crewConfig?.lifeSupport ?? 0,
|
||||
unlockedTechs: liveAgency.unlockedTechs ?? [],
|
||||
difficulty: liveAgency.difficulty,
|
||||
crewedSeats: liveAgency.crewConfig?.crewSize ?? 0,
|
||||
eclssLevel: liveAgency.crewConfig?.lifeSupport ?? 0,
|
||||
},
|
||||
);
|
||||
hasLockedDesignParts =
|
||||
agency.rocketDesign.stages.some(
|
||||
liveAgency.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)) ||
|
||||
!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, agency)),
|
||||
!isPartUnlocked(st.dropTankId, liveAgency)),
|
||||
) ||
|
||||
!isPartUnlocked(agency.rocketDesign.fairingId, agency) ||
|
||||
(!!agency.rocketDesign.computerId &&
|
||||
!isPartUnlocked(agency.rocketDesign.computerId, agency)) ||
|
||||
(agency.rocketDesign.proParts ?? []).some(
|
||||
!isPartUnlocked(liveAgency.rocketDesign.fairingId, liveAgency) ||
|
||||
(!!liveAgency.rocketDesign.computerId &&
|
||||
!isPartUnlocked(liveAgency.rocketDesign.computerId, liveAgency)) ||
|
||||
(liveAgency.rocketDesign.proParts ?? []).some(
|
||||
(pp) =>
|
||||
!isPartUnlocked(pp.partId, agency) ||
|
||||
(!!pp.materialId && !isPartUnlocked(pp.materialId, agency)),
|
||||
!isPartUnlocked(pp.partId, liveAgency) ||
|
||||
(!!pp.materialId && !isPartUnlocked(pp.materialId, liveAgency)),
|
||||
);
|
||||
} catch {
|
||||
validationSummary = null;
|
||||
}
|
||||
}
|
||||
const flights = createFlightsPanel();
|
||||
refreshFlightsRef = flights.renderFlights;
|
||||
const deps: DashboardSidebarDeps = {
|
||||
agency,
|
||||
contract,
|
||||
weather,
|
||||
agency: liveAgency,
|
||||
contract: liveContract,
|
||||
weather: liveWeather,
|
||||
profile,
|
||||
unlockedSet,
|
||||
bailoutsRem,
|
||||
|
|
@ -294,9 +325,9 @@ export function renderDashboard(root: HTMLElement): () => void {
|
|||
const { agencyStatsPanel, contractPanel } =
|
||||
createTelemetryAndContractCards(deps);
|
||||
const hazardPanel = createHazardPanel();
|
||||
const lastSettlementCard = createLastSettlementCard(agency);
|
||||
const lastSettlementCard = createLastSettlementCard(liveAgency);
|
||||
const navGrid = createNavGrid(deps);
|
||||
const tutorialOfferBanner = shouldShowFirstRunTutorialOffer(agency)
|
||||
const tutorialOfferBanner = shouldShowFirstRunTutorialOffer(liveAgency)
|
||||
? h(
|
||||
"div",
|
||||
{
|
||||
|
|
@ -354,6 +385,7 @@ export function renderDashboard(root: HTMLElement): () => void {
|
|||
),
|
||||
)
|
||||
: null;
|
||||
clear(sidebarEl);
|
||||
if (terminatedBanner) sidebarEl.appendChild(terminatedBanner);
|
||||
if (standdownBanner) sidebarEl.appendChild(standdownBanner);
|
||||
if (bailoutBanner) sidebarEl.appendChild(bailoutBanner);
|
||||
|
|
@ -362,14 +394,30 @@ export function renderDashboard(root: HTMLElement): () => void {
|
|||
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();
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 () => {
|
||||
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",
|
||||
{},
|
||||
);
|
||||
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,6 +430,8 @@ export function createNavGrid(deps: DashboardSidebarDeps): HTMLElement {
|
|||
agency.treasury >= (validationSummary?.totalMissionCost ?? 0);
|
||||
const launchBtnLabel = hasActiveOwnFlight
|
||||
? "Mission In Flight — Spectate"
|
||||
: directorLock.lockedByOther
|
||||
? `Launch Locked (${directorLock.ownerCallsign ?? "FD"})`
|
||||
: padDamagedRem > 0 || groundedRem > 0
|
||||
? "Launch Stand-Down Active"
|
||||
: canLaunch
|
||||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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<string>): 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<string>): void {
|
|||
{
|
||||
class: "btn xs primary",
|
||||
disabled:
|
||||
directorLocked ||
|
||||
!repMet ||
|
||||
agency!.treasury < node.cost ||
|
||||
!!agency!.terminatedReason,
|
||||
|
|
|
|||
|
|
@ -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<{
|
||||
const attemptDirectLaunch = (overrideReady = false) =>
|
||||
api.post<{
|
||||
ok: boolean;
|
||||
mission: ActiveMission;
|
||||
settlement?: MissionSettlement;
|
||||
remainingTreasury: number;
|
||||
agency?: AgencyState;
|
||||
}>("/api/mission/launch", {});
|
||||
}>(
|
||||
"/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();
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
},
|
||||
},
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
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,17 +345,16 @@ export function renderMissionConfig(root: HTMLElement): () => void {
|
|||
"ratio",
|
||||
"meco_seco",
|
||||
),
|
||||
h(
|
||||
);
|
||||
const crewLockHost = h("div");
|
||||
const crewControlsBox = h(
|
||||
"div",
|
||||
{ class: "slot-group" },
|
||||
crewLockHost,
|
||||
h(
|
||||
"div",
|
||||
{ class: "spread" },
|
||||
h(
|
||||
"span",
|
||||
{ class: "slot-title" },
|
||||
term("Crew Complement", "crew_eclss"),
|
||||
),
|
||||
h("span", { class: "slot-title" }, term("Crew Complement", "crew_eclss")),
|
||||
crewVal,
|
||||
),
|
||||
crewSizeInput,
|
||||
|
|
@ -341,46 +369,126 @@ export function renderMissionConfig(root: HTMLElement): () => void {
|
|||
eclssVal,
|
||||
),
|
||||
eclssInput,
|
||||
),
|
||||
h(
|
||||
"div",
|
||||
{ class: "row", style: { marginTop: "auto", paddingTop: "8px" } },
|
||||
h(
|
||||
);
|
||||
const saveProfileBtn = h(
|
||||
"button",
|
||||
{
|
||||
class: "btn sm ghost",
|
||||
onClick: async () => {
|
||||
try {
|
||||
if (await saveParameters())
|
||||
toast("Flight parameters & ECLSS saved.", "ok");
|
||||
toast("Owned parameter domain saved.", "ok");
|
||||
} catch (err) {
|
||||
toast((err as Error).message, "err");
|
||||
}
|
||||
},
|
||||
},
|
||||
"Save Profile",
|
||||
),
|
||||
h(
|
||||
) as HTMLButtonElement;
|
||||
const proceedPadBtn = h(
|
||||
"button",
|
||||
{
|
||||
class: "btn sm primary grow",
|
||||
onClick: async () => {
|
||||
try {
|
||||
if (await saveParameters()) navigate("launch");
|
||||
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" } },
|
||||
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);
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<{
|
||||
|
|
|
|||
|
|
@ -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<TeamStationId, ReturnType<typeof setTimeout>>();
|
||||
const lastToastAtBySender = new Map<string, number>();
|
||||
|
||||
async function syncSectionNow(section: TeamStationId): Promise<void> {
|
||||
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<void> {
|
||||
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,13 +396,14 @@ 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(
|
||||
h(
|
||||
const nameRow = h(
|
||||
"div",
|
||||
{ class: "row", style: { alignItems: "flex-end" } },
|
||||
h("label", { class: "field grow" }, "Vehicle Designation", nameInput),
|
||||
|
|
@ -327,12 +441,21 @@ export function renderRocketBuilder(root: HTMLElement): () => void {
|
|||
},
|
||||
"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<Record<string, any>>).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) {
|
||||
|
|
|
|||
|
|
@ -43,6 +43,9 @@ export function renderWorldMap(root: HTMLElement): () => void {
|
|||
solar = solarSystem;
|
||||
view.scene.add(solarSystem.group);
|
||||
viewportEl.appendChild(
|
||||
h(
|
||||
"div",
|
||||
{ class: "viewport-hud" },
|
||||
h(
|
||||
"div",
|
||||
{ class: "dash-header" },
|
||||
|
|
@ -98,6 +101,7 @@ export function renderWorldMap(root: HTMLElement): () => void {
|
|||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const assetPreviewBox = h("div", {
|
||||
class: "onboard-preview-box",
|
||||
|
|
|
|||
|
|
@ -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<void> {
|
||||
|
|
@ -44,10 +51,14 @@ export async function refreshMe(): Promise<AgencyState | null> {
|
|||
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<ContractOffer[]>("/api/contracts", true);
|
||||
} catch {}
|
||||
|
|
@ -56,7 +67,9 @@ export async function refreshMe(): Promise<AgencyState | null> {
|
|||
} 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,14 +210,81 @@ 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) {
|
||||
} 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 }));
|
||||
if (!incomingAgency && !isSelfEcho) {
|
||||
void refreshMe().then(() => {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("sgywftp:agency-sync", { detail: d }),
|
||||
|
|
@ -206,10 +292,23 @@ function handleLiveEvent(ev: {
|
|||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<RocketPatchSection>;
|
||||
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 {
|
||||
|
|
|
|||
|
|
@ -27,21 +27,21 @@ export interface PresetDescriptor<T extends string> {
|
|||
}
|
||||
|
||||
export const SHAPE_SET_OPTIONS: PresetDescriptor<ShapeSet>[] = [
|
||||
{
|
||||
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<ColorSet> {
|
||||
|
|
|
|||
606
src/client/ui/coopBar.ts
Normal file
606
src/client/ui/coopBar.ts
Normal file
|
|
@ -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<TeamStationId, string> = {
|
||||
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<void> {
|
||||
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<boolean> {
|
||||
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<boolean> {
|
||||
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<LaunchApiResponse>(
|
||||
"/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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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.",
|
||||
],
|
||||
},
|
||||
],
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
}
|
||||
|
|
|
|||
282
src/server/coopPresence.ts
Normal file
282
src/server/coopPresence.ts
Normal file
|
|
@ -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<SseClientEntry>();
|
||||
const disconnectTimers = new Map<string, NodeJS.Timeout>();
|
||||
|
||||
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<string, CoopOperatorPresence>();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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<string, unknown> = {}): void {
|
||||
broadcaster?.({ type, data, at: Date.now() });
|
||||
}
|
||||
|
||||
export function emitToAgency(
|
||||
agencyName: string,
|
||||
type: string,
|
||||
data: Record<string, unknown> = {},
|
||||
): void {
|
||||
broadcaster?.(
|
||||
{
|
||||
type,
|
||||
data: { agency: agencyName, agencyName, ...data },
|
||||
at: Date.now(),
|
||||
},
|
||||
agencyName,
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<Response>();
|
||||
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")));
|
||||
|
|
|
|||
|
|
@ -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 });
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
|
|
|
|||
|
|
@ -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 });
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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,24 +38,62 @@ 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";
|
||||
|
||||
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) {
|
||||
const VALID_SECTIONS = new Set<RocketPatchSection>([
|
||||
"director",
|
||||
"propulsion",
|
||||
"science",
|
||||
"systems",
|
||||
"all",
|
||||
]);
|
||||
|
||||
function handleRocketSaveOrPatch(req: AuthedRequest, res: Response): void {
|
||||
const raw = req.body?.design as Partial<RocketDesign> | 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!;
|
||||
const clean = normalizeDesign(raw, PARTS, MATERIALS);
|
||||
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,
|
||||
|
|
@ -56,6 +102,7 @@ export function registerDesignRoutes(router: Router): void {
|
|||
weather: getWeather(),
|
||||
unlockedTechs: agency.unlockedTechs ?? [],
|
||||
});
|
||||
|
||||
agency.rocketDesign = clean;
|
||||
if (
|
||||
agency.staticFiredDesignHash &&
|
||||
|
|
@ -63,20 +110,31 @@ export function registerDesignRoutes(router: Router): void {
|
|||
) {
|
||||
agency.staticFiredDesignHash = null;
|
||||
}
|
||||
if (touchedStations.length > 0) {
|
||||
resetStationsReadyOnEdit(agency, touchedStations);
|
||||
}
|
||||
|
||||
putAgency(agency.name, agency);
|
||||
saveDb(true);
|
||||
emit("agency.updated", {
|
||||
agency: agency.name,
|
||||
sender: req.accountName,
|
||||
rocketDesign: clean,
|
||||
teamStations: agency.teamStations,
|
||||
emitAgencySync(req, agency, {
|
||||
changedSection: section,
|
||||
touchedStations,
|
||||
});
|
||||
res.json({
|
||||
ok: true,
|
||||
design: clean,
|
||||
agency,
|
||||
changedSection: section,
|
||||
touchedStations,
|
||||
});
|
||||
res.json({ ok: true, design: clean });
|
||||
} catch (err) {
|
||||
res.status(400).json({ error: String((err as Error).message ?? err) });
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function registerDesignRoutes(router: Router): void {
|
||||
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 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] = {
|
||||
agency.teamStations![stationId] = {
|
||||
stationId,
|
||||
title: def.title,
|
||||
operatorName,
|
||||
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(),
|
||||
|
|
|
|||
|
|
@ -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<string, unknown> = {},
|
||||
): 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,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
235
src/shared/coop.ts
Normal file
235
src/shared/coop.ts
Normal file
|
|
@ -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<TeamStationId, string> = {
|
||||
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<TeamStationId, Partial<TeamStationAssignment>>>,
|
||||
): Record<TeamStationId, TeamStationAssignment> {
|
||||
const out = {} as Record<TeamStationId, TeamStationAssignment>;
|
||||
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<string, unknown>)
|
||||
.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<RocketDesign>,
|
||||
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;
|
||||
}
|
||||
|
|
@ -82,6 +82,7 @@ export interface AgencyState {
|
|||
lastSettlement?: MissionSettlement | null;
|
||||
terminatedReason?: string | null;
|
||||
teamStations?: Record<TeamStationId, TeamStationAssignment>;
|
||||
coopJoinCode?: string;
|
||||
savedDesigns?: SavedRocketBlueprint[];
|
||||
isAI?: boolean;
|
||||
aiType?: "standard" | "ml";
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue