From 7fbe4c324de05b3823f497c59c7bf8704e02db06 Mon Sep 17 00:00:00 2001 From: Denis Denisov Date: Sun, 13 Sep 2026 12:41:47 +0300 Subject: [PATCH] =?UTF-8?q?=D0=98=D0=B3=D1=80=D0=B0=20=D0=B7=D0=B0=D0=BF?= =?UTF-8?q?=D1=83=D1=81=D0=BA=D0=B0=D0=B5=D1=82=D1=81=D1=8F=20=D0=B8=20?= =?UTF-8?q?=D0=B8=D0=B3=D1=80=D0=B0=D0=B5=D1=82=D1=81=D1=8F:=20=D1=82?= =?UTF-8?q?=D1=80=D0=B8=20=D1=80=D0=B0=D0=BD=D1=82=D0=B0=D0=B9=D0=BC-?= =?UTF-8?q?=D0=B1=D0=B0=D0=B3=D0=B0=20=D0=B8=20=D0=B0=D0=B4=D0=B0=D0=BF?= =?UTF-8?q?=D1=82=D0=B8=D0=B2=D0=BD=D0=B0=D1=8F=20=D0=B2=D1=91=D1=80=D1=81?= =?UTF-8?q?=D1=82=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Проверено вживую в Chrome: лобби -> матч -> бот ходит -> результат -> статистика в лобби. Полный матч отыгран, оба исхода видел. Баги, которые собирались и типизировались, но падали только в рантайме: 1. Canvas не менял размер под экран. Своего cc.Widget у него не было, а alignCanvasWithScreen правит только камеру. Canvas оставался 1280x720, и все растянутые по нему дети — тоже. 2. [...map.values()] превращается сборкой в [].concat(map.values()), а concat не разворачивает итератор, а кладёт его одним элементом. Отсюда "view.cancelAnimations is not a function" на первой же уборке карт. Теперь Array.from. 3. Рубашка козыря рисовалась поверх колоды, а не под ней. Вёрстка переделана под требование UI.md (4:3 .. 21:9): - fitWidth даёт постоянную ширину, но не высоту: на 4:3 видно только ±720 юнитов. Кнопка "Leave" на y=840 и низ руки на -860 были за экраном именно там, где это важнее всего - рука и панель действий считаются от нижней границы экрана, "Leave" прибит виджетом к левому верхнему углу - стол — один ряд до шести карт вместо двух рядов по три: экономит ~215 юнитов высоты, которых на 4:3 нет. Ряд центрируется по тем картам, что реально на столе - затемнение под окном результата рисуется непрозрачным спрайтом: тонировать и без того полупрозрачный спрайт почти ничего не даёт Инструменты: - npm run serve — отдаёт сборку и роут /_aspects: игра в трёх фиксированных iframe-ах 4:3 / 16:9 / 21:9. Движок подгоняет себя под окно, поэтому iframe — единственный простой способ увидеть вёрстку в форме, которой окно не имеет - npm run check:spreads — ловит спред неитерируемого в массив - npm run check — чистота core, спреды, сцены, типы, тесты Co-Authored-By: Claude Opus 5 --- assets/art/ui/fill.png | Bin 0 -> 93 bytes assets/art/ui/fill.png.meta | 134 ++++++++++++++++ assets/scenes/loader.scene | 55 +++++-- assets/scenes/lobby.scene | 223 ++++++++++++++++++--------- assets/scripts/ui/common/Theme.ts | 66 +++++--- assets/scripts/ui/game/GameScreen.ts | 81 +++++++--- docs/DECISIONS.md | 31 ++++ docs/PLAN.md | 26 ++-- docs/TECHNICAL.md | 41 +++-- package.json | 4 +- scripts/build-art.mjs | 12 ++ scripts/check-scenes.mjs | 23 +++ scripts/check-spreads.mjs | 64 ++++++++ scripts/serve-build.mjs | 102 ++++++++++++ 14 files changed, 710 insertions(+), 152 deletions(-) create mode 100644 assets/art/ui/fill.png create mode 100644 assets/art/ui/fill.png.meta create mode 100644 scripts/check-spreads.mjs create mode 100644 scripts/serve-build.mjs diff --git a/assets/art/ui/fill.png b/assets/art/ui/fill.png new file mode 100644 index 0000000000000000000000000000000000000000..5bfbaf4efd7204f2bf54615fd5ca504dda5a8b0f GIT binary patch literal 93 zcmeAS@N?(olHy`uVBq!ia0vp^93afW1|*O0@9PFqoCO|{#S9EO-XP4l)OOlRpdi1e mi(`ny<>Vj!3 void) | null = null; onQuitRequested: (() => void) | null = null; @@ -145,7 +148,12 @@ export class GameScreen extends Component { /** Releases every card node and forgets the match. Safe to call twice. */ teardown(): void { this.unscheduleAllCallbacks(); - for (const view of [...this._views.values(), ...this._anonymous]) { + // Array.from, not [...map.values()]. The build transpiles array spread + // to [].concat(...), which appends a Map iterator as a single element + // instead of expanding it — so the loop would run once over the iterator + // itself. See docs/DECISIONS.md. + const live = Array.from(this._views.values()).concat(this._anonymous); + for (const view of live) { view.cancelAnimations(); this._recycle(view); } @@ -289,6 +297,13 @@ export class GameScreen extends Component { // Rendering // ----------------------------------------------------------------------- + /** Half the canvas height, which is how far the layout may reach from centre. */ + private _halfHeight(): number { + const transform = this.node.getComponent(UITransform); + const height = transform && transform.height > 0 ? transform.height : Layout.designHeight; + return height / 2; + } + /** Lays the whole table out from the current state, tweening over `duration`. */ render(duration: number): void { const match = this._match; @@ -298,16 +313,23 @@ export class GameScreen extends Component { const state = match.state; const view = match.viewFor(HUMAN); const live = new Set(); + const anchors = bottomAnchors(this._halfHeight()); - // Trump card, lying under the deck. + this._layOutHud(anchors.actionBarY); + + // The trump card lies face up under the draw pile, turned sideways so the + // suit shows. _place lifts whatever it touches to the top of the layer, + // so it is pushed back down afterwards. if (state.deck.length > 0) { live.add(state.trumpCard); this._place(state.trumpCard, true, - v3(Layout.region.trump.x, Layout.region.trump.y, 0), 0.62, 90, duration); + v3(Layout.trump.x, Layout.trump.y, 0), Layout.tableCardScale, 90, duration); + this._views.get(state.trumpCard)?.node.setSiblingIndex(0); } - // The player's hand: a straight row, tightened as it grows. - const hand = [...view.hand].sort(byTrumpThenRank(state.trumpSuit)); + // The player's hand: a straight row, tightened as it grows, and sitting + // against the bottom edge wherever that happens to be. + const hand = view.hand.slice().sort(byTrumpThenRank(state.trumpSuit)); const step = Math.min( Layout.handStep, hand.length > 1 ? (Layout.handMaxWidth - Layout.cardWidth) / (hand.length - 1) : Layout.handStep, @@ -317,15 +339,13 @@ export class GameScreen extends Component { live.add(card); const lifted = card === this._selected ? Layout.handLift : 0; this._place(card, true, - v3(handLeft + i * step, Layout.region.playerHandY + lifted, 0), 1, 0, duration); + v3(handLeft + i * step, anchors.handY + lifted, 0), 1, 0, duration); }); - // The table: attacking cards with whatever beat them, three to a row. + // The table: one centred row of attacking cards, each with whatever beat it. state.table.forEach((slot, i) => { - const column = i % 3; - const row = Math.floor(i / 3); - const x = (column - 1) * Layout.region.tableColumnStep; - const y = Layout.region.tableTopY - row * Layout.region.tableRowStep; + const x = tableSlotX(i, state.table.length); + const y = Layout.tableY; live.add(slot.attack); this._place(slot.attack, true, v3(x, y, 0), Layout.tableCardScale, 0, duration); @@ -343,6 +363,20 @@ export class GameScreen extends Component { this._renderChrome(view.opponents[0]?.handSize ?? 0); } + /** + * Puts the scene's fixed furniture where this screen shape wants it. Doing it + * here rather than in the scene keeps one source of truth for the layout, and + * the action bar has to move with the hand anyway. + */ + private _layOutHud(actionBarY: number): void { + moveNodeY(this.actionBar, actionBarY); + moveNodeY(this.opponentLabel?.node ?? null, Layout.opponentLabelY); + moveNodeY(this.messageLabel?.node ?? null, Layout.messageY); + if (this.deckAnchor) { + this.deckAnchor.setPosition(Layout.deck.x, Layout.deckLabelY, 0); + } + } + /** Face-down nodes: a short stack for the deck, and the opponent's hand. */ private _renderAnonymous(deckSize: number, opponentHand: number, duration: number): void { // Three backs are enough to read as a pile; drawing twenty-four is waste. @@ -358,8 +392,8 @@ export class GameScreen extends Component { for (let i = 0; i < deckBacks; i++) { this._anonymous[i].moveTo( - v3(Layout.region.deck.x + i * 3, Layout.region.deck.y + i * 3, 0), - 0.62, 0, duration, + v3(Layout.deck.x + i * 3, Layout.deck.y + i * 3, 0), + Layout.tableCardScale, 0, duration, ); } @@ -367,7 +401,7 @@ export class GameScreen extends Component { const left = -step * (opponentHand - 1) / 2; for (let i = 0; i < opponentHand; i++) { this._anonymous[deckBacks + i].moveTo( - v3(left + i * step, Layout.region.opponentHandY, 0), + v3(left + i * step, Layout.opponentHandY, 0), Layout.opponentCardScale, 0, duration, ); } @@ -409,7 +443,7 @@ export class GameScreen extends Component { if (!view) { view = this._take(card, faceUp); // A card appearing for the first time slides out of the deck. - view.moveTo(v3(Layout.region.deck.x, Layout.region.deck.y, 0), 0.62, 0, 0); + view.moveTo(v3(Layout.deck.x, Layout.deck.y, 0), Layout.tableCardScale, 0, 0); this._views.set(card, view); } view.flipTo(faceUp); @@ -419,14 +453,15 @@ export class GameScreen extends Component { /** Cards that have left the visible table — they went to the discard or a hand. */ private _retireCardsNotIn(live: Set, duration: number): void { - for (const [card, view] of [...this._views]) { + // Array.from, not [...map] — see the note in teardown. + for (const [card, view] of Array.from(this._views.entries())) { if (live.has(card)) continue; this._views.delete(card); const goingToOpponent = !this._match?.state.discard.includes(card); const target = goingToOpponent - ? v3(0, Layout.region.opponentHandY, 0) - : v3(Layout.region.discard.x, Layout.region.discard.y, 0); + ? v3(0, Layout.opponentHandY, 0) + : v3(Layout.discard.x, Layout.discard.y, 0); view.moveTo(target, 0.4, 0, duration); view.flipTo(false); @@ -512,6 +547,12 @@ function setActive(node: Node | null, active: boolean): void { if (node) node.active = active; } +function moveNodeY(node: Node | null, y: number): void { + if (node && node.position.y !== y) { + node.setPosition(node.position.x, y, 0); + } +} + function setButton(button: Button | null, enabled: boolean): void { if (!button) return; button.node.active = enabled; diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 513277d..fd87756 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -171,3 +171,34 @@ every node authored through the editor tools had been left on the DEFAULT layer while the camera only renders UI_2D (see CODE_MODE_SETUP.md). A blank screen carries no information about which step failed, and a loader that can hang forever on an asset the lobby does not even need is a dead end for no reason. + +## 2026-09-13 · Presentation · The vertical layout follows the screen edges + +**Decision.** `Layout` holds fixed anchors only for things that live near the +centre, and every one of those is inside ±700. The player's hand and the action +bar are computed from the actual canvas height at render time (`bottomAnchors`), +and the Leave button is pinned to the top-left with a Widget. + +**Why.** `fitWidth` means the width is always 1080 units but the height is not: +a 4:3 phone sees 1440 units (±720) and a 21:9 phone sees 2520 (±1260). The first +version used fixed design coordinates, which put the Leave button at y = 840 and +the bottom of the hand at −860 — both off screen on a 4:3 phone, the very case +docs/UI.md asks for. The table is also a single row of up to six slots rather +than two rows of three, which buys back the ~215 units of height that 4:3 cannot +spare, and the row is centred on the cards actually in play so a lone attacking +card sits in the middle of the table. + +## 2026-09-13 · Build · Never array-spread anything that is not an array + +The build transpiles `[...a, ...b]` to `[].concat(a, b)`. That is right for +arrays, but `Array.prototype.concat` does not expand an arbitrary iterable — it +appends it as a single element. `[...this._views.values()]` therefore produced a +one-element array holding the Map iterator, and the first card ever recycled +threw `view.cancelAnimations is not a function`. + +**Decision.** Use `Array.from(...)` for anything that is not already an array, +and `npm run check:spreads` fails the build on `...x.values()`, `...x.keys()`, +`...x.entries()` and spreads of things named like a Map or Set. + +**Why.** It type-checks, it reads correctly, and it only fails at runtime on a +real build — exactly the kind of mistake a static check earns its keep on. diff --git a/docs/PLAN.md b/docs/PLAN.md index 4f1520e..c9bff26 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -80,21 +80,19 @@ progress. The Cocos layer only renders state and turns taps into actions. - [x] Return to lobby; start another match without a scene leak - [x] Leave-match button, which ends the match as a loss -### M8 — Responsive and touch pass `[~]` +### M8 — Responsive and touch pass `[x]` - [x] Fit-width canvas, safe-area root, widget-stretched background -- [x] Every interactive element authored at or above the 120-unit minimum +- [x] Every interactive element at or above the 120-unit minimum (buttons 330×140 and 560×150; hand cards expose ~128 units each) -- [x] Vertical positions kept inside the 4:3 crop -- [ ] **Blocked:** seen at the extreme aspect ratios. Needs a machine that can - actually run the build — see "What is and is not verified" in - [TECHNICAL.md](TECHNICAL.md) +- [x] Hand and action bar follow the bottom edge; Leave pinned to the top-left +- [x] Seen running at 4:3, 16:9 and 21:9 — `npm run serve` then `/_aspects` -### M9 — Build verification and hand-off `[~]` +### M9 — Build verification and hand-off `[x]` - [x] `web-mobile` build completes clean; command recorded in TECHNICAL.md - [x] Card art reaches the build and packs into a single 2048² atlas - [x] Every component reference in the scene verified populated -- [ ] **Blocked:** the build seen running. The browser in this environment falls - back to a software renderer that cannot start the engine's main loop +- [x] A full match played in a browser: deal, attack, defend, take, discard, + redraw, result overlay, statistics written and shown back in the lobby - [x] Android/iOS texture settings written up in TECHNICAL.md (they have to be applied once in the Inspector; they live in the `.meta` files) - [x] README @@ -105,9 +103,13 @@ progress. The Cocos layer only renders state and turns taps into actions. is off in both scenes, but the scene keeps its `_envmapHDR` reference and the builder follows it. The editor tool server cannot write a null reference; clearing the field in the Inspector by hand would do it. -- Nothing verifies the presentation layer automatically. The obvious next step is - a smoke test that boots the scene headlessly and asserts the card nodes land - where the layout says they should. +- Nothing verifies the presentation layer automatically. `npm run check:scenes` + and `npm run check:spreads` catch the two classes of mistake that have + actually bitten, but a smoke test that boots the scene and asserts card + positions would cover more. +- At 21:9 there is a lot of empty felt between the table and the hand. It reads + as roomy rather than broken, but the table could drift downwards on very tall + screens. ## Deliberately out of scope for iteration 1 diff --git a/docs/TECHNICAL.md b/docs/TECHNICAL.md index 6d5795b..22abb1c 100644 --- a/docs/TECHNICAL.md +++ b/docs/TECHNICAL.md @@ -241,19 +241,34 @@ The card atlas is the only texture where this matters — 2048×2048 uncompresse is 16 MB of video memory, and ASTC 6×6 brings that to roughly 1.2 MB. Do it before the first device build. -### What is and is not verified - -The rules, the bot and the save format are covered by `npm test` and are -verified. The presentation layer is verified only as far as this environment -allows: the project builds clean, every component reference in the scene is -populated, and all 37 card sprites pack into one 2048² texture. - -It has **not** been seen running. The browser available here falls back to a -software renderer that cannot start the Cocos main loop (`totalFrames` stays at -0), so no screenshot of the actual game was possible. To check it by eye, open -the project in Cocos Creator and press Preview, or serve `build/web-mobile` over -HTTP — it is a static folder and needs no server features: +### Looking at it ```bash -npx http-server build/web-mobile -p 8123 -c-1 +npm run serve ``` + +Serves `build/web-mobile` on http://localhost:8123, plus one route of its own: + +- `/_aspects` — the game in fixed-size iframes at 4:3, 16:9 and 21:9 portrait, + side by side. The engine resizes itself to fill whatever window it is in, so + an iframe is the only straightforward way to see the layout at a shape the + desktop window is not. +- `/_aspects?only=16:9&h=690` — one viewport, which boots much faster than three. + +The layout has been checked this way at all three ratios, and a full match +played through in the browser: deal, attack, defend, take, discard, redraw, +result overlay, and the statistics written and read back in the lobby. + +### Three traps this project has already fallen into + +All three build and type-check cleanly, look right in the editor, and fail only +at runtime. Each now has a guard; `npm run check` runs all of them. + +1. **Node layers.** `nodeCreate` puts nodes on DEFAULT; a Canvas camera renders + UI_2D only, so the build shows the camera's clear colour and nothing else. + The scene view renders every layer, so the editor looks fine. +2. **The Canvas needs its own Widget.** Without one the Canvas keeps the size it + was authored at and every widget-stretched child inherits it. + `alignCanvasWithScreen` does not do this — it only adjusts the camera. +3. **Array spread of a non-array.** The build turns `[...x]` into `[].concat(x)`, + which appends an iterator rather than expanding it. Use `Array.from`. diff --git a/package.json b/package.json index 5cd7a07..550ec1f 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,8 @@ "stats:bot": "vitest run --config vitest.stats.mts", "build:art": "node scripts/build-art.mjs", "check:scenes": "node scripts/check-scenes.mjs", - "check": "npm run check:core-purity && npm run check:scenes && npm run typecheck && npm test" + "check": "npm run check:core-purity && npm run check:spreads && npm run check:scenes && npm run typecheck && npm test", + "serve": "node scripts/serve-build.mjs", + "check:spreads": "node scripts/check-spreads.mjs" } } diff --git a/scripts/build-art.mjs b/scripts/build-art.mjs index f3676f4..455179f 100644 --- a/scripts/build-art.mjs +++ b/scripts/build-art.mjs @@ -96,6 +96,17 @@ function tableBackground() { `; } +/** + * A plain opaque square, used as a full-screen dimmer behind dialogs. It has to + * be fully opaque so that tinting it decides the darkness — tinting an already + * translucent sprite multiplies the two and barely darkens anything. + */ +function fill() { + return ` + +`; +} + /** Outline of a place where a card can go. Drawn under the table slots. */ function cardSlot() { return ` @@ -144,6 +155,7 @@ const DRAWINGS = { [`${CARDS_OUT}/card_back.png`]: cardBack(), [`${UI_OUT}/table_bg.png`]: tableBackground(), [`${UI_OUT}/card_slot.png`]: cardSlot(), + [`${UI_OUT}/fill.png`]: fill(), [`${UI_OUT}/panel.png`]: nineSlice({ fill: '#062718', fillOpacity: 0.88, stroke: '#2f7a52', strokeWidth: 4, radius: 34, }), diff --git a/scripts/check-scenes.mjs b/scripts/check-scenes.mjs index a9d00a6..24a830c 100644 --- a/scripts/check-scenes.mjs +++ b/scripts/check-scenes.mjs @@ -49,6 +49,8 @@ function checkLayers(path, objects) { } } +const ALIGN_ALL = 45; // top | bottom | left | right + function checkCanvas(path, objects) { const canvases = objects.filter((o) => o && o.__type__ === 'cc.Canvas'); if (path.endsWith('.scene') && canvases.length === 0) { @@ -58,6 +60,27 @@ function checkCanvas(path, objects) { if (!canvas._cameraComponent) { problems.push(`${path}: a Canvas has no camera assigned`); } + + // The Canvas node needs its own Widget stretched to all four edges. It + // is what keeps the Canvas the size of the screen; without it the Canvas + // keeps whatever size it was authored at (1280x720 by default) and every + // widget-stretched child inherits that wrong size. `alignCanvasWithScreen` + // does NOT do this — it only adjusts the camera. + const node = objects[canvas.node?.__id__]; + const components = (node?._components ?? []).map((ref) => objects[ref.__id__]); + const widget = components.find((c) => c && c.__type__ === 'cc.Widget'); + + if (!widget) { + problems.push( + `${path}: the Canvas node has no cc.Widget, so it will not resize ` + + `to the screen and every stretched child will be the wrong size`, + ); + } else if (widget._alignFlags !== ALIGN_ALL) { + problems.push( + `${path}: the Canvas Widget is not stretched to all four edges ` + + `(alignFlags ${widget._alignFlags}, expected ${ALIGN_ALL})`, + ); + } } } diff --git a/scripts/check-spreads.mjs b/scripts/check-spreads.mjs new file mode 100644 index 0000000..201e176 --- /dev/null +++ b/scripts/check-spreads.mjs @@ -0,0 +1,64 @@ +// Flags array-spread of things that are not arrays. +// +// npm run check:spreads +// +// The engine's build transpiles `[...a, ...b]` to `[].concat(a, b)`. That is +// correct for arrays, but `Array.prototype.concat` does NOT expand an arbitrary +// iterable — it appends it as a single element. So +// +// for (const view of [...this._views.values()]) // Map iterator +// +// silently loops once, over the iterator object itself, and every property +// access on it is undefined. It type-checks, it reads perfectly, and it only +// fails at runtime on a real build. That cost a debugging session; hence this +// check. Use `Array.from(...)` instead, which transpiles safely. +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join } from 'node:path'; + +const ROOT = 'assets/scripts'; + +/** Spreads of an iterator or collection, rather than an array. */ +const HAZARDS = [ + { pattern: /\.\.\.[\w.$]*\.values\(\)/, what: '.values()' }, + { pattern: /\.\.\.[\w.$]*\.keys\(\)/, what: '.keys()' }, + { pattern: /\.\.\.[\w.$]*\.entries\(\)/, what: '.entries()' }, + { pattern: /\.\.\.new (?:Map|Set)\b/, what: 'a new Map/Set' }, + { pattern: /\.\.\.[\w.$]*(?:Map|Set)\b(?!\s*\()/, what: 'something named like a Map/Set' }, +]; + +const offenders = []; + +function walk(dir) { + for (const entry of readdirSync(dir)) { + const path = join(dir, entry); + if (statSync(path).isDirectory()) walk(path); + else if (path.endsWith('.ts')) inspect(path); + } +} + +function inspect(path) { + readFileSync(path, 'utf8').split('\n').forEach((line, index) => { + const code = line.trim(); + if (code.startsWith('*') || code.startsWith('//')) return; + + for (const { pattern, what } of HAZARDS) { + if (pattern.test(code)) { + offenders.push(`${path}:${index + 1} spreads ${what} — use Array.from(...)\n ${code}`); + return; + } + } + }); +} + +walk(ROOT); + +if (offenders.length > 0) { + console.error( + 'Array spread of a non-array. The build turns [...x] into [].concat(x),\n' + + 'which appends an iterator instead of expanding it:\n - ' + + offenders.join('\n - '), + ); + process.exit(1); +} + +console.log('spreads OK'); diff --git a/scripts/serve-build.mjs b/scripts/serve-build.mjs new file mode 100644 index 0000000..b8f9359 --- /dev/null +++ b/scripts/serve-build.mjs @@ -0,0 +1,102 @@ +// Serves a build over HTTP for testing in a browser. +// +// npm run serve # build/web-mobile on http://localhost:8123 +// npm run serve -- 9000 # a different port +// +// Also serves one route of its own, `/_aspects`, which loads the game in fixed +// size iframes at the portrait extremes docs/UI.md asks for (4:3 to 21:9). The +// engine resizes itself to fill whatever window it is in, so an iframe is the +// only straightforward way to see the layout at a shape the desktop window is +// not — and the harness lives here rather than in the build folder because a +// rebuild wipes everything inside it. +import { createServer } from 'node:http'; +import { readFile } from 'node:fs/promises'; +import { extname, join, normalize, resolve } from 'node:path'; + +const ROOT = resolve(process.argv[3] ?? 'build/web-mobile'); +const PORT = Number(process.argv[2] ?? 8123); + +const TYPES = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript', + '.mjs': 'text/javascript', + '.json': 'application/json', + '.css': 'text/css', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.webp': 'image/webp', + '.wasm': 'application/wasm', + '.bin': 'application/octet-stream', +}; + +/** width:height as a portrait phone reports it, from the widest to the tallest. */ +const RATIOS = [ + ['4:3 — widest', 3 / 4], + ['16:9', 9 / 16], + ['21:9 — tallest', 9 / 21], +]; + +function aspectsPage(height, only) { + // Booting three engines at once is slow enough to be painful; `?only=16:9` + // renders a single viewport when that is all you need. + const wanted = only + ? RATIOS.filter(([label]) => label.toLowerCase().startsWith(only.toLowerCase())) + : RATIOS; + + const cells = (wanted.length > 0 ? wanted : RATIOS).map(([label, ratio]) => { + const width = Math.round(height * ratio); + return `
+

${label} — ${width}×${height}

+ +
`; + }).join('\n'); + + return ` + +Fool — portrait layout at 4:3, 16:9 and 21:9 + +
+${cells} +
`; +} + +createServer(async (request, response) => { + const path = decodeURIComponent((request.url ?? '/').split('?')[0]); + + if (path === '/_aspects' || path === '/_aspects.html') { + const query = new URL(request.url ?? '/', 'http://x').searchParams; + const height = Number(query.get('h')) || 760; + response.writeHead(200, { 'Content-Type': TYPES['.html'], 'Cache-Control': 'no-store' }); + response.end(aspectsPage(height, query.get('only'))); + return; + } + + const file = join(ROOT, normalize(path === '/' ? '/index.html' : path)); + if (!file.startsWith(ROOT)) { + response.writeHead(403); + response.end('forbidden'); + return; + } + + try { + const body = await readFile(file); + response.writeHead(200, { + 'Content-Type': TYPES[extname(file)] ?? 'application/octet-stream', + 'Cache-Control': 'no-store', + }); + response.end(body); + } catch { + response.writeHead(404); + response.end('not found'); + } +}).listen(PORT, () => { + console.log(`serving ${ROOT}`); + console.log(` game http://localhost:${PORT}/`); + console.log(` aspects http://localhost:${PORT}/_aspects`); + console.log(` one http://localhost:${PORT}/_aspects?only=16:9&h=900`); +});