Compare commits
8
Commits
d2b4f62949
...
c8daa086e1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8daa086e1 | ||
|
|
85336f109f | ||
|
|
a5385a53a7 | ||
|
|
0846c017ae | ||
|
|
b4e5846dff | ||
|
|
3afd892487 | ||
|
|
cc1005c99e | ||
|
|
c998f8fda0 |
No files matched your search
@@ -7,3 +7,4 @@ node_modules
|
||||
.DS_Store
|
||||
web/static/css/app.css
|
||||
art
|
||||
web/static/app
|
||||
@@ -2,6 +2,7 @@
|
||||
/bin/
|
||||
/moonminers
|
||||
/web/static/css/app.css
|
||||
/web/static/app/
|
||||
|
||||
# Local env files (never commit)
|
||||
.env
|
||||
|
||||
+30
-2
@@ -9,6 +9,10 @@ shared rules: `../AGENTS.md`. Run every command below from this directory (`serv
|
||||
- The interface is server-rendered HTML. htmx swaps it in place, morphing the game's regions
|
||||
(idiomorph extension, vendored in `web/static/vendor/idiomorph`) so elements keep their
|
||||
state; Tailwind v4 (standalone CLI) builds the CSS. No bundler, no TypeScript, no Alpine.
|
||||
- Experiment: a second web client at `/app` (`web/app/`), Preact + JSX + `@preact/signals`
|
||||
(vendored in `web/app/vendor`, no other libraries, no preact/compat), bundled by esbuild
|
||||
(standalone binary fetched like Tailwind, `make app`) into `web/static/app/` (built, not
|
||||
committed). See "web/app" below.
|
||||
- three.js is a plain ES module loaded through an import map (vendored in `web/static/vendor`).
|
||||
The viewport in the aside shows the selected moon, generated procedurally from its id
|
||||
(`terrain.js`, run in a worker by `moon-worker.js`; settings tuned on `/utils/moons` and
|
||||
@@ -139,6 +143,27 @@ shared rules: `../AGENTS.md`. Run every command below from this directory (`serv
|
||||
ops at `/utils/liveops` (dashboard from `event_log`, timed events in `live_event` applied
|
||||
via `eventMultiplier` in game.go, `announcement`; both shown in the game's `#banner`).
|
||||
- `web/css/app.css`: Tailwind input (custom HUD styles); builds to `web/static/css/app.css`.
|
||||
- `web/app/` (the Preact client, `GET /app`, template `spa.html`): the Moons slice (header and
|
||||
wallet, Claim all, moon list with its Active/Past tabs, search and past pages, wells table
|
||||
with multi-well drills and claim-wide, the moon's resale, well panel with the better-well
|
||||
line, a past moon's haul, viewport, toasts) on the JSON API; other sections, buying a moon
|
||||
and the store link to the classic client. `session.js`: like the Defold client's session
|
||||
(`base` server state, `pending` predictions, `shown`/`live` computeds, an outbox sending
|
||||
one request at a time with `clientSeq`, rollback on 422, predicted navigation);
|
||||
`predict.js`: port of the Defold `predict.lua` (claim, stake, redrill; readiness is local,
|
||||
`end <= now`). `clock.js`: server clock, `edge` (bumped at each drill end), the frame loop
|
||||
and eased numbers. `ui.jsx`: `Num`, `Countdown`, `DrillBar` (Web Animation, keyed by tool
|
||||
id; corrections change its playback rate). `fx.js`: effects at the click from the
|
||||
predicted change, using exports of the classic `fx.js`/`sfx.js`. `scene.js` +
|
||||
`scene-worker.js`: the classic `MoonScene` in a worker on an OffscreenCanvas (main thread
|
||||
fallback, `?mainscene`). `dialog.jsx`: the confirm dialog (the classic markup, opened by
|
||||
the classic `ui.js`), for the API's `confirm` texts. Same classes as the classic markup (app.css); `preact.css` only
|
||||
for what differs.
|
||||
Rules: pass signals to JSX as they are; read `.value` only in logic, `computed()` and
|
||||
effects (`scripts/check-signals-jsx.mjs` in `make check` flags `.value` inside JSX).
|
||||
Key list items by stable ids (drills by tool id, not stake id: a predicted stake's id
|
||||
changes when the server answers); never swap an element that animates for another.
|
||||
Animate with transform/opacity (CSS, Web Animations), FLIP (`flip.js`) for rows that move.
|
||||
- `sql/tables.sql`, `sql/data.sql`: schema for fresh databases. `sql/migrations/` (001–016):
|
||||
changes for existing ones, applied on every `migrate`, so each must be idempotent.
|
||||
- `test-endpoints.restclient`: the up-to-date list of endpoints, in Emacs restclient format.
|
||||
@@ -146,9 +171,12 @@ shared rules: `../AGENTS.md`. Run every command below from this directory (`serv
|
||||
they write into `web/static/assets`.
|
||||
|
||||
## Commands
|
||||
- `make dev`: server on :3000 that reloads templates/static from disk, with Tailwind watching.
|
||||
- `make dev`: server on :3000 that reloads templates/static from disk, with Tailwind and
|
||||
esbuild (the Preact client) watching. `MM_API_DELAY_MS=300` (with `MM_DEV=1`) holds every
|
||||
game request that long, to try both clients on a slow connection.
|
||||
- `make build`, `make check` (gofmt, vet, template check, JS syntax of every `web/static/js/*.js`,
|
||||
moon traits check), `make migrate`, `make load-config`. `go run . sim` prints the economy analysis.
|
||||
moon traits check, the Preact client's `.value` check and build), `make migrate`,
|
||||
`make load-config`. `go run . sim` prints the economy analysis.
|
||||
- Template check: `templates_test.go` (`go test -run Templates`, in `make check`) parses the
|
||||
templates like the server and renders every page and region against in-memory game states;
|
||||
when you add a page, section or view model branch, make sure its states/views reach it.
|
||||
|
||||
@@ -5,10 +5,14 @@ ARG TAILWIND_VERSION=v4.1.14
|
||||
RUN curl -fsSL -o /usr/local/bin/tailwindcss \
|
||||
https://github.com/tailwindlabs/tailwindcss/releases/download/${TAILWIND_VERSION}/tailwindcss-linux-x64 \
|
||||
&& chmod +x /usr/local/bin/tailwindcss
|
||||
ARG ESBUILD_VERSION=0.28.2
|
||||
RUN curl -fsSL https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-${ESBUILD_VERSION}.tgz \
|
||||
| tar xz -C /usr/local/bin --strip-components=2 package/bin/esbuild
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN tailwindcss -i web/css/app.css -o web/static/css/app.css --minify \
|
||||
&& make app ESBUILD=/usr/local/bin/esbuild \
|
||||
&& CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /moonminers .
|
||||
|
||||
FROM scratch
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
# Hand-off: Preact web client experiment (branch `s-preact`)
|
||||
|
||||
## Goal
|
||||
Find out whether a web client can feel as smooth and instant as the Defold client (which
|
||||
predicts click results locally and eases corrections). It's built with Preact + JSX +
|
||||
@preact/signals and compiled by esbuild, on the existing JSON API. It's served at `/app`
|
||||
next to the classic htmx client at `/`. The user will compare them by feel: fast
|
||||
claim/redrill/deploy clicks, and animations that never hitch.
|
||||
|
||||
## What's built
|
||||
- `web/app/` (about 2,400 lines without the vendored code):
|
||||
- `session.js`: a port of the Defold `session.lua`. Holds the `base`/`pending` signals,
|
||||
the `shown`/`live` computeds, and an outbox that sends one request at a time with
|
||||
`clientSeq`. A 422 rolls the prediction back. Navigation is predicted. It refetches at
|
||||
`nextEnd` and keeps the URL in sync.
|
||||
- `predict.js`: a port of `predict.lua` (claim, stake, redrill, derive). One deliberate
|
||||
difference: readiness is local (`s.ready || s.end <= now`).
|
||||
- `clock.js`: server clock offset. An `edge` signal is bumped by a timer at each drill
|
||||
end. Also a single rAF ticker loop and eased numbers (`eased`, `hold`/`release`).
|
||||
- `ui.jsx`:
|
||||
- `Num`: eased number, written by the ticker.
|
||||
- `Countdown`.
|
||||
- `DrillBar`: a WAAPI `scaleX` animation keyed by tool id. A server correction changes
|
||||
`playbackRate` so the bar lands on the true end without jumping.
|
||||
- `SupplyBar`: clip-path.
|
||||
- `buttons.jsx`: `ReadyButton`. It dispatches `mm:ready` when the clock (not a new
|
||||
state) enables it, and the classic fx.js then plays the pop, sparks and sound.
|
||||
- `header.jsx`, `moons.jsx`, `side.jsx`: the same markup and classes as the classic
|
||||
templates, so they use `app.css`. `preact.css` covers only the differences. The whole
|
||||
Moons slice: the moon list's Active/Past tabs, search and past pages, a past moon's
|
||||
haul, the multi-well row and claim-wide (not predicted: the server splits it), the
|
||||
moon sale, and the well panel's better-well line ("Deploy there" moves the view, so it
|
||||
waits for the server).
|
||||
- `dialog.jsx`: the classic confirm dialog (its markup, opened by the classic `ui.js`),
|
||||
for the API's `confirm` texts (the moon sale).
|
||||
- `fx.js`: effects at the click, from the predicted diff. Uses exports added to
|
||||
`web/static/js/fx.js` (`floatText`, `stream`, `mark`, `centerOf`, `formatMoney`) and to
|
||||
`sfx.js`.
|
||||
- `flip.js`: FLIP for keyed rows, with positions relative to the container.
|
||||
- `scene.js` + `scene-worker.js`: the classic `MoonScene` runs in a worker on an
|
||||
OffscreenCanvas. It uses stand-ins for the canvas, its container, `ResizeObserver` and
|
||||
`document`. Pointer and wheel events and the size are forwarded from the page. Drag and
|
||||
zoom were verified. If the worker fails it falls back to the page's thread;
|
||||
`?mainscene` forces that.
|
||||
- `vendor/`: preact 11.0.1 and signals 2.11.3 / signals-core 1.14.4. `jsconfig.json`
|
||||
holds the path aliases, including `three`, used by the worker bundle.
|
||||
- Go: `GET /app` renders `web/templates/spa.html`. `MM_API_DELAY_MS` (dev only) delays
|
||||
`/act/`, `/api/act/`, `/api/state` and htmx `GET /` for both clients.
|
||||
- Build:
|
||||
- `make app`: esbuild is fetched into `bin/` from the npm tarball. It outputs `app.js`,
|
||||
`app.css`, `scene-worker.js` and `moon-worker.js` to `web/static/app/`, which is
|
||||
gitignored and in `.dockerignore`.
|
||||
- `make dev` watches the client.
|
||||
- `make build` depends on `app`.
|
||||
- The Dockerfile fetches esbuild and runs `make app`.
|
||||
- `make check` (passes) also runs `scripts/check-signals-jsx.mjs`, which flags `.value`
|
||||
inside JSX, and builds the client.
|
||||
- AGENTS.md documents `web/app` and its rules. `/app` is in `templates_test.go` and
|
||||
`test-endpoints.restclient`.
|
||||
|
||||
## How to try it
|
||||
```
|
||||
cd wt-s-preact && make app && go build -o bin/moonminers .
|
||||
DB_DATABASE=mm_s_preact PORT=3151 MM_DEV=1 ./bin/moonminers serve
|
||||
# second, slow server on the same DB: MM_API_DELAY_MS=300 PORT=3152 ...
|
||||
```
|
||||
Open `http://localhost:3151/app` and `http://localhost:3151/`. They share the same player
|
||||
cookie. The database `mm_s_preact` is kept. `.env` was copied from `../server/.env` and is
|
||||
gitignored. **The servers are stopped now**; restart them with the commands above.
|
||||
|
||||
## Measurements
|
||||
|
||||
### Second run (Oct 20, after the Moons slice was finished)
|
||||
Headless Chrome 155 on macOS over the DevTools protocol (no puppeteer), Metal GPU
|
||||
(`--use-angle=metal --enable-gpu --ignore-gpu-blocklist`), 1440×900. Same method as below:
|
||||
the median of 3 alternating runs; latency from pointerdown to the first frame where the
|
||||
side panel's drill line count changes. Each test starts from a known state set through the
|
||||
API and admin endpoints (the wells topped up, one drone finished on the well). No other
|
||||
engine was running; the machine's load average was 6 to 9 from other work.
|
||||
|
||||
| | classic, 0 ms | app, 0 ms | classic, +300 ms | app, +300 ms |
|
||||
|---|---|---|---|---|
|
||||
| claim to visible result | 30 ms | 13 ms | 347 ms | 14 ms |
|
||||
| redrill to visible result | 31 ms | 15 ms | 331 ms | 14 ms |
|
||||
| 6 deploy clicks 120 ms apart that took effect | 6, 6, 6 | 6, 6, 6 | **2, 2, 2** | 6, 6, 6 |
|
||||
| Redrill clickable 150 ms after Claim | yes | yes | **no** | yes |
|
||||
| dropped frames (>25 ms) per run | 0, 0, 0 | 0, 0, 0 | 0, 0, 1 | 0, 0, 0 |
|
||||
|
||||
Main-thread time for one claim (Chrome's Performance.getMetrics counters, from the click to
|
||||
1.5 s after, 0 ms delay, median of 3):
|
||||
|
||||
| | script | layout | style | all tasks |
|
||||
|---|---|---|---|---|
|
||||
| classic | 25 ms | 5 ms | 9 ms | 69 ms |
|
||||
| app | 11 ms | 8 ms | 10 ms | 62 ms |
|
||||
|
||||
- The classic client's first claim of a page load had 109 ms of script (the AudioContext on
|
||||
the first gesture, as below); the others 24–25 ms.
|
||||
- Most of "all tasks" is the viewport and other frames in the window, the same in both.
|
||||
- With an idle GPU the frame drops are gone for both clients: the earlier noise was the
|
||||
other engine.
|
||||
- Side-by-side screenshots (moon, well panel, multi-well moon, past moons) are identical but
|
||||
for the header's Classic/Admin link.
|
||||
|
||||
### First run
|
||||
Headless Chromium 156 (Playwright's cache) with puppeteer-core, GPU via
|
||||
`--enable-gpu --use-angle=gl-egl`. Swiftshader is far too slow to use. Each figure is the
|
||||
median of 3 alternating runs. The latency is the time from pointerdown to the first frame
|
||||
where the side panel's drill lines change.
|
||||
|
||||
| | classic, 0 ms | app, 0 ms | classic, +300 ms | app, +300 ms |
|
||||
|---|---|---|---|---|
|
||||
| claim to visible result | 52 ms | 14 ms | 342 ms | 12 ms |
|
||||
| redrill to visible result | 41 ms | 11 ms | 329 ms | 8 ms |
|
||||
| 6 deploy clicks 120 ms apart that took effect | 6, 6, 5 | 6, 6, 6 | **2, 2, 2** | 6, 6, 6 |
|
||||
| Redrill clickable 150 ms after Claim | yes | yes | **no** | yes |
|
||||
| dropped frames (>25 ms) per run | 9, 7, 2 | 7, 12, 1 | 9, 5, 1 | 4, 4, 2 |
|
||||
|
||||
- The classic client drops clicks while a request runs: `body.is-busy` sets
|
||||
`pointer-events: none`.
|
||||
- Frame drops were noisy and about the same for both clients. Another agent's Defold engine
|
||||
was using about 460% CPU and the GPU.
|
||||
- Long-animation-frame entries show the frames waiting on the GPU or presentation rather
|
||||
than on scripts.
|
||||
- The worker viewport and the main-thread viewport (`app-main`) showed no clear difference
|
||||
under this load.
|
||||
- The first click in each run has a long task of about 120 ms in both clients. It comes
|
||||
from `sfx.js` creating the AudioContext on the first gesture.
|
||||
- The harness lives in the session scratchpad, which is not kept. If it's needed again,
|
||||
recreate it from this description: `measure.mjs` (in-page rAF sampling, longtask/LoAF
|
||||
observers, a `watch` predicate on the drill-line count, `page.mouse.click`), `setup.mjs`
|
||||
(a player via the admin endpoints: unlock all, 5 drones, credits, a moon) and
|
||||
`runall.sh`.
|
||||
|
||||
## Unfinished / next steps
|
||||
Done since the first hand-off: the well panel and Moons section gaps (better well, multi-well
|
||||
rows and claim-wide, moon sale, past moons tab, search and pages), navigation and sale and
|
||||
mined-out effects, the measurements on a quiet GPU with main-thread time per claim, and the
|
||||
side-by-side screenshots. What's left:
|
||||
1. Other sections (Equipment, Store, Market, Refinery, Advisors, Leaderboard, Help), buying
|
||||
a moon (the new-moon teaser and reveal) and the store link still open the classic client.
|
||||
The API has every section's state and the prediction rules for sells and refinery
|
||||
batches (api.md "Prediction").
|
||||
2. Moon sale, claim-wide and "Deploy there" wait for the server (a spinner); predicting them
|
||||
would need the server's split of multi-well claims and the sale's payout rules.
|
||||
3. The measurement harness lived in a session scratchpad again (CDP: an in-page rAF watch on
|
||||
the drill-line count, clicks through Input.dispatchMouseEvent, Performance.getMetrics
|
||||
around a claim). Worth keeping in `scripts/` if the comparison continues.
|
||||
4. Report: rough line counts are above. Hard parts:
|
||||
- predicted stake ids differ from the server's, so drill rows are keyed by tool id;
|
||||
- easing bar corrections (playbackRate);
|
||||
- OffscreenCanvas shims for OrbitControls (`getRootNode`, pointer capture, readonly
|
||||
`Event.type`);
|
||||
- avoiding ticker writes conflicting with Preact's children (the ticker writes into
|
||||
empty spans).
|
||||
|
||||
## Gotchas
|
||||
- `live` re-derives counts on every `edge`. Components read `live.value` in their body,
|
||||
which is allowed. Never read `.value` inside JSX.
|
||||
- Readiness from the clock: `clockCaused()` compares the time of the last edge with the
|
||||
last `shown` change, because Preact re-renders asynchronously.
|
||||
- The worker bundle includes three.js (about 600 KB). The page itself uses the import map
|
||||
only for the main-thread fallback.
|
||||
- esbuild needs `--tsconfig=web/app/jsconfig.json` so that `three` resolves for
|
||||
`web/static/js/scene.js` too.
|
||||
- Never `pkill -f` a pattern contained in your own command line; it kills your own shell.
|
||||
- `scripts/check-signals-jsx.mjs` flags any `.value` in JSX, including plain objects' fields
|
||||
(the sale lines' `value`): destructure them under another name.
|
||||
- Headless Chrome plays the game's sounds through the speakers; start it with `--mute-audio`.
|
||||
+22
-5
@@ -1,20 +1,31 @@
|
||||
TAILWIND_VERSION := v4.1.14
|
||||
TAILWIND := bin/tailwindcss
|
||||
CSS := web/static/css/app.css
|
||||
ESBUILD_VERSION := 0.28.2
|
||||
ESBUILD := bin/esbuild
|
||||
# The Preact client (web/app) bundled into web/static/app: app.js, app.css and the viewport's
|
||||
# worker with three.js (scene-worker.js, which starts moon-worker.js for meshes). The page loads the classic client's modules
|
||||
# (/static/js/...) by URL.
|
||||
APP := $(ESBUILD) app=web/app/main.jsx scene-worker=web/app/scene-worker.js moon-worker=web/static/js/moon-worker.js --bundle --format=esm --target=es2022 '--external:/static/*' --tsconfig=web/app/jsconfig.json --outdir=web/static/app
|
||||
|
||||
.PHONY: build dev css migrate load-config check
|
||||
.PHONY: build dev css app migrate load-config check
|
||||
|
||||
build: css
|
||||
build: css app
|
||||
go build -o bin/moonminers .
|
||||
|
||||
# Server on :3000 that reloads templates and static files from disk; CSS rebuilds on change.
|
||||
dev: $(TAILWIND)
|
||||
# Server on :3000 that reloads templates and static files from disk; CSS and the Preact
|
||||
# client rebuild on change.
|
||||
dev: $(TAILWIND) $(ESBUILD)
|
||||
$(TAILWIND) -i web/css/app.css -o $(CSS) --watch=always & \
|
||||
trap 'kill $$!' EXIT; MM_DEV=1 go run . serve
|
||||
$(APP) --sourcemap --watch=forever & \
|
||||
trap 'kill $$(jobs -p)' EXIT; MM_DEV=1 go run . serve
|
||||
|
||||
css: $(TAILWIND)
|
||||
$(TAILWIND) -i web/css/app.css -o $(CSS) --minify
|
||||
|
||||
app: $(ESBUILD)
|
||||
$(APP) --minify
|
||||
|
||||
migrate:
|
||||
go run . migrate
|
||||
|
||||
@@ -26,6 +37,12 @@ check:
|
||||
go test -run '^(TestTemplates|TestAPI|TestSharedQuotes)$$' -count=1 .
|
||||
for f in web/static/js/*.js; do node --check $$f || exit 1; done
|
||||
node --no-warnings scripts/check-moon-traits.mjs
|
||||
node scripts/check-signals-jsx.mjs web/app
|
||||
$(APP) --minify --log-level=warning
|
||||
|
||||
$(ESBUILD):
|
||||
mkdir -p bin
|
||||
curl -fsSL https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-$(ESBUILD_VERSION).tgz | tar xz -C bin --strip-components=2 package/bin/esbuild
|
||||
|
||||
$(TAILWIND):
|
||||
mkdir -p bin
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// The Preact client's rule (AGENTS.md, "web/app"): pass signals to JSX as they are and
|
||||
// read `.value` only in logic, computed() and effects. A `.value` read inside JSX makes the
|
||||
// whole component re-render on every change instead of Preact updating one text node or
|
||||
// attribute.
|
||||
//
|
||||
// Flags `.value` inside a JSX expression container in web/app/**/*.jsx (`>{x.value}`,
|
||||
// `attr={x.value}`, a `{x.value …}` child on its own line), up to the first function in
|
||||
// it: event handlers (`onClick={() => x.value++}`) are fine, `{xs.value.map(…)}` isn't.
|
||||
// A guard rail, not a parser: it reads the source line by line, so keep JSX in .jsx files
|
||||
// and Prettier's style (`attr={…}` without spaces; plain JS assignments as `x = {…}`).
|
||||
//
|
||||
// Usage: node scripts/check-signals-jsx.mjs <dir>
|
||||
|
||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const dir = process.argv[2] ?? "web/app";
|
||||
// A container: opened right after a tag's `>`, an attribute's `=`, or at the start of a
|
||||
// line (a child), up to its closing brace; nested `${…}` is allowed inside.
|
||||
const container = /(?:>|=|^\s*)\{((?:[^{}]|\{[^{}]*\})*)\}?/g;
|
||||
const read = /\.value\b(?!\s*=[^=])/;
|
||||
|
||||
function* files(d) {
|
||||
for (const name of readdirSync(d)) {
|
||||
const p = join(d, name);
|
||||
if (name === "vendor") continue;
|
||||
if (statSync(p).isDirectory()) yield* files(p);
|
||||
else if (p.endsWith(".jsx")) yield p;
|
||||
}
|
||||
}
|
||||
|
||||
let bad = 0;
|
||||
for (const file of files(dir)) {
|
||||
readFileSync(file, "utf8")
|
||||
.split("\n")
|
||||
.forEach((line, i) => {
|
||||
if (/^\s*(\/\/|\*)/.test(line)) return;
|
||||
for (const m of line.matchAll(container)) {
|
||||
// What runs during render: the part before any function in it.
|
||||
const body = m[1].split(/=>|\bfunction\b/)[0];
|
||||
if (read.test(body)) {
|
||||
console.error(`${file}:${i + 1}: .value read inside JSX; pass the signal, or read it in a computed: ${line.trim()}`);
|
||||
bad++;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
process.exit(bad ? 1 : 0);
|
||||
+20
-1
@@ -77,11 +77,17 @@ func serve(ctx context.Context) error {
|
||||
mux.HandleFunc("GET /api/leaderboard", s.handleLeaderboard)
|
||||
mux.HandleFunc("GET /api/state", s.handleAPIState)
|
||||
mux.HandleFunc("POST /api/act/{action}", s.handleAPIAction)
|
||||
// The Preact client (web/app, built into web/static/app), next to the htmx one.
|
||||
mux.HandleFunc("GET /app", func(w http.ResponseWriter, r *http.Request) { s.render(w, "spa", nil) })
|
||||
|
||||
var handler http.Handler = mux
|
||||
if ms, _ := strconv.Atoi(os.Getenv("MM_API_DELAY_MS")); ms > 0 && s.dev {
|
||||
handler = delayGame(handler, time.Duration(ms)*time.Millisecond)
|
||||
}
|
||||
addr := ":" + env("PORT", "3000")
|
||||
srv := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: logRequests(secureHeaders(limitBody(mux))),
|
||||
Handler: logRequests(secureHeaders(limitBody(handler))),
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 60 * time.Second,
|
||||
@@ -123,6 +129,19 @@ func (s *server) render(w http.ResponseWriter, name string, data any) {
|
||||
}
|
||||
}
|
||||
|
||||
// delayGame holds every game request (the htmx page's swaps and actions, the JSON API) for
|
||||
// d before answering, to try the clients with a slow connection (MM_API_DELAY_MS, dev only).
|
||||
func delayGame(next http.Handler, d time.Duration) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
if strings.HasPrefix(p, "/act/") || strings.HasPrefix(p, "/api/act/") || p == "/api/state" ||
|
||||
(p == "/" && r.Header.Get("HX-Request") == "true") {
|
||||
time.Sleep(d)
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func logRequests(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
@@ -62,6 +62,9 @@ func TestTemplates(t *testing.T) {
|
||||
render("regions", p)
|
||||
}
|
||||
|
||||
// The Preact client's page (/app).
|
||||
render("spa", nil)
|
||||
|
||||
// Admin pages and the pages outside the game, with and without permission.
|
||||
s := veteranState()
|
||||
now := time.Now()
|
||||
|
||||
@@ -22,6 +22,9 @@ userId=:user_id
|
||||
GET :host/?s=store
|
||||
:headers
|
||||
|
||||
# The Preact client (web/app): a page that runs on the JSON API below; same view params
|
||||
GET :host/app?s=moons
|
||||
|
||||
GET :host/?list=past&page=2
|
||||
:headers
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// Buttons that change state in place (never replaced while they animate).
|
||||
|
||||
import { useRef, useLayoutEffect } from "preact/hooks";
|
||||
import { busy, clockCaused } from "./session.js";
|
||||
|
||||
// A Claim button: disabled until `ready`. When the clock (not a new state) makes it ready,
|
||||
// it fires "mm:ready" (the classic client's fx.js plays the ready sound, pop and sparks).
|
||||
// busyKey: shows the spinner while an unpredicted action with that key is on its way.
|
||||
export function ReadyButton({ ready = true, busyKey = "", class: cls, children, ...rest }) {
|
||||
const ref = useRef(null);
|
||||
const was = useRef(ready);
|
||||
useLayoutEffect(() => {
|
||||
if (ready && !was.current && clockCaused()) ref.current?.dispatchEvent(new CustomEvent("mm:ready", { bubbles: true }));
|
||||
was.current = ready;
|
||||
}, [ready]);
|
||||
const spinning = busyKey && busy.value[busyKey];
|
||||
return (
|
||||
<button ref={ref} type="button" data-claim class={`${cls}${spinning ? " htmx-request" : ""}`} disabled={!ready} {...rest}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Lookups in the static catalog (state.catalog) and the player's tools.
|
||||
|
||||
import { base } from "./session.js";
|
||||
|
||||
export const colorOf = (resource) =>
|
||||
base.peek()?.catalog?.resources?.find((r) => r.name === resource)?.color ??
|
||||
base.peek()?.catalog?.refined?.find((r) => r.name === resource)?.color ??
|
||||
"#e2e8f0";
|
||||
|
||||
export const toolOf = (st, id) => st.tools.find((t) => t.id === id);
|
||||
|
||||
export const imageOf = (st, storeItemId) => st.catalog?.tools?.find((t) => t.storeItemId === storeItemId)?.image ?? "";
|
||||
@@ -0,0 +1,105 @@
|
||||
// The server's clock, the frame loop and eased numbers (display only).
|
||||
//
|
||||
// - now(): the server's clock in unix ms (its state.now plus the time since the response).
|
||||
// - edge: a signal bumped when a drill's end passes (scheduled with a timer for the next
|
||||
// one), so readiness-dependent computeds re-run then and not every frame.
|
||||
// - The frame loop runs tickers (countdown texts, eased numbers) registered by components;
|
||||
// they write textContent directly, so no signal changes per frame.
|
||||
// - Eased numbers (like client/modules/tween_numbers.lua): a value keyed by name ("credits",
|
||||
// "res:Sollux") that moves from what is shown to its new value over DURATION instead of
|
||||
// snapping, whether the change came from a prediction or the server correcting one.
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
|
||||
let offset = 0; // server clock minus ours
|
||||
export const now = () => Date.now() + offset;
|
||||
export function syncClock(serverNow, receivedAt) {
|
||||
offset = serverNow - receivedAt;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- edges
|
||||
|
||||
export const edge = signal(0);
|
||||
// When the last edge passed (performance.now()).
|
||||
export let lastEdge = -Infinity;
|
||||
let edgeTimer = 0;
|
||||
let edgeAt = Infinity;
|
||||
|
||||
// Wake at the soonest of these ends (unix ms, server clock).
|
||||
export function armEdge(ends) {
|
||||
const t = now();
|
||||
let next = Infinity;
|
||||
for (const e of ends) if (e > t && e < next) next = e;
|
||||
if (next === edgeAt) return;
|
||||
clearTimeout(edgeTimer);
|
||||
edgeAt = next;
|
||||
if (next === Infinity) return;
|
||||
edgeTimer = setTimeout(() => {
|
||||
edgeAt = Infinity;
|
||||
lastEdge = performance.now();
|
||||
edge.value++;
|
||||
}, Math.max(0, next - t) + 1);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- frame loop
|
||||
|
||||
const tickers = new Set();
|
||||
let frame = 0;
|
||||
|
||||
export function addTicker(fn) {
|
||||
tickers.add(fn);
|
||||
fn(performance.now());
|
||||
if (!frame) frame = requestAnimationFrame(loop);
|
||||
return () => tickers.delete(fn);
|
||||
}
|
||||
|
||||
function loop(t) {
|
||||
for (const fn of tickers) fn(t);
|
||||
frame = tickers.size ? requestAnimationFrame(loop) : 0;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- eased numbers
|
||||
|
||||
export const DURATION = 420;
|
||||
const ease = (k) => 1 - Math.pow(1 - k, 3); // out cubic
|
||||
const vals = new Map(); // key -> {shown, from, to, t0, hold}
|
||||
|
||||
// The value to show for key now, given its true value (which may have just changed).
|
||||
export function eased(key, truth, t = performance.now()) {
|
||||
let e = vals.get(key);
|
||||
if (!e) {
|
||||
e = { shown: truth, from: truth, to: truth, t0: 0, hold: false };
|
||||
vals.set(key, e);
|
||||
return truth;
|
||||
}
|
||||
if (e.hold) return e.shown;
|
||||
if (e.to !== truth) {
|
||||
e.from = e.shown;
|
||||
e.to = truth;
|
||||
e.t0 = t;
|
||||
}
|
||||
const k = Math.min(1, (t - e.t0) / DURATION);
|
||||
e.shown = k >= 1 ? e.to : e.from + (e.to - e.from) * ease(k);
|
||||
return e.shown;
|
||||
}
|
||||
|
||||
export const moving = (key) => {
|
||||
const e = vals.get(key);
|
||||
return !!e && (e.hold || e.shown !== e.to);
|
||||
};
|
||||
|
||||
// Keep showing key's current value until release (a claim's resources wait for their
|
||||
// particles to land in the wallet).
|
||||
export function hold(key) {
|
||||
const e = vals.get(key);
|
||||
if (e) e.hold = true;
|
||||
}
|
||||
|
||||
export function release(key) {
|
||||
const e = vals.get(key);
|
||||
if (!e || !e.hold) return;
|
||||
e.hold = false;
|
||||
e.from = e.shown;
|
||||
e.t0 = performance.now();
|
||||
e.to = NaN; // restart from what is shown towards the truth on the next frame
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// The confirm dialog: the classic client's markup (admin.html "confirm-dialog"), opened and
|
||||
// closed by its ui.js (closing animation, Escape, backdrop) with its sounds.
|
||||
|
||||
import { useRef, useLayoutEffect } from "preact/hooks";
|
||||
import { ask, wireDialog } from "/static/js/ui.js";
|
||||
import * as sfx from "/static/js/sfx.js";
|
||||
|
||||
let dialog = null;
|
||||
|
||||
export function ConfirmDialog() {
|
||||
const ref = useRef(null);
|
||||
useLayoutEffect(() => {
|
||||
dialog = ref.current;
|
||||
wireDialog(dialog, { onClose: (value) => sfx.play(value === "ok" ? "confirm" : "close") });
|
||||
}, []);
|
||||
return (
|
||||
<dialog ref={ref} id="confirm" class="dialog frame" aria-labelledby="confirm-title">
|
||||
<form method="dialog">
|
||||
<h2 id="confirm-title" class="dialog-title">
|
||||
Confirm
|
||||
</h2>
|
||||
<p class="dialog-message" />
|
||||
<div class="dialog-actions">
|
||||
<button value="cancel" class="btn">
|
||||
Cancel
|
||||
</button>
|
||||
<button value="ok" class="btn btn-primary" autofocus>
|
||||
Confirm
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// Asks the API's confirm ({title, text, ok, danger}); resolves true on OK.
|
||||
export function confirm(c) {
|
||||
if (!dialog) return Promise.resolve(false);
|
||||
sfx.play("open");
|
||||
return ask(dialog, { message: c.text, title: c.title, ok: c.ok, danger: c.danger });
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// FLIP for rows that move: children with data-key slide from where they were to where a
|
||||
// render put them (transform only, Web Animations API). New children don't move.
|
||||
// Positions are relative to the container, so scrolling or the container moving doesn't
|
||||
// count as a move.
|
||||
|
||||
import { useRef, useLayoutEffect } from "preact/hooks";
|
||||
|
||||
export function useFlip(duration = 260) {
|
||||
const ref = useRef(null);
|
||||
const last = useRef(new Map());
|
||||
useLayoutEffect(() => {
|
||||
const box = ref.current;
|
||||
if (!box) return;
|
||||
const next = new Map();
|
||||
const b = box.getBoundingClientRect();
|
||||
for (const el of box.querySelectorAll(":scope > [data-key]")) {
|
||||
const e = el.getBoundingClientRect();
|
||||
const r = { left: e.left - b.left, top: e.top - b.top };
|
||||
next.set(el.dataset.key, r);
|
||||
const was = last.current.get(el.dataset.key);
|
||||
if (!was) continue;
|
||||
const dx = was.left - r.left;
|
||||
const dy = was.top - r.top;
|
||||
if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) continue;
|
||||
el.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: "none" }], {
|
||||
duration,
|
||||
easing: "cubic-bezier(.2,.8,.3,1)",
|
||||
composite: "add",
|
||||
});
|
||||
}
|
||||
last.current = next;
|
||||
});
|
||||
return ref;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// The web's formats (views.go, api.md "Texts").
|
||||
|
||||
export const currency = "₥";
|
||||
|
||||
// formatMoney in views.go: thousands commas, up to 2 decimals.
|
||||
export function money(n) {
|
||||
const v = Math.round(Math.abs(n) * 100) / 100;
|
||||
const [whole, frac] = v.toFixed(2).split(".");
|
||||
const f = frac.replace(/0+$/, "");
|
||||
return (n < 0 && v !== 0 ? "-" : "") + whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (f ? "." + f : "");
|
||||
}
|
||||
|
||||
export const cur = (n) => currency + money(n);
|
||||
|
||||
// money with a fixed number of decimals (a number mid-count keeps its width).
|
||||
export function fixed(n, digits) {
|
||||
const v = Math.abs(n).toFixed(digits);
|
||||
const [whole, frac] = v.split(".");
|
||||
return (n < 0 && Number(v) !== 0 ? "-" : "") + whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (frac ? "." + frac : "");
|
||||
}
|
||||
|
||||
export const decimals = (n) => (money(n).split(".")[1] ?? "").length;
|
||||
|
||||
// Countdowns: m:ss, h:mm:ss.
|
||||
export function left(ms) {
|
||||
const total = Math.ceil(Math.max(0, ms) / 1000);
|
||||
const h = Math.floor(total / 3600);
|
||||
const m = Math.floor((total % 3600) / 60);
|
||||
const s = String(total % 60).padStart(2, "0");
|
||||
return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${s}` : `${m}:${s}`;
|
||||
}
|
||||
|
||||
// Cycles: 3s, 2m, 2m 30s.
|
||||
export function secs(n) {
|
||||
n = Math.round(n);
|
||||
if (n < 60) return `${n}s`;
|
||||
return n % 60 === 0 ? `${n / 60}m` : `${Math.floor(n / 60)}m ${n % 60}s`;
|
||||
}
|
||||
|
||||
export const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
||||
|
||||
// A moon thumbnail's hue from its id (FNV-1a, like views.go "planet").
|
||||
export function hue(id) {
|
||||
let h = 0x811c9dc5;
|
||||
for (const b of new TextEncoder().encode(id)) {
|
||||
h ^= b;
|
||||
h = Math.imul(h, 0x01000193) >>> 0;
|
||||
}
|
||||
return h % 360;
|
||||
}
|
||||
|
||||
// The tool's model code, the last word of its name ("PD-1").
|
||||
export const code = (name) => name?.trim().split(/\s+/).pop() || "Tool";
|
||||
|
||||
// A row's drills, compactly ("PD-1 T1", "PD-1 ×3", "PD-1 ×3 +1"), like drillLabel in views.go.
|
||||
export function drillLabel(drills, toolOf) {
|
||||
if (!drills.length) return "";
|
||||
const codeOf = (d) => toolOf(d.toolId)?.code ?? "Tool";
|
||||
if (drills.length === 1) return `${codeOf(drills[0])} T${toolOf(drills[0].toolId)?.tier ?? 0}`;
|
||||
const count = new Map();
|
||||
let top = codeOf(drills[0]);
|
||||
for (const d of drills) {
|
||||
const c = codeOf(d);
|
||||
count.set(c, (count.get(c) ?? 0) + 1);
|
||||
if (count.get(c) > count.get(top)) top = c;
|
||||
}
|
||||
const rest = drills.length - count.get(top);
|
||||
return `${top} ×${count.get(top)}${rest > 0 ? ` +${rest}` : ""}`;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Effects for actions, played at the click from the predicted change (the server's answer
|
||||
// only corrects the numbers). The particles, floating numbers and sounds are the classic
|
||||
// client's (web/static/js/fx.js, sfx.js).
|
||||
|
||||
import { hooks } from "./session.js";
|
||||
import { hold, release } from "./clock.js";
|
||||
import { burst, floatText, stream, mark, centerOf, formatMoney } from "/static/js/fx.js";
|
||||
import * as sfx from "/static/js/sfx.js";
|
||||
|
||||
const token = (name, fallback) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback;
|
||||
const CYAN = () => token("--cyan", "#5fd4ff");
|
||||
const CYAN_HI = () => token("--cyan-hi", "#b3ecff");
|
||||
const GOLD = () => token("--ready", "#ffd166");
|
||||
const GOLD_HI = () => token("--ready-hi", "#fff1c2");
|
||||
|
||||
const amounts = (st) => new Map((st?.resources ?? []).map((r) => [r.name, r.amount]));
|
||||
const colorOf = (st, name) => st?.catalog?.resources?.find((r) => r.name === name)?.color ?? CYAN();
|
||||
|
||||
hooks.onAction = (kind, prev, next, at) => {
|
||||
const from = at ?? centerOf(document.getElementById("main"));
|
||||
if (kind === "claim") {
|
||||
const before = amounts(prev);
|
||||
const gains = [];
|
||||
for (const [name, v] of amounts(next)) {
|
||||
const d = v - (before.get(name) ?? 0);
|
||||
if (d > 0) gains.push({ name, d, color: colorOf(next, name) });
|
||||
}
|
||||
if (!gains.length) return;
|
||||
sfx.claim();
|
||||
burst(from.x, from.y, gains.map((g) => g.color), 46);
|
||||
gains.forEach((g, i) => {
|
||||
const key = `res:${g.name}`;
|
||||
hold(key);
|
||||
floatText(`+${formatMoney(g.d)} ${g.name}`, from.x, from.y - 10 - i * 30, g.color, i * 90);
|
||||
const chip = document.querySelector(`[data-chip="${CSS.escape(g.name)}"]`);
|
||||
const to = centerOf(chip);
|
||||
stream(from, to, g.color, 14, 120 + i * 90, () => {
|
||||
release(key);
|
||||
sfx.arrive(i);
|
||||
const num = chip?.querySelector(".num");
|
||||
if (num) mark(num, "fx-gain");
|
||||
burst(to.x, to.y, [g.color], 14, 0.5);
|
||||
});
|
||||
});
|
||||
// Claim and redeploy: the new drills too.
|
||||
flashNewDrills(prev, next);
|
||||
return;
|
||||
}
|
||||
if (kind === "stake" || kind === "redrill") {
|
||||
sfx.play("deploy");
|
||||
burst(from.x, from.y, [CYAN(), CYAN_HI()], 26);
|
||||
flashNewDrills(prev, next);
|
||||
return;
|
||||
}
|
||||
// A moon sold (answered, not predicted): a gold ring where it was offered, the credits
|
||||
// counting up in the wallet.
|
||||
if (kind === "sell-moon") {
|
||||
sfx.play("shimmer");
|
||||
burst(from.x, from.y, [GOLD(), GOLD_HI(), CYAN_HI()], 60, 1.2);
|
||||
const credits = (next?.credits ?? 0) - (prev?.credits ?? 0);
|
||||
if (credits > 0) {
|
||||
sfx.cash(credits);
|
||||
floatText(`+₥${formatMoney(credits)}`, from.x, from.y - 10, GOLD());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// What only the server knows: a claim that mined a moon out (its entry leaves for the
|
||||
// Past tab).
|
||||
hooks.onAnswer = (kind, data) => {
|
||||
if (!data?.fx?.finished?.length) return;
|
||||
sfx.minedOut(450);
|
||||
requestAnimationFrame(() => mark(document.querySelector("#moonlist [data-past-tab]"), "fx-past"));
|
||||
};
|
||||
|
||||
// Following a link (moon, well, tab, page): the classic client's relay click.
|
||||
hooks.onNavigate = () => sfx.play("nav");
|
||||
|
||||
// Drill lines for tools that weren't mining before light up (after the render).
|
||||
function flashNewDrills(prev, next) {
|
||||
const was = new Set((prev?.stakes ?? []).map((s) => s.toolId));
|
||||
const added = (next?.stakes ?? []).filter((s) => !was.has(s.toolId)).map((s) => s.toolId);
|
||||
if (!added.length) return;
|
||||
requestAnimationFrame(() => {
|
||||
for (const id of added) for (const el of document.querySelectorAll(`[data-tool="${CSS.escape(id)}"]`)) mark(el, "fx-new");
|
||||
});
|
||||
}
|
||||
|
||||
hooks.onError = (at) => {
|
||||
sfx.play("error");
|
||||
const el = at?.el?.isConnected ? at.el : at && document.elementFromPoint(at.x, at.y)?.closest(".btn");
|
||||
if (el) mark(el, "fx-shake");
|
||||
};
|
||||
@@ -0,0 +1,95 @@
|
||||
// Header: section tabs (Moons here, the rest open the classic client), Claim all, the
|
||||
// wallet with eased counts, sound and theme toggles.
|
||||
|
||||
import { useComputed } from "@preact/signals";
|
||||
import { live, act } from "./session.js";
|
||||
import { Num, Countdown, Dot } from "./ui.jsx";
|
||||
import { colorOf } from "./catalog.js";
|
||||
import { ReadyButton } from "./buttons.jsx";
|
||||
|
||||
const TABS = [
|
||||
["equipment", "Equipment"],
|
||||
["store", "Store"],
|
||||
["market", "Market"],
|
||||
["refinery", "Refinery"],
|
||||
["advisors", "Advisors"],
|
||||
["leaderboard", "Leaderboard"],
|
||||
["help", "Help"],
|
||||
];
|
||||
|
||||
export function Header() {
|
||||
const st = live.value;
|
||||
const credits = useComputed(() => live.value?.credits ?? 0);
|
||||
return (
|
||||
<header id="top" class="top">
|
||||
<span class="brand">
|
||||
<b>MOON MINERS</b>
|
||||
<span class="cap">Extraction command</span>
|
||||
</span>
|
||||
<nav aria-label="Main" class="nav">
|
||||
<a id="tab-moons" href="/app" aria-current="page">
|
||||
Moons{" "}
|
||||
<span class="badge" hidden={!st.ready}>
|
||||
{st.ready}
|
||||
</span>
|
||||
</a>
|
||||
{TABS.filter(([s]) => st.unlocked[s]).map(([s, label]) => (
|
||||
<a key={s} href={`/?s=${s}`} title="Opens the classic client">
|
||||
{label}
|
||||
</a>
|
||||
))}
|
||||
{st.unlocked["claim-all"] && (st.ready > 0 || st.nextEnd) && <ClaimAll ready={st.ready} nextEnd={st.nextEnd} />}
|
||||
</nav>
|
||||
<div class="wallet">
|
||||
{st.resources.map((r) => (
|
||||
<Chip key={r.name} name={r.name} />
|
||||
))}
|
||||
<Num class="balance frame num" value={credits} k="credits" prefix="₥" />
|
||||
</div>
|
||||
<div class="top-ctl">
|
||||
<button type="button" class="top-btn sfx-toggle" data-sfx-toggle aria-label="Mute sound" aria-pressed="false" title="Sound on">
|
||||
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<path d="M4 9.5h3.5L12 5.5v13l-4.5-4H4z" />
|
||||
<path class="sfx-on" d="M15.5 9a4 4 0 0 1 0 6M18 6.5a7.5 7.5 0 0 1 0 11" />
|
||||
<path class="sfx-off" d="M16 9.5l5 5M21 9.5l-5 5" />
|
||||
</svg>
|
||||
</button>
|
||||
<button type="button" class="top-btn theme-toggle" data-theme-toggle aria-label="Switch light or dark theme" title="Light / dark theme">
|
||||
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<g class="theme-sun">
|
||||
<circle cx="12" cy="12" r="4" />
|
||||
<path d="M12 2.5v2.5M12 19v2.5M2.5 12H5M19 12h2.5M5.3 5.3l1.8 1.8M16.9 16.9l1.8 1.8M5.3 18.7l1.8-1.8M16.9 7.1l1.8-1.8" />
|
||||
</g>
|
||||
<path class="theme-moon" d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z" />
|
||||
</svg>
|
||||
</button>
|
||||
<a href="/" class="top-btn" title="The htmx client">
|
||||
Classic
|
||||
</a>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
function Chip({ name }) {
|
||||
const amount = useComputed(() => live.value?.resources.find((r) => r.name === name)?.amount ?? 0);
|
||||
return (
|
||||
<span class="chip" title={name} data-chip={name}>
|
||||
<Dot color={colorOf(name)} />
|
||||
<Num class="num" value={amount} k={`res:${name}`} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ClaimAll({ ready, nextEnd }) {
|
||||
return (
|
||||
<ReadyButton class="btn btn-primary claim-all" ready={ready > 0} onClick={(e) => act("claim", {}, e.currentTarget)}>
|
||||
Claim all{ready > 0 ? "" : " "}
|
||||
{ready > 0 ? null : <Countdown end={nextEnd} />}
|
||||
<span class="badge" hidden={!ready}>
|
||||
{ready}
|
||||
</span>
|
||||
</ReadyButton>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "preact",
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"preact": [
|
||||
"vendor/preact/preact.mjs"
|
||||
],
|
||||
"preact/hooks": [
|
||||
"vendor/preact/hooks.mjs"
|
||||
],
|
||||
"preact/jsx-runtime": [
|
||||
"vendor/preact/jsxRuntime.mjs"
|
||||
],
|
||||
"@preact/signals": [
|
||||
"vendor/signals/signals.mjs"
|
||||
],
|
||||
"@preact/signals-core": [
|
||||
"vendor/signals/signals-core.mjs"
|
||||
],
|
||||
"three": [
|
||||
"../static/vendor/three/three.module.min.js"
|
||||
],
|
||||
"three/addons/*": [
|
||||
"../static/vendor/three/addons/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// The Preact client at /app: the Moons slice of the game (header and wallet, moon list,
|
||||
// wells table, well panel, viewport, toasts) on the JSON API (api.md), predicting every
|
||||
// core-loop click locally like the Defold client. Other sections open the classic client.
|
||||
|
||||
import { render } from "preact";
|
||||
import { live, boot, toasts, start } from "./session.js";
|
||||
import { Header } from "./header.jsx";
|
||||
import { MoonList, MoonsSection } from "./moons.jsx";
|
||||
import { Side } from "./side.jsx";
|
||||
import { Viewport } from "./viewport.jsx";
|
||||
import { ConfirmDialog } from "./dialog.jsx";
|
||||
import "./fx.js";
|
||||
import "./preact.css";
|
||||
|
||||
function App() {
|
||||
const st = live.value;
|
||||
if (!st) {
|
||||
return (
|
||||
<div class="splash">
|
||||
<div>
|
||||
<h1>Moon Miners</h1>
|
||||
<p>{boot}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const aside = !!st.moon;
|
||||
return (
|
||||
<>
|
||||
<div class="app">
|
||||
<Header />
|
||||
<div class="app-body">
|
||||
<MoonList />
|
||||
<main id="main" class="main frame">
|
||||
<MoonsSection />
|
||||
</main>
|
||||
<aside id="aside" class="aside frame" hidden={!aside}>
|
||||
<Viewport />
|
||||
<section id="side" class={`side${st.well && (st.moon?.wells.find((w) => w.id === st.well.id)?.supply ?? 1) <= 0 ? " depleted" : ""}`}>
|
||||
<Side />
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
<Toasts />
|
||||
<ConfirmDialog />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Toasts() {
|
||||
const list = toasts.value;
|
||||
return (
|
||||
<div id="toasts" class="toasts" aria-live="polite">
|
||||
{list.map((t) => (
|
||||
<div key={t.id} class={`toast${t.error ? " toast-error" : ""}${t.out ? " toast-out" : ""}`} data-fx={t.kind}>
|
||||
{t.message}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render(<App />, document.getElementById("root"));
|
||||
start();
|
||||
// sfx.js syncs its mute button on this event (the classic client's htmx fires it).
|
||||
requestAnimationFrame(() => document.dispatchEvent(new Event("htmx:load")));
|
||||
@@ -0,0 +1,14 @@
|
||||
// A component that renders once (no preact/compat): its props never change it.
|
||||
|
||||
import { Component, h } from "preact";
|
||||
|
||||
export function memo(render) {
|
||||
return class Once extends Component {
|
||||
shouldComponentUpdate() {
|
||||
return false;
|
||||
}
|
||||
render(props) {
|
||||
return h(render, props);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
// The moon list (active and past moons, a search box) and the Moons section (wells table
|
||||
// with drill bars, claim and redrill, multi-well drills, the moon's resale; a past moon's
|
||||
// haul).
|
||||
|
||||
import { signal } from "@preact/signals";
|
||||
import { live, act, navigate, viewURL, hooks, busy } from "./session.js";
|
||||
import { Countdown, DrillBar, Dot, Planet, RatingChip, SupplyBar, Num } from "./ui.jsx";
|
||||
import { ReadyButton } from "./buttons.jsx";
|
||||
import { confirm } from "./dialog.jsx";
|
||||
import { colorOf, toolOf } from "./catalog.js";
|
||||
import { money, cur, plural, drillLabel } from "./format.js";
|
||||
import { useFlip } from "./flip.js";
|
||||
import { now } from "./clock.js";
|
||||
import { isReady, find } from "./predict.js";
|
||||
|
||||
// A link to a view that navigates in place.
|
||||
export function ViewLink({ to, children, ...rest }) {
|
||||
return (
|
||||
<a
|
||||
href={viewURL(to)}
|
||||
onClick={(e) => {
|
||||
if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
|
||||
e.preventDefault();
|
||||
hooks.onNavigate();
|
||||
navigate(to);
|
||||
}}
|
||||
{...rest}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
// The search box's text: it stays while the list changes under it.
|
||||
const query = signal("");
|
||||
const onFind = (e) => (query.value = e.currentTarget.value);
|
||||
|
||||
const minedTotal = (m) => (m.mined ?? []).reduce((sum, a) => sum + a.amount, 0);
|
||||
|
||||
export function MoonList() {
|
||||
const st = live.value;
|
||||
const ref = useFlip();
|
||||
const past = !!st.view.past;
|
||||
const store = st.unlocked.store;
|
||||
const total = st.pastPage?.total ?? 0;
|
||||
const list = past ? st.past ?? [] : st.moons;
|
||||
const q = query.value.trim().toLowerCase();
|
||||
const found = q ? list.filter((m) => m.name.toLowerCase().includes(q)) : list;
|
||||
const page = st.pastPage ?? { page: 1, pages: 1 };
|
||||
const activeMoon = st.moons.find((m) => m.selected)?.id ?? "";
|
||||
return (
|
||||
<section id="moonlist" class="moonlist frame" aria-label="Your moons" ref={ref}>
|
||||
{store && (st.moons.length > 0 || total > 0) && (
|
||||
<nav class="tabs list-tabs" aria-label="Moon list">
|
||||
<ViewLink to={{ section: "moons", moon: activeMoon }} aria-current={past ? undefined : "page"}>
|
||||
Active <span class="muted num">{st.moons.length}</span>
|
||||
</ViewLink>
|
||||
{total > 0 ? (
|
||||
<ViewLink to={{ section: "moons", past: true, page: 1 }} aria-current={past ? "page" : undefined} data-past-tab>
|
||||
Past <span class="muted num">{total}</span>
|
||||
</ViewLink>
|
||||
) : (
|
||||
<a aria-disabled="true" title="Moons you mine out go here" data-past-tab>
|
||||
Past <span class="muted num">0</span>
|
||||
</a>
|
||||
)}
|
||||
</nav>
|
||||
)}
|
||||
{store && list.length > 0 && (
|
||||
<>
|
||||
<label for="find" class="label">
|
||||
Find a moon
|
||||
</label>
|
||||
<input id="find" type="search" placeholder="Name" class="input" value={query} onInput={onFind} />
|
||||
</>
|
||||
)}
|
||||
{past ? (
|
||||
<>
|
||||
{found.map((m) => (
|
||||
<ViewLink
|
||||
key={m.id}
|
||||
to={{ section: "moons", moon: m.id, past: true, page: page.page }}
|
||||
id={`moon-${m.id}`}
|
||||
data-key={m.id}
|
||||
class="moon past"
|
||||
aria-current={m.selected && st.view.section === "moons" ? "true" : undefined}
|
||||
>
|
||||
<Planet id={m.id} />
|
||||
<span class="grow">
|
||||
<b>{m.name}</b>
|
||||
<RatingChip r={m.rating} />
|
||||
<br />
|
||||
<span class="muted small num">
|
||||
Mined {money(minedTotal(m))}
|
||||
{m.finishedOn && ` · ${m.finishedOn}`}
|
||||
</span>
|
||||
</span>
|
||||
</ViewLink>
|
||||
))}
|
||||
{page.pages > 1 && (
|
||||
<nav class="past-paging small" aria-label="Past moon pages">
|
||||
{page.page > 1 ? (
|
||||
<ViewLink to={{ section: "moons", past: true, page: page.page - 1 }} class="btn btn-sm" rel="prev">
|
||||
‹ Newer
|
||||
</ViewLink>
|
||||
) : (
|
||||
<span class="btn btn-sm" aria-disabled="true">
|
||||
‹ Newer
|
||||
</span>
|
||||
)}
|
||||
<span class="muted num grow">
|
||||
{page.page} / {page.pages}
|
||||
</span>
|
||||
{page.page < page.pages ? (
|
||||
<ViewLink to={{ section: "moons", past: true, page: page.page + 1 }} class="btn btn-sm" rel="next">
|
||||
Older ›
|
||||
</ViewLink>
|
||||
) : (
|
||||
<span class="btn btn-sm" aria-disabled="true">
|
||||
Older ›
|
||||
</span>
|
||||
)}
|
||||
</nav>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{found.map((m) => {
|
||||
const dry = m.wells.length > 0 && m.wells.every((w) => w.supply <= 0);
|
||||
return (
|
||||
<ViewLink
|
||||
key={m.id}
|
||||
to={{ section: "moons", moon: m.id }}
|
||||
id={`moon-${m.id}`}
|
||||
data-key={m.id}
|
||||
class={`moon${dry ? " depleted" : ""}`}
|
||||
aria-current={m.selected && st.view.section === "moons" ? "true" : undefined}
|
||||
>
|
||||
<Planet id={m.id} />
|
||||
<span class="grow">
|
||||
<b>{m.name}</b>
|
||||
<RatingChip r={m.rating} />
|
||||
<br />
|
||||
<span class="muted small">
|
||||
{m.over && <i class="warn-dot" title="A well here has more drills than supply" />}
|
||||
{m.drills ? plural(m.drills, "drill") : dry ? "Tapped out" : "Idle"}
|
||||
</span>
|
||||
</span>
|
||||
<span class="badge" title={plural(m.ready, "drill") + " ready"} hidden={!m.ready}>
|
||||
{m.ready}
|
||||
</span>
|
||||
</ViewLink>
|
||||
);
|
||||
})}
|
||||
{!st.moons.length && total > 0 && <p class="muted small">Every moon you own is mined out.</p>}
|
||||
</>
|
||||
)}
|
||||
{st.unlocked["new-moon"] && (
|
||||
<a class="btn btn-dashed new-moon" href="/?s=new-moon" title="Opens the classic client">
|
||||
+ New moon · <span class="num accent">₥{money(st.moonPrice)}</span>
|
||||
</a>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function MoonsSection() {
|
||||
const st = live.value;
|
||||
const moon = st.moon;
|
||||
if (!moon) {
|
||||
const r = st.rules;
|
||||
return (
|
||||
<div class="empty">
|
||||
<h1>Claim your first moon</h1>
|
||||
<p class="muted measure">
|
||||
A moon comes with {r.wellsMin === r.wellsMax ? r.wellsMin : `${r.wellsMin}–${r.wellsMax}`} resource wells. Deploy mining tools on its
|
||||
wells, claim what they dig up, and sell it in the market.
|
||||
</p>
|
||||
<a class="btn btn-primary" href="/?s=new-moon" title="Opens the classic client">
|
||||
Scan for a moon · <span class="num">{cur(st.moonPrice)}</span>
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (moon.finished) return <PastMoon st={st} moon={moon} />;
|
||||
const max = st.rules.maxSupply;
|
||||
return (
|
||||
<>
|
||||
<div class="heading">
|
||||
<div class="grow">
|
||||
<div class="num muted small">{moon.id}</div>
|
||||
<h1>{moon.name}</h1>
|
||||
{(moon.kind && moon.kind !== moon.name) || moon.rating ? (
|
||||
<p class="cap muted small">
|
||||
{moon.kind && moon.kind !== moon.name && `${moon.kind} class`}
|
||||
<RatingChip r={moon.rating} />
|
||||
</p>
|
||||
) : null}
|
||||
<p class="muted measure">{moon.description || " "}</p>
|
||||
</div>
|
||||
{(moon.ready > 0 || moon.nextEnd) && (
|
||||
<ReadyButton class="btn btn-primary" ready={moon.ready > 0} onClick={(e) => act("claim", { "claim-moon": moon.id }, e.currentTarget)}>
|
||||
{moon.ready > 0 ? `Claim ${plural(moon.ready, "drill")}` : <>Claim <Countdown end={moon.nextEnd} /></>}
|
||||
</ReadyButton>
|
||||
)}
|
||||
</div>
|
||||
<div class="table-box">
|
||||
<table class="table wells-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Well</th>
|
||||
<th class="w-supply">Supply left</th>
|
||||
<th class="col-drill">Drill</th>
|
||||
<th class="right">Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{moon.wells.map((w) => (
|
||||
<WellRow key={w.id} st={st} moon={moon} w={w} max={max} />
|
||||
))}
|
||||
{/* Drills that mine several wells (reach) are claimed together, from the moon. */}
|
||||
{moon.wide?.drills?.length > 0 && (
|
||||
<tr class="wide-row">
|
||||
<td>
|
||||
<span class="cap small">Multi-well</span>
|
||||
</td>
|
||||
<td class="cell-wrap">
|
||||
<span class="num muted">{money(moon.wide.cap)}</span> <span class="muted small">left on the moon</span>
|
||||
</td>
|
||||
<td class="col-drill">
|
||||
<DrillCell st={st} drills={moon.wide.drills} />
|
||||
</td>
|
||||
<td class="right">
|
||||
<div class="row-actions">
|
||||
<WideClaim moon={moon} small />
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{st.unlocked.store && <MoonSale moon={moon} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// A finished moon, read-only: what it gave (its entry in the past list has the haul).
|
||||
function PastMoon({ st, moon }) {
|
||||
const entry = find(st.past, moon.id);
|
||||
const mined = entry?.mined ?? [];
|
||||
return (
|
||||
<>
|
||||
<div class="heading">
|
||||
<div class="grow">
|
||||
<div class="num muted small">{moon.id}</div>
|
||||
<h1>{moon.name}</h1>
|
||||
<p class="tapped">
|
||||
Mined out{moon.finishedOn && ` · ${moon.finishedOn}`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="table-box past-moon">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Resource</th>
|
||||
<th class="right">Mined</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{mined.map((a) => (
|
||||
<tr key={a.name}>
|
||||
<td>
|
||||
<Dot color={colorOf(a.name)} />
|
||||
{a.name}
|
||||
</td>
|
||||
<td class="right num">{money(a.amount)}</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr class="total">
|
||||
<td>Total</td>
|
||||
<td class="right num">{money(minedTotal({ mined }))}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p class="muted small measure">Its wells are empty. It still counts toward the price of your next moon.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Claim for the moon's multi-well drills (claim-wide: the server splits what they get
|
||||
// between their wells, so it isn't predicted; the button spins until it answers).
|
||||
export function WideClaim({ moon, small = false }) {
|
||||
const wide = moon.wide;
|
||||
if (!wide || !(wide.ready > 0 || wide.nextEnd)) return null;
|
||||
return (
|
||||
<ReadyButton
|
||||
class={`btn btn-primary${small ? " btn-sm" : ""}`}
|
||||
ready={wide.ready > 0}
|
||||
busyKey="claim-wide"
|
||||
onClick={(e) => act("claim", { "claim-wide": moon.id }, e.currentTarget, "claim-wide")}
|
||||
>
|
||||
Claim {wide.ready > 0 ? <Num class="num" n={wide.readyAmount} k={`wide:${moon.id}`} /> : <Countdown end={wide.nextEnd} />}
|
||||
</ReadyButton>
|
||||
);
|
||||
}
|
||||
|
||||
// Selling the moon back: the offer against a new moon's price, and what's left in its
|
||||
// wells. A just-bought moon becomes sellable at holdEnd (the session wakes then).
|
||||
function MoonSale({ moon }) {
|
||||
const sale = moon.sale;
|
||||
if (!sale) return null;
|
||||
const held = sale.why === "hold" && sale.holdEnd && now() < sale.holdEnd;
|
||||
const can = sale.canSell || (sale.why === "hold" && !held);
|
||||
const profit = sale.delta > 0;
|
||||
const spinning = !!busy.value["sell-moon"];
|
||||
const sell = (e) => {
|
||||
// The button sits in the summary: no toggling the details.
|
||||
e.preventDefault();
|
||||
const el = e.currentTarget;
|
||||
confirm(sale.confirm).then((yes) => yes && act("sell-moon", { "sell-moon": moon.id }, el, "sell-moon"));
|
||||
};
|
||||
return (
|
||||
<details class="resale">
|
||||
<summary>
|
||||
<span class="grow">
|
||||
Sell moon <span class="muted">· offer</span> <span class="num">{cur(sale.total)}</span>{" "}
|
||||
<span class={`num resale-delta ${profit ? "up" : "down"}`}>{profit ? `+${cur(sale.delta)} profit` : `−${cur(-sale.delta)} vs a new moon`}</span>
|
||||
</span>
|
||||
<button type="button" class={`btn btn-sm btn-danger${spinning ? " htmx-request" : ""}`} disabled={!can || spinning} title={can ? undefined : sale.whyText} onClick={sell}>
|
||||
Sell moon
|
||||
</button>
|
||||
</summary>
|
||||
<div class="resale-body">
|
||||
<p class="muted small">
|
||||
What's left in its wells at today's prices, ×{sale.factor}
|
||||
{sale.capped && `, capped at ${cur(sale.total)}`}. A new moon would cost {cur(sale.replace)} after the sale.
|
||||
{sale.ready > 0 && ` ${plural(sale.ready, "finished drill")} claimed first.`}
|
||||
{held && (
|
||||
<>
|
||||
{" "}
|
||||
Sellable in <Countdown end={sale.holdEnd} done="0:00" />.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Well</th>
|
||||
<th class="right">Left</th>
|
||||
<th class="right">Price</th>
|
||||
<th class="right">Value</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sale.lines.map(({ resource, supply, rate, value: worth }) => (
|
||||
<tr key={resource}>
|
||||
<td>
|
||||
<Dot color={colorOf(resource)} />
|
||||
{resource}
|
||||
</td>
|
||||
<td class="right num">{money(supply)}</td>
|
||||
<td class="right num">{cur(rate)}</td>
|
||||
<td class="right num">{cur(worth)}</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr class="resale-total">
|
||||
<td>Market value</td>
|
||||
<td />
|
||||
<td />
|
||||
<td class="right num">{cur(sale.market)}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
|
||||
// The moon's multi-well drills that mine well w too.
|
||||
export const wideOn = (moon, w) => (moon.wide?.drills ?? []).filter((d) => w.wide?.includes(d.id));
|
||||
|
||||
function WellRow({ st, moon, w, max }) {
|
||||
const dry = w.supply <= 0;
|
||||
const to = { section: "moons", moon: moon.id, well: w.id };
|
||||
const mining = w.drills.length > 0;
|
||||
const drills = [...w.drills, ...wideOn(moon, w)];
|
||||
return (
|
||||
<tr class={`${w.selected ? "selected" : ""}${dry ? " depleted" : ""}`}>
|
||||
<td>
|
||||
<ViewLink to={to} class="row-link">
|
||||
<Dot color={colorOf(w.resource)} />
|
||||
{w.resource}
|
||||
</ViewLink>
|
||||
</td>
|
||||
<td>
|
||||
{dry ? (
|
||||
<span class="tapped">Tapped out</span>
|
||||
) : (
|
||||
<SupplyBar supply={w.supply} demand={w.demand} max={max} color={colorOf(w.resource)} full={w.full} showNum={w.id} />
|
||||
)}
|
||||
</td>
|
||||
<td class="col-drill">
|
||||
{drills.length ? <DrillCell st={st} drills={drills} /> : <span class="muted">Empty</span>}
|
||||
</td>
|
||||
<td class="right">
|
||||
<div class="row-actions">
|
||||
{mining ? (
|
||||
<ReadyButton class="btn btn-primary btn-sm" ready={w.ready > 0} onClick={(e) => act("claim", { "claim-well": w.id }, e.currentTarget)}>
|
||||
Claim {w.ready > 0 ? <Num class="num" n={w.readyAmount} k={`ready:${w.id}`} /> : <Countdown end={w.nextEnd} />}
|
||||
</ReadyButton>
|
||||
) : (
|
||||
w.redrill > 0 &&
|
||||
!dry &&
|
||||
st.unlocked.market && (
|
||||
<button type="button" class="btn btn-sm btn-redrill" onClick={(e) => act("redrill", { "redrill-well": w.id }, e.currentTarget)}>
|
||||
Redrill
|
||||
</button>
|
||||
)
|
||||
)}
|
||||
<ViewLink to={to} class="btn btn-sm">
|
||||
{dry ? "View" : "Manage"}
|
||||
</ViewLink>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
|
||||
const MAX_BARS = 4;
|
||||
|
||||
export function DrillCell({ st, drills }) {
|
||||
const t = now();
|
||||
return (
|
||||
<div class="drill-cell" title={drills.map((d) => d.fate ?? "").join("\n")}>
|
||||
<span class="drill-bars">
|
||||
{drills.slice(0, MAX_BARS).map((d) => (
|
||||
<DrillBar key={d.toolId} start={d.start} end={d.end} state={d.state ?? "ok"} ready={isReady(d, t)} wide={(d.reach ?? 1) > 1} />
|
||||
))}
|
||||
</span>
|
||||
{drills.length > MAX_BARS && <span class="drill-more num">+{drills.length - MAX_BARS}</span>}
|
||||
<span class="drill-label">{drillLabel(drills, (id) => toolOf(st, id))}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/* The Preact client (/app): only what its markup does differently from the classic
|
||||
client's (web/css/app.css, loaded first). Moving things use transform or opacity. */
|
||||
|
||||
/* Drill timer bars: an inner fill scaled by a Web Animation instead of --p widths. */
|
||||
.pa .drill-bar.pa-bar::before {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.pa .drill-bar .pa-fill {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: var(--c);
|
||||
transform-origin: left center;
|
||||
transform: scaleX(0);
|
||||
will-change: transform;
|
||||
}
|
||||
|
||||
.pa .drill-bar.is-none .pa-fill {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.pa .drill-bar.is-ready .pa-fill {
|
||||
box-shadow: 0 0 5px rgb(var(--c-rgb) / calc(0.7 * var(--glow-k)));
|
||||
}
|
||||
|
||||
/* Supply bars: both parts span the bar, clipped to their share. */
|
||||
.pa .bar.pa-split {
|
||||
position: relative;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.pa .bar.pa-split > span {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
transition: clip-path 0.35s cubic-bezier(0.2, 0.8, 0.3, 1);
|
||||
}
|
||||
|
||||
/* Claim buttons breathe while ready and pop in when a drill finishes (the classic CSS
|
||||
matches them by hx-post). */
|
||||
.pa button[data-claim]:not(:disabled) {
|
||||
animation: fx-ready-glow 1.8s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.pa button[data-claim].fx-ready-pop {
|
||||
animation:
|
||||
fx-ready-pop 0.6s cubic-bezier(0.2, 0.9, 0.3, 1.4),
|
||||
fx-ready-glow 1.8s 0.6s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* Wallet numbers pop in place. */
|
||||
.pa .wallet .num,
|
||||
.pa .balance {
|
||||
display: inline-block;
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
// Client-side prediction, ported from the Defold client (client/modules/predict.lua).
|
||||
//
|
||||
// The server still decides. A predictor only reuses numbers the server sent (a stake's
|
||||
// `take`, a tool's `cycleSecs`/`yield`, see api.md "Prediction"); it never invents game
|
||||
// rules. The session keeps the last server state as the base and shows base + every
|
||||
// pending prediction, re-applied in click order whenever a response brings a new base.
|
||||
//
|
||||
// A predictor: fn(st, params, ctx) -> true when it predicted (and changed st), false when
|
||||
// it can't (the button then waits for the server). st is a copy of the shown state, ctx
|
||||
// {now: server ms at the click, seq}. It must be deterministic in (st, params, ctx): it
|
||||
// runs again on every new base, so it reads the time from ctx.now, never the clock.
|
||||
//
|
||||
// One difference from the Lua: readiness is local. A stake counts as ready once its end
|
||||
// has passed on the server's clock (`isReady`), so a Claim pressed at local zero predicts
|
||||
// without waiting for a refetch.
|
||||
|
||||
export const registry = {};
|
||||
// What the client learned from server states (not rules): the well each tool last mined.
|
||||
export const memo = { lastWell: new Map() };
|
||||
|
||||
export const isReady = (s, now) => s.ready || s.end <= now;
|
||||
|
||||
// ---------------------------------------------------------------- state helpers
|
||||
|
||||
const SHARED = new Set(["catalog", "rules"]);
|
||||
|
||||
export function copy(st) {
|
||||
const out = {};
|
||||
for (const k in st) out[k] = SHARED.has(k) ? st[k] : structuredClone(st[k]);
|
||||
return out;
|
||||
}
|
||||
|
||||
export const find = (list, id, key = "id") => (list ?? []).find((x) => x[key] === id);
|
||||
const indexOf = (list, id, key = "id") => (list ?? []).findIndex((x) => x[key] === id);
|
||||
|
||||
// Every well entry with this id: the moon list's and the selected moon's.
|
||||
function wells(st, id) {
|
||||
const out = [];
|
||||
for (const list of [st.moons, st.past]) {
|
||||
for (const moon of list ?? []) {
|
||||
const w = find(moon.wells, id);
|
||||
if (w) out.push(w);
|
||||
}
|
||||
}
|
||||
const w = st.moon && find(st.moon.wells, id);
|
||||
if (w) out.push(w);
|
||||
return out;
|
||||
}
|
||||
|
||||
export const supply = (st, wellId) => wells(st, wellId)[0]?.supply ?? 0;
|
||||
|
||||
function addSupply(st, wellId, delta) {
|
||||
for (const w of wells(st, wellId)) w.supply = Math.max(0, w.supply + delta);
|
||||
}
|
||||
|
||||
// Add delta of a resource or refined item (balance and its market quote).
|
||||
function addItem(st, name, delta) {
|
||||
let e = find(st.resources, name, "name") ?? find(st.refined, name, "name");
|
||||
if (!e) {
|
||||
e = { name, amount: 0 };
|
||||
(st.refined ??= []).push(e);
|
||||
}
|
||||
e.amount = Math.max(0, e.amount + delta);
|
||||
const q = st.market && find(st.market.quotes, name, "item");
|
||||
if (q) {
|
||||
q.balance = e.amount;
|
||||
q.value = q.balance * q.price;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- tools and stakes
|
||||
|
||||
// The tool to deploy for id: it, or an idle copy of it (same store item and tier).
|
||||
function idleCopy(st, id) {
|
||||
const t = find(st.tools, id);
|
||||
if (!t || !t.stakeId) return t;
|
||||
return st.tools.find((x) => !x.stakeId && x.storeItemId === t.storeItemId && x.tier === t.tier);
|
||||
}
|
||||
|
||||
const yieldBoost = (st, resource) => st.rules?.boosts?.yield?.[resource] ?? 1;
|
||||
|
||||
const sameGroup = (g, tool) => g.storeItemId === tool.storeItemId && g.tier === tool.tier;
|
||||
|
||||
// A new stake of tool on well starting at ctx.now. group: the well panel's idle group for
|
||||
// it (cycle and yield already for this well).
|
||||
function addStake(st, tool, moonId, well, ctx, group) {
|
||||
const cycle = group ? group.cycleSecs : tool.cycleSecs;
|
||||
const amount = group ? group.yield : tool.yield * yieldBoost(st, well.resource);
|
||||
let committed = 0;
|
||||
for (const s of st.stakes) if (s.wellId === well.id) committed += s.take ?? 0;
|
||||
const take = Math.max(0, Math.min(amount, supply(st, well.id) - committed));
|
||||
const s = {
|
||||
id: `pred:${ctx.seq}:${tool.id}`,
|
||||
moonId,
|
||||
wellId: well.id,
|
||||
toolId: tool.id,
|
||||
resource: well.resource,
|
||||
amount,
|
||||
reach: tool.reach ?? 1,
|
||||
reachText: "",
|
||||
start: ctx.now,
|
||||
end: ctx.now + cycle * 1000,
|
||||
durationSecs: cycle,
|
||||
ready: false,
|
||||
take,
|
||||
predicted: true,
|
||||
};
|
||||
st.stakes.push(s);
|
||||
tool.stakeId = s.id;
|
||||
// Off the selected well's idle list; what the next one would get there shrinks.
|
||||
if (st.well) {
|
||||
const i = (st.well.idle ?? []).findIndex((g) => sameGroup(g, tool));
|
||||
if (i >= 0) {
|
||||
const g = st.well.idle[i];
|
||||
g.count--;
|
||||
if (g.toolId === tool.id) {
|
||||
const next = st.tools.find((x) => !x.stakeId && sameGroup(g, x));
|
||||
if (next) g.toolId = next.id;
|
||||
}
|
||||
if (g.count <= 0) st.well.idle.splice(i, 1);
|
||||
}
|
||||
if (st.well.id === well.id) {
|
||||
for (const g of st.well.idle ?? []) {
|
||||
g.free = Math.max(0, g.free - take);
|
||||
g.here = Math.min(g.yield, g.free);
|
||||
g.short = g.free < g.yield;
|
||||
}
|
||||
}
|
||||
}
|
||||
// It no longer counts for Redrill on the well it last mined.
|
||||
const last = memo.lastWell.get(tool.id);
|
||||
const w = last && st.moon && find(st.moon.wells, last);
|
||||
if (w && (w.redrill ?? 0) > 0) w.redrill--;
|
||||
return s;
|
||||
}
|
||||
|
||||
// Take a stake off (claimed); its tool becomes idle.
|
||||
function removeStake(st, s) {
|
||||
const i = indexOf(st.stakes, s.id);
|
||||
if (i >= 0) st.stakes.splice(i, 1);
|
||||
const tool = find(st.tools, s.toolId);
|
||||
if (!tool) return;
|
||||
delete tool.stakeId;
|
||||
const w = st.moon && find(st.moon.wells, s.wellId);
|
||||
if (w) w.redrill = (w.redrill ?? 0) + 1;
|
||||
if (st.well?.idle) {
|
||||
const g = st.well.idle.findLast((x) => sameGroup(x, tool));
|
||||
if (g) g.count++;
|
||||
else {
|
||||
const free = supply(st, st.well.id);
|
||||
const y = tool.yield * yieldBoost(st, st.well.resource);
|
||||
st.well.idle.push({
|
||||
toolId: tool.id,
|
||||
storeItemId: tool.storeItemId,
|
||||
name: tool.name,
|
||||
tier: tool.tier,
|
||||
count: 1,
|
||||
cycleSecs: tool.cycleSecs,
|
||||
yield: y,
|
||||
reach: tool.reach,
|
||||
here: Math.min(y, free),
|
||||
free,
|
||||
short: free < y,
|
||||
attachments: tool.attachments ?? [],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Recompute what the server derives from stakes, tools and supplies (counts, the claim
|
||||
// buttons' amounts, next ends), as of server time now. Wide drills (reach > 1) keep the
|
||||
// server's projection (what each gets); only their readiness is local.
|
||||
export function derive(st, now) {
|
||||
let ready = 0;
|
||||
let idle = 0;
|
||||
let nextEnd = null;
|
||||
const perMoon = new Map();
|
||||
for (const s of st.stakes ?? []) {
|
||||
const m = perMoon.get(s.moonId) ?? { drills: 0, ready: 0 };
|
||||
perMoon.set(s.moonId, m);
|
||||
m.drills++;
|
||||
if (isReady(s, now)) {
|
||||
ready++;
|
||||
m.ready++;
|
||||
} else if (nextEnd === null || s.end < nextEnd) nextEnd = s.end;
|
||||
}
|
||||
for (const t of st.tools ?? []) if (!t.stakeId) idle++;
|
||||
st.ready = ready;
|
||||
st.idle = idle;
|
||||
st.nextEnd = nextEnd;
|
||||
for (const moon of st.moons ?? []) {
|
||||
const m = perMoon.get(moon.id) ?? { drills: 0, ready: 0 };
|
||||
moon.drills = m.drills;
|
||||
moon.ready = m.ready;
|
||||
}
|
||||
const moon = st.moon;
|
||||
if (!moon) return st;
|
||||
let mready = 0;
|
||||
let mnext = null;
|
||||
for (const w of moon.wells ?? []) {
|
||||
const old = new Map((w.drills ?? []).map((d) => [d.id, d]));
|
||||
const drills = [];
|
||||
let wready = 0;
|
||||
let amount = 0;
|
||||
let wnext = null;
|
||||
let demand = 0;
|
||||
for (const s of st.stakes ?? []) {
|
||||
if (s.wellId !== w.id || (s.reach ?? 1) > 1) continue;
|
||||
let d = old.get(s.id);
|
||||
if (!d) {
|
||||
d = { ...s, gets: s.take, here: s.take };
|
||||
d.state = s.take <= 0 ? "none" : s.take < s.amount ? "short" : "ok";
|
||||
}
|
||||
drills.push(d);
|
||||
demand += d.here ?? s.take ?? 0;
|
||||
if (isReady(s, now)) {
|
||||
wready++;
|
||||
amount += s.take ?? 0;
|
||||
} else if (wnext === null || s.end < wnext) wnext = s.end;
|
||||
}
|
||||
drills.sort((a, b) => a.start - b.start);
|
||||
w.drills = drills;
|
||||
w.ready = wready;
|
||||
w.readyAmount = amount;
|
||||
w.nextEnd = wnext;
|
||||
w.demand = demand;
|
||||
w.remain = Math.max(0, w.supply - demand);
|
||||
mready += wready;
|
||||
if (wnext !== null && (mnext === null || wnext < mnext)) mnext = wnext;
|
||||
}
|
||||
if (moon.wide) {
|
||||
let wready = 0;
|
||||
let amount = 0;
|
||||
let wnext = null;
|
||||
for (const d of moon.wide.drills ?? []) {
|
||||
if (isReady(d, now)) {
|
||||
wready++;
|
||||
amount += d.gets ?? d.take ?? 0;
|
||||
} else if (wnext === null || d.end < wnext) wnext = d.end;
|
||||
}
|
||||
moon.wide.ready = wready;
|
||||
moon.wide.readyAmount = amount;
|
||||
moon.wide.nextEnd = wnext;
|
||||
mready += wready;
|
||||
if (wnext !== null && (mnext === null || wnext < mnext)) mnext = wnext;
|
||||
}
|
||||
moon.ready = mready;
|
||||
moon.nextEnd = mnext;
|
||||
return st;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- queue
|
||||
|
||||
// Learn from a server state (the well each running or unclaimed drill is on).
|
||||
export function learn(st) {
|
||||
for (const s of st.stakes ?? []) memo.lastWell.set(s.toolId, s.wellId);
|
||||
}
|
||||
|
||||
// Run one pending entry ({fn, params, at, seq}) on st; true when it predicted.
|
||||
export function run(st, e) {
|
||||
let res = false;
|
||||
try {
|
||||
res = !!e.fn(st, e.params, { now: e.at, seq: e.seq });
|
||||
} catch (err) {
|
||||
console.warn(`predict: ${e.name} failed`, err);
|
||||
return false;
|
||||
}
|
||||
if (res) derive(st, e.at);
|
||||
return res;
|
||||
}
|
||||
|
||||
// The state to show: base with every pending prediction applied in order (base itself
|
||||
// when nothing is pending).
|
||||
export function apply(base, pending) {
|
||||
if (!pending.length) return base;
|
||||
const st = copy(base);
|
||||
for (const e of pending) run(st, e);
|
||||
return st;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- core-loop predictors
|
||||
|
||||
const moonOfWell = (st, wellId) => {
|
||||
for (const moon of st.moons ?? []) {
|
||||
const w = find(moon.wells, wellId);
|
||||
if (w) return [moon, w];
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
const groupFor = (st, wellId, tool) =>
|
||||
st.well && st.well.id === wellId ? (st.well.idle ?? []).findLast((g) => sameGroup(g, tool)) : undefined;
|
||||
|
||||
// claim: claim-well / claim-moon / everything ready; redeploy=1 restarts the same tools.
|
||||
registry.claim = (st, p, ctx) => {
|
||||
if (p["claim-wide"]) return false;
|
||||
const list = [];
|
||||
for (const s of st.stakes) {
|
||||
if (!isReady(s, ctx.now)) continue;
|
||||
if (p["claim-well"] && s.wellId !== p["claim-well"]) continue;
|
||||
if (p["claim-moon"] && s.moonId !== p["claim-moon"]) continue;
|
||||
if ((s.reach ?? 1) > 1) return false; // multi-well drills: the server splits them
|
||||
list.push(s);
|
||||
}
|
||||
if (!list.length) return false;
|
||||
for (const s of list) {
|
||||
addItem(st, s.resource, s.take ?? 0);
|
||||
addSupply(st, s.wellId, -(s.take ?? 0));
|
||||
removeStake(st, s);
|
||||
}
|
||||
if (p.redeploy) {
|
||||
for (const s of list) {
|
||||
const tool = find(st.tools, s.toolId);
|
||||
const w = wells(st, s.wellId)[0];
|
||||
if (tool && !tool.stakeId && w && w.supply > 0) {
|
||||
addStake(st, tool, s.moonId, w, ctx, groupFor(st, w.id, tool));
|
||||
const detail = st.moon && find(st.moon.wells, s.wellId);
|
||||
if (detail && memo.lastWell.get(tool.id) !== s.wellId && (detail.redrill ?? 0) > 0) detail.redrill--;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
// stake (deploy): the deploy card's tool on the target well, timer from now.
|
||||
registry.stake = (st, p, ctx) => {
|
||||
const [moon, w] = moonOfWell(st, p.target);
|
||||
if (!moon || w.supply <= 0) return false;
|
||||
// "Deploy there": the view moves to the other well, wait for it.
|
||||
if (st.view && ((p.moon && p.moon !== st.view.moon) || (p.well && p.well !== st.view.well))) return false;
|
||||
const tool = idleCopy(st, p.tool);
|
||||
if (!tool || (tool.reach ?? 1) > 1) return false;
|
||||
addStake(st, tool, moon.id, w, ctx, groupFor(st, w.id, tool));
|
||||
return true;
|
||||
};
|
||||
|
||||
// redrill: the idle tools that last mined the well (as far as the client saw).
|
||||
registry.redrill = (st, p, ctx) => {
|
||||
const id = p["redrill-well"];
|
||||
const [moon, w] = moonOfWell(st, id);
|
||||
if (!moon || w.supply <= 0) return false;
|
||||
const detail = st.moon && find(st.moon.wells, id);
|
||||
const n = detail?.redrill ?? 0;
|
||||
const tools = [];
|
||||
for (const t of st.tools) {
|
||||
if (tools.length < n && !t.stakeId && memo.lastWell.get(t.id) === id && (t.reach ?? 1) <= 1) tools.push(t);
|
||||
}
|
||||
if (!tools.length) return false;
|
||||
for (const t of tools) addStake(st, t, moon.id, w, ctx, groupFor(st, id, t));
|
||||
if (detail) detail.redrill = 0;
|
||||
return true;
|
||||
};
|
||||
@@ -0,0 +1,108 @@
|
||||
// The moon viewport rendered in a worker on an OffscreenCanvas, so the page's thread never
|
||||
// waits on three.js. Runs the classic client's MoonScene (web/static/js/scene.js, bundled
|
||||
// here with three.js) against a stand-in for the DOM it expects: the canvas element, its
|
||||
// container, ResizeObserver and the document. The page (scene.js) forwards pointer and
|
||||
// wheel events and the container's size.
|
||||
//
|
||||
// Messages in: {type: "init", canvas, width, height, dpr}, {type: "size", width, height,
|
||||
// left, top}, {type: "event", event: {...}}, {type: "show", seed, settings},
|
||||
// {type: "visible", hidden}. Out: {type: "ready"}, {type: "error", message}.
|
||||
|
||||
let canvas = null;
|
||||
let rect = { left: 0, top: 0, width: 1, height: 1 };
|
||||
const resizers = new Set();
|
||||
const root = new EventTarget(); // canvas.getRootNode(): OrbitControls listens for keys there
|
||||
|
||||
// ---------------------------------------------------------------- DOM stand-ins
|
||||
|
||||
self.window = self;
|
||||
self.document = {
|
||||
hidden: false,
|
||||
createElementNS: () => takeCanvas(),
|
||||
createElement: (tag) => (tag === "canvas" ? new OffscreenCanvas(1, 1) : {}),
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
self.ResizeObserver = class {
|
||||
constructor(fn) {
|
||||
this.fn = fn;
|
||||
}
|
||||
observe() {
|
||||
resizers.add(this.fn);
|
||||
}
|
||||
disconnect() {
|
||||
resizers.delete(this.fn);
|
||||
}
|
||||
};
|
||||
|
||||
// The first canvas three.js asks for is the page's (transferred); later ones are scratch.
|
||||
let given = false;
|
||||
function takeCanvas() {
|
||||
if (given) return new OffscreenCanvas(1, 1);
|
||||
given = true;
|
||||
return canvas;
|
||||
}
|
||||
|
||||
function dressCanvas(c) {
|
||||
c.style = {};
|
||||
c.className = "";
|
||||
c.getRootNode = () => root;
|
||||
c.setPointerCapture = () => {};
|
||||
c.releasePointerCapture = () => {};
|
||||
c.focus = () => {};
|
||||
Object.defineProperties(c, {
|
||||
clientWidth: { get: () => rect.width },
|
||||
clientHeight: { get: () => rect.height },
|
||||
});
|
||||
c.getBoundingClientRect = () => ({ ...rect, x: rect.left, y: rect.top, right: rect.left + rect.width, bottom: rect.top + rect.height });
|
||||
}
|
||||
|
||||
const container = {
|
||||
get clientWidth() {
|
||||
return rect.width;
|
||||
},
|
||||
get clientHeight() {
|
||||
return rect.height;
|
||||
},
|
||||
get offsetWidth() {
|
||||
return rect.width;
|
||||
},
|
||||
dataset: {},
|
||||
prepend() {},
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- messages
|
||||
|
||||
let scene = null;
|
||||
let wanted = null; // a show that came before the scene was up
|
||||
|
||||
self.onmessage = async ({ data }) => {
|
||||
try {
|
||||
if (data.type === "init") {
|
||||
canvas = data.canvas;
|
||||
self.devicePixelRatio = data.dpr;
|
||||
rect = { left: 0, top: 0, width: data.width, height: data.height };
|
||||
dressCanvas(canvas);
|
||||
const { MoonScene } = await import("../static/js/scene.js");
|
||||
scene = new MoonScene(container, {
|
||||
onContextChange: (lost) => self.postMessage({ type: "context", lost }),
|
||||
});
|
||||
if (wanted) scene.show(wanted);
|
||||
self.postMessage({ type: "ready" });
|
||||
} else if (data.type === "size") {
|
||||
rect = { left: data.left, top: data.top, width: data.width, height: data.height };
|
||||
for (const fn of resizers) fn();
|
||||
} else if (data.type === "event") {
|
||||
const { type, ...fields } = data.event;
|
||||
const e = new Event(type, { cancelable: true });
|
||||
Object.assign(e, fields);
|
||||
e.preventDefault = () => {};
|
||||
canvas?.dispatchEvent(e);
|
||||
} else if (data.type === "show") {
|
||||
wanted = { seed: data.seed, settings: data.settings };
|
||||
scene?.show(wanted);
|
||||
}
|
||||
} catch (error) {
|
||||
self.postMessage({ type: "error", message: String(error?.message ?? error) });
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,112 @@
|
||||
// The moon in the viewport. startViewport(container) -> {show(moonId), dispose()}.
|
||||
//
|
||||
// Preferred: the classic client's MoonScene rendered in a worker on an OffscreenCanvas
|
||||
// (scene-worker.js), with the canvas's pointer and wheel events and its size forwarded.
|
||||
// Without OffscreenCanvas, or if the worker fails to start, the classic client's scene runs
|
||||
// on this thread (web/static/js/scene.js, three.js through the page's import map).
|
||||
|
||||
import { mergeSettings } from "/static/js/terrain.js";
|
||||
|
||||
// The moon look tuned by admins (/utils/moons), merged over the defaults.
|
||||
const settings = fetch("/api/moon-settings")
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.catch(() => null)
|
||||
.then((saved) => mergeSettings(saved));
|
||||
|
||||
// Where the viewport runs, for the measurements: "worker" or "main".
|
||||
export let mode = "";
|
||||
|
||||
export function startViewport(container) {
|
||||
const offscreen = "transferControlToOffscreen" in HTMLCanvasElement.prototype && !new URLSearchParams(location.search).has("mainscene");
|
||||
return offscreen ? workerViewport(container) : mainViewport(container);
|
||||
}
|
||||
|
||||
function mainViewport(container) {
|
||||
mode = "main";
|
||||
let seed = "";
|
||||
let scene = null;
|
||||
import("/static/js/scene.js").then(({ startScene }) => {
|
||||
scene = startScene(container, {
|
||||
onStatus(message) {
|
||||
if (message) console.warn("viewport:", message);
|
||||
},
|
||||
});
|
||||
if (seed) show(seed);
|
||||
});
|
||||
const show = (s) => {
|
||||
seed = s;
|
||||
if (scene) settings.then((set) => scene.show({ seed: s, settings: set }));
|
||||
};
|
||||
return { show, dispose: () => scene?.dispose() };
|
||||
}
|
||||
|
||||
const FIELDS = ["pointerId", "pointerType", "button", "buttons", "clientX", "clientY", "pageX", "pageY", "deltaX", "deltaY", "deltaMode", "ctrlKey", "metaKey", "shiftKey", "altKey"];
|
||||
|
||||
function workerViewport(container) {
|
||||
mode = "worker";
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.className = "game-canvas";
|
||||
canvas.style.touchAction = "none";
|
||||
container.prepend(canvas);
|
||||
const worker = new Worker(new URL("./scene-worker.js", import.meta.url), { type: "module" });
|
||||
let failed = null;
|
||||
let seed = "";
|
||||
const fail = (why) => {
|
||||
if (failed) return;
|
||||
console.warn("viewport: worker failed, drawing on the page's thread:", why);
|
||||
worker.terminate();
|
||||
stop();
|
||||
canvas.remove();
|
||||
failed = mainViewport(container);
|
||||
if (seed) failed.show(seed);
|
||||
};
|
||||
worker.onerror = (e) => {
|
||||
e.preventDefault?.();
|
||||
fail(e.message);
|
||||
};
|
||||
worker.onmessage = ({ data }) => {
|
||||
if (data.type === "error") fail(data.message);
|
||||
};
|
||||
const box = () => container.getBoundingClientRect();
|
||||
const r = box();
|
||||
const off = canvas.transferControlToOffscreen();
|
||||
worker.postMessage(
|
||||
{ type: "init", canvas: off, width: r.width, height: r.height, dpr: Math.min(devicePixelRatio, 2) },
|
||||
[off]
|
||||
);
|
||||
const size = () => {
|
||||
const b = box();
|
||||
worker.postMessage({ type: "size", width: b.width, height: b.height, left: b.left, top: b.top });
|
||||
};
|
||||
const resize = new ResizeObserver(size);
|
||||
resize.observe(container);
|
||||
// OrbitControls listens on the canvas; it captures the pointer while dragging.
|
||||
const forward = (e) => {
|
||||
if (e.type === "pointerdown") {
|
||||
canvas.setPointerCapture(e.pointerId);
|
||||
size(); // its rect is read on drag start
|
||||
}
|
||||
if (e.type === "wheel" || e.type === "contextmenu") e.preventDefault();
|
||||
const msg = { type: e.type };
|
||||
for (const k of FIELDS) if (k in e) msg[k] = e[k];
|
||||
worker.postMessage({ type: "event", event: msg });
|
||||
};
|
||||
const types = ["pointerdown", "pointermove", "pointerup", "pointercancel", "wheel", "contextmenu"];
|
||||
for (const t of types) canvas.addEventListener(t, forward, { passive: t !== "wheel" && t !== "contextmenu" });
|
||||
const stop = () => {
|
||||
resize.disconnect();
|
||||
for (const t of types) canvas.removeEventListener(t, forward);
|
||||
};
|
||||
return {
|
||||
show(s) {
|
||||
seed = s;
|
||||
if (failed) return failed.show(s);
|
||||
settings.then((set) => worker.postMessage({ type: "show", seed: s, settings: set }));
|
||||
},
|
||||
dispose() {
|
||||
stop();
|
||||
worker.terminate();
|
||||
failed?.dispose();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
// The session with the server, like the Defold client's (client/screens/game/core/session.lua).
|
||||
//
|
||||
// State: `base` (the last server state), `pending` (predicted actions and navigations
|
||||
// not answered yet), `shown` (base + pending, predict.apply) and `live` (shown with the
|
||||
// counts that depend on the clock re-derived at every drill end).
|
||||
// Requests (state fetches and actions) go out one at a time in click order from the
|
||||
// outbox, so the server runs actions in click order and each response's state is the
|
||||
// base for the predictions still queued behind it. A response replaces the base and drops
|
||||
// its own prediction (a 422 or a network error rolls it back). Nothing waits for the
|
||||
// server to show a result: a predicted action's effects play at the click.
|
||||
|
||||
import { signal, computed, batch, effect } from "@preact/signals";
|
||||
import * as P from "./predict.js";
|
||||
import { now, syncClock, edge, armEdge, lastEdge } from "./clock.js";
|
||||
|
||||
export const base = signal(null);
|
||||
export const pending = signal([]);
|
||||
export const shown = computed(() => base.value && P.apply(base.value, pending.value));
|
||||
export const live = computed(() => {
|
||||
edge.value;
|
||||
const st = shown.value;
|
||||
if (!st) return null;
|
||||
P.derive(st, now());
|
||||
return { ...st };
|
||||
});
|
||||
// Whether the latest change on screen came from the clock (a drill finishing) rather than
|
||||
// a new state: a Claim button enabled by the clock plays the ready effect.
|
||||
let lastShown = -Infinity;
|
||||
effect(() => {
|
||||
shown.value;
|
||||
lastShown = performance.now();
|
||||
});
|
||||
export const clockCaused = () => lastEdge > lastShown;
|
||||
export const toasts = signal([]);
|
||||
// Buttons waiting for an answer they couldn't predict (key -> seq): they show a spinner.
|
||||
export const busy = signal({});
|
||||
export const boot = signal("Preparing your mining rig…");
|
||||
|
||||
// Wake at every drill end (readiness is local) and when a just-bought moon becomes
|
||||
// sellable, and refetch shortly after the soonest drill end as a safety net, like the
|
||||
// Defold client's arm_refetch.
|
||||
effect(() => {
|
||||
const st = live.value;
|
||||
if (!st) return;
|
||||
const ends = st.stakes.filter((s) => !P.isReady(s, now())).map((s) => s.end);
|
||||
if (st.moon?.sale?.holdEnd) ends.push(st.moon.sale.holdEnd);
|
||||
armEdge(ends);
|
||||
armRefetch(st.nextEnd);
|
||||
});
|
||||
|
||||
// Effects hooks (fx.js sets them): onAction(kind, prev, next, origin) when an action is
|
||||
// predicted (or answered without a prediction), onAnswer(kind, data) on every accepted
|
||||
// action (what only the server knows, like a moon mined out), onError(origin) on a
|
||||
// refusal, onNavigate() when the player follows a link.
|
||||
export const hooks = { onAction() {}, onAnswer() {}, onError() {}, onToast() {}, onNavigate() {} };
|
||||
|
||||
let seq = 0;
|
||||
let applied = 0;
|
||||
let catalog = null;
|
||||
let catalogVersion = "";
|
||||
const outbox = [];
|
||||
let sending = null;
|
||||
|
||||
// ---------------------------------------------------------------- views
|
||||
|
||||
const VIEW_KEYS = { section: "s", moon: "moon", well: "well", pick: "pick", drill: "drill", adv: "adv" };
|
||||
|
||||
export function viewParams(v, extra = {}) {
|
||||
const p = {};
|
||||
for (const [k, q] of Object.entries(VIEW_KEYS)) if (v?.[k]) p[q] = v[k];
|
||||
if (v?.past) p.list = "past";
|
||||
if (v?.past && v.page > 1) p.page = String(v.page);
|
||||
return { ...p, ...extra };
|
||||
}
|
||||
|
||||
export function viewURL(v) {
|
||||
const q = new URLSearchParams(viewParams(v));
|
||||
const s = q.toString();
|
||||
return "/app" + (s ? "?" + s : "");
|
||||
}
|
||||
|
||||
function viewFromURL() {
|
||||
const q = new URLSearchParams(location.search);
|
||||
return {
|
||||
section: q.get("s") ?? "",
|
||||
moon: q.get("moon") ?? "",
|
||||
well: q.get("well") ?? "",
|
||||
past: q.get("list") === "past",
|
||||
page: Number(q.get("page")) || 1,
|
||||
};
|
||||
}
|
||||
|
||||
// The view in effect for the next request: the shown one (a predicted navigation counts).
|
||||
const currentView = () => shown.value?.view ?? viewFromURL();
|
||||
|
||||
// Keep the address bar on the shown view.
|
||||
let fromHistory = false;
|
||||
effect(() => {
|
||||
const v = shown.value?.view;
|
||||
if (!v) return;
|
||||
const url = viewURL(v);
|
||||
if (url === location.pathname + location.search) return;
|
||||
if (fromHistory) history.replaceState(null, "", url);
|
||||
else history.pushState(null, "", url);
|
||||
});
|
||||
addEventListener("popstate", () => {
|
||||
fromHistory = true;
|
||||
navigate(viewFromURL());
|
||||
fromHistory = false;
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- requests
|
||||
|
||||
function enqueue(r) {
|
||||
outbox.push(r);
|
||||
pump();
|
||||
}
|
||||
|
||||
async function pump() {
|
||||
if (sending || !outbox.length) return;
|
||||
const r = (sending = outbox.shift());
|
||||
const params = { ...r.params, catalog: catalogVersion || undefined };
|
||||
if (!catalogVersion) delete params.catalog;
|
||||
let data = null;
|
||||
let status = 0;
|
||||
try {
|
||||
const res =
|
||||
r.kind === "get"
|
||||
? await fetch("/api/state?" + new URLSearchParams(params), { credentials: "same-origin" })
|
||||
: await fetch(`/api/act/${r.kind}`, {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ ...params, clientSeq: r.seq }),
|
||||
});
|
||||
status = res.status;
|
||||
data = await res.json().catch(() => null);
|
||||
} catch {
|
||||
status = 0;
|
||||
}
|
||||
sending = null;
|
||||
receive(r, data, status, Date.now());
|
||||
pump();
|
||||
}
|
||||
|
||||
function dropPending(s) {
|
||||
const list = pending.value;
|
||||
const i = list.findIndex((e) => e.seq === s);
|
||||
if (i < 0) return false;
|
||||
pending.value = list.toSpliced(i, 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
function setBase(st, recv) {
|
||||
if (st.catalog) {
|
||||
catalog = st.catalog;
|
||||
catalogVersion = st.catalogVersion;
|
||||
} else st.catalog = catalog;
|
||||
syncClock(st.now, recv);
|
||||
P.learn(st);
|
||||
remember(st);
|
||||
base.value = st;
|
||||
}
|
||||
|
||||
function receive(r, data, status, recv) {
|
||||
const prev = shown.value;
|
||||
let predicted = false;
|
||||
batch(() => {
|
||||
predicted = dropPending(r.seq);
|
||||
if (data?.state && r.seq > applied) {
|
||||
applied = r.seq;
|
||||
setBase(data.state, recv);
|
||||
}
|
||||
if (r.busyKey && busy.value[r.busyKey] === r.seq) {
|
||||
const b = { ...busy.value };
|
||||
delete b[r.busyKey];
|
||||
busy.value = b;
|
||||
}
|
||||
});
|
||||
if (!base.value) {
|
||||
boot.value =
|
||||
status === 403 ? "This account is suspended." : `Could not start the game: ${status ? "HTTP " + status : "Can't reach the server"}`;
|
||||
if (status !== 403) setTimeout(() => navigate(viewFromURL(), { quiet: true }), 3000);
|
||||
return;
|
||||
}
|
||||
boot.value = "";
|
||||
if (status === 403) {
|
||||
location.reload();
|
||||
return;
|
||||
}
|
||||
if (r.kind === "get") {
|
||||
if (!data?.ok && status !== 200) toast(status ? "Something went wrong" : "Can't reach the server", "error", true);
|
||||
return;
|
||||
}
|
||||
const ok = !!data?.ok;
|
||||
if (!ok) hooks.onError(r.origin);
|
||||
else if (!predicted) hooks.onAction(r.kind, prev, shown.value, r.origin, data);
|
||||
if (ok) hooks.onAnswer(r.kind, data);
|
||||
if (data?.toast) toast(data.toast.message, data.toast.kind, data.toast.error);
|
||||
else if (!ok) toast(status ? "Something went wrong" : "Can't reach the server", "error", true);
|
||||
}
|
||||
|
||||
let refetchTimer = 0;
|
||||
let refetchAt = 0;
|
||||
function armRefetch(due) {
|
||||
if (!due || due === refetchAt) return;
|
||||
clearTimeout(refetchTimer);
|
||||
refetchAt = due;
|
||||
const left = due - now();
|
||||
if (left < -2000) return;
|
||||
refetchTimer = setTimeout(() => {
|
||||
refetchAt = 0;
|
||||
if (!sending && !outbox.length) enqueue({ kind: "get", params: viewParams(currentView()), seq: ++seq });
|
||||
}, Math.max(0, left) + 300);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- toasts
|
||||
|
||||
let toastId = 0;
|
||||
export function toast(message, kind = "", error = false) {
|
||||
const t = { id: ++toastId, message, kind: error ? "error" : kind, error };
|
||||
toasts.value = [...toasts.value.slice(-4), t];
|
||||
hooks.onToast(t);
|
||||
setTimeout(() => (toasts.value = toasts.value.map((x) => (x.id === t.id ? { ...x, out: true } : x))), 3200);
|
||||
setTimeout(() => (toasts.value = toasts.value.filter((x) => x.id !== t.id)), 3800);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- actions
|
||||
|
||||
// Run an action with the current view. origin: the clicked element (effects start there).
|
||||
// Returns true when the result was predicted (shown now).
|
||||
export function act(name, params = {}, origin = null, busyKey = "") {
|
||||
const s = ++seq;
|
||||
const p = { ...viewParams(currentView()), ...params };
|
||||
const fn = P.registry[name];
|
||||
let predicted = false;
|
||||
const prev = shown.value;
|
||||
const at = now();
|
||||
if (fn && prev) {
|
||||
const e = { seq: s, name, params: p, at, fn };
|
||||
const st = P.copy(prev);
|
||||
if (P.run(st, e)) {
|
||||
pending.value = [...pending.value, e];
|
||||
predicted = true;
|
||||
hooks.onAction(name, prev, shown.value, rectOf(origin));
|
||||
}
|
||||
}
|
||||
if (!predicted && busyKey) busy.value = { ...busy.value, [busyKey]: s };
|
||||
enqueue({ kind: name, params: p, seq: s, origin: rectOf(origin), busyKey: predicted ? "" : busyKey });
|
||||
return predicted;
|
||||
}
|
||||
|
||||
const rectOf = (el) => {
|
||||
if (!el?.getBoundingClientRect) return null;
|
||||
const r = el.getBoundingClientRect();
|
||||
const box = (el.closest?.(".line, tr, .moon, .heading, .deploy-card") ?? el).getBoundingClientRect();
|
||||
return { x: r.left + r.width / 2, y: r.top + r.height / 2, box, el };
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- navigation
|
||||
|
||||
// Details seen in server states, by id, for predicted navigation.
|
||||
const seenMoons = new Map();
|
||||
function remember(st) {
|
||||
if (st.moon) seenMoons.set(st.moon.id, st.moon);
|
||||
}
|
||||
|
||||
// Go to a view; the moon and well show at once from what the client has (the moon list,
|
||||
// the stakes and tools, details seen before), and the server's answer fills in the rest.
|
||||
export function navigate(v, { quiet = false } = {}) {
|
||||
const s = ++seq;
|
||||
const target = { section: "moons", moon: "", well: "", past: false, page: 1, ...v };
|
||||
const st = shown.value;
|
||||
if (st) {
|
||||
const e = { seq: s, name: "nav", params: target, at: now(), fn: predictNav };
|
||||
const copy = P.copy(st);
|
||||
if (P.run(copy, e)) pending.value = [...pending.value, e];
|
||||
}
|
||||
enqueue({ kind: "get", params: viewParams(target), seq: s, quiet });
|
||||
}
|
||||
|
||||
function predictNav(st, v) {
|
||||
if (v.section !== "moons" || v.past) return false;
|
||||
const entry = P.find(st.moons, v.moon) ?? (!v.moon && st.moons?.[0]);
|
||||
if (!entry) return false;
|
||||
const seen = seenMoons.get(entry.id);
|
||||
const wellId = v.well && P.find(entry.wells, v.well) ? v.well : "";
|
||||
st.view = { ...st.view, section: "moons", moon: entry.id, well: wellId, past: false, aside: true };
|
||||
for (const m of st.moons) m.selected = m.id === entry.id;
|
||||
if (st.moon?.id !== entry.id) {
|
||||
st.moon = {
|
||||
id: entry.id,
|
||||
name: entry.name,
|
||||
kind: entry.kind,
|
||||
description: seen?.description ?? "",
|
||||
rating: entry.rating,
|
||||
finished: false,
|
||||
wells: entry.wells.map((w) => ({ ...w, drills: [], wide: [], label: "", redrill: 0 })),
|
||||
wide: seen?.wide ?? null,
|
||||
sale: null,
|
||||
};
|
||||
// Redrill: idle tools that last mined each well.
|
||||
for (const w of st.moon.wells) {
|
||||
w.redrill = st.tools.filter((t) => !t.stakeId && P.memo.lastWell.get(t.id) === w.id && (t.reach ?? 1) <= 1).length;
|
||||
}
|
||||
}
|
||||
for (const w of st.moon.wells) w.selected = w.id === wellId;
|
||||
if (!wellId) st.well = null;
|
||||
else if (st.well?.id !== wellId) st.well = predictWell(st, P.find(entry.wells, wellId));
|
||||
return true;
|
||||
}
|
||||
|
||||
// The well panel for a well: the idle tools grouped like the server's deploy cards.
|
||||
function predictWell(st, w) {
|
||||
let committed = 0;
|
||||
for (const s of st.stakes) if (s.wellId === w.id) committed += s.take ?? 0;
|
||||
const free = Math.max(0, w.supply - committed);
|
||||
const boost = st.rules?.boosts?.yield?.[w.resource] ?? 1;
|
||||
const groups = new Map();
|
||||
for (const t of st.tools) {
|
||||
if (t.stakeId) continue;
|
||||
const key = `${t.storeItemId}:${t.tier}:${(t.attachments ?? []).join("+")}`;
|
||||
const g = groups.get(key);
|
||||
if (g) {
|
||||
g.count++;
|
||||
continue;
|
||||
}
|
||||
const y = t.yield * boost;
|
||||
groups.set(key, {
|
||||
toolId: t.id,
|
||||
storeItemId: t.storeItemId,
|
||||
name: t.name,
|
||||
tier: t.tier,
|
||||
count: 1,
|
||||
cycleSecs: t.cycleSecs,
|
||||
yield: y,
|
||||
reach: t.reach,
|
||||
here: Math.min(y, free),
|
||||
free,
|
||||
short: free < y,
|
||||
attachments: t.attachments ?? [],
|
||||
});
|
||||
}
|
||||
const quote = st.market && P.find(st.market.quotes, w.resource, "item");
|
||||
return { id: w.id, resource: w.resource, rate: quote?.price ?? 0, idle: [...groups.values()], better: null };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- start
|
||||
|
||||
export function start() {
|
||||
enqueue({ kind: "get", params: viewParams(viewFromURL()), seq: ++seq });
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
// The side panel next to the viewport: the selected well (deploy cards, a better well to
|
||||
// deploy on, drill lines with the moon's multi-well drills that mine it too, claim,
|
||||
// redrill) or the moon.
|
||||
|
||||
import { live, act, busy } from "./session.js";
|
||||
import { Countdown, Dot, Num, SupplyBar } from "./ui.jsx";
|
||||
import { ReadyButton } from "./buttons.jsx";
|
||||
import { ViewLink, WideClaim, wideOn } from "./moons.jsx";
|
||||
import { colorOf, imageOf, toolOf } from "./catalog.js";
|
||||
import { money, cur, secs } from "./format.js";
|
||||
import { useFlip } from "./flip.js";
|
||||
import { now } from "./clock.js";
|
||||
import { isReady, find } from "./predict.js";
|
||||
|
||||
export function Side() {
|
||||
const st = live.value;
|
||||
const moon = st.moon;
|
||||
const well = st.well;
|
||||
if (!moon) return null;
|
||||
const w = well && find(moon.wells, well.id);
|
||||
if (!well || !w) {
|
||||
return (
|
||||
<>
|
||||
<h2>{moon.name}</h2>
|
||||
{moon.finished ? (
|
||||
<p class="tapped-note">Mined out. Nothing left to dig.</p>
|
||||
) : (
|
||||
<p class="muted small">Pick a well in the table to deploy tools and claim resources.</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
return <WellPanel st={st} moon={moon} well={well} w={w} />;
|
||||
}
|
||||
|
||||
function WellPanel({ st, moon, well, w }) {
|
||||
const dry = w.supply <= 0;
|
||||
const color = colorOf(w.resource);
|
||||
const t = now();
|
||||
const cards = useFlip();
|
||||
const lines = useFlip();
|
||||
const mining = w.drills.length > 0;
|
||||
const wide = wideOn(moon, w);
|
||||
return (
|
||||
<>
|
||||
<h2>
|
||||
<Dot color={color} />
|
||||
{w.resource} well
|
||||
</h2>
|
||||
{dry ? (
|
||||
<>
|
||||
<div class="bar" />
|
||||
<p class="tapped-note">Nothing left to mine here.</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<SupplyBar supply={w.supply} demand={w.demand} max={st.rules.maxSupply} color={color} full={w.full} />
|
||||
{w.demand > 0 && (
|
||||
<span class={`well-note small${w.full ? " warn" : ""}`}>
|
||||
<span class="num">{money(w.supply)}</span> left · <span class="num">{money(w.demand)}</span> committed ·{" "}
|
||||
<span class="num">{money(w.remain)}</span> free after
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<dl class="facts">
|
||||
<div>
|
||||
<dt>Supply left</dt>
|
||||
<dd class="num">
|
||||
<Num n={w.supply} k={`side-supply:${w.id}`} />
|
||||
</dd>
|
||||
</div>
|
||||
{w.demand > 0 && (
|
||||
<div>
|
||||
<dt>After current drills</dt>
|
||||
<dd class={`num${w.full ? " warn" : ""}`}>{money(w.remain)}</dd>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<dt>Sells for</dt>
|
||||
<dd class="num">{cur(well.rate)} each</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
{!dry && (
|
||||
<>
|
||||
<h3>Deploy a tool</h3>
|
||||
{well.idle.length ? (
|
||||
<div class="deploy-cards" ref={cards}>
|
||||
{well.idle.map((g) => (
|
||||
<DeployCard key={`${g.storeItemId}:${g.tier}:${(g.attachments ?? []).join("+")}`} st={st} g={g} wellId={well.id} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p class="muted small">
|
||||
No idle tools.
|
||||
{st.unlocked.store && (
|
||||
<>
|
||||
{" "}
|
||||
<a href="/?s=store" title="Opens the classic client">
|
||||
Buy one in the store
|
||||
</a>
|
||||
.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{well.idle.length > 0 && well.better && <BetterWell st={st} moon={moon} b={well.better} />}
|
||||
</>
|
||||
)}
|
||||
|
||||
<h3>
|
||||
Drills
|
||||
{w.drills.length > 1 && <span class="muted small"> · {w.drills.length} share this well, oldest claims first</span>}
|
||||
</h3>
|
||||
<div ref={lines}>
|
||||
{[...w.drills, ...wide].map((d) => {
|
||||
const tool = toolOf(st, d.toolId);
|
||||
const ready = isReady(d, t);
|
||||
return (
|
||||
<div key={d.toolId} data-key={d.toolId} data-tool={d.toolId} class={`line drill-line is-${d.state ?? "ok"}`}>
|
||||
<span class="drill-thumb">{tool && <img src={tool.image} alt="" />}</span>
|
||||
<span class="drill-main">
|
||||
<span class="drill-name">
|
||||
{tool?.name ?? "Tool"} <span class="muted">T{tool?.tier ?? 0}</span>
|
||||
</span>
|
||||
<span class="drill-meta small">
|
||||
<span class="muted">
|
||||
<span class="num">+{money(d.amount)}</span>/cycle
|
||||
{d.reachText && ` · ${d.reachText}`}
|
||||
</span>
|
||||
{d.state === "none" ? (
|
||||
<span class="drill-tag">Nothing left</span>
|
||||
) : (
|
||||
<span class="drill-gets">
|
||||
{" "}
|
||||
· Gets <span class="num">{money(d.here ?? d.take)}</span>
|
||||
{(d.reach ?? 1) > 1 && " here"}
|
||||
{(d.reach ?? 1) > 1 && d.gets != null && d.gets !== d.here && (
|
||||
<>
|
||||
{" "}
|
||||
· <span class="num">{money(d.gets)}</span> in all
|
||||
</>
|
||||
)}
|
||||
{d.state === "short" && (
|
||||
<>
|
||||
{" "}
|
||||
of <span class="num">{money(d.amount)}</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
{ready ? <span class="ready small">Ready</span> : <Countdown end={d.end} class="num muted small" />}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{!mining && !wide.length && <p class="muted small">Nothing is mining here yet.</p>}
|
||||
{mining && (
|
||||
<div class="actions">
|
||||
<ReadyButton class="btn btn-primary" ready={w.ready > 0} onClick={(e) => act("claim", { "claim-well": w.id }, e.currentTarget)}>
|
||||
Claim {w.ready > 0 ? <Num class="num" n={w.readyAmount} k={`side-ready:${w.id}`} /> : <Countdown end={w.nextEnd} />}
|
||||
</ReadyButton>
|
||||
{w.ready > 0 && !dry && st.unlocked.store && (
|
||||
<button type="button" class="btn" onClick={(e) => act("claim", { "claim-well": w.id, redeploy: "1" }, e.currentTarget)}>
|
||||
Claim and redeploy
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{wide.length > 0 && (
|
||||
<div class="actions">
|
||||
<WideClaim moon={moon} />
|
||||
{moon.wide.ready > 0 && st.unlocked.store && (
|
||||
<button type="button" class="btn" onClick={(e) => act("claim", { "claim-wide": moon.id, redeploy: "1" }, e.currentTarget)}>
|
||||
Claim and redeploy
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{w.redrill > 0 && !dry && st.unlocked.market && (
|
||||
<div class="actions">
|
||||
<button type="button" class="btn btn-redrill" onClick={(e) => act("redrill", { "redrill-well": w.id }, e.currentTarget)}>
|
||||
Redrill{w.redrill > 1 ? ` ${w.redrill}` : ""}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function DeployCard({ st, g, wellId }) {
|
||||
const key = `${g.storeItemId}:${g.tier}:${(g.attachments ?? []).join("+")}`;
|
||||
const cls = g.short ? (g.here > 0 ? " is-short" : " is-spoken") : "";
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
data-key={key}
|
||||
class={`btn deploy-card${cls}`}
|
||||
title={`Deploy ${g.name} T${g.tier}`}
|
||||
onClick={(e) => act("stake", { tool: g.toolId, target: wellId }, e.currentTarget, `stake:${key}`)}
|
||||
>
|
||||
<span class="deploy-card-media">
|
||||
<img src={imageOf(st, g.storeItemId)} alt="" />
|
||||
{g.attachments?.length > 0 && (
|
||||
<span class="deploy-card-pips pips">
|
||||
{g.attachments.map((a, i) => (
|
||||
<i key={i} class="pip is-on" />
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
{g.count > 1 && <span class="deploy-card-count num">×{g.count}</span>}
|
||||
</span>
|
||||
<span class="deploy-card-info">
|
||||
<span class="deploy-card-name">
|
||||
<span class="deploy-card-title">{g.name}</span> <span class="tier-chip num">T{g.tier}</span>
|
||||
</span>
|
||||
<span class="deploy-card-meta">
|
||||
<span class="num">
|
||||
+{money(g.here)} / {secs(g.cycleSecs)}
|
||||
</span>
|
||||
<span class="deploy-card-go">Deploy</span>
|
||||
</span>
|
||||
{g.short && (
|
||||
<span class="deploy-card-note">
|
||||
{g.here > 0 ? (
|
||||
<>
|
||||
Only <span class="num">{money(g.free)}</span> left after current drills
|
||||
</>
|
||||
) : (
|
||||
"Well spoken for: nothing left after current drills"
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// A better well for the idle tools (more free supply), maybe on another moon: deploying
|
||||
// there moves the view to it, so it waits for the server (the button spins).
|
||||
function BetterWell({ st, moon, b }) {
|
||||
const other = b.moonId !== moon.id ? find(st.moons, b.moonId)?.name : null;
|
||||
const spinning = !!busy.value["stake:better"];
|
||||
const deploy = (e) => act("stake", { tool: b.toolId, target: b.wellId, s: "moons", moon: b.moonId, well: b.wellId }, e.currentTarget, "stake:better");
|
||||
return (
|
||||
<div class="line better-well">
|
||||
<span class="grow small">
|
||||
Better:{" "}
|
||||
<ViewLink to={{ section: "moons", moon: b.moonId, well: b.wellId }}>
|
||||
<Dot color={colorOf(b.resource)} />
|
||||
{b.resource} well
|
||||
</ViewLink>
|
||||
{other && ` on ${other}`}, <span class="num">{money(b.free)}</span> free
|
||||
</span>
|
||||
{b.toolId && (
|
||||
<button type="button" class={`btn btn-sm btn-primary${spinning ? " htmx-request" : ""}`} disabled={spinning} title="Deploy on that well" onClick={deploy}>
|
||||
Deploy there
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// Small display pieces shared by the sections. Values that change every frame (eased
|
||||
// numbers, countdowns, drill bars) are written by the frame loop or the Web Animations
|
||||
// API on elements Preact created once, so a re-render never replaces or restarts them.
|
||||
|
||||
import { useRef, useEffect, useLayoutEffect } from "preact/hooks";
|
||||
import { addTicker, eased, moving, now } from "./clock.js";
|
||||
import { money, fixed, decimals, left, hue } from "./format.js";
|
||||
import { mark } from "/static/js/fx.js";
|
||||
|
||||
// A number that eases to its new value (key: what it is, e.g. "credits"). value: a signal
|
||||
// or computed, or n: a plain number (the component re-renders with it). A gain pops, a loss nudges (CSS fx-gain / fx-loss), unless something holds
|
||||
// it (a claim's resources wait for their particles).
|
||||
export function Num({ value, n, k, prefix = "", class: cls, ...rest }) {
|
||||
const ref = useRef(null);
|
||||
const src = useRef(null);
|
||||
src.current = value ?? n;
|
||||
const read = () => (typeof src.current === "number" ? src.current : src.current.peek());
|
||||
useLayoutEffect(() => {
|
||||
let last = read();
|
||||
let digits = decimals(last);
|
||||
return addTicker((t) => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const truth = read();
|
||||
if (truth !== last) {
|
||||
if (!moving(k)) mark(el, truth > last ? "fx-gain" : "fx-loss");
|
||||
digits = Math.max(decimals(last), decimals(truth));
|
||||
last = truth;
|
||||
}
|
||||
const v = eased(k, truth, t);
|
||||
// Whole counts tick as whole numbers; others keep their decimals while moving.
|
||||
const text = prefix + (v === truth ? money(truth) : Number.isInteger(truth) ? money(Math.round(v)) : fixed(v, digits));
|
||||
if (el.textContent !== text) el.textContent = text;
|
||||
});
|
||||
}, [k]);
|
||||
return <span ref={ref} class={cls} data-num={k} {...rest} />;
|
||||
}
|
||||
|
||||
// Time left until end (unix ms, server clock), then `done`.
|
||||
export function Countdown({ end, done = "", class: cls = "num" }) {
|
||||
const ref = useRef(null);
|
||||
const endRef = useRef(end);
|
||||
endRef.current = end;
|
||||
useLayoutEffect(
|
||||
() =>
|
||||
addTicker(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const ms = endRef.current - now();
|
||||
const text = ms > 0 ? left(ms) : done;
|
||||
if (el.textContent !== text) el.textContent = text;
|
||||
}),
|
||||
[]
|
||||
);
|
||||
return <time ref={ref} class={cls} />;
|
||||
}
|
||||
|
||||
// A drill's timer bar (keyed by tool id, so the server's correction of a predicted stake
|
||||
// keeps the element). The fill is a compositor animation (transform); a correction
|
||||
// changes its playback rate so it lands on the true end instead of jumping.
|
||||
export function DrillBar({ start, end, state, ready, wide }) {
|
||||
const fill = useRef(null);
|
||||
const anim = useRef(null);
|
||||
useLayoutEffect(() => {
|
||||
const el = fill.current;
|
||||
const d = Math.max(1, end - start);
|
||||
const t = now();
|
||||
let a = anim.current;
|
||||
if (!a) {
|
||||
a = anim.current = el.animate([{ transform: "scaleX(0)" }, { transform: "scaleX(1)" }], {
|
||||
duration: d,
|
||||
fill: "both",
|
||||
easing: "linear",
|
||||
});
|
||||
a.currentTime = Math.min(d, Math.max(0, t - start));
|
||||
return;
|
||||
}
|
||||
// Correction: keep the progress shown, finish at the true end.
|
||||
const timing = a.effect.getComputedTiming();
|
||||
const p = Math.min(1, (timing.progress ?? (a.playState === "finished" ? 1 : 0)));
|
||||
a.effect.updateTiming({ duration: d });
|
||||
a.currentTime = p * d;
|
||||
const rest = end - t;
|
||||
if (rest <= 0 || p >= 1) {
|
||||
a.updatePlaybackRate(1);
|
||||
a.currentTime = rest <= 0 ? d : a.currentTime;
|
||||
return;
|
||||
}
|
||||
a.updatePlaybackRate(Math.min(4, Math.max(0.25, ((1 - p) * d) / rest)));
|
||||
}, [start, end]);
|
||||
useEffect(() => () => anim.current?.cancel(), []);
|
||||
return (
|
||||
<i class={`drill-bar pa-bar is-${state}${wide ? " is-wide" : ""}${ready ? " is-ready" : ""}`}>
|
||||
<b ref={fill} class="pa-fill" />
|
||||
</i>
|
||||
);
|
||||
}
|
||||
|
||||
export const Dot = ({ color }) => <span class="dot" style={{ background: color ?? "#e2e8f0" }} aria-hidden="true" />;
|
||||
export const Planet = ({ id }) => <span class="planet" style={{ "--hue": hue(id) }} aria-hidden="true" />;
|
||||
|
||||
export function RatingChip({ r }) {
|
||||
if (!r) return null;
|
||||
return (
|
||||
<span class={`rating-chip tier-${r.tier}`} title={`${r.label} moon · top ${r.top}%`} aria-label={`${r.label} moon, ${r.stars} of 5 stars`}>
|
||||
★{r.stars}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// A supply bar: what stays after the drills (solid), then what they will take (striped).
|
||||
// Both parts span the bar and are clipped (paint only, no layout), so a change glides
|
||||
// without stretching the cells or stripes.
|
||||
export function SupplyBar({ supply, demand, max, color, full, showNum }) {
|
||||
const m = Math.max(1, max);
|
||||
const remain = Math.max(0, supply - demand);
|
||||
const taken = Math.min(demand, supply);
|
||||
const r = Math.min(1, remain / m);
|
||||
const u = Math.min(1 - r, taken / m);
|
||||
const pct = (x) => `${(x * 100).toFixed(2)}%`;
|
||||
return (
|
||||
<div class={`supply${full ? " is-full" : ""}`}>
|
||||
<div class="bar bar-split pa-split">
|
||||
<span style={{ clipPath: `inset(0 ${pct(1 - r)} 0 0)`, background: color }} />
|
||||
<span class="bar-used" style={{ clipPath: `inset(0 ${pct(1 - r - u)} 0 ${pct(r)})`, background: color }} />
|
||||
</div>
|
||||
{showNum && <Num class="num muted" n={supply} k={`supply:${showNum}`} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-present Jason Miller
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import{options as n}from"preact";var t,r,u,i,o=Object.is,f=0,c=[],e=[],a=n,v=a.__b,l=a.__r,m=a.diffed,s=a.__c,h=a.unmount,p=a.__;function y(n,t){a.__h&&a.__h(r,n,f||t),f=0;var u=r.__H||(r.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function d(n){return f=1,_(G,n)}function _(n,u,i){var f=y(t++,2);if(f.t=n,!f.__c&&(f.__=[i?i(u):G(void 0,u),function(n){var t=f.__N?f.__N[0]:f.__[0],r=f.t(t,n);o(t,r)||(f.__N=[r,f.__[1]],f.__c.setState({}))}],f.__c=r,!r.__f)){r.__f=!0;var c=r.shouldComponentUpdate;r.shouldComponentUpdate=function(n,t,r){var u=this.__H;if(!u)return!0;var i=!1,f=this.props!=n;if(u.__.some(function(n){n.__N&&(i=!0,o(n.__[0],n.__N[0])||(f=!0))}),c){var e=c.call(this,n,t,r);return i?e||f:e}return!i||f}}return f.__}function A(n,u){var i=y(t++,3);!a.__s&&E(i.__H,u)&&(i.__P=!0,i.__=n,i.u=u,r.__H.__h.push(i))}function F(n,u){var i=y(t++,4);!a.__s&&E(i.__H,u)&&(i.__P=!1,i.__=n,i.u=u,r.__h.push(i))}function T(n){return f=5,b(function(){return{current:n}},[])}function q(n,t,r){f=6,F(function(){if("function"==typeof n){var r=n(t());return function(){n(null),r&&"function"==typeof r&&r()}}if(n)return n.current=t(),function(){return n.current=null}},null==r?r:r.concat(n))}function b(n,r){var u=y(t++,7);return E(u.__H,r)&&(u.__=n(),u.__H=r),u.__}function j(n,t){return f=8,b(function(){return n},t)}function w(n){var u=r.context[n.__c],i=y(t++,9);return i.c=n,u?(null==i.__&&(i.__=!0,u.sub(r)),u.props.value):n.__}function x(n,t){a.useDebugValue&&a.useDebugValue(t?t(n):n)}function O(n){var u=y(t++,10),i=d();return u.__=n,r.componentDidCatch||(r.componentDidCatch=function(n,t){u.__&&u.__(n,t),i[1](n)}),[i[0],function(){i[1](void 0)}]}function P(){var n=y(t++,11);if(!n.__){for(var u=r.__v;!u.__m&&u.__;)u=u.__;var i=u.__m||(u.__m=[0,0]);n.__="P"+i[0]+"-"+i[1]++}return n.__}function g(){var n;do{for(;n=e.shift();)try{C(n)}catch(t){a.__e(t,{__:(n=n.__P)&&n.__v})}for(;n=c.shift();){var t=n.__H;if(n.__P&&t)try{t.__h.some(C),t.__h.some(D),t.__h=[]}catch(r){t.__h=[],a.__e(r,n.__v)}}}while(e.length)}a.__b=function(n){r=null,v&&v(n)},a.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),p&&p(n,t)},a.__r=function(n){l&&l(n),t=0;var i=(r=n.__c).__H;i&&(u==r?r.__h=[]:(i.__h.some(C),i.__h.some(D),t=0),i.__h=[],i.__.some(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0})),u=r},a.diffed=function(n){m&&m(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&B(c.push(t)),t.__H.__.some(function(n){n.u&&(n.__H=n.u)})),u=r=null},a.__c=function(n,t){t.some(function(n){try{n.__h.some(C),n.__h=n.__h.filter(function(n){return!n.__||D(n)})}catch(r){t.some(function(n){n.__h&&(n.__h=[])}),t=[],a.__e(r,n.__v)}}),s&&s(n,t)},a.unmount=function(n){h&&h(n);var t,r,u=n.__c;u&&u.__H&&(u.__H.__.some(function(u){try{if(u.__P&&u.__c){if(void 0===r){for(r=n.__;r&&(!r.__c||!r.__c.__P);)r=r.__;r=r&&r.__c}u.__P=r,B(e.push(u))}else C(u)}catch(n){t=n}}),u.__H=void 0,t&&a.__e(t,u.__v))};var k="function"==typeof requestAnimationFrame;function z(n){var t,r=function(){clearTimeout(u),k&&cancelAnimationFrame(t),setTimeout(n)},u=setTimeout(r,35);k&&(t=requestAnimationFrame(r))}function B(n){1!=n&&i==a.requestAnimationFrame||((i=a.requestAnimationFrame)||z)(g)}function C(n){var t=r,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),r=t}function D(n){var t=r;n.__c=n.__(),r=t}function E(n,t){return!n||n.length!=t.length||t.some(function(t,r){return!o(t,n[r])})}function G(n,t){return"function"==typeof t?t(n):t}export{j as useCallback,w as useContext,x as useDebugValue,A as useEffect,O as useErrorBoundary,P as useId,q as useImperativeHandle,F as useLayoutEffect,b as useMemo,_ as useReducer,T as useRef,d as useState};
|
||||
//# sourceMappingURL=hooks.mjs.map
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import{options as r,Fragment as t}from"preact";export{Fragment}from"preact";var e=/["&<]/;function n(r){if(!r.length||!e.test(r))return r;for(var t=0,n=0,o="",f="";n<r.length;n++){switch(r.charCodeAt(n)){case 34:f=""";break;case 38:f="&";break;case 60:f="<";break;default:continue}n!=t&&(o+=r.slice(t,n)),o+=f,t=n+1}return n!=t&&(o+=r.slice(t,n)),o}var o=0,f=Array.isArray;function u(t,e,n,f,u,i){e||(e={});var a,c,l=e;if("ref"in l&&"function"!=typeof t)for(c in l={},e)"ref"==c?a=e[c]:l[c]=e[c];var p={type:t,props:l,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--o,__i:-1,__u:0};return(u||i)&&(p.__source=u,p.__self=i),r.vnode&&r.vnode(p),p}function i(r){var e=u(t,{tpl:r,exprs:[].slice.call(arguments,1)});return e.key=e.__v,e}var a={},c=/[A-Z]/g;function l(t,e){if(r.attr){var o=r.attr(t,e);if("string"==typeof o)return o}if(e=function(r){return null!=r&&"object"==typeof r&&"function"==typeof r.valueOf?r.valueOf():r}(e),"ref"==t||"key"==t)return"";if("style"==t&&"object"==typeof e){var f="";for(var u in e){var i=e[u];null!=i&&""!==i&&(f=f+("-"==u[0]?u:a[u]||(a[u]=u.replace(c,"-$&").toLowerCase()))+":"+i+";")}return t+'="'+n(f)+'"'}return null==e||!1===e||"function"==typeof e||"object"==typeof e?"":!0===e?t:t+'="'+n(""+e)+'"'}function p(r){if(null==r||"boolean"==typeof r||"function"==typeof r)return null;if("object"==typeof r){if(void 0===r.constructor)return r;if(f(r)){for(var t=0;t<r.length;t++)r[t]=p(r[t]);return r}}return n(""+r)}export{u as jsx,l as jsxAttr,u as jsxDEV,p as jsxEscape,i as jsxTemplate,u as jsxs};
|
||||
//# sourceMappingURL=jsxRuntime.mjs.map
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
var n,t,i,r,u,f,o,e,l,c,a,s,h={},p=[],v=/^m(i|n|o|s|text|space)$/,y=Array.isArray,d=p.slice,w=Object.assign;function _(n){n&&n.parentNode&&n.remove()}function g(n,t,i){var r,u,f,o={},e=arguments.length;for(f in t)"key"==f?r=t[f]:"ref"==f&&"function"!=typeof n?u=t[f]:o[f]=t[f];return e>2&&(o.children=e>3?d.call(arguments,2):i),b(n,o,r,u,null)}function k(n,t,i){var r,u,f,o=w({},n.props),e=arguments.length;for(f in t)"key"==f?r=t[f]:"ref"==f&&"function"!=typeof n.type?u=t[f]:o[f]=t[f];return e>2&&(o.children=e>3?d.call(arguments,2):i),b(n.type,o,void 0!==r?r:n.key,void 0!==u?u:n.ref,null)}function b(i,r,u,f,o){var e={type:i,props:r,key:u,ref:f,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o||++t,__i:-1,__u:0};return!o&&n.vnode&&n.vnode(e),e}function m(){return{current:null}}function M(n){return n.children}function $(n,t){this.props=n,this.context=t,this.__g=0}function x(n,t){if(null==t)return n.__?x(n.__,n.__i+1):null;for(var i;t<n.__k.length;t++)if((i=n.__k[t])&&i.__e)return i.__e;return"function"!=typeof n.type||n.props.__P?null:x(n)}function S(n){if((n=n.__)&&n.__c&&!n.props.__P)return n.__e=null,n.__k.some(function(t){return t&&(n.__e=t.__e)}),S(n)}function C(t){(8&t.__g||!(t.__g|=8)||!r.push(t)||f++)&&u==n.debounceRendering||((u=n.debounceRendering)||queueMicrotask)(j)}function j(){var t,i,u,e,l,c,a,s,h;try{for(i=1;r.length;)r.length>i&&r.sort(o),t=r.shift(),i=r.length,8&t.__g&&(e=void 0,l=void 0,c=(l=(u=t).__v).__e,a=[],s=[],(h=u.__P)&&((e=w({constructor:void 0},l)).__v=l.__v+1,n.vnode&&n.vnode(e),N(h,e,l,u.__n,h.namespaceURI,32&l.__u?[c]:null,a,c||x(l),32&l.__u,s),e.__v=l.__v,e.__.__k[e.__i]=e,z(a,e,s),l.__=l.__e=null,e.__e!=c&&S(e)))}finally{r.length=f=0}}function L(n,t,i,r,u,f,o,e,l,c,a){var s,v,y,d,w,_,g=r.__k||p,k=t.length;for(l=H(i,t,g,l,k),s=0;s<k;s++)null!=(y=i.__k[s])&&(v=~y.__i&&g[y.__i]||h,y.__i=s,_=N(n,y,v,u,f,o,e,l,c,a),d=y.__e,(v.ref!=y.ref||8&v.__u)&&(v.ref&&D(v.ref,null,y,v),y.ref&&a.push(y.ref,y.__c||d,y)),w=w||d,4&y.__u?(l=I(y,l,n,!v.__v),v.__e&&(v.__e=null)):"function"==typeof y.type&&void 0!==_?l=_:d&&(l=d.nextSibling),y.__u&=-7);return i.__e=w,l}function H(n,t,i,r,u){var f,o,e,l,c,a,s,h,p,v,d=i.length,w=d,_=0,g=!1,k=n.__k=Array(u);for(f=0;f<u;f++)null!=(o=t[f])&&"boolean"!=typeof o&&"function"!=typeof o?("object"!=typeof o||o.constructor==String?o=k[f]=b(null,o):y(o)?o=k[f]=b(M,{children:o}):void 0===o.constructor&&o.__b?o=k[f]=b(o.type,o.props,o.key,o.ref,o.__v):k[f]=o,l=f+_,o.__=n,o.__b=n.__b+1,e=null,~(c=o.__i=O(o,i,l,w))&&(w--,(e=i[c])&&(e.__u|=2)),e&&e.__v?(o.__u|=2,c==l-1?_--:c==l+1?_++:c!=l&&(c>l?_--:_++,g=!0)):(~c||(u>d?_--:u<d&&_++),"function"!=typeof o.type&&(o.__u|=4))):k[f]=null;if(g){for(a=[],s=[],f=0;f<u;f++)if((o=k[f])&&2&o.__u){for(h=0,p=a.length;h<p;)a[v=h+p>>1]<o.__i?h=v+1:p=v;a[h]=o.__i,s[f]=h+1}for(_=a.length;f--;)s[f]&&(s[f]==_?_--:k[f].__u|=4)}if(w)for(f=0;f<d;f++)!(e=i[f])||2&e.__u||(e.__e==r&&(r=x(e)),E(e,e));return r}function I(n,t,i,r){var u,f,o;if("function"==typeof n.type){if(n.props.__P)return t;if(u=n.__k)for(f=0;f<u.length;f++)u[f]&&(u[f].__=n,t=I(u[f],t,i,!1));return t}for(t&&!t.parentNode&&(t=x(n))&&!t.parentNode&&(t=null),o=t;o&&8==o.nodeType;)o=o.nextSibling;for(n.__e!=o&&(!r&&i.moveBefore&&n.__e.parentNode?i.moveBefore(n.__e,t):i.insertBefore(n.__e,t||null)),t=n.__e;(t=t&&t.nextSibling)&&8==t.nodeType;);return t}function A(n,t){return t=t||[],null!=n&&"boolean"!=typeof n&&(y(n)?n.some(function(n){A(n,t)}):t.push(n)),t}function O(n,t,i,r){var u,f,o,e=n.key,l=n.type,c=t[i],a=c&&!(2&c.__u);if(null===c&&null==e||a&&e==c.key&&l==c.type)return i;if(r>(a?1:0))for(u=i-1,f=i+1;u>=0||f<t.length;)if((c=t[o=u>=0?u--:f++])&&!(2&c.__u)&&e==c.key&&l==c.type)return o;return-1}function P(n,t,i){null==i&&(i=""),"-"==t[0]?n.setProperty(t,i):n[t]=i}function T(n,t,i,r,u){var f,o;n:if("style"==t)if("string"==typeof i)n.style.cssText=i;else{if("string"==typeof r&&(n.style.cssText=r=""),r)for(t in r)i&&t in i||P(n.style,t,"");if(i)for(t in i)r&&i[t]==r[t]||P(n.style,t,i[t])}else if("o"==t[0]&&"n"==t[1])(n.__e||(n.__e={}))[t]=i,i&&r||(o=a[t]||(a[t]=q(t)),(n.__a||(n.__a={}))[t]=c,f=t!=(t=t.replace(l,"$1")),(t=t.slice(2))[0]<"a"&&(t=t.toLowerCase()),i?n.addEventListener(t,o,f):n.removeEventListener(t,o,f));else{if("http://www.w3.org/2000/svg"==u)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in n)try{n[t]=null==i?"":i;break n}catch(n){}"function"==typeof i||(null==i||!1===i&&"-"!=t[4]?n.removeAttribute(t):n.setAttribute(t,"popover"==t&&1==i?"":i))}}function q(t){return function(i){if(this.__e){var r=this.__e[t];if(null==i[e])i[e]=c++;else if(i[e]<this.__a[t])return;return r(n.event?n.event(i):i)}}}function N(t,i,r,u,f,o,e,l,c,a){var s,h,v,d,g,k,b,m,S,C,j,H,I,A,O,P,T,q,N,z,D=i.type;if(void 0!==i.constructor)return null;if(128&r.__u&&(c=32&r.__u,s=r.__c.__z)){if(i.__u|=c,h=o=[],8==s.nodeType)for(v=1,d=s.Line truncated
|
||||
//# sourceMappingURL=preact.mjs.map
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2022-present Preact Team
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1 @@
|
||||
const i=Symbol.for("preact-signals");function t(){if(e>1){e--;return}let i,t=!1;!function(){let i=f;f=void 0;while(void 0!==i){const t=i.S;if(t.v===i.v)for(let n=t.t;void 0!==n;n=n.x)if(n.i===i.i)n.i=t.i;i=i.o}}();while(void 0!==h){let n=h;h=void 0;c++;while(void 0!==n){const o=n.u;n.u=void 0;n.f&=-3;if(!(8&n.f)&&w(n))try{n.c()}catch(n){if(!t){i=n;t=!0}}n=o}}c=0;e--;if(t)throw i}function n(i){if(e>0)return i();d=++u;e++;try{return i()}finally{t()}}let o,s,h;function r(i){const t=o,n=s;o=void 0;s=void 0;try{return i()}finally{o=t;s=n}}let f,e=0,c=0,u=0,d=0,v=0;function l(i){if(void 0===o)return;let t=i.n;if(void 0===t||t.t!==o){t={i:0,S:i,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:t};if(void 0!==o.s)o.s.n=t;o.s=t;i.n=t;if(32&o.f)i.S(t);return t}else if(-1===t.i){t.i=0;if(void 0!==t.n){t.n.p=t.p;if(void 0!==t.p)t.p.n=t.n;t.p=o.s;t.n=void 0;o.s.n=t;o.s=t}return t}}function a(i,t){this.v=i;this.i=0;this.n=void 0;this.t=void 0;this.l=0;this.W=null==t?void 0:t.watched;this.Z=null==t?void 0:t.unwatched;this.name=null==t?void 0:t.name}a.prototype.brand=i;a.prototype.h=function(){return!0};a.prototype.S=function(i){const t=this.t;if(t!==i&&void 0===i.e){i.x=t;this.t=i;if(void 0!==t)t.e=i;else r(()=>{var i;null==(i=this.W)||i.call(this)})}};a.prototype.U=function(i){if(void 0!==this.t){const t=i.e,n=i.x;if(void 0!==t){t.x=n;i.e=void 0}if(void 0!==n){n.e=t;i.x=void 0}if(i===this.t){this.t=n;if(void 0===n)r(()=>{var i;null==(i=this.Z)||i.call(this)})}}};a.prototype.subscribe=function(i){return j(()=>{const t=this.value;r(()=>i(t))},{name:"sub"})};a.prototype.valueOf=function(){return this.value};a.prototype.toString=function(){return this.value+""};a.prototype.toJSON=function(){return this.value};a.prototype.peek=function(){return r(()=>this.value)};Object.defineProperty(a.prototype,"value",{get(){const i=l(this);if(void 0!==i)i.i=this.i;return this.v},set(i){if(i!==this.v){if(c>100)throw new Error("Cycle detected");!function(i){if(0!==e&&0===c)if(i.l!==d){i.l=d;f={S:i,v:i.v,i:i.i,o:f}}}(this);this.v=i;this.i++;v++;e++;try{for(let i=this.t;void 0!==i;i=i.x)i.t.N()}finally{t()}}}});function y(i,t){return new a(i,t)}function w(i){for(let t=i.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return!0;return!1}function _(i){for(let t=i.s;void 0!==t;t=t.n){const n=t.S.n;if(void 0!==n)t.r=n;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break}}}function b(i){let t,n=i.s;while(void 0!==n){const i=n.p;if(-1===n.i){n.S.U(n);if(void 0!==i)i.n=n.n;if(void 0!==n.n)n.n.p=i}else t=n;n.S.n=n.r;if(void 0!==n.r)n.r=void 0;n=i}i.s=t}function p(i,t){a.call(this,void 0,t);this.x=i;this.s=void 0;this.g=v-1;this.f=4}p.prototype=new a;p.prototype.h=function(){this.f&=-3;if(1&this.f)return!1;if(32==(36&this.f))return!0;this.f&=-5;if(this.g===v)return!0;this.g=v;this.f|=1;if(this.i>0&&!w(this)){this.f&=-2;return!0}const i=o;try{_(this);o=this;const i=this.x();if(16&this.f||this.v!==i||0===this.i){this.v=i;this.f&=-17;this.i++}}catch(i){this.v=i;this.f|=16;this.i++}o=i;b(this);this.f&=-2;return!0};p.prototype.S=function(i){if(void 0===this.t){this.f|=36;for(let i=this.s;void 0!==i;i=i.n)i.S.S(i)}a.prototype.S.call(this,i)};p.prototype.U=function(i){if(void 0!==this.t){a.prototype.U.call(this,i);if(void 0===this.t){this.f&=-33;for(let i=this.s;void 0!==i;i=i.n)i.S.U(i)}}};p.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(let i=this.t;void 0!==i;i=i.x)i.t.N()}};Object.defineProperty(p.prototype,"value",{get(){if(1&this.f)throw new Error("Cycle detected");const i=l(this);this.h();if(void 0!==i)i.i=this.i;if(16&this.f)throw this.v;return this.v}});function g(i,t){return new p(i,t)}function S(i){const n=i.m;i.m=void 0;if("function"==typeof n){e++;const s=o;o=void 0;try{n()}catch(t){i.f&=-2;i.f|=8;m(i);throw t}finally{o=s;t()}}}function m(i){for(let t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;S(i)}function x(i){if(o!==this)throw new Error("Out-of-order effect");b(this);o=i;this.f&=-2;if(8&this.f)m(this);t()}function E(i,t){this.x=i;this.m=void 0;this.s=void 0;this.u=void 0;this.f=32;this.name=null==t?void 0:t.name;if(s)s.push(this)}E.prototype.c=function(){const i=this.S();try{if(8&this.f)return;if(void 0===this.x)return;const t=this.x();if("function"==typeof t)this.m=t}finally{i()}};E.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1;this.f&=-9;S(this);_(this);e++;const i=o;o=this;return x.bind(this,i)};E.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.u=h;h=this}};E.prototype.d=function(){this.f|=8;if(!(1&this.f))m(this)};E.prototype.dispose=function(){this.d()};function j(i,t){const n=new E(i,t);try{n.c()}catch(i){n.d();throw i}const o=n.d.bind(n);o[Symbol.dispose]=o;return o}function C(i){return function(...t){return n(()=>r(()=>i.apply(this,t)))}}const O=i=>{for(const t in i){const n=i[t];if("function"==typeof n)i[t]=C(n);else if("object"==typeof n&&null!==n&&!("brand"in n))O(n)}};function k(i){return function(...t){let n,o;const h=function(){let i=s;s=[];return function(){let t=s;if(s&&i)i=i.concat(sLine truncated
|
||||
+1
@@ -0,0 +1 @@
|
||||
import{Component as t,options as i,isValidElement as n,Fragment as e}from"preact";import{useMemo as o,useRef as f,useEffect as r}from"preact/hooks";import{effect as u,Signal as c,computed as s,signal as l,batch as a}from"@preact/signals-core";export{Signal,action,batch,computed,createModel,effect,signal,untracked}from"@preact/signals-core";const h="undefined"!=typeof window&&!!window.__PREACT_SIGNALS_DEVTOOLS__;let d,p,m,v=[],_=[];u(function(){d=this.N})();function g(t,n){i[t]=n.bind(null,i[t]||(()=>{}))}function b(t){if(m){const t=m;m=void 0;t()}m=t&&t.S()}function y({data:t}){const i=useSignal(t);i.name="ReactiveDom";i.value=t;const[e,f]=o(()=>{let t=this,e=this.__v;while(e=e.__)if(e.__c){e.__c.__$f|=4;break}const o=s(()=>{let t=i.value.value;return 0===t?0:!0===t?"":t||""}),f=s(()=>!Array.isArray(o.value)&&!n(o.value)),r=u(function(){this.N=F;if(f.value){const i=o.value;if(t.__v&&t.__v.__e&&3===t.__v.__e.nodeType)t.__v.__e.data=i}}),c=this.__$u.d;this.__$u.d=function(){r();c.call(this)};return[f,o]},[]);return e.value?f.peek():f.value}y.displayName="ReactiveTextNode";Object.defineProperties(c.prototype,{constructor:{configurable:!0,value:void 0},type:{configurable:!0,value:y},props:{configurable:!0,get(){const t=this;return{data:{get value(){return t.value}}}}},__b:{configurable:!0,value:1}});g("__b",(t,i)=>{b();p=void 0;if("string"==typeof i.type){let t,n=i.props;for(let e in n){if("children"===e)continue;let o=n[e];if(o instanceof c){if(!t)i.__np=t={};t[e]=o;n[e]=o.peek()}}}t(i)});g("__r",(t,i)=>{t(i);if(i.type!==e){b();let t,n=i.__c;if(n){n.__$f&=-2;t=n.__$u;if(void 0===t)n.__$u=t=function(t,i){let n;u(function(){n=this},{name:i});n.c=t;return n}(function(t){return function(){var i;if(h)null==(i=this.y)||i.call(this);t.__$f|=1;t.setState({})}}(n),"function"==typeof i.type?i.type.displayName||i.type.name:"")}p=n;b(t)}});g("__e",(t,i,n,e)=>{b();p=void 0;t(i,n,e)});g("diffed",(t,i)=>{b();p=void 0;let n;if("string"==typeof i.type&&(n=i.__e)){let t=i.__np,e=i.props,o=n.U;if(o)for(let i in o){let n=o[i];if(!(void 0===n||t&&i in t)){n.d();o[i]=void 0}}if(t){if(!o){o={};n.U=o}for(let i in t){let f=o[i],r=t[i];if(void 0===f){f=w(n,i,r,e);o[i]=f}else f.o(r,e)}}}t(i)});function w(t,i,n,e){const o=i in t&&void 0===t.ownerSVGElement,f=l(n);return{o:(t,i)=>{f.value=t;e=i},d:u(function(){this.N=F;const n=f.value.value;if(e[i]!==n){e[i]=n;if(o)t[i]=n;else if(null!=n&&(!1!==n||"-"===i[4]))t.setAttribute(i,n);else t.removeAttribute(i)}})}}g("unmount",(t,i)=>{if("string"==typeof i.type){let t=i.__e;if(t){const i=t.U;if(i){t.U=void 0;for(let t in i){let n=i[t];if(n)n.d()}}}let n=i.__np;if(n){let t=i.props;for(let i in n)t[i]=n[i]}i.__np=void 0}else{let t=i.__c;if(t){t.__$f|=8;const i=t.__$u;if(i){t.__$u=void 0;i.d()}}}t(i)});g("__h",(t,i,n,e)=>{if(e<3)i.__$f|=2;t(i,n,e)});t.prototype.shouldComponentUpdate=function(t,i){if(this.__R)return!0;const n=this.__$u,e=n&&void 0!==n.s;for(let t in i)return!0;if(this.__f||"boolean"==typeof this.u&&!0===this.u){const t=2&this.__$f;if(!(e||t||4&this.__$f))return!0;if(1&this.__$f)return!0}else{if(!(e||4&this.__$f))return!0;if(3&this.__$f)return!0}for(let i in t)if("__source"!==i&&t[i]!==this.props[i])return!0;for(let i in this.props)if(!(i in t))return!0;return!1};function useSignal(t,i){return o(()=>l(t,i),[])}function useComputed(t,i){const n=f(t);n.current=t;p.__$f|=4;return o(()=>s(()=>n.current(),i),[])}const k="undefined"==typeof requestAnimationFrame?setTimeout:function(t){const i=()=>{clearTimeout(n);cancelAnimationFrame(e);t()},n=setTimeout(i,35),e=requestAnimationFrame(i)},q=t=>{queueMicrotask(()=>{queueMicrotask(t)})};function A(){a(()=>{let t;while(t=v.shift())d.call(t)})}function T(){if(1===v.push(this))(i.requestAnimationFrame||k)(A)}function x(){a(()=>{let t;while(t=_.shift())d.call(t)})}function F(){if(1===_.push(this))(i.requestAnimationFrame||q)(x)}function useSignalEffect(t,i){const n=f(t);n.current=t;const e=p;r(()=>u(function(){this.N=T;if(!(e&&8&e.__$f))return n.current()},i),[])}function M(t){const i=o(()=>t(),[]);r(()=>i[Symbol.dispose],[i]);return i}export{useComputed,M as useModel,useSignal,useSignalEffect};//# sourceMappingURL=signals.mjs.map
|
||||
@@ -0,0 +1,32 @@
|
||||
// The moon viewport: the classic client's three.js scene (scene.js, terrain.js), shown
|
||||
// for the selected moon. Its element is rendered once and never touched by Preact again.
|
||||
|
||||
import { useRef, useEffect } from "preact/hooks";
|
||||
import { effect } from "@preact/signals";
|
||||
import { memo } from "./memo.js";
|
||||
import { shown } from "./session.js";
|
||||
import { startViewport } from "./scene.js";
|
||||
|
||||
export const Viewport = memo(function Viewport() {
|
||||
const ref = useRef(null);
|
||||
useEffect(() => {
|
||||
const view = startViewport(ref.current);
|
||||
let last = "";
|
||||
const stop = effect(() => {
|
||||
const id = shown.value?.moon?.id ?? "";
|
||||
if (id && id !== last) {
|
||||
last = id;
|
||||
view.show(id);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
stop();
|
||||
view.dispose();
|
||||
};
|
||||
}, []);
|
||||
return (
|
||||
<figure id="viewport" class="viewport" ref={ref}>
|
||||
<figcaption class="cap">Orbital scan · drag to rotate</figcaption>
|
||||
</figure>
|
||||
);
|
||||
});
|
||||
@@ -5,7 +5,7 @@
|
||||
// bits of the DOM; after it settles we read them again and play effects for the
|
||||
// difference: count-ups, floating numbers, sparks and particles flying to the wallet,
|
||||
// scan sweeps on what was bought, a pulse on new drills and on Claim buttons as their
|
||||
// drills finish.
|
||||
// drills finish. The Preact client (web/app/fx.js) reuses the exported pieces.
|
||||
|
||||
import * as sfx from "./sfx.js";
|
||||
import { updateEstimate, setHero } from "./market.js";
|
||||
@@ -379,14 +379,14 @@ function gradient(i) {
|
||||
const currency = "₥";
|
||||
|
||||
// Same as formatMoney in views.go.
|
||||
function formatMoney(n) {
|
||||
export function formatMoney(n) {
|
||||
const v = Math.round(Math.abs(n) * 100) / 100;
|
||||
const [whole, frac] = v.toFixed(2).split(".");
|
||||
const f = frac.replace(/0+$/, "");
|
||||
return (n < 0 && v !== 0 ? "-" : "") + whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (f ? "." + f : "");
|
||||
}
|
||||
|
||||
function centerOf(el) {
|
||||
export function centerOf(el) {
|
||||
const r = el?.getBoundingClientRect() ?? { left: innerWidth / 2, top: innerHeight / 2, width: 0, height: 0 };
|
||||
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
||||
}
|
||||
@@ -422,7 +422,7 @@ function moonOut(id, row, delay) {
|
||||
}
|
||||
|
||||
// Restart a CSS animation class on an element.
|
||||
function mark(el, cls) {
|
||||
export function mark(el, cls) {
|
||||
if (!el) return;
|
||||
el.classList.remove(cls);
|
||||
void el.offsetWidth;
|
||||
@@ -490,7 +490,7 @@ function shake(at) {
|
||||
}
|
||||
|
||||
// A big number that pops out of a point and drifts up (dir -1) or down (dir 1).
|
||||
function floatText(text, x, y, color, delay = 0, big = false, dir = -1) {
|
||||
export function floatText(text, x, y, color, delay = 0, big = false, dir = -1) {
|
||||
const el = document.createElement("div");
|
||||
el.className = `fx-float${big ? " fx-float-big" : ""}`;
|
||||
el.textContent = text;
|
||||
@@ -643,7 +643,7 @@ export function burst(x, y, colors, n, scale = 1) {
|
||||
}
|
||||
|
||||
// Glowing motes that stream along a curve into a target, calling onArrive with the first.
|
||||
function stream(from, to, color, n, delay, onArrive) {
|
||||
export function stream(from, to, color, n, delay, onArrive) {
|
||||
if (reduced()) return onArrive();
|
||||
ensureCanvas();
|
||||
let arrived = false;
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
{{/* The Preact client at /app (web/app, built by esbuild into web/static/app). Same look
|
||||
(app.css) and the classic client's scene, effects and sounds, loaded as modules. */}}
|
||||
{{define "spa"}}{{template "head"}}
|
||||
<link rel="stylesheet" href="/static/app/app.css">
|
||||
<script type="importmap">
|
||||
{"imports": {
|
||||
"three": "/static/vendor/three/three.module.min.js",
|
||||
"three/addons/": "/static/vendor/three/addons/"
|
||||
}}
|
||||
</script>
|
||||
<script type="module" src="/static/app/app.js"></script>
|
||||
</head>
|
||||
<body class="pa">
|
||||
<div id="root"></div>
|
||||
</body>
|
||||
</html>
|
||||
{{end}}
|
||||
Reference in new issue
Block a user