Stage 3-5 server (military, expansion, social), web client for stages 1-2, ops/deploy

Built: units/research/training, movements (scan, raid, attack, takeover, reinforce, settle, transport), deterministic
combat resolved in the event queue, reports, power/offline units, founding + conquest + incumbent sites; alliances,
roles, diplomacy (24h pact cancel via events), messages, rankings; vanilla-JS phone-first client (auth, POP, map,
alerts, settings, en/nb); systemd units, backup timer, DEPLOY.md, tools/admin.js.
Tested: npm test 96/96 (fake clock, in-memory db, a few real-HTTP tests); client checked with headless Chromium
screenshots only. NOT done: marketplace/transport trade, client screens for military/social, WebSocket push,
bots/balance, e2e suite. All unit stats and costs are unbalanced first guesses.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
jvanvik 2026-10-11 18:32:36 +02:00
parent b56b13880e
commit 249818a7aa
111 changed files with 17472 additions and 13 deletions

324
public/css/style.css Normal file
View file

@ -0,0 +1,324 @@
/* UPSTREAM client styles. Dark "network ops console", phone-first.
*
* Layout modes (the shell is a grid on #app):
* portrait / narrow top bar, resource bar, scrolling view, bottom nav (thumb reach)
* rail (landscape and short) OR (width >= 900): nav becomes a left rail, so landscape phones keep their height
* Safe-area insets are applied once, on #app. Every interactive target is at least 44px tall. No hover-only affordances.
*/
:root {
--bg: #070b16;
--panel: #0c1322;
--panel2: #111b30;
--panel3: #16233d;
--line: #1d2c4c;
--line2: #2a3f6b;
--text: #d3e6ff;
--dim: #9bb2d6;
--dimmer: #7790b8;
--cyan: #4de3ff;
--amber: #ffd24d;
--red: #ff6b87;
--green: #35e0a1;
--violet: #b06cff;
--fiber: #4de3ff;
--hardware: #ff9f5a;
--capital: #5be08f;
--power: #ffd24d;
--safe-t: env(safe-area-inset-top, 0px);
--safe-r: env(safe-area-inset-right, 0px);
--safe-b: env(safe-area-inset-bottom, 0px);
--safe-l: env(safe-area-inset-left, 0px);
--nav-h: 58px;
--rail-w: 76px;
--radius: 14px;
--font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
color-scheme: dark;
}
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); font: 15px/1.4 var(--font); overflow: hidden; overscroll-behavior: none; -webkit-text-size-adjust: 100%; }
button, input, select { font: inherit; color: inherit; }
button { cursor: pointer; touch-action: manipulation; }
h1, h2, h3, p, ul { margin: 0; padding: 0; }
ul { list-style: none; }
[hidden] { display: none !important; }
b { font-weight: 650; }
.mono { font-family: var(--mono); font-variant-numeric: tabular-nums; }
.dimmer { color: var(--dimmer); }
.small { font-size: 13px; }
svg.ic { width: 1.3em; height: 1.3em; flex: none; display: inline-block; vertical-align: middle; }
:focus-visible { outline: 2px solid var(--cyan); outline-offset: 2px; border-radius: 6px; }
button:focus:not(:focus-visible), [tabindex="-1"]:focus { outline: none; }
/* ---------------------------------------------------------------- shell */
#app {
position: fixed; inset: 0; height: 100dvh;
display: grid; grid-template-columns: minmax(0, 1fr);
grid-template-rows: auto auto minmax(0, 1fr) auto;
grid-template-areas: "top" "hud" "view" "nav";
padding: var(--safe-t) var(--safe-r) 0 var(--safe-l);
background: radial-gradient(1000px 520px at 15% -10%, #0e1d3a 0%, transparent 60%), radial-gradient(800px 460px at 100% 110%, #1a0f33 0%, transparent 55%), var(--bg);
}
#topbar { grid-area: top; display: flex; align-items: center; gap: 10px; padding: 8px 16px 6px; min-height: 44px; }
.brand { display: flex; align-items: center; gap: 10px; font-weight: 700; letter-spacing: .08em; font-size: 15px; }
.brand-mark { width: 18px; height: 18px; background: linear-gradient(135deg, var(--cyan), #3b82f6); clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%); flex: none; }
.brand-mark.big { width: 40px; height: 40px; }
.netstate { margin-left: auto; font-size: 12px; padding: 4px 10px; border-radius: 999px; background: #3a1620; color: #ffb3c2; border: 1px solid #6b2236; }
.netstate.ok { background: #0f3a2c; color: #9af0cd; border-color: #1a6a4f; }
#hud { grid-area: hud; width: 100%; max-width: 1124px; justify-self: center; }
#view { grid-area: view; min-height: 0; overflow-y: auto; overflow-x: hidden; -webkit-overflow-scrolling: touch; overscroll-behavior: contain; }
#app[data-screen="map"] #view { overflow: hidden; }
#app[data-screen="auth"] #topbar, #app[data-state="out"] #topbar { display: none; }
.screen { min-height: 100%; }
.screen-map { height: 100%; min-height: 0; position: relative; }
#nav {
grid-area: nav; display: grid; grid-auto-flow: column; grid-auto-columns: 1fr;
background: rgba(9, 15, 29, .96); border-top: 1px solid var(--line);
padding-bottom: var(--safe-b);
}
.nav-btn { background: none; border: 0; min-height: var(--nav-h); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; color: var(--dim); font-size: 12px; position: relative; padding: 4px 2px; }
.nav-btn[aria-current="page"] { color: var(--cyan); }
.nav-btn[aria-current="page"]::before { content: ""; position: absolute; top: 0; left: 28%; right: 28%; height: 3px; border-radius: 0 0 3px 3px; background: var(--cyan); }
.nav-ic { position: relative; display: inline-flex; }
.nav-ic svg.ic { width: 24px; height: 24px; }
.nav-badge { position: absolute; top: -5px; right: -9px; min-width: 17px; height: 17px; padding: 0 4px; border-radius: 9px; background: var(--red); color: #1a0710; font-size: 11px; font-weight: 700; display: grid; place-items: center; }
.nav-lbl { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@media (orientation: landscape) and (max-height: 520px), (min-width: 900px) {
#app {
grid-template-columns: var(--rail-w) minmax(0, 1fr);
grid-template-rows: auto auto minmax(0, 1fr);
grid-template-areas: "nav top" "nav hud" "nav view";
padding-bottom: var(--safe-b);
}
#app[data-state="out"] { grid-template-columns: minmax(0, 1fr); grid-template-areas: "view" "view" "view"; }
#nav { grid-auto-flow: row; grid-auto-columns: auto; grid-auto-rows: min-content; align-content: start; border-top: 0; border-right: 1px solid var(--line); padding: 6px 0; padding-bottom: 6px; overflow-y: auto; }
.nav-btn { min-height: 62px; }
.nav-btn[aria-current="page"]::before { top: 22%; bottom: 22%; left: 0; right: auto; width: 3px; height: auto; border-radius: 0 3px 3px 0; }
#topbar { padding-top: 4px; min-height: 36px; }
}
.boot { display: grid; place-items: center; gap: 14px; padding: 48px 16px; color: var(--dim); text-align: center; }
.spinner { width: 28px; height: 28px; border: 3px solid var(--line2); border-top-color: var(--cyan); border-radius: 50%; animation: spin .9s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 3s; } * { scroll-behavior: auto !important; } }
/* ---------------------------------------------------------------- resource bar */
.hud { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; padding: 4px 12px 8px; }
.hud-chip { background: rgba(12, 19, 34, .9); border: 1px solid var(--line); border-radius: 12px; padding: 6px 8px 7px; min-width: 0; --c: var(--dim); }
.hud-chip.fiber { --c: var(--fiber); } .hud-chip.hardware { --c: var(--hardware); } .hud-chip.capital { --c: var(--capital); } .hud-chip.power { --c: var(--power); }
.hud-top { display: flex; align-items: center; gap: 4px; color: var(--c); white-space: nowrap; }
.hud-top svg.ic { width: 16px; height: 16px; }
.hud-top .val { color: var(--text); font-family: var(--mono); font-size: 15px; letter-spacing: -.02em; }
.hud-top .cap { color: var(--dimmer); font-size: 11px; font-family: var(--mono); overflow: hidden; text-overflow: ellipsis; }
.hud-sub { font-size: 11px; color: var(--dim); font-family: var(--mono); margin: 1px 0 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.hud-chip.full { border-color: #6b5a1f; }
.hud-chip.full .rate { color: var(--amber); font-weight: 700; letter-spacing: .06em; }
.hud-chip.bad { border-color: #6b2236; }
.hud-chip.bad .val, .hud-chip.empty .rate { color: var(--red); }
.hud-chip.bad .bar i, .hud-chip.empty .bar i { background: var(--red); }
.bar { height: 4px; border-radius: 2px; background: #0a1020; overflow: hidden; }
.bar i { display: block; height: 100%; width: calc(var(--p, 0) * 100%); background: var(--c, var(--cyan)); border-radius: 2px; transition: width .4s linear; }
.hud-chip.full .bar i { background: var(--amber); }
@media (max-width: 400px) { .hud { gap: 4px; padding: 4px 8px 6px; } .hud-top .cap { display: none; } .hud-top .val { font-size: 14px; } }
@media (orientation: landscape) and (max-height: 520px) { .hud { padding-bottom: 4px; } .hud-chip { padding: 4px 8px 5px; } .hud-sub { margin-bottom: 2px; } }
/* ---------------------------------------------------------------- generic parts */
.page { padding: 8px 12px 24px; display: grid; gap: 12px; max-width: 720px; margin: 0 auto; }
.pad { padding: 28px 16px; }
.card { background: rgba(12, 19, 34, .88); border: 1px solid var(--line); border-radius: var(--radius); padding: 12px; }
.card-head { display: flex; align-items: center; gap: 8px; justify-content: space-between; margin-bottom: 10px; }
.card-head h1, .card-head h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .1em; color: var(--dim); font-weight: 650; display: flex; align-items: center; gap: 6px; }
.card-head h1 { font-size: 15px; color: var(--text); }
.page-head { margin-bottom: 0; }
.empty { color: var(--dimmer); font-size: 14px; text-align: center; padding: 10px 6px; }
.row { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
.kv { display: flex; justify-content: space-between; gap: 12px; padding: 7px 0; border-bottom: 1px solid var(--line); }
.kv:last-of-type { border-bottom: 0; }
.kv .k { color: var(--dimmer); } .kv .v { text-align: right; overflow-wrap: anywhere; }
.pill { display: inline-flex; align-items: center; gap: 5px; padding: 3px 9px; border-radius: 999px; background: var(--panel3); border: 1px solid var(--line2); font-size: 12px; color: var(--dim); max-width: 100%; }
.pill svg.ic { width: 13px; height: 13px; }
.pill.accent { color: #06222b; background: var(--cyan); border-color: var(--cyan); font-weight: 650; }
.pill.green { color: #04241a; background: var(--green); border-color: var(--green); font-weight: 650; }
.pill.amber { color: #2b2204; background: var(--amber); border-color: var(--amber); font-weight: 600; }
.pill.dim { color: var(--dimmer); background: transparent; }
.pill.res-fiber { color: var(--fiber); } .pill.res-hardware { color: var(--hardware); } .pill.res-capital { color: var(--capital); } .pill.res-power { color: var(--power); }
.pill-row { display: flex; flex-wrap: wrap; gap: 6px; margin: 4px 0 8px; }
.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 46px; padding: 0 18px; border-radius: 12px; border: 1px solid var(--line2); background: var(--panel3); color: var(--text); font-weight: 600; }
.btn:disabled { opacity: .45; cursor: not-allowed; }
.btn.primary { background: linear-gradient(180deg, #2fc4e6, #1b97c0); border-color: #55d6f2; color: #03202a; }
.btn.primary:disabled { background: var(--panel3); border-color: var(--line2); color: var(--dim); }
.btn.danger { background: #3a1620; border-color: #7a2a3f; color: #ffc4d0; }
.btn.wide { width: 100%; }
.btn.small { min-height: 36px; padding: 0 12px; font-size: 13px; }
.btn-row { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 10px; margin-top: 12px; }
.icon-btn { width: 44px; height: 44px; flex: none; display: inline-grid; place-items: center; border-radius: 12px; background: transparent; border: 1px solid transparent; color: var(--dim); }
.icon-btn:hover { background: var(--panel3); }
.linklike { background: none; border: 0; color: var(--cyan); min-height: 44px; text-decoration: underline; text-underline-offset: 3px; width: 100%; }
.chip-btn { min-width: 52px; min-height: 40px; border-radius: 999px; background: transparent; border: 1px solid var(--line2); color: var(--dim); padding: 0 14px; }
.chip-btn[aria-pressed="true"], .seg-btn[aria-pressed="true"] { background: var(--cyan); border-color: var(--cyan); color: #04222b; font-weight: 700; }
.seg { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; gap: 6px; }
.seg-btn { min-height: 46px; border-radius: 12px; background: var(--panel3); border: 1px solid var(--line2); color: var(--dim); }
.field { display: grid; gap: 5px; margin-bottom: 12px; }
.field-lbl { font-size: 13px; color: var(--dim); }
.field-hint { font-size: 12px; color: var(--dimmer); }
input[type="text"], input[type="password"], select { width: 100%; min-height: 48px; padding: 0 14px; border-radius: 12px; background: #080e1c; border: 1px solid var(--line2); color: var(--text); font-size: 16px; }
input:focus-visible, select:focus-visible { outline: 2px solid var(--cyan); outline-offset: 1px; border-color: var(--cyan); }
.form-error { color: #ffc4d0; background: #3a1620; border: 1px solid #7a2a3f; border-radius: 10px; padding: 9px 12px; font-size: 14px; margin-bottom: 12px; }
.notice { color: var(--amber); font-size: 14px; margin-bottom: 12px; }
/* ---------------------------------------------------------------- auth */
.screen-auth { display: grid; place-items: center; padding: calc(16px + var(--safe-t)) 16px calc(16px + var(--safe-b)); min-height: 100%; }
.auth-card { width: min(100%, 400px); display: grid; gap: 14px; }
.auth-logo { display: flex; align-items: center; gap: 14px; justify-content: center; }
.auth-name { font-size: 28px; font-weight: 750; letter-spacing: .12em; }
.auth-tag { text-align: center; color: var(--dim); }
.auth-form { background: rgba(12, 19, 34, .9); border: 1px solid var(--line); border-radius: 18px; padding: 18px 16px 8px; }
.auth-h { font-size: 20px; margin-bottom: 14px; }
.lang-switch { display: flex; justify-content: center; gap: 8px; }
/* ---------------------------------------------------------------- POP */
.cols { display: grid; gap: 12px; padding: 4px 12px 24px; max-width: 1100px; margin: 0 auto; align-items: start; }
.col { display: grid; gap: 12px; min-width: 0; }
@media (min-width: 760px) { .cols { grid-template-columns: minmax(0, 5fr) minmax(0, 6fr); } }
.pop-title { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: -4px 0 4px; }
.town-name { font-size: 22px; font-weight: 700; overflow-wrap: anywhere; }
.town-select { font-size: 18px; font-weight: 650; }
.pop-meta { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; color: var(--dim); font-size: 13px; }
.queue { display: grid; gap: 8px; }
.q-item { display: flex; align-items: center; gap: 4px; background: var(--panel2); border: 1px solid #5a4a14; border-radius: 12px; padding-right: 2px; }
.q-main { flex: 1; min-width: 0; display: flex; align-items: center; gap: 10px; background: none; border: 0; padding: 8px 6px 8px 10px; text-align: left; min-height: 56px; }
.q-main .bar { margin-top: 6px; --c: var(--amber); }
.q-main > b { font-size: 15px; color: var(--amber); }
.row-ic { width: 38px; height: 38px; flex: none; display: grid; place-items: center; border-radius: 10px; background: var(--panel3); color: var(--cyan); }
.row-ic svg.ic { width: 22px; height: 22px; }
.row-main { flex: 1; min-width: 0; display: grid; gap: 2px; }
.row-title { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; }
.row-title .lv { color: var(--dim); font-size: 13px; }
.row-sub { color: var(--dimmer); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.stat-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 10px; }
.stat { background: var(--panel2); border-radius: 10px; padding: 7px 10px; display: grid; }
.stat small { color: var(--dimmer); font-size: 11px; text-transform: uppercase; letter-spacing: .08em; }
.stat b { font-family: var(--mono); font-size: 17px; }
.good { color: var(--green); } .bad { color: var(--red); }
.power-card .bar { height: 8px; --c: var(--power); margin: 6px 0 8px; }
.power-status { font-size: 13px; color: var(--dim); }
.power-status.warn { color: var(--amber); } .power-status.bad { color: var(--red); }
.groups { display: grid; gap: 12px; }
.group { --c: var(--cyan); }
.group.res-fiber { --c: var(--fiber); } .group.res-hardware { --c: var(--hardware); } .group.res-capital { --c: var(--capital); } .group.res-power { --c: var(--power); }
.group-head { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; color: var(--c); }
.group-head b { color: var(--text); }
.group-rate { margin-left: auto; font-family: var(--mono); font-size: 12px; color: var(--c); }
.tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(56px, 1fr)); gap: 8px; }
.tile { position: relative; aspect-ratio: 1; min-height: 56px; border-radius: 14px; background: var(--panel2); border: 1px solid color-mix(in srgb, var(--c) 35%, var(--line)); color: var(--c); padding: 6px; display: block; text-align: left; overflow: hidden; }
.tile.res-fiber { --c: var(--fiber); } .tile.res-hardware { --c: var(--hardware); } .tile.res-capital { --c: var(--capital); } .tile.res-power { --c: var(--power); }
.tile-ic { width: 26px; height: 26px; opacity: .95; }
.tile-lvl { position: absolute; right: 8px; bottom: 6px; font-family: var(--mono); font-size: 22px; color: var(--text); line-height: 1; }
.tile-badge { position: absolute; right: 5px; top: 5px; display: grid; place-items: center; }
.tile-badge svg.ic { width: 15px; height: 15px; }
.tile-bar { position: absolute; left: 0; right: 0; bottom: 0; height: 4px; background: transparent; }
.tile-bar i { display: block; height: 100%; width: calc(var(--p, 0) * 100%); background: var(--amber); }
.tile[data-st="ready"] { border-color: var(--green); box-shadow: 0 0 0 1px rgba(53, 224, 161, .35), 0 0 14px rgba(53, 224, 161, .18); }
.tile[data-st="ready"] .tile-badge { color: var(--green); }
.tile[data-st="queued"] { border-color: var(--amber); } .tile[data-st="queued"] .tile-badge { color: var(--amber); }
.tile[data-st="locked"] { opacity: .65; } .tile[data-st="locked"] .tile-badge { color: var(--dimmer); }
.tile[data-st="max"] { border-color: #8a7a2a; }
.rows { display: grid; gap: 8px; }
.row-btn { position: relative; width: 100%; display: flex; align-items: center; gap: 10px; background: var(--panel2); border: 1px solid var(--line); border-radius: 12px; padding: 8px 10px; min-height: 58px; text-align: left; overflow: hidden; }
.row-btn[data-st="ready"] { border-color: color-mix(in srgb, var(--green) 70%, var(--line)); }
.row-btn[data-st="queued"] { border-color: var(--amber); }
.row-btn[data-st="locked"] .row-ic { color: var(--dimmer); }
.row-btn .pill { flex: none; max-width: 42%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
/* ---------------------------------------------------------------- sheet */
.sheet-wrap { position: fixed; inset: 0; z-index: 50; display: flex; align-items: flex-end; justify-content: center; pointer-events: none; }
.backdrop { position: absolute; inset: 0; background: rgba(2, 5, 12, .62); opacity: 0; transition: opacity .18s; pointer-events: auto; }
.sheet { position: relative; width: min(100%, 520px); max-height: min(86dvh, 720px); overflow-y: auto; background: var(--panel); border: 1px solid var(--line2); border-bottom: 0; border-radius: 20px 20px 0 0; padding: 6px 16px calc(16px + var(--safe-b)); transform: translateY(24px); opacity: 0; transition: transform .2s ease-out, opacity .2s; pointer-events: auto; box-shadow: 0 -10px 40px rgba(0, 0, 0, .5); margin: 0 var(--safe-r) 0 var(--safe-l); }
.sheet-wrap.open .backdrop { opacity: 1; }
.sheet-wrap.open .sheet { transform: none; opacity: 1; }
.sheet-grab { width: 40px; height: 4px; border-radius: 2px; background: var(--line2); margin: 4px auto 6px; }
.sheet-head { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; }
.sheet-title { flex: 1; font-size: 19px; min-width: 0; overflow-wrap: anywhere; }
.sheet-icon { width: 40px; height: 40px; border-radius: 12px; background: var(--panel3); display: grid; place-items: center; color: var(--cyan); flex: none; }
.sheet-icon.res-fiber { color: var(--fiber); } .sheet-icon.res-hardware { color: var(--hardware); } .sheet-icon.res-capital { color: var(--capital); } .sheet-icon.res-power { color: var(--power); }
.sheet-icon svg.ic { width: 24px; height: 24px; }
.detail { display: grid; gap: 10px; }
.detail-desc { color: var(--dim); }
.detail-level { display: flex; justify-content: space-between; align-items: center; gap: 10px; }
.lvl-now { font-weight: 700; font-size: 17px; }
.lvl-next { display: inline-flex; align-items: center; gap: 4px; color: var(--green); font-size: 14px; }
.preview { color: var(--text); background: var(--panel2); border-radius: 10px; padding: 8px 12px; font-size: 14px; }
.sub { font-size: 12px; text-transform: uppercase; letter-spacing: .1em; color: var(--dimmer); margin-top: 2px; }
.costs { display: flex; flex-wrap: wrap; gap: 8px; }
.cost { display: inline-flex; align-items: center; gap: 6px; background: var(--panel2); border: 1px solid var(--line2); border-radius: 10px; padding: 6px 10px; --c: var(--dim); }
.cost.fiber { --c: var(--fiber); } .cost.hardware { --c: var(--hardware); } .cost.capital { --c: var(--capital); }
.cost svg.ic { color: var(--c); width: 18px; height: 18px; }
.cost b { font-family: var(--mono); }
.cost small { color: var(--dimmer); font-size: 11px; }
.cost.short { border-color: #7a2a3f; } .cost.short b { color: var(--red); }
.meta { justify-content: flex-start; color: var(--dim); }
.reqs { display: grid; gap: 6px; }
.reqs li { display: flex; align-items: center; gap: 8px; font-size: 14px; }
.reqs li.ok { color: var(--green); } .reqs li.miss { color: var(--red); }
.reqs small { margin-left: auto; color: var(--dimmer); }
.reason { color: var(--amber); font-size: 14px; min-height: 1.4em; }
.detail-queue { background: var(--panel2); border: 1px solid #5a4a14; border-radius: 12px; padding: 12px; display: grid; gap: 8px; }
.detail-queue .bar { --c: var(--amber); height: 6px; }
.detail-queue b { color: var(--amber); font-size: 18px; }
@media (min-width: 700px) and (min-height: 560px) {
.sheet-wrap { align-items: center; }
.sheet { border-bottom: 1px solid var(--line2); border-radius: 20px; max-height: 86dvh; padding-bottom: 16px; }
}
@media (orientation: landscape) and (max-height: 520px) {
.sheet { max-height: 94dvh; width: min(100%, 560px); }
.sheet-grab { display: none; }
}
/* ---------------------------------------------------------------- toasts */
#toasts { position: fixed; left: 0; right: 0; bottom: calc(var(--nav-h) + var(--safe-b) + 12px); display: grid; justify-items: center; gap: 8px; z-index: 80; pointer-events: none; padding: 0 16px; }
.toast { background: #12203b; border: 1px solid var(--line2); color: var(--text); padding: 10px 16px; border-radius: 12px; font-size: 14px; max-width: 480px; box-shadow: 0 8px 24px rgba(0, 0, 0, .5); transition: opacity .25s, transform .25s; }
.toast.ok { border-color: #1a6a4f; background: #0e2b23; }
.toast.error { border-color: #7a2a3f; background: #2d1019; color: #ffd0da; }
.toast.out { opacity: 0; transform: translateY(8px); }
@media (orientation: landscape) and (max-height: 520px), (min-width: 900px) { #toasts { bottom: 14px; left: var(--rail-w); } }
/* ---------------------------------------------------------------- map */
.map-canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; touch-action: none; cursor: grab; outline: none; user-select: none; -webkit-user-select: none; }
.map-canvas.grabbing { cursor: grabbing; }
.map-canvas:focus-visible { outline: 2px solid var(--cyan); outline-offset: -2px; }
.map-controls { position: absolute; right: 12px; bottom: 14px; display: grid; gap: 8px; z-index: 3; }
.map-btn { width: 48px; height: 48px; border-radius: 14px; background: rgba(12, 19, 34, .92); border: 1px solid var(--line2); color: var(--text); display: grid; place-items: center; box-shadow: 0 4px 14px rgba(0, 0, 0, .45); }
.map-btn svg.ic { width: 24px; height: 24px; }
.map-coords { position: absolute; left: 12px; bottom: 14px; z-index: 3; padding: 4px 10px; border-radius: 999px; background: rgba(12, 19, 34, .85); border: 1px solid var(--line); color: var(--dim); font-size: 12px; pointer-events: none; }
.map-legend { position: absolute; left: 10px; top: 8px; z-index: 3; display: flex; flex-wrap: wrap; gap: 4px 12px; padding: 5px 10px; border-radius: 10px; background: rgba(12, 19, 34, .8); border: 1px solid var(--line); font-size: 11px; color: var(--dim); pointer-events: none; max-width: calc(100% - 20px); }
.map-legend li { display: flex; align-items: center; gap: 5px; }
.lg { width: 10px; height: 10px; display: inline-block; }
.lg.you { background: var(--cyan); clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%); }
.lg.rival { background: #e08a4a; clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%); }
.lg.rural { border: 2px solid var(--capital); border-radius: 50%; }
.lg.incumbent { background: #241338; border: 2px solid var(--violet); }
@media (max-height: 420px) { .map-legend { display: none; } }
/* ---------------------------------------------------------------- alerts + settings */
.alert-list { display: grid; gap: 8px; }
.alert { width: 100%; display: flex; align-items: center; gap: 10px; background: rgba(12, 19, 34, .88); border: 1px solid var(--line); border-radius: 12px; padding: 8px 10px; min-height: 58px; text-align: left; }
.alert.new { border-color: var(--cyan); background: #0c1f33; }
.when { font-size: 12px; color: var(--dimmer); flex: none; }
.device-list { display: grid; gap: 8px; margin-top: 10px; }
.device { display: flex; align-items: center; gap: 10px; background: var(--panel2); border-radius: 12px; padding: 8px 10px; min-height: 56px; }
.device .row-sub { white-space: normal; }
.card .btn.wide { margin-top: 10px; }
@media (prefers-reduced-motion: reduce) { .sheet, .backdrop, .toast, .bar i { transition: none; } }

BIN
public/icons/icon-192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
public/icons/icon-512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

17
public/icons/icon.svg Normal file
View file

@ -0,0 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<defs>
<radialGradient id="g" cx="30%" cy="18%" r="95%"><stop offset="0" stop-color="#16315c"/><stop offset="1" stop-color="#070b16"/></radialGradient>
</defs>
<rect width="512" height="512" rx="112" fill="url(#g)"/>
<rect x="20" y="20" width="472" height="472" rx="94" fill="none" stroke="#4de3ff" stroke-opacity=".35" stroke-width="6"/>
<!-- region links to the core POP -->
<path d="M120 410L256 290M392 410L256 290M150 170L256 290M362 170L256 290" fill="none" stroke="#4de3ff" stroke-width="10" stroke-linecap="round" stroke-opacity=".7"/>
<g fill="#0d2038" stroke="#5aa9ff" stroke-width="9">
<circle cx="120" cy="410" r="26"/><circle cx="392" cy="410" r="26"/><circle cx="150" cy="170" r="26"/><circle cx="362" cy="170" r="26"/>
</g>
<!-- the core POP: a hexagon -->
<path d="M256 220l54 31v62l-54 31-54-31v-62z" fill="#0d2a44" stroke="#4de3ff" stroke-width="12" stroke-linejoin="round"/>
<circle cx="256" cy="282" r="17" fill="#35e0a1"/>
<!-- upstream arrow -->
<path d="M256 140V70M226 98l30-30 30 30" fill="none" stroke="#ffd24d" stroke-width="13" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

49
public/icons/sprite.svg Normal file
View file

@ -0,0 +1,49 @@
<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0">
<!-- UPSTREAM icon sprite. 24x24, stroke/fill currentColor. Referenced as <use href="icons/sprite.svg#i-name">. -->
<defs>
<!-- navigation / ui -->
<symbol id="i-pop" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3.5l7.5 4.3v8.4L12 20.5l-7.5-4.3V7.8z"/><circle fill="currentColor" cx="12" cy="12" r="2.6"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3.5v6M12 14.5v6M4.5 7.8l5.2 3M14.3 13.2l5.2 3M19.5 7.8l-5.2 3M9.7 13.2l-5.2 3" opacity=".55"/></symbol>
<symbol id="i-map" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M3.5 6l5.5-2 6 2 5.5-2v14l-5.5 2-6-2-5.5 2z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M9 4v14M15 6v14"/></symbol>
<symbol id="i-bell" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M6 17V11a6 6 0 0112 0v6l1.6 1.8H4.4z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M10 20.5a2.2 2.2 0 004 0"/></symbol>
<symbol id="i-gear" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="3"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3.2l1.6 2.3 2.7-.7.9 2.7 2.7.9-.7 2.7 2.3 1.6-2.3 1.6.7 2.7-2.7.9-.9 2.7-2.7-.7L12 20.8l-1.6-2.3-2.7.7-.9-2.7-2.7-.9.7-2.7L2.5 12l2.3-1.6-.7-2.7 2.7-.9.9-2.7 2.7.7z"/></symbol>
<symbol id="i-x" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M6 6l12 12M18 6L6 18" stroke-width="2.4"/></symbol>
<symbol id="i-check" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M5 12.5l4.5 4.5L19 7.5" stroke-width="2.6"/></symbol>
<symbol id="i-plus" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M12 5v14M5 12h14" stroke-width="2.4"/></symbol>
<symbol id="i-minus" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M5 12h14" stroke-width="2.4"/></symbol>
<symbol id="i-locate" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="6.5"/><circle fill="currentColor" cx="12" cy="12" r="2.2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 2.5v3.5M12 18v3.5M2.5 12H6M18 12h3.5"/></symbol>
<symbol id="i-logout" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M10 4.5H5.5v15H10M14 8l4 4-4 4M18 12H9.5"/></symbol>
<symbol id="i-shield" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3l7 3v5.5c0 4.6-3 7.6-7 9.5-4-1.9-7-4.9-7-9.5V6z"/></symbol>
<symbol id="i-clock" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="8.5"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 7v5.2l3.4 2"/></symbol>
<symbol id="i-pencil" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M4.5 19.5l1-4.2L16 4.8a1.8 1.8 0 012.6 0l.6.6a1.8 1.8 0 010 2.6L8.7 18.5z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M14.5 6.5l3 3"/></symbol>
<symbol id="i-alert" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 4l9 16H3z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 10v4.5M12 17.4v.1"/></symbol>
<symbol id="i-lock" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="5.5" y="11" width="13" height="9" rx="2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M8.5 11V8a3.5 3.5 0 017 0v3"/></symbol>
<symbol id="i-up" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M12 19V6M6 11.5l6-6 6 6" stroke-width="2.4"/></symbol>
<symbol id="i-refresh" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M19 12a7 7 0 11-2.2-5.1M19 4.5v4.3h-4.3"/></symbol>
<symbol id="i-device" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="7" y="3.5" width="10" height="17" rx="2.2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M10.5 17.5h3"/></symbol>
<!-- resources -->
<symbol id="i-fiber" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="8.5"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="3.2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3.5c-3 3.4-3 13.6 0 17M5 6.8c4 1 10 1 14 0" opacity=".6"/></symbol>
<symbol id="i-hardware" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="6.5" y="6.5" width="11" height="11" rx="1.8"/><rect fill="currentColor" x="10" y="10" width="4" height="4" rx=".6"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M9.5 3.5v3M14.5 3.5v3M9.5 17.5v3M14.5 17.5v3M3.5 9.5h3M3.5 14.5h3M17.5 9.5h3M17.5 14.5h3"/></symbol>
<symbol id="i-capital" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="8.5"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M14.6 9.4c-.5-1-1.4-1.5-2.6-1.5-1.5 0-2.6.8-2.6 2 0 2.7 5.2 1.4 5.2 4.2 0 1.2-1.1 2-2.6 2-1.2 0-2.2-.6-2.7-1.6M12 6.2v1.7M12 16.1v1.7"/></symbol>
<symbol id="i-power" viewBox="0 0 24 24"><path fill="currentColor" d="M13.4 2.8L5.5 13.4h5.2l-1 7.8 8.8-11.4h-5.4z"/></symbol>
<symbol id="i-battery" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="3.5" y="7.5" width="15" height="9" rx="2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M21 10.5v3"/><path fill="currentColor" d="M6 10h3v4H6z"/></symbol>
<!-- buildings: i-b-<type> -->
<symbol id="i-b-cable_yard" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="8.5"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="3"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M5.5 8.5c3.5 1.6 9.5 1.6 13 0M5.5 15.5c3.5-1.6 9.5-1.6 13 0" opacity=".65"/></symbol>
<symbol id="i-b-supply_depot" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M3.5 8.2L12 4l8.5 4.2v8.6L12 21l-8.5-4.2z"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M3.5 8.2L12 12.5l8.5-4.3M12 12.5V21"/></symbol>
<symbol id="i-b-sales_office" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M4 20.5V8.5l6-4v16M10 8.5l10 3.5v8.5"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M6.5 11h1.5M6.5 14.5h1.5M13.5 15h3"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M3 20.5h18"/></symbol>
<symbol id="i-b-substation" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3v18M7.5 21l4.5-13 4.5 13M5 8.5h14M7 13.5h10"/><path fill="currentColor" d="M12 3l1.5 2.5h-3z"/></symbol>
<symbol id="i-b-core_router" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="12" r="3.4"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M12 3.5v5.1M12 15.4v5.1M3.5 12h5.1M15.4 12h5.1M6 6l3.6 3.6M14.4 14.4L18 18M18 6l-3.6 3.6M9.6 14.4L6 18"/><circle fill="currentColor" cx="12" cy="3.5" r="1.4"/><circle fill="currentColor" cx="12" cy="20.5" r="1.4"/><circle fill="currentColor" cx="3.5" cy="12" r="1.4"/><circle fill="currentColor" cx="20.5" cy="12" r="1.4"/></symbol>
<symbol id="i-b-rack_hall" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="5" y="3.5" width="14" height="17" rx="1.8"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M5 9.2h14M5 14.8h14M8 6.4h.1M8 12h.1M8 17.7h.1M12 6.4h4.5M12 12h4.5M12 17.7h4.5"/></symbol>
<symbol id="i-b-battery_bank" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="3" y="6.5" width="16" height="11" rx="2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M21.5 10v4"/><path fill="currentColor" d="M5.5 9h2.6v6H5.5zM9.6 9h2.6v6H9.6z"/></symbol>
<symbol id="i-b-firewall" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="3.5" y="4.5" width="17" height="15" rx="1.5"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M3.5 9.5h17M3.5 14.5h17M9 4.5v5M15 4.5v5M6.5 9.5v5M12 9.5v5M17.5 9.5v5M9 14.5v5M15 14.5v5"/></symbol>
<symbol id="i-b-noc" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="3" y="4" width="18" height="12.5" rx="2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M8 20.5h8M12 16.5v4M5.8 11h3l1.6-3.5 2.4 6 1.6-2.5h3.2"/></symbol>
<symbol id="i-b-research_lab" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M9.5 3.5h5M10.5 3.5v6L5 19a1.5 1.5 0 001.3 2.2h11.4A1.5 1.5 0 0019 19l-5.5-9.5v-6"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M7.8 15h8.4"/><circle fill="currentColor" cx="10.5" cy="17.7" r=".9"/><circle fill="currentColor" cx="14" cy="16.7" r=".7"/></symbol>
<symbol id="i-b-ops_lab" viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" x="3" y="4.5" width="18" height="15" rx="2"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M7 9.5l3.2 2.5L7 14.5M12.5 15h4.5"/></symbol>
<symbol id="i-b-internet_exchange" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M4 8h13M13.5 4.5L17 8l-3.5 3.5M20 16H7M10.5 12.5L7 16l3.5 3.5"/></symbol>
<symbol id="i-b-peering_office" viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="8.5" cy="12" r="5"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="15.5" cy="12" r="5"/></symbol>
<symbol id="i-b-rollout_depot" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M2.5 16.5V8h10v8.5M12.5 11h4.2l3 3.2v2.3h-7.2"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="7" cy="17.5" r="2"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="16.5" cy="17.5" r="2"/></symbol>
<symbol id="i-b-backbone_node" viewBox="0 0 24 24"><circle fill="currentColor" cx="4.5" cy="12" r="2.1"/><circle fill="currentColor" cx="12" cy="12" r="2.1"/><circle fill="currentColor" cx="19.5" cy="12" r="2.1"/><path fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" d="M6.6 12h3.3M14.1 12h3.3M12 4.5v5.4M12 14.1v5.4"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="4.5" r="1.4"/><circle fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" cx="12" cy="19.5" r="1.4"/></symbol>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 13 KiB

46
public/index.html Normal file
View file

@ -0,0 +1,46 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#070b16">
<meta name="color-scheme" content="dark">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="UPSTREAM">
<meta name="description" content="UPSTREAM: build POPs, connect the region and outlast rival network operators.">
<title>UPSTREAM</title>
<link rel="manifest" href="manifest.webmanifest">
<link rel="icon" href="icons/icon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="icons/icon-192.png">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="app" data-state="boot">
<header id="topbar">
<div class="brand"><span class="brand-mark" aria-hidden="true"></span><span id="title">UPSTREAM</span></div>
<span id="netstate" class="netstate" role="status" aria-live="polite" hidden></span>
</header>
<section id="hud" class="hud" aria-label="Resources" hidden></section>
<main id="view"></main>
<nav id="nav" aria-label="Main navigation" hidden></nav>
</div>
<div id="sheet-root"></div>
<div id="toasts" role="status" aria-live="polite"></div>
<noscript><p style="padding:24px;color:#d3e6ff;font-family:sans-serif">UPSTREAM needs JavaScript.</p></noscript>
<script src="js/data.js" defer></script>
<script src="js/rules.js" defer></script>
<script src="js/i18n.js" defer></script>
<script src="js/api.js" defer></script>
<script src="js/ui.js" defer></script>
<script src="js/render.js" defer></script>
<script src="js/main.js" defer></script>
<script src="js/screens/auth.js" defer></script>
<script src="js/screens/pop.js" defer></script>
<script src="js/screens/map.js" defer></script>
<script src="js/screens/alerts.js" defer></script>
<script src="js/screens/settings.js" defer></script>
</body>
</html>

203
public/js/api.js Normal file
View file

@ -0,0 +1,203 @@
'use strict';
/*
* REST client for /api/v1. No DOM; fetch, storage, clock and sleep are injected so Node tests can drive it
* (test/client-api.test.js). Loads as a browser script (window.UpstreamApi) and as a Node module.
*
* const api = UpstreamApi.createApi({ fetch, storage: localStorage });
* const me = await api.get('/me');
* await api.post('/towns/3/build', { key: 'f1' }, { intent: 'build:3:f1' });
* api.serverNow(); // server clock estimate in ms: use this for every countdown
* api.on('unauthorized', fn); // token rejected: the shell drops to the login screen
* api.on('push', fn); // reserved: the WebSocket client (stage 6) calls api.emit('push', msg)
*
* Rules it follows (docs/API.md):
* - every response carries serverTime; the offset is kept from the lowest-latency sample (replayed idempotent
* responses carry the ORIGINAL serverTime and are ignored for this)
* - errors are { error: { code, message, details } } and become ApiError with .code; callers switch on code
* - mutating POSTs of a logged-in user carry an Idempotency-Key. An "intent" (a stable string like
* 'build:3:f1') keeps the same key across calls until the server has given a definite answer, so a tap that
* died on a flaky network and is tapped again cannot build twice. Without an intent, one key per call, reused
* by that call's retries.
* - retries with backoff: network errors, 429 (Retry-After honoured, seconds), 502/503/504 and request_in_progress.
* Network errors and 5xx are only retried when repeating is safe (GET, a keyed POST). 429 is always safe.
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory();
else root.UpstreamApi = factory();
}(typeof self !== 'undefined' ? self : this, function () {
class ApiError extends Error {
constructor(code, message, status, details, retryAfter) {
super(message || code);
this.name = 'ApiError';
this.code = code;
this.status = status || 0;
this.details = details || {};
this.retryAfter = retryAfter || 0;
}
}
const KEY_RE = /^[A-Za-z0-9_.:-]{8,64}$/;
function defaultHex() {
const c = typeof globalThis !== 'undefined' && globalThis.crypto;
if (c && c.getRandomValues) {
const a = new Uint8Array(12);
c.getRandomValues(a);
return Array.prototype.map.call(a, (b) => (b < 16 ? '0' : '') + b.toString(16)).join('');
}
let s = '';
for (let i = 0; i < 24; i++) s += Math.floor(Math.random() * 16).toString(16);
return s;
}
function createApi(opts) {
opts = opts || {};
const doFetch = opts.fetch;
const now = opts.now || Date.now;
const sleep = opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
const base = (opts.base || 'api/v1').replace(/\/$/, '');
const tokenKey = opts.tokenKey || 'upstream.token';
const maxRetries = opts.maxRetries === undefined ? 4 : opts.maxRetries;
const maxWaitMs = opts.maxWaitMs || 15000; // a Retry-After longer than this is given to the caller instead
const hex = opts.randomHex || defaultHex;
const jitter = opts.jitter || (() => Math.random());
// ---- token (storage can throw or be empty in private windows: stay usable from memory)
let memToken = null;
const store = opts.storage;
function getToken() {
if (memToken) return memToken;
try { return (store && store.getItem(tokenKey)) || null; } catch (e) { return null; }
}
function setToken(t) {
memToken = t || null;
try { if (store) { if (t) store.setItem(tokenKey, t); else store.removeItem(tokenKey); } } catch (e) { /* memory only */ }
}
const clearToken = () => setToken(null);
// ---- events
const handlers = {};
function on(evt, fn) {
(handlers[evt] = handlers[evt] || new Set()).add(fn);
return () => off(evt, fn);
}
function off(evt, fn) { if (handlers[evt]) handlers[evt].delete(fn); }
function emit(evt, data) {
if (!handlers[evt]) return;
for (const fn of Array.from(handlers[evt])) { try { fn(data); } catch (e) { /* a listener must not break the client */ } }
}
// ---- server clock
let offset = 0, bestRtt = null, bestAt = 0, haveOffset = false;
function observeServerTime(serverTime, t0, t1) {
if (!Number.isFinite(serverTime)) return;
const rtt = Math.max(0, t1 - t0);
if (bestRtt === null || rtt <= bestRtt || t1 - bestAt > 5 * 60 * 1000) {
offset = serverTime - (t0 + t1) / 2;
bestRtt = rtt; bestAt = t1; haveOffset = true;
emit('offset', offset);
}
}
const serverNow = () => now() + offset;
// ---- idempotency keys
const intents = new Map();
const newKey = () => 'u' + hex();
function keyFor(intent) {
if (!intent) return newKey();
let k = intents.get(intent);
if (!k) { k = newKey(); intents.set(intent, k); }
return k;
}
function backoff(attempt) { return Math.round(400 * Math.pow(2, attempt) * (0.75 + jitter() * 0.5)); }
let offline = false;
function setOffline(v) { if (v !== offline) { offline = v; emit(v ? 'offline' : 'online'); } }
function buildUrl(path, query) {
let u = base + (path[0] === '/' ? path : '/' + path);
if (query) {
const p = [];
for (const k of Object.keys(query)) if (query[k] !== undefined && query[k] !== null) p.push(encodeURIComponent(k) + '=' + encodeURIComponent(query[k]));
if (p.length) u += '?' + p.join('&');
}
return u;
}
async function request(method, path, o) {
o = o || {};
const authed = o.auth !== false;
const token = authed ? getToken() : null;
const hasBody = o.body !== undefined && method !== 'GET';
const keyed = method === 'POST' && !!token;
const key = keyed ? keyFor(o.intent) : null;
const safeToRepeat = method === 'GET' || keyed;
const headers = { Accept: 'application/json' };
if (token) headers.Authorization = 'Bearer ' + token;
if (hasBody) headers['Content-Type'] = 'application/json';
if (key) headers['Idempotency-Key'] = key;
const init = { method, headers, cache: 'no-store' };
if (hasBody) init.body = JSON.stringify(o.body);
const url = buildUrl(path, o.query);
const retries = o.retries === undefined ? maxRetries : o.retries;
for (let attempt = 0; ; attempt++) {
const t0 = now();
let res;
try {
res = await doFetch(url, init);
} catch (e) {
setOffline(true);
if (attempt < retries && (safeToRepeat || method === 'DELETE')) { await sleep(backoff(attempt)); continue; }
throw new ApiError('network_error', String(e && e.message || e), 0); // intent key is kept: same tap, same key
}
const t1 = now();
let body = null;
try { body = await res.json(); } catch (e) { body = null; }
const replay = res.headers && res.headers.get && res.headers.get('Idempotent-Replay');
if (body && !replay) observeServerTime(body.serverTime, t0, t1);
if (res.ok) {
setOffline(false);
if (o.intent) intents.delete(o.intent);
return body || {};
}
const err = body && body.error ? body.error : {};
const code = err.code || (res.status === 429 ? 'rate_limited' : 'http_' + res.status);
let retryAfter = 0;
const ra = res.headers && res.headers.get ? Number(res.headers.get('Retry-After')) : NaN;
if (Number.isFinite(ra) && ra > 0) retryAfter = ra;
else if (err.details && Number(err.details.retryAfter) > 0) retryAfter = Number(err.details.retryAfter);
// 429 was refused before doing anything, so it is always safe to repeat.
if (res.status === 429 && attempt < retries) {
const wait = retryAfter ? retryAfter * 1000 : backoff(attempt);
if (wait <= maxWaitMs) { await sleep(wait); continue; }
}
if ([502, 503, 504].includes(res.status) && attempt < retries && safeToRepeat) { await sleep(backoff(attempt)); continue; }
if (code === 'request_in_progress' && attempt < retries) { await sleep(500 + backoff(attempt)); continue; }
setOffline(false); // the server answered: the network is fine
if (o.intent && res.status !== 429 && res.status < 500) intents.delete(o.intent); // a definite answer ends the intent
if (res.status === 401 && token && code === 'unauthorized') { clearToken(); emit('unauthorized', {}); }
throw new ApiError(code, err.message, res.status, err.details, retryAfter);
}
}
return {
request,
get: (path, query, o) => request('GET', path, Object.assign({ query }, o)),
post: (path, body, o) => request('POST', path, Object.assign({ body: body === undefined ? {} : body }, o)),
del: (path, o) => request('DELETE', path, o),
getToken, setToken, clearToken, hasToken: () => !!getToken(),
on, off, emit,
serverNow, hasServerTime: () => haveOffset, serverOffset: () => offset,
pendingIntents: () => Array.from(intents.keys()),
isValidKey: (k) => KEY_RE.test(k),
};
}
return { createApi, ApiError };
}));

View file

@ -94,6 +94,47 @@
// AS numbers come from the 32-bit private range (RFC 6996). Display name only.
const AS_RANGE = { min: 4200000000, max: 4294967294 };
// Alliances, diplomacy, messages (stage 5). Roles are listed most senior first. `permissions` maps an action to the
// roles allowed to do it; rules.allianceCan reads it. Times in hours are at world speed 1x unless noted "real".
const SOCIAL = {
roles: ['leader', 'diplomat', 'officer', 'member'],
permissions: {
invite: ['leader', 'officer'],
cancelInvite: ['leader', 'officer'],
viewInvites: ['leader', 'officer'],
kick: ['leader', 'officer'], // and only members the actor outranks
setRole: ['leader'],
transfer: ['leader'],
diplomacy: ['leader', 'diplomat'],
editNotes: ['leader', 'diplomat', 'officer'],
broadcast: ['leader', 'diplomat', 'officer', 'member'],
disband: ['leader'],
},
allianceBaseSize: 10, // size cap = base + perLevel * Peering office level (best POP of the leader)
allianceSizePerLevel: 2,
minPeeringLevel: 1, // needed to found or join
nameLen: [3, 30], tagLen: [2, 5],
inviteTtlHours: 168, // real time, not divided by world speed
proposalTtlHours: 72, // real time
maxPendingInvites: 25,
maxNotes: 10, noteMax: 1000,
// Diplomacy. from -> to -> how the change happens: 'immediate' (one side decides), 'proposal' (the other side
// must accept) or 'delayed' (one side cancels, takes pactCancelHours / world speed). Missing = not allowed.
diplomacyStates: ['war', 'neutral', 'nap', 'confed'],
diplomacyMoves: {
neutral: { war: 'immediate', nap: 'proposal', confed: 'proposal' },
nap: { neutral: 'delayed', war: 'delayed', confed: 'proposal' },
confed: { neutral: 'delayed', nap: 'delayed', war: 'delayed' },
war: { neutral: 'proposal', nap: 'proposal' },
},
pactCancelHours: 24,
// Messages: plain text, DB-backed send limits per sender (counted over the window, real time).
messageMax: 2000,
messageLimits: { dm10min: 15, dmHour: 60, broadcastHour: 20 },
maxBlocks: 100,
rankingsPageMax: 100,
};
const WORLD_DEFAULTS = {
name: 'World 1',
speed: 1,
@ -101,6 +142,99 @@
preset: 'standard',
};
return { HOUR_MS, RESOURCES, FORMULAS, FIELD_SLOTS, FIELD_TYPES, FIELD_PRODUCES, FIELDS_PER_TYPE, WILD_SLOTS,
BUILDINGS, START, TILE, PROTECTION_HOURS, AS_RANGE, WORLD_DEFAULTS };
// ------------------------------------------------------------------ military (stages 3 and 4)
// Units. Stats: attack, defence, speed (tiles/hour at 1x), carry (loot per unit), draw (power points/hour while
// stationed), cost (per unit), time (seconds per unit at 1x, before building level), building (where it is trained),
// requires (all must hold; the training building is always required at level 1). `fixed: true` = never moves.
// role: scout | defender | attacker | siege | settler | conquest. Ids are generic; i18n.js holds the names.
const UNITS = {
port_scanner: { role: 'scout', building: 'noc', attack: 0, defence: 1, speed: 20, carry: 0, draw: 1, cost: { fiber: 30, hardware: 30, capital: 20 }, time: 90, requires: [{ type: 'noc', level: 1 }] },
soc_analyst: { role: 'defender', building: 'noc', attack: 5, defence: 25, speed: 7, carry: 0, draw: 1, cost: { fiber: 60, hardware: 20, capital: 10 }, time: 120, requires: [{ type: 'noc', level: 1 }] },
blue_team: { role: 'defender', building: 'noc', attack: 10, defence: 80, speed: 5, carry: 0, draw: 2, cost: { fiber: 100, hardware: 90, capital: 50 }, time: 300, requires: [{ type: 'noc', level: 5 }, { type: 'research_lab', level: 2 }] },
honeypot: { role: 'defender', building: 'noc', attack: 0, defence: 100, speed: 0, carry: 0, draw: 1, cost: { fiber: 120, hardware: 80, capital: 40 }, time: 280, requires: [{ type: 'noc', level: 3 }, { type: 'research_lab', level: 1 }], fixed: true },
script_crew: { role: 'attacker', building: 'ops_lab', attack: 40, defence: 10, speed: 8, carry: 50, draw: 1, cost: { fiber: 80, hardware: 40, capital: 30 }, time: 180, requires: [{ type: 'ops_lab', level: 1 }] },
botnet: { role: 'attacker', building: 'ops_lab', attack: 90, defence: 25, speed: 14, carry: 150, draw: 3, cost: { fiber: 200, hardware: 160, capital: 120 }, time: 420, requires: [{ type: 'ops_lab', level: 5 }, { type: 'research_lab', level: 5 }] },
ddos_rig: { role: 'siege', building: 'ops_lab', attack: 60, defence: 20, speed: 5, carry: 0, draw: 3, cost: { fiber: 300, hardware: 250, capital: 100 }, time: 600, requires: [{ type: 'ops_lab', level: 8 }, { type: 'research_lab', level: 6 }] },
exploit_kit: { role: 'siege', building: 'ops_lab', attack: 40, defence: 10, speed: 5, carry: 0, draw: 3, cost: { fiber: 280, hardware: 300, capital: 150 }, time: 720, requires: [{ type: 'ops_lab', level: 10 }, { type: 'research_lab', level: 8 }] },
rollout_crew: { role: 'settler', building: 'rollout_depot', attack: 0, defence: 5, speed: 6, carry: 0, draw: 2, cost: { fiber: 400, hardware: 300, capital: 300 }, time: 900, requires: [{ type: 'rollout_depot', level: 1 }] },
ma_team: { role: 'conquest', building: 'rollout_depot', attack: 0, defence: 5, speed: 6, carry: 0, draw: 2, cost: { fiber: 700, hardware: 600, capital: 800 }, time: 1200, requires: [{ type: 'rollout_depot', level: 5 }] },
};
// Display / UI order.
const UNIT_ORDER = ['port_scanner', 'soc_analyst', 'blue_team', 'honeypot', 'script_crew', 'botnet', 'ddos_rig', 'exploit_kit', 'rollout_crew', 'ma_team'];
const MILITARY = {
researchPerLevel: 0.05, // +5% attack or defence per research level of one unit type
trainSpeedPerLevel: 0.03, // training time / (1 + 0.03 * level of the training building)
maxTrainQueue: 8, // batches waiting per training building
maxBatch: 5000,
defenceBase: 10, // flat defence of any POP, before the firewall multiplier
rigFirewallDivisor: 10, // every 10 DDoS rigs lower the effective firewall by one level
lossExponent: 1.5,
raidLossFactor: 0.5, // raid: both sides lose 0.5 * (weak/strong)^1.5
cachePerLevel: 0.10, // Rack hall hides 10% of the stock per level from raids ...
cacheMax: 0.5, // ... up to 50%
kitsMin: 5, // exploit kits (survivors) needed to damage a building at all
kitsPerLevel: 20, // levels destroyed = max(1, floor(kits / 20))
loyaltyDrop: [15, 30], // inclusive range, rolled from the world seed
scanBuildingsRatio: 2, // attacking scanners needed per defending scanner to see buildings
scanLossExponent: 1.5,
recallWindowMs: 90 * 1000,
reportRetentionMs: 14 * 24 * HOUR_MS, // real time
pointsPerCost: 0.01, // battle points per resource point of killed units (operator_stats)
decommissionHours: 24, // offline this long (divided by world speed) and units are decommissioned
batteryEpsilon: 1e-6,
maxLists: 200,
};
// Research: +5% (MILITARY.researchPerLevel) attack or defence for ONE unit type per level, per POP, in the Research lab.
// Level n needs a Research lab of level n + labOffset. One research at a time per POP.
const RESEARCH = {
stats: ['attack', 'defence'],
maxLevel: 10,
labOffset: 2,
costFactor: 8, // times the unit's own cost, per level, growing with costGrowth
costGrowth: 1.35,
timeBase: 1800, // seconds at level 1
timeGrowth: 1.3,
labSpeedPerLevel: 0.03,
};
// Founding and conquering POPs (stage 4).
const EXPANSION = {
settleUnit: 'rollout_crew',
crews: 3, // exactly this many found a POP; consumed
maxDistance: 15, // from any own POP
startResources: { fiber: 250, hardware: 250, capital: 250 }, // "1 h of resources" for a POP that produces nothing yet
foundedLoyalty: 100,
conqueredLoyalty: 25,
conquestUnit: 'ma_team', // one per takeover counts and is used up when it lowers loyalty
};
// Resource transport between POPs (trade is built on it): `links` concurrent transports = Internet exchange level.
const TRANSPORT = { building: 'internet_exchange', speed: 12, capacityPerLink: 500 };
// Which unit roles may go on which movement type.
const MOVE_ROLES = {
scan: ['scout'],
raid: ['attacker', 'defender'],
attack: ['attacker', 'defender', 'siege'],
takeover: ['attacker', 'defender', 'siege', 'conquest'],
reinforce: ['scout', 'defender', 'attacker', 'siege', 'settler', 'conquest'],
settle: ['settler'],
};
// Incumbent (NPC) sites: static defence that grows with world age. Taking one (first time per operator) gives a
// one-time Hardware bonus; each distinct site taken adds +10% research speed, up to researchSpeedMax.
const INCUMBENT = {
baseDefence: 600,
variance: 0.25, // per-site factor 1 +- variance, from the world seed
perDayGrowth: 0.04, // +4% of base per world day (world days = real days * speed)
scanStrength: 12, // counts as this many scanners when scanned
hardwareBonus: 2500,
researchSpeedBonus: 0.10,
researchSpeedMax: 0.5,
};
return { UNITS, UNIT_ORDER, MILITARY, RESEARCH, EXPANSION, TRANSPORT, MOVE_ROLES, INCUMBENT, HOUR_MS, RESOURCES, FORMULAS, FIELD_SLOTS, FIELD_TYPES, FIELD_PRODUCES, FIELDS_PER_TYPE, WILD_SLOTS,
SOCIAL, BUILDINGS, START, TILE, PROTECTION_HOURS, AS_RANGE, WORLD_DEFAULTS };
}));

376
public/js/i18n.js Normal file
View file

@ -0,0 +1,376 @@
'use strict';
/*
* UPSTREAM strings (en + nb) and number/time formatting. Pure: no DOM, no storage, no Date.now(). Loads as a browser
* script (window.UpstreamI18n) and as a Node module (the key-parity test lives in test/client-i18n.test.js).
*
* Player-facing names of buildings, resources and tile types live ONLY here (and as ids in data.js); game logic uses
* the generic ids. Keys are flat dotted strings. `{name}` placeholders are filled by t(). Both languages must have
* identical key sets and identical placeholders: the test enforces it.
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory();
else root.UpstreamI18n = factory();
}(typeof self !== 'undefined' ? self : this, function () {
const LANGS = ['en', 'nb'];
const en = {
'app.name': 'UPSTREAM',
'app.tagline': 'Build your POP. Connect the region. Outlast the competition.',
'nav.pop': 'POP', 'nav.map': 'Map', 'nav.alerts': 'Alerts', 'nav.settings': 'Settings', 'nav.label': 'Main navigation',
'screen.pop': 'Your POP', 'screen.map': 'Region map', 'screen.alerts': 'Alerts', 'screen.settings': 'Settings',
'common.cancel': 'Cancel', 'common.close': 'Close', 'common.back': 'Back', 'common.save': 'Save', 'common.confirm': 'Confirm',
'common.loading': 'Loading…', 'common.retry': 'Retry', 'common.none': 'None', 'common.yes': 'Yes', 'common.no': 'No',
'common.offline': 'Connection lost. Retrying…', 'common.online': 'Back online.',
'common.perHour': '/h', 'common.tiles': 'tiles',
'res.fiber': 'Fiber', 'res.hardware': 'Hardware', 'res.capital': 'Capital', 'res.power': 'Power', 'res.battery': 'Battery',
'tile.land': 'Open land', 'tile.rural': 'Unconnected rural area', 'tile.incumbent': 'Legacy incumbent site', 'tile.pop': 'POP', 'tile.void': 'Off the map',
'building.cable_yard.name': 'Cable yard',
'building.cable_yard.desc': 'Spools, reels and a suspicious amount of duct tape. Produces Fiber.',
'building.supply_depot.name': 'Supply depot',
'building.supply_depot.desc': 'Racks of spare parts nobody dares to count. Produces Hardware.',
'building.sales_office.name': 'Sales office',
'building.sales_office.desc': 'Convinces customers that 99.9% is a lot of nines. Produces Capital.',
'building.substation.name': 'Substation',
'building.substation.desc': 'Turns mains hum into power points. Everything you build draws from it.',
'building.core_router.name': 'Core router',
'building.core_router.desc': 'The thing everything else routes through. Shortens all build times.',
'building.rack_hall.name': 'Rack hall',
'building.rack_hall.desc': 'Floor space with good airflow. Sets how much Fiber, Hardware and Capital you can store.',
'building.battery_bank.name': 'Battery bank',
'building.battery_bank.desc': 'Buys you time when power is short. Sets the power buffer.',
'building.firewall.name': 'Firewall',
'building.firewall.desc': 'Default deny, mostly. Boosts the defence of the whole POP.',
'building.noc.name': 'NOC',
'building.noc.desc': 'Screens full of green dots and one red one. Trains defensive crews.',
'building.research_lab.name': 'Research lab',
'building.research_lab.desc': 'Where the clever ideas get a budget. Unlocks units and upgrades.',
'building.ops_lab.name': 'Ops lab',
'building.ops_lab.desc': 'Tools for the operations people do not talk about. Trains offensive units.',
'building.internet_exchange.name': 'Internet exchange',
'building.internet_exchange.desc': 'Where everyone meets and pretends not to compete. Trade between POPs.',
'building.peering_office.name': 'Peering office',
'building.peering_office.desc': 'Handshakes and mutual benefit. Found or join an alliance.',
'building.rollout_depot.name': 'Rollout depot',
'building.rollout_depot.desc': 'Trucks, trenchers and optimism. Trains the crews that found new POPs.',
'building.backbone_node.name': 'Backbone node',
'building.backbone_node.desc': 'The end-game building. Level 100 wins the world.',
'pop.capital': 'Capital POP',
'pop.rename': 'Rename POP', 'pop.rename.label': 'POP name', 'pop.rename.done': 'POP renamed.',
'pop.coords': 'x {x} · y {y}',
'pop.loyalty': 'Customer loyalty', 'pop.footprint': 'Footprint', 'pop.footprintPerDay': '+{n}/day',
'pop.queue.title': 'Build queue', 'pop.queue.slots': '{used}/{total} slots',
'pop.queue.empty': 'Nothing under construction. An idle network is not the same as a healthy one.',
'pop.queue.to': 'to level {n}', 'pop.queue.cancel': 'Cancel build',
'pop.fields.title': 'Resource fields', 'pop.fields.group': '{name} · {n} fields',
'pop.infra.title': 'Infrastructure',
'pop.level': 'Lv {n}', 'pop.notBuilt': 'Not built', 'pop.max': 'Max', 'pop.inQueue': 'Building',
'pop.upgradeReady': 'Can upgrade', 'pop.locked': 'Requirements missing',
'pop.load.error': 'Could not load this POP.',
'pop.noTown': 'No POP on this account yet.',
'pop.bonus': 'Rural bonus', 'pop.bonus.none': 'No rural areas in reach',
'power.title': 'Power', 'power.out': 'Output', 'power.draw': 'Draw', 'power.net': 'Net', 'power.buffer': 'Buffer',
'power.ok': 'Stable', 'power.draining': 'Draining: empty in {t}', 'power.charging': 'Charging: full in {t}', 'power.full': 'Buffer full',
'power.empty': 'Buffer empty: units offline', 'power.unit': 'pts',
'sheet.level': 'Level {n}', 'sheet.nextLevel': 'Next: level {n}',
'sheet.cost': 'Cost', 'sheet.time': 'Build time', 'sheet.requires': 'Requires', 'sheet.have': 'have {n}',
'sheet.build': 'Build level {n}', 'sheet.upgrade': 'Upgrade to level {n}', 'sheet.building': 'Building…',
'sheet.maxed': 'Fully upgraded', 'sheet.underway': 'Under construction', 'sheet.done': 'Done in {t}',
'sheet.affordableIn': 'Affordable in {t}', 'sheet.capTooLow': 'Needs a bigger Rack hall (it holds {cap})',
'sheet.cancel': 'Cancel this build', 'sheet.cancel.confirm': 'Cancel {name} to level {n}?',
'sheet.cancel.refund': '80% of the cost comes back to the POP.', 'sheet.cancel.keep': 'Keep building',
'sheet.built': 'Queued {name} to level {n}.', 'sheet.cancelled': 'Build cancelled. Refund added.',
'sheet.preview.output': 'Output {a} → {b} per hour', 'sheet.preview.storage': 'Storage {a} → {b}',
'sheet.preview.battery': 'Power buffer {a} → {b}', 'sheet.preview.core': 'Build time ×{a} → ×{b}',
'sheet.preview.core2': 'Level {n} opens a second build slot.', 'sheet.preview.draw': 'Power draw +{n}',
'sheet.preview.firewall': 'Defence ×{a} → ×{b}', 'sheet.preview.output.now': 'Output now: {a} per hour',
'map.centre': 'Centre on my POP', 'map.zoomIn': 'Zoom in', 'map.zoomOut': 'Zoom out',
'map.label': 'Region map. Drag to pan, pinch or scroll to zoom, tap a tile for details.',
'map.noWorld': 'This account has not joined a world yet.', 'map.error': 'Could not load part of the map.',
'map.scanning': 'Scanning…', 'map.legend.rural': 'Rural', 'map.legend.incumbent': 'Incumbent', 'map.legend.you': 'You', 'map.legend.rival': 'Rival',
'map.info.coords': 'x {x} · y {y}', 'map.info.distance': '{d} tiles from your capital',
'map.info.land': 'Nothing here yet. Not a single strand of fibre.',
'map.info.rural': 'POPs within {n} tiles get +{p}% {res} output while they stay connected.',
'map.info.incumbent': 'A legacy telco stronghold. It never attacks. It does not need to.',
'map.info.operator': 'Operator', 'map.info.as': 'AS number', 'map.info.yours': 'Your POP', 'map.info.rival': 'Rival operator',
'map.info.protected': 'Beginner protection, no attacks in or out.', 'map.info.open': 'Open POP', 'map.info.capital': 'Capital',
'alerts.empty': 'All quiet on the wire.', 'alerts.error': 'Could not load alerts.', 'alerts.new': 'new',
'alerts.build_done': '{name} reached level {level}', 'alerts.build_done.in': 'in {town}',
'alerts.unknown': 'Event: {type}', 'alerts.more': 'Older alerts hidden', 'alerts.count': '{n} unread',
'settings.language': 'Language', 'settings.lang.en': 'English', 'settings.lang.nb': 'Norsk (bokmål)',
'settings.account': 'Account', 'settings.username': 'Username', 'settings.operator': 'Operator', 'settings.as': 'AS number', 'settings.world': 'World',
'settings.worldInfo': '{name} · {speed}× speed · radius {r}',
'settings.devices': 'Devices', 'settings.devices.hint': 'Each device holds its own token. Revoke one and that device is logged out.',
'settings.device.current': 'This device', 'settings.device.unnamed': 'Unnamed device', 'settings.device.revoke': 'Revoke',
'settings.device.revoked': 'Device revoked.', 'settings.device.lastUsed': 'Last used {t}', 'settings.device.created': 'Added {t}',
'settings.logout': 'Log out', 'settings.logout.confirm': 'Log out on this device?',
'settings.about': 'About', 'settings.about.text': 'UPSTREAM is a hobby project. Fictional operators only; any resemblance to real networks is a routing leak.',
'auth.login': 'Log in', 'auth.signup': 'Sign up', 'auth.username': 'Username', 'auth.password': 'Password',
'auth.invite': 'Invite code', 'auth.invite.hint': 'This server needs an invite code to sign up.',
'auth.toSignup': 'New operator? Create an account', 'auth.toLogin': 'Already peering? Log in',
'auth.username.hint': '3-20 letters, digits, _ or -', 'auth.password.hint': 'At least 8 characters',
'auth.working': 'Working…', 'auth.expired': 'Your session ended. Log in again.',
'auth.welcome': 'Welcome, operator.',
'time.d': 'd', 'time.h': 'h', 'time.m': 'm', 'time.s': 's',
'time.now': 'just now', 'time.ago': '{t} ago', 'time.in': 'in {t}',
'err.bad_request': 'The request was malformed.',
'err.validation_failed': 'Some field is missing or looks wrong.',
'err.unauthorized': 'You are not logged in.',
'err.invalid_credentials': 'Wrong username or password.',
'err.forbidden': 'You may not do that.',
'err.not_found': 'That no longer exists.',
'err.method_not_allowed': 'That is not allowed here.',
'err.conflict': 'That clashes with the current state. Refresh and try again.',
'err.request_in_progress': 'Still working on your last request.',
'err.idempotency_key_reuse': 'That request clashed with an earlier one. Try again.',
'err.payload_too_large': 'That is too much data.',
'err.rate_limited': 'Too many requests. Slow down a little.',
'err.internal_error': 'Something broke on the server side.',
'err.signup_closed': 'Signup needs a valid invite code.',
'err.username_taken': 'That username is taken.',
'err.world_full': 'No room left on the map.',
'err.unknown_building': 'No such building or slot.',
'err.not_buildable': 'That cannot be built here.',
'err.max_level': 'Already at the maximum level.',
'err.requirements_not_met': 'A required building is missing.',
'err.already_queued': 'That is already under construction.',
'err.queue_full': 'All build slots are busy.',
'err.not_enough_resources': 'Not enough resources yet.',
'err.network_error': 'Cannot reach the server.',
'err.unknown': 'Something went wrong.',
};
const nb = {
'app.name': 'UPSTREAM',
'app.tagline': 'Bygg din POP. Koble sammen regionen. Overlev konkurrentene.',
'nav.pop': 'POP', 'nav.map': 'Kart', 'nav.alerts': 'Varsler', 'nav.settings': 'Innstillinger', 'nav.label': 'Hovednavigasjon',
'screen.pop': 'Din POP', 'screen.map': 'Regionkart', 'screen.alerts': 'Varsler', 'screen.settings': 'Innstillinger',
'common.cancel': 'Avbryt', 'common.close': 'Lukk', 'common.back': 'Tilbake', 'common.save': 'Lagre', 'common.confirm': 'Bekreft',
'common.loading': 'Laster…', 'common.retry': 'Prøv igjen', 'common.none': 'Ingen', 'common.yes': 'Ja', 'common.no': 'Nei',
'common.offline': 'Mistet forbindelsen. Prøver igjen…', 'common.online': 'Tilbake på nett.',
'common.perHour': '/t', 'common.tiles': 'ruter',
'res.fiber': 'Fiber', 'res.hardware': 'Maskinvare', 'res.capital': 'Kapital', 'res.power': 'Strøm', 'res.battery': 'Batteri',
'tile.land': 'Åpent land', 'tile.rural': 'Utkoblet landsbygd', 'tile.incumbent': 'Gammelt monopolsted', 'tile.pop': 'POP', 'tile.void': 'Utenfor kartet',
'building.cable_yard.name': 'Kabelgård',
'building.cable_yard.desc': 'Trommer, kveiler og mistenkelig mye teip. Produserer Fiber.',
'building.supply_depot.name': 'Utstyrslager',
'building.supply_depot.desc': 'Hyller med reservedeler ingen tør telle. Produserer Maskinvare.',
'building.sales_office.name': 'Salgskontor',
'building.sales_office.desc': 'Overbeviser kunder om at 99,9 % er mange nitall. Produserer Kapital.',
'building.substation.name': 'Transformatorstasjon',
'building.substation.desc': 'Gjør nettbrumming om til strømpoeng. Alt du bygger trekker herfra.',
'building.core_router.name': 'Kjerneruter',
'building.core_router.desc': 'Alt annet ruter gjennom denne. Gjør alle byggetider kortere.',
'building.rack_hall.name': 'Racksal',
'building.rack_hall.desc': 'Gulvplass med god luftstrøm. Bestemmer hvor mye Fiber, Maskinvare og Kapital du kan lagre.',
'building.battery_bank.name': 'Batteribank',
'building.battery_bank.desc': 'Kjøper deg tid når strømmen er knapp. Bestemmer strømbufferen.',
'building.firewall.name': 'Brannmur',
'building.firewall.desc': 'Stort sett «deny all». Styrker forsvaret i hele POP-en.',
'building.noc.name': 'NOC',
'building.noc.desc': 'Skjermer full av grønne prikker og én rød. Trener forsvarsmannskap.',
'building.research_lab.name': 'Forskningslab',
'building.research_lab.desc': 'Der kloke ideer får budsjett. Låser opp enheter og oppgraderinger.',
'building.ops_lab.name': 'Ops-lab',
'building.ops_lab.desc': 'Verktøy for operasjoner ingen snakker høyt om. Trener angrepsenheter.',
'building.internet_exchange.name': 'Internettknutepunkt',
'building.internet_exchange.desc': 'Der alle møtes og later som de ikke konkurrerer. Handel mellom POP-er.',
'building.peering_office.name': 'Peeringkontor',
'building.peering_office.desc': 'Håndtrykk og gjensidig nytte. Stift eller bli med i en allianse.',
'building.rollout_depot.name': 'Utrullingsdepot',
'building.rollout_depot.desc': 'Lastebiler, grøftefresere og optimisme. Trener mannskapene som stifter nye POP-er.',
'building.backbone_node.name': 'Ryggradsnode',
'building.backbone_node.desc': 'Sluttspillbygget. Nivå 100 vinner verdenen.',
'pop.capital': 'Hoved-POP',
'pop.rename': 'Gi POP-en nytt navn', 'pop.rename.label': 'POP-navn', 'pop.rename.done': 'POP-en har fått nytt navn.',
'pop.coords': 'x {x} · y {y}',
'pop.loyalty': 'Kundelojalitet', 'pop.footprint': 'Fotavtrykk', 'pop.footprintPerDay': '+{n}/døgn',
'pop.queue.title': 'Byggekø', 'pop.queue.slots': '{used}/{total} plasser',
'pop.queue.empty': 'Ingenting under bygging. Et stille nett er ikke det samme som et friskt nett.',
'pop.queue.to': 'til nivå {n}', 'pop.queue.cancel': 'Avbryt bygging',
'pop.fields.title': 'Ressursfelt', 'pop.fields.group': '{name} · {n} felt',
'pop.infra.title': 'Infrastruktur',
'pop.level': 'Nv {n}', 'pop.notBuilt': 'Ikke bygget', 'pop.max': 'Maks', 'pop.inQueue': 'Under bygging',
'pop.upgradeReady': 'Kan oppgraderes', 'pop.locked': 'Mangler krav',
'pop.load.error': 'Kunne ikke laste denne POP-en.',
'pop.noTown': 'Ingen POP på denne kontoen ennå.',
'pop.bonus': 'Landsbygdbonus', 'pop.bonus.none': 'Ingen landsbygd innen rekkevidde',
'power.title': 'Strøm', 'power.out': 'Produksjon', 'power.draw': 'Forbruk', 'power.net': 'Netto', 'power.buffer': 'Buffer',
'power.ok': 'Stabil', 'power.draining': 'Tapper: tom om {t}', 'power.charging': 'Lader: full om {t}', 'power.full': 'Bufferen er full',
'power.empty': 'Bufferen er tom: enheter er frakoblet', 'power.unit': 'p',
'sheet.level': 'Nivå {n}', 'sheet.nextLevel': 'Neste: nivå {n}',
'sheet.cost': 'Kostnad', 'sheet.time': 'Byggetid', 'sheet.requires': 'Krever', 'sheet.have': 'har {n}',
'sheet.build': 'Bygg nivå {n}', 'sheet.upgrade': 'Oppgrader til nivå {n}', 'sheet.building': 'Bygger…',
'sheet.maxed': 'Fullt oppgradert', 'sheet.underway': 'Under bygging', 'sheet.done': 'Ferdig om {t}',
'sheet.affordableIn': 'Råd om {t}', 'sheet.capTooLow': 'Trenger større Racksal (rommer {cap})',
'sheet.cancel': 'Avbryt denne byggingen', 'sheet.cancel.confirm': 'Avbryte {name} til nivå {n}?',
'sheet.cancel.refund': '80 % av kostnaden går tilbake til POP-en.', 'sheet.cancel.keep': 'Fortsett byggingen',
'sheet.built': '{name} til nivå {n} er satt i kø.', 'sheet.cancelled': 'Bygging avbrutt. Refusjon lagt til.',
'sheet.preview.output': 'Produksjon {a} → {b} per time', 'sheet.preview.storage': 'Lager {a} → {b}',
'sheet.preview.battery': 'Strømbuffer {a} → {b}', 'sheet.preview.core': 'Byggetid ×{a} → ×{b}',
'sheet.preview.core2': 'Nivå {n} åpner en ekstra byggeplass.', 'sheet.preview.draw': 'Strømforbruk +{n}',
'sheet.preview.firewall': 'Forsvar ×{a} → ×{b}', 'sheet.preview.output.now': 'Produksjon nå: {a} per time',
'map.centre': 'Sentrer på min POP', 'map.zoomIn': 'Zoom inn', 'map.zoomOut': 'Zoom ut',
'map.label': 'Regionkart. Dra for å flytte, knip eller scroll for å zoome, trykk på en rute for detaljer.',
'map.noWorld': 'Denne kontoen er ikke med i noen verden ennå.', 'map.error': 'Kunne ikke laste deler av kartet.',
'map.scanning': 'Skanner…', 'map.legend.rural': 'Landsbygd', 'map.legend.incumbent': 'Monopolist', 'map.legend.you': 'Deg', 'map.legend.rival': 'Rival',
'map.info.coords': 'x {x} · y {y}', 'map.info.distance': '{d} ruter fra hovedstaden din',
'map.info.land': 'Ingenting her ennå. Ikke en eneste fiberstreng.',
'map.info.rural': 'POP-er innen {n} ruter får +{p} % {res}-produksjon så lenge de er tilkoblet.',
'map.info.incumbent': 'Et gammelt telekomfestning. Det angriper aldri. Det trenger ikke.',
'map.info.operator': 'Operatør', 'map.info.as': 'AS-nummer', 'map.info.yours': 'Din POP', 'map.info.rival': 'Rivaliserende operatør',
'map.info.protected': 'Nybegynnerbeskyttelse, ingen angrep inn eller ut.', 'map.info.open': 'Åpne POP', 'map.info.capital': 'Hovedstad',
'alerts.empty': 'Stille på linja.', 'alerts.error': 'Kunne ikke laste varsler.', 'alerts.new': 'ny',
'alerts.build_done': '{name} nådde nivå {level}', 'alerts.build_done.in': 'i {town}',
'alerts.unknown': 'Hendelse: {type}', 'alerts.more': 'Eldre varsler er skjult', 'alerts.count': '{n} uleste',
'settings.language': 'Språk', 'settings.lang.en': 'English', 'settings.lang.nb': 'Norsk (bokmål)',
'settings.account': 'Konto', 'settings.username': 'Brukernavn', 'settings.operator': 'Operatør', 'settings.as': 'AS-nummer', 'settings.world': 'Verden',
'settings.worldInfo': '{name} · {speed}× fart · radius {r}',
'settings.devices': 'Enheter', 'settings.devices.hint': 'Hver enhet har sin egen token. Tilbakekall én, så logges den enheten ut.',
'settings.device.current': 'Denne enheten', 'settings.device.unnamed': 'Enhet uten navn', 'settings.device.revoke': 'Tilbakekall',
'settings.device.revoked': 'Enheten er tilbakekalt.', 'settings.device.lastUsed': 'Sist brukt {t}', 'settings.device.created': 'Lagt til {t}',
'settings.logout': 'Logg ut', 'settings.logout.confirm': 'Logge ut på denne enheten?',
'settings.about': 'Om', 'settings.about.text': 'UPSTREAM er et hobbyprosjekt. Kun fiktive operatører; likhet med ekte nett er en rutelekkasje.',
'auth.login': 'Logg inn', 'auth.signup': 'Registrer deg', 'auth.username': 'Brukernavn', 'auth.password': 'Passord',
'auth.invite': 'Invitasjonskode', 'auth.invite.hint': 'Denne serveren krever invitasjonskode for å registrere deg.',
'auth.toSignup': 'Ny operatør? Opprett konto', 'auth.toLogin': 'Allerede peeret? Logg inn',
'auth.username.hint': '3-20 bokstaver, tall, _ eller -', 'auth.password.hint': 'Minst 8 tegn',
'auth.working': 'Jobber…', 'auth.expired': 'Økten er over. Logg inn igjen.',
'auth.welcome': 'Velkommen, operatør.',
'time.d': 'd', 'time.h': 't', 'time.m': 'm', 'time.s': 's',
'time.now': 'akkurat nå', 'time.ago': '{t} siden', 'time.in': 'om {t}',
'err.bad_request': 'Forespørselen var ugyldig.',
'err.validation_failed': 'Et felt mangler eller ser feil ut.',
'err.unauthorized': 'Du er ikke logget inn.',
'err.invalid_credentials': 'Feil brukernavn eller passord.',
'err.forbidden': 'Det har du ikke lov til.',
'err.not_found': 'Det finnes ikke lenger.',
'err.method_not_allowed': 'Det er ikke tillatt her.',
'err.conflict': 'Det kolliderer med dagens tilstand. Oppdater og prøv igjen.',
'err.request_in_progress': 'Jobber fortsatt med forrige forespørsel.',
'err.idempotency_key_reuse': 'Forespørselen kolliderte med en tidligere. Prøv igjen.',
'err.payload_too_large': 'Det er for mye data.',
'err.rate_limited': 'For mange forespørsler. Ta det litt roligere.',
'err.internal_error': 'Noe gikk i stykker hos serveren.',
'err.signup_closed': 'Registrering krever gyldig invitasjonskode.',
'err.username_taken': 'Brukernavnet er opptatt.',
'err.world_full': 'Ikke plass igjen på kartet.',
'err.unknown_building': 'Ingen slik bygning eller plass.',
'err.not_buildable': 'Det kan ikke bygges her.',
'err.max_level': 'Allerede på høyeste nivå.',
'err.requirements_not_met': 'En påkrevd bygning mangler.',
'err.already_queued': 'Det er allerede under bygging.',
'err.queue_full': 'Alle byggeplasser er opptatt.',
'err.not_enough_resources': 'Ikke nok ressurser ennå.',
'err.network_error': 'Får ikke kontakt med serveren.',
'err.unknown': 'Noe gikk galt.',
};
const strings = { en, nb };
function detectLang(navLang) {
const l = String(navLang || '').toLowerCase();
return /^(nb|nn|no)(\b|-|_)/.test(l) || l === 'no' ? 'nb' : 'en';
}
// Fill {placeholders}. Missing vars stay visible as {name}, so a bug shows up on screen instead of as "undefined".
function fill(s, vars) {
if (!vars) return s;
return s.replace(/\{(\w+)\}/g, (m, k) => (Object.prototype.hasOwnProperty.call(vars, k) ? String(vars[k]) : m));
}
function t(lang, key, vars) {
const table = strings[lang] || en;
const s = Object.prototype.hasOwnProperty.call(table, key) ? table[key] : (Object.prototype.hasOwnProperty.call(en, key) ? en[key] : key);
return fill(s, vars);
}
const locale = (lang) => (lang === 'nb' ? 'nb-NO' : 'en-GB');
const nfCache = {};
function nf(lang, digits) {
const k = lang + digits;
if (!nfCache[k]) nfCache[k] = new Intl.NumberFormat(locale(lang), { minimumFractionDigits: digits, maximumFractionDigits: digits });
return nfCache[k];
}
// Whole numbers for amounts. Compact (12.3k, 4.5M) from 100 000 up so nothing overflows a phone-width chip.
function fmtNum(lang, n) {
n = Number(n) || 0;
const a = Math.abs(n);
if (a >= 1e6) return nf(lang, 1).format(Math.floor(n / 1e5) / 10) + 'M';
if (a >= 1e5) return nf(lang, 0).format(Math.floor(n / 1e3)) + 'k';
return nf(lang, 0).format(Math.floor(n + 1e-9));
}
// One decimal below 100, whole numbers above; always signed when `signed` (rates: +12.4, -3).
function fmtDec(lang, n, signed) {
n = Number(n) || 0;
const a = Math.abs(n);
const s = a >= 100 ? nf(lang, 0).format(Math.round(a)) : nf(lang, 1).format(a);
const sign = n < 0 ? '−' : (signed && n > 0 ? '+' : '');
return sign + s;
}
// "2d 3h", "2h 5m", "4m 10s", "12s". At most `parts` units (default 2), rounding the last one up never; floors.
function fmtDuration(lang, ms, parts) {
parts = parts || 2;
let s = Math.max(0, Math.floor(ms / 1000));
if (s < 1) return '0' + t(lang, 'time.s');
const units = [['time.d', 86400], ['time.h', 3600], ['time.m', 60], ['time.s', 1]];
const out = [];
for (const [k, size] of units) {
const v = Math.floor(s / size);
s -= v * size;
if (v > 0 || out.length) out.push(v + t(lang, k));
if (out.length >= parts) break;
}
while (out.length > 1 && /^0\D/.test(out[out.length - 1])) out.pop(); // "1h 0m" -> "1h"
return out.join(' ');
}
// Countdown clock "h:mm:ss" (or "m:ss" under an hour). Ceil so it never shows 0:00 while time is left.
function fmtClock(ms) {
const total = Math.max(0, Math.ceil(ms / 1000));
const h = Math.floor(total / 3600), m = Math.floor((total % 3600) / 60), s = total % 60;
const p = (v) => (v < 10 ? '0' : '') + v;
return h > 0 ? h + ':' + p(m) + ':' + p(s) : m + ':' + p(s);
}
// "5m ago", "just now". `diff` = now - then in ms.
function fmtAgo(lang, diff) {
if (diff < 45000) return t(lang, 'time.now');
return t(lang, 'time.ago', { t: fmtDuration(lang, diff, 1) });
}
// Fictional AS numbers come from the private 32-bit range; shown as "AS4200000123".
const fmtAs = (n) => 'AS' + n;
return { LANGS, strings, t, fill, detectLang, fmtNum, fmtDec, fmtDuration, fmtClock, fmtAgo, fmtAs };
}));

404
public/js/main.js Normal file
View file

@ -0,0 +1,404 @@
'use strict';
/*
* The shell: session, screen registry, bottom nav, resource bar (HUD), ticker, language. Screens live in
* js/screens/*.js and register themselves:
*
* App.registerScreen({
* id: 'pop', titleKey: 'screen.pop', navKey: 'nav.pop', icon: 'pop', // nav: false hides it from the nav
* hud: true, // show the resource bar above it
* render(container) {}, // once, when the screen is first shown: build the persistent DOM
* onShow(params) {}, // every time it becomes visible
* onHide() {},
* onLang() {}, // optional: language changed while visible (default: onShow again)
* });
*
* Later stages add screens (units, reports, ...) the same way: one file, one registerScreen call, one script tag.
* Everything time-based is computed from api.serverNow() (server clock), never from the device clock alone.
*/
(function () {
const { h, clear, icon, toast, safeStore } = UI;
const I = UpstreamI18n;
const R = UpstreamRules;
const D = UpstreamData;
const api = UpstreamApi.createApi({
fetch: window.fetch.bind(window),
storage: (function () { try { return window.localStorage; } catch (e) { return null; } }()),
});
const LANG_KEY = 'upstream.lang';
const TOWN_KEY = 'upstream.town';
const SEEN_KEY = 'upstream.alerts.seen.';
const App = {
api,
state: { user: null, operators: [], operator: null, world: null, towns: [], townId: null, townData: null, townFetchedAt: 0, lang: 'en', unread: 0 },
screens: new Map(),
current: null,
params: null,
};
window.App = App;
// ------------------------------------------------------------------ tiny event bus (town, session, lang)
const bus = {};
App.on = (evt, fn) => { (bus[evt] = bus[evt] || new Set()).add(fn); return () => bus[evt].delete(fn); };
App.emit = (evt, data) => { if (bus[evt]) for (const fn of Array.from(bus[evt])) { try { fn(data); } catch (e) { console.error(e); } } };
// ------------------------------------------------------------------ i18n helpers
App.t = (key, vars) => I.t(App.state.lang, key, vars);
App.fmt = {
num: (n) => I.fmtNum(App.state.lang, n),
dec: (n, signed) => I.fmtDec(App.state.lang, n, signed),
dur: (ms, parts) => I.fmtDuration(App.state.lang, ms, parts),
clock: (ms) => I.fmtClock(ms),
ago: (ms) => I.fmtAgo(App.state.lang, ms),
compact: (n) => (Math.abs(n) >= 1000 ? I.fmtDec(App.state.lang, n / 1000) + 'k' : I.fmtNum(App.state.lang, n)),
};
App.errMsg = (err) => {
const code = err && err.code;
if (code && Object.prototype.hasOwnProperty.call(I.strings.en, 'err.' + code)) return App.t('err.' + code);
return (err && err.message) || App.t('err.unknown');
};
App.resName = (r) => App.t('res.' + r);
App.buildingName = (type) => (I.strings.en['building.' + type + '.name'] ? App.t('building.' + type + '.name') : type);
App.buildingDesc = (type) => (I.strings.en['building.' + type + '.desc'] ? App.t('building.' + type + '.desc') : '');
App.setLang = (lang) => {
if (!I.LANGS.includes(lang)) return;
App.state.lang = lang;
safeStore.set(LANG_KEY, lang);
document.documentElement.lang = lang;
buildNav();
renderHud(true);
if (App.current) {
setTitle(App.current);
if (App.current.onLang) App.current.onLang(); else if (App.current.onShow) App.current.onShow(App.params || {});
}
App.emit('lang', lang);
};
// ------------------------------------------------------------------ server clock + ticker
App.now = () => api.serverNow();
const tickers = new Set();
App.onTick = (fn) => { tickers.add(fn); return () => tickers.delete(fn); };
setInterval(() => {
if (document.hidden) return;
const now = api.serverNow();
tickHud(now);
for (const fn of Array.from(tickers)) { try { fn(now); } catch (e) { console.error(e); } }
}, 250);
// ------------------------------------------------------------------ screens + nav
const elView = () => document.getElementById('view');
const elNav = () => document.getElementById('nav');
const elApp = () => document.getElementById('app');
App.registerScreen = (def) => { App.screens.set(def.id, def); };
function buildNav() {
const nav = elNav();
clear(nav);
nav.setAttribute('aria-label', App.t('nav.label'));
for (const def of App.screens.values()) {
if (def.nav === false) continue;
const badge = h('span', { class: 'nav-badge', hidden: true, 'aria-hidden': 'true' });
const btn = h('button', { class: 'nav-btn', type: 'button', dataset: { screen: def.id }, onclick: () => App.go(def.id) },
h('span', { class: 'nav-ic' }, icon(def.icon), badge), h('span', { class: 'nav-lbl', text: App.t(def.navKey || def.titleKey) }));
if (App.current && App.current.id === def.id) btn.setAttribute('aria-current', 'page');
nav.appendChild(btn);
}
updateBadge();
}
function updateBadge() {
const n = App.state.unread;
const b = elNav().querySelector('[data-screen="alerts"] .nav-badge');
if (!b) return;
b.hidden = !n;
b.textContent = n > 9 ? '9+' : String(n);
const btn = b.closest('button');
if (btn) btn.setAttribute('aria-label', App.t('nav.alerts') + (n ? ' (' + App.t('alerts.count', { n }) + ')' : ''));
}
function setTitle(def) { document.getElementById('title').textContent = def.id === 'auth' ? App.t('app.name') : App.t(def.titleKey); document.title = (def.id === 'auth' ? '' : App.t(def.titleKey) + ' · ') + 'UPSTREAM'; }
// Navigate. Sets the hash (so back/forward work); hashchange does the actual switch.
App.go = (id, params) => {
App.nextParams = params || null;
const want = '#/' + id;
if (location.hash === want) show(id, App.nextParams); else location.hash = want;
};
function show(id, params) {
if (!App.state.user && id !== 'auth') id = 'auth';
if (App.state.user && id === 'auth') id = 'pop';
const def = App.screens.get(id) || App.screens.get(App.state.user ? 'pop' : 'auth');
if (!def) return;
if (App.current && App.current !== def && App.current.onHide) App.current.onHide();
const view = elView();
for (const s of view.children) s.hidden = s.dataset.screen !== def.id;
let box = view.querySelector('[data-screen="' + def.id + '"]');
if (!box) {
box = h('section', { class: 'screen screen-' + def.id, dataset: { screen: def.id }, tabindex: '-1' });
view.appendChild(box);
if (def.render) def.render(box);
}
box.hidden = false;
App.current = def;
App.params = params || {};
const app = elApp();
app.dataset.screen = def.id;
app.dataset.state = App.state.user ? 'in' : 'out';
elNav().hidden = !App.state.user;
for (const b of elNav().children) { if (b.dataset.screen === def.id) b.setAttribute('aria-current', 'page'); else b.removeAttribute('aria-current'); }
setTitle(def);
renderHud(false);
if (def.onShow) def.onShow(App.params);
if (App.state.user && def.nav !== false) safeStore.set('upstream.screen', def.id);
}
window.addEventListener('hashchange', () => {
const id = (location.hash.match(/^#\/(\w+)/) || [])[1] || 'pop';
const p = App.nextParams; App.nextParams = null;
show(id, p);
});
// ------------------------------------------------------------------ session
// Accepts the operators array of /me or of an auth response.
App.setSession = (user, operators) => {
const st = App.state;
st.user = user;
st.operators = operators || [];
st.operator = st.operators[0] || null; // v1: one world per account
st.world = st.operator ? st.operator.world : null;
st.towns = st.operator ? st.operator.towns : [];
const saved = Number(safeStore.get(TOWN_KEY));
const pick = st.towns.find((t) => t.id === saved) || st.towns.find((t) => t.isCapital) || st.towns[0] || null;
st.townId = pick ? pick.id : null;
st.townData = null;
st.unread = 0;
App.emit('session', st);
};
App.clearSession = () => {
const st = App.state;
st.user = null; st.operators = []; st.operator = null; st.world = null; st.towns = []; st.townId = null; st.townData = null; st.unread = 0;
api.clearToken();
renderHud(true);
App.emit('session', st);
};
App.loadMe = async () => {
const me = await api.get('/me');
App.setSession(me.user, me.operators);
return me;
};
App.setTown = (id) => {
if (App.state.townId === id) return;
App.state.townId = id; App.state.townData = null;
safeStore.set(TOWN_KEY, String(id));
App.refreshTown().catch(() => {});
App.emit('townchange', id);
};
let townInflight = null;
App.refreshTown = () => {
const st = App.state;
if (!st.townId) return Promise.resolve(null);
if (townInflight) return townInflight;
const id = st.townId;
townInflight = api.get('/towns/' + id).then((r) => {
if (st.townId !== id) return null;
st.townData = r.town;
st.townFetchedAt = Date.now();
App.fetchedServerTime = r.serverTime; // the instant the amounts in r.town are exact for
rulesCache = null;
renderHud(true);
App.emit('town', r.town);
return r.town;
}).finally(() => { townInflight = null; });
return townInflight;
};
// ------------------------------------------------------------------ rules.js view of the current POP (previews + ticking)
let rulesCache = null;
// The rules.js town shape from the API response: same function the server settles with, so the numbers agree.
App.rulesTown = () => {
const st = App.state, td = st.townData;
if (!td || !st.world) return null;
if (rulesCache && rulesCache.src === td) return rulesCache.town;
const buildings = {};
let bdraw = 0;
for (const b of td.buildings) {
if (b.level <= 0) continue;
buildings[b.key] = { type: b.type, level: b.level };
const def = D.BUILDINGS[b.type];
if (def && def.kind === 'infra') bdraw += def.draw * b.level;
}
const town = {
id: td.id, speed: st.world.speed, updatedAt: App.fetchedServerTime || 0,
res: { fiber: td.resources.fiber.amount, hardware: td.resources.hardware.amount, capital: td.resources.capital.amount, battery: td.power.buffer },
footprint: td.footprint, buildings, unitDraw: Math.max(0, Math.round(td.power.draw - bdraw)), bonus: td.bonus || {},
};
rulesCache = { src: td, town };
return town;
};
// Current amounts at server time `now`. Falls back to the fetched values if the rules cannot be applied.
App.resourcesNow = (now) => {
const td = App.state.townData;
if (!td) return null;
try {
const rt = App.rulesTown();
const cur = R.resourcesAt(rt, now === undefined ? api.serverNow() : now);
return { amounts: cur.amounts, caps: cur.caps, rates: cur.rates };
} catch (e) {
const amounts = { battery: td.power.buffer }, caps = { battery: td.power.bufferCap };
for (const r of D.RESOURCES) { amounts[r] = td.resources[r].amount; caps[r] = td.resources[r].cap; }
return { amounts, caps, rates: { fiber: td.resources.fiber.rate, hardware: td.resources.hardware.rate, capital: td.resources.capital.rate, powerOut: td.power.out, powerDraw: td.power.draw, powerNet: td.power.net } };
}
};
// ------------------------------------------------------------------ resource bar
const hudRefs = {};
function renderHud(rebuild) {
const hud = document.getElementById('hud');
const def = App.current;
const td = App.state.townData;
const want = !!(def && def.hud && td && App.state.user);
hud.hidden = !want;
if (!want) return;
if (!rebuild && hud.firstChild) return;
clear(hud);
for (const r of D.RESOURCES.concat(['power'])) {
const refs = {
val: h('b', { class: 'val' }), cap: h('span', { class: 'cap' }), rate: h('span', { class: 'rate' }), fill: h('i'),
};
hudRefs[r] = refs;
hud.appendChild(h('div', { class: 'hud-chip ' + r, role: 'group', dataset: { res: r } },
h('div', { class: 'hud-top' }, icon(r), refs.val, refs.cap),
h('div', { class: 'hud-sub' }, refs.rate),
h('div', { class: 'bar', 'aria-hidden': 'true' }, refs.fill)));
}
tickHud(api.serverNow(), true);
}
const lastText = new WeakMap();
function setText(el, s) { if (lastText.get(el) !== s) { lastText.set(el, s); el.textContent = s; } }
function tickHud(now, force) {
const hud = document.getElementById('hud');
if (hud.hidden && !force) return;
const cur = App.resourcesNow(now);
if (!cur || !hudRefs.fiber) return;
const f = App.fmt;
for (const r of D.RESOURCES) {
const refs = hudRefs[r];
const amt = cur.amounts[r], cap = cur.caps[r], rate = cur.rates[r];
const full = amt >= cap - 0.01;
setText(refs.val, f.num(amt));
setText(refs.cap, '/' + f.compact(cap));
setText(refs.rate, full ? 'FULL' : f.dec(rate, true) + App.t('common.perHour'));
refs.fill.style.setProperty('--p', String(cap > 0 ? Math.min(1, amt / cap) : 0));
const chip = refs.val.closest('.hud-chip');
chip.classList.toggle('full', full);
if (force) chip.setAttribute('aria-label', App.resName(r) + ': ' + f.num(amt) + ' / ' + f.num(cap) + ', ' + f.dec(rate, true) + App.t('common.perHour'));
}
const p = hudRefs.power;
const net = cur.rates.powerNet, buf = cur.amounts.battery, bcap = cur.caps.battery;
setText(p.val, f.dec(net, true));
setText(p.cap, App.t('power.unit'));
setText(p.rate, buf <= 0 && net < 0 ? App.t('power.empty').split(':')[0] : f.num(buf) + '/' + f.compact(bcap));
p.fill.style.setProperty('--p', String(bcap > 0 ? Math.min(1, buf / bcap) : 0));
const pc = p.val.closest('.hud-chip');
pc.classList.toggle('bad', net < 0);
pc.classList.toggle('empty', buf <= 0 && net < 0);
if (force) pc.setAttribute('aria-label', App.t('res.power') + ': ' + f.dec(net, true) + ', ' + App.t('res.battery') + ' ' + f.num(buf) + ' / ' + f.num(bcap));
}
// ------------------------------------------------------------------ alerts badge (unread count from the notification feed)
const seenKey = () => SEEN_KEY + (App.state.user ? App.state.user.id : '0');
App.getSeen = () => Number(safeStore.get(seenKey())) || 0;
App.markSeen = (id) => {
if (id > App.getSeen()) safeStore.set(seenKey(), String(id));
App.state.unread = 0;
updateBadge();
};
App.checkAlerts = async () => {
if (!App.state.user) return;
try {
const after = App.getSeen();
const r = await api.get('/notifications', { after, limit: 50 });
if (App.current && App.current.id === 'alerts') { App.state.unread = 0; }
else App.state.unread = r.items.length;
updateBadge();
} catch (e) { /* badge is a convenience */ }
};
// ------------------------------------------------------------------ connection state
let backTimer = null;
api.on('offline', () => {
const el = document.getElementById('netstate');
el.textContent = App.t('common.offline'); el.hidden = false; el.classList.remove('ok');
clearTimeout(backTimer);
});
api.on('online', () => {
const el = document.getElementById('netstate');
if (el.hidden) return;
el.textContent = App.t('common.online'); el.classList.add('ok');
backTimer = setTimeout(() => { el.hidden = true; }, 1800);
if (App.state.user) App.refreshTown().catch(() => {});
});
api.on('unauthorized', () => {
App.clearSession();
App.authNotice = App.t('auth.expired');
App.go('auth');
});
document.addEventListener('visibilitychange', () => {
if (document.hidden || !App.state.user) return;
if (Date.now() - App.state.townFetchedAt > 20000) App.refreshTown().catch(() => {});
App.checkAlerts();
});
setInterval(() => { if (!document.hidden && App.state.user) App.checkAlerts(); }, 60000);
// After login or boot: load the POP and go to the screen the hash asks for.
App.enter = async (wantScreen) => {
buildNav();
const id = wantScreen || (location.hash.match(/^#\/(\w+)/) || [])[1] || safeStore.get('upstream.screen') || 'pop';
App.go(App.screens.has(id) && id !== 'auth' ? id : 'pop');
App.checkAlerts();
try { await App.refreshTown(); } catch (e) { toast(App.errMsg(e), 'error'); }
};
// ------------------------------------------------------------------ boot
async function boot() {
const saved = safeStore.get(LANG_KEY);
App.state.lang = I.LANGS.includes(saved) ? saved : I.detectLang(navigator.language);
document.documentElement.lang = App.state.lang;
buildNav();
if (!api.hasToken()) { App.go('auth'); return; }
const view = elView();
const status = h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }), h('p', { text: App.t('common.loading') }));
view.appendChild(status);
try {
await App.loadMe();
status.remove();
await App.enter();
} catch (e) {
status.remove();
if (e.code === 'network_error') {
const retry = h('button', { class: 'btn primary', type: 'button', onclick: () => { card.remove(); boot(); } }, icon('refresh'), App.t('common.retry'));
const card = h('div', { class: 'boot' }, h('p', { text: App.errMsg(e) }), retry);
view.appendChild(card);
} else if (e.code !== 'unauthorized') {
toast(App.errMsg(e), 'error');
App.go('auth');
}
}
}
document.addEventListener('DOMContentLoaded', boot);
}());

398
public/js/render.js Normal file
View file

@ -0,0 +1,398 @@
'use strict';
/*
* The canvas map and nothing else (window.MapRender.MapView): camera, pan / pinch / wheel / keyboard, tile culling,
* drawing. It knows no API. The screen gives it a `source` with the loaded data and callbacks:
*
* source.forEachSpecial(x0, y0, x1, y1, fn(special)) rural + incumbent tiles in the rect
* source.townsInRect(x0, y0, x1, y1) -> [town] POPs in the rect
* source.isOwn(town) -> bool
* onTap(x, y) a finger lift / click that was not a drag or a pinch (act on lift)
* onMoveEnd(view) debounced after the camera stopped; view = { x0, y0, x1, y1, cx, cy, zoom }
*
* Coordinates are tile units, y grows downward; tile (x, y) is the square [x-.5, x+.5] x [y-.5, y+.5].
* Touch: one finger pans, two fingers pinch-zoom around their midpoint and never trigger a tap. A tap is only
* reported when no second finger was ever down and the finger moved less than a few pixels.
*/
(function () {
const COLORS = {
void: '#04070e', land: '#0d1626', land2: '#0f192b', grid: 'rgba(120,160,220,0.10)', grid10: 'rgba(120,160,220,0.22)', border: 'rgba(77,227,255,0.55)',
fiber: '#4de3ff', hardware: '#ff9f5a', capital: '#5be08f', incumbent: '#b06cff', incumbentFill: '#241338',
own: '#4de3ff', ownFill: '#0f4b63', select: '#ffd24d', text: '#e4f0ff', halo: 'rgba(4,7,14,0.9)', reach: 'rgba(77,227,255,0.35)',
};
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
// A stable colour per operator id so rivals are told apart but never confused with you (cyan) or incumbents (violet).
function rivalColors(id) {
const hues = [8, 28, 48, 86, 150, 330, 355, 120]; // warm and green hues, no cyan/blue/violet
const hue = hues[Math.abs(id | 0) % hues.length];
return { fill: 'hsl(' + hue + ',45%,24%)', stroke: 'hsl(' + hue + ',70%,62%)' };
}
class MapView {
constructor(canvas, source, opts) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.src = source;
this.opts = opts || {};
this.radius = 50;
this.cx = 0; this.cy = 0; this.zoom = 24;
this.w = 0; this.h = 0; this.dpr = 1;
this.selected = null;
this.pointers = new Map();
this.drag = null;
this.pinch = null;
this.raf = 0;
this.moveTimer = 0;
this.labelFn = null;
this.reachTiles = 2;
this._bind();
}
setWorld(radius) { this.radius = radius; this._limits(); this.invalidate(); }
setSelected(x, y) { this.selected = x === null ? null : { x, y }; this.invalidate(); }
resize() {
const r = this.canvas.getBoundingClientRect();
const dpr = Math.min(window.devicePixelRatio || 1, 3);
if (!r.width || !r.height) return false;
this.w = r.width; this.h = r.height; this.dpr = dpr;
this.canvas.width = Math.round(r.width * dpr);
this.canvas.height = Math.round(r.height * dpr);
this._limits();
this.zoom = clamp(this.zoom, this.minZoom, this.maxZoom);
this._clampCenter();
this.invalidate();
this._scheduleMoveEnd(0);
return true;
}
_limits() {
const span = this.radius * 2 + 3;
this.minZoom = clamp(Math.min(this.w || 300, this.h || 300) / span, 2.5, 20);
this.maxZoom = 90;
}
_clampCenter() {
this.cx = clamp(this.cx, -this.radius, this.radius);
this.cy = clamp(this.cy, -this.radius, this.radius);
}
setView(cx, cy, zoom) {
this.cx = cx; this.cy = cy;
if (zoom) this.zoom = clamp(zoom, this.minZoom, this.maxZoom);
this._clampCenter();
this.invalidate();
this._scheduleMoveEnd(0);
}
// screen px (relative to the canvas) <-> tile coordinates
toTile(px, py) { return { x: (px - this.w / 2) / this.zoom + this.cx, y: (py - this.h / 2) / this.zoom + this.cy }; }
toScreen(x, y) { return { x: (x - this.cx) * this.zoom + this.w / 2, y: (y - this.cy) * this.zoom + this.h / 2 }; }
// Visible tiles clamped to the world.
view() {
const a = this.toTile(0, 0), b = this.toTile(this.w, this.h), r = this.radius;
return {
x0: clamp(Math.floor(a.x), -r, r), y0: clamp(Math.floor(a.y), -r, r),
x1: clamp(Math.ceil(b.x), -r, r), y1: clamp(Math.ceil(b.y), -r, r),
cx: this.cx, cy: this.cy, zoom: this.zoom,
};
}
// Zoom keeping the world point under screen (px, py) fixed.
zoomAt(px, py, factor) {
const before = this.toTile(px, py);
this.zoom = clamp(this.zoom * factor, this.minZoom, this.maxZoom);
this.cx = before.x - (px - this.w / 2) / this.zoom;
this.cy = before.y - (py - this.h / 2) / this.zoom;
this._clampCenter();
this.invalidate();
this._scheduleMoveEnd();
}
panBy(dxPx, dyPx) {
this.cx -= dxPx / this.zoom; this.cy -= dyPx / this.zoom;
this._clampCenter();
this.invalidate();
this._scheduleMoveEnd();
}
_scheduleMoveEnd(delay) {
clearTimeout(this.moveTimer);
this.moveTimer = setTimeout(() => { if (this.opts.onMoveEnd && this.w) this.opts.onMoveEnd(this.view()); }, delay === undefined ? 200 : delay);
}
invalidate() {
if (this.raf) return;
this.raf = requestAnimationFrame(() => { this.raf = 0; this.draw(); });
}
// ------------------------------------------------------------------ input
_bind() {
const c = this.canvas;
const rel = (e) => { const r = c.getBoundingClientRect(); return { x: e.clientX - r.left, y: e.clientY - r.top }; };
c.addEventListener('pointerdown', (e) => {
if (e.pointerType === 'mouse' && e.button !== 0) return;
try { c.setPointerCapture(e.pointerId); } catch (err) { /* synthetic */ }
const p = rel(e);
this.pointers.set(e.pointerId, { x: p.x, y: p.y });
if (this.pointers.size === 1) {
this.drag = { startX: p.x, startY: p.y, lastX: p.x, lastY: p.y, moved: false, pinched: false, t: e.timeStamp, touch: e.pointerType !== 'mouse' };
} else if (this.pointers.size === 2 && this.drag) {
this.drag.pinched = true;
this._startPinch();
}
});
c.addEventListener('pointermove', (e) => {
const cur = this.pointers.get(e.pointerId);
if (!cur || !this.drag) return;
const p = rel(e);
cur.x = p.x; cur.y = p.y;
if (this.pointers.size >= 2 && this.pinch) { this._movePinch(); return; }
if (this.pointers.size === 1 && !this.drag.pinched) {
const slop = this.drag.touch ? 9 : 5;
if (!this.drag.moved && Math.hypot(p.x - this.drag.startX, p.y - this.drag.startY) > slop) this.drag.moved = true;
if (this.drag.moved) {
this.panBy(p.x - this.drag.lastX, p.y - this.drag.lastY);
c.classList.add('grabbing');
}
this.drag.lastX = p.x; this.drag.lastY = p.y;
}
});
const end = (e, cancelled) => {
if (!this.pointers.has(e.pointerId)) return;
const p = rel(e);
this.pointers.delete(e.pointerId);
try { c.releasePointerCapture(e.pointerId); } catch (err) { /* already released */ }
const d = this.drag;
if (this.pointers.size === 1 && d) {
// one finger left after a pinch: continue as a pan from where that finger is, never as a tap
const [rest] = this.pointers.values();
d.lastX = rest.x; d.lastY = rest.y; d.startX = rest.x; d.startY = rest.y; d.moved = true;
this.pinch = null;
}
if (this.pointers.size === 0 && d) {
const tap = !cancelled && !d.moved && !d.pinched && e.timeStamp - d.t < 700;
this.drag = null; this.pinch = null;
c.classList.remove('grabbing');
if (tap && this.opts.onTap) {
const t = this.toTile(p.x, p.y);
this.opts.onTap(Math.round(t.x), Math.round(t.y));
}
this._scheduleMoveEnd(60);
}
};
c.addEventListener('pointerup', (e) => end(e, false));
c.addEventListener('pointercancel', (e) => end(e, true));
c.addEventListener('lostpointercapture', (e) => { if (this.pointers.has(e.pointerId)) end(e, true); });
c.addEventListener('wheel', (e) => {
e.preventDefault();
const p = rel(e);
const dy = e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY;
this.zoomAt(p.x, p.y, Math.exp(-dy * 0.0016));
}, { passive: false });
c.addEventListener('keydown', (e) => {
const step = Math.max(24, this.w * 0.2);
const k = e.key;
if (k === 'ArrowLeft') this.panBy(step, 0);
else if (k === 'ArrowRight') this.panBy(-step, 0);
else if (k === 'ArrowUp') this.panBy(0, step);
else if (k === 'ArrowDown') this.panBy(0, -step);
else if (k === '+' || k === '=') this.zoomAt(this.w / 2, this.h / 2, 1.3);
else if (k === '-' || k === '_') this.zoomAt(this.w / 2, this.h / 2, 1 / 1.3);
else if ((k === 'Enter' || k === ' ') && this.opts.onTap) this.opts.onTap(Math.round(this.cx), Math.round(this.cy));
else return;
e.preventDefault();
});
}
_pair() { const a = Array.from(this.pointers.values()); return [a[0], a[1]]; }
_startPinch() {
const [a, b] = this._pair();
const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
this.pinch = { dist: Math.max(10, Math.hypot(a.x - b.x, a.y - b.y)), zoom: this.zoom, world: this.toTile(mid.x, mid.y) };
}
_movePinch() {
const [a, b] = this._pair();
const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
const k = Math.hypot(a.x - b.x, a.y - b.y) / this.pinch.dist;
this.zoom = clamp(this.pinch.zoom * k, this.minZoom, this.maxZoom);
// keep the world point that was under the fingers' midpoint under it (also pans with the midpoint)
this.cx = this.pinch.world.x - (mid.x - this.w / 2) / this.zoom;
this.cy = this.pinch.world.y - (mid.y - this.h / 2) / this.zoom;
this._clampCenter();
this.invalidate();
this._scheduleMoveEnd();
}
// ------------------------------------------------------------------ drawing
draw() {
const { ctx, dpr, w, h, zoom: z } = this;
if (!w || !h) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.fillStyle = COLORS.void;
ctx.fillRect(0, 0, w, h);
const r = this.radius;
const tl = this.toScreen(-r - 0.5, -r - 0.5), br = this.toScreen(r + 0.5, r + 0.5);
ctx.fillStyle = COLORS.land;
ctx.fillRect(tl.x, tl.y, br.x - tl.x, br.y - tl.y);
const v = this.view();
// land texture + grid
if (z >= 9) {
ctx.fillStyle = COLORS.land2;
for (let y = v.y0; y <= v.y1; y++) {
for (let x = v.x0 + (((v.x0 + y) & 1) ? 1 : 0); x <= v.x1; x += 2) {
const s = this.toScreen(x - 0.5, y - 0.5);
ctx.fillRect(s.x, s.y, z, z);
}
}
}
ctx.lineWidth = 1;
if (z >= 14) {
ctx.strokeStyle = COLORS.grid;
ctx.beginPath();
for (let x = v.x0; x <= v.x1 + 1; x++) { const s = this.toScreen(x - 0.5, 0).x; ctx.moveTo(Math.round(s) + 0.5, Math.max(0, tl.y)); ctx.lineTo(Math.round(s) + 0.5, Math.min(h, br.y)); }
for (let y = v.y0; y <= v.y1 + 1; y++) { const s = this.toScreen(0, y - 0.5).y; ctx.moveTo(Math.max(0, tl.x), Math.round(s) + 0.5); ctx.lineTo(Math.min(w, br.x), Math.round(s) + 0.5); }
ctx.stroke();
}
// every 10 tiles, so a zoomed-out map still reads as a map
ctx.strokeStyle = COLORS.grid10;
ctx.beginPath();
for (let x = Math.ceil(v.x0 / 10) * 10; x <= v.x1; x += 10) { const s = this.toScreen(x, 0).x; ctx.moveTo(Math.round(s) + 0.5, Math.max(0, tl.y)); ctx.lineTo(Math.round(s) + 0.5, Math.min(h, br.y)); }
for (let y = Math.ceil(v.y0 / 10) * 10; y <= v.y1; y += 10) { const s = this.toScreen(0, y).y; ctx.moveTo(Math.max(0, tl.x), Math.round(s) + 0.5); ctx.lineTo(Math.min(w, br.x), Math.round(s) + 0.5); }
ctx.stroke();
// specials: rural areas and incumbent sites
this.src.forEachSpecial(v.x0, v.y0, v.x1, v.y1, (sp) => {
const s = this.toScreen(sp.x, sp.y);
if (sp.type === 'rural') this._rural(s.x, s.y, sp.bonus);
else this._incumbent(s.x, s.y);
});
const towns = this.src.townsInRect(v.x0 - 1, v.y0 - 1, v.x1 + 1, v.y1 + 1);
// faint rural reach rings around your own POPs
if (z >= 10) {
ctx.save();
ctx.setLineDash([4, 5]);
ctx.strokeStyle = COLORS.reach;
for (const t of towns) {
if (!this.src.isOwn(t)) continue;
const s = this.toScreen(t.x, t.y);
ctx.beginPath(); ctx.arc(s.x, s.y, this.reachTiles * z, 0, Math.PI * 2); ctx.stroke();
}
ctx.restore();
}
for (const t of towns) this._pop(t);
// world border
ctx.strokeStyle = COLORS.border;
ctx.lineWidth = 2;
ctx.strokeRect(tl.x, tl.y, br.x - tl.x, br.y - tl.y);
// selection
if (this.selected) this._selection(this.selected);
}
_rural(x, y, bonus) {
const { ctx, zoom: z } = this;
const col = COLORS[bonus] || COLORS.capital;
if (z < 6) { ctx.fillStyle = col; ctx.globalAlpha = 0.8; ctx.fillRect(x - Math.max(1, z / 2), y - Math.max(1, z / 2), Math.max(2, z), Math.max(2, z)); ctx.globalAlpha = 1; return; }
ctx.globalAlpha = 0.2; ctx.fillStyle = col;
ctx.beginPath(); ctx.arc(x, y, z * 0.46, 0, Math.PI * 2); ctx.fill();
ctx.globalAlpha = 1; ctx.strokeStyle = col; ctx.lineWidth = Math.max(1, z * 0.06);
ctx.beginPath(); ctx.arc(x, y, z * 0.46, 0, Math.PI * 2); ctx.stroke();
if (z >= 12) {
// "unconnected": a signal glyph with a cut line through it
ctx.lineWidth = Math.max(1, z * 0.07); ctx.lineCap = 'round';
for (let i = 1; i <= 2; i++) { ctx.beginPath(); ctx.arc(x, y + z * 0.14, z * 0.1 * i + z * 0.04, Math.PI * 1.2, Math.PI * 1.8); ctx.stroke(); }
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(x, y + z * 0.14, z * 0.05, 0, Math.PI * 2); ctx.fill();
}
}
_incumbent(x, y) {
const { ctx, zoom: z } = this;
const s = z * 0.78;
ctx.fillStyle = COLORS.incumbentFill; ctx.strokeStyle = COLORS.incumbent; ctx.lineWidth = Math.max(1, z * 0.07);
ctx.fillRect(x - s / 2, y - s / 2, s, s);
ctx.strokeRect(x - s / 2, y - s / 2, s, s);
if (z >= 14) {
ctx.fillStyle = COLORS.incumbent;
const n = 3, nw = s / 7;
for (let i = 0; i < n; i++) ctx.fillRect(x - s / 2 + s * 0.12 + i * (s * 0.3), y - s / 2 - nw * 0.0 + 1, nw * 1.3, nw * 1.3);
ctx.fillRect(x - s * 0.12, y + s * 0.02, s * 0.24, s * 0.28);
}
}
_hex(x, y, rad) {
const { ctx } = this;
ctx.beginPath();
for (let i = 0; i < 6; i++) {
const a = Math.PI / 6 + i * Math.PI / 3;
const px = x + Math.cos(a) * rad, py = y + Math.sin(a) * rad;
if (i) ctx.lineTo(px, py); else ctx.moveTo(px, py);
}
ctx.closePath();
}
_pop(t) {
const { ctx, zoom: z } = this;
const s = this.toScreen(t.x, t.y);
if (s.x < -40 || s.y < -40 || s.x > this.w + 40 || s.y > this.h + 40) return;
const own = this.src.isOwn(t);
const col = own ? { fill: COLORS.ownFill, stroke: COLORS.own } : rivalColors(t.owner.id);
const rad = Math.max(3, z * (own ? 0.5 : 0.42));
if (own) {
ctx.save();
ctx.shadowColor = COLORS.own; ctx.shadowBlur = Math.min(22, 6 + z * 0.35);
this._hex(s.x, s.y, rad); ctx.fillStyle = col.fill; ctx.fill();
ctx.restore();
}
this._hex(s.x, s.y, rad);
ctx.fillStyle = col.fill; ctx.fill();
ctx.strokeStyle = col.stroke; ctx.lineWidth = own ? Math.max(2, z * 0.1) : Math.max(1.2, z * 0.07); ctx.stroke();
if (z >= 10) {
ctx.fillStyle = col.stroke;
ctx.beginPath(); ctx.arc(s.x, s.y, Math.max(1.5, rad * (t.isCapital ? 0.38 : 0.22)), 0, Math.PI * 2); ctx.fill();
if (t.isCapital) { ctx.strokeStyle = col.stroke; ctx.lineWidth = 1; this._hex(s.x, s.y, rad * 0.68); ctx.stroke(); }
}
if (z >= 18 && t.owner.protected) {
ctx.strokeStyle = COLORS.select; ctx.lineWidth = Math.max(1, z * 0.05); ctx.setLineDash([3, 3]);
this._hex(s.x, s.y, rad + z * 0.12); ctx.stroke(); ctx.setLineDash([]);
}
if (z >= 24 || (own && z >= 12)) {
const label = this.labelFn ? this.labelFn(t, own) : t.name;
ctx.font = (own ? '700 ' : '600 ') + Math.round(clamp(z * 0.34, 10, 14)) + 'px system-ui, sans-serif';
ctx.textAlign = 'center'; ctx.textBaseline = 'top';
ctx.lineWidth = 3; ctx.lineJoin = 'round'; ctx.strokeStyle = COLORS.halo;
ctx.strokeText(label, s.x, s.y + rad + 3);
ctx.fillStyle = own ? COLORS.own : COLORS.text;
ctx.fillText(label, s.x, s.y + rad + 3);
}
}
_selection(sel) {
const { ctx, zoom: z } = this;
const s = this.toScreen(sel.x, sel.y);
const half = Math.max(5, z * 0.52), len = Math.max(3, half * 0.5);
ctx.strokeStyle = COLORS.select; ctx.lineWidth = 2.2; ctx.lineCap = 'round'; ctx.lineJoin = 'round';
ctx.beginPath();
for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {
const px = s.x + sx * half, py = s.y + sy * half;
ctx.moveTo(px - sx * len, py); ctx.lineTo(px, py); ctx.lineTo(px, py - sy * len);
}
ctx.stroke();
}
}
window.MapRender = { MapView, COLORS };
}());

View file

@ -284,6 +284,37 @@
return out;
}
// ------------------------------------------------------------------ alliances and diplomacy
// Member cap of an alliance for a given Peering office level (best POP of the leader). The server stores the cap at
// founding and only ever raises it (server/alliances.js effectiveCap), so a lost building never kicks anyone.
function allianceCap(peeringLevel) {
return D.SOCIAL.allianceBaseSize + D.SOCIAL.allianceSizePerLevel * Math.max(0, Math.floor(peeringLevel || 0));
}
// May a member with `role` perform `action` (a key of SOCIAL.permissions)?
function allianceCan(role, action) {
const list = hasOwn(D.SOCIAL.permissions, action) ? D.SOCIAL.permissions[action] : null;
return !!list && list.indexOf(role) >= 0;
}
// Seniority: leader 4 .. member 1, unknown roles -1.
function roleRank(role) {
const i = D.SOCIAL.roles.indexOf(role);
return i < 0 ? -1 : D.SOCIAL.roles.length - i;
}
const outranks = (a, b) => roleRank(a) > roleRank(b);
// How an alliance may move a relation from `from` to `to`: 'immediate' | 'proposal' | 'delayed' | null (not allowed).
function diplomacyMove(from, to) {
const row = hasOwn(D.SOCIAL.diplomacyMoves, from) ? D.SOCIAL.diplomacyMoves[from] : null;
return row && hasOwn(row, to) ? row[to] : null;
}
// Time a unilateral cancel of a pact takes (24 h at 1x, shorter on faster worlds).
function pactCancelMs(worldSpeed) {
return Math.max(1000, Math.round(D.SOCIAL.pactCancelHours * HOUR / (worldSpeed || 1)));
}
// ------------------------------------------------------------------ movement
// Latency in ms for a distance in tiles at `speed` tiles/hour (unit speed), world speed `worldSpeed`; min 10 min.
function latencyMs(dist, unitSpeed, worldSpeed) {
@ -291,10 +322,343 @@
return Math.max(10 * 60 * 1000, Math.round(hours * HOUR));
}
// ------------------------------------------------------------------ military: units, training, research (stages 3-4)
// Units are always plain objects { unitId: count }. `research` is { 'unitId:attack': level, 'unitId:defence': level }.
const MIL = D.MILITARY;
function unitDef(id) { return hasOwn(D.UNITS, id) ? D.UNITS[id] : null; }
const buildingLevel = (town, type) => (town.buildings[type] ? town.buildings[type].level : 0);
const unitCount = (units) => Object.keys(units || {}).reduce((s, k) => s + (units[k] || 0), 0);
const costValue = (cost) => D.RESOURCES.reduce((s, r) => s + ((cost && cost[r]) || 0), 0);
const unitValue = (id) => costValue(unitDef(id).cost);
const researchKey = (unit, stat) => unit + ':' + stat;
const researchLevel = (research, unit, stat) => (research && research[researchKey(unit, stat)]) || 0;
const researchMult = (level) => 1 + MIL.researchPerLevel * level;
// attack | defence of one unit of this type, with research
function unitStat(unit, stat, research) { return unitDef(unit)[stat] * researchMult(researchLevel(research, unit, stat)); }
function unitCost(unit, count) {
const def = unitDef(unit), out = {};
for (const r of D.RESOURCES) out[r] = def.cost[r] * count;
return out;
}
// Training time in ms for a batch. The training building's level shortens it; world speed divides it.
function trainTimeMs(unit, count, buildingLvl, speed) {
const secs = unitDef(unit).time * count / (1 + MIL.trainSpeedPerLevel * buildingLvl) / (speed || 1);
return Math.max(1000, Math.round(secs * 1000));
}
// Missing requirements of a unit in a town: [{ type, level, have }]. The training building counts at level 1.
function unitMissing(town, unit) {
const def = unitDef(unit);
const need = [{ type: def.building, level: 1 }].concat(def.requires);
const best = {};
for (const r of need) best[r.type] = Math.max(best[r.type] || 0, r.level);
const missing = [];
for (const type of Object.keys(best)) {
const have = buildingLevel(town, type);
if (have < best[type]) missing.push({ type, level: best[type], have });
}
return missing;
}
// Can `count` of `unit` be queued now? `tailAt` = due time of the last batch queued in the same building (batches of
// one building run one after another). Codes: unknown_unit, validation_failed, requirements_not_met, not_enough_resources.
function trainPlan(town, unit, count, now, tailAt) {
const def = unitDef(unit);
const base = { ok: false, unit, count };
if (!def) return Object.assign(base, { code: 'unknown_unit' });
if (!Number.isInteger(count) || count < 1 || count > MIL.maxBatch) return Object.assign(base, { code: 'validation_failed' });
const missing = unitMissing(town, unit);
base.building = def.building;
base.cost = unitCost(unit, count);
base.durationMs = trainTimeMs(unit, count, buildingLevel(town, def.building), town.speed);
base.startAt = Math.max(now, tailAt || 0);
base.dueAt = base.startAt + base.durationMs;
base.missing = missing;
if (missing.length) return Object.assign(base, { code: 'requirements_not_met' });
const have = resourcesAt(town, now).amounts;
for (const r of D.RESOURCES) if (have[r] + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' });
base.ok = true;
return base;
}
// ---- research
const RS = D.RESEARCH;
function researchCost(unit, toLevel) {
const def = unitDef(unit), out = {};
for (const r of D.RESOURCES) out[r] = Math.round(def.cost[r] * RS.costFactor * Math.pow(RS.costGrowth, toLevel - 1));
return out;
}
// speedBonus: the operator's permanent research speed bonus from incumbent sites (0.1 = +10%).
function researchTimeMs(unit, toLevel, labLevel, speed, speedBonus) {
const secs = RS.timeBase * Math.pow(RS.timeGrowth, toLevel - 1) / (1 + RS.labSpeedPerLevel * labLevel) / (speed || 1) / (1 + (speedBonus || 0));
return Math.max(1000, Math.round(secs * 1000));
}
function researchSpeedBonus(sitesTaken) { return Math.min(D.INCUMBENT.researchSpeedMax, D.INCUMBENT.researchSpeedBonus * sitesTaken); }
// Plan one research level. `current` = level now, `busy` = a research is already running in this POP.
// Codes: unknown_unit, not_researchable, max_level, requirements_not_met, queue_full, not_enough_resources.
function researchPlan(town, unit, stat, current, busy, now, speedBonus) {
const def = unitDef(unit);
const base = { ok: false, unit, stat, fromLevel: current, toLevel: current + 1 };
if (!def) return Object.assign(base, { code: 'unknown_unit' });
if (RS.stats.indexOf(stat) < 0 || !(def[stat] > 0)) return Object.assign(base, { code: 'not_researchable' });
if (current >= RS.maxLevel) return Object.assign(base, { code: 'max_level' });
const lab = buildingLevel(town, 'research_lab');
const missing = unitMissing(town, unit);
const needLab = base.toLevel + RS.labOffset;
if (lab < needLab) missing.push({ type: 'research_lab', level: needLab, have: lab });
base.missing = missing;
base.cost = researchCost(unit, base.toLevel);
base.durationMs = researchTimeMs(unit, base.toLevel, lab, town.speed, speedBonus);
if (missing.length) return Object.assign(base, { code: 'requirements_not_met' });
if (busy) return Object.assign(base, { code: 'queue_full' });
const have = resourcesAt(town, now).amounts;
for (const r of D.RESOURCES) if (have[r] + 1e-6 < base.cost[r]) return Object.assign(base, { code: 'not_enough_resources' });
base.ok = true;
return base;
}
// ------------------------------------------------------------------ military: movements
// Slowest speed (tiles/hour at 1x) among the units actually in the group; Infinity when empty.
function slowestSpeed(units) {
let s = Infinity;
for (const k of Object.keys(units || {})) if (units[k] > 0 && unitDef(k)) s = Math.min(s, unitDef(k).speed);
return s;
}
// Travel time of a unit group over `dist` tiles (min 10 min, see latencyMs). An empty group travels at transport speed.
function movementMs(dist, units, worldSpeed) {
const s = slowestSpeed(units);
return latencyMs(dist, isFinite(s) ? s : D.TRANSPORT.speed, worldSpeed);
}
function transportMs(dist, worldSpeed) { return latencyMs(dist, D.TRANSPORT.speed, worldSpeed); }
// Shape and role check of the units on a movement of `type`. null when fine, otherwise { code, reason }.
function checkUnitsForType(type, units) {
const roles = hasOwn(D.MOVE_ROLES, type) ? D.MOVE_ROLES[type] : null;
if (!roles) return { code: 'validation_failed', reason: 'type carries no units' };
let total = 0;
for (const k of Object.keys(units || {})) {
const n = units[k];
const def = unitDef(k);
if (!def) return { code: 'unknown_unit', reason: k };
if (!Number.isInteger(n) || n < 0) return { code: 'validation_failed', reason: 'bad count for ' + k };
if (n === 0) continue;
if (def.fixed) return { code: 'validation_failed', reason: k + ' cannot move' };
if (roles.indexOf(def.role) < 0) return { code: 'validation_failed', reason: k + ' cannot go on a ' + type };
total += n;
}
if (total < 1) return { code: 'validation_failed', reason: 'no units' };
if (type === 'settle') {
const only = Object.keys(units).filter((k) => units[k] > 0);
if (only.length !== 1 || only[0] !== D.EXPANSION.settleUnit || units[only[0]] !== D.EXPANSION.crews) {
return { code: 'validation_failed', reason: 'a settle needs exactly ' + D.EXPANSION.crews + ' ' + D.EXPANSION.settleUnit };
}
}
if (type === 'takeover' && !(units[D.EXPANSION.conquestUnit] > 0)) return { code: 'validation_failed', reason: 'a takeover needs a ' + D.EXPANSION.conquestUnit };
return null;
}
// Beginner protection: a protected operator cannot be attacked (raid, attack, takeover). Scans are fine.
const isProtected = (protectionUntil, at) => (protectionUntil || 0) > at;
// ------------------------------------------------------------------ military: combat
const firewallMult = (level) => 1 + F.firewallPerLevel * level;
const effectiveFirewall = (level, rigs) => Math.max(0, level - (rigs || 0) / MIL.rigFirewallDivisor);
function powerOf(units, research, stat) {
let s = 0;
for (const k of Object.keys(units || {})) if (units[k] > 0 && unitDef(k)) s += units[k] * unitStat(k, stat, research);
return s;
}
const attackPower = (units, research) => powerOf(units, research, 'attack');
const defencePower = (units, research) => powerOf(units, research, 'defence');
// Remove a fraction of every unit type (rounded to whole units). -> { survivors, lost }
function applyLoss(units, fraction) {
const survivors = {}, lost = {};
for (const k of Object.keys(units || {})) {
const n = units[k];
if (!(n > 0)) continue;
const l = fraction >= 1 ? n : Math.min(n, Math.round(n * fraction));
if (l > 0) lost[k] = l;
if (n - l > 0) survivors[k] = n - l;
}
return { survivors, lost };
}
// The battle. Deterministic: inputs in, result out, no randomness.
// o.kind: 'attack' (full) | 'raid'
// o.attackers: { units, research }
// o.defenders: [{ id, units, research }] everything defending the POP (home crews first, then each reinforcement)
// o.firewall: Firewall level of the target; o.staticDefence: a number for an incumbent site (no groups, no losses)
// Full attack: the loser loses everything, the winner loses (loser/winner)^1.5 of its units.
// Raid: both sides lose 0.5 * (weaker/stronger)^1.5, whoever wins. Ties go to the defender.
function resolveBattle(o) {
const att = o.attackers.units || {};
const A = attackPower(att, o.attackers.research);
const rigs = att.ddos_rig || 0;
const effFw = effectiveFirewall(o.firewall || 0, rigs);
const groups = o.defenders || [];
const raw = groups.map((g) => defencePower(g.units, g.research));
const rawTotal = raw.reduce((s, v) => s + v, 0);
const isStatic = o.staticDefence !== undefined && o.staticDefence !== null;
const Dv = isStatic ? o.staticDefence : (rawTotal + MIL.defenceBase) * firewallMult(effFw);
const attackerWins = A > Dv;
const hi = Math.max(A, Dv), lo = Math.min(A, Dv);
const ratio = hi > 0 ? lo / hi : 0;
let attF, defF;
if (o.kind === 'raid') {
attF = defF = MIL.raidLossFactor * Math.pow(ratio, MIL.lossExponent);
} else if (attackerWins) {
attF = Math.min(1, Math.pow(ratio, MIL.lossExponent)); defF = 1;
} else {
attF = 1; defF = Math.min(1, Math.pow(ratio, MIL.lossExponent));
}
if (isStatic) defF = 0;
const a = applyLoss(att, attF);
const defenders = groups.map((g, i) => {
const r = applyLoss(g.units, defF);
return { id: g.id, sent: g.units, lost: r.lost, survivors: r.survivors, share: rawTotal > 0 ? raw[i] / rawTotal : 0 };
});
return { kind: o.kind, A, D: Dv, defenceRaw: rawTotal, effectiveFirewall: effFw, attackerWins, ratio, attackerLossFraction: attF, defenderLossFraction: defF,
attacker: { sent: att, lost: a.lost, survivors: a.survivors }, defenders };
}
// Battle points for destroying units (operator_stats.attack_points / defense_points).
function battlePoints(lostUnits) {
let v = 0;
for (const k of Object.keys(lostUnits || {})) if (unitDef(k)) v += unitValue(k) * lostUnits[k];
return v * MIL.pointsPerCost;
}
// Share of the stock the Rack hall hides from a raid ("cold spare").
const cacheFraction = (rackLevel) => Math.min(MIL.cacheMax, MIL.cachePerLevel * Math.max(0, rackLevel || 0));
// Loot: `carry` is split evenly over Fiber/Hardware/Capital; what one resource cannot give is shared by the others.
// avail = what can be taken. -> whole-number { fiber, hardware, capital }.
function lootSplit(carry, avail) {
const take = { fiber: 0, hardware: 0, capital: 0 };
let left = Math.max(0, carry);
for (let pass = 0; pass < 4 && left > 1e-9; pass++) {
const open = D.RESOURCES.filter((r) => avail[r] - take[r] > 1e-9);
if (!open.length) break;
const share = left / open.length;
for (const r of open) {
const t = Math.min(share, avail[r] - take[r]);
take[r] += t; left -= t;
}
}
for (const r of D.RESOURCES) take[r] = Math.floor(take[r] + 1e-9);
return take;
}
const carryOf = (units) => Object.keys(units || {}).reduce((s, k) => s + (unitDef(k) ? unitDef(k).carry * units[k] : 0), 0);
// Exploit kits (survivors) tear levels off one chosen building after a win.
const siegeLevels = (kits) => (kits >= MIL.kitsMin ? Math.max(1, Math.floor(kits / MIL.kitsPerLevel)) : 0);
// Customer loyalty lost to one M&A team, from a seeded roll r in [0, 1).
function loyaltyDrop(r) { const lo = MIL.loyaltyDrop[0], hi = MIL.loyaltyDrop[1]; return lo + Math.min(hi - lo, Math.floor(r * (hi - lo + 1))); }
// Why a POP cannot change owner: 'capital' | 'last_pop' | null. (A capital can still be dragged to zero loyalty.)
function takeoverBlock(isCapital, defenderTownCount) {
if (defenderTownCount <= 1) return 'last_pop'; // wins over 'capital': a lone capital is not even drained
if (isCapital) return 'capital';
return null;
}
// Footprint gate for founding or taking over: the operator owns `ownedCount` POPs now, `footprint` is their total.
function footprintGate(ownedCount, footprint) {
const need = footprintNeeded(ownedCount);
return { ok: footprint + 1e-6 >= need, need, have: footprint };
}
// Founding a POP: info about the target tile and the operator. Codes: invalid_target, out_of_range, footprint_too_low.
function settleCheck(o) {
if (o.tileType !== 'land' || o.occupied) return { ok: false, code: 'invalid_target', reason: o.occupied ? 'occupied' : 'not_empty_land' };
if (!(o.nearestOwnDist <= D.EXPANSION.maxDistance)) return { ok: false, code: 'out_of_range', max: D.EXPANSION.maxDistance, have: o.nearestOwnDist };
const g = footprintGate(o.ownedCount, o.footprint);
if (!g.ok) return { ok: false, code: 'footprint_too_low', need: g.need, have: g.have };
return { ok: true };
}
// Wild slot choice at founding: two field types (any of FIELD_TYPES). Anything else falls back to the defaults.
function cleanWild(wild) {
const out = [];
for (let i = 0; i < D.WILD_SLOTS; i++) out.push(wild && D.FIELD_TYPES.indexOf(wild[i]) >= 0 ? wild[i] : D.START.wild[i]);
return out;
}
// A new POP: every field at level 0, no infrastructure at all.
function newTownBuildings(wild) {
const layout = fieldLayout(wild);
const out = {};
for (const key of Object.keys(layout)) out[key] = { type: layout[key], level: 0 };
return out;
}
// ---- scanning
const scanStrength = (count, research) => count * researchMult(researchLevel(research, 'port_scanner', 'defence'));
// sa = attacking scanner strength, sd = defending. Success needs sa > sd; buildings (and more) at 2:1.
// A failed scan loses every scanner and reveals the scanner to the target; a successful one loses 0.5*(sd/sa)^1.5.
function resolveScan(sa, sd) {
const success = sa > sd;
return {
success,
detail: !success ? 'none' : (sa >= MIL.scanBuildingsRatio * sd ? 'full' : 'basic'),
identityRevealed: !success,
lossFraction: success ? MIL.raidLossFactor * Math.pow(sd / sa, MIL.scanLossExponent) : 1,
};
}
// ---- incumbent (NPC) sites
// Static defence of the site at (x, y); ageDays = world age in world days (real days * speed).
function incumbentDefence(seed, x, y, ageDays) {
const f = 1 + D.INCUMBENT.variance * (2 * (hash(seed ^ 0x1ac0, x, y) / 4294967296) - 1);
return Math.round(D.INCUMBENT.baseDefence * f * (1 + D.INCUMBENT.perDayGrowth * Math.max(0, ageDays)));
}
// ---- power: when the battery is empty, units go offline and are decommissioned later
const decommissionMs = (speed) => Math.round(MIL.decommissionHours * HOUR / (speed || 1));
// units = { unit: count } of everything drawing power in one POP; allowedDraw = output minus building draw.
// Returns how many of each unit to decommission, most expensive first, until the draw fits.
function decommissionPlan(units, allowedDraw) {
let draw = 0;
for (const k of Object.keys(units)) draw += (units[k] || 0) * unitDef(k).draw;
const order = Object.keys(units).filter((k) => units[k] > 0).sort((a, b) => unitValue(b) - unitValue(a) || (a < b ? -1 : 1));
const remove = {};
for (const k of order) {
if (draw <= Math.max(0, allowedDraw) + 1e-9) break;
const d = unitDef(k).draw;
const n = d > 0 ? Math.min(units[k], Math.ceil((draw - Math.max(0, allowedDraw)) / d)) : 0;
if (n > 0) { remove[k] = n; draw -= n * d; }
}
return remove;
}
// ---- transport (trade is built on it): concurrent links = Internet exchange level, each carries up to capacityPerLink
const transportLinks = (town) => buildingLevel(town, D.TRANSPORT.building);
// Codes: validation_failed, capacity_exceeded, no_transport_link, not_enough_resources.
function transportPlan(town, cargo, activeLinks, now) {
let total = 0;
for (const r of Object.keys(cargo || {})) {
if (D.RESOURCES.indexOf(r) < 0 || !Number.isInteger(cargo[r]) || cargo[r] < 0) return { ok: false, code: 'validation_failed' };
total += cargo[r];
}
if (total < 1) return { ok: false, code: 'validation_failed' };
if (activeLinks >= transportLinks(town)) return { ok: false, code: 'no_transport_link', links: transportLinks(town), active: activeLinks };
if (total > D.TRANSPORT.capacityPerLink) return { ok: false, code: 'capacity_exceeded', capacity: D.TRANSPORT.capacityPerLink, total };
const have = resourcesAt(town, now).amounts;
for (const r of D.RESOURCES) if (have[r] + 1e-6 < (cargo[r] || 0)) return { ok: false, code: 'not_enough_resources' };
return { ok: true, total };
}
return {
rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn,
unitDef, unitCount, costValue, unitValue, researchKey, researchLevel, researchMult, unitStat, unitCost, trainTimeMs, unitMissing, trainPlan, researchCost, researchTimeMs, researchSpeedBonus, researchPlan, slowestSpeed, movementMs, transportMs, checkUnitsForType, isProtected, firewallMult, effectiveFirewall, attackPower, defencePower, applyLoss, resolveBattle, battlePoints, cacheFraction, lootSplit, carryOf, siegeLevels, loyaltyDrop, takeoverBlock, footprintGate, settleCheck, cleanWild, newTownBuildings, scanStrength, resolveScan, incumbentDefence, decommissionMs, decommissionPlan, transportLinks, transportPlan, rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn,
buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, queueSlots, storageCap, batteryCap,
fieldOutputPerHour, ratesPerHour, resourcesAt, batteryEmptyAt, unitsOnline, footprintPerDay, footprintAt,
allianceCap, allianceCan, roleRank, outranks, diplomacyMove, pactCancelMs,
footprintNeeded, loyaltyAt, buildPlan, initialBuildings, latencyMs,
};
}));

View file

@ -0,0 +1,84 @@
'use strict';
/* Alerts: the durable notification feed (GET /notifications). Newest first; what arrived since you last looked is marked. */
(function () {
const { h, clear, icon } = UI;
const PAGE = 100, MAX_PAGES = 5;
let box, listEl, statusEl, items = [], seenAtOpen = 0, loading = false, offTick = null;
function townName(id) {
const t = App.state.towns.find((x) => x.id === id);
return t ? t.name : '#' + id;
}
// One entry per notification type: icon + title + detail. Unknown types still show something readable.
function describe(n) {
const p = n.payload || {};
if (n.type === 'build_done') {
return { icon: 'b-' + p.type, title: App.t('alerts.build_done', { name: App.buildingName(p.type), level: p.level }), detail: App.t('alerts.build_done.in', { town: townName(p.townId) }), go: 'pop' };
}
return { icon: 'bell', title: App.t('alerts.unknown', { type: n.type }), detail: '', go: null };
}
function draw() {
clear(listEl);
if (!items.length) { listEl.appendChild(h('p', { class: 'empty pad', text: App.t('alerts.empty') })); return; }
const now = App.now();
for (const n of items.slice().reverse()) {
const d = describe(n);
const isNew = n.id > seenAtOpen;
listEl.appendChild(h('li', null,
h('button', { class: 'alert' + (isNew ? ' new' : ''), type: 'button', onclick: () => { if (d.go) App.go(d.go); } },
h('span', { class: 'row-ic' }, icon(d.icon)),
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: d.title }), isNew ? h('span', { class: 'pill accent', text: App.t('alerts.new') }) : null),
d.detail ? h('span', { class: 'row-sub', text: d.detail }) : null),
h('span', { class: 'when mono', dataset: { at: n.createdAt }, text: App.fmt.ago(now - n.createdAt) }))));
}
}
async function load() {
if (loading) return;
loading = true;
statusEl.hidden = true;
try {
let after = items.length ? items[items.length - 1].id : 0;
for (let page = 0; page < MAX_PAGES; page++) {
const r = await App.api.get('/notifications', { after, limit: PAGE });
items = items.concat(r.items);
if (r.next === null || !r.items.length) break;
after = r.next;
}
draw();
if (items.length) App.markSeen(items[items.length - 1].id); else App.markSeen(0);
} catch (e) {
statusEl.textContent = App.t('alerts.error') + ' ' + App.errMsg(e);
statusEl.hidden = false;
} finally { loading = false; }
}
App.registerScreen({
id: 'alerts', titleKey: 'screen.alerts', navKey: 'nav.alerts', icon: 'bell', hud: false,
render(container) {
box = container;
listEl = h('ul', { class: 'alert-list' });
statusEl = h('p', { class: 'form-error', role: 'alert', hidden: true });
box.appendChild(h('div', { class: 'page' },
h('div', { class: 'card-head page-head' }, h('h1', { text: App.t('screen.alerts') }),
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => load() }, icon('refresh'))),
statusEl, listEl));
App.on('session', () => { items = []; });
},
onShow() {
seenAtOpen = App.getSeen();
box.querySelector('h1').textContent = App.t('screen.alerts');
draw();
load();
if (offTick) offTick();
offTick = App.onTick(() => {
const now = App.now();
for (const el of listEl.querySelectorAll('.when')) { const s = App.fmt.ago(now - Number(el.dataset.at)); if (el.textContent !== s) el.textContent = s; }
});
},
onHide() { if (offTick) offTick(); offTick = null; },
});
}());

100
public/js/screens/auth.js Normal file
View file

@ -0,0 +1,100 @@
'use strict';
/* Login / signup. Not in the nav. The invite field appears when the server answers signup_closed. */
(function () {
const { h, icon, clear } = UI;
let box, mode = 'login', needInvite = false, busy = false;
let refs = {};
function deviceName() {
const ua = navigator.userAgent || '';
const browser = /Edg\//.test(ua) ? 'Edge' : /OPR\//.test(ua) ? 'Opera' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Browser';
const os = /Android/.test(ua) ? 'Android' : /iPhone|iPad|iPod/.test(ua) ? 'iOS' : /Windows/.test(ua) ? 'Windows' : /Mac OS/.test(ua) ? 'macOS' : /Linux/.test(ua) ? 'Linux' : '';
return (browser + (os ? ' on ' + os : '')).slice(0, 40);
}
function showError(msg) { refs.err.textContent = msg || ''; refs.err.hidden = !msg; }
function validationMessage(err) {
const list = err.details && err.details.errors;
const base = App.t('err.validation_failed');
if (Array.isArray(list) && list.length) {
const f = list[0];
const path = String(f.path || '').replace(/^\$?\.?/, '');
return base + (path ? ' (' + path + ')' : '');
}
return base;
}
async function submit(ev) {
ev.preventDefault();
if (busy) return;
showError('');
const username = refs.user.value.trim(), password = refs.pass.value;
if (!username || !password) { showError(App.t('err.validation_failed')); return; }
busy = true; refs.go.disabled = true; refs.goText.textContent = App.t('auth.working');
try {
let r;
if (mode === 'signup') {
const body = { username, password, device: deviceName() };
if (needInvite && refs.invite.value.trim()) body.invite = refs.invite.value.trim();
r = await App.api.post('/auth/signup', body, { auth: false });
} else {
r = await App.api.post('/auth/login', { username, password, device: deviceName() }, { auth: false });
}
App.api.setToken(r.token);
App.setSession(r.user, r.operators);
refs.pass.value = '';
App.authNotice = null;
await App.enter('pop');
} catch (e) {
if (e.code === 'signup_closed') { needInvite = true; draw(); refs.invite.focus(); showError(App.t('auth.invite.hint')); }
else if (e.code === 'validation_failed') showError(validationMessage(e));
else showError(App.errMsg(e));
} finally {
busy = false;
if (refs.go) { refs.go.disabled = false; refs.goText.textContent = App.t(mode === 'signup' ? 'auth.signup' : 'auth.login'); }
}
}
function field(id, label, input, hint) {
return h('label', { class: 'field', for: id }, h('span', { class: 'field-lbl', text: label }), input, hint ? h('span', { class: 'field-hint', text: hint }) : null);
}
function draw() {
const keep = { u: refs.user ? refs.user.value : '', p: refs.pass ? refs.pass.value : '', i: refs.invite ? refs.invite.value : '', e: refs.err ? refs.err.textContent : '' };
clear(box);
const signup = mode === 'signup';
refs.user = h('input', { id: 'f-user', name: 'username', type: 'text', autocomplete: 'username', autocapitalize: 'none', autocorrect: 'off', spellcheck: 'false', required: true, minlength: signup ? '3' : null, maxlength: '20', pattern: signup ? '[A-Za-z0-9_\\-]{3,20}' : null, enterkeyhint: 'next' });
refs.pass = h('input', { id: 'f-pass', name: 'password', type: 'password', autocomplete: signup ? 'new-password' : 'current-password', required: true, minlength: signup ? '8' : null, maxlength: '128', enterkeyhint: needInvite && signup ? 'next' : 'go' });
refs.invite = h('input', { id: 'f-invite', name: 'invite', type: 'text', autocomplete: 'off', autocapitalize: 'none', spellcheck: 'false', maxlength: '64', enterkeyhint: 'go' });
refs.user.value = keep.u; refs.pass.value = keep.p; refs.invite.value = keep.i;
refs.err = h('p', { class: 'form-error', role: 'alert', hidden: true });
refs.goText = h('span', { text: App.t(signup ? 'auth.signup' : 'auth.login') });
refs.go = h('button', { class: 'btn primary wide', type: 'submit' }, icon('check'), refs.goText);
const notice = App.authNotice ? h('p', { class: 'notice', text: App.authNotice }) : null;
const form = h('form', { class: 'auth-form', novalidate: false, onsubmit: submit },
h('h1', { class: 'auth-h', text: App.t(signup ? 'auth.signup' : 'auth.login') }),
notice,
field('f-user', App.t('auth.username'), refs.user, signup ? App.t('auth.username.hint') : null),
field('f-pass', App.t('auth.password'), refs.pass, signup ? App.t('auth.password.hint') : null),
signup && needInvite ? field('f-invite', App.t('auth.invite'), refs.invite) : null,
refs.err, refs.go,
h('button', { class: 'linklike', type: 'button', onclick: () => { mode = signup ? 'login' : 'signup'; draw(); } }, App.t(signup ? 'auth.toLogin' : 'auth.toSignup')));
box.appendChild(h('div', { class: 'auth-card' },
h('div', { class: 'auth-logo' }, h('span', { class: 'brand-mark big', 'aria-hidden': 'true' }), h('span', { class: 'auth-name', text: App.t('app.name') })),
h('p', { class: 'auth-tag', text: App.t('app.tagline') }),
form,
h('div', { class: 'lang-switch', role: 'group', 'aria-label': App.t('settings.language') },
...['en', 'nb'].map((l) => h('button', { class: 'chip-btn', type: 'button', 'aria-pressed': String(App.state.lang === l), onclick: () => App.setLang(l) }, l === 'en' ? 'EN' : 'NB')))));
if (keep.e) showError(keep.e);
}
App.registerScreen({
id: 'auth', titleKey: 'app.name', nav: false, hud: false,
render(container) { box = container; },
onShow() { draw(); if (window.matchMedia('(pointer: fine)').matches) setTimeout(() => { if (refs.user) refs.user.focus({ preventScroll: true }); }, 50); },
onLang() { draw(); },
});
}());

220
public/js/screens/map.js Normal file
View file

@ -0,0 +1,220 @@
'use strict';
/*
* Map screen: owns the canvas (render.js draws it), fetches GET /map by viewport into a chunk cache, and shows the
* tile info sheet. One /map request returns at most a 81 x 81 window (r <= 40), so the world is cut into 40 x 40
* chunks and only the chunks the viewport touches are fetched, again when the camera stops moving. Land tiles are
* implied by the API (only rural areas, incumbent sites and POPs are listed).
*/
(function () {
const { h, icon, openSheet, closeSheet, toast } = UI;
const R = UpstreamRules;
const F = UpstreamData.FORMULAS;
const CHUNK = 40, STALE_MS = 60000, RETRY_MS = 6000, MAX_PARALLEL = 2;
// ------------------------------------------------------------------ chunk store
class Store {
constructor() { this.chunks = new Map(); this.active = 0; this.errShown = 0; this.onChange = null; }
reset() { this.chunks.clear(); }
key(i, j) { return i + ',' + j; }
// Make sure every chunk touching the rect is loaded and fresh.
ensure(v, radius) {
const i0 = Math.floor(v.x0 / CHUNK), i1 = Math.floor(v.x1 / CHUNK), j0 = Math.floor(v.y0 / CHUNK), j1 = Math.floor(v.y1 / CHUNK);
const want = [];
for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) {
if (i * CHUNK > radius || (i + 1) * CHUNK - 1 < -radius || j * CHUNK > radius || (j + 1) * CHUNK - 1 < -radius) continue;
const c = this.chunks.get(this.key(i, j));
const now = Date.now();
if (!c || (c.state === 'ok' && now - c.at > STALE_MS) || (c.state === 'error' && now - c.at > RETRY_MS)) want.push([i, j]);
}
// nearest to the view centre first
want.sort((a, b) => Math.hypot((a[0] + 0.5) * CHUNK - v.cx, (a[1] + 0.5) * CHUNK - v.cy) - Math.hypot((b[0] + 0.5) * CHUNK - v.cx, (b[1] + 0.5) * CHUNK - v.cy));
for (const [i, j] of want) this.fetch(i, j);
}
async fetch(i, j) {
const k = this.key(i, j);
const prev = this.chunks.get(k);
if (prev && prev.state === 'loading') return;
if (this.active >= MAX_PARALLEL) { setTimeout(() => this.fetch(i, j), 120); return; }
const rec = prev || { specials: [], towns: [], map: new Map(), at: 0 };
rec.state = 'loading';
this.chunks.set(k, rec);
this.active++;
const x0 = i * CHUNK, y0 = j * CHUNK;
try {
const r = await App.api.get('/map', { x: x0 + CHUNK / 2, y: y0 + CHUNK / 2, r: CHUNK / 2 });
const inChunk = (o) => o.x >= x0 && o.x < x0 + CHUNK && o.y >= y0 && o.y < y0 + CHUNK;
rec.specials = r.specials.filter(inChunk);
rec.map = new Map(rec.specials.map((s) => [s.x * 4096 + s.y, s]));
rec.towns = r.towns.filter(inChunk);
rec.state = 'ok'; rec.at = Date.now();
} catch (e) {
rec.state = prev && prev.at ? 'ok' : 'error'; rec.at = Date.now(); // keep showing old data when a refresh fails
if (Date.now() - this.errShown > 8000) { this.errShown = Date.now(); toast(App.t('map.error'), 'error'); }
} finally {
this.active--;
if (this.onChange) this.onChange();
}
}
chunkAt(x, y) { return this.chunks.get(this.key(Math.floor(x / CHUNK), Math.floor(y / CHUNK))); }
special(x, y) { const c = this.chunkAt(x, y); return c ? c.map.get(x * 4096 + y) : undefined; }
townAt(x, y) { const c = this.chunkAt(x, y); return c ? c.towns.find((t) => t.x === x && t.y === y) : undefined; }
loaded(x, y) { const c = this.chunkAt(x, y); return !!c && c.state === 'ok'; }
forEachSpecial(x0, y0, x1, y1, fn) {
for (const c of this.chunks.values()) for (const s of c.specials) if (s.x >= x0 && s.x <= x1 && s.y >= y0 && s.y <= y1) fn(s);
}
townsInRect(x0, y0, x1, y1) {
const out = [];
for (const c of this.chunks.values()) for (const t of c.towns) if (t.x >= x0 && t.x <= x1 && t.y >= y0 && t.y <= y1) out.push(t);
return out;
}
// After a rename the capital on the map must not show a stale name.
patchTown(id, patch) { for (const c of this.chunks.values()) for (const t of c.towns) if (t.id === id) Object.assign(t, patch); }
}
// ------------------------------------------------------------------ screen
let box, canvas, view, coordsEl, legendEl, ready = false, visible = false, pendingFocus = 'own';
const store = new Store();
let infoSheet = null;
const ownOperatorId = () => (App.state.operator ? App.state.operator.id : null);
const capital = () => App.state.towns.find((t) => t.isCapital) || App.state.towns[0] || null;
function updateCoords() {
if (!coordsEl || !view) return;
coordsEl.textContent = 'x ' + Math.round(view.cx) + ' · y ' + Math.round(view.cy);
}
function centreOnOwn() {
const c = App.state.towns.find((t) => t.id === App.state.townId) || capital();
if (!c) return;
view.setView(c.x, c.y, 30);
}
function setup() {
if (ready) return;
ready = true;
canvas = h('canvas', { class: 'map-canvas', tabindex: '0', role: 'application', 'aria-label': App.t('map.label') });
coordsEl = h('div', { class: 'map-coords mono', 'aria-hidden': 'true' });
legendEl = h('ul', { class: 'map-legend', 'aria-hidden': 'true' });
const zoomBtn = (name, label, f) => h('button', { class: 'map-btn', type: 'button', 'aria-label': label, onclick: f }, icon(name));
const controls = h('div', { class: 'map-controls' },
zoomBtn('plus', App.t('map.zoomIn'), () => view.zoomAt(view.w / 2, view.h / 2, 1.5)),
zoomBtn('minus', App.t('map.zoomOut'), () => view.zoomAt(view.w / 2, view.h / 2, 1 / 1.5)),
zoomBtn('locate', App.t('map.centre'), centreOnOwn));
controls.dataset.role = 'controls';
box.appendChild(canvas); box.appendChild(legendEl); box.appendChild(coordsEl); box.appendChild(controls);
const source = {
forEachSpecial: (a, b, c, d, fn) => store.forEachSpecial(a, b, c, d, fn),
townsInRect: (a, b, c, d) => store.townsInRect(a, b, c, d),
isOwn: (t) => t.owner.id === ownOperatorId(),
};
view = new MapRender.MapView(canvas, source, {
onTap: onTap,
onMoveEnd: (v) => { updateCoords(); store.ensure(v, App.state.world ? App.state.world.mapRadius : 50); },
});
view.labelFn = (t, own) => (own ? t.name : t.owner.name);
view.reachTiles = F.ruralReach;
store.onChange = () => view.invalidate();
new ResizeObserver(() => { if (visible && view.resize()) updateCoords(); }).observe(box);
// The camera moves are frequent; keep the coords chip in step cheaply.
canvas.addEventListener('pointermove', () => updateCoords());
canvas.addEventListener('wheel', () => updateCoords(), { passive: true });
drawLegend();
}
function drawLegend() {
UI.clear(legendEl);
const item = (cls, text) => h('li', null, h('span', { class: 'lg ' + cls }), text);
legendEl.appendChild(item('you', App.t('map.legend.you')));
legendEl.appendChild(item('rival', App.t('map.legend.rival')));
legendEl.appendChild(item('rural', App.t('map.legend.rural')));
legendEl.appendChild(item('incumbent', App.t('map.legend.incumbent')));
}
// ------------------------------------------------------------------ tile info
function onTap(x, y) {
const w = App.state.world;
if (!w) return;
if (Math.abs(x) > w.mapRadius || Math.abs(y) > w.mapRadius) return;
showTile(x, y);
}
function showTile(x, y) {
view.setSelected(x, y);
const town = store.townAt(x, y);
const special = store.special(x, y);
const known = store.loaded(x, y);
const type = town ? 'pop' : special ? special.type : 'land';
const cap = capital();
const body = [];
const row = (label, value) => h('div', { class: 'kv' }, h('span', { class: 'k', text: label }), h('span', { class: 'v', text: value }));
if (town) {
const own = town.owner.id === ownOperatorId();
body.push(h('div', { class: 'pill-row' },
own ? h('span', { class: 'pill accent', text: App.t('map.info.yours') }) : h('span', { class: 'pill', text: App.t('map.info.rival') }),
town.isCapital ? h('span', { class: 'pill', text: App.t('map.info.capital') }) : null,
town.owner.protected ? h('span', { class: 'pill amber' }, icon('shield'), App.t('map.info.protected')) : null));
body.push(row(App.t('map.info.operator'), town.owner.name));
body.push(row(App.t('map.info.as'), UpstreamI18n.fmtAs(town.owner.asNumber)));
} else if (special && special.type === 'rural') {
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.rural', { n: F.ruralReach, p: Math.round(F.ruralBonus * 100), res: App.resName(special.bonus) }) }));
body.push(h('div', { class: 'pill-row' }, h('span', { class: 'pill res-' + special.bonus }, icon(special.bonus), '+' + Math.round(F.ruralBonus * 100) + '% ' + App.resName(special.bonus))));
} else if (special && special.type === 'incumbent') {
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.incumbent') }));
} else if (!known) {
body.push(h('p', { class: 'detail-desc dimmer', text: App.t('map.scanning') }));
} else {
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.land') }));
}
body.push(row('', App.t('map.info.coords', { x, y })));
if (cap && !(town && town.id === cap.id)) body.push(row('', App.t('map.info.distance', { d: App.fmt.dec(R.distance(cap.x, cap.y, x, y)) })));
if (town && town.owner.id === ownOperatorId() && App.state.towns.some((t) => t.id === town.id)) {
body.push(h('button', { class: 'btn primary wide', type: 'button', onclick: () => { closeSheet(); App.setTown(town.id); App.go('pop'); } }, icon('pop'), App.t('map.info.open')));
}
const title = town ? town.name : App.t('tile.' + type);
infoSheet = openSheet({
title, icon: town ? 'pop' : type === 'rural' ? 'fiber' : type === 'incumbent' ? 'b-core_router' : 'map', iconClass: special && special.type === 'rural' ? 'res-' + special.bonus : (town && town.owner.id === ownOperatorId() ? 'own' : ''),
closeLabel: App.t('common.close'), body: h('div', { class: 'detail' }, body),
onClose: () => { if (view) view.setSelected(null); infoSheet = null; },
});
}
// ------------------------------------------------------------------ screen registration
App.registerScreen({
id: 'map', titleKey: 'screen.map', navKey: 'nav.map', icon: 'map', hud: true,
render(container) {
box = container;
App.on('session', () => { store.reset(); pendingFocus = 'own'; });
App.on('town', () => { const t = App.state.townData; if (t) store.patchTown(t.id, { name: t.name }); });
},
onShow(params) {
visible = true;
if (!App.state.world) { UI.clear(box); box.appendChild(h('p', { class: 'empty pad', text: App.t('map.noWorld') })); ready = false; return; }
setup();
view.setWorld(App.state.world.mapRadius);
const apply = () => {
if (params && Number.isFinite(params.x)) view.setView(params.x, params.y, params.zoom || 40);
else if (pendingFocus) { centreOnOwn(); pendingFocus = null; }
else view.setView(view.cx, view.cy);
updateCoords();
};
// the container was display:none until now: measure after layout
requestAnimationFrame(() => { if (view.resize()) apply(); else setTimeout(() => { view.resize(); apply(); }, 60); });
},
onHide() { visible = false; closeSheet(); },
onLang() {
if (!ready) return;
canvas.setAttribute('aria-label', App.t('map.label'));
drawLegend();
const labels = ['map.zoomIn', 'map.zoomOut', 'map.centre'];
box.querySelectorAll('.map-controls .map-btn').forEach((b, i) => b.setAttribute('aria-label', App.t(labels[i])));
},
});
}());

495
public/js/screens/pop.js Normal file
View file

@ -0,0 +1,495 @@
'use strict';
/*
* POP screen: header, build queue, power, resource fields (grouped by type), infrastructure; tap a building for
* the detail sheet. All numbers come from GET /towns/:id (the server's "next" plan decides what is buildable); the
* client only ticks values forward with rules.js and re-checks affordability live, so a button wakes up the moment
* the resources are there. Countdowns come from the server clock (App.now()).
*/
(function () {
const { h, clear, icon, toast, openSheet, closeSheet } = UI;
const R = UpstreamRules;
const D = UpstreamData;
const F = D.FORMULAS;
let box = null, dirty = true, visible = false;
let refs = { tiles: new Map(), rows: new Map(), queue: [] };
let offTick = null;
let prevQueue = null;
const refetchTries = new Map(); // queue event id -> refetch attempts after it came due
let sheetCtl = null;
const td = () => App.state.townData;
const find = (key) => (td() ? td().buildings.find((b) => b.key === key) : null);
const resOf = (type) => D.FIELD_PRODUCES[type] || null;
// ------------------------------------------------------------------ building state (live)
// 'queued' | 'ready' | 'locked' | 'max' | 'wait'. `code` is the reason it cannot be built now (null = can).
function stateOf(b, cur) {
const t = td();
if (t.queue.some((q) => q.key === b.key)) return { st: 'queued', code: 'already_queued' };
if (b.level >= b.maxLevel) return { st: 'max', code: 'max_level' };
const n = b.next;
let code = n.code;
if (code === 'not_enough_resources' && cur && n.cost) {
let ok = true;
for (const r of D.RESOURCES) if (cur.amounts[r] + 1e-6 < n.cost[r]) ok = false;
if (ok) code = null;
}
if (code === null) return { st: 'ready', code: null };
if (code === 'requirements_not_met') return { st: 'locked', code };
return { st: 'wait', code };
}
// How long until the resources for `cost` are there (ms), or null if never (rate 0) / Infinity if above the storage cap.
function etaFor(cost, cur) {
let worst = 0;
for (const r of D.RESOURCES) {
const need = cost[r] - cur.amounts[r];
if (need <= 0) continue;
if (cost[r] > cur.caps[r]) return Infinity;
const rate = cur.rates[r];
if (rate <= 0) return null;
worst = Math.max(worst, need / rate * D.HOUR_MS);
}
return worst;
}
// ------------------------------------------------------------------ pieces
function costChips(cost, cur, withHave) {
return h('div', { class: 'costs' }, D.RESOURCES.map((r) => {
const short = cur && cur.amounts[r] + 1e-6 < cost[r];
return h('span', { class: 'cost ' + r + (short ? ' short' : ''), dataset: { res: r } }, icon(r),
h('b', { text: App.fmt.num(cost[r]) }),
withHave && cur ? h('small', { text: App.t('sheet.have', { n: App.fmt.num(cur.amounts[r]) }) }) : null);
}));
}
const fmt2 = (x) => x.toFixed(2).replace('.', App.state.lang === 'nb' ? ',' : '.');
function levelPreview(b, toLevel) {
// [{ text }] lines describing what the next level changes, from rules.js.
const t = td(), rt = App.rulesTown(), world = App.state.world;
const lines = [];
const fmt = App.fmt;
const withLevel = (lvl) => {
const bb = Object.assign({}, rt.buildings);
bb[b.key] = { type: b.type, level: lvl };
return Object.assign({}, rt, { buildings: bb });
};
if (b.kind === 'field') {
const res = resOf(b.type);
const mult = res === 'power' ? 1 : (world.speed || 1) * (1 + ((t.bonus && t.bonus[res]) || 0));
const a = R.fieldOutputPerHour(b.level) * mult, c = R.fieldOutputPerHour(toLevel) * mult;
lines.push(App.t('sheet.preview.output', { a: fmt.dec(a), b: fmt.dec(c) }) + ' ' + App.resName(res));
} else if (b.type === 'rack_hall') {
lines.push(App.t('sheet.preview.storage', { a: fmt.num(R.storageCap(withLevel(b.level))), b: fmt.num(R.storageCap(withLevel(toLevel))) }));
} else if (b.type === 'battery_bank') {
lines.push(App.t('sheet.preview.battery', { a: fmt.num(R.batteryCap(withLevel(b.level))), b: fmt.num(R.batteryCap(withLevel(toLevel))) }));
} else if (b.type === 'core_router') {
const k = (l) => fmt2(1 / (1 + F.coreSpeedPerLevel * l));
lines.push(App.t('sheet.preview.core', { a: k(b.level), b: k(toLevel) }));
if (toLevel === F.secondQueueCoreLevel) lines.push(App.t('sheet.preview.core2', { n: toLevel }));
} else if (b.type === 'firewall') {
lines.push(App.t('sheet.preview.firewall', { a: fmt2(1 + F.firewallPerLevel * b.level), b: fmt2(1 + F.firewallPerLevel * toLevel) }));
}
const def = D.BUILDINGS[b.type];
if (def && def.draw > 0) lines.push(App.t('sheet.preview.draw', { n: def.draw }));
return lines;
}
function requirementList(b) {
const def = D.BUILDINGS[b.type];
const levels = {};
for (const x of td().buildings) if (x.kind === 'infra') levels[x.type] = x.level;
return (def.requires || []).map((rq) => {
const have = levels[rq.type] || 0, ok = have >= rq.level;
return h('li', { class: ok ? 'ok' : 'miss' }, icon(ok ? 'check' : 'lock'),
h('span', { text: App.buildingName(rq.type) + ' ' + App.t('pop.level', { n: rq.level }) }),
h('small', { text: App.t('sheet.have', { n: have }) }));
});
}
// ------------------------------------------------------------------ detail sheet
function openBuilding(key, opts) {
const first = find(key);
if (!first) return;
const R_ = { cur: null };
const body = h('div', { class: 'detail' });
const ctl = openSheet({
title: App.buildingName(first.type), icon: 'b-' + first.type, iconClass: first.kind === 'field' ? 'res-' + resOf(first.type) : '',
closeLabel: App.t('common.close'), body,
onClose: () => { if (offSheetTick) offSheetTick(); offSheetTick = null; sheetCtl = null; },
});
sheetCtl = ctl;
let offSheetTick = null;
const els = {};
function build() {
for (const k of Object.keys(els)) delete els[k];
const b = find(key);
if (!b) { ctl.close(); return; }
const cur = App.resourcesNow();
clear(body);
body.appendChild(h('p', { class: 'detail-desc', text: App.buildingDesc(b.type) }));
body.appendChild(h('div', { class: 'detail-level' },
h('span', { class: 'lvl-now', text: b.level > 0 ? App.t('sheet.level', { n: b.level }) : App.t('pop.notBuilt') }),
b.level < b.maxLevel ? h('span', { class: 'lvl-next' }, icon('up'), App.t('sheet.nextLevel', { n: b.level + 1 })) : h('span', { class: 'lvl-next', text: App.t('sheet.maxed') })));
const queued = td().queue.find((q) => q.key === key);
if (queued) {
els.qbar = h('i');
els.qtime = h('b', { class: 'mono' });
body.appendChild(h('div', { class: 'detail-queue' },
h('div', { class: 'row' }, h('span', { text: App.t('sheet.underway') + ' · ' + App.t('pop.queue.to', { n: queued.toLevel }) }), els.qtime),
h('div', { class: 'bar' }, els.qbar)));
els.cancel = h('button', { class: 'btn danger wide', type: 'button', onclick: () => confirmCancel(queued) }, icon('x'), App.t('sheet.cancel'));
body.appendChild(els.cancel);
updateQueueEls(queued, App.now());
return;
}
if (b.level >= b.maxLevel) return;
const to = b.level + 1;
const next = b.next;
for (const text of levelPreview(b, to)) body.appendChild(h('p', { class: 'preview', text }));
els.costs = costChips(next.cost, cur, true);
body.appendChild(h('h3', { class: 'sub', text: App.t('sheet.cost') }));
body.appendChild(els.costs);
body.appendChild(h('div', { class: 'row meta' }, icon('clock'), h('span', { text: App.t('sheet.time') + ': ' }), h('b', { text: App.fmt.dur(next.durationMs) })));
const reqs = requirementList(b);
if (reqs.length) { body.appendChild(h('h3', { class: 'sub', text: App.t('sheet.requires') })); body.appendChild(h('ul', { class: 'reqs' }, reqs)); }
els.reason = h('p', { class: 'reason', 'aria-live': 'polite' });
els.btn = h('button', { class: 'btn primary wide', type: 'button', onclick: () => doBuild(b.key) }, icon('up'), h('span', { text: App.t(b.level > 0 ? 'sheet.upgrade' : 'sheet.build', { n: to }) }));
body.appendChild(els.reason);
body.appendChild(els.btn);
updateLive();
}
function updateQueueEls(q, now) {
const left = q.dueAt - now;
els.qtime.textContent = App.fmt.clock(left);
els.qbar.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))));
}
let busy = false;
function updateLive() {
const b = find(key);
if (!b || !els.btn) return;
const cur = App.resourcesNow();
const s = stateOf(b, cur);
for (const chip of els.costs.children) chip.classList.toggle('short', cur.amounts[chip.dataset.res] + 1e-6 < b.next.cost[chip.dataset.res]);
const can = s.code === null && !busy;
els.btn.disabled = !can;
let reason = '';
if (s.code) {
reason = App.t('err.' + s.code);
if (s.code === 'not_enough_resources') {
const eta = etaFor(b.next.cost, cur);
if (eta === Infinity) reason = App.t('sheet.capTooLow', { cap: App.fmt.num(cur.caps.fiber) });
else if (eta !== null) reason = App.t('sheet.affordableIn', { t: App.fmt.dur(Math.max(1000, eta)) });
}
}
els.reason.textContent = reason;
els.reason.hidden = !reason;
}
async function doBuild(k) {
if (busy) return;
busy = true; els.btn.disabled = true;
els.btn.querySelector('span').textContent = App.t('sheet.building');
const t = td();
try {
const b = find(k);
await App.api.post('/towns/' + t.id + '/build', { key: k }, { intent: 'build:' + t.id + ':' + k });
toast(App.t('sheet.built', { name: App.buildingName(b.type), n: b.level + 1 }), 'ok');
ctl.close();
await App.refreshTown();
} catch (e) {
toast(App.errMsg(e), 'error');
busy = false;
try { await App.refreshTown(); } catch (e2) { /* shown by the offline chip */ }
if (sheetCtl === ctl) build();
}
}
function confirmCancel(q) {
clear(body);
const b = find(key);
body.appendChild(h('p', { class: 'detail-desc', text: App.t('sheet.cancel.confirm', { name: App.buildingName(b.type), n: q.toLevel }) }));
body.appendChild(h('p', { class: 'preview', text: App.t('sheet.cancel.refund') }));
body.appendChild(h('div', { class: 'btn-row' },
h('button', { class: 'btn', type: 'button', onclick: () => build() }, App.t('sheet.cancel.keep')),
h('button', { class: 'btn danger', type: 'button', onclick: async (ev) => {
ev.currentTarget.disabled = true;
try {
await App.api.del('/towns/' + td().id + '/queue/' + q.id);
toast(App.t('sheet.cancelled'), 'ok');
} catch (e) { toast(App.errMsg(e), 'error'); }
ctl.close();
App.refreshTown().catch(() => {});
} }, icon('x'), App.t('sheet.cancel'))));
}
offSheetTick = App.onTick((now) => {
const q = td() && td().queue.find((x) => x.key === key);
if (q && els.qtime) updateQueueEls(q, now); else if (els.btn) updateLive();
});
const offTown = App.on('town', () => { if (sheetCtl === ctl) build(); });
const prevClose = offSheetTick;
offSheetTick = () => { prevClose(); offTown(); };
build();
if (opts && opts.cancel) { const q = td().queue.find((x) => x.key === key); if (q) confirmCancel(q); }
}
// ------------------------------------------------------------------ main drawing
function tileLabel(b, s) {
const status = s.st === 'queued' ? App.t('pop.inQueue') : s.st === 'ready' ? App.t('pop.upgradeReady') : s.st === 'max' ? App.t('pop.max') : s.st === 'locked' ? App.t('pop.locked') : '';
return App.buildingName(b.type) + ', ' + (b.level > 0 ? App.t('pop.level', { n: b.level }) : App.t('pop.notBuilt')) + (status ? ', ' + status : '');
}
function fieldTile(b) {
const res = resOf(b.type);
const lvl = h('b', { class: 'tile-lvl', text: String(b.level) });
const badge = h('span', { class: 'tile-badge', 'aria-hidden': 'true' });
const bar = h('i');
const el = h('button', { class: 'tile res-' + res, type: 'button', dataset: { key: b.key }, onclick: () => openBuilding(b.key) },
icon('b-' + b.type, 'tile-ic'), lvl, badge, h('span', { class: 'tile-bar', 'aria-hidden': 'true' }, bar));
refs.tiles.set(b.key, { el, badge, bar, b });
return el;
}
function infraRow(b) {
const status = h('span', { class: 'pill' });
const sub = h('span', { class: 'row-sub' });
const bar = h('i');
const el = h('button', { class: 'row-btn', type: 'button', dataset: { key: b.key }, onclick: () => openBuilding(b.key) },
h('span', { class: 'row-ic' }, icon('b-' + b.type)),
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: App.buildingName(b.type) }), h('span', { class: 'lv', text: b.level > 0 ? App.t('pop.level', { n: b.level }) : App.t('pop.notBuilt') })),
sub),
status, h('span', { class: 'tile-bar', 'aria-hidden': 'true' }, bar));
refs.rows.set(b.key, { el, status, sub, bar, b });
return el;
}
function header(t) {
const st = App.state;
const bonus = D.RESOURCES.filter((r) => (t.bonus && t.bonus[r] > 0)).map((r) => h('span', { class: 'pill res-' + r }, icon(r), '+' + Math.round(t.bonus[r] * 100) + '% ' + App.resName(r)));
const title = st.towns.length > 1
? h('select', { class: 'town-select', 'aria-label': App.t('screen.pop'), onchange: (e) => App.setTown(Number(e.target.value)) },
st.towns.map((x) => h('option', { value: x.id, selected: x.id === t.id, text: x.name })))
: h('h1', { class: 'town-name', text: t.name });
return h('section', { class: 'card pop-head' },
h('div', { class: 'pop-title' }, title,
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('pop.rename'), onclick: openRename }, icon('pencil'))),
h('div', { class: 'pop-meta' },
h('span', { text: App.t('pop.coords', { x: t.x, y: t.y }) }),
t.isCapital ? h('span', { class: 'pill accent', text: App.t('pop.capital') }) : null,
h('span', { class: 'pill' }, icon('shield'), App.t('pop.loyalty') + ' ' + App.fmt.num(t.loyalty)),
h('span', { class: 'pill', text: App.t('pop.footprint') + ' ' + App.fmt.num(t.footprint) + ' (' + App.t('pop.footprintPerDay', { n: App.fmt.num(t.footprintPerDay) }) + ')' }),
bonus.length ? bonus : h('span', { class: 'pill dim', text: App.t('pop.bonus.none') })));
}
function openRename() {
const t = td();
const input = h('input', { type: 'text', value: t.name, maxlength: '40', minlength: '2', 'aria-label': App.t('pop.rename.label'), autocomplete: 'off', enterkeyhint: 'done' });
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
const save = h('button', { class: 'btn primary wide', type: 'submit' }, icon('check'), App.t('common.save'));
const form = h('form', { class: 'detail', onsubmit: async (ev) => {
ev.preventDefault();
const name = input.value.trim();
if (name.length < 2) { err.textContent = App.t('err.validation_failed'); err.hidden = false; return; }
save.disabled = true;
try {
const r = await App.api.post('/towns/' + t.id + '/rename', { name });
const known = App.state.towns.find((x) => x.id === t.id);
if (known) known.name = r.name;
toast(App.t('pop.rename.done'), 'ok');
sheet.close();
await App.refreshTown();
} catch (e) { err.textContent = App.errMsg(e); err.hidden = false; save.disabled = false; }
} }, h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('pop.rename.label') }), input), err, save);
const sheet = openSheet({ title: App.t('pop.rename'), icon: 'pencil', closeLabel: App.t('common.close'), body: form });
setTimeout(() => { input.focus(); input.select(); }, 60);
}
function queueCard(t) {
refs.queue = [];
const slots = h('span', { class: 'pill', text: App.t('pop.queue.slots', { used: t.queue.length, total: t.queueSlots }) });
const list = h('div', { class: 'queue' });
for (const q of t.queue) {
const time = h('b', { class: 'mono' }), bar = h('i');
const name = App.buildingName(q.type);
list.appendChild(h('div', { class: 'q-item' },
h('button', { class: 'q-main', type: 'button', onclick: () => openBuilding(q.key), 'aria-label': name + ' ' + App.t('pop.queue.to', { n: q.toLevel }) },
h('span', { class: 'row-ic' }, icon('b-' + q.type)),
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: name }), h('span', { class: 'lv', text: App.t('pop.queue.to', { n: q.toLevel }) })),
h('span', { class: 'bar' }, bar)),
time),
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('pop.queue.cancel') + ': ' + name, onclick: () => openBuilding(q.key, { cancel: true }) }, icon('x'))));
refs.queue.push({ q, time, bar });
}
if (!t.queue.length) list.appendChild(h('p', { class: 'empty', text: App.t('pop.queue.empty') }));
return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.queue.title') }), slots), list);
}
function powerCard() {
refs.power = { out: h('b'), draw: h('b'), net: h('b'), buf: h('span', { class: 'mono' }), bar: h('i'), status: h('p', { class: 'power-status' }) };
const p = refs.power;
return h('section', { class: 'card power-card' },
h('div', { class: 'card-head' }, h('h2', null, icon('power'), App.t('power.title'))),
h('div', { class: 'stat-row' },
h('div', { class: 'stat' }, h('small', { text: App.t('power.out') }), p.out),
h('div', { class: 'stat' }, h('small', { text: App.t('power.draw') }), p.draw),
h('div', { class: 'stat' }, h('small', { text: App.t('power.net') }), p.net)),
h('div', { class: 'row' }, h('span', { class: 'dimmer', text: App.t('power.buffer') }), p.buf),
h('div', { class: 'bar power-bar', 'aria-hidden': 'true' }, p.bar), p.status);
}
function fieldsCard(t) {
const fields = t.buildings.filter((b) => b.kind === 'field');
const world = App.state.world;
const groups = h('div', { class: 'groups' });
for (const type of D.FIELD_TYPES) {
const list = fields.filter((b) => b.type === type);
if (!list.length) continue;
const res = resOf(type);
const mult = res === 'power' ? 1 : (world.speed || 1) * (1 + ((t.bonus && t.bonus[res]) || 0));
const total = list.reduce((s, b) => s + R.fieldOutputPerHour(b.level) * mult, 0);
groups.appendChild(h('div', { class: 'group res-' + res },
h('div', { class: 'group-head' }, icon(res), h('b', { text: App.buildingName(type) }), h('span', { class: 'dimmer', text: '×' + list.length }),
h('span', { class: 'group-rate', text: App.fmt.dec(total, true) + ' ' + App.resName(res) + App.t('common.perHour') })),
h('div', { class: 'tiles' }, list.map(fieldTile))));
}
return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.fields.title') })), groups);
}
function infraCard(t) {
const list = t.buildings.filter((b) => b.kind === 'infra');
return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.infra.title') })), h('div', { class: 'rows' }, list.map(infraRow)));
}
function draw() {
dirty = false;
refs = { tiles: new Map(), rows: new Map(), queue: [] };
clear(box);
const t = td();
if (!App.state.townId) { box.appendChild(h('p', { class: 'empty pad', text: App.t('pop.noTown') })); return; }
if (!t) { box.appendChild(h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }), h('p', { text: App.t('common.loading') }))); return; }
box.appendChild(h('div', { class: 'cols' },
h('div', { class: 'col' }, header(t), queueCard(t), powerCard()),
h('div', { class: 'col' }, fieldsCard(t), infraCard(t))));
tick(App.now());
}
// ------------------------------------------------------------------ ticking
function tick(now) {
const t = td();
if (!t || !refs.power) return;
const cur = App.resourcesNow(now);
const f = App.fmt;
// queue countdowns + the refetch when something comes due
for (const e of refs.queue) {
const q = e.q, left = q.dueAt - now;
const time = f.clock(left);
if (e.time.textContent !== time) e.time.textContent = time;
e.bar.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))));
if (left <= -300) {
const tries = refetchTries.get(q.id) || { n: 0, at: 0 };
if (Date.now() >= tries.at) {
refetchTries.set(q.id, { n: tries.n + 1, at: Date.now() + Math.min(10000, 1500 * (tries.n + 1)) });
App.refreshTown().catch(() => {});
}
}
}
// tiles and rows
const queueByKey = new Map(t.queue.map((q) => [q.key, q]));
for (const [key, e] of refs.tiles) {
const s = stateOf(e.b, cur);
if (e.el.dataset.st !== s.st) {
e.el.dataset.st = s.st;
e.badge.textContent = '';
if (s.st === 'queued') e.badge.appendChild(icon('clock'));
else if (s.st === 'ready') e.badge.appendChild(icon('up'));
else if (s.st === 'locked') e.badge.appendChild(icon('lock'));
e.el.setAttribute('aria-label', tileLabel(e.b, s));
}
const q = queueByKey.get(key);
e.bar.style.setProperty('--p', q ? String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))) : '0');
}
for (const [key, e] of refs.rows) {
const s = stateOf(e.b, cur);
const q = queueByKey.get(key);
let pill = '', pillCls = 'pill', sub = '';
if (s.st === 'queued') { pill = f.clock(q.dueAt - now); pillCls += ' amber mono'; sub = App.buildingDesc(e.b.type); }
else if (s.st === 'ready') { pill = App.t(e.b.level > 0 ? 'pop.upgradeReady' : 'sheet.build', { n: e.b.level + 1 }); pillCls += ' green'; sub = App.buildingDesc(e.b.type); }
else if (s.st === 'max') { pill = App.t('pop.max'); sub = App.buildingDesc(e.b.type); }
else if (s.st === 'locked') {
const m = (e.b.next.missing || [])[0];
pill = m ? App.buildingName(m.type) + ' ' + App.t('pop.level', { n: m.level }) : App.t('pop.locked'); pillCls += ' dim';
sub = App.buildingDesc(e.b.type);
} else sub = App.buildingDesc(e.b.type);
if (e.status.textContent !== pill) e.status.textContent = pill;
e.status.className = pillCls;
e.status.hidden = !pill;
if (e.sub.textContent !== sub) e.sub.textContent = sub;
e.el.dataset.st = s.st;
e.bar.style.setProperty('--p', q ? String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))) : '0');
}
// power
const p = refs.power, net = cur.rates.powerNet, buf = cur.amounts.battery, bcap = cur.caps.battery;
p.out.textContent = f.dec(cur.rates.powerOut);
p.draw.textContent = f.dec(cur.rates.powerDraw);
p.net.textContent = f.dec(net, true);
p.net.className = net < 0 ? 'bad' : 'good';
p.buf.textContent = f.num(buf) + ' / ' + f.num(bcap) + ' ' + App.t('power.unit');
p.bar.style.setProperty('--p', String(bcap > 0 ? Math.min(1, buf / bcap) : 0));
const speed = App.state.world.speed || 1;
let status, cls = '';
if (net < 0) {
if (buf <= 0) { status = App.t('power.empty'); cls = 'bad'; }
else { status = App.t('power.draining', { t: f.dur(buf / (-net * speed) * D.HOUR_MS) }); cls = 'warn'; }
} else if (net > 0 && buf < bcap - 0.01) status = App.t('power.charging', { t: f.dur((bcap - buf) / (net * speed) * D.HOUR_MS) });
else status = buf >= bcap - 0.01 && bcap > 0 ? App.t('power.full') : App.t('power.ok');
if (p.status.textContent !== status) p.status.textContent = status;
p.status.className = 'power-status ' + cls;
}
// ------------------------------------------------------------------ town changed
function onTown(t) {
// toast for levels that finished since the last fetch
if (prevQueue && prevQueue.townId === t.id) {
const nowIds = new Set(t.queue.map((q) => q.id));
for (const q of prevQueue.items) {
if (nowIds.has(q.id)) continue;
const b = t.buildings.find((x) => x.key === q.key);
if (b && b.level >= q.toLevel) toast(App.t('alerts.build_done', { name: App.buildingName(q.type), level: b.level }), 'ok');
refetchTries.delete(q.id);
App.checkAlerts();
}
}
prevQueue = { townId: t.id, items: t.queue.slice() };
if (visible) draw(); else dirty = true;
}
App.registerScreen({
id: 'pop', titleKey: 'screen.pop', navKey: 'nav.pop', icon: 'pop', hud: true,
render(container) {
box = container;
App.on('town', onTown);
App.on('session', () => { dirty = true; prevQueue = null; });
App.on('townchange', () => { dirty = true; if (visible) draw(); });
},
onShow() {
visible = true;
draw();
if (offTick) offTick();
offTick = App.onTick(tick);
if (td() && Date.now() - App.state.townFetchedAt > 15000) App.refreshTown().catch(() => {});
},
onHide() { visible = false; if (offTick) offTick(); offTick = null; closeSheet(); },
});
}());

View file

@ -0,0 +1,84 @@
'use strict';
/* Settings: language, account info, device tokens (list + revoke) and logout. */
(function () {
const { h, clear, icon, toast, openSheet } = UI;
const I = UpstreamI18n;
let box, devicesEl, tokens = null, tokenErr = null;
function kv(label, value) { return h('div', { class: 'kv' }, h('span', { class: 'k', text: label }), h('span', { class: 'v', text: value })); }
async function loadTokens() {
try { tokens = (await App.api.get('/auth/tokens')).tokens; tokenErr = null; } catch (e) { tokenErr = App.errMsg(e); }
drawDevices();
}
function drawDevices() {
if (!devicesEl) return;
clear(devicesEl);
if (tokenErr) { devicesEl.appendChild(h('p', { class: 'form-error', role: 'alert', text: tokenErr })); return; }
if (!tokens) { devicesEl.appendChild(h('p', { class: 'empty', text: App.t('common.loading') })); return; }
const now = App.now();
for (const t of tokens) {
devicesEl.appendChild(h('li', { class: 'device' },
h('span', { class: 'row-ic' }, icon('device')),
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: t.device || App.t('settings.device.unnamed') }), t.current ? h('span', { class: 'pill accent', text: App.t('settings.device.current') }) : null),
h('span', { class: 'row-sub', text: App.t('settings.device.created', { t: App.fmt.ago(now - t.createdAt) }) + ' · ' + App.t('settings.device.lastUsed', { t: App.fmt.ago(now - t.lastUsedAt) }) })),
t.current ? null : h('button', { class: 'btn small danger', type: 'button', onclick: (ev) => revoke(t, ev.currentTarget) }, App.t('settings.device.revoke'))));
}
}
async function revoke(t, btn) {
btn.disabled = true;
try {
await App.api.del('/auth/tokens/' + t.id);
toast(App.t('settings.device.revoked'), 'ok');
} catch (e) { if (e.code !== 'not_found') toast(App.errMsg(e), 'error'); }
loadTokens();
}
function confirmLogout() {
const sheet = openSheet({
title: App.t('settings.logout'), icon: 'logout', closeLabel: App.t('common.close'),
body: h('div', { class: 'detail' }, h('p', { class: 'detail-desc', text: App.t('settings.logout.confirm') }),
h('div', { class: 'btn-row' },
h('button', { class: 'btn', type: 'button', onclick: () => sheet.close() }, App.t('common.cancel')),
h('button', { class: 'btn danger', type: 'button', onclick: async () => {
try { await App.api.post('/auth/logout', {}, { retries: 1 }); } catch (e) { /* the token may already be gone */ }
sheet.close();
App.clearSession();
App.authNotice = null;
App.go('auth');
} }, icon('logout'), App.t('settings.logout')))),
});
}
function draw() {
clear(box);
const st = App.state;
const op = st.operator, w = st.world;
devicesEl = h('ul', { class: 'device-list' });
box.appendChild(h('div', { class: 'page' },
h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.language') })),
h('div', { class: 'seg', role: 'group', 'aria-label': App.t('settings.language') },
I.LANGS.map((l) => h('button', { class: 'seg-btn', type: 'button', 'aria-pressed': String(st.lang === l), onclick: () => App.setLang(l) }, App.t('settings.lang.' + l))))),
h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.account') })),
st.user ? kv(App.t('settings.username'), st.user.username) : null,
op ? kv(App.t('settings.operator'), op.name) : null,
op ? kv(App.t('settings.as'), I.fmtAs(op.asNumber)) : null,
w ? kv(App.t('settings.world'), App.t('settings.worldInfo', { name: w.name, speed: w.speed, r: w.mapRadius })) : null,
h('button', { class: 'btn danger wide', type: 'button', onclick: confirmLogout }, icon('logout'), App.t('settings.logout'))),
h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.devices') })),
h('p', { class: 'dimmer small', text: App.t('settings.devices.hint') }), devicesEl),
h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('settings.about') })),
h('p', { class: 'dimmer small', text: App.t('settings.about.text') }))));
drawDevices();
}
App.registerScreen({
id: 'settings', titleKey: 'screen.settings', navKey: 'nav.settings', icon: 'gear', hud: false,
render(container) { box = container; App.on('session', () => { tokens = null; }); },
onShow() { draw(); loadTokens(); },
});
}());

132
public/js/ui.js Normal file
View file

@ -0,0 +1,132 @@
'use strict';
/*
* Small DOM helpers shared by the shell and the screens (window.UI). Everything is built with createElement and
* textContent: player-controlled strings (POP names, usernames) never go through innerHTML. No inline handlers
* (CSP): events are attached with addEventListener.
*/
(function () {
const SVG_NS = 'http://www.w3.org/2000/svg';
const XLINK = 'http://www.w3.org/1999/xlink';
// h('button', { class: 'btn', onclick: fn, 'aria-label': 'x', dataset: { k: 1 } }, 'text', childNode, [more])
function h(tag, props, ...kids) {
const el = document.createElement(tag);
if (props) {
for (const k of Object.keys(props)) {
const v = props[k];
if (v === undefined || v === null || v === false) continue;
if (k === 'class') el.className = v;
else if (k === 'text') el.textContent = v;
else if (k === 'dataset') Object.assign(el.dataset, v);
else if (k === 'style') { for (const s of Object.keys(v)) el.style.setProperty(s, v[s]); }
else if (k.startsWith('on') && typeof v === 'function') el.addEventListener(k.slice(2), v);
else if (v === true) el.setAttribute(k, '');
else el.setAttribute(k, String(v));
}
}
append(el, kids);
return el;
}
function append(el, kids) {
for (const c of kids) {
if (c === null || c === undefined || c === false) continue;
if (Array.isArray(c)) append(el, c);
else el.appendChild(c instanceof Node ? c : document.createTextNode(String(c)));
}
return el;
}
function clear(el) { while (el.firstChild) el.removeChild(el.firstChild); return el; }
// <svg class="ic"><use href="icons/sprite.svg#i-name"></use></svg>
function icon(name, cls) {
const svg = document.createElementNS(SVG_NS, 'svg');
svg.setAttribute('class', 'ic' + (cls ? ' ' + cls : ''));
svg.setAttribute('aria-hidden', 'true');
svg.setAttribute('focusable', 'false');
const use = document.createElementNS(SVG_NS, 'use');
use.setAttribute('href', 'icons/sprite.svg#i-' + name);
use.setAttributeNS(XLINK, 'xlink:href', 'icons/sprite.svg#i-' + name);
svg.appendChild(use);
return svg;
}
// ------------------------------------------------------------------ toasts
function toast(msg, kind) {
const root = document.getElementById('toasts');
if (!root) return;
const el = h('div', { class: 'toast ' + (kind || 'info'), text: msg });
root.appendChild(el);
while (root.children.length > 3) root.removeChild(root.firstChild);
setTimeout(() => { el.classList.add('out'); setTimeout(() => el.remove(), 250); }, kind === 'error' ? 4500 : 2600);
}
// ------------------------------------------------------------------ sheet (bottom sheet on phones, dialog on desktop)
// openSheet({ title, icon, body: Node|Node[], onClose }) -> { el, body, close(), setTitle() }
let current = null;
function openSheet(opts) {
if (current) current.close(true);
const root = document.getElementById('sheet-root');
const prevFocus = document.activeElement;
const titleId = 'sheet-title';
const body = h('div', { class: 'sheet-body' });
const titleEl = h('h2', { id: titleId, class: 'sheet-title', text: opts.title || '' });
const closeBtn = h('button', { class: 'icon-btn', type: 'button', 'aria-label': opts.closeLabel || 'Close' }, icon('x'));
const panel = h('div', { class: 'sheet', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': titleId, tabindex: '-1' },
h('div', { class: 'sheet-grab', 'aria-hidden': 'true' }),
h('div', { class: 'sheet-head' }, opts.icon ? h('span', { class: 'sheet-icon ' + (opts.iconClass || '') }, icon(opts.icon)) : null, titleEl, closeBtn),
body);
const backdrop = h('div', { class: 'backdrop' });
const wrap = h('div', { class: 'sheet-wrap' }, backdrop, panel);
append(body, [].concat(opts.body || []));
root.appendChild(wrap);
requestAnimationFrame(() => wrap.classList.add('open'));
let closed = false;
const api = {
el: panel, body,
setTitle(s) { titleEl.textContent = s; },
close(silent) {
if (closed) return;
closed = true;
if (current === api) current = null;
document.removeEventListener('keydown', onKey, true);
wrap.classList.remove('open');
setTimeout(() => wrap.remove(), 200);
if (!silent && prevFocus && prevFocus.focus && document.contains(prevFocus)) { try { prevFocus.focus({ preventScroll: true }); } catch (e) { /* gone */ } }
if (opts.onClose) opts.onClose();
},
};
function onKey(e) {
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); api.close(); return; }
if (e.key !== 'Tab') return;
const f = panel.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');
if (!f.length) return;
const first = f[0], last = f[f.length - 1];
if (e.shiftKey && (document.activeElement === first || document.activeElement === panel)) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
}
document.addEventListener('keydown', onKey, true);
closeBtn.addEventListener('click', () => api.close());
// a sheet opened on finger lift (map tap) must not be closed by the compatibility click that follows the lift
const openedAt = Date.now();
backdrop.addEventListener('click', () => { if (Date.now() - openedAt > 400) api.close(); });
setTimeout(() => { try { panel.focus({ preventScroll: true }); } catch (e) { /* ignore */ } }, 0);
current = api;
return api;
}
function closeSheet() { if (current) current.close(); }
const sheetOpen = () => !!current;
// Cheap safe storage for per-viewer conveniences (language, last screen). Never for anything that must persist.
const safeStore = {
get(k) { try { return window.localStorage.getItem(k); } catch (e) { return null; } },
set(k, v) { try { window.localStorage.setItem(k, v); } catch (e) { /* private window */ } },
del(k) { try { window.localStorage.removeItem(k); } catch (e) { /* ignore */ } },
};
window.UI = { h, append, clear, icon, toast, openSheet, closeSheet, sheetOpen, safeStore };
}());

View file

@ -0,0 +1,17 @@
{
"name": "UPSTREAM",
"short_name": "UPSTREAM",
"description": "A persistent strategy game about rival regional network operators. Build POPs, connect the region, outlast the competition.",
"start_url": "./",
"scope": "./",
"display": "standalone",
"orientation": "any",
"background_color": "#070b16",
"theme_color": "#070b16",
"icons": [
{ "src": "icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
{ "src": "icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
{ "src": "icons/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" },
{ "src": "icons/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }
]
}