From 08c757dba2b5b2f52cf7d2bf6026589a463d3881 Mon Sep 17 00:00:00 2001 From: kp Date: Tue, 3 Nov 2026 22:31:46 -0800 Subject: [PATCH] feat: Shift+click selects several nodes, and the tools act on all of them With the Select tool, Shift+click adds or removes a node. Then: - dragging any of them moves the group. Every member lands the same number of tiles from where it started; if one would land on an occupied tile the whole group goes back, because a group that lands apart is not the shape the player was moving; - Link and Unlink carry the selection over and apply to the node clicked next: every member that may link does, and Unlink removes the links between the selection and that node in either direction; - Delete (Backspace on a Mac keyboard) removes them, refunding as the Demolish tool does. A click inside the group that moves nothing narrows it to that node. A single selected node does not carry into Link, because every drag leaves one selected and the next click would be a wire nobody asked for. The selection is now STATE.selection, a set of node ids, and selectedNodeId goes back to being only the Link source. The help screen's Select entry claimed that clicking Compute or a DB upgrades it, which the placement tools do. It now describes what the tool does, in all eleven locales. The README's controls list has this and the Shift hold from the previous change. Touch has no Shift, so phones keep single selection. Closes #89 item 2. --- README.md | 4 +- game.js | 9 +- index.html | 7 +- src/entities/Service.js | 9 +- src/input/handlers.js | 135 ++++++-- src/locales/de.js | 2 +- src/locales/en.js | 2 +- src/locales/fr.js | 2 +- src/locales/hi.js | 2 +- src/locales/it.js | 2 +- src/locales/ko.js | 2 +- src/locales/nep.js | 2 +- src/locales/pt-BR.js | 2 +- src/locales/ru.js | 2 +- src/locales/uk.js | 2 +- src/locales/zh.js | 2 +- src/persistence/save-load.js | 1 + src/sim/topology.js | 3 + src/state.js | 3 +- src/ui/link-feedback.js | 30 +- tests/helpers/sim-world.mjs | 1 + tests/sim/multi-select.test.mjs | 490 ++++++++++++++++++++++++++++++ tests/sim/selected-links.test.mjs | 10 +- 23 files changed, 651 insertions(+), 73 deletions(-) create mode 100644 tests/sim/multi-select.test.mjs diff --git a/README.md b/README.md index 27f6358..9d55916 100644 --- a/README.md +++ b/README.md @@ -169,7 +169,9 @@ Built something you're proud of? The share panel exports your architecture two w - **Hide HUD:** Press `H` to toggle UI panels. - **Category Tabs:** The toolbar groups services into five tabs — Front Door, Compute, Data, Async, Ops. Keys `1-5` switch between them. - **Build Tools:** `V` Select, `C` Link, `X` Demolish, `U` Unlink. Each key is shown in the corner of its button. -- **Connect Tool:** Click two nodes to create a connection (flow direction matters!). +- **Select Tool:** Click a node to see its links, outgoing in cyan and incoming in magenta. Drag it to move it. + - _Several at once:_ `Shift`+click adds a node to the selection. Drag any of them to move the group, press `Delete` to remove them, or choose Link or Unlink and click a node to apply it to all of them. +- **Connect Tool:** Click two nodes to create a connection (flow direction matters!). Hold `Shift` while clicking the destination to keep linking from the same source. - _Valid Flows:_ Internet -> (GeoDNS/Firewall/CDN/API Gateway) -> Load Balancer -> Queue -> Compute -> Cache -> (Search Engine/Read Replica/SQL DB/NoSQL DB/Storage) - **Delete Tool:** Remove services to recover 50% of the cost. - **Time Controls:** Pause, Play (1x), and Fast Forward (3x). diff --git a/game.js b/game.js index c4883c7..d16b8f6 100644 --- a/game.js +++ b/game.js @@ -562,6 +562,7 @@ function resetGame(mode = "survival") { // player did not draw. STATE.activeTool = "select"; STATE.selectedNodeId = null; + STATE.selection.clear(); // A run that ended while the main menu was open left its own speed here, // and Resume restores it: a new run could start at the old run's 2x. STATE.previousTimeScale = 1; @@ -1005,6 +1006,12 @@ window.startSandbox = () => { window.setTool = (t) => { STATE.activeTool = t; STATE.selectedNodeId = null; + // A multi-selection carries into Link and Unlink, which act on all of it. + // A single node does not: every drag leaves one selected, and the next + // Link click would become a wire the player never asked for. + if (STATE.selection.size < 2 || !["select", "connect", "unlink"].includes(t)) { + STATE.selection.clear(); + } document .querySelectorAll(".service-btn") .forEach((b) => b.classList.remove("active")); @@ -1469,7 +1476,7 @@ function animate(time) { } if (STATE.internetNode.ring) { - if (STATE.selectedNodeId === "internet") { + if (STATE.selectedNodeId === "internet" || STATE.selection.has("internet")) { STATE.internetNode.ring.material.opacity = 1.0; } else { STATE.internetNode.ring.material.opacity = 0.2; diff --git a/index.html b/index.html index 6ff191f..e4ebad4 100644 --- a/index.html +++ b/index.html @@ -1261,8 +1261,11 @@

TOOL SELECT

- Inspect services to see load and stats. Click Compute/DB to - upgrade. + Click a node to see its links: + outgoing and + incoming. Drag to move it. + Shift+click selects several: drag them together, use Link or + Unlink and click a node to act on all of them, or press Delete.

diff --git a/src/entities/Service.js b/src/entities/Service.js index ac629d8..43130f1 100644 --- a/src/entities/Service.js +++ b/src/entities/Service.js @@ -802,30 +802,31 @@ export class Service { // teaching one colour language in the campaign and another in survival // would be worse than the bug. const ringLoad = this.smoothedLoad; + const selected = STATE.selectedNodeId === this.id || STATE.selection.has(this.id); if (ringLoad > CONFIG.load.ringRed) { this.loadRing.material.color.setHex(0xff0000); - if (STATE.selectedNodeId === this.id) { + if (selected) { this.loadRing.material.opacity = 1.0; } else { this.loadRing.material.opacity = 0.8; } } else if (ringLoad > CONFIG.load.ringOrange) { this.loadRing.material.color.setHex(0xffaa00); - if (STATE.selectedNodeId === this.id) { + if (selected) { this.loadRing.material.opacity = 1.0; } else { this.loadRing.material.opacity = 0.6; } } else if (ringLoad > CONFIG.load.ringYellow) { this.loadRing.material.color.setHex(0xffff00); - if (STATE.selectedNodeId === this.id) { + if (selected) { this.loadRing.material.opacity = 1.0; } else { this.loadRing.material.opacity = 0.4; } } else { this.loadRing.material.color.setHex(0x00ff00); - if (STATE.selectedNodeId === this.id) { + if (selected) { this.loadRing.material.opacity = 1.0; } else { this.loadRing.material.opacity = 0.3; diff --git a/src/input/handlers.js b/src/input/handlers.js index 0608c6f..4e45f4e 100644 --- a/src/input/handlers.js +++ b/src/input/handlers.js @@ -26,6 +26,8 @@ import { deleteConnection, deleteObject, getConnectionAtPoint, + linkTargets, + nodeById, snapToGrid, updateConnectionsForNode, } from "../sim/topology.js"; @@ -86,6 +88,8 @@ let isDraggingNode = false; let draggedNode = null; let dragOffset = new THREE.Vector3(); let dragStartPos = new THREE.Vector3(); +// The rest of a multi-selection, moving with draggedNode: { node, start }. +let dragGroup = []; let isPanning = false; let lastMouseX = 0; @@ -417,7 +421,19 @@ function handlePrimaryDown(clientX, clientY, preventDefault = () => {}, shiftKey const i = getIntersect(clientX, clientY); if (STATE.activeTool === "select") { const i = getIntersect(clientX, clientY); - STATE.selectedNodeId = i.type === "ground" ? null : i.id; + const nodeId = i.type === "ground" ? null : i.id; + if (shiftKey) { + // Shift+click only edits the selection: no grab, no repair. + if (nodeId && !STATE.selection.delete(nodeId)) STATE.selection.add(nodeId); + preventDefault(); + return; + } + // A click inside a multi-selection keeps it, to drag the group. + // finishNodeDrag narrows it to this node if nothing moved. + if (!STATE.selection.has(nodeId)) { + STATE.selection.clear(); + if (nodeId) STATE.selection.add(nodeId); + } if (i.type === "service") { const svc = STATE.services.find((s) => s.id === i.id); // Use criticalHealth from config for consistency @@ -440,6 +456,11 @@ function handlePrimaryDown(clientX, clientY, preventDefault = () => {}, shiftKey if (draggedNode) { isDraggingNode = true; dragStartPos.copy(draggedNode.position); + dragGroup = [...STATE.selection] + .filter((id) => id !== draggedNode.id) + .map(nodeById) + .filter(Boolean) + .map((node) => ({ node, start: node.position.clone() })); const hit = getIntersect(clientX, clientY); if (hit.pos) { dragOffset.copy(draggedNode.position).sub(hit.pos); @@ -451,8 +472,15 @@ function handlePrimaryDown(clientX, clientY, preventDefault = () => {}, shiftKey } else if (STATE.activeTool === "delete" && i.type === "service") deleteObject(i.id); else if (STATE.activeTool === "unlink") { + const onNode = i.type === "service" || i.type === "internet"; const conn = getConnectionAtPoint(clientX, clientY); - if (conn) { + if (STATE.selection.size > 1 && onNode) { + if (unlinkSelectionFrom(i.id)) { + if (!shiftKey) STATE.selection.clear(); + } else { + new Audio("assets/sounds/click-9.mp3").play(); + } + } else if (conn) { deleteConnection(conn.from, conn.to); } else { new Audio("assets/sounds/click-9.mp3").play(); @@ -461,7 +489,10 @@ function handlePrimaryDown(clientX, clientY, preventDefault = () => {}, shiftKey STATE.activeTool === "connect" && (i.type === "service" || i.type === "internet") ) { - if (STATE.selectedNodeId) { + if (STATE.selection.size > 1) { + linkSelectionTo(i.id); + if (!shiftKey) STATE.selection.clear(); + } else if (STATE.selectedNodeId) { createConnection(STATE.selectedNodeId, i.id); // Shift keeps the source, to wire one node to several (#89). if (!shiftKey) STATE.selectedNodeId = null; @@ -503,6 +534,23 @@ function handlePrimaryDown(clientX, clientY, preventDefault = () => {}, shiftKey } } +// Links every selected node to `targetId`. When none of them may, the first one +// tries anyway, because its refusal is what explains the rule to the player. +function linkSelectionTo(targetId) { + const sources = [...STATE.selection]; + const accepted = sources.filter((id) => linkTargets(id).has(targetId)); + (accepted.length ? accepted : sources.slice(0, 1)).forEach((id) => createConnection(id, targetId)); +} + +// Removes the links between `id` and the selection, in either direction. +function unlinkSelectionFrom(id) { + const links = STATE.connections.filter( + (c) => (STATE.selection.has(c.from) && c.to === id) || (c.from === id && STATE.selection.has(c.to)) + ); + links.forEach((c) => deleteConnection(c.from, c.to)); + return links.length; +} + container.addEventListener("mousedown", (e) => { if (!STATE.isRunning) return; @@ -547,20 +595,13 @@ function handlePointerMove(clientX, clientY) { const newPos = hit.pos.clone().add(dragOffset); newPos.y = 0; - draggedNode.position.copy(newPos); - - if (draggedNode === STATE.internetNode) { - STATE.internetNode.mesh.position.x = newPos.x; - STATE.internetNode.mesh.position.z = newPos.z; - STATE.internetNode.ring.position.x = newPos.x; - STATE.internetNode.ring.position.z = newPos.z; - } else if (draggedNode.mesh) { - draggedNode.mesh.position.x = newPos.x; - draggedNode.mesh.position.z = newPos.z; + moveNodeTo(draggedNode, newPos); + for (const { node, start } of dragGroup) { + const pos = start.clone().add(newPos).sub(dragStartPos); + pos.y = 0; + moveNodeTo(node, pos); } - updateConnectionsForNode(draggedNode.id); - container.style.cursor = "grabbing"; } return; @@ -747,7 +788,7 @@ function handlePointerMove(clientX, clientY) { } content += `
`; - if (STATE.activeTool === "select" && STATE.selectedNodeId === s.id) { + if (STATE.activeTool === "select" && STATE.selection.has(s.id)) { content += `
${selectedLinksLine(s.id)}
`; } @@ -928,36 +969,51 @@ window.addEventListener("toolbarRendered", setupUITooltips); // if nothing is being dragged. Shared by every way a grab can end — mouse // release, touch release, touch cancel — since it only ever acts on the // module's own drag state and takes nothing from the event that ended it. +function moveNodeTo(node, pos) { + node.position.copy(pos); + + if (node === STATE.internetNode) { + STATE.internetNode.mesh.position.x = pos.x; + STATE.internetNode.mesh.position.z = pos.z; + STATE.internetNode.ring.position.x = pos.x; + STATE.internetNode.ring.position.z = pos.z; + } else if (node.mesh) { + node.mesh.position.x = pos.x; + node.mesh.position.z = pos.z; + } + + updateConnectionsForNode(node.id); +} + function finishNodeDrag() { if (!(isDraggingNode && draggedNode)) return; isDraggingNode = false; - let snapped = snapToGrid(draggedNode.position); + const home = snapToGrid(dragStartPos); + const snapped = snapToGrid(draggedNode.position); + const group = dragGroup; + dragGroup = []; + // Every member lands the same whole number of tiles from where it started. + const landings = group.map(({ start }) => snapToGrid(start.clone().add(snapped).sub(home))); // Reject a drop onto a tile already occupied by another service — // otherwise the two overlap and whichever mesh the raycaster hits first // makes the other permanently unselectable (can't delete/upgrade it). - const occupied = STATE.services.some( - (s) => s !== draggedNode && s.position.distanceTo(snapped) < 1 + // One blocked member sends the whole group back: a group that lands apart + // is not the shape the player was moving. + const moving = new Set([draggedNode, ...group.map((m) => m.node)]); + const occupied = [snapped, ...landings].some((pos) => + STATE.services.some((s) => !moving.has(s) && s.position.distanceTo(pos) < 1) ); - if (occupied) { - snapped = snapToGrid(dragStartPos); - } - draggedNode.position.copy(snapped); + moveNodeTo(draggedNode, occupied ? home : snapped); + group.forEach(({ node, start }, k) => moveNodeTo(node, occupied ? snapToGrid(start) : landings[k])); - if (draggedNode === STATE.internetNode) { - STATE.internetNode.mesh.position.x = snapped.x; - STATE.internetNode.mesh.position.z = snapped.z; - STATE.internetNode.ring.position.x = snapped.x; - STATE.internetNode.ring.position.z = snapped.z; - } else if (draggedNode.mesh) { - draggedNode.mesh.position.x = snapped.x; - draggedNode.mesh.position.z = snapped.z; + if (group.length && !occupied && snapped.distanceTo(home) < 1) { + STATE.selection.clear(); + STATE.selection.add(draggedNode.id); } - updateConnectionsForNode(draggedNode.id); - draggedNode = null; container.style.cursor = "default"; } @@ -1001,6 +1057,7 @@ export function endPointerInteraction() { const wasActive = isDraggingNode || isPanning || isOrbiting; isDraggingNode = false; draggedNode = null; + dragGroup = []; isPanning = false; isOrbiting = false; if (container) container.style.cursor = "default"; @@ -1228,6 +1285,18 @@ document.addEventListener("keydown", (event) => { return; } if (isTypingTarget(event.target)) return; + // Backspace is what a Mac keyboard calls its Delete key. + if ( + (event.key === "Delete" || event.key === "Backspace") && + STATE.activeTool === "select" && + STATE.isRunning && + !window.tutorial?.isActive && + document.getElementById("main-menu-modal").classList.contains("hidden") + ) { + [...STATE.selection].forEach(deleteObject); + STATE.selection.clear(); + return; + } if (event.key === "H" || event.key === "h") { document.getElementById("statsPanel").classList.toggle("hidden"); document.getElementById("detailsPanel").classList.toggle("hidden"); diff --git a/src/locales/de.js b/src/locales/de.js index 19c95b4..fd5347c 100644 --- a/src/locales/de.js +++ b/src/locales/de.js @@ -313,7 +313,7 @@ export const DE_TRANSLATIONS = { "cache_desc_short": "Cache-Layer ($60)", "storage_desc_short": "Speichert Web-Daten ($25)", "tools_controls": "WERKZEUGE & STEUERUNG", - "tool_select_desc": "Inspiziere Dienste für Last und Statistiken. Klicke Compute/DB zum Upgraden.", + "tool_select_desc": "Klicke auf einen Knoten, um seine Verbindungen zu sehen: ausgehende und eingehende. Ziehen verschiebt ihn. Shift+Klick wählt mehrere aus: gemeinsam ziehen, mit Verbinden oder Trennen einen Knoten anklicken, um auf alle zu wirken, oder Entf drücken.", "tool_connect_desc": "Verbinde Knoten. Klicke Quelle dann Ziel. Halte Shift beim Klick auf das Ziel, um von derselben Quelle weiter zu verbinden.", "tool_delete_desc": "Entferne Komponenten oder Verbindungen. Komponenten erstatten 50% der Kosten.", "tool_unlink": "TRENNEN", diff --git a/src/locales/en.js b/src/locales/en.js index fe1c58c..a7743a5 100644 --- a/src/locales/en.js +++ b/src/locales/en.js @@ -313,7 +313,7 @@ export const EN_TRANSLATIONS = { "cache_desc_short": "Cache layer ($60)", "storage_desc_short": "Stores Web Data ($25)", "tools_controls": "TOOLS & CONTROLS", - "tool_select_desc": "Inspect services to see load and stats. Click Compute/DB to upgrade.", + "tool_select_desc": "Click a node to see its links: outgoing and incoming. Drag to move it. Shift+click selects several: drag them together, use Link or Unlink and click a node to act on all of them, or press Delete.", "tool_connect_desc": "Link nodes together. Click Source then Destination. Hold Shift while clicking the destination to keep linking from the same source.", "tool_delete_desc": "Remove components or links. Components refund 50% of their cost.", "tool_unlink": "UNLINK", diff --git a/src/locales/fr.js b/src/locales/fr.js index 9be414c..ccade39 100644 --- a/src/locales/fr.js +++ b/src/locales/fr.js @@ -313,7 +313,7 @@ export const FR_TRANSLATIONS = { "cache_desc_short": "Couche de cache ($60)", "storage_desc_short": "Stocke les données web ($25)", "tools_controls": "OUTILS & CONTRÔLES", - "tool_select_desc": "Inspectez les services pour voir la charge et les statistiques. Cliquez sur Calcul/DB pour améliorer.", + "tool_select_desc": "Cliquez sur un nœud pour voir ses liens : sortants et entrants. Faites-le glisser pour le déplacer. Maj+clic en sélectionne plusieurs : déplacez-les ensemble, utilisez Lien ou Délier puis cliquez sur un nœud pour agir sur tous, ou appuyez sur Suppr.", "tool_connect_desc": "Liez les nœuds ensemble. Cliquez sur Source puis Destination. Maintenez Maj en cliquant sur la destination pour continuer à lier depuis la même source.", "tool_delete_desc": "Supprimez les composants ou les liens. Les composants remboursent 50% de leur coût.", "tool_unlink": "DÉLIER", diff --git a/src/locales/hi.js b/src/locales/hi.js index 0b71484..756f340 100644 --- a/src/locales/hi.js +++ b/src/locales/hi.js @@ -347,7 +347,7 @@ export const HI_TRANSLATIONS = { "cache_desc_short": "Cache layer ($60)", "storage_desc_short": "Web data store करता है ($25)", "tools_controls": "TOOLS और CONTROLS", - "tool_select_desc": "Services inspect करके load और stats देखें। Upgrade के लिए Compute/DB पर क्लिक करें।", + "tool_select_desc": "किसी node पर क्लिक करके उसके links देखें: outgoing और incoming। Drag करके उसे हिलाएँ। Shift+क्लिक से कई nodes चुनें: उन्हें साथ में drag करें, Link या Unlink चुनकर किसी node पर क्लिक करें ताकि सभी पर लागू हो, या Delete दबाएँ।", "tool_connect_desc": "Nodes को आपस में link करें। पहले Source पर क्लिक करें, फिर Destination पर। Destination पर क्लिक करते समय Shift दबाए रखें, ताकि उसी Source से आगे भी link कर सकें।", "tool_delete_desc": "Components या links हटाएँ। Components की 50% लागत वापस मिलती है।", "tool_unlink": "UNLINK", diff --git a/src/locales/it.js b/src/locales/it.js index b3993c6..2cffff8 100644 --- a/src/locales/it.js +++ b/src/locales/it.js @@ -313,7 +313,7 @@ export const IT_TRANSLATIONS = { "cache_desc_short": "Livello Cache ($60)", "storage_desc_short": "Memorizza Dati Web ($25)", "tools_controls": "STRUMENTI E CONTROLLI", - "tool_select_desc": "Ispeziona i servizi per vedere carico e statistiche. Fai clic su Compute/DB per aggiornare.", + "tool_select_desc": "Fai clic su un nodo per vederne i collegamenti: in uscita e in entrata. Trascinalo per spostarlo. Maiusc+clic ne seleziona più di uno: trascinali insieme, usa Collega o Scollega e fai clic su un nodo per agire su tutti, oppure premi Canc.", "tool_connect_desc": "Collega i nodi tra loro. Fai clic su Origine e poi su Destinazione. Tieni premuto Maiusc mentre fai clic sulla destinazione per continuare a collegare dalla stessa origine.", "tool_delete_desc": "Rimuovi componenti o collegamenti. I componenti rimborsano il 50% del costo.", "tool_unlink": "SCOLLEGA", diff --git a/src/locales/ko.js b/src/locales/ko.js index a81ac68..2f45904 100644 --- a/src/locales/ko.js +++ b/src/locales/ko.js @@ -313,7 +313,7 @@ export const KO_TRANSLATIONS = { "cache_desc_short": "캐시 레이어 ($60)", "storage_desc_short": "웹 데이터 저장 ($25)", "tools_controls": "도구 및 컨트롤", - "tool_select_desc": "서비스를 검사해 부하와 통계를 확인하세요. 컴퓨트/DB를 클릭해 업그레이드하세요.", + "tool_select_desc": "노드를 클릭하면 나가는 연결과 들어오는 연결이 표시됩니다. 드래그하면 이동합니다. Shift+클릭으로 여러 개를 선택해 함께 드래그하거나, 연결 또는 연결 해제를 고른 뒤 노드를 클릭해 모두에 적용하거나, Delete 키를 누르세요.", "tool_connect_desc": "노드를 연결합니다. 출발지를 클릭한 다음 목적지를 클릭하세요. 목적지를 클릭할 때 Shift 키를 누르고 있으면 같은 출발지에서 계속 연결할 수 있습니다.", "tool_delete_desc": "구성 요소 또는 연결을 제거합니다. 구성 요소는 비용의 50%를 환불합니다.", "tool_unlink": "연결 해제", diff --git a/src/locales/nep.js b/src/locales/nep.js index 0a5848e..a040bd7 100644 --- a/src/locales/nep.js +++ b/src/locales/nep.js @@ -313,7 +313,7 @@ export const NE_TRANSLATIONS = { "cache_desc_short": "क्यास तह ($60)", "storage_desc_short": "वेब डाटा भण्डारण ($25)", "tools_controls": "उपकरणहरू र नियन्त्रणहरू", - "tool_select_desc": "लोड र तथ्यांक हेर्न सेवाहरू निरीक्षण गर्नुहोस्। अपग्रेड गर्न कम्प्युट/DB मा क्लिक गर्नुहोस्।", + "tool_select_desc": "नोडमा क्लिक गरेर यसका लिंकहरू हेर्नुहोस्: बाहिर जाने र भित्र आउने। सार्न तान्नुहोस्। Shift+क्लिकले धेरै चयन गर्छ: सँगै तान्नुहोस्, लिंक वा अनलिंक छानेर नोडमा क्लिक गरी सबैमा लागू गर्नुहोस्, वा Delete थिच्नुहोस्।", "tool_connect_desc": "नोडहरू जडान गर्नुहोस्। स्रोत मा क्लिक गर्नुहोस् त्यसपछि गन्तव्य मा क्लिक गर्नुहोस्। एउटै स्रोतबाट जडान गरिरहन गन्तव्यमा क्लिक गर्दा Shift थिचिराख्नुहोस्।", "tool_delete_desc": "अवयवहरू वा लिंकहरू हटाउनुहोस्। अवयवहरूले आफ्नो लागतको ५०% फिर्ता गर्छन्।", "tool_unlink": "अनलिंक", diff --git a/src/locales/pt-BR.js b/src/locales/pt-BR.js index 1096f14..42ed6e6 100644 --- a/src/locales/pt-BR.js +++ b/src/locales/pt-BR.js @@ -313,7 +313,7 @@ export const PT_BR_TRANSLATIONS = { "cache_desc_short": "Camada de cache ($60)", "storage_desc_short": "Armazena dados do site ($25)", "tools_controls": "Ferramentas e Controles", - "tool_select_desc": "Selecione para ver carga e estatísticas de serviços. Clique em nós de computação/banco de dados para atualizar.", + "tool_select_desc": "Clique em um nó para ver seus links: de saída e de entrada. Arraste para movê-lo. Shift+clique seleciona vários: arraste-os juntos, use Conectar ou Desconectar e clique em um nó para agir em todos, ou pressione Delete.", "tool_connect_desc": "Conecte nós. Clique em origem primeiro, depois em destino. Segure Shift ao clicar no destino para continuar conectando a partir da mesma origem.", "tool_delete_desc": "Remova componentes ou conexões. Componentes reembolsam 50% do custo.", "tool_unlink": "Desconectar", diff --git a/src/locales/ru.js b/src/locales/ru.js index f7ee13d..5a88ee6 100644 --- a/src/locales/ru.js +++ b/src/locales/ru.js @@ -313,7 +313,7 @@ export const RU_TRANSLATIONS = { "cache_desc_short": "Кэш‑слой ($60)", "storage_desc_short": "Хранит веб‑данные ($25)", "tools_controls": "ИНСТРУМЕНТЫ И УПРАВЛЕНИЕ", - "tool_select_desc": "Осматривайте сервисы. Нажмите на Compute/DB для улучшения.", + "tool_select_desc": "Нажмите на узел, чтобы увидеть его связи: исходящие и входящие. Перетащите, чтобы переместить. Shift+клик выбирает несколько: двигайте их вместе, выберите «Соединить» или «Разорвать связь» и нажмите на узел, чтобы применить ко всем, или нажмите Delete.", "tool_connect_desc": "Соединяйте узлы. Нажмите Источник → Назначение. Удерживайте Shift при клике на назначение, чтобы продолжать соединять из того же источника.", "tool_delete_desc": "Удаляйте компоненты или связи. Возвращается 50% стоимости компонента.", "tool_unlink": "РАЗОРВАТЬ", diff --git a/src/locales/uk.js b/src/locales/uk.js index 987c76a..6828d27 100644 --- a/src/locales/uk.js +++ b/src/locales/uk.js @@ -311,7 +311,7 @@ export const UK_TRANSLATIONS = { "cache_desc_short": "Шар кешу ($60)", "storage_desc_short": "Зберігає веб-дані ($25)", "tools_controls": "ІНСТРУМЕНТИ Й КЕРУВАННЯ", - "tool_select_desc": "Оглядай сервіси, щоб бачити навантаження та статистику. Клікни Compute чи БД, щоб апгрейднути.", + "tool_select_desc": "Клікни вузол, щоб побачити його звʼязки: вихідні та вхідні. Перетягни, щоб перемістити. Shift+клік вибирає кілька: рухай їх разом, обери «Зʼєднати» чи «Розʼєднати» і клікни вузол, щоб застосувати до всіх, або натисни Delete.", "tool_connect_desc": "Зʼєднуй вузли між собою. Клікни Джерело, потім Ціль. Тримай Shift, коли клікаєш ціль, щоб далі зʼєднувати з того самого джерела.", "tool_delete_desc": "Видаляй компоненти або звʼязки. За компоненти повертається 50% вартості.", "tool_unlink": "РОЗʼЄДНАТИ", diff --git a/src/locales/zh.js b/src/locales/zh.js index e17ba6d..45ef399 100644 --- a/src/locales/zh.js +++ b/src/locales/zh.js @@ -313,7 +313,7 @@ export const ZH_TRANSLATIONS = { "cache_desc_short": "缓存层 ($60)", "storage_desc_short": "存储网站数据 ($25)", "tools_controls": "工具与控制", - "tool_select_desc": "检查服务以查看负载和统计信息。点击计算节点/数据库进行升级。", + "tool_select_desc": "点击节点查看其连接:出站和入站。拖动可移动节点。按住 Shift 点击可多选:一起拖动,或选择“连接”或“断开”后点击某个节点以应用到全部,或按 Delete 键。", "tool_connect_desc": "连接节点。点击 源 然后点击 目的地。 点击目的地时按住 Shift,可以继续从同一个源连接。", "tool_delete_desc": "移除组件或连接。组件可退还 50% 的成本。", "tool_unlink": "断开连接", diff --git a/src/persistence/save-load.js b/src/persistence/save-load.js index 0b4b976..0dafede 100644 --- a/src/persistence/save-load.js +++ b/src/persistence/save-load.js @@ -244,6 +244,7 @@ function loadGameState(saveData = null) { }; STATE.activeTool = saveData.activeTool || "select"; STATE.selectedNodeId = saveData.selectedNodeId || null; + STATE.selection.clear(); STATE.lastTime = performance.now(); // Reset timing STATE.spawnTimer = saveData.spawnTimer || 0; STATE.currentRPS = saveData.currentRPS || 0.5; diff --git a/src/sim/topology.js b/src/sim/topology.js index 9ca1f06..b06b3d9 100644 --- a/src/sim/topology.js +++ b/src/sim/topology.js @@ -364,6 +364,7 @@ function deleteObject(id) { return; } + STATE.selection.delete(id); STATE.services.forEach( (s) => (s.connections = s.connections.filter((c) => c !== id)) ); @@ -499,6 +500,7 @@ function findSPOFs(state = STATE) { } function clearAllServices() { + STATE.selection.clear(); STATE.services.forEach((s) => s.destroy()); STATE.services = []; recomputePower(); @@ -516,6 +518,7 @@ function clearAllServices() { } export { + nodeById, clearAllServices, createConnection, createService, diff --git a/src/state.js b/src/state.js index 3d746c7..4bae851 100644 --- a/src/state.js +++ b/src/state.js @@ -38,7 +38,8 @@ export const STATE = { }, activeTool: 'select', - selectedNodeId: null, + selectedNodeId: null, // the Link tool's source + selection: new Set(), // what the Select tool has picked: node ids services: [], requests: [], connections: [], diff --git a/src/ui/link-feedback.js b/src/ui/link-feedback.js index 12acbaa..8ab43b0 100644 --- a/src/ui/link-feedback.js +++ b/src/ui/link-feedback.js @@ -91,6 +91,12 @@ export function showLinkRejected(fromType, toType, targets) { }, SHOW_MS - 300); } +function linkSources() { + if (STATE.activeTool !== "connect") return []; + if (STATE.selection.size > 1) return [...STATE.selection]; + return STATE.selectedNodeId ? [STATE.selectedNodeId] : []; +} + /** * Rings every node the picked Link source could connect to, before the player * clicks, so the rule is visible rather than discovered one refusal at a time. @@ -98,13 +104,12 @@ export function showLinkRejected(fromType, toType, targets) { * paused. Any tool but Link, or no source picked yet, clears every ring. */ export function showLinkTargets(now = 0) { - const sourceId = STATE.activeTool === "connect" ? STATE.selectedNodeId : null; - const targets = sourceId ? linkTargets(sourceId) : null; + const targets = new Set(linkSources().flatMap((id) => [...linkTargets(id)])); // A slow pulse, so a ring reads as an offer rather than as a state. const opacity = 0.55 + 0.35 * Math.sin(now / 250); for (const s of STATE.services) { if (!s.linkTargetRing) continue; - const on = targets !== null && targets.has(s.id); + const on = targets.has(s.id); s.linkTargetRing.visible = on; if (on) s.linkTargetRing.material.opacity = opacity; } @@ -113,15 +118,9 @@ export function showLinkTargets(now = 0) { // Whether showSelectedLinks() has recoloured the links and owes them a reset. let linksPainted = false; -function selectedNode() { - if (STATE.activeTool !== "select" || !STATE.selectedNodeId) return null; - if (STATE.selectedNodeId === "internet") return "internet"; - return STATE.services.some((s) => s.id === STATE.selectedNodeId) ? STATE.selectedNodeId : null; -} - /** - * Colours the links of the node the Select tool has picked: what it sends to, - * what it receives from, and the rest dimmed so those two stand out. + * Colours the links of what the Select tool has picked: what it sends to, what + * it receives from, and the rest dimmed so those two stand out. * * Called from animate() last before the render, paused or not, because the * hover path in handlers.js resets every link on every pointer move. With @@ -129,14 +128,15 @@ function selectedNode() { * last a frame, apart from the one reset a cleared selection is owed. */ export function showSelectedLinks() { - const id = selectedNode(); - if (!id && !linksPainted) return; - linksPainted = id !== null; + const picked = STATE.activeTool === "select" ? STATE.selection : null; + const any = picked !== null && picked.size > 0; + if (!any && !linksPainted) return; + linksPainted = any; const { line, lineActive, lineIncoming, lineDim } = CONFIG.colors; for (const c of STATE.connections) { if (!c.mesh?.material) continue; let color = line; - if (id) color = c.from === id ? lineActive : c.to === id ? lineIncoming : lineDim; + if (any) color = picked.has(c.from) ? lineActive : picked.has(c.to) ? lineIncoming : lineDim; c.mesh.material.color.setHex(color); } } diff --git a/tests/helpers/sim-world.mjs b/tests/helpers/sim-world.mjs index c7bf642..a56ba9c 100644 --- a/tests/helpers/sim-world.mjs +++ b/tests/helpers/sim-world.mjs @@ -45,6 +45,7 @@ export function resetWorld({ money = 100000, gameMode = "sandbox" } = {}) { STATE.spawnTimer = 0; STATE.currentRPS = 0; STATE.selectedNodeId = null; + STATE.selection.clear(); STATE.activeTool = "select"; // ...and so do the interventions, which this helper's own header has diff --git a/tests/sim/multi-select.test.mjs b/tests/sim/multi-select.test.mjs new file mode 100644 index 0000000..aa552d1 --- /dev/null +++ b/tests/sim/multi-select.test.mjs @@ -0,0 +1,490 @@ +// Shift+click selects several nodes, and the operations act on all of them +// (#89 item 2): dragging moves the group, Link and Unlink carry the selection +// over and apply it to the node clicked next, and Delete removes it. +// +// Real mouse and key events throughout. The raycaster is primed per click, and +// the ground point follows `pointer`, because a drag is measured against it. +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { STATE } from "../../src/state.js"; +import { CONFIG } from "../../src/config.js"; +import { resetGame, raycaster } from "../../game.js"; +import { clearAllServices, createConnection, createService } from "../../src/sim/topology.js"; +import { showLinkTargets, showSelectedLinks } from "../../src/ui/link-feedback.js"; +import { loadGameState } from "../../src/persistence/save-load.js"; +import { i18n } from "../../src/i18n.js"; +import { raycastHits, resetRaycastHits } from "../helpers/three-stub.mjs"; + +const T = globalThis.THREE; +const TILE = CONFIG.tileSize; +const container = () => document.getElementById("canvas-container"); +const savedIntersectPlane = raycaster.ray.intersectPlane; +let pointer = { x: 0, z: 0 }; + +function place(type, tileX, tileZ = 0) { + createService(type, new T.Vector3(tileX * TILE, 0, tileZ * TILE)); + return STATE.services[STATE.services.length - 1]; +} + +function mouse(type, init = {}) { + container().dispatchEvent( + new globalThis.MouseEvent(type, { bubbles: true, button: 0, clientX: 10, clientY: 10, ...init }) + ); +} + +function down(node, { shiftKey = false } = {}) { + raycastHits.services = node ? [{ object: node.mesh }] : []; + mouse("mousedown", { shiftKey }); + resetRaycastHits(); +} + +function click(node, opts) { + down(node, opts); + mouse("mouseup"); +} + +function dragTo(tileX, tileZ = 0) { + pointer = { x: tileX * TILE, z: tileZ * TILE }; + resetRaycastHits(); + mouse("mousemove"); +} + +const tile = (s) => [s.position.x / TILE, s.position.z / TILE]; +const meshTile = (s) => [s.mesh.position.x / TILE, s.mesh.position.z / TILE]; +const selection = () => [...STATE.selection]; +const links = () => STATE.connections.map((c) => [c.from, c.to]); +const press = (key, target = document.body) => + target.dispatchEvent(new globalThis.KeyboardEvent("keydown", { key, bubbles: true })); + +let a, b, other; + +beforeEach(() => { + resetGame("survival"); + resetRaycastHits(); + raycaster.ray.intersectPlane = (_plane, target) => target.set(pointer.x, 0, pointer.z); + STATE.isRunning = true; + STATE.money = 100000; + document.getElementById("main-menu-modal").classList.add("hidden"); + window.setTool("select"); + a = place("compute", 0); + b = place("compute", 2); + other = place("db", 10); +}); + +afterEach(() => { + resetRaycastHits(); + raycaster.ray.intersectPlane = savedIntersectPlane; + i18n.setLocale("en"); + if (STATE.animationId) { + globalThis.cancelAnimationFrame(STATE.animationId); + STATE.animationId = null; + } +}); + +describe("building a selection", () => { + it("Shift+click adds a node, and again removes it", () => { + click(a); + click(b, { shiftKey: true }); + expect(selection()).toEqual([a.id, b.id]); + + click(a, { shiftKey: true }); + expect(selection()).toEqual([b.id]); + }); + + it("Shift+click neither grabs nor repairs", () => { + a.health = 10; + + down(a, { shiftKey: true }); + + expect(a.health).toBe(10); + expect(container().style.cursor).not.toBe("grabbing"); + mouse("mouseup"); + }); + + it("a plain click on a node outside it starts over", () => { + click(a); + click(b, { shiftKey: true }); + + click(other); + + expect(selection()).toEqual([other.id]); + }); + + it("a plain click on the ground clears it, Shift on the ground keeps it", () => { + click(a); + click(b, { shiftKey: true }); + + click(null, { shiftKey: true }); + expect(selection()).toEqual([a.id, b.id]); + + click(null); + expect(selection()).toEqual([]); + }); + + it("the Internet node can join", () => { + click(a); + raycastHits.internet = [{ object: STATE.internetNode.mesh }]; + mouse("mousedown", { shiftKey: true }); + mouse("mouseup"); + resetRaycastHits(); + + expect(selection()).toEqual([a.id, "internet"]); + }); + + it("every selected node gets the bright ring", () => { + click(a); + click(b, { shiftKey: true }); + + for (const s of STATE.services) s.update(0); + + expect(a.loadRing.material.opacity).toBe(1); + expect(b.loadRing.material.opacity).toBe(1); + expect(other.loadRing.material.opacity).toBeLessThan(1); + }); + + it("a Link source keeps its bright ring too", () => { + window.setTool("connect"); + click(a); + + for (const s of STATE.services) s.update(0); + + expect(a.loadRing.material.opacity).toBe(1); + expect(b.loadRing.material.opacity).toBeLessThan(1); + }); + + it("the links of all of them are coloured", () => { + const c = place("db", 4); + const d = place("alb", -2); + createConnection(a.id, c.id); + createConnection(d.id, b.id); + createConnection(d.id, a.id); + click(a); + click(b, { shiftKey: true }); + + showSelectedLinks(); + + const colour = (from, to) => + STATE.connections.find((k) => k.from === from.id && k.to === to.id).mesh.material.color.getHex(); + expect(colour(a, c)).toBe(CONFIG.colors.lineActive); + expect(colour(d, b)).toBe(CONFIG.colors.lineIncoming); + expect(colour(d, a)).toBe(CONFIG.colors.lineIncoming); + }); +}); + +describe("dragging a selected node moves the group", () => { + beforeEach(() => { + click(a); + click(b, { shiftKey: true }); + }); + + it("every member moves by the same number of tiles and stays selected", () => { + down(a); + dragTo(5, 3); + mouse("mouseup"); + + expect(tile(a)).toEqual([5, 3]); + expect(tile(b)).toEqual([7, 3]); + expect(meshTile(b)).toEqual([7, 3]); + expect(selection()).toEqual([a.id, b.id]); + }); + + it("the group follows the pointer during the drag", () => { + down(a); + dragTo(1, 1); + + expect(tile(b)).toEqual([3, 1]); + mouse("mouseup"); + }); + + it("the links of a member that was not grabbed follow it", () => { + const c = place("db", 4); + createConnection(b.id, c.id); + const line = STATE.connections.find((k) => k.from === b.id).mesh; + + down(a); + dragTo(0, 3); + mouse("mouseup"); + + const start = line.geometry.points[0]; + expect([start.x / TILE, start.z / TILE]).toEqual([2, 3]); + }); + + it("if one member would land on an occupied tile, the whole group goes back", () => { + // a lands on (8,0), free; b would land on (10,0), the DB's tile. + down(a); + dragTo(8); + mouse("mouseup"); + + expect(tile(a)).toEqual([0, 0]); + expect(tile(b)).toEqual([2, 0]); + expect(meshTile(b)).toEqual([2, 0]); + }); + + it("members may land on tiles the group itself is leaving", () => { + down(a); + dragTo(2); + mouse("mouseup"); + + expect(tile(a)).toEqual([2, 0]); + expect(tile(b)).toEqual([4, 0]); + }); + + it("a click that moves nothing narrows the selection to that node", () => { + click(b); + + expect(selection()).toEqual([b.id]); + expect(tile(b)).toEqual([2, 0]); + }); + + it("a blocked drop keeps the selection, so the player can try again", () => { + down(a); + dragTo(8); + mouse("mouseup"); + + expect(selection()).toEqual([a.id, b.id]); + }); + + it("a single node still drags alone", () => { + click(other); + down(other); + dragTo(14); + mouse("mouseup"); + + expect(tile(other)).toEqual([14, 0]); + expect(tile(a)).toEqual([0, 0]); + }); +}); + +describe("Link acts on all of a multi-selection", () => { + it("links every selected node to the node clicked next", () => { + click(a); + click(b, { shiftKey: true }); + window.setTool("connect"); + + click(other); + + expect(links()).toEqual([[a.id, other.id], [b.id, other.id]]); + expect(selection()).toEqual([]); + expect(STATE.selectedNodeId).toBeNull(); + }); + + it("Shift on the target keeps the selection for another target", () => { + const db2 = place("db", 14); + click(a); + click(b, { shiftKey: true }); + window.setTool("connect"); + + click(other, { shiftKey: true }); + click(db2); + + expect(links().length).toBe(4); + expect(selection()).toEqual([]); + }); + + it("skips the members that may not link, without a refusal", () => { + const alb = place("alb", 6); + document.getElementById("intervention-warnings").innerHTML = ""; + click(alb); + click(a, { shiftKey: true }); + window.setTool("connect"); + + click(b); + + // The LB may send to Compute; a Compute may not. + expect(links()).toEqual([[alb.id, b.id]]); + expect(document.querySelector("[data-link-rejected]")).toBeNull(); + }); + + it("when none may, one refusal explains why", () => { + const dbs = [other, place("db", 14)]; + document.getElementById("intervention-warnings").innerHTML = ""; + click(dbs[0]); + click(dbs[1], { shiftKey: true }); + window.setTool("connect"); + + click(a); + + expect(links()).toEqual([]); + expect(document.querySelectorAll("[data-link-rejected]").length).toBe(1); + }); + + it("rings every node at least one of them can reach", () => { + const alb = place("alb", 6); + click(alb); + click(a, { shiftKey: true }); + window.setTool("connect"); + + showLinkTargets(); + + expect(other.linkTargetRing.visible, "a Compute can reach the DB").toBe(true); + expect(b.linkTargetRing.visible, "the LB can reach this Compute").toBe(true); + }); + + it("a single selected node does not carry over: a drag must not arm a link", () => { + click(a); + window.setTool("connect"); + expect(selection()).toEqual([]); + + click(other); + + expect(links()).toEqual([]); + expect(STATE.selectedNodeId, "the click picks a source, as ever").toBe(other.id); + }); +}); + +describe("Unlink acts on all of a multi-selection", () => { + beforeEach(() => { + createConnection(a.id, other.id); + createConnection(b.id, other.id); + }); + + it("removes the links between the selection and the node clicked", () => { + const keep = place("compute", 6); + createConnection(keep.id, other.id); + click(a); + click(b, { shiftKey: true }); + window.setTool("unlink"); + + click(other); + + expect(links()).toEqual([[keep.id, other.id]]); + expect(selection()).toEqual([]); + }); + + it("works in either direction", () => { + const lb = place("alb", 6); + createConnection(lb.id, a.id); + createConnection(lb.id, b.id); + click(a); + click(b, { shiftKey: true }); + window.setTool("unlink"); + + click(lb); + + expect(links()).toEqual([[a.id, other.id], [b.id, other.id]]); + }); + + it("with nothing to remove it keeps the selection", () => { + const lone = place("compute", 14); + click(a); + click(b, { shiftKey: true }); + window.setTool("unlink"); + + click(lone); + + expect(links().length).toBe(2); + expect(selection()).toEqual([a.id, b.id]); + }); + + it("with no selection, clicking a node removes nothing", () => { + window.setTool("unlink"); + + click(other); + + expect(links().length).toBe(2); + }); +}); + +describe("Delete removes the selection", () => { + beforeEach(() => { + click(a); + click(b, { shiftKey: true }); + }); + + it.each(["Delete", "Backspace"])("%s removes every selected node", (key) => { + press(key); + + expect(STATE.services).toEqual([other]); + expect(selection()).toEqual([]); + }); + + it("refunds them as the Demolish tool does", () => { + const before = STATE.money; + + press("Delete"); + + expect(STATE.money).toBe(before + CONFIG.services.compute.cost); + }); + + it("the Internet node survives it", () => { + STATE.selection.add("internet"); + + press("Delete"); + + expect(STATE.internetNode.mesh).toBeTruthy(); + expect(STATE.services).toEqual([other]); + }); + + it("not while typing in a field", () => { + const field = document.createElement("input"); + document.body.appendChild(field); + + press("Backspace", field); + + expect(STATE.services.length).toBe(3); + field.remove(); + }); + + it("not with the main menu open", () => { + document.getElementById("main-menu-modal").classList.remove("hidden"); + + press("Delete"); + + expect(STATE.services.length).toBe(3); + }); + + it("not during the tutorial", () => { + window.tutorial.isActive = true; + + press("Delete"); + + window.tutorial.isActive = false; + expect(STATE.services.length).toBe(3); + }); +}); + +describe("the selection ends", () => { + beforeEach(() => { + click(a); + click(b, { shiftKey: true }); + }); + + it("when a placement or Demolish tool is chosen", () => { + window.setTool("delete"); + expect(selection()).toEqual([]); + }); + + it("with the run", () => { + resetGame("sandbox"); + expect(selection()).toEqual([]); + }); + + it("when a save is loaded", () => { + loadGameState({ + version: "2.0", + money: 500, + reputation: 80, + requestsProcessed: 0, + isRunning: false, + services: [], + connections: [], + internetConnections: [], + }); + expect(selection()).toEqual([]); + }); + + it("when the sandbox board is cleared", () => { + clearAllServices(); + expect(selection()).toEqual([]); + }); +}); + +describe("the help screen teaches it", () => { + it.each(["en", "de", "fr", "hi", "it", "ko", "nep", "pt-BR", "ru", "uk", "zh"])("in %s", (locale) => { + i18n.setLocale(locale); + const key = { fr: "Maj", it: "Maiusc" }[locale] || "Shift"; + + expect(i18n.t("tool_select_desc")).toContain(key); + expect(i18n.t("tool_select_desc")).toContain("text-cyan-400"); + expect(i18n.t("tool_select_desc")).toContain("text-fuchsia-400"); + }); +}); diff --git a/tests/sim/selected-links.test.mjs b/tests/sim/selected-links.test.mjs index 9556fad..10af634 100644 --- a/tests/sim/selected-links.test.mjs +++ b/tests/sim/selected-links.test.mjs @@ -69,7 +69,7 @@ describe("clicking a node with the Select tool", () => { it("selects it", () => { down(alb); - expect(STATE.selectedNodeId).toBe(alb.id); + expect([...STATE.selection]).toEqual([alb.id]); }); it("colours its outgoing and incoming links differently, and dims the rest", () => { @@ -85,7 +85,7 @@ describe("clicking a node with the Select tool", () => { it("also works for the Internet node", () => { STATE.internetNode.connections = []; createConnection("internet", waf.id); - STATE.selectedNodeId = "internet"; + STATE.selection.add("internet"); showSelectedLinks(); const c = STATE.connections.find((k) => k.from === "internet"); @@ -98,7 +98,7 @@ describe("clicking a node with the Select tool", () => { new globalThis.MouseEvent("mousedown", { bubbles: true, button: 0, clientX: 10, clientY: 10 }) ); - expect(STATE.selectedNodeId).toBe(alb.id); + expect([...STATE.selection]).toEqual([alb.id]); expect(container().style.cursor).toBe("grabbing"); }); @@ -107,7 +107,7 @@ describe("clicking a node with the Select tool", () => { down(alb); expect(alb.health).toBeGreaterThan(10); - expect(STATE.selectedNodeId).toBe(alb.id); + expect([...STATE.selection]).toEqual([alb.id]); }); it("clicking another node moves the selection", () => { @@ -132,7 +132,7 @@ describe("the links go back to normal", () => { down(null); showSelectedLinks(); - expect(STATE.selectedNodeId).toBeNull(); + expect(STATE.selection.size).toBe(0); expect(allNormal()).toEqual(normal()); });