Move app to apps/web-react in pnpm workspace layout

This commit is contained in:
Kalle
2026-08-16 09:20:33 +03:00
parent 7e365ccfcf
commit bbc8ea57af
2913 changed files with 227 additions and 250 deletions

View File

@@ -0,0 +1,100 @@
import type { DamageType } from "~/features/build-analyzer/analyzer-types";
import type {
MainWeaponId,
SpecialWeaponId,
SubWeaponId,
} from "~/modules/in-game-lists/types";
export const MAX_WEAPONS = 4;
export const MAX_DAMAGE_TYPES_PER_COMBO = 3;
export const MAX_REPEATS_PER_DAMAGE_TYPE = 2;
export const MAX_COMBOS_DISPLAYED = 50;
export const COMBO_DAMAGE_THRESHOLD = 80;
export const LETHAL_DAMAGE = 100;
export const SUB_WEAPON_CATEGORIES: Record<SubWeaponId, SubWeaponCategory> = {
0: "LETHAL", // Splat Bomb
1: "LETHAL", // Suction Bomb
2: "CHIP", // Burst Bomb
3: "TURF", // Sprinkler
4: "AREA_DENIAL", // Splash Wall
5: "CHIP", // Fizzy Bomb
6: "MOBILITY", // Curling Bomb
7: "SEEKING", // Autobomb
8: "MOBILITY", // Squid Beakon
9: "TRACKING", // Point Sensor
10: "AREA_DENIAL", // Ink Mine
11: "AREA_DENIAL", // Toxic Mist
12: "TRACKING", // Angle Shooter
13: "SEEKING", // Torpedo
};
export const SPECIAL_WEAPON_CATEGORIES: Record<
SpecialWeaponId,
SpecialWeaponCategory
> = {
1: "RANGED_BURST", // Trizooka
2: "TEAM_SHIELD", // Big Bubbler
3: "MELEE", // Zipcaster
4: "GLOBAL_TRACKING", // Tenta Missiles
5: "AREA_CONTROL", // Ink Storm
6: "RANGED_BURST", // Booyah Bomb
7: "AREA_CONTROL", // Wave Breaker
8: "TEAM_SHIELD", // Ink Vac
9: "GLOBAL_TRACKING", // Killer Wail 5.1
10: "RANGED_BURST", // Inkjet
11: "RANGED_BURST", // Ultra Stamp
12: "RANGED_BURST", // Crab Tank
13: "MELEE", // Reefslider
14: "AREA_CONTROL", // Triple Inkstrike
15: "TEAM_BUFF", // Tacticooler
16: "AREA_CONTROL", // Super Chump
17: "MELEE", // Kraken Royale
18: "MELEE", // Triple Splashdown
19: "AREA_CONTROL", // Splattercolor Screen
};
export const SUB_CATEGORY_ORDER = [
"LETHAL",
"CHIP",
"SEEKING",
"AREA_DENIAL",
"MOBILITY",
"TRACKING",
"TURF",
] as const;
export const SPECIAL_CATEGORY_ORDER = [
"MELEE",
"RANGED_BURST",
"GLOBAL_TRACKING",
"AREA_CONTROL",
"TEAM_SHIELD",
"TEAM_BUFF",
] as const;
export type SubWeaponCategory = (typeof SUB_CATEGORY_ORDER)[number];
export type SpecialWeaponCategory = (typeof SPECIAL_CATEGORY_ORDER)[number];
interface VirtualDamageCombo {
damageTypes: DamageType[];
virtualType: DamageType;
}
const EXPLOSHER_ID = 3040 as MainWeaponId;
export const VIRTUAL_DAMAGE_COMBOS: Partial<
Record<MainWeaponId, VirtualDamageCombo[]>
> = {
[EXPLOSHER_ID]: [
{
damageTypes: ["DIRECT", "DISTANCE"],
virtualType: "COMBO",
},
],
};

View File

@@ -0,0 +1,22 @@
import { useSearchParam } from "~/modules/search-params/hooks";
import { compAnalyzerSearchParams } from "./comp-analyzer-search-params";
export function useCategorization() {
return useSearchParam(compAnalyzerSearchParams, "categorization");
}
export function useSelectedWeapons() {
return useSearchParam(compAnalyzerSearchParams, "weapons");
}
export function useSingleWeaponCombos() {
return useSearchParam(compAnalyzerSearchParams, "singleCombos");
}
export function useTargetSubDefenseAp() {
return useSearchParam(compAnalyzerSearchParams, "subDef");
}
export function useTargetResAp() {
return useSearchParam(compAnalyzerSearchParams, "res");
}

View File

@@ -0,0 +1,43 @@
import { describe, expect, test } from "vitest";
import * as SearchParams from "~/modules/search-params/search-params";
import {
assertDecodesToDefault,
assertRoundTrips,
} from "~/modules/search-params/search-params-test-utils";
import { compAnalyzerSearchParams } from "./comp-analyzer-search-params";
describe("compAnalyzerSearchParams", () => {
test("round-trips", () => {
assertRoundTrips(compAnalyzerSearchParams, {
categorization: ["category", "sub", "special"],
weapons: [[], [0], [10, 20, 30, 40]],
singleCombos: [false, true],
subDef: [0, 29, 57],
res: [0, 57],
});
});
test("accepts legacy comma-joined weapon ids", () => {
expect(
SearchParams.decodeParam(compAnalyzerSearchParams.shape.weapons, [
"10,20",
]),
).toEqual([10, 20]);
});
test("malformed values decode to defaults", () => {
assertDecodesToDefault(compAnalyzerSearchParams, "categorization", [
["kit"],
]);
assertDecodesToDefault(compAnalyzerSearchParams, "weapons", [
["0,10,20,30,40"],
]);
assertDecodesToDefault(compAnalyzerSearchParams, "singleCombos", [["1"]]);
assertDecodesToDefault(compAnalyzerSearchParams, "subDef", [
["-1"],
["58"],
["abc"],
]);
assertDecodesToDefault(compAnalyzerSearchParams, "res", [["-1"], ["58"]]);
});
});

View File

@@ -0,0 +1,34 @@
import { z } from "zod";
import { MAX_AP } from "~/features/build-analyzer/analyzer-constants";
import { mainWeaponIds } from "~/modules/in-game-lists/weapon-ids";
import * as SearchParams from "~/modules/search-params/search-params";
import { SP } from "~/modules/search-params/search-params";
import { numericEnum } from "~/utils/zod";
import { MAX_WEAPONS } from "./comp-analyzer-constants";
import type { CategorizationType } from "./comp-analyzer-types";
const CATEGORIZATION_TYPES = [
"category",
"sub",
"special",
] as const satisfies readonly CategorizationType[];
export const compAnalyzerSearchParams = SearchParams.define({
categorization: SP.param(z.enum(CATEGORIZATION_TYPES), {
default: "category",
loader: false,
}),
weapons: SP.param(z.array(numericEnum(mainWeaponIds)).max(MAX_WEAPONS), {
default: [],
loader: false,
}),
singleCombos: SP.param(z.boolean(), { default: false, loader: false }),
subDef: SP.param(z.number().int().min(0).max(MAX_AP), {
default: 0,
loader: false,
}),
res: SP.param(z.number().int().min(0).max(MAX_AP), {
default: 0,
loader: false,
}),
});

View File

@@ -0,0 +1,30 @@
import type { DamageType } from "~/features/build-analyzer/analyzer-types";
import type { MainWeaponId } from "~/modules/in-game-lists/types";
export type CategorizationType = "category" | "sub" | "special";
export interface DamageSegment {
weaponSlot: number;
weaponId: MainWeaponId;
damageType: DamageType;
damageValue: number;
isSubWeapon: boolean;
isSpecialWeapon: boolean;
count: number;
}
export interface DamageCombo {
segments: DamageSegment[];
totalDamage: number;
hitCount: number;
}
export interface WeaponDamageSource {
weaponSlot: number;
weaponId: MainWeaponId;
damages: Array<{
type: DamageType;
value: number;
weaponType: "MAIN" | "SUB" | "SPECIAL";
}>;
}

View File

@@ -0,0 +1,339 @@
.container {
display: flex;
flex-direction: column;
border: 1px solid var(--color-border);
border-radius: var(--radius-field);
background: var(--color-bg);
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
padding: var(--s-2) var(--s-3);
background: var(--color-bg-higher);
border: none;
border-radius: var(--radius-field);
cursor: pointer;
font-size: var(--font-sm);
font-weight: var(--weight-semi);
color: var(--color-text);
width: 100%;
text-align: left;
&:hover {
background: var(--color-bg-high);
}
}
.headerTitle {
flex: 1;
}
.collapseIcon {
font-size: var(--font-lg);
font-weight: var(--weight-bold);
color: var(--color-text-high);
width: 20px;
text-align: center;
}
.content {
display: flex;
flex-direction: column;
gap: var(--s-3);
padding: var(--s-3);
}
.comboRow {
display: flex;
align-items: center;
gap: var(--s-4);
}
.barSection {
position: relative;
display: flex;
flex: 1;
background-color: var(--color-bg-high);
border-radius: var(--radius-selector);
overflow: hidden;
}
.segmentWrapper {
display: flex;
flex-direction: column;
min-width: fit-content;
}
.segment {
display: flex;
align-items: center;
justify-content: center;
gap: var(--s-1);
height: 36px;
padding: 0 var(--s-2);
color: var(--color-text-inverse);
font-weight: var(--weight-semi);
&[data-slot-color="yellow"] {
background-color: #f5d742;
}
&[data-slot-color="pink"] {
background-color: #f5b8d0;
}
&[data-slot-color="green"] {
background-color: #90e8a8;
}
&[data-slot-color="blue"] {
background-color: #8cd4f5;
}
}
.damageTypeLabel {
font-size: var(--font-2xs);
color: var(--color-text-high);
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding: var(--s-0-5) var(--s-0-5);
background: none;
border: 1px solid transparent;
border-radius: var(--radius-selector);
cursor: pointer;
&:hover {
text-decoration: line-through;
}
}
.damageValue {
font-size: var(--font-sm);
font-weight: var(--weight-bold);
}
.hitMultiplier {
font-size: var(--font-2xs);
font-weight: var(--weight-semi);
opacity: 0.8;
margin-left: var(--s-0-5);
}
.weaponIcon {
min-width: 24px;
min-height: 24px;
}
.subSpecialWeaponIcon {
min-width: 18px;
min-height: 18px;
}
.thresholdLine {
position: absolute;
top: 0;
bottom: 0;
width: 2px;
background-image: repeating-linear-gradient(
to bottom,
rgb(80 80 100) 0,
rgb(80 80 100) 5px,
transparent 5px,
transparent 10px
);
pointer-events: none;
z-index: 1;
}
.totalSection {
display: flex;
flex-direction: column;
align-items: flex-end;
min-width: 60px;
flex-shrink: 0;
}
.totalDamage {
font-size: var(--font-xl);
font-weight: var(--weight-bold);
}
.hitCount {
font-size: var(--font-sm);
color: var(--color-text-high);
}
.singleWeaponToggleRow {
display: flex;
padding-block-end: var(--s-3);
border-block-end: 1px solid var(--color-border);
margin-block-end: var(--s-1);
}
.filterControlsRow {
display: flex;
gap: var(--s-2);
padding-block-end: var(--s-2);
border-block-end: 1px solid var(--color-border);
margin-block-end: var(--s-1);
}
.filterControlButton {
padding: var(--s-1) var(--s-2);
background: var(--color-bg-higher);
border: 1px solid var(--color-border);
border-radius: var(--radius-field);
font-size: var(--font-xs);
color: var(--color-text);
cursor: pointer;
transition: background-color 0.15s ease;
&:hover:not(:disabled) {
background: var(--color-bg-high);
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
}
.filteredItemsRow {
display: flex;
flex-wrap: wrap;
gap: var(--s-2);
padding-bottom: var(--s-2);
border-bottom: 1px solid var(--color-border);
margin-bottom: var(--s-1);
}
.filteredItem {
display: flex;
align-items: center;
gap: var(--s-1);
padding: var(--s-1) var(--s-2);
background: var(--color-bg-higher);
border: 1px solid var(--color-border);
border-radius: var(--radius-field);
font-size: var(--font-xs);
color: var(--color-text-high);
cursor: pointer;
transition: background-color 0.15s ease;
&:hover {
background: var(--color-bg-high);
}
}
.slidersContainer {
display: grid;
grid-template-columns: auto auto 1fr auto;
gap: var(--s-2) var(--s-2);
align-items: center;
padding-bottom: var(--s-3);
border-bottom: 1px solid var(--color-border);
margin-bottom: var(--s-1);
}
@container (width < 640px) {
.slidersContainer {
grid-template-columns: auto 1fr auto;
}
/* Row 1: icon 1 + label 1 */
.slidersContainer > :nth-child(1) {
grid-row: 1;
grid-column: 1;
}
.slidersContainer > :nth-child(2) {
grid-row: 1;
grid-column: 2 / -1;
}
/* Row 2: slider 1 + value 1 */
.slidersContainer > :nth-child(3) {
grid-row: 2;
grid-column: 1 / 3;
}
.slidersContainer > :nth-child(4) {
grid-row: 2;
grid-column: 3;
}
/* Row 3: icon 2 + label 2 */
.slidersContainer > :nth-child(5) {
grid-row: 3;
grid-column: 1;
}
.slidersContainer > :nth-child(6) {
grid-row: 3;
grid-column: 2 / -1;
}
/* Row 4: slider 2 + value 2 */
.slidersContainer > :nth-child(7) {
grid-row: 4;
grid-column: 1 / 3;
}
.slidersContainer > :nth-child(8) {
grid-row: 4;
grid-column: 3;
}
}
.resSliderLabel {
font-size: var(--font-sm);
color: var(--color-text-high);
white-space: nowrap;
}
.resSlider {
min-width: 100%;
cursor: pointer;
}
.resSliderValue {
font-size: var(--font-sm);
font-weight: var(--weight-semi);
}
.inkTimeSegment {
display: flex;
align-items: center;
justify-content: center;
gap: var(--s-1);
height: 36px;
padding: 0 var(--s-2);
background: repeating-linear-gradient(
-45deg,
var(--color-bg-higher) 0,
var(--color-bg-higher) 4px,
var(--color-bg-high) 4px,
var(--color-bg-high) 8px
);
color: var(--color-text);
font-weight: var(--weight-semi);
min-width: fit-content;
}
.inkTimeDamage {
font-size: var(--font-sm);
font-weight: var(--weight-bold);
color: var(--color-text);
}
.inkTimeLabel {
font-size: var(--font-2xs);
color: var(--color-text-second);
text-align: center;
white-space: nowrap;
padding: var(--s-0-5) var(--s-0-5);
font-weight: var(--weight-semi);
}

View File

@@ -0,0 +1,430 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { SendouSwitch } from "~/components/elements/Switch";
import { Image, WeaponImage } from "~/components/Image";
import { MAX_AP } from "~/features/build-analyzer/analyzer-constants";
import { mainWeaponParams } from "~/features/build-analyzer/core/utils";
import type {
MainWeaponId,
SpecialWeaponId,
SubWeaponId,
} from "~/modules/in-game-lists/types";
import {
abilityImageUrl,
specialWeaponImageUrl,
subWeaponImageUrl,
} from "~/utils/urls";
import { LETHAL_DAMAGE } from "../comp-analyzer-constants";
import {
useSingleWeaponCombos,
useTargetResAp,
useTargetSubDefenseAp,
} from "../comp-analyzer-hooks";
import type { DamageCombo, DamageSegment } from "../comp-analyzer-types";
import {
calculateDamageCombos,
calculateInkTimeToKill,
type ExcludedDamageKey,
getAllDamageKeys,
} from "../core/damage-combinations";
import styles from "./DamageComboBar.module.css";
function filterKeyToString(key: ExcludedDamageKey): string {
return `${key.weaponId}-${key.weaponType}-${key.damageType}`;
}
function weaponTypeFromSegment(
segment: DamageSegment,
): "main" | "sub" | "special" {
if (segment.isSubWeapon) return "sub";
if (segment.isSpecialWeapon) return "special";
return "main";
}
const SLOT_COLORS = ["yellow", "pink", "green", "blue"] as const;
interface DamageComboBarProps {
combo: DamageCombo;
inkTimeFrames: number | null;
onToggleFilter: (key: ExcludedDamageKey) => void;
}
function DamageComboBar({
combo,
inkTimeFrames,
onToggleFilter,
}: DamageComboBarProps) {
const { t } = useTranslation(["analyzer", "weapons"]);
const thresholdPosition = (LETHAL_DAMAGE / combo.totalDamage) * 100;
const inkDamage = inkTimeFrames ? LETHAL_DAMAGE - combo.totalDamage : 0;
const totalWithInk = inkTimeFrames
? LETHAL_DAMAGE
: Math.max(combo.totalDamage, LETHAL_DAMAGE);
return (
<div className={styles.comboRow}>
<div className={styles.barSection}>
{inkTimeFrames ? (
<InkTimeSegment
inkDamage={inkDamage}
totalDamage={totalWithInk}
inkTimeFrames={inkTimeFrames}
/>
) : null}
{combo.segments.map((segment, index) => (
<SegmentBar
key={index}
segment={segment}
totalDamage={totalWithInk}
damageTypeLabel={t(`analyzer:damage.${segment.damageType}` as any)}
onToggleFilter={onToggleFilter}
/>
))}
{thresholdPosition < 100 && !inkTimeFrames ? (
<div
className={styles.thresholdLine}
style={{ left: `${thresholdPosition}%` }}
/>
) : null}
</div>
<div className={styles.totalSection}>
<span className={styles.totalDamage}>
{combo.totalDamage.toFixed(1)}
</span>
<span className={styles.hitCount}>
{t("analyzer:comp.hits", { count: combo.hitCount })}
</span>
</div>
</div>
);
}
interface SegmentBarProps {
segment: DamageSegment;
totalDamage: number;
damageTypeLabel: string;
onToggleFilter: (key: ExcludedDamageKey) => void;
}
function SegmentBar({
segment,
totalDamage,
damageTypeLabel,
onToggleFilter,
}: SegmentBarProps) {
const segmentDamage = segment.damageValue * segment.count;
const widthPercent = (segmentDamage / totalDamage) * 100;
const slotColor = SLOT_COLORS[segment.weaponSlot] ?? "yellow";
const params = mainWeaponParams(segment.weaponId);
const handleFilterClick = () => {
onToggleFilter({
weaponId: segment.weaponId,
weaponType: weaponTypeFromSegment(segment),
damageType: segment.damageType,
});
};
return (
<div
className={styles.segmentWrapper}
style={{ width: `${widthPercent}%` }}
>
<div className={styles.segment} data-slot-color={slotColor}>
<WeaponIcon
weaponId={segment.weaponId}
isSubWeapon={segment.isSubWeapon}
isSpecialWeapon={segment.isSpecialWeapon}
subWeaponId={params.subWeaponId}
specialWeaponId={params.specialWeaponId}
/>
<span className={styles.damageValue}>
{segment.damageValue}
{segment.count > 1 ? (
<span className={styles.hitMultiplier}>×{segment.count}</span>
) : null}
</span>
</div>
<button
type="button"
className={styles.damageTypeLabel}
onClick={handleFilterClick}
>
{damageTypeLabel}
</button>
</div>
);
}
interface InkTimeSegmentProps {
inkDamage: number;
totalDamage: number;
inkTimeFrames: number;
}
function InkTimeSegment({
inkDamage,
totalDamage,
inkTimeFrames,
}: InkTimeSegmentProps) {
const widthPercent = (inkDamage / totalDamage) * 100;
return (
<div
className={styles.segmentWrapper}
style={{ width: `${widthPercent}%` }}
>
<div className={styles.inkTimeSegment}>
<Image path={abilityImageUrl("RES")} alt="" size={18} />
<span className={styles.inkTimeDamage}>{inkDamage.toFixed(1)}</span>
</div>
<div className={styles.inkTimeLabel}>{inkTimeFrames}f</div>
</div>
);
}
interface WeaponIconProps {
weaponId: MainWeaponId;
isSubWeapon: boolean;
isSpecialWeapon: boolean;
subWeaponId: SubWeaponId;
specialWeaponId: SpecialWeaponId;
}
function WeaponIcon({
weaponId,
isSubWeapon,
isSpecialWeapon,
subWeaponId,
specialWeaponId,
}: WeaponIconProps) {
if (isSubWeapon) {
return (
<Image
path={subWeaponImageUrl(subWeaponId)}
alt=""
size={18}
className={styles.subSpecialWeaponIcon}
/>
);
}
if (isSpecialWeapon) {
return (
<Image
path={specialWeaponImageUrl(specialWeaponId)}
alt=""
size={18}
className={styles.subSpecialWeaponIcon}
/>
);
}
return (
<WeaponImage
weaponSplId={weaponId}
variant="build"
size={24}
className={styles.weaponIcon}
/>
);
}
interface FilteredItemProps {
filterKey: ExcludedDamageKey;
onRestore: (key: ExcludedDamageKey) => void;
}
function FilteredItem({ filterKey, onRestore }: FilteredItemProps) {
const { t } = useTranslation(["analyzer", "weapons"]);
const params = mainWeaponParams(filterKey.weaponId);
return (
<button
type="button"
className={styles.filteredItem}
onClick={() => onRestore(filterKey)}
>
<WeaponIcon
weaponId={filterKey.weaponId}
isSubWeapon={filterKey.weaponType === "sub"}
isSpecialWeapon={filterKey.weaponType === "special"}
subWeaponId={params.subWeaponId}
specialWeaponId={params.specialWeaponId}
/>
<span>{t(`analyzer:damage.${filterKey.damageType}` as any)}</span>
</button>
);
}
interface DamageComboListProps {
weaponIds: MainWeaponId[];
}
export function DamageComboList({ weaponIds }: DamageComboListProps) {
const { t } = useTranslation(["analyzer"]);
const [excludedKeys, setExcludedKeys] = useState<ExcludedDamageKey[]>([]);
const [initialTargetResAp, commitTargetResAp] = useTargetResAp();
const [initialTargetSubDefenseAp, commitTargetSubDefenseAp] =
useTargetSubDefenseAp();
const [targetResAp, setTargetResAp] = useState(initialTargetResAp);
const [targetSubDefenseAp, setTargetSubDefenseAp] = useState(
initialTargetSubDefenseAp,
);
const [isCollapsed, setIsCollapsed] = useState(false);
const [singleWeaponCombos, setSingleWeaponCombos] = useSingleWeaponCombos();
const singleWeaponOnly = weaponIds.length === 1;
const includeSingleWeaponCombos = singleWeaponOnly || singleWeaponCombos;
const allDamageKeys = getAllDamageKeys(weaponIds, targetSubDefenseAp);
const allDamageKeyStrings = new Set(allDamageKeys.map(filterKeyToString));
const validExcludedKeys = excludedKeys.filter((key) =>
allDamageKeyStrings.has(filterKeyToString(key)),
);
const combos = calculateDamageCombos(
weaponIds,
validExcludedKeys,
targetSubDefenseAp,
undefined,
includeSingleWeaponCombos,
);
if (weaponIds.length < 1) {
return null;
}
const handleToggleFilter = (key: ExcludedDamageKey) => {
const keyString = filterKeyToString(key);
const exists = excludedKeys.some((k) => filterKeyToString(k) === keyString);
if (exists) {
setExcludedKeys(
excludedKeys.filter((k) => filterKeyToString(k) !== keyString),
);
} else {
setExcludedKeys([...excludedKeys, key]);
}
};
const handleRemoveAll = () => {
setExcludedKeys(allDamageKeys);
};
const handleClearAll = () => {
setExcludedKeys([]);
};
return (
<div className={styles.container} data-testid="damage-combo-list">
<button
type="button"
className={styles.header}
onClick={() => setIsCollapsed(!isCollapsed)}
data-testid="damage-combo-toggle"
>
<span className={styles.headerTitle}>
{t("analyzer:comp.damageCombos")}
</span>
<span className={styles.collapseIcon}>{isCollapsed ? "+" : "-"}</span>
</button>
{isCollapsed ? null : (
<div className={styles.content}>
<div className={styles.slidersContainer}>
<Image path={abilityImageUrl("SRU")} alt="" size={24} />
<label className={styles.resSliderLabel}>
{t("analyzer:comp.enemySubDef")}
</label>
<input
type="range"
min={0}
max={MAX_AP}
value={targetSubDefenseAp}
onChange={(e) => setTargetSubDefenseAp(Number(e.target.value))}
onPointerUp={() => commitTargetSubDefenseAp(targetSubDefenseAp)}
onKeyUp={() => commitTargetSubDefenseAp(targetSubDefenseAp)}
onBlur={() => commitTargetSubDefenseAp(targetSubDefenseAp)}
className={styles.resSlider}
/>
<span className={styles.resSliderValue}>
{targetSubDefenseAp} AP
</span>
<Image path={abilityImageUrl("RES")} alt="" size={24} />
<label className={styles.resSliderLabel}>
{t("analyzer:comp.enemyRes")}
</label>
<input
type="range"
min={0}
max={MAX_AP}
value={targetResAp}
onChange={(e) => setTargetResAp(Number(e.target.value))}
onPointerUp={() => commitTargetResAp(targetResAp)}
onKeyUp={() => commitTargetResAp(targetResAp)}
onBlur={() => commitTargetResAp(targetResAp)}
className={styles.resSlider}
/>
<span className={styles.resSliderValue}>{targetResAp} AP</span>
</div>
<div className={styles.singleWeaponToggleRow}>
<SendouSwitch
isSelected={includeSingleWeaponCombos}
onChange={setSingleWeaponCombos}
isDisabled={singleWeaponOnly}
>
{t("analyzer:comp.singleWeaponCombos")}
</SendouSwitch>
</div>
<div className={styles.filterControlsRow}>
<button
type="button"
className={styles.filterControlButton}
onClick={handleRemoveAll}
disabled={validExcludedKeys.length === allDamageKeys.length}
>
{t("analyzer:comp.removeAll")}
</button>
<button
type="button"
className={styles.filterControlButton}
onClick={handleClearAll}
disabled={validExcludedKeys.length === 0}
>
{t("analyzer:comp.addAll")}
</button>
</div>
{validExcludedKeys.length > 0 ? (
<div className={styles.filteredItemsRow}>
{validExcludedKeys.map((key) => (
<FilteredItem
key={filterKeyToString(key)}
filterKey={key}
onRestore={handleToggleFilter}
/>
))}
</div>
) : null}
{combos.map((combo, index) => {
const inkTimeFrames = calculateInkTimeToKill(
combo.totalDamage,
targetResAp,
);
if (combo.totalDamage < 100 && inkTimeFrames === null) {
return null;
}
return (
<DamageComboBar
key={index}
combo={combo}
inkTimeFrames={inkTimeFrames}
onToggleFilter={handleToggleFilter}
/>
);
})}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,112 @@
.container {
display: flex;
flex-direction: column;
border: 1px solid var(--color-border);
border-radius: var(--radius-field);
background: var(--color-bg);
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
padding: var(--s-2) var(--s-3);
background: var(--color-bg-higher);
border: none;
border-radius: var(--radius-field);
cursor: pointer;
font-size: var(--font-sm);
font-weight: var(--weight-semi);
color: var(--color-text);
width: 100%;
text-align: left;
&:hover {
background: var(--color-bg-high);
}
}
.headerTitle {
flex: 1;
}
.collapseIcon {
font-size: var(--font-lg);
font-weight: var(--weight-bold);
color: var(--color-text-high);
width: 20px;
text-align: center;
}
.content {
padding: var(--s-3);
}
.benchmarkLegend {
display: flex;
gap: var(--s-4);
margin-bottom: var(--s-3);
padding-bottom: var(--s-2);
border-bottom: 1px solid var(--color-border);
}
.legendItem {
display: flex;
align-items: center;
gap: var(--s-1);
font-size: var(--font-xs);
color: var(--color-text-high);
}
.legendLine {
width: 16px;
height: 2px;
background-image: repeating-linear-gradient(
to right,
rgb(100 100 120) 0,
rgb(100 100 120) 4px,
transparent 4px,
transparent 8px
);
}
.legendLabel {
white-space: nowrap;
}
.chartContainer {
display: flex;
flex-direction: column;
gap: var(--s-2);
}
.weaponLegend {
display: flex;
flex-wrap: wrap;
gap: var(--s-3);
}
.weaponLegendItem {
display: flex;
align-items: center;
gap: var(--s-1);
}
.weaponLegendColor {
width: 12px;
height: 3px;
border-radius: 2px;
}
.weaponLegendRange {
font-size: var(--font-xs);
color: var(--color-text-high);
font-weight: var(--weight-semi);
}
.chart {
width: 100%;
max-width: 100%;
height: auto;
min-height: 150px;
}

View File

@@ -0,0 +1,355 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { WeaponImage } from "~/components/Image";
import type { MainWeaponId } from "~/modules/in-game-lists/types";
import {
BENCHMARK_WEAPON_IDS,
getBenchmarkTrajectories,
getWeaponsWithRange,
type TrajectoryPoint,
type WeaponWithRange,
} from "../core/weapon-range";
import styles from "./RangeVisualization.module.css";
const SLOT_COLORS = ["#f5d742", "#f5b8d0", "#90e8a8", "#8cd4f5"] as const;
const BENCHMARK_COLORS = [
"rgba(100, 100, 120, 0.5)",
"rgba(100, 100, 120, 0.5)",
] as const;
interface RangeVisualizationProps {
weaponIds: MainWeaponId[];
}
export function RangeVisualization({ weaponIds }: RangeVisualizationProps) {
const { t } = useTranslation(["analyzer", "weapons"]);
const [isCollapsed, setIsCollapsed] = useState(false);
const weaponsWithRange = getWeaponsWithRange(weaponIds);
const benchmarkTrajectories = getBenchmarkTrajectories();
if (weaponsWithRange.length === 0) {
return null;
}
const maxRange = 32;
const allYValues: number[] = [];
for (const weapon of weaponsWithRange) {
if (weapon.trajectory) {
for (const point of weapon.trajectory) {
if (point.y >= 0) {
allYValues.push(point.y);
}
}
}
}
const minY = 0;
const maxY = Math.max(...allYValues, 2);
return (
<div className={styles.container} data-testid="range-visualization">
<button
type="button"
className={styles.header}
onClick={() => setIsCollapsed(!isCollapsed)}
data-testid="range-toggle"
>
<span className={styles.headerTitle}>
{t("analyzer:comp.weaponRanges")}
</span>
<span className={styles.collapseIcon}>{isCollapsed ? "+" : "-"}</span>
</button>
{!isCollapsed ? (
<div className={styles.content}>
<div className={styles.benchmarkLegend}>
{BENCHMARK_WEAPON_IDS.map((weaponId) => (
<div key={weaponId} className={styles.legendItem}>
<span className={styles.legendLine} />
<span className={styles.legendLabel}>
{t(`weapons:MAIN_${weaponId}`)}
</span>
</div>
))}
</div>
<TrajectoryChart
weapons={weaponsWithRange}
benchmarkTrajectories={benchmarkTrajectories}
maxRange={maxRange}
minY={minY}
maxY={maxY}
weaponIds={weaponIds}
/>
</div>
) : null}
</div>
);
}
interface TrajectoryChartProps {
weapons: WeaponWithRange[];
benchmarkTrajectories: Array<{
id: MainWeaponId;
range: number;
trajectory?: TrajectoryPoint[];
}>;
maxRange: number;
minY: number;
maxY: number;
weaponIds: MainWeaponId[];
}
function TrajectoryChart({
weapons,
benchmarkTrajectories,
maxRange,
minY,
maxY,
weaponIds,
}: TrajectoryChartProps) {
const chartWidth = 600;
const chartHeight = 200;
const padding = { top: 20, right: 60, bottom: 30, left: 50 };
const innerWidth = chartWidth - padding.left - padding.right;
const innerHeight = chartHeight - padding.top - padding.bottom;
const xScale = (z: number) => (z / maxRange) * innerWidth;
const yScale = (y: number) =>
innerHeight - ((y - minY) / (maxY - minY)) * innerHeight;
// Returns the point where trajectory hits y=0 (ground level).
// This differs from lastPoint which may be below ground or mid-air.
// Used for blast radius positioning since explosions happen at ground impact.
const getGroundIntersection = (
trajectory: TrajectoryPoint[],
): TrajectoryPoint | null => {
for (let i = 0; i < trajectory.length; i++) {
const point = trajectory[i];
if (point.y < 0) {
const prevPoint = trajectory[i - 1];
if (prevPoint && prevPoint.y >= 0) {
const t = prevPoint.y / (prevPoint.y - point.y);
const groundZ = prevPoint.z + t * (point.z - prevPoint.z);
return { z: groundZ, y: 0 };
}
break;
}
}
const lastPoint = trajectory[trajectory.length - 1];
return lastPoint && lastPoint.y >= 0 ? lastPoint : null;
};
const trajectoryToPath = (trajectory: TrajectoryPoint[]): string => {
if (trajectory.length === 0) return "";
const clampedPoints: TrajectoryPoint[] = [];
for (const point of trajectory) {
if (point.y >= 0) {
clampedPoints.push(point);
} else {
const prevPoint = clampedPoints[clampedPoints.length - 1];
if (prevPoint && prevPoint.y > 0) {
const t = prevPoint.y / (prevPoint.y - point.y);
const groundZ = prevPoint.z + t * (point.z - prevPoint.z);
clampedPoints.push({ z: groundZ, y: 0 });
}
break;
}
}
if (clampedPoints.length === 0) return "";
const points = clampedPoints.map((p) => `${xScale(p.z)},${yScale(p.y)}`);
return `M ${points.join(" L ")}`;
};
const groundY = yScale(0);
const xTicks = [];
const xStep = Math.ceil(maxRange / 5);
for (let x = 0; x <= maxRange; x += xStep) {
xTicks.push(x);
}
const yTicks = [];
const yStep = Math.ceil((maxY - minY) / 4);
for (let y = Math.ceil(minY); y <= maxY; y += yStep) {
yTicks.push(y);
}
return (
<div className={styles.chartContainer}>
<div className={styles.weaponLegend}>
{weapons.map((weapon, index) => {
const slotIndex = weaponIds.indexOf(weapon.weaponId);
const color = SLOT_COLORS[slotIndex % SLOT_COLORS.length];
return (
<div
key={`${weapon.weaponId}-${index}`}
className={styles.weaponLegendItem}
>
<WeaponImage
weaponSplId={weapon.weaponId}
variant="build"
size={24}
/>
<span
className={styles.weaponLegendColor}
style={{ backgroundColor: color }}
/>
<span className={styles.weaponLegendRange}>
{weapon.range.toFixed(1)}
</span>
</div>
);
})}
</div>
<svg
viewBox={`0 0 ${chartWidth} ${chartHeight}`}
className={styles.chart}
preserveAspectRatio="xMidYMid meet"
>
<g transform={`translate(${padding.left}, ${padding.top})`}>
{/* Grid lines */}
{xTicks.map((tick) => (
<line
key={`x-grid-${tick}`}
x1={xScale(tick)}
y1={0}
x2={xScale(tick)}
y2={innerHeight}
stroke="var(--color-border)"
strokeWidth={0.5}
/>
))}
{yTicks.map((tick) => (
<line
key={`y-grid-${tick}`}
x1={0}
y1={yScale(tick)}
x2={innerWidth}
y2={yScale(tick)}
stroke="var(--color-border)"
strokeWidth={0.5}
/>
))}
{/* Ground line (y=0) */}
<line
x1={0}
y1={groundY}
x2={innerWidth}
y2={groundY}
stroke="var(--color-text-high)"
strokeWidth={1}
/>
{/* Benchmark vertical lines */}
{benchmarkTrajectories.map((benchmark, index) => {
const x = xScale(benchmark.range);
return (
<line
key={benchmark.id}
x1={x}
y1={0}
x2={x}
y2={innerHeight}
stroke={BENCHMARK_COLORS[index % BENCHMARK_COLORS.length]}
strokeWidth={2}
strokeDasharray="4,4"
/>
);
})}
{/* Weapon trajectories */}
{weapons.map((weapon, index) => {
if (!weapon.trajectory) return null;
const slotIndex = weaponIds.indexOf(weapon.weaponId);
const color = SLOT_COLORS[slotIndex % SLOT_COLORS.length];
return (
<path
key={`${weapon.weaponId}-${index}`}
d={trajectoryToPath(weapon.trajectory)}
fill="none"
stroke={color}
strokeWidth={2.5}
/>
);
})}
{/* Blast radius circles */}
{weapons.map((weapon, index) => {
if (!weapon.blastRadius || !weapon.trajectory) return null;
const groundPoint = getGroundIntersection(weapon.trajectory);
if (!groundPoint) return null;
const slotIndex = weaponIds.indexOf(weapon.weaponId);
const color = SLOT_COLORS[slotIndex % SLOT_COLORS.length];
const radiusPixels = xScale(weapon.blastRadius);
return (
<circle
key={`blast-${weapon.weaponId}-${index}`}
cx={xScale(groundPoint.z)}
cy={yScale(0)}
r={radiusPixels}
fill={`${color}33`}
stroke={color}
strokeWidth={1}
/>
);
})}
{/* X axis labels */}
{xTicks.map((tick) => (
<text
key={`x-label-${tick}`}
x={xScale(tick)}
y={innerHeight + 15}
textAnchor="middle"
fontSize={10}
fill="var(--color-text-high)"
>
{tick}
</text>
))}
{/* Y axis labels */}
{yTicks.map((tick) => (
<text
key={`y-label-${tick}`}
x={-8}
y={yScale(tick) + 3}
textAnchor="end"
fontSize={10}
fill="var(--color-text-high)"
>
{tick}
</text>
))}
{/* Axis labels */}
<text
x={innerWidth / 2}
y={innerHeight + 25}
textAnchor="middle"
fontSize={11}
fill="var(--color-text-high)"
>
z
</text>
<text
x={-25}
y={innerHeight / 2}
textAnchor="middle"
fontSize={11}
fill="var(--color-text-high)"
transform={`rotate(-90, -25, ${innerHeight / 2})`}
>
y
</text>
</g>
</svg>
</div>
);
}

View File

@@ -0,0 +1,149 @@
import type { ComponentProps } from "react";
import { createMemoryRouter, RouterProvider } from "react-router";
import { describe, expect, test, vi } from "vitest";
import { render } from "vitest-browser-react";
import { MAX_WEAPONS } from "../comp-analyzer-constants";
import { SelectedWeapons } from "./SelectedWeapons";
const defaultProps: ComponentProps<typeof SelectedWeapons> = {
selectedWeaponIds: [],
onRemove: vi.fn(),
onReorder: vi.fn(),
};
function renderSelectedWeapons(
props: Partial<ComponentProps<typeof SelectedWeapons>> = {},
) {
const router = createMemoryRouter(
[
{
path: "/",
element: <SelectedWeapons {...defaultProps} {...props} />,
},
],
{ initialEntries: ["/"] },
);
return render(<RouterProvider router={router} />);
}
describe("SelectedWeapons", () => {
describe("empty state", () => {
test("renders empty slots when no weapons selected", async () => {
const screen = await renderSelectedWeapons({ selectedWeaponIds: [] });
const emptySlots = screen.container.querySelectorAll(
'[class*="weaponNameEmpty"]',
);
expect(emptySlots.length).toBe(MAX_WEAPONS);
});
test("renders correct number of slots", async () => {
const screen = await renderSelectedWeapons();
const rows = screen.container.querySelectorAll(
'[class*="selectedWeaponRow"]',
);
expect(rows.length).toBe(MAX_WEAPONS);
});
});
describe("selected weapons", () => {
test("renders selected weapon with name", async () => {
const screen = await renderSelectedWeapons({
selectedWeaponIds: [0],
});
await expect.element(screen.getByText("Sploosh-o-matic")).toBeVisible();
});
test("renders multiple selected weapons", async () => {
const screen = await renderSelectedWeapons({
selectedWeaponIds: [0, 10],
});
await expect.element(screen.getByText("Sploosh-o-matic")).toBeVisible();
await expect.element(screen.getByText("Splattershot Jr.")).toBeVisible();
});
test("renders sub and special icons for selected weapon", async () => {
const screen = await renderSelectedWeapons({
selectedWeaponIds: [0],
});
const subSpecialContainers = screen.container.querySelectorAll(
'[class*="subSpecialContainer"]',
);
const filledContainers = Array.from(subSpecialContainers).filter(
(container) => !container.className.includes("Spacer"),
);
expect(filledContainers.length).toBeGreaterThan(0);
const kitIcons = screen.container.querySelectorAll('[class*="kitIcon"]');
expect(kitIcons.length).toBeGreaterThan(0);
});
test("shows empty slots for remaining positions", async () => {
const screen = await renderSelectedWeapons({
selectedWeaponIds: [0],
});
const emptySlots = screen.container.querySelectorAll(
'[class*="weaponNameEmpty"]',
);
expect(emptySlots.length).toBe(MAX_WEAPONS - 1);
});
});
describe("remove functionality", () => {
test("renders remove button for selected weapons", async () => {
const screen = await renderSelectedWeapons({
selectedWeaponIds: [0],
});
const removeButton = screen.getByTestId("remove-weapon-0");
await expect.element(removeButton).toBeVisible();
});
test("calls onRemove with correct index when remove button clicked", async () => {
const onRemove = vi.fn();
const screen = await renderSelectedWeapons({
selectedWeaponIds: [0, 10],
onRemove,
});
const removeButtons = screen.container.querySelectorAll(
'[class*="removeButton"]',
);
(removeButtons[0] as HTMLElement).click();
expect(onRemove).toHaveBeenCalledWith(0);
});
test("calls onRemove with second index when second remove button clicked", async () => {
const onRemove = vi.fn();
const screen = await renderSelectedWeapons({
selectedWeaponIds: [0, 10],
onRemove,
});
const removeButtons = screen.container.querySelectorAll(
'[class*="removeButton"]',
);
(removeButtons[1] as HTMLElement).click();
expect(onRemove).toHaveBeenCalledWith(1);
});
test("does not render remove button for empty slots", async () => {
const screen = await renderSelectedWeapons({
selectedWeaponIds: [],
});
const removeButtons = screen.container.querySelectorAll(
'[class*="removeButton"]',
);
expect(removeButtons.length).toBe(0);
});
});
});

View File

@@ -0,0 +1,149 @@
.selectedWeapons {
display: flex;
flex-direction: column;
gap: var(--s-3);
}
.selectedWeaponRow {
display: flex;
align-items: center;
gap: var(--s-2);
transition: opacity 0.2s;
&.isDragging {
opacity: 0.5;
}
}
.weaponImageContainer {
position: relative;
z-index: 1;
display: flex;
align-items: center;
justify-content: center;
width: 56px;
height: 56px;
background-color: var(--color-bg-high);
border: 2px solid var(--color-border);
border-radius: 50%;
flex-shrink: 0;
}
.weaponImageContainerEmpty {
position: relative;
z-index: 1;
display: flex;
align-items: center;
justify-content: center;
width: 56px;
height: 56px;
background-color: var(--color-bg-higher);
border: 2px dashed var(--color-border);
border-radius: 50%;
flex-shrink: 0;
opacity: 0.6;
}
.weaponNamePill {
display: flex;
align-items: center;
gap: var(--s-2);
padding: var(--s-2) var(--s-3);
padding-left: var(--s-5);
background-color: var(--color-bg-high);
border: 2px solid var(--color-border);
border-radius: var(--radius-full);
flex: 1;
min-width: 0;
}
.weaponName {
flex: 1;
font-weight: var(--weight-semi);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.weaponNamePillEmpty {
display: flex;
align-items: center;
padding: var(--s-2) var(--s-3);
padding-left: var(--s-5);
background-color: var(--color-bg-higher);
border: 2px dashed var(--color-border);
border-radius: var(--radius-full);
flex: 1;
min-width: 0;
opacity: 0.6;
}
.weaponNameEmpty {
flex: 1;
font-weight: var(--weight-semi);
font-style: italic;
color: var(--color-text-high);
}
.removeButton {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
background: none;
border: none;
cursor: pointer;
font-size: 18px;
font-weight: bold;
line-height: 1;
color: var(--color-text-high);
flex-shrink: 0;
&:hover {
color: var(--color-error);
}
}
.dragHandle {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
padding: 0;
background: none;
border: none;
font-size: var(--font-md);
line-height: 1;
color: var(--color-text-high);
cursor: grab;
user-select: none;
touch-action: none;
flex-shrink: 0;
&:active {
cursor: grabbing;
}
}
.subSpecialContainer {
display: flex;
gap: var(--s-2);
flex-shrink: 0;
}
.subSpecialContainerSpacer {
width: 89px;
}
.kitIcon {
display: flex;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
background-color: var(--color-bg-high);
border: 2px solid var(--color-border);
border-radius: 50%;
}

View File

@@ -0,0 +1,192 @@
import type { DragEndEvent } from "@dnd-kit/core";
import {
closestCenter,
DndContext,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
} from "@dnd-kit/core";
import {
SortableContext,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import clsx from "clsx";
import { useTranslation } from "react-i18next";
import { Image, WeaponImage } from "~/components/Image";
import { mainWeaponParams } from "~/features/build-analyzer/core/utils";
import type { MainWeaponId } from "~/modules/in-game-lists/types";
import {
abilityImageUrl,
specialWeaponImageUrl,
subWeaponImageUrl,
} from "~/utils/urls";
import { MAX_WEAPONS } from "../comp-analyzer-constants";
import styles from "./SelectedWeapons.module.css";
interface SelectedWeaponsProps {
selectedWeaponIds: MainWeaponId[];
onRemove: (index: number) => void;
onReorder: (newIds: MainWeaponId[]) => void;
}
export function SelectedWeapons({
selectedWeaponIds,
onRemove,
onReorder,
}: SelectedWeaponsProps) {
const { t } = useTranslation(["weapons", "analyzer"]);
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
}),
);
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (over && active.id !== over.id) {
const oldIndex = selectedWeaponIds.indexOf(active.id as MainWeaponId);
const newIndex = selectedWeaponIds.indexOf(over.id as MainWeaponId);
const newIds = [...selectedWeaponIds];
const [removed] = newIds.splice(oldIndex, 1);
newIds.splice(newIndex, 0, removed);
onReorder(newIds);
}
};
const emptySlotCount = MAX_WEAPONS - selectedWeaponIds.length;
const showDragHandle = selectedWeaponIds.length > 1;
return (
<div className={styles.selectedWeapons} data-testid="selected-weapons">
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={selectedWeaponIds}
strategy={verticalListSortingStrategy}
>
{selectedWeaponIds.map((weaponId, index) => (
<SortableWeaponRow
key={weaponId}
weaponId={weaponId}
index={index}
onRemove={onRemove}
showDragHandle={showDragHandle}
/>
))}
</SortableContext>
</DndContext>
{Array.from({ length: emptySlotCount }, (_, i) => (
<div key={`empty-${i}`} className={styles.selectedWeaponRow}>
<div className={styles.weaponImageContainerEmpty}>
<Image path={abilityImageUrl("UNKNOWN")} alt="" size={48} />
</div>
<div className={styles.weaponNamePillEmpty}>
<span className={styles.weaponNameEmpty}>
{t("analyzer:comp.pickWeapon")}
</span>
</div>
<div className={styles.subSpecialContainerSpacer} />
</div>
))}
</div>
);
}
interface SortableWeaponRowProps {
weaponId: MainWeaponId;
index: number;
onRemove: (index: number) => void;
showDragHandle: boolean;
}
function SortableWeaponRow({
weaponId,
index,
onRemove,
showDragHandle,
}: SortableWeaponRowProps) {
const { t } = useTranslation(["weapons", "analyzer"]);
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: weaponId });
const style = {
transform: CSS.Transform.toString(transform),
transition,
};
const params = mainWeaponParams(weaponId);
return (
<div
ref={setNodeRef}
style={style}
className={clsx(styles.selectedWeaponRow, {
[styles.isDragging]: isDragging,
})}
data-testid={`selected-weapon-${index}`}
{...attributes}
>
<div className={styles.weaponImageContainer}>
<WeaponImage weaponSplId={weaponId} variant="build" size={48} />
</div>
<div className={styles.weaponNamePill}>
<span className={styles.weaponName}>
{t(`weapons:MAIN_${weaponId}`)}
</span>
{showDragHandle ? (
<button
type="button"
className={styles.dragHandle}
aria-label={t("analyzer:comp.reorderWeapon")}
{...listeners}
>
☰
</button>
) : null}
<button
type="button"
className={styles.removeButton}
onClick={() => onRemove(index)}
aria-label={t("analyzer:comp.removeWeapon")}
data-testid={`remove-weapon-${index}`}
>
&times;
</button>
</div>
<div className={styles.subSpecialContainer}>
<div className={styles.kitIcon}>
<Image
path={subWeaponImageUrl(params.subWeaponId)}
alt={t(`weapons:SUB_${params.subWeaponId}`)}
size={24}
/>
</div>
<div className={styles.kitIcon}>
<Image
path={specialWeaponImageUrl(params.specialWeaponId)}
alt={t(`weapons:SPECIAL_${params.specialWeaponId}`)}
size={24}
/>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,60 @@
.container {
display: flex;
flex-direction: column;
gap: var(--s-2);
}
.legend {
display: flex;
gap: var(--s-4);
font-size: var(--font-xs);
color: var(--color-text-high);
}
.legendItem {
display: flex;
align-items: center;
gap: var(--s-1-5);
}
.legendSwatch {
width: 12px;
height: 12px;
border-radius: 2px;
}
.row {
display: grid;
grid-template-columns: 32px 1fr 3rem;
align-items: center;
gap: var(--s-2);
}
.track {
position: relative;
height: 14px;
border-radius: var(--radius-field);
background: var(--color-bg-high);
overflow: hidden;
}
.bar {
position: absolute;
inset-block: 0;
inset-inline-start: 0;
border-radius: var(--radius-field);
}
.blast {
position: absolute;
inset-block: 0;
opacity: 0.4;
}
.range {
font-size: var(--font-xs);
font-weight: var(--weight-semi);
color: var(--color-text-high);
text-align: end;
font-variant-numeric: tabular-nums;
}

View File

@@ -0,0 +1,85 @@
// note: dev only component, not used in production code
import { useTranslation } from "react-i18next";
import { Image } from "~/components/Image";
import { specialWeaponImageUrl } from "~/utils/urls";
import {
getSpecialsWithRange,
type SpecialWeaponWithRange,
} from "../core/special-weapon-range";
import styles from "./SpecialRangeVisualization.module.css";
const RANGE_TYPE_COLOR: Record<SpecialWeaponWithRange["rangeType"], string> = {
projectile: "#8cd4f5",
radius: "#f5b8d0",
};
export function SpecialRangeVisualization() {
const { t } = useTranslation(["weapons"]);
const specials = getSpecialsWithRange();
if (specials.length === 0) {
return null;
}
const maxRange = Math.max(
...specials.map((special) => special.range + (special.blastRadius ?? 0)),
);
return (
<div className={styles.container} data-testid="special-range-visualization">
<div className={styles.legend}>
<div className={styles.legendItem}>
<span
className={styles.legendSwatch}
style={{ backgroundColor: RANGE_TYPE_COLOR.projectile }}
/>
projectile
</div>
<div className={styles.legendItem}>
<span
className={styles.legendSwatch}
style={{ backgroundColor: RANGE_TYPE_COLOR.radius }}
/>
radius
</div>
</div>
{specials.map((special) => {
const color = RANGE_TYPE_COLOR[special.rangeType];
const rangeWidth = (special.range / maxRange) * 100;
const blastWidth = special.blastRadius
? (special.blastRadius / maxRange) * 100
: 0;
return (
<div key={special.specialWeaponId} className={styles.row}>
<Image
path={specialWeaponImageUrl(special.specialWeaponId)}
width={28}
height={28}
alt={t(`weapons:SPECIAL_${special.specialWeaponId}`)}
title={t(`weapons:SPECIAL_${special.specialWeaponId}`)}
/>
<div className={styles.track}>
{blastWidth > 0 ? (
<span
className={styles.blast}
style={{
insetInlineStart: `${rangeWidth}%`,
width: `${blastWidth}%`,
backgroundColor: color,
}}
/>
) : null}
<span
className={styles.bar}
style={{ width: `${rangeWidth}%`, backgroundColor: color }}
/>
</div>
<span className={styles.range}>{special.range.toFixed(1)}</span>
</div>
);
})}
</div>
);
}

View File

@@ -0,0 +1,52 @@
.container {
display: flex;
flex-wrap: wrap;
gap: var(--s-4);
max-width: 100%;
}
.categorySection {
display: flex;
flex-direction: column;
gap: var(--s-1);
margin: 0 auto;
max-width: 100%;
}
.categoryLabel {
font-size: var(--font-sm);
font-weight: var(--weight-semi);
color: var(--color-text-high);
}
.categoryPill {
display: flex;
align-items: center;
background-color: var(--color-bg-high);
border: 2px solid var(--color-border);
border-radius: var(--radius-full);
overflow-x: auto;
overflow-y: hidden;
max-width: 100%;
width: fit-content;
}
.categoryItem {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--s-1);
padding: var(--s-1) var(--s-4);
border-left: 1.5px solid var(--color-border);
flex-shrink: 0;
&[data-first="true"] {
border-left: none;
}
}
.categoryName {
font-size: var(--font-2xs);
font-weight: var(--weight-semi);
white-space: nowrap;
}

View File

@@ -0,0 +1,126 @@
import { useTranslation } from "react-i18next";
import { Image } from "~/components/Image";
import { mainWeaponParams } from "~/features/build-analyzer/core/utils";
import type {
MainWeaponId,
SpecialWeaponId,
SubWeaponId,
} from "~/modules/in-game-lists/types";
import { specialWeaponImageUrl, subWeaponImageUrl } from "~/utils/urls";
import {
SPECIAL_CATEGORY_ORDER,
SPECIAL_WEAPON_CATEGORIES,
type SpecialWeaponCategory,
SUB_CATEGORY_ORDER,
SUB_WEAPON_CATEGORIES,
type SubWeaponCategory,
} from "../comp-analyzer-constants";
import styles from "./WeaponCategories.module.css";
interface WeaponCategoriesProps {
selectedWeaponIds: MainWeaponId[];
}
interface SubWeaponItem {
subId: SubWeaponId;
category: SubWeaponCategory;
weaponIndex: number;
}
interface SpecialWeaponItem {
specialId: SpecialWeaponId;
category: SpecialWeaponCategory;
weaponIndex: number;
}
export function WeaponCategories({ selectedWeaponIds }: WeaponCategoriesProps) {
const { t } = useTranslation(["weapons", "analyzer"]);
if (selectedWeaponIds.length === 0) {
return null;
}
const subItems: SubWeaponItem[] = [];
const specialItems: SpecialWeaponItem[] = [];
for (const [index, weaponId] of selectedWeaponIds.entries()) {
const params = mainWeaponParams(weaponId);
subItems.push({
subId: params.subWeaponId,
category: SUB_WEAPON_CATEGORIES[params.subWeaponId],
weaponIndex: index,
});
specialItems.push({
specialId: params.specialWeaponId,
category: SPECIAL_WEAPON_CATEGORIES[params.specialWeaponId],
weaponIndex: index,
});
}
const sortedSubItems = [...subItems].sort((a, b) => {
const aIndex = SUB_CATEGORY_ORDER.indexOf(a.category);
const bIndex = SUB_CATEGORY_ORDER.indexOf(b.category);
if (aIndex !== bIndex) return aIndex - bIndex;
return a.weaponIndex - b.weaponIndex;
});
const sortedSpecialItems = [...specialItems].sort((a, b) => {
const aIndex = SPECIAL_CATEGORY_ORDER.indexOf(a.category);
const bIndex = SPECIAL_CATEGORY_ORDER.indexOf(b.category);
if (aIndex !== bIndex) return aIndex - bIndex;
return a.weaponIndex - b.weaponIndex;
});
return (
<div className={styles.container}>
<div className={styles.categorySection}>
<div className={styles.categoryLabel}>
{t("analyzer:comp.subRoles")}
</div>
<div className={styles.categoryPill}>
{sortedSubItems.map((item, index) => (
<div
key={`${item.weaponIndex}-${item.subId}`}
className={styles.categoryItem}
data-first={index === 0}
>
<Image
path={subWeaponImageUrl(item.subId)}
alt={t(`weapons:SUB_${item.subId}`)}
size={20}
/>
<span className={styles.categoryName}>
{t(`analyzer:comp.subCategory.${item.category}`)}
</span>
</div>
))}
</div>
</div>
<div className={styles.categorySection}>
<div className={styles.categoryLabel}>
{t("analyzer:comp.specialRoles")}
</div>
<div className={styles.categoryPill}>
{sortedSpecialItems.map((item, index) => (
<div
key={`${item.weaponIndex}-${item.specialId}`}
className={styles.categoryItem}
data-first={index === 0}
>
<Image
path={specialWeaponImageUrl(item.specialId)}
alt={t(`weapons:SPECIAL_${item.specialId}`)}
size={20}
/>
<span className={styles.categoryName}>
{t(`analyzer:comp.specialCategory.${item.category}`)}
</span>
</div>
))}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,135 @@
import type { ComponentProps } from "react";
import { createMemoryRouter, RouterProvider } from "react-router";
import { describe, expect, test, vi } from "vitest";
import { render } from "vitest-browser-react";
import { WeaponGrid } from "./WeaponGrid";
const defaultProps: ComponentProps<typeof WeaponGrid> = {
selectedWeaponIds: [],
onWeaponClick: vi.fn(),
categorization: "category",
onCategorizationChange: vi.fn(),
isCollapsed: false,
onToggleCollapse: vi.fn(),
};
function renderWeaponGrid(
props: Partial<ComponentProps<typeof WeaponGrid>> = {},
) {
const router = createMemoryRouter(
[
{
path: "/",
element: <WeaponGrid {...defaultProps} {...props} />,
},
],
{ initialEntries: ["/"] },
);
return render(<RouterProvider router={router} />);
}
describe("WeaponGrid", () => {
describe("collapse toggle", () => {
test("renders with collapse toggle visible", async () => {
const screen = await renderWeaponGrid();
await expect
.element(screen.getByText("Hide weapon selector"))
.toBeVisible();
});
test("shows 'Show weapon selector' when collapsed", async () => {
const screen = await renderWeaponGrid({ isCollapsed: true });
await expect
.element(screen.getByText("Show weapon selector"))
.toBeVisible();
});
test("calls onToggleCollapse when toggle button clicked", async () => {
const onToggleCollapse = vi.fn();
const screen = await renderWeaponGrid({ onToggleCollapse });
await screen.getByText("Hide weapon selector").click();
expect(onToggleCollapse).toHaveBeenCalledTimes(1);
});
test("hides weapon grid content when collapsed", async () => {
const screen = await renderWeaponGrid({ isCollapsed: true });
await expect
.element(screen.getByText("Show weapon selector"))
.toBeVisible();
const groupByLabel = screen.container.querySelector(
'[class*="categorizationToggle"]',
);
expect(groupByLabel).toBeNull();
});
});
describe("categorization", () => {
test("shows categorization radio buttons when expanded", async () => {
const screen = await renderWeaponGrid();
await expect.element(screen.getByText("Weapon type")).toBeVisible();
await expect.element(screen.getByText("Sub weapon")).toBeVisible();
await expect.element(screen.getByText("Special weapon")).toBeVisible();
});
test("calls onCategorizationChange when radio button clicked", async () => {
const onCategorizationChange = vi.fn();
const screen = await renderWeaponGrid({ onCategorizationChange });
await screen.getByText("Sub weapon").click();
expect(onCategorizationChange).toHaveBeenCalledWith("sub");
});
test("shows correct radio button as checked", async () => {
const screen = await renderWeaponGrid({ categorization: "special" });
const specialRadio = screen.getByRole("radio", {
name: "Special weapon",
});
await expect.element(specialRadio).toBeChecked();
});
});
describe("weapon selection", () => {
test("calls onWeaponClick when weapon button clicked", async () => {
const onWeaponClick = vi.fn();
const screen = await renderWeaponGrid({ onWeaponClick });
const weaponButtons = screen.container.querySelectorAll("button[title]");
const firstWeaponButton = weaponButtons[1] as HTMLElement | undefined;
if (firstWeaponButton) {
firstWeaponButton.click();
expect(onWeaponClick).toHaveBeenCalledTimes(1);
}
});
test("disables unselected weapons when max is reached", async () => {
const screen = await renderWeaponGrid({
selectedWeaponIds: [0, 10, 20, 30],
});
const disabledButtons = screen.container.querySelectorAll(
"button[title][disabled]",
);
expect(disabledButtons.length).toBeGreaterThan(0);
});
test("shows selected weapons with selected style", async () => {
const screen = await renderWeaponGrid({
selectedWeaponIds: [0],
});
const selectedButtons = screen.container.querySelectorAll(
'[class*="weaponButtonSelected"]',
);
expect(selectedButtons.length).toBeGreaterThan(0);
});
});
});

View File

@@ -0,0 +1,104 @@
.container {
display: flex;
flex-direction: column;
gap: var(--s-4);
}
.collapseToggle {
display: flex;
align-items: center;
gap: var(--s-2);
background-color: transparent;
border: none;
cursor: pointer;
font-weight: var(--weight-semi);
color: var(--color-text);
}
.collapseArrow {
transition: transform 0.2s;
}
.collapseArrowCollapsed {
transform: rotate(-90deg);
}
.categorizationToggle {
display: flex;
gap: var(--s-2);
flex-wrap: wrap;
}
.weaponGrid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: var(--s-4);
}
@container (width < 640px) {
.weaponGrid {
grid-template-columns: repeat(2, 1fr);
}
}
@container (width < 560px) {
.weaponGrid {
grid-template-columns: 1fr;
}
}
.categorySection {
display: flex;
flex-direction: column;
gap: var(--s-2);
}
.categoryHeader {
display: flex;
align-items: center;
gap: var(--s-2);
padding-bottom: var(--s-1);
border-bottom: 3px solid var(--color-border);
}
.categoryName {
font-weight: var(--weight-semi);
font-size: var(--font-sm);
text-transform: capitalize;
}
.categoryWeapons {
display: flex;
flex-wrap: wrap;
gap: var(--s-1);
}
.weaponButton {
display: flex;
align-items: center;
justify-content: center;
padding: var(--s-1);
background-color: var(--color-bg-higher);
border: 2px solid transparent;
border-radius: var(--radius-box);
cursor: pointer;
transition: border-color 0.1s;
&:hover {
border-color: var(--color-text-accent);
}
&:disabled {
opacity: 0.6;
cursor: not-allowed;
&:hover {
border-color: transparent;
}
}
}
.weaponButtonSelected {
background-color: var(--color-bg-high);
border: 2px solid var(--color-border);
}

View File

@@ -0,0 +1,208 @@
import { useTranslation } from "react-i18next";
import { Image, WeaponImage } from "~/components/Image";
import { Label } from "~/components/Label";
import { mainWeaponParams } from "~/features/build-analyzer/core/utils";
import type {
MainWeaponId,
SpecialWeaponId,
SubWeaponId,
} from "~/modules/in-game-lists/types";
import {
mainWeaponIds,
specialWeaponIds,
subWeaponIds,
weaponCategories,
} from "~/modules/in-game-lists/weapon-ids";
import {
specialWeaponImageUrl,
subWeaponImageUrl,
weaponCategoryUrl,
} from "~/utils/urls";
import { MAX_WEAPONS } from "../comp-analyzer-constants";
import type { CategorizationType } from "../comp-analyzer-types";
import styles from "./WeaponGrid.module.css";
interface WeaponGridProps {
selectedWeaponIds: MainWeaponId[];
onWeaponClick: (weaponId: MainWeaponId) => void;
categorization: CategorizationType;
onCategorizationChange: (categorization: CategorizationType) => void;
isCollapsed: boolean;
onToggleCollapse: () => void;
}
export function WeaponGrid({
selectedWeaponIds,
onWeaponClick,
categorization,
onCategorizationChange,
isCollapsed,
onToggleCollapse,
}: WeaponGridProps) {
const { t } = useTranslation(["weapons", "analyzer"]);
const isMaxSelected = selectedWeaponIds.length >= MAX_WEAPONS;
const groupedWeapons = groupWeaponsByType(categorization);
return (
<div className={styles.container} data-testid="weapon-grid">
<button
type="button"
className={styles.collapseToggle}
onClick={onToggleCollapse}
data-testid="weapon-grid-toggle"
>
<span
className={`${styles.collapseArrow} ${isCollapsed ? styles.collapseArrowCollapsed : ""}`}
>
▼
</span>
<span>
{isCollapsed
? t("analyzer:comp.showWeaponGrid")
: t("analyzer:comp.hideWeaponGrid")}
</span>
</button>
{!isCollapsed ? (
<>
<div>
<Label>{t("analyzer:comp.groupBy")}</Label>
<div
className={styles.categorizationToggle}
data-testid="categorization-toggle"
>
<label className="stack horizontal sm items-center">
<input
type="radio"
name="categorization"
value="category"
checked={categorization === "category"}
onChange={() => onCategorizationChange("category")}
data-testid="categorization-category"
/>
<span>{t("analyzer:comp.groupBy.category")}</span>
</label>
<label className="stack horizontal sm items-center">
<input
type="radio"
name="categorization"
value="sub"
checked={categorization === "sub"}
onChange={() => onCategorizationChange("sub")}
data-testid="categorization-sub"
/>
<span>{t("analyzer:comp.groupBy.sub")}</span>
</label>
<label className="stack horizontal sm items-center">
<input
type="radio"
name="categorization"
value="special"
checked={categorization === "special"}
onChange={() => onCategorizationChange("special")}
data-testid="categorization-special"
/>
<span>{t("analyzer:comp.groupBy.special")}</span>
</label>
</div>
</div>
<div className={styles.weaponGrid}>
{groupedWeapons.map((group) => (
<div key={group.key} className={styles.categorySection}>
<div className={styles.categoryHeader}>
{group.iconPath ? (
<Image path={group.iconPath} alt="" size={24} />
) : null}
<span className={styles.categoryName}>
{group.name.startsWith("SUB_") ||
group.name.startsWith("SPECIAL_")
? t(`weapons:${group.name}` as "SUB_0")
: group.name}
</span>
</div>
<div className={styles.categoryWeapons}>
{group.weaponIds.map((weaponId) => {
const isSelected = selectedWeaponIds.includes(weaponId);
const isDisabled = !isSelected && isMaxSelected;
return (
<button
key={weaponId}
type="button"
className={`${styles.weaponButton} ${isSelected ? styles.weaponButtonSelected : ""}`}
onClick={() => onWeaponClick(weaponId)}
disabled={isDisabled}
title={t(`weapons:MAIN_${weaponId}`)}
data-testid={`weapon-button-${weaponId}`}
>
<WeaponImage
weaponSplId={weaponId}
variant="build"
size={32}
/>
</button>
);
})}
</div>
</div>
))}
</div>
</>
) : null}
</div>
);
}
interface WeaponGroup {
key: string;
name: string;
iconPath: string | null;
weaponIds: MainWeaponId[];
}
function groupWeaponsByType(categorization: CategorizationType): WeaponGroup[] {
if (categorization === "category") {
return weaponCategories.map((category) => ({
key: category.name,
name: category.name.toLowerCase(),
iconPath: weaponCategoryUrl(category.name),
weaponIds: [...category.weaponIds] as MainWeaponId[],
}));
}
if (categorization === "sub") {
return subWeaponIds
.map((subId) => {
const weaponsWithSub = mainWeaponIds.filter((weaponId) => {
const params = mainWeaponParams(weaponId);
return params.subWeaponId === subId;
});
return {
key: `sub-${subId}`,
name: `SUB_${subId}`,
iconPath: subWeaponImageUrl(subId as SubWeaponId),
weaponIds: weaponsWithSub,
};
})
.filter((group) => group.weaponIds.length > 0);
}
return specialWeaponIds
.map((specialId) => {
const weaponsWithSpecial = mainWeaponIds.filter((weaponId) => {
const params = mainWeaponParams(weaponId);
return params.specialWeaponId === specialId;
});
return {
key: `special-${specialId}`,
name: `SPECIAL_${specialId}`,
iconPath: specialWeaponImageUrl(specialId as SpecialWeaponId),
weaponIds: weaponsWithSpecial,
};
})
.filter((group) => group.weaponIds.length > 0);
}

View File

@@ -0,0 +1,497 @@
import { describe, expect, test } from "vitest";
import {
COMBO_DAMAGE_THRESHOLD,
MAX_COMBOS_DISPLAYED,
MAX_DAMAGE_TYPES_PER_COMBO,
MAX_REPEATS_PER_DAMAGE_TYPE,
} from "../comp-analyzer-constants";
import {
calculateDamageCombos,
calculateInkTimeToKill,
extractDamageSources,
} from "./damage-combinations";
const SPLATTERSHOT_ID = 40;
const SPLAT_ROLLER_ID = 1010;
const SPLAT_CHARGER_ID = 2010;
const AEROSPRAY_MG_ID = 30;
const SPLATTERSHOT_JR_ID = 10;
const EXPLOSHER_ID = 3040;
describe("extractDamageSources", () => {
test("extracts main weapon damages", () => {
const sources = extractDamageSources([SPLATTERSHOT_ID]);
expect(sources.length).toBe(1);
expect(sources[0].weaponId).toBe(SPLATTERSHOT_ID);
expect(sources[0].weaponSlot).toBe(0);
const mainDamages = sources[0].damages.filter(
(d) => d.weaponType === "MAIN",
);
expect(mainDamages.length).toBeGreaterThan(0);
});
test("extracts sub weapon damages", () => {
const sources = extractDamageSources([SPLATTERSHOT_ID]);
const subDamages = sources[0].damages.filter((d) => d.weaponType === "SUB");
expect(subDamages.length).toBeGreaterThan(0);
});
test("extracts special weapon damages when applicable", () => {
const sources = extractDamageSources([SPLATTERSHOT_ID]);
const specialDamages = sources[0].damages.filter(
(d) => d.weaponType === "SPECIAL",
);
expect(specialDamages.length).toBeGreaterThan(0);
});
test("assigns correct weapon slots for multiple weapons", () => {
const sources = extractDamageSources([
SPLATTERSHOT_ID,
SPLAT_ROLLER_ID,
SPLAT_CHARGER_ID,
]);
expect(sources.length).toBe(3);
expect(sources[0].weaponSlot).toBe(0);
expect(sources[1].weaponSlot).toBe(1);
expect(sources[2].weaponSlot).toBe(2);
});
});
describe("calculateDamageCombos - basic combination generation", () => {
test("generates combos involving 2+ weapons", () => {
const combos = calculateDamageCombos([SPLATTERSHOT_ID, SPLAT_ROLLER_ID]);
expect(combos.length).toBeGreaterThan(0);
for (const combo of combos) {
const uniqueSlots = new Set(combo.segments.map((s) => s.weaponSlot));
expect(uniqueSlots.size).toBeGreaterThanOrEqual(2);
}
});
test("calculates correct total damage", () => {
const combos = calculateDamageCombos([SPLATTERSHOT_ID, SPLAT_ROLLER_ID]);
for (const combo of combos) {
const calculatedTotal = combo.segments.reduce(
(sum, segment) => sum + segment.damageValue * segment.count,
0,
);
expect(combo.totalDamage).toBeCloseTo(calculatedTotal, 1);
}
});
test("calculates correct hit count", () => {
const combos = calculateDamageCombos([SPLATTERSHOT_ID, SPLAT_ROLLER_ID]);
for (const combo of combos) {
const calculatedHitCount = combo.segments.reduce(
(sum, segment) => sum + segment.count,
0,
);
expect(combo.hitCount).toBe(calculatedHitCount);
}
});
});
describe("calculateDamageCombos - constraint enforcement", () => {
test("respects max damage types per combo constraint", () => {
const combos = calculateDamageCombos([
SPLATTERSHOT_ID,
SPLAT_ROLLER_ID,
SPLAT_CHARGER_ID,
AEROSPRAY_MG_ID,
]);
for (const combo of combos) {
const uniqueTypes = new Set(combo.segments.map((s) => s.damageType));
expect(uniqueTypes.size).toBeLessThanOrEqual(MAX_DAMAGE_TYPES_PER_COMBO);
}
});
test("respects max repeats per damage type constraint", () => {
const combos = calculateDamageCombos([
SPLATTERSHOT_ID,
SPLAT_ROLLER_ID,
SPLAT_CHARGER_ID,
AEROSPRAY_MG_ID,
]);
for (const combo of combos) {
const typeToCount = new Map<string, number>();
for (const segment of combo.segments) {
const current = typeToCount.get(segment.damageType) ?? 0;
typeToCount.set(segment.damageType, current + segment.count);
}
for (const [type, count] of typeToCount) {
expect(
count,
`Type ${type} has ${count} uses, max is ${MAX_REPEATS_PER_DAMAGE_TYPE}`,
).toBeLessThanOrEqual(MAX_REPEATS_PER_DAMAGE_TYPE);
}
}
});
test("requires 2+ weapon slots in each combo", () => {
const combos = calculateDamageCombos([
SPLATTERSHOT_ID,
SPLAT_ROLLER_ID,
SPLAT_CHARGER_ID,
]);
for (const combo of combos) {
const uniqueSlots = new Set(combo.segments.map((s) => s.weaponSlot));
expect(uniqueSlots.size).toBeGreaterThanOrEqual(2);
}
});
});
describe("calculateDamageCombos - threshold filtering", () => {
test("excludes combos below damage threshold", () => {
const combos = calculateDamageCombos([SPLATTERSHOT_ID, SPLAT_ROLLER_ID]);
for (const combo of combos) {
expect(combo.totalDamage).toBeGreaterThanOrEqual(COMBO_DAMAGE_THRESHOLD);
}
});
test("includes combos at or above damage threshold", () => {
const combos = calculateDamageCombos([SPLATTERSHOT_ID, SPLAT_ROLLER_ID]);
const hasValidCombos = combos.some(
(c) => c.totalDamage >= COMBO_DAMAGE_THRESHOLD,
);
expect(hasValidCombos).toBe(true);
});
});
describe("calculateDamageCombos - one-shot exclusion", () => {
test("excludes all combos containing a 100+ damage hit", () => {
const combos = calculateDamageCombos([SPLAT_CHARGER_ID, SPLATTERSHOT_ID]);
for (const combo of combos) {
const hasOneShot = combo.segments.some((s) => s.damageValue >= 100);
expect(hasOneShot).toBe(false);
}
});
});
describe("calculateDamageCombos - sorting", () => {
test("sorts results by totalDamage closest to 100 (lethal threshold)", () => {
const combos = calculateDamageCombos([
SPLATTERSHOT_ID,
SPLAT_ROLLER_ID,
SPLAT_CHARGER_ID,
]);
if (combos.length < 2) {
return;
}
for (let i = 0; i < combos.length - 1; i++) {
const currentDistTo100 = Math.abs(combos[i].totalDamage - 100);
const nextDistTo100 = Math.abs(combos[i + 1].totalDamage - 100);
expect(currentDistTo100).toBeLessThanOrEqual(nextDistTo100);
}
});
});
describe("calculateDamageCombos - result cap", () => {
test("returns at most MAX_COMBOS_DISPLAYED results", () => {
const combos = calculateDamageCombos([
SPLATTERSHOT_ID,
SPLAT_ROLLER_ID,
SPLAT_CHARGER_ID,
AEROSPRAY_MG_ID,
]);
expect(combos.length).toBeLessThanOrEqual(MAX_COMBOS_DISPLAYED);
});
});
describe("calculateDamageCombos - edge cases", () => {
test("returns empty array for empty weapon selection", () => {
const combos = calculateDamageCombos([]);
expect(combos).toEqual([]);
});
test("returns empty array for single weapon (cannot make cross-weapon combos)", () => {
const combos = calculateDamageCombos([SPLATTERSHOT_ID]);
expect(combos).toEqual([]);
});
test("same sub weapon on multiple weapons creates valid combos", () => {
const combos = calculateDamageCombos([SPLATTERSHOT_ID, SPLATTERSHOT_JR_ID]);
expect(combos.length).toBeGreaterThanOrEqual(0);
for (const combo of combos) {
const uniqueSlots = new Set(combo.segments.map((s) => s.weaponSlot));
expect(uniqueSlots.size).toBeGreaterThanOrEqual(2);
}
});
test("all segments have valid weapon slot assignments", () => {
const combos = calculateDamageCombos([SPLATTERSHOT_ID, SPLAT_ROLLER_ID]);
for (const combo of combos) {
for (const segment of combo.segments) {
expect(segment.weaponSlot).toBeGreaterThanOrEqual(0);
expect(segment.weaponSlot).toBeLessThan(4);
}
}
});
test("all segments have count of 1 or 2", () => {
const combos = calculateDamageCombos([
SPLATTERSHOT_ID,
SPLAT_ROLLER_ID,
SPLAT_CHARGER_ID,
]);
for (const combo of combos) {
for (const segment of combo.segments) {
expect(segment.count).toBeGreaterThanOrEqual(1);
expect(segment.count).toBeLessThanOrEqual(2);
}
}
});
});
describe("calculateInkTimeToKill", () => {
test("returns null for combos that are already lethal (>= 100 damage)", () => {
const result = calculateInkTimeToKill(100, 0);
expect(result).toBeNull();
});
test("returns null for combos above 100 damage", () => {
const result = calculateInkTimeToKill(150, 0);
expect(result).toBeNull();
});
test("calculates short ink time for 99 damage combo with 0 RES", () => {
const result = calculateInkTimeToKill(99, 0);
expect(result).not.toBeNull();
expect(result).toBeGreaterThan(0);
expect(result).toBeLessThan(30);
});
test("calculates longer ink time for 80 damage combo with 0 RES", () => {
const result = calculateInkTimeToKill(80, 0);
expect(result).not.toBeNull();
expect(result).toBeGreaterThan(60);
});
test("returns null when remaining damage exceeds ink damage limit with high RES", () => {
const result = calculateInkTimeToKill(60, 57);
expect(result).toBeNull();
});
test("higher RES increases ink time", () => {
const resultNoRes = calculateInkTimeToKill(90, 0);
const resultMaxRes = calculateInkTimeToKill(90, 57);
expect(resultNoRes).not.toBeNull();
expect(resultMaxRes).not.toBeNull();
expect(resultMaxRes!).toBeGreaterThan(resultNoRes!);
});
test("handles boundary case at 0 AP", () => {
const result = calculateInkTimeToKill(80, 0);
expect(result).not.toBeNull();
expect(result).toBeGreaterThan(0);
});
test("handles boundary case at 57 AP", () => {
const result = calculateInkTimeToKill(90, 57);
expect(result).not.toBeNull();
expect(result).toBeGreaterThan(0);
});
});
describe("calculateDamageCombos - excessive combo filtering", () => {
test("filters out excessive combos (200+ damage where removing any hit still kills)", () => {
const combos = calculateDamageCombos(
[SPLATTERSHOT_ID, SPLAT_ROLLER_ID, SPLAT_CHARGER_ID, AEROSPRAY_MG_ID],
[],
0,
1000,
);
const hasExcessiveCombo = combos.some((combo) => {
const flatDamages = combo.segments.flatMap((s) =>
Array(s.count).fill(s.damageValue),
);
for (const damage of flatDamages) {
const reducedDamage = combo.totalDamage - damage;
if (reducedDamage >= 100) {
return true;
}
}
return false;
});
expect(hasExcessiveCombo).toBe(false);
});
test("allows combos where removing any hit drops below lethal threshold", () => {
const combos = calculateDamageCombos(
[SPLATTERSHOT_ID, SPLAT_ROLLER_ID],
[],
0,
1000,
);
for (const combo of combos) {
const flatDamages = combo.segments.flatMap((s) =>
Array(s.count).fill(s.damageValue),
);
const allHitsNecessary = flatDamages.every(
(damage) => combo.totalDamage - damage < 100,
);
expect(allHitsNecessary).toBe(true);
}
});
});
const TRI_SLOSHER_ID = 3010;
const INKBRUSH_ID = 1100;
const GOLD_DYNAMO_ROLLER_ID = 1021;
const RAPID_BLASTER_PRO_WNT_R_ID = 252;
describe("calculateDamageCombos - deduplication", () => {
test("no duplicate combos with bug report weapons", () => {
const combos = calculateDamageCombos(
[
TRI_SLOSHER_ID,
INKBRUSH_ID,
GOLD_DYNAMO_ROLLER_ID,
RAPID_BLASTER_PRO_WNT_R_ID,
],
[],
0,
1000,
);
const canonicalKeys = combos.map((combo) => {
const grouped = new Map<string, number>();
for (const segment of combo.segments) {
const key = `${segment.damageType}:${segment.damageValue}`;
grouped.set(key, (grouped.get(key) ?? 0) + segment.count);
}
return [...grouped.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.map(([key, count]) => `${key}:${count}`)
.join("|");
});
const uniqueKeys = new Set(canonicalKeys);
expect(uniqueKeys.size).toBe(canonicalKeys.length);
});
});
describe("calculateDamageCombos - single weapon combos", () => {
test("returns no combos for a single weapon when disabled", () => {
const combos = calculateDamageCombos([SPLATTERSHOT_ID]);
expect(combos).toEqual([]);
});
test("generates combos from a single weapon when enabled", () => {
const combos = calculateDamageCombos(
[SPLATTERSHOT_ID],
[],
0,
undefined,
true,
);
expect(combos.length).toBeGreaterThan(0);
for (const combo of combos) {
const uniqueSlots = new Set(combo.segments.map((s) => s.weaponSlot));
expect(uniqueSlots.size).toBe(1);
expect(combo.totalDamage).toBeGreaterThanOrEqual(COMBO_DAMAGE_THRESHOLD);
}
});
test("lets a single weapon pair its main and sub damage when enabled", () => {
const combos = calculateDamageCombos(
[SPLATTERSHOT_ID],
[],
0,
undefined,
true,
);
const hasMainSubCombo = combos.some((combo) => {
const hasMain = combo.segments.some(
(s) => !s.isSubWeapon && !s.isSpecialWeapon,
);
const hasSub = combo.segments.some((s) => s.isSubWeapon);
return hasMain && hasSub;
});
expect(hasMainSubCombo).toBe(true);
});
test("keeps single-weapon combos alongside cross-weapon ones when enabled", () => {
const withoutSingle = calculateDamageCombos(
[SPLATTERSHOT_ID, SPLAT_ROLLER_ID],
[],
0,
1000,
);
const withSingle = calculateDamageCombos(
[SPLATTERSHOT_ID, SPLAT_ROLLER_ID],
[],
0,
1000,
true,
);
expect(withSingle.length).toBeGreaterThanOrEqual(withoutSingle.length);
});
});
describe("virtual damage combos", () => {
test("Explosher has COMBO damage type combining DIRECT and DISTANCE", () => {
const sources = extractDamageSources([EXPLOSHER_ID]);
const damages = sources[0].damages;
const comboDamage = damages.find((d) => d.type === "COMBO");
expect(comboDamage).toBeDefined();
expect(comboDamage?.weaponType).toBe("MAIN");
const directDamage = damages.find((d) => d.type === "DIRECT");
const distanceDamage = damages.find((d) => d.type === "DISTANCE");
expect(directDamage).toBeDefined();
expect(distanceDamage).toBeDefined();
const expectedComboValue =
(directDamage?.value ?? 0) + (distanceDamage?.value ?? 0);
expect(comboDamage?.value).toBeCloseTo(expectedComboValue, 1);
});
test("COMBO damage appears in damage combos", () => {
const combos = calculateDamageCombos([EXPLOSHER_ID, SPLATTERSHOT_ID]);
const comboWithComboType = combos.find((c) =>
c.segments.some((s) => s.damageType === "COMBO"),
);
expect(comboWithComboType).toBeDefined();
});
});

View File

@@ -0,0 +1,506 @@
import { damageTypeToWeaponType } from "~/features/build-analyzer/analyzer-constants";
import type {
AbilityPoints,
DamageType,
} from "~/features/build-analyzer/analyzer-types";
import {
buildStats,
subWeaponDamageValue,
} from "~/features/build-analyzer/core/stats";
import { weaponParams } from "~/features/build-analyzer/core/utils";
import type { MainWeaponId } from "~/modules/in-game-lists/types";
import {
COMBO_DAMAGE_THRESHOLD,
LETHAL_DAMAGE,
MAX_COMBOS_DISPLAYED,
MAX_DAMAGE_TYPES_PER_COMBO,
MAX_REPEATS_PER_DAMAGE_TYPE,
VIRTUAL_DAMAGE_COMBOS,
} from "../comp-analyzer-constants";
import type {
DamageCombo,
DamageSegment,
WeaponDamageSource,
} from "../comp-analyzer-types";
interface DamageOption {
weaponSlot: number;
weaponId: MainWeaponId;
damageType: DamageType;
damageValue: number;
weaponType: "MAIN" | "SUB" | "SPECIAL";
}
export function extractDamageSources(
weaponIds: MainWeaponId[],
targetSubDefenseAp = 0,
): WeaponDamageSource[] {
return weaponIds.map((weaponId, slot) => {
const stats = buildStats({ weaponSplId: weaponId, hasTacticooler: false });
const damages: WeaponDamageSource["damages"] = [];
for (const damage of stats.stats.damages) {
const weaponType = damageTypeToWeaponType[damage.type];
if (weaponType === "MAIN") {
damages.push({
type: damage.type,
value: damage.value,
weaponType: "MAIN",
});
}
}
for (const subDamage of stats.stats.subWeaponDefenseDamages) {
if (subDamage.subWeaponId === stats.weapon.subWeaponSplId) {
const params = weaponParams();
const reducedValue =
targetSubDefenseAp === 0
? subDamage.baseValue
: subWeaponDamageValue({
baseValue: subDamage.baseValue,
subWeaponId: subDamage.subWeaponId,
abilityPoints: targetSubDefenseAp,
params: params.subWeapons[subDamage.subWeaponId],
});
damages.push({
type: subDamage.type,
value: reducedValue,
weaponType: "SUB",
});
}
}
for (const specialDamage of stats.stats.specialWeaponDamages) {
damages.push({
type: specialDamage.type,
value: specialDamage.value,
weaponType: "SPECIAL",
});
}
const virtualCombos = VIRTUAL_DAMAGE_COMBOS[weaponId];
if (virtualCombos) {
for (const combo of virtualCombos) {
const combinedValue = combo.damageTypes.reduce((sum, type) => {
const damage = damages.find((d) => d.type === type);
return sum + (damage?.value ?? 0);
}, 0);
if (combinedValue > 0) {
damages.push({
type: combo.virtualType,
value: combinedValue,
weaponType: "MAIN",
});
}
}
}
return {
weaponSlot: slot,
weaponId,
damages,
};
});
}
export interface ExcludedDamageKey {
weaponId: MainWeaponId;
weaponType: "main" | "sub" | "special";
damageType: DamageType;
}
export function getAllDamageKeys(
weaponIds: MainWeaponId[],
targetSubDefenseAp = 0,
): ExcludedDamageKey[] {
const sources = extractDamageSources(weaponIds, targetSubDefenseAp);
const seen = new Set<string>();
const keys: ExcludedDamageKey[] = [];
for (const source of sources) {
for (const damage of source.damages) {
const weaponType = damage.weaponType.toLowerCase() as
| "main"
| "sub"
| "special";
const keyString = `${source.weaponId}-${weaponType}-${damage.type}`;
if (seen.has(keyString)) {
continue;
}
seen.add(keyString);
keys.push({
weaponId: source.weaponId,
weaponType,
damageType: damage.type,
});
}
}
return keys;
}
export function calculateDamageCombos(
weaponIds: MainWeaponId[],
excludedKeys: ExcludedDamageKey[] = [],
targetSubDefenseAp = 0,
maxCombosDisplayed = MAX_COMBOS_DISPLAYED,
includeSingleWeaponCombos = false,
): DamageCombo[] {
const minWeaponSlots = includeSingleWeaponCombos ? 1 : 2;
if (weaponIds.length < minWeaponSlots) {
return [];
}
const excludedSet = new Set(
excludedKeys.map((k) => `${k.weaponId}-${k.weaponType}-${k.damageType}`),
);
const sources = extractDamageSources(weaponIds, targetSubDefenseAp);
const damageOptions = flattenToOptions(sources, excludedSet);
const combos = generateCombinations(
damageOptions,
minWeaponSlots,
includeSingleWeaponCombos,
);
const filtered = filterAndSortCombos(combos, maxCombosDisplayed);
return filtered;
}
function flattenToOptions(
sources: WeaponDamageSource[],
excludedSet: Set<string>,
): DamageOption[] {
const options: DamageOption[] = [];
for (const source of sources) {
for (const damage of source.damages) {
const weaponType = damage.weaponType.toLowerCase() as
| "main"
| "sub"
| "special";
const key = `${source.weaponId}-${weaponType}-${damage.type}`;
if (excludedSet.has(key)) {
continue;
}
options.push({
weaponSlot: source.weaponSlot,
weaponId: source.weaponId,
damageType: damage.type,
damageValue: damage.value,
weaponType: damage.weaponType,
});
}
}
return options;
}
interface PartialCombo {
segments: DamageSegment[];
totalDamage: number;
hitCount: number;
usedSlots: Set<number>;
typeCountMap: Map<DamageType, number>;
slotDamageType: Map<string, DamageType>;
}
/**
* Groups a weapon slot's damage into a single "channel" that may only ever
* contribute one damage type per combo. In single-weapon mode each weapon type
* (main/sub/special) is its own channel so a single weapon can pair e.g. its
* main damage with its sub; otherwise a whole slot is one channel.
*/
function slotDamageChannel(
option: DamageOption,
includeSingleWeaponCombos: boolean,
): string {
return includeSingleWeaponCombos
? `${option.weaponSlot}-${option.weaponType}`
: String(option.weaponSlot);
}
function generateCombinations(
options: DamageOption[],
minWeaponSlots: number,
includeSingleWeaponCombos: boolean,
): DamageCombo[] {
const results: DamageCombo[] = [];
const initialState: PartialCombo = {
segments: [],
totalDamage: 0,
hitCount: 0,
usedSlots: new Set(),
typeCountMap: new Map(),
slotDamageType: new Map(),
};
backtrack(
options,
0,
initialState,
results,
minWeaponSlots,
includeSingleWeaponCombos,
);
return results;
}
function backtrack(
options: DamageOption[],
startIndex: number,
current: PartialCombo,
results: DamageCombo[],
minWeaponSlots: number,
includeSingleWeaponCombos: boolean,
): void {
if (
current.usedSlots.size >= minWeaponSlots &&
current.totalDamage >= COMBO_DAMAGE_THRESHOLD
) {
results.push({
segments: [...current.segments],
totalDamage: current.totalDamage,
hitCount: current.hitCount,
});
}
if (
current.typeCountMap.size >= MAX_DAMAGE_TYPES_PER_COMBO &&
current.totalDamage >= COMBO_DAMAGE_THRESHOLD
) {
return;
}
for (let i = startIndex; i < options.length; i++) {
const option = options[i];
const currentTypeCount = current.typeCountMap.get(option.damageType) ?? 0;
if (
current.typeCountMap.size >= MAX_DAMAGE_TYPES_PER_COMBO &&
!current.typeCountMap.has(option.damageType)
) {
continue;
}
if (currentTypeCount >= MAX_REPEATS_PER_DAMAGE_TYPE) {
continue;
}
const slotChannel = slotDamageChannel(option, includeSingleWeaponCombos);
const existingTypeForSlot = current.slotDamageType.get(slotChannel);
if (existingTypeForSlot && existingTypeForSlot !== option.damageType) {
continue;
}
for (
let count = 1;
count <= Math.min(2, MAX_REPEATS_PER_DAMAGE_TYPE - currentTypeCount);
count++
) {
const segment: DamageSegment = {
weaponSlot: option.weaponSlot,
weaponId: option.weaponId,
damageType: option.damageType,
damageValue: option.damageValue,
isSubWeapon: option.weaponType === "SUB",
isSpecialWeapon: option.weaponType === "SPECIAL",
count,
};
const newUsedSlots = new Set(current.usedSlots);
newUsedSlots.add(option.weaponSlot);
const newTypeCountMap = new Map(current.typeCountMap);
newTypeCountMap.set(option.damageType, currentTypeCount + count);
const newSlotDamageType = new Map(current.slotDamageType);
newSlotDamageType.set(slotChannel, option.damageType);
const newState: PartialCombo = {
segments: [...current.segments, segment],
totalDamage: current.totalDamage + option.damageValue * count,
hitCount: current.hitCount + count,
usedSlots: newUsedSlots,
typeCountMap: newTypeCountMap,
slotDamageType: newSlotDamageType,
};
backtrack(
options,
i + 1,
newState,
results,
minWeaponSlots,
includeSingleWeaponCombos,
);
}
}
}
function normalizeCombo(combo: DamageCombo): DamageCombo {
const grouped = new Map<
string,
{ segment: DamageSegment; totalCount: number }
>();
for (const segment of combo.segments) {
const key = `${segment.damageType}:${segment.damageValue}`;
const existing = grouped.get(key);
if (existing) {
existing.totalCount += segment.count;
} else {
grouped.set(key, { segment, totalCount: segment.count });
}
}
const segments: DamageSegment[] = [];
for (const { segment, totalCount } of grouped.values()) {
segments.push({ ...segment, count: totalCount });
}
segments.sort((a, b) => {
const typeCompare = a.damageType.localeCompare(b.damageType);
if (typeCompare !== 0) return typeCompare;
return a.damageValue - b.damageValue;
});
return {
segments,
totalDamage: combo.totalDamage,
hitCount: combo.hitCount,
};
}
function comboKey(normalized: DamageCombo): string {
return normalized.segments
.map((s) => `${s.damageType}:${s.damageValue}:${s.count}`)
.join("|");
}
function deduplicateCombos(combos: DamageCombo[]): DamageCombo[] {
const seen = new Map<string, DamageCombo>();
for (const combo of combos) {
const normalized = normalizeCombo(combo);
const key = comboKey(normalized);
const existing = seen.get(key);
if (!existing || combo.segments.length < existing.segments.length) {
seen.set(key, combo);
}
}
return [...seen.values()];
}
function filterAndSortCombos(
combos: DamageCombo[],
maxCombosDisplayed: number,
): DamageCombo[] {
const filtered = combos.filter((combo) => {
if (combo.totalDamage < COMBO_DAMAGE_THRESHOLD) {
return false;
}
if (hasOneShot(combo)) {
return false;
}
if (isExcessiveCombo(combo)) {
return false;
}
return true;
});
const deduplicated = deduplicateCombos(filtered);
deduplicated.sort((a, b) => {
const aDistTo100 = Math.abs(a.totalDamage - 100);
const bDistTo100 = Math.abs(b.totalDamage - 100);
if (aDistTo100 !== bDistTo100) {
return aDistTo100 - bDistTo100;
}
return a.hitCount - b.hitCount;
});
return deduplicated.slice(0, maxCombosDisplayed);
}
function hasOneShot(combo: DamageCombo): boolean {
return combo.segments.some((s) => s.damageValue >= LETHAL_DAMAGE);
}
function isExcessiveCombo(combo: DamageCombo): boolean {
const flatDamages = combo.segments.flatMap((s) =>
Array(s.count).fill(s.damageValue),
);
const totalDamage = combo.totalDamage;
for (let i = 0; i < flatDamages.length; i++) {
const damage = flatDamages[i];
const reducedDamage = totalDamage - damage;
if (reducedDamage >= LETHAL_DAMAGE) {
return true;
}
}
return false;
}
const SPLASH_O_MATIC_ID = 20;
/**
* Calculates the number of frames needed for enemy ink damage to finish off
* a target after dealing a certain amount of combo damage.
*
* @param comboDamage - The damage dealt by the combo
* @param targetResAp - The target's Ink Resistance Up ability points (0-57)
* @returns The number of frames needed, or null if the combo is already lethal
* or ink damage cannot finish the kill (remaining damage exceeds ink damage limit)
*/
export function calculateInkTimeToKill(
comboDamage: number,
targetResAp: number,
): number | null {
if (comboDamage >= 100) {
return null;
}
const remainingDamage = 100 - comboDamage;
const abilityPoints: AbilityPoints = new Map([["RES", targetResAp]]);
const stats = buildStats({
weaponSplId: SPLASH_O_MATIC_ID,
abilityPoints,
hasTacticooler: false,
});
const damagePerSecond = stats.stats.damageTakenInEnemyInkPerSecond.value;
const damageLimit = stats.stats.enemyInkDamageLimit.value;
const gracePeriodFrames =
stats.stats.framesBeforeTakingDamageInEnemyInk.value;
if (remainingDamage > damageLimit) {
return null;
}
const damageFrames = remainingDamage / (damagePerSecond / 60);
const totalFrames = gracePeriodFrames + damageFrames;
return Math.ceil(totalFrames);
}
// TBD: Advanced filtering options
// - Distance range filtering
// - Damage type include/exclude
// - Hit count constraints

View File

@@ -0,0 +1,57 @@
import { describe, expect, test } from "vitest";
import {
BIG_BUBBLER_ID,
BOOYAH_BOMB_ID,
CRAB_TANK_ID,
SPLATTERCOLOR_SCREEN_ID,
specialWeaponIds,
TRIZOOKA_ID,
WAVE_BREAKER_ID,
} from "~/modules/in-game-lists/weapon-ids";
import { getSpecialWeaponRange } from "./special-weapon-range";
describe("special weapon range", () => {
test("computes a projectile range for Trizooka", () => {
const result = getSpecialWeaponRange(TRIZOOKA_ID);
expect(result?.rangeType).toBe("projectile");
expect(result?.range).toBeGreaterThan(0);
});
test("Crab Tank reaches further than Trizooka", () => {
const crab = getSpecialWeaponRange(CRAB_TANK_ID);
const trizooka = getSpecialWeaponRange(TRIZOOKA_ID);
expect(crab!.range).toBeGreaterThan(trizooka!.range);
});
test("throws-and-bursts specials expose a throw range plus explosion blast", () => {
const booyah = getSpecialWeaponRange(BOOYAH_BOMB_ID);
expect(booyah?.rangeType).toBe("projectile");
expect(booyah?.range).toBeGreaterThan(0);
expect(booyah?.blastRadius).toBeGreaterThan(0);
});
test("returns the effect radius for area specials", () => {
const waveBreaker = getSpecialWeaponRange(WAVE_BREAKER_ID);
expect(waveBreaker?.rangeType).toBe("radius");
expect(waveBreaker?.range).toBeGreaterThan(0);
});
test("returns null for global / utility specials without a meaningful circle", () => {
expect(getSpecialWeaponRange(BIG_BUBBLER_ID)).toBeNull();
expect(getSpecialWeaponRange(SPLATTERCOLOR_SCREEN_ID)).toBeNull();
});
test("every special is either unsupported or has a positive finite range", () => {
for (const id of specialWeaponIds) {
const result = getSpecialWeaponRange(id);
if (result === null) continue;
expect(Number.isFinite(result.range)).toBe(true);
expect(result.range).toBeGreaterThan(0);
}
});
});

View File

@@ -0,0 +1,88 @@
import { specialWeaponParams } from "~/features/build-analyzer/core/utils";
import type { SpecialWeaponId } from "~/modules/in-game-lists/types";
import { specialWeaponIds } from "~/modules/in-game-lists/weapon-ids";
import {
calculateGroundRange,
simulateTrajectoryPoints,
type TrajectoryParams,
} from "./weapon-range";
const DEFAULT_BRAKE_AIR_RESIST = 0.36;
const DEFAULT_BRAKE_GRAVITY = 0.07;
const DEFAULT_BRAKE_TO_FREE_FRAME = 4;
const DEFAULT_FREE_GRAVITY = 0.016;
const DEFAULT_FREE_AIR_RESIST = 0;
export interface SpecialWeaponRangeResult {
/** Radius of the range circle, in game distance units. */
range: number;
/** Extra outer radius covered by the projectile's blast, in game distance units. */
blastRadius?: number;
rangeType: "projectile" | "radius";
}
/**
* Range circle definition for a special weapon, or `null` when the special has no meaningful
* range to draw. The underlying values come from `weapon-params.ts` (populated by
* `scripts/create-analyzer-json.ts`): projectile specials reuse the main weapon trajectory
* model, the rest carry a single effect radius.
*/
export function getSpecialWeaponRange(
specialWeaponId: SpecialWeaponId,
): SpecialWeaponRangeResult | null {
const params = specialWeaponParams(specialWeaponId);
if (params.Range_Radius !== undefined) {
return { range: params.Range_Radius, rangeType: "radius" };
}
if (params.Range_Distance !== undefined) {
return {
range: params.Range_Distance,
blastRadius: params.Range_BlastRadius,
rangeType: "projectile",
};
}
if (params.Range_SpawnSpeed === undefined) return null;
const trajectoryParams: TrajectoryParams = {
spawnSpeed: params.Range_SpawnSpeed,
goStraightStateEndMaxSpeed:
params.Range_GoStraightStateEndMaxSpeed ?? params.Range_SpawnSpeed,
goStraightToBrakeStateFrame: params.Range_GoStraightToBrakeStateFrame ?? 4,
freeGravity: params.Range_FreeGravity ?? DEFAULT_FREE_GRAVITY,
freeAirResist: params.Range_FreeAirResist ?? DEFAULT_FREE_AIR_RESIST,
brakeAirResist: params.Range_BrakeAirResist ?? DEFAULT_BRAKE_AIR_RESIST,
brakeGravity: params.Range_BrakeGravity ?? DEFAULT_BRAKE_GRAVITY,
brakeToFreeFrame:
params.Range_BrakeToFreeStateFrame ?? DEFAULT_BRAKE_TO_FREE_FRAME,
};
const range = calculateGroundRange(
simulateTrajectoryPoints(trajectoryParams),
);
return {
range,
blastRadius: params.Range_BlastRadius,
rangeType: "projectile",
};
}
export interface SpecialWeaponWithRange extends SpecialWeaponRangeResult {
specialWeaponId: SpecialWeaponId;
}
/**
* Every special weapon that has a range to draw, widest first. Specials without a meaningful
* range circle are omitted.
*/
export function getSpecialsWithRange(): SpecialWeaponWithRange[] {
return specialWeaponIds
.flatMap((specialWeaponId): SpecialWeaponWithRange[] => {
const result = getSpecialWeaponRange(specialWeaponId);
return result ? [{ specialWeaponId, ...result }] : [];
})
.sort((a, b) => b.range - a.range);
}

View File

@@ -0,0 +1,24 @@
import { describe, expect, test } from "vitest";
import type { MainWeaponId } from "~/modules/in-game-lists/types";
import { getWeaponsWithRange } from "./weapon-range";
// [longerRangeWeaponId, shorterRangeWeaponId]
const RANGE_COMPARISONS: [MainWeaponId, MainWeaponId][] = [
[220, 210], // Range Blaster > Blaster
[70, 40], // Splattershot Pro > Splattershot
[7010, 7030], // Tri-Stringer > Wellstring V
[2020, 7030], // Splatterscope > Wellstring V
[2070, 7010], // Snipewriter 5H > Tri-Stringer
];
describe("weapon range comparisons", () => {
test.each(RANGE_COMPARISONS)(
"weapon %i has more range than weapon %i",
(longerId, shorterId) => {
const [longer] = getWeaponsWithRange([longerId]);
const [shorter] = getWeaponsWithRange([shorterId]);
expect(longer.range).toBeGreaterThan(shorter.range);
},
);
});

View File

@@ -0,0 +1,257 @@
import { mainWeaponParams } from "~/features/build-analyzer/core/utils";
import type { MainWeaponId } from "~/modules/in-game-lists/types";
import { weaponCategories } from "~/modules/in-game-lists/weapon-ids";
export interface TrajectoryParams {
spawnSpeed: number;
goStraightStateEndMaxSpeed: number;
goStraightToBrakeStateFrame: number;
freeGravity: number;
freeAirResist: number;
brakeAirResist: number;
brakeGravity: number;
brakeToFreeFrame: number;
burstFrame?: number;
bounceAfterMaxSpeed?: number;
}
export interface TrajectoryPoint {
z: number;
y: number;
}
const DEFAULT_BRAKE_AIR_RESIST = 0.36;
const DEFAULT_BRAKE_GRAVITY = 0.07;
const DEFAULT_BRAKE_TO_FREE_FRAME = 4;
const DEFAULT_FREE_GRAVITY = 0.016;
const DEFAULT_FREE_AIR_RESIST = 0;
function getWeaponCategoryName(weaponId: MainWeaponId): string | undefined {
for (const category of weaponCategories) {
if (category.weaponIds.some((id) => id === weaponId)) {
return category.name;
}
}
return undefined;
}
const PLAYER_HEIGHT = 1.0;
export function calculateGroundRange(trajectory: TrajectoryPoint[]): number {
for (let i = 1; i < trajectory.length; i++) {
const point = trajectory[i];
const prevPoint = trajectory[i - 1];
if (point.y < 0 && prevPoint.y >= 0) {
const t = prevPoint.y / (prevPoint.y - point.y);
return prevPoint.z + t * (point.z - prevPoint.z);
}
}
const lastPoint = trajectory[trajectory.length - 1];
return lastPoint?.z ?? 0;
}
function calculateBouncingRange(trajectory: TrajectoryPoint[]): number {
const lastPoint = trajectory[trajectory.length - 1];
return lastPoint?.z ?? 0;
}
export function simulateTrajectoryPoints(
params: TrajectoryParams,
): TrajectoryPoint[] {
const {
spawnSpeed,
goStraightStateEndMaxSpeed,
goStraightToBrakeStateFrame,
freeGravity,
freeAirResist,
brakeAirResist,
brakeGravity,
brakeToFreeFrame,
burstFrame,
bounceAfterMaxSpeed,
} = params;
const isBouncing = bounceAfterMaxSpeed !== undefined;
const maxBounces =
isBouncing && burstFrame !== undefined ? burstFrame : undefined;
const maxFrames = isBouncing ? 300 : (burstFrame ?? 300);
const points: TrajectoryPoint[] = [];
let z = 0;
let y = PLAYER_HEIGHT;
let vz = spawnSpeed;
let vy = 0;
let frame = 0;
let bounceCount = 0;
points.push({ z, y });
while (frame < goStraightToBrakeStateFrame && frame < maxFrames) {
z += vz;
points.push({ z, y });
frame++;
}
vz = Math.min(vz, goStraightStateEndMaxSpeed);
for (let i = 0; i < brakeToFreeFrame && frame < maxFrames; i++) {
vz *= 1 - brakeAirResist;
vy = (1 - brakeAirResist) * vy - brakeGravity;
z += vz;
y += vy;
points.push({ z, y });
frame++;
if (y < 0) {
if (isBouncing) {
bounceCount++;
if (maxBounces !== undefined && bounceCount >= maxBounces) {
return points;
}
y = Math.abs(y);
vy = Math.abs(vy);
vz *= bounceAfterMaxSpeed;
} else {
return points;
}
}
}
while (frame < maxFrames) {
vz *= 1 - freeAirResist;
vy = (1 - freeAirResist) * vy - freeGravity;
z += vz;
y += vy;
if (y < 0) {
if (isBouncing) {
bounceCount++;
if (maxBounces !== undefined && bounceCount >= maxBounces) {
points.push({ z, y: 0 });
return points;
}
y = Math.abs(y);
vy = Math.abs(vy);
vz *= bounceAfterMaxSpeed;
} else {
points.push({ z, y });
return points;
}
}
points.push({ z, y });
frame++;
if (!isBouncing && y < 0) {
return points;
}
if (vz < 0.01) {
return points;
}
}
return points;
}
export interface WeaponRangeResult {
range: number;
blastRadius?: number;
rangeType: "calculated" | "direct" | "unsupported";
trajectory?: TrajectoryPoint[];
}
export function getWeaponRange(weaponId: MainWeaponId): WeaponRangeResult {
const category = getWeaponCategoryName(weaponId);
if (!category) {
return { range: 0, rangeType: "unsupported" };
}
const params = mainWeaponParams(weaponId);
if (category === "CHARGERS" && params.DistanceFullCharge !== undefined) {
const range = params.DistanceFullCharge;
return {
range,
rangeType: "direct",
trajectory: [
{ z: 0, y: PLAYER_HEIGHT },
{ z: range, y: PLAYER_HEIGHT },
],
};
}
if (params.Range_SpawnSpeed === undefined) {
return { range: 0, rangeType: "unsupported" };
}
const trajectoryParams: TrajectoryParams = {
spawnSpeed: params.Range_SpawnSpeed,
goStraightStateEndMaxSpeed:
params.Range_GoStraightStateEndMaxSpeed ?? params.Range_SpawnSpeed,
goStraightToBrakeStateFrame: params.Range_GoStraightToBrakeStateFrame ?? 4,
freeGravity: params.Range_FreeGravity ?? DEFAULT_FREE_GRAVITY,
freeAirResist: params.Range_FreeAirResist ?? DEFAULT_FREE_AIR_RESIST,
brakeAirResist: params.Range_BrakeAirResist ?? DEFAULT_BRAKE_AIR_RESIST,
brakeGravity: params.Range_BrakeGravity ?? DEFAULT_BRAKE_GRAVITY,
brakeToFreeFrame:
params.Range_BrakeToFreeStateFrame ?? DEFAULT_BRAKE_TO_FREE_FRAME,
burstFrame: params.Range_BurstFrame,
bounceAfterMaxSpeed: params.Range_BounceAfterMaxSpeed,
};
const trajectory = simulateTrajectoryPoints(trajectoryParams);
const range =
params.Range_BounceAfterMaxSpeed !== undefined
? calculateBouncingRange(trajectory)
: calculateGroundRange(trajectory);
return {
range,
blastRadius: params.BlastRadius,
rangeType: "calculated",
trajectory,
};
}
export interface WeaponWithRange {
weaponId: MainWeaponId;
range: number;
blastRadius?: number;
rangeType: "calculated" | "direct" | "unsupported";
trajectory?: TrajectoryPoint[];
}
export function getWeaponsWithRange(
weaponIds: MainWeaponId[],
): WeaponWithRange[] {
return weaponIds
.map((weaponId) => {
const result = getWeaponRange(weaponId);
return {
weaponId,
...result,
};
})
.filter((w) => w.rangeType !== "unsupported");
}
export const BENCHMARK_WEAPON_IDS = [40, 2070] satisfies MainWeaponId[];
export interface BenchmarkTrajectory {
id: MainWeaponId;
range: number;
trajectory?: TrajectoryPoint[];
}
export function getBenchmarkTrajectories(): BenchmarkTrajectory[] {
return BENCHMARK_WEAPON_IDS.map((weaponId) => {
const result = getWeaponRange(weaponId);
return {
id: weaponId,
range: result.range,
trajectory: result.trajectory,
};
}).filter((b) => b.trajectory !== undefined);
}

View File

@@ -0,0 +1,41 @@
import { Main } from "~/components/Main";
import type { MainWeaponId } from "~/modules/in-game-lists/types";
import {
weaponCategories,
weaponIdToType,
} from "~/modules/in-game-lists/weapon-ids";
import { RangeVisualization } from "../components/RangeVisualization";
import { SpecialRangeVisualization } from "../components/SpecialRangeVisualization";
export default function AllRangesPage() {
return (
<Main className="stack lg">
<h1>All Weapon Ranges (Dev)</h1>
{weaponCategories.map((category) => {
const baseWeaponIds: MainWeaponId[] = category.weaponIds.flatMap(
(id): MainWeaponId[] => {
const weaponId = id as MainWeaponId;
return weaponIdToType(weaponId) === "BASE" ? [weaponId] : [];
},
);
if (baseWeaponIds.length === 0) {
return null;
}
return (
<section key={category.name}>
<h2 style={{ textTransform: "capitalize" }}>
{category.name.toLowerCase()}
</h2>
<RangeVisualization weaponIds={baseWeaponIds} />
</section>
);
})}
<section>
<h2 style={{ textTransform: "capitalize" }}>specials</h2>
<SpecialRangeVisualization />
</section>
</Main>
);
}

View File

@@ -0,0 +1,96 @@
import { useState } from "react";
import type { MetaFunction, ShouldRevalidateFunction } from "react-router";
import { Main } from "~/components/Main";
import { Placeholder } from "~/components/Placeholder";
import { useHydrated } from "~/hooks/useHydrated";
import type { MainWeaponId } from "~/modules/in-game-lists/types";
import type { SendouRouteHandle } from "~/utils/remix.server";
import { COMP_ANALYZER_URL, navIconUrl } from "~/utils/urls";
import { metaTags } from "../../../utils/remix";
import { MAX_WEAPONS } from "../comp-analyzer-constants";
import { useCategorization, useSelectedWeapons } from "../comp-analyzer-hooks";
import { DamageComboList } from "../components/DamageComboBar";
import { RangeVisualization } from "../components/RangeVisualization";
import { SelectedWeapons } from "../components/SelectedWeapons";
import { WeaponCategories } from "../components/WeaponCategories";
import { WeaponGrid } from "../components/WeaponGrid";
export const meta: MetaFunction = (args) => {
return metaTags({
title: "Composition Analyzer",
ogTitle: "Splatoon 3 composition analyzer",
location: args.location,
description:
"Analyze team compositions and discover damage combo synergies between weapons in Splatoon 3.",
});
};
export const handle: SendouRouteHandle = {
i18n: ["weapons", "analyzer"],
breadcrumb: () => ({
imgPath: navIconUrl("comp-analyzer"),
href: COMP_ANALYZER_URL,
type: "IMAGE",
}),
};
export const shouldRevalidate: ShouldRevalidateFunction = () => false;
export default function CompAnalyzerShell() {
const isHydrated = useHydrated();
if (!isHydrated) {
return <Placeholder />;
}
return <CompAnalyzerPage />;
}
function CompAnalyzerPage() {
const [selectedWeaponIds, setSelectedWeaponIds] = useSelectedWeapons();
const [categorization, setCategorization] = useCategorization();
const [isGridCollapsed, setIsGridCollapsed] = useState(
selectedWeaponIds.length >= MAX_WEAPONS,
);
const handleWeaponClick = (weaponId: MainWeaponId) => {
if (selectedWeaponIds.length >= MAX_WEAPONS) {
return;
}
const newSelectedWeapons = [...selectedWeaponIds, weaponId];
setSelectedWeaponIds(newSelectedWeapons);
if (newSelectedWeapons.length >= MAX_WEAPONS) {
setIsGridCollapsed(true);
}
};
const handleRemoveWeapon = (index: number) => {
if (selectedWeaponIds.length >= MAX_WEAPONS) {
setIsGridCollapsed(false);
}
setSelectedWeaponIds(selectedWeaponIds.filter((_, i) => i !== index));
};
return (
<Main className="stack lg">
<SelectedWeapons
selectedWeaponIds={selectedWeaponIds}
onRemove={handleRemoveWeapon}
onReorder={setSelectedWeaponIds}
/>
<WeaponCategories selectedWeaponIds={selectedWeaponIds} />
<WeaponGrid
selectedWeaponIds={selectedWeaponIds}
onWeaponClick={handleWeaponClick}
categorization={categorization}
onCategorizationChange={setCategorization}
isCollapsed={isGridCollapsed}
onToggleCollapse={() => setIsGridCollapsed(!isGridCollapsed)}
/>
<RangeVisualization weaponIds={selectedWeaponIds} />
<DamageComboList weaponIds={selectedWeaponIds} />
</Main>
);
}