Skip to content

feat: multi-warship selection with Shift+drag box - #3677

Merged
evanpelle merged 19 commits into
openfrontio:mainfrom
baculinivan-web:feature/warship-selection-and-move
Apr 21, 2026
Merged

evanpelle merged 19 commits into
openfrontio:mainfrom
baculinivan-web:feature/warship-selection-and-move

Conversation

@baculinivan-web

@baculinivan-web baculinivan-web commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #3666

Description:

Adds RTS-style box selection for warships. Hold Shift and drag (desktop) or long-press and drag (touch/mobile) to draw a selection rectangle — all player-owned warships inside get selected at once. A subsequent click/tap on water sends them all to that location.

  • SelectionBoxLayer — pixel-dashed rectangle in world-space, player territory color; shared between desktop and touch
  • UILayer — same pulsing selection outline on each box-selected warship; clears correctly when switching between single/multi selection
  • UnitLayer — finds warships in screen rect, filters inactive ships before sending; touch support included
  • InputHandler — Shift+drag and touch long-press+drag both emit selection box events; cursor becomes crosshair on Shift; discards active ghost structure on Shift press; configurable via shiftKey keybind
  • Transport — single atomic move_multiple_warships intent (no split on socket drop)
  • Schemas + ExecutionManager + MoveMultipleWarshipsExecution — server fans out atomic intent into individual MoveWarshipExecution per ship
  • DynamicUILayer — MoveIndicatorUI chevron animation on target tile for both single and multi move
  • UnitDisplay — warship tooltip Shift hint via translateText
  • HelpModal — new hotkey row: Shift + drag → select multiple warships

Please complete the following:

  • I have added screenshots for all UI updates
  • I process any text displayed to the user through translateText() and I've added it to the en.json file
  • I have added relevant tests to the test directory
  • I confirm I have thoroughly tested these changes and take full responsibility for any bugs introduced

UI update

Mouse + Keyboard

CleanShot.2026-04-15.at.14.48.02.mp4

Touch

IMG_2237.2.MOV

Please put your Discord username so you can be contacted if a bug or regression is found:

fghjk_60845

Resolves openfrontio#3666

- Shift+drag draws a pixel-dashed selection rectangle in player color
- All player-owned warships inside the box get selected at once
- Click on water sends all selected warships to that location
- Same pulsing selection outline as single-warship selection
- MoveIndicatorUI chevron animation shown on target tile
- Shift keydown discards active ghost structure (build mode)
- Crosshair cursor on Shift hold, resets on release/blur
- Warship toolbar tooltip includes Shift hint (en.json)
- Tests: WarshipMultiSelection.test.ts + InputHandler selection box tests
@coderabbitai

coderabbitai Bot commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 69511bc5-f07a-4342-a591-e811f3b3a83e

📥 Commits

Reviewing files that changed from the base of the PR and between f7b5717 and 8639c6b.

📒 Files selected for processing (1)
  • src/client/InputHandler.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/client/InputHandler.ts

Walkthrough

Adds shift+drag warship multi-selection, a select-all hotkey, UI selection-box overlays, input events for selection-box lifecycle and touch long-press, transport/schema/execution changes to send/handle arrays of warship IDs, and tests covering the new behaviors.

Changes

Cohort / File(s) Summary
Localization & Help
resources/lang/en.json
Added localization keys for warship multi-select/help: help_modal.action_warship_multiselect, help_modal.action_warship_selectall, help_modal.drag, and build_menu.desc.warship_shift_hint.
Help Modal UI
src/client/HelpModal.ts
Appended two hotkey rows: Shift+drag hint (uses keybinds.shiftKey + help_modal.drag) and the select-all key (keybinds.selectAllWarships).
Keybinds / Settings
src/core/game/UserSettings.ts
Added default selectAllWarships: "KeyF" to the default keybind map.
Input events & handler
src/client/InputHandler.ts
Extended UnitSelectionEvent with units: UnitView[]; added selection-box and touch long-press state; emits WarshipSelectionBoxUpdateEvent, WarshipSelectionBoxCompleteEvent, WarshipSelectionBoxCancelEvent, SelectAllWarshipsEvent, and TouchLongPressStartEvent; keyboard and pointer logic updated to enter/exit box-mode and manage crosshair/cancellation.
Client transport
src/client/Transport.ts
MoveWarshipIntentEvent and outgoing "move_warship" intent now use unitIds: number[] (array) instead of a single unitId.
UI overlay & rendering
src/client/graphics/layers/UILayer.ts
Added drag-rectangle overlay canvas and drawing helpers; renders active selection rectangle and per-warship selection boxes; manages multi-selection box lifecycle and cleanup.
Unit display
src/client/graphics/layers/UnitDisplay.ts
Adjusted tooltip placement and added conditional tooltip row for warships showing the Shift+drag hint (build_menu.warship_shift_hint).
Unit selection & actions
src/client/graphics/layers/UnitLayer.ts
Tracks selectedWarships for multi-selection, handles box-complete/cancel/select-all events to populate/clear selections, routes tile clicks to emit batch MoveWarshipIntentEvent with unitIds[], and clears multi-selection after issuing move.
Core schemas & execution
src/core/Schemas.ts, src/core/execution/ExecutionManager.ts, src/core/execution/MoveWarshipExecution.ts
Normalized "move_warship" intent to unitIds: number[] in schema/types; ExecutionManager forwards unitIds; MoveWarshipExecution now accepts unitIds[], deduplicates IDs, applies patrol tile to each owned/active warship, and skips missing/inactive IDs without throwing.
Tests
tests/InputHandler.test.ts, tests/WarshipMultiSelection.test.ts, tests/Warship.test.ts
Extended InputHandler tests for shift+drag lifecycle, cursor and cancel behavior; added WarshipMultiSelection tests for batch moves and ownership/deleted-unit handling; updated existing warship tests to use array-form unit IDs.

Sequence Diagram

sequenceDiagram
    participant User as User
    participant Input as InputHandler
    participant UI as UILayer
    participant Unit as UnitLayer
    participant ExecMgr as ExecutionManager
    participant Game as Game

    User->>Input: Pointer down (with Shift)
    Input->>Input: record start coords, set crosshair
    Input->>UI: WarshipSelectionBoxUpdateEvent(start,end)
    User->>Input: Pointer move (with Shift)
    Input->>UI: WarshipSelectionBoxUpdateEvent(updated)
    UI->>UI: Render drag rectangle overlay (offscreen canvas)
    User->>Input: Pointer up
    Input->>Unit: WarshipSelectionBoxCompleteEvent(box)
    Unit->>Unit: Compute selectedWarships (screen→world, filter owned/active)
    User->>Unit: Click water tile (target)
    Unit->>ExecMgr: MoveWarshipIntentEvent(unitIds[], tile)
    ExecMgr->>Game: Create MoveWarshipExecution(unitIds, tile)
    Game->>Game: Update patrolTile for each valid owned warship
    Unit->>UI: UnitSelectionEvent(null,false)
    UI->>UI: Clear selection overlays
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

Shift draws a box across the foam,
Many keels answer, leaving home,
One target called, a single beat,
Hulls steer together, lines meet,
⚓️🟦

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title accurately summarizes the main feature: multi-warship selection using Shift+drag box selection, which is the core objective of the changeset.
Description check ✅ Passed The PR description is well-detailed and directly related to the changeset, covering implementation details, components changed, testing, and providing evidence of manual testing with screenshots.
Linked Issues check ✅ Passed The PR implements all coding requirements from issue #3666: RTS-style multi-warship selection with Shift keybinding [#3666], box selection rectangle [#3666], grouped move commands [#3666], and touch parity via long-press [#3666].
Out of Scope Changes check ✅ Passed All code changes are directly related to implementing multi-warship selection and grouped move commands. UI updates (tooltip hints, help modal entries), event system changes, and test additions all support the core feature without introducing unrelated modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/client/graphics/layers/UnitLayer.ts (1)

1-702: ⚠️ Potential issue | 🟡 Minor

Formatting issue flagged by CI pipeline.

The Prettier check reported a formatting/style issue for this file. Please run your formatter to fix it before merge.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/graphics/layers/UnitLayer.ts` around lines 1 - 702, The file
UnitLayer.ts fails the Prettier/style check; run your formatter (e.g., npm run
format or npx prettier --write) on UnitLayer.ts (the class UnitLayer and its
methods like onMouseUp, onUnitSelectionChange, drawSprite, paintCell, etc.) and
commit the formatted file so the CI Prettier check passes—do not change logic,
only apply formatting and stage the updated file for the PR.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/client/graphics/layers/UILayer.ts`:
- Around line 211-225: onMultiSelection currently only clears
multiSelectionBoxCenters, so any existing single-selection state (selectedUnit
and lastSelectionBoxCenter) continues animating; update onMultiSelection to also
clear the single-selection outline by calling
clearSelectionBox(lastSelectionBoxCenter.x, lastSelectionBoxCenter.y,
lastSelectionBoxCenter.size) if lastSelectionBoxCenter is set, then null out
selectedUnit and lastSelectionBoxCenter before proceeding to set
multiSelectedWarships and drawSelectionBoxMulti for active units.

In `@src/client/Transport.ts`:
- Around line 637-645: The onMoveMultipleWarshipsEvent currently loops and calls
sendIntent repeatedly, which can split group moves if the socket drops; change
it to send a single batched intent (e.g. sendIntent with type
"move_multiple_warships" and payload { unitIds: event.unitIds, tile: event.tile
}) so the client emits one atomic intent and let the server/local executor (or
existing intent handler) fan out into individual move_warship actions; update
any handlers expecting multiple individual intents to accept and expand the new
batched intent (references: onMoveMultipleWarshipsEvent, sendIntent,
MoveMultipleWarshipsIntentEvent).

---

Outside diff comments:
In `@src/client/graphics/layers/UnitLayer.ts`:
- Around line 1-702: The file UnitLayer.ts fails the Prettier/style check; run
your formatter (e.g., npm run format or npx prettier --write) on UnitLayer.ts
(the class UnitLayer and its methods like onMouseUp, onUnitSelectionChange,
drawSprite, paintCell, etc.) and commit the formatted file so the CI Prettier
check passes—do not change logic, only apply formatting and stage the updated
file for the PR.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 108a19e0-761b-426a-96c9-9d1c20bc3fda

📥 Commits

Reviewing files that changed from the base of the PR and between 3a49b9a and 60a202f.

📒 Files selected for processing (11)
  • resources/lang/en.json
  • src/client/InputHandler.ts
  • src/client/Transport.ts
  • src/client/graphics/GameRenderer.ts
  • src/client/graphics/layers/DynamicUILayer.ts
  • src/client/graphics/layers/SelectionBoxLayer.ts
  • src/client/graphics/layers/UILayer.ts
  • src/client/graphics/layers/UnitDisplay.ts
  • src/client/graphics/layers/UnitLayer.ts
  • tests/InputHandler.test.ts
  • tests/WarshipMultiSelection.test.ts

Comment thread src/client/graphics/layers/UILayer.ts Resolved
Comment thread src/client/Transport.ts Resolved
@github-project-automation github-project-automation Bot moved this from Triage to Development in OpenFront Release Management Apr 15, 2026
- Replace hardcoded ShiftLeft/ShiftRight with this.keybinds.shiftKey
- Add warship multi-select row to HelpModal hotkeys table
- Add help_modal.action_warship_multiselect and drag keys to en.json

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/client/graphics/layers/UILayer.ts (1)

230-271: Extract the shared selection-box painter.

drawSelectionBoxMulti() now copies almost all of drawSelectionBox(). One helper for the pulse/color/border drawing would keep single- and multi-select visuals from drifting on the next style change.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/graphics/layers/UILayer.ts` around lines 230 - 271, Extract the
duplicated selection-box drawing from drawSelectionBoxMulti() and
drawSelectionBox() into a single helper (e.g., paintSelectionBox or
drawSelectionBoxAt) that accepts centerX, centerY, size, ownerColor (or a
computed selectionColor), and uses this.selectionAnimTime / SELECTION_BOX_SIZE
to compute pulse opacity and paint the border cells via this.paintCell; update
both drawSelectionBoxMulti and drawSelectionBox to call the new helper, keep
clearSelectionBox and multiSelectionBoxCenters logic in the callers (only the
painting/pulse/color loop moves to the helper) and reuse
this.SELECTION_BOX_SIZE, this.paintCell, and this.selectionAnimTime symbols to
preserve behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/client/graphics/layers/UnitLayer.ts`:
- Around line 159-169: The current multi-move branch emits
MoveMultipleWarshipsIntentEvent using this.selectedWarships without filtering
out ships that may have been destroyed or deactivated; before emitting, filter
this.selectedWarships to only include currently active/player-owned warships
(e.g., check each warship.isActive() and warship.ownerId === currentPlayerId or
equivalent), then map to ids and emit MoveMultipleWarshipsIntentEvent with that
filtered id list; if the filtered list is empty, do not emit the move intent but
still clear this.selectedWarships and emit WarshipMultiSelectionEvent([]).

---

Nitpick comments:
In `@src/client/graphics/layers/UILayer.ts`:
- Around line 230-271: Extract the duplicated selection-box drawing from
drawSelectionBoxMulti() and drawSelectionBox() into a single helper (e.g.,
paintSelectionBox or drawSelectionBoxAt) that accepts centerX, centerY, size,
ownerColor (or a computed selectionColor), and uses this.selectionAnimTime /
SELECTION_BOX_SIZE to compute pulse opacity and paint the border cells via
this.paintCell; update both drawSelectionBoxMulti and drawSelectionBox to call
the new helper, keep clearSelectionBox and multiSelectionBoxCenters logic in the
callers (only the painting/pulse/color loop moves to the helper) and reuse
this.SELECTION_BOX_SIZE, this.paintCell, and this.selectionAnimTime symbols to
preserve behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c08444b4-2d2b-4217-a30c-2f7b0d74560e

📥 Commits

Reviewing files that changed from the base of the PR and between 60a202f and 7b44813.

📒 Files selected for processing (5)
  • src/client/graphics/layers/DynamicUILayer.ts
  • src/client/graphics/layers/UILayer.ts
  • src/client/graphics/layers/UnitLayer.ts
  • tests/InputHandler.test.ts
  • tests/WarshipMultiSelection.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/client/graphics/layers/DynamicUILayer.ts
  • tests/WarshipMultiSelection.test.ts
  • tests/InputHandler.test.ts

Comment thread src/client/graphics/layers/UnitLayer.ts Resolved
onMultiSelection now clears selectedUnit and lastSelectionBoxCenter
before applying multi-selection, preventing ghost outlines
…onBoxAt helper

- UnitLayer: filter selectedWarships to active+owned before emitting
  MoveMultipleWarshipsIntentEvent; skip emit if none remain active
- UILayer: extract shared paintSelectionBoxAt() helper used by both
  drawSelectionBox and drawSelectionBoxMulti to remove duplication

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/client/graphics/layers/UILayer.ts (1)

238-279: Extract one shared selection-box painter.

drawSelectionBoxMulti() now copies most of drawSelectionBox(). Keeping two copies of the same pulse/border logic will drift fast. Please move the shared paint logic into one helper and keep only the per-mode state tracking separate.

Small refactor sketch
+  private drawAnimatedSelectionBox(
+    centerX: number,
+    centerY: number,
+    selectionSize: number,
+    selectionColor: Colord,
+  ) {
+    const baseOpacity = 200;
+    const pulseAmount = 55;
+    const opacity =
+      baseOpacity + Math.sin(this.selectionAnimTime * 0.1) * pulseAmount;
+
+    for (let x = centerX - selectionSize; x <= centerX + selectionSize; x++) {
+      for (let y = centerY - selectionSize; y <= centerY + selectionSize; y++) {
+        if (
+          (x === centerX - selectionSize ||
+            x === centerX + selectionSize ||
+            y === centerY - selectionSize ||
+            y === centerY + selectionSize) &&
+          (x + y) % 2 === 0
+        ) {
+          this.paintCell(x, y, selectionColor, opacity);
+        }
+      }
+    }
+  }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/graphics/layers/UILayer.ts` around lines 238 - 279,
drawSelectionBoxMulti duplicates the pulse/border painting logic from
drawSelectionBox; extract that shared logic into a new helper (e.g.,
paintSelectionBox or paintSelectionBorder) that accepts centerX, centerY,
selectionSize, selectionColor and opacity and performs the nested x/y loop and
paintCell calls. In drawSelectionBoxMulti and drawSelectionBox compute
mode-specific state (selectionSize, centerX/centerY, selectionColor, opacity)
and then call the new helper; keep each function's per-mode state tracking
(multiSelectionBoxCenters vs the single-selection center/clear logic) unchanged.
Ensure helper references the same this.paintCell and
this.selectionAnimTime/SELECTION_BOX_SIZE/theme checks as needed and update
callers to remove duplicated logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/client/graphics/layers/UILayer.ts`:
- Around line 220-225: Update UILayer to clear multi-selection state when a
single unit is selected: in the UILayer.onUnitSelectionChange handler (the
method that processes UnitSelectionEvent), detect when the event represents a
single unit selection and then clear this.multiSelectedWarships and
this.multiSelectionBoxCenters (and remove any rendered boxes via the same
clearSelectionBox logic used in the WarshipMultiSelectionEvent handling). This
mirrors the WarshipMultiSelectionEvent flow (which clears boxes and centers) so
ensure you call the same clearing logic before setting single selection state.

---

Nitpick comments:
In `@src/client/graphics/layers/UILayer.ts`:
- Around line 238-279: drawSelectionBoxMulti duplicates the pulse/border
painting logic from drawSelectionBox; extract that shared logic into a new
helper (e.g., paintSelectionBox or paintSelectionBorder) that accepts centerX,
centerY, selectionSize, selectionColor and opacity and performs the nested x/y
loop and paintCell calls. In drawSelectionBoxMulti and drawSelectionBox compute
mode-specific state (selectionSize, centerX/centerY, selectionColor, opacity)
and then call the new helper; keep each function's per-mode state tracking
(multiSelectionBoxCenters vs the single-selection center/clear logic) unchanged.
Ensure helper references the same this.paintCell and
this.selectionAnimTime/SELECTION_BOX_SIZE/theme checks as needed and update
callers to remove duplicated logic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ca104888-b7c1-4c1f-be67-ab596db346e5

📥 Commits

Reviewing files that changed from the base of the PR and between 5f23c20 and 72b2b4c.

📒 Files selected for processing (1)
  • src/client/graphics/layers/UILayer.ts

Comment thread src/client/graphics/layers/UILayer.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
src/client/graphics/layers/UILayer.ts (1)

189-205: ⚠️ Potential issue | 🟠 Major

Clear box-selection state on normal single selection.

A single UnitSelectionEvent sets selectedUnit, but it does not clear multiSelectedWarships or the already painted multi-selection boxes. After box-selecting warships, a normal click can therefore leave stale group outlines on screen until some later WarshipMultiSelectionEvent([]) happens.

Suggested fix
   private onUnitSelection(event: UnitSelectionEvent) {
     if (event.isSelected) {
+      for (const [, center] of this.multiSelectionBoxCenters) {
+        this.clearSelectionBox(center.x, center.y, center.size);
+      }
+      this.multiSelectionBoxCenters.clear();
+      this.multiSelectedWarships = [];
+
       this.selectedUnit = event.unit;
       if (event.unit && event.unit.type() === UnitType.Warship) {
         this.drawSelectionBox(event.unit);
       }
     } else {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/graphics/layers/UILayer.ts` around lines 189 - 205, When handling
a normal single selection in onUnitSelection, you must also clear any prior
multi-selection state and visuals so stale group outlines aren't left on screen;
update onUnitSelection to reset this.multiSelectedWarships (set to empty array)
and remove any painted multi-selection boxes — either call an existing
clearMultiSelectionBoxes() helper if present or iterate the stored
multi-selection centers and call clearSelectionBox(x,y,size) for each before
setting this.selectedUnit; ensure any stored multi-selection center/state is
nulled after clearing.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/client/graphics/layers/UILayer.ts`:
- Around line 189-205: When handling a normal single selection in
onUnitSelection, you must also clear any prior multi-selection state and visuals
so stale group outlines aren't left on screen; update onUnitSelection to reset
this.multiSelectedWarships (set to empty array) and remove any painted
multi-selection boxes — either call an existing clearMultiSelectionBoxes()
helper if present or iterate the stored multi-selection centers and call
clearSelectionBox(x,y,size) for each before setting this.selectedUnit; ensure
any stored multi-selection center/state is nulled after clearing.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f032545b-bc27-4586-a3ec-ceeb986e9cb3

📥 Commits

Reviewing files that changed from the base of the PR and between 72b2b4c and edf42ea.

📒 Files selected for processing (3)
  • src/client/graphics/layers/UILayer.ts
  • src/client/graphics/layers/UnitLayer.ts
  • tests/InputHandler.test.ts
✅ Files skipped from review due to trivial changes (1)
  • src/client/graphics/layers/UnitLayer.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/InputHandler.test.ts

@baculinivan-web

Copy link
Copy Markdown
Contributor Author

@coderabbitai resume

@coderabbitai

coderabbitai Bot commented Apr 15, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Reviews resumed.

@baculinivan-web

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 15, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@VariableVince

VariableVince commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Nice. Have you thought about how the mobile equivalent would work? The goal is to have mobile on par with desktop as much as possible, even if hotkeys etc aren't possible.

Maybe in a follow-up PR if you'd be up for it and this one gets merged.

Perhaps something like this (but water instead of ground in this case ofc)

Screenshot_20260415_162453_Vivaldi

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/client/graphics/layers/UILayer.ts (1)

271-293: Nice extraction of shared logic.

paintSelectionBoxAt consolidates the duplicated box-painting code. Clean and readable.

One small note: the nested loop iterates all cells in the box but only paints border pixels. You could iterate just the border for a tiny speedup, but with SELECTION_BOX_SIZE = 6 (13×13 = 169 iterations), this is fine as-is.

♻️ Optional: iterate only border cells
 private paintSelectionBoxAt(
   centerX: number,
   centerY: number,
   selectionColor: Colord,
 ) {
   const size = this.SELECTION_BOX_SIZE;
   const opacity = 200 + Math.sin(this.selectionAnimTime * 0.1) * 55;
 
-  for (let x = centerX - size; x <= centerX + size; x++) {
-    for (let y = centerY - size; y <= centerY + size; y++) {
-      if (
-        x === centerX - size ||
-        x === centerX + size ||
-        y === centerY - size ||
-        y === centerY + size
-      ) {
-        if ((x + y) % 2 === 0) {
-          this.paintCell(x, y, selectionColor, opacity);
-        }
-      }
-    }
-  }
+  // Top and bottom edges
+  for (let x = centerX - size; x <= centerX + size; x++) {
+    if ((x + centerY - size) % 2 === 0) {
+      this.paintCell(x, centerY - size, selectionColor, opacity);
+    }
+    if ((x + centerY + size) % 2 === 0) {
+      this.paintCell(x, centerY + size, selectionColor, opacity);
+    }
+  }
+  // Left and right edges (skip corners, already painted)
+  for (let y = centerY - size + 1; y < centerY + size; y++) {
+    if ((centerX - size + y) % 2 === 0) {
+      this.paintCell(centerX - size, y, selectionColor, opacity);
+    }
+    if ((centerX + size + y) % 2 === 0) {
+      this.paintCell(centerX + size, y, selectionColor, opacity);
+    }
+  }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/graphics/layers/UILayer.ts` around lines 271 - 293,
paintSelectionBoxAt currently loops over the entire square but only paints
border cells; refactor it to iterate only the four border ranges to avoid
unnecessary iterations: compute size = this.SELECTION_BOX_SIZE and opacity as
before, then loop x from centerX - size to centerX + size for the top (y =
centerY - size) and bottom (y = centerY + size) edges and loop y from centerY -
size + 1 to centerY + size - 1 for the left (x = centerX - size) and right (x =
centerX + size) edges, calling this.paintCell(x,y, selectionColor, opacity);
keep using the same function name paintSelectionBoxAt and the same opacity
calculation so behavior is unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/client/graphics/layers/UILayer.ts`:
- Around line 271-293: paintSelectionBoxAt currently loops over the entire
square but only paints border cells; refactor it to iterate only the four border
ranges to avoid unnecessary iterations: compute size = this.SELECTION_BOX_SIZE
and opacity as before, then loop x from centerX - size to centerX + size for the
top (y = centerY - size) and bottom (y = centerY + size) edges and loop y from
centerY - size + 1 to centerY + size - 1 for the left (x = centerX - size) and
right (x = centerX + size) edges, calling this.paintCell(x,y, selectionColor,
opacity); keep using the same function name paintSelectionBoxAt and the same
opacity calculation so behavior is unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 09065808-86a5-4bd0-b271-c5b5bf224c63

📥 Commits

Reviewing files that changed from the base of the PR and between 72b2b4c and cf5c50a.

📒 Files selected for processing (3)
  • src/client/graphics/layers/UILayer.ts
  • src/client/graphics/layers/UnitLayer.ts
  • tests/InputHandler.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/InputHandler.test.ts
  • src/client/graphics/layers/UnitLayer.ts

- Add MoveMultipleWarshipsIntentSchema to Schemas.ts
- Add MoveMultipleWarshipsExecution that fans out to individual MoveWarshipExecutions
- Transport now sends a single batched intent instead of N individual ones
- Prevents split group moves if socket drops mid-loop

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
src/client/Transport.ts (1)

637-643: Consider cloning unitIds before sending to keep payload immutable.

At Line 640, passing the same array reference works today, but a defensive copy avoids accidental mutation side effects in future listeners/refactors.

🛡️ Small defensive tweak
   private onMoveMultipleWarshipsEvent(event: MoveMultipleWarshipsIntentEvent) {
     this.sendIntent({
       type: "move_multiple_warships",
-      unitIds: event.unitIds,
+      unitIds: [...event.unitIds],
       tile: event.tile,
     });
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/Transport.ts` around lines 637 - 643, The
onMoveMultipleWarshipsEvent handler passes the original
MoveMultipleWarshipsIntentEvent.unitIds array to sendIntent, risking accidental
mutation of the payload; update onMoveMultipleWarshipsEvent to send a shallow
copy of unitIds (e.g., via slice() or spread) when calling sendIntent so the
intent payload is immutable — locate the onMoveMultipleWarshipsEvent function
and change the unitIds argument to a cloned array before sending.
src/core/Schemas.ts (1)

413-417: Constrain unitIds in the schema to avoid malformed or oversized intents.

At Line 415, z.array(z.number()) allows empty lists, duplicates, and non-integer IDs. Tightening this will prevent no-op/duplicate fan-out and reduce abuse risk from oversized payloads.

♻️ Suggested schema hardening
 export const MoveMultipleWarshipsIntentSchema = z.object({
   type: z.literal("move_multiple_warships"),
-  unitIds: z.array(z.number()),
+  unitIds: z
+    .array(z.number().int().nonnegative())
+    .min(1)
+    // pick a game-appropriate cap constant
+    .max(1000)
+    .refine((ids) => new Set(ids).size === ids.length, {
+      message: "unitIds must be unique",
+    }),
   tile: z.number(),
 });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/core/Schemas.ts` around lines 413 - 417, The
MoveMultipleWarshipsIntentSchema's unitIds currently allows empty, non-integer,
duplicate or overly large arrays; update the unitIds definition to be an array
of integers (use z.number().int()), require at least one entry (.nonempty()),
enforce a sensible maximum length to prevent oversized payloads (e.g., .max(N)
with N chosen by domain limits), and enforce uniqueness (either via .refine(...)
or .superRefine(...) checking new Set(size) equals array length). Keep the
schema name MoveMultipleWarshipsIntentSchema and field unitIds when making these
validations so downstream code still matches.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/client/Transport.ts`:
- Around line 637-643: The onMoveMultipleWarshipsEvent handler passes the
original MoveMultipleWarshipsIntentEvent.unitIds array to sendIntent, risking
accidental mutation of the payload; update onMoveMultipleWarshipsEvent to send a
shallow copy of unitIds (e.g., via slice() or spread) when calling sendIntent so
the intent payload is immutable — locate the onMoveMultipleWarshipsEvent
function and change the unitIds argument to a cloned array before sending.

In `@src/core/Schemas.ts`:
- Around line 413-417: The MoveMultipleWarshipsIntentSchema's unitIds currently
allows empty, non-integer, duplicate or overly large arrays; update the unitIds
definition to be an array of integers (use z.number().int()), require at least
one entry (.nonempty()), enforce a sensible maximum length to prevent oversized
payloads (e.g., .max(N) with N chosen by domain limits), and enforce uniqueness
(either via .refine(...) or .superRefine(...) checking new Set(size) equals
array length). Keep the schema name MoveMultipleWarshipsIntentSchema and field
unitIds when making these validations so downstream code still matches.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0354f116-d367-446a-bc09-71a34d361b4b

📥 Commits

Reviewing files that changed from the base of the PR and between cf5c50a and 19a5c75.

📒 Files selected for processing (4)
  • src/client/Transport.ts
  • src/core/Schemas.ts
  • src/core/execution/ExecutionManager.ts
  • src/core/execution/MoveMultipleWarshipsExecution.ts

coderabbitai[bot]
coderabbitai Bot previously approved these changes Apr 15, 2026
@baculinivan-web

Copy link
Copy Markdown
Contributor Author

@coderabbitai resolve

@coderabbitai

coderabbitai Bot commented Apr 15, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Comments resolved and changes approved.

@baculinivan-web

Copy link
Copy Markdown
Contributor Author

@VariableVince Is mobile support nessesary to. be merged? idk how such a complex gesture can be implemented for mobile. two finger drag might work, but on a small screen gust selecting by hand would probably be simpler for the end user

@baculinivan-web

Copy link
Copy Markdown
Contributor Author

@VariableVince i looked at how mobile interactions are handled (first time playing on touchscreen....) and figured Hold + Drag would work.

flowchart TD
    A[User holds finger on map for ~1 second] --> B[Cross target appears under finger]
    B --> C[User drags]
    C --> D[Selection box is created]
    D --> E[User lets go]
    E --> F[Warships are selected]
    F --> G[User taps]
    G --> H[Warships go to tapped area]
Loading

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (4)
src/client/graphics/layers/UILayer.ts (1)

308-353: Single/multi selection handoff looks correct now.

Both branches clear the other mode before applying, which resolves the earlier "one outline keeps animating" and "multi boxes linger after single select" issues. Small nitpick: this.selectedUnit = null is only reset inside the if (this.lastSelectionBoxCenter) guard. In today's code they're always set together, but an unconditional this.selectedUnit = null before deciding single vs multi would be more defensive against future refactors.

♻️ Optional tidy-up
     if (event.isSelected) {
-      // Always clear single-selection outline first
-      if (this.lastSelectionBoxCenter) {
-        const { x, y, size } = this.lastSelectionBoxCenter;
-        this.clearSelectionBox(x, y, size);
-        this.lastSelectionBoxCenter = null;
-        this.selectedUnit = null;
-      }
+      // Always clear single-selection outline first
+      if (this.lastSelectionBoxCenter) {
+        const { x, y, size } = this.lastSelectionBoxCenter;
+        this.clearSelectionBox(x, y, size);
+        this.lastSelectionBoxCenter = null;
+      }
+      this.selectedUnit = null;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/graphics/layers/UILayer.ts` around lines 308 - 353, Make clearing
selectedUnit unconditional before handling single vs multi selection: in
onUnitSelection(event: UnitSelectionEvent) set this.selectedUnit = null
immediately after clearing any lastSelectionBoxCenter and before the check that
branches into multi-selection (event.units) vs single-selection (event.unit).
This ensures selectedUnit is always reset regardless of whether
lastSelectionBoxCenter existed and prevents future regressions; adjust only the
onUnitSelection method and keep drawSelectionBox/drawSelectionBoxMulti logic
unchanged.
src/core/Schemas.ts (1)

403-407: Consider tightening unitIds validation.

z.array(z.number()) accepts empty arrays and non-integer values. Clients in this PR always send at least one id, and ids are integers — rejecting bad payloads at the schema avoids creating no-op executions on the server.

♻️ Suggested change
 export const MoveWarshipIntentSchema = z.object({
   type: z.literal("move_warship"),
-  unitIds: z.array(z.number()),
+  unitIds: z.array(z.number().int().nonnegative()).min(1),
   tile: z.number(),
 });

Please double-check that no replay/record fixtures or test payloads send an empty unitIds that this tightening would reject.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/core/Schemas.ts` around lines 403 - 407, MoveWarshipIntentSchema's
unitIds currently allows empty arrays and non-integer numbers; update the schema
(MoveWarshipIntentSchema -> unitIds) to require a non-empty array of integers
(e.g., use an integer validator and non-empty constraint) so invalid payloads
are rejected before server execution, and then run/verify replay/record fixtures
and tests to ensure no existing test payloads rely on empty or non-integer
unitIds.
src/core/execution/MoveWarshipExecution.ts (1)

5-32: Narrow unitIds to number[] and include the id in warnings.

The schema (Schemas.ts line 405) and ExecutionManager.ts line 71 always pass an array, so the number | number[] union adds a branch for a case that never happens in production. Keeping the type narrow makes the contract clearer and removes the Array.isArray runtime check. Also, the two warning strings don't carry the failing id, which makes triaging a batch move harder.

♻️ Suggested change
 export class MoveWarshipExecution implements Execution {
   constructor(
     private readonly owner: Player,
-    private readonly unitIds: number | number[],
+    private readonly unitIds: readonly number[],
     private readonly position: TileRef,
   ) {}
 
   init(mg: Game, _ticks: number): void {
     if (!mg.isValidRef(this.position)) {
       console.warn(`MoveWarshipExecution: position ${this.position} not valid`);
       return;
     }
-    const ids = Array.isArray(this.unitIds) ? this.unitIds : [this.unitIds];
-    for (const unitId of ids) {
+    for (const unitId of this.unitIds) {
       const warship = this.owner
         .units(UnitType.Warship)
         .find((u) => u.id() === unitId);
       if (!warship) {
-        console.warn("MoveWarshipExecution: warship not found");
+        console.warn(`MoveWarshipExecution: warship ${unitId} not found`);
         continue;
       }
       if (!warship.isActive()) {
-        console.warn("MoveWarshipExecution: warship is not active");
+        console.warn(`MoveWarshipExecution: warship ${unitId} is not active`);
         continue;
       }
       warship.setPatrolTile(this.position);
       warship.setTargetTile(undefined);
     }
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/core/execution/MoveWarshipExecution.ts` around lines 5 - 32, Change
MoveWarshipExecution.unitIds from number | number[] to number[] and remove the
Array.isArray branch in init; iterate directly over unitIds, and update the
warning messages inside init to include the failing unitId (e.g., when warship
is not found or not active) so logs show the id; keep other behavior (checking
mg.isValidRef(this.position), warship.setPatrolTile(this.position),
warship.setTargetTile(undefined)) unchanged.
src/client/InputHandler.ts (1)

571-590: Cancel the long-press timer when a second pointer starts a pinch.

If a touch user starts a one-finger press and lands a second finger within 800 ms to pinch-zoom, the long-press timer still fires: longPressActive flips to true and the cursor switches to crosshair mid-pinch. Once the user lifts a finger back to one pointer, any small move will then enter box-draw mode unexpectedly. Clearing the timer in the pointers.size === 2 branch fixes it.

♻️ Suggested change
     } else if (this.pointers.size === 2) {
+      if (this.longPressTimer !== null) {
+        clearTimeout(this.longPressTimer);
+        this.longPressTimer = null;
+      }
+      this.longPressActive = false;
       this.lastPinchDistance = this.getPinchDistance();
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/InputHandler.ts` around lines 571 - 590, In the pointer-down
handling branch where you detect a second touch (this.pointers.size === 2),
cancel any pending long-press by clearing this.longPressTimer, setting
this.longPressTimer = null and this.longPressActive = false, and ensure the
cursor/state used for long-press (this.canvas.style.cursor) is reset so the
TouchLongPressStartEvent cannot fire mid-pinch; update the code in InputHandler
(the pointer-down logic that currently only sets this.lastPinchDistance) to
perform this cleanup before computing pinch state.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/client/graphics/layers/UILayer.ts`:
- Around line 308-353: Make clearing selectedUnit unconditional before handling
single vs multi selection: in onUnitSelection(event: UnitSelectionEvent) set
this.selectedUnit = null immediately after clearing any lastSelectionBoxCenter
and before the check that branches into multi-selection (event.units) vs
single-selection (event.unit). This ensures selectedUnit is always reset
regardless of whether lastSelectionBoxCenter existed and prevents future
regressions; adjust only the onUnitSelection method and keep
drawSelectionBox/drawSelectionBoxMulti logic unchanged.

In `@src/client/InputHandler.ts`:
- Around line 571-590: In the pointer-down handling branch where you detect a
second touch (this.pointers.size === 2), cancel any pending long-press by
clearing this.longPressTimer, setting this.longPressTimer = null and
this.longPressActive = false, and ensure the cursor/state used for long-press
(this.canvas.style.cursor) is reset so the TouchLongPressStartEvent cannot fire
mid-pinch; update the code in InputHandler (the pointer-down logic that
currently only sets this.lastPinchDistance) to perform this cleanup before
computing pinch state.

In `@src/core/execution/MoveWarshipExecution.ts`:
- Around line 5-32: Change MoveWarshipExecution.unitIds from number | number[]
to number[] and remove the Array.isArray branch in init; iterate directly over
unitIds, and update the warning messages inside init to include the failing
unitId (e.g., when warship is not found or not active) so logs show the id; keep
other behavior (checking mg.isValidRef(this.position),
warship.setPatrolTile(this.position), warship.setTargetTile(undefined))
unchanged.

In `@src/core/Schemas.ts`:
- Around line 403-407: MoveWarshipIntentSchema's unitIds currently allows empty
arrays and non-integer numbers; update the schema (MoveWarshipIntentSchema ->
unitIds) to require a non-empty array of integers (e.g., use an integer
validator and non-empty constraint) so invalid payloads are rejected before
server execution, and then run/verify replay/record fixtures and tests to ensure
no existing test payloads rely on empty or non-integer unitIds.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 675bde7f-0d88-4a8e-95db-caa027da657d

📥 Commits

Reviewing files that changed from the base of the PR and between 16e2b2d and 91f600f.

📒 Files selected for processing (8)
  • src/client/InputHandler.ts
  • src/client/Transport.ts
  • src/client/graphics/layers/UILayer.ts
  • src/client/graphics/layers/UnitLayer.ts
  • src/core/Schemas.ts
  • src/core/execution/ExecutionManager.ts
  • src/core/execution/MoveWarshipExecution.ts
  • tests/WarshipMultiSelection.test.ts
✅ Files skipped from review due to trivial changes (1)
  • tests/WarshipMultiSelection.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/core/execution/ExecutionManager.ts
  • src/client/Transport.ts

coderabbitai[bot]
coderabbitai Bot previously approved these changes Apr 21, 2026
- UILayer: selectedUnit = null unconditionally before single/multi branch
- InputHandler: cancel long-press timer on second touch (pinch)
- MoveWarshipExecution: unitIds is number[] only, no Array.isArray branch; log unitId in warnings
- Schemas: MoveWarshipIntentSchema unitIds requires non-empty array of integers
@baculinivan-web

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 21, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@baculinivan-web

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 21, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
src/core/execution/MoveWarshipExecution.ts (1)

16-30: Small perf tidy-up: look up the unit list once, and dedupe ids.

For each id you walk the full owner.units(UnitType.Warship) list, so N ids cost N×M. If a player sends a big box selection this gets noisy. Also, if unitIds happens to contain duplicates (e.g., from client event merging), the same warship gets setPatrolTile called twice — harmless today but easy to avoid. Composition-friendly, no new libs:

♻️ Optional refactor
-    for (const unitId of this.unitIds) {
-      const warship = this.owner
-        .units(UnitType.Warship)
-        .find((u) => u.id() === unitId);
-      if (!warship) {
-        console.warn(`MoveWarshipExecution: warship ${unitId} not found`);
-        continue;
-      }
-      if (!warship.isActive()) {
-        console.warn(`MoveWarshipExecution: warship ${unitId} is not active`);
-        continue;
-      }
-      warship.setPatrolTile(this.position);
-      warship.setTargetTile(undefined);
-    }
+    const warships = new Map(
+      this.owner.units(UnitType.Warship).map((u) => [u.id(), u] as const),
+    );
+    for (const unitId of new Set(this.unitIds)) {
+      const warship = warships.get(unitId);
+      if (!warship) {
+        console.warn(`MoveWarshipExecution: warship ${unitId} not found`);
+        continue;
+      }
+      if (!warship.isActive()) {
+        console.warn(`MoveWarshipExecution: warship ${unitId} is not active`);
+        continue;
+      }
+      warship.setPatrolTile(this.position);
+      warship.setTargetTile(undefined);
+    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/core/execution/MoveWarshipExecution.ts` around lines 16 - 30, The loop is
repeatedly calling this.owner.units(UnitType.Warship) for each id and may call
setPatrolTile multiple times for duplicate ids; fix by fetching the warship list
once into a local variable (e.g., const warships =
this.owner.units(UnitType.Warship)), build a Map from warship.id() to warship
(or iterate and check a Set of remaining ids), deduplicate this.unitIds using a
Set, then iterate the unique ids to look up the warship in the cached map and
call warship.setPatrolTile(this.position) and warship.setTargetTile(undefined)
only once per actual unit (use warship.isActive() check as before).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/client/InputHandler.ts`:
- Around line 747-759: The pointer-move branch incorrectly switches to emitting
DragEvent when Shift is released mid-drag even though selectionBoxActive is
still true; change the conditional in InputHandler (the pointer move handling
that references this.activeKeys, this.keybinds.shiftKey, this.longPressActive,
this.selectionBoxActive, this.eventBus, WarshipSelectionBoxUpdateEvent and
DragEvent) so that if this.selectionBoxActive is true it continues to emit
WarshipSelectionBoxUpdateEvent (using lastPointerDownX/lastPointerDownY and
event.clientX/Y) until pointerup/cancel resets selectionBoxActive; in short, use
(this.selectionBoxActive || this.activeKeys.has(this.keybinds.shiftKey) ||
this.longPressActive) to decide the selection-box branch and ensure
pointerup/pointercancel handlers clear this.selectionBoxActive.
- Around line 614-623: The long-press cleanup currently resets longPressActive
but still allows the subsequent touch release to emit a normal TouchEvent;
change the cleanup so that when the timer fired (wasLongPress is true) and no
drag occurred you prevent a tap from being emitted—either return early from the
touchend handler or set a suppression flag (e.g., this.suppressNextTap) in this
long-press cleanup block (where this.longPressTimer, this.longPressActive and
this.canvas.style.cursor are handled) and ensure the touchend/emitTouchEvent
logic checks that flag and skips emitting TouchEvent.

In `@src/core/execution/MoveWarshipExecution.ts`:
- Around line 7-16: The tests call the MoveWarshipExecution constructor with a
single number (warship.id()) but the implementation now expects unitIds:
number[]; update the failing tests (e.g., Warship.test.ts cases "fails
gracefully if warship not found", "fails if warship is not active", "fails if
player is not the owner" and the main case around line ~164–166) to pass an
array containing the id (wrap warship.id() in [ ... ]) so that the constructor's
unitIds parameter is iterable and the for-of loop in MoveWarshipExecution works
correctly.

---

Nitpick comments:
In `@src/core/execution/MoveWarshipExecution.ts`:
- Around line 16-30: The loop is repeatedly calling
this.owner.units(UnitType.Warship) for each id and may call setPatrolTile
multiple times for duplicate ids; fix by fetching the warship list once into a
local variable (e.g., const warships = this.owner.units(UnitType.Warship)),
build a Map from warship.id() to warship (or iterate and check a Set of
remaining ids), deduplicate this.unitIds using a Set, then iterate the unique
ids to look up the warship in the cached map and call
warship.setPatrolTile(this.position) and warship.setTargetTile(undefined) only
once per actual unit (use warship.isActive() check as before).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5cf524af-241f-47bc-a813-03a3ed12487c

📥 Commits

Reviewing files that changed from the base of the PR and between 91f600f and 4782fce.

📒 Files selected for processing (4)
  • src/client/InputHandler.ts
  • src/client/graphics/layers/UILayer.ts
  • src/core/Schemas.ts
  • src/core/execution/MoveWarshipExecution.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/core/Schemas.ts

Comment thread src/client/InputHandler.ts Resolved
…long-press; deduplicate warship ids

- InputHandler: selectionBoxActive keeps emitting WarshipSelectionBoxUpdateEvent even after Shift released mid-drag
- InputHandler: suppressNextTap flag prevents spurious TouchEvent after long-press without drag
- MoveWarshipExecution: cache warship list in Map, deduplicate unitIds with Set
@baculinivan-web

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 21, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/client/InputHandler.ts (2)

273-292: ⚠️ Potential issue | 🟠 Major

Tell the selection owner when blur clears multi-selection.

Line 291 only clears InputHandler state. UnitLayer owns selectedWarships, so after window blur it can still keep a stale multi-selection and later move those ships even though the cursor was reset.

🐛 Proposed fix
-      if (this.selectionBoxActive) {
+      const shouldCancelWarshipSelection =
+        this.selectionBoxActive || this.multiSelectionActive;
+      if (shouldCancelWarshipSelection) {
         this.selectionBoxActive = false;
+        this.multiSelectionActive = false;
         this.eventBus.emit(new WarshipSelectionBoxCancelEvent());
       }
-      this.multiSelectionActive = false;
       this.canvas.style.cursor = "";
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/InputHandler.ts` around lines 273 - 292, The window "blur" handler
in InputHandler (inside the window.addEventListener("blur", ...) block) only
resets InputHandler state (e.g., activeKeys, selectionBoxActive,
multiSelectionActive) but doesn't notify the owner of selectedWarships
(UnitLayer), leaving a stale multi-selection; update the blur handler to emit
the appropriate selection-cancel/clear event via this.eventBus (the same
mechanism used for WarshipSelectionBoxCancelEvent) or a dedicated "clear
selection" event when multiSelectionActive or selectionBoxActive is cleared so
UnitLayer can drop its selectedWarships. Ensure you reference the existing
symbols InputHandler, window.addEventListener("blur", ...),
this.multiSelectionActive, this.selectionBoxActive, this.eventBus and the
WarshipSelectionBoxCancelEvent (or a new ClearSelection event) when making the
change.

251-263: ⚠️ Potential issue | 🟠 Major

Add pointercancel listener to handle interrupted touch streams on mobile.

Mobile browsers fire pointercancel to interrupt pointer streams without sending pointerup. Without this listener, the long-press timer, selection box, or cursor can remain stuck.

Extract the pointer cleanup logic into a helper method and attach it to the pointercancel event:

Proposed implementation
    window.addEventListener("pointermove", this.onPointerMove.bind(this));
+   window.addEventListener("pointercancel", () =>
+     this.cancelPointerInteraction(),
+   );
    this.canvas.addEventListener("contextmenu", (e) => this.onContextMenu(e));

Add this helper near the other pointer event handlers:

+  private cancelPointerInteraction() {
+    this.pointerDown = false;
+    this.pointers.clear();
+
+    if (this.longPressTimer !== null) {
+      clearTimeout(this.longPressTimer);
+      this.longPressTimer = null;
+    }
+
+    const shouldCancelSelectionBox =
+      this.selectionBoxActive || this.longPressActive;
+
+    this.longPressActive = false;
+    this.suppressNextTap = false;
+
+    if (shouldCancelSelectionBox) {
+      this.selectionBoxActive = false;
+      this.eventBus.emit(new WarshipSelectionBoxCancelEvent());
+    }
+
+    if (!this.multiSelectionActive) {
+      this.canvas.style.cursor = "";
+    }
+  }
+
   private onPointerDown(event: PointerEvent) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/InputHandler.ts` around lines 251 - 263, The pointer stream can be
interrupted by pointercancel on mobile which leaves state like long-press timers
or selection boxes stuck; refactor the cleanup currently in onPointerUp into a
new helper (e.g., cleanupPointer or handlePointerEnd) and call it from
onPointerUp and from a new pointercancel listener, and register that listener
alongside existing event bindings in the constructor where you attach
this.canvas.addEventListener("pointerdown", ...),
window.addEventListener("pointerup", ...), etc.; ensure the helper clears any
timers, selection state, and active pointer tracking used by
onPointerDown/onPointerMove so pointercancel behaves identical to pointerup.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/client/InputHandler.ts`:
- Around line 238-249: The handler for UnitSelectionEvent currently treats any
e.isSelected as activating multiSelection and changing the cursor even if
e.units is empty; change the conditional to only enable multiSelectionActive and
set canvas.style.cursor = "crosshair" when e.isSelected AND e.units.length > 0,
and ensure when e.isSelected is false or e.units.length === 0 you clear
multiSelectionActive and fall back to checking selectionBoxActive before
resetting canvas.style.cursor; update the listener attached to
eventBus.on(UnitSelectionEvent, ...) and references to multiSelectionActive,
selectionBoxActive, and canvas.style.cursor accordingly.
- Around line 238-249: The handler registered in InputHandler for
UnitSelectionEvent is treating any isSelected=true as an active selection and
forcing canvas.style.cursor = "crosshair", even when e.units is empty; change
the logic so multiSelectionActive and the cursor are set only when e.isSelected
&& e.units.length > 0 (i.e., an actual non-empty selection). Keep the existing
else branch that clears multiSelectionActive and only resets canvas.style.cursor
when !selectionBoxActive so empty-box results (UnitSelectionEvent with [] units)
no longer leave the cursor stuck; update the event callback that references
multiSelectionActive, selectionBoxActive, and canvas.style.cursor accordingly.
- Around line 238-249: Update InputHandler so blur and Escape handlers emit
WarshipSelectionBoxCancelEvent when either selectionBoxActive or
multiSelectionActive is true (not just selectionBoxActive) to ensure
UnitLayer.selectedWarships is cleared after a completed selection box loses
focus; locate the blur handler and the Escape/key handler in InputHandler and
change the conditional to check (this.selectionBoxActive ||
this.multiSelectionActive) before emitting WarshipSelectionBoxCancelEvent and
resetting state. Also add a window "pointercancel" listener that forwards to the
existing onPointerUp method (e.g., window.addEventListener("pointercancel", (e)
=> this.onPointerUp(e))) so pointers tracked in this.pointers are cleaned up on
cancelled pointer interactions.

---

Outside diff comments:
In `@src/client/InputHandler.ts`:
- Around line 273-292: The window "blur" handler in InputHandler (inside the
window.addEventListener("blur", ...) block) only resets InputHandler state
(e.g., activeKeys, selectionBoxActive, multiSelectionActive) but doesn't notify
the owner of selectedWarships (UnitLayer), leaving a stale multi-selection;
update the blur handler to emit the appropriate selection-cancel/clear event via
this.eventBus (the same mechanism used for WarshipSelectionBoxCancelEvent) or a
dedicated "clear selection" event when multiSelectionActive or
selectionBoxActive is cleared so UnitLayer can drop its selectedWarships. Ensure
you reference the existing symbols InputHandler, window.addEventListener("blur",
...), this.multiSelectionActive, this.selectionBoxActive, this.eventBus and the
WarshipSelectionBoxCancelEvent (or a new ClearSelection event) when making the
change.
- Around line 251-263: The pointer stream can be interrupted by pointercancel on
mobile which leaves state like long-press timers or selection boxes stuck;
refactor the cleanup currently in onPointerUp into a new helper (e.g.,
cleanupPointer or handlePointerEnd) and call it from onPointerUp and from a new
pointercancel listener, and register that listener alongside existing event
bindings in the constructor where you attach
this.canvas.addEventListener("pointerdown", ...),
window.addEventListener("pointerup", ...), etc.; ensure the helper clears any
timers, selection state, and active pointer tracking used by
onPointerDown/onPointerMove so pointercancel behaves identical to pointerup.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ea2ff39e-d452-4f3f-9bda-1e522e549687

📥 Commits

Reviewing files that changed from the base of the PR and between f730eed and 2c9695e.

📒 Files selected for processing (2)
  • src/client/InputHandler.ts
  • src/core/execution/MoveWarshipExecution.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/core/execution/MoveWarshipExecution.ts

Comment thread src/client/InputHandler.ts Resolved
…n; pointercancel handler

- Cursor crosshair only when isSelected && units.length > 0 (multi) or isSelected (single)
- blur and Escape emit WarshipSelectionBoxCancelEvent when multiSelectionActive too
- pointercancel forwards to onPointerUp to clean up stuck pointer state
@baculinivan-web

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 21, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/client/InputHandler.ts (2)

646-665: Tiny nit: share the drag threshold with the click-vs-drag check below.

The value 10 used here as the box-drag threshold is the same magic number used at line 679 for the tap/click distance check. Pulling it into a named constant (e.g., DRAG_THRESHOLD_PX) next to LONG_PRESS_MS would make the intent clearer and keep the two in sync if one ever changes.

♻️ Suggested tidy-up
   private readonly LONG_PRESS_MS = 800;
+  private readonly DRAG_THRESHOLD_PX = 10;

Then use this.DRAG_THRESHOLD_PX at lines 652 and 679.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/InputHandler.ts` around lines 646 - 665, Introduce a shared named
drag threshold constant (e.g., DRAG_THRESHOLD_PX) alongside the existing
LONG_PRESS_MS constant and replace the hard-coded 10 in the selection box
completion logic (referencing selectionBoxActive, lastPointerDownX,
lastPointerDownY, WarshipSelectionBoxCompleteEvent,
WarshipSelectionBoxCancelEvent) with this new constant; also update the other
tap/click distance check that currently uses 10 to reference
this.DRAG_THRESHOLD_PX so both checks remain consistent.

587-615: Small defensive cleanup for the long-press timer.

If a pointerdown ever arrives while a previous longPressTimer is still pending (e.g., an orphaned pointer sequence where pointerup/pointercancel did not fire as expected), line 591 will overwrite the handle and leak the previous timeout. Clearing any existing timer first is a cheap safety net and keeps state tidy.

🧹 Proposed guard
       if (event.pointerType === "touch") {
         this.longPressActive = false;
+        if (this.longPressTimer !== null) {
+          clearTimeout(this.longPressTimer);
+        }
         this.longPressTimer = setTimeout(() => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/client/InputHandler.ts` around lines 587 - 615, When starting the
long-press timer in the pointerdown handler, clear any existing timer first to
avoid leaking timeouts; before assigning this.longPressTimer = setTimeout(...),
check if this.longPressTimer !== null and call clearTimeout(this.longPressTimer)
and set it to null. Update the logic around this.longPressTimer (used with
LONG_PRESS_MS and TouchLongPressStartEvent) so a new touch pointerdown always
replaces/cleans any previous pending timeout.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/client/InputHandler.ts`:
- Around line 630-644: Reset this.suppressNextTap to false before any early
returns in the pointerup handler that exit due to build-modifier or alt-modifier
so the leftover suppression from a prior long-press doesn’t swallow the next
real touch tap; locate the pointerup handling branch in InputHandler (the
section that checks build/alt modifiers and returns early) and add a line to set
this.suppressNextTap = false immediately before each early return (keeping the
existing long-press cleanup code that sets suppressNextTap when
selectionBoxActive is false).

---

Nitpick comments:
In `@src/client/InputHandler.ts`:
- Around line 646-665: Introduce a shared named drag threshold constant (e.g.,
DRAG_THRESHOLD_PX) alongside the existing LONG_PRESS_MS constant and replace the
hard-coded 10 in the selection box completion logic (referencing
selectionBoxActive, lastPointerDownX, lastPointerDownY,
WarshipSelectionBoxCompleteEvent, WarshipSelectionBoxCancelEvent) with this new
constant; also update the other tap/click distance check that currently uses 10
to reference this.DRAG_THRESHOLD_PX so both checks remain consistent.
- Around line 587-615: When starting the long-press timer in the pointerdown
handler, clear any existing timer first to avoid leaking timeouts; before
assigning this.longPressTimer = setTimeout(...), check if this.longPressTimer
!== null and call clearTimeout(this.longPressTimer) and set it to null. Update
the logic around this.longPressTimer (used with LONG_PRESS_MS and
TouchLongPressStartEvent) so a new touch pointerdown always replaces/cleans any
previous pending timeout.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4c3405fe-2c61-4d7d-8c9a-0b5b9418c54d

📥 Commits

Reviewing files that changed from the base of the PR and between 2c9695e and f7b5717.

📒 Files selected for processing (5)
  • resources/lang/en.json
  • src/client/InputHandler.ts
  • src/core/Schemas.ts
  • tests/InputHandler.test.ts
  • tests/Warship.test.ts
✅ Files skipped from review due to trivial changes (2)
  • tests/InputHandler.test.ts
  • resources/lang/en.json
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/Warship.test.ts
  • src/core/Schemas.ts

Comment thread src/client/InputHandler.ts Resolved
…PX constant; clear longPressTimer before new one

- Reset suppressNextTap before modifier/alt early returns in onPointerUp
- Extract DRAG_THRESHOLD_PX = 10 constant, use it in all distance checks
- Clear existing longPressTimer before starting a new one on pointerdown
@baculinivan-web

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Apr 21, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@evanpelle evanpelle left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks!

@github-project-automation github-project-automation Bot moved this from Development to Final Review in OpenFront Release Management Apr 21, 2026
@evanpelle evanpelle added this to the v31 milestone Apr 21, 2026
@evanpelle
evanpelle merged commit 29a1e8d into openfrontio:main Apr 21, 2026
10 of 11 checks passed
@github-project-automation github-project-automation Bot moved this from Final Review to Complete in OpenFront Release Management Apr 21, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Apr 24, 2026
4 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Complete

Development

Successfully merging this pull request may close these issues.

Feature Allow selecting multiple warships with keybinding (default shift)

3 participants