overflow content in tank search

This commit is contained in:
tresabhi committed 2026-11-21 20:06:39 -06:00
1 parent 2ed6371ed3
commit 16ff393ea0
25 files changed
+556 -374

No files matched your search

@@ -1,6 +1,8 @@
.button {
border: none;
white-space: nowrap;
display: flex;
align-items: center;
justify-content: center;
@@ -12,7 +12,7 @@ import { Button } from "../Button";
import { Checkbox } from "../Checkbox";
import { Dialog } from "../Dialog";
import { SegmentedControl } from "../SegmentedControl";
import { TankSearch } from "../TankSearch";
import { TankSearchResults } from "../TankSearchResults";
import styles from "./index.module.css";
export function CompareControls() {
@@ -52,7 +52,7 @@ export function CompareControls() {
</Dialog.Header>
<Dialog.Body>
<TankSearch
<TankSearchResults
compact
onSelect={(tank) => {
CompareEphemeral.mutate((draft) => {
@@ -7,7 +7,7 @@ import { useStrings } from "../../hooks/useStrings";
import { CompareEphemeral } from "../../stores/compareEphemeral";
import { Dialog } from "../Dialog";
import { IconButton } from "../IconButton";
import { TankSearch } from "../TankSearch";
import { TankSearchResults } from "../TankSearchResults";
import styles from "./index.module.css";
interface CompareTankControlProps {
@@ -51,7 +51,7 @@ export function CompareTankControl({ index, slug }: CompareTankControlProps) {
</Dialog.Header>
<Dialog.Body>
<TankSearch
<TankSearchResults
compact
onSelect={(tank) => {
CompareEphemeral.mutate((draft) => {
@@ -16,7 +16,7 @@ import { IconButton } from "../IconButton";
import { LazyImage } from "../LazyImage";
import { Popover } from "../Popover";
import { Skeleton } from "../Skeleton";
import { TankSearch } from "../TankSearch";
import { TankSearchResults } from "../TankSearchResults";
import styles from "./index.module.css";
const tankDefinitions = await api.tanks();
@@ -26,7 +26,7 @@ type MixerModuleChooserProps = MaybeSkeletonComponentProps & {
onSelect: (
tank: TankDefinition,
turret?: TurretDefinition,
gun?: GunDefinition
gun?: GunDefinition,
) => void;
turret?: number;
gun?: number;
@@ -69,7 +69,7 @@ export function MixerModuleChooser({
style={{
backgroundImage: `url(${alias(
"api",
`/tanks/${tank}/icons/big.webp`
`/tanks/${tank}/icons/big.webp`,
)})`,
}}
/>
@@ -87,7 +87,7 @@ export function MixerModuleChooser({
</Dialog.Header>
<Dialog.Body>
<TankSearch
<TankSearchResults
compact
onSelect={(tank) => {
onSelect?.(tank);
@@ -1,8 +1,22 @@
.recent {
margin-top: var(--space-4);
display: flex;
flex-direction: column;
gap: var(--space-4);
padding: var(--space-4);
background-color: var(--gray-a2);
border-radius: var(--space-3);
width: fit-content;
.list {
display: flex;
gap: var(--space-4);
width: fit-content;
--min-tank-card-size: 7rem;
}
}
@@ -1,32 +1,34 @@
import { isEqual } from "lodash-es";
import { useMemo } from "react";
import { api } from "../../api/dynamic";
import { withLocale } from "../../hocs/withLocale";
import { useStrings } from "../../hooks/useStrings";
import { TankFilters } from "../../stores/tankFilters";
import { TankopediaPersistent } from "../../stores/tankopediaPersistent";
import { TankSort } from "../../stores/tankopediaSort";
import { TankCard } from "../TankCard";
import { TankCardWrapper } from "../TankCardWrapper";
import { Text } from "../Text";
import styles from "./index.module.css";
const tankDefinitions = await api.tanks();
export function RecentlyViewedTanks() {
export const RecentlyViewedTanks = withLocale(Content);
function Content() {
const filters = TankFilters.use();
// non-reactive because it is a little weird that it updates instantly even before the page loads
const recentlyViewed = TankopediaPersistent.state.recentlyViewed.filter(
(id) => id in tankDefinitions.tanks
(id) => id in tankDefinitions.tanks,
);
const hasFilters = useMemo(
() =>
Object.entries(filters).some(([key, value]) => {
return !isEqual(
value,
TankFilters.initial[key as keyof typeof TankFilters.initial]
TankFilters.initial[key as keyof typeof TankFilters.initial],
);
}),
[filters]
[filters],
);
const strings = useStrings();
@@ -37,23 +39,16 @@ export function RecentlyViewedTanks() {
}
return (
<div
className={styles.recent}
style={{
display: "flex",
flexDirection: "column",
gap: "var(--space-4)",
}}
>
<Text color="gray" lowContrast>
<div className={styles.recent}>
<Text color="gray" lowContrast className={styles.label}>
{strings.website.common.tank_search.recent}
</Text>
<TankCardWrapper compact>
<div className={styles.list}>
{recentlyViewed.map((id) => (
<TankCard compact tank={tankDefinitions.tanks[id]} key={id} />
))}
</TankCardWrapper>
</div>
</div>
);
}
@@ -78,6 +78,7 @@ interface Drag {
axis: Axis;
}
// TODO: sunset scroller
export function Scroller({
children,
className,
@@ -0,0 +1,29 @@
.anchor {
display: none;
}
.target {
--scroller-curtains-size: min(25%, var(--space-6));
--scroller-curtains-x-start: 0;
--scroller-curtains-x-end: 0;
--scroller-curtains-y-start: 0;
--scroller-curtains-y-end: 0;
/* Masks the element's own box, so the fade stays put while the content scrolls under it */
mask-image:
linear-gradient(
90deg,
rgb(0 0 0 / calc(1 - var(--scroller-curtains-x-start))),
black var(--scroller-curtains-size),
black calc(100% - var(--scroller-curtains-size)),
rgb(0 0 0 / calc(1 - var(--scroller-curtains-x-end)))
),
linear-gradient(
180deg,
rgb(0 0 0 / calc(1 - var(--scroller-curtains-y-start))),
black var(--scroller-curtains-size),
black calc(100% - var(--scroller-curtains-size)),
rgb(0 0 0 / calc(1 - var(--scroller-curtains-y-end)))
);
mask-composite: intersect;
}
@@ -0,0 +1,136 @@
import { useCallback, useEffect, useRef } from "react";
import { clamp } from "three/src/math/MathUtils.js";
import { ScrollerOrientation } from "../Scroller";
import styles from "./index.module.css";
enum Axis {
X = "x",
Y = "y",
}
enum Side {
Start = "start",
End = "end",
}
interface ScrollerCurtainsProps {
orientation?: ScrollerOrientation;
// Whether the fade at each end of the scroll axis is rendered
startCurtain?: boolean;
endCurtain?: boolean;
}
const MAX_FADE_DISTANCE = 60;
const FADE_RATIO = 0.15;
const ORIENTATION_AXES = {
[ScrollerOrientation.Horizontal]: [Axis.X],
[ScrollerOrientation.Vertical]: [Axis.Y],
[ScrollerOrientation.Both]: [Axis.X, Axis.Y],
} satisfies Record<ScrollerOrientation, Axis[]>;
const DIMENSIONS = {
[Axis.X]: {
scroll: "scrollLeft",
scrollSize: "scrollWidth",
clientSize: "clientWidth",
},
[Axis.Y]: {
scroll: "scrollTop",
scrollSize: "scrollHeight",
clientSize: "clientHeight",
},
} as const;
// Fades the edges of the parent element, which must already be scrollable
export function ScrollerCurtains({
orientation = ScrollerOrientation.Horizontal,
startCurtain = true,
endCurtain = true,
}: ScrollerCurtainsProps) {
const anchor = useRef<HTMLSpanElement>(null!);
const sync = useCallback(
(element: HTMLElement) => {
for (const axis of ORIENTATION_AXES[orientation]) {
const dimension = DIMENSIONS[axis];
const clientSize = element[dimension.clientSize];
const position = element[dimension.scroll];
const overflow = element[dimension.scrollSize] - clientSize;
const fadeDistance = Math.min(
MAX_FADE_DISTANCE,
clientSize * FADE_RATIO,
);
const start =
!startCurtain || overflow <= 0
? 0
: clamp(position / fadeDistance, 0, 1);
const end =
!endCurtain || overflow <= 0
? 0
: clamp((overflow - position) / fadeDistance, 0, 1);
element.style.setProperty(
`--scroller-curtains-${axis}-${Side.Start}`,
`${start}`,
);
element.style.setProperty(
`--scroller-curtains-${axis}-${Side.End}`,
`${end}`,
);
}
},
[orientation, startCurtain, endCurtain],
);
useEffect(() => {
let element = anchor.current.parentElement!;
// Skips boxless wrappers like astro-island to reach the actual scroller
while (getComputedStyle(element).display === "contents") {
element = element.parentElement!;
}
const handleSync = () => sync(element);
const resizeObserver = new ResizeObserver(handleSync);
// Tracks children as they mount and unmount instead of re-subscribing every render
const mutationObserver = new MutationObserver((records) => {
for (const record of records) {
record.removedNodes.forEach((node) => {
if (node instanceof Element) resizeObserver.unobserve(node);
});
record.addedNodes.forEach((node) => {
if (node instanceof Element) resizeObserver.observe(node);
});
}
});
element.classList.add(styles.target);
resizeObserver.observe(element);
Array.from(element.children).forEach((child) =>
resizeObserver.observe(child),
);
mutationObserver.observe(element, { childList: true });
element.addEventListener("scroll", handleSync, { passive: true });
handleSync();
return () => {
resizeObserver.disconnect();
mutationObserver.disconnect();
element.removeEventListener("scroll", handleSync);
element.classList.remove(styles.target);
for (const axis of Object.values(Axis)) {
for (const side of Object.values(Side)) {
element.style.removeProperty(`--scroller-curtains-${axis}-${side}`);
}
}
};
}, [sync]);
return <span ref={anchor} className={styles.anchor} />;
}
@@ -19,7 +19,6 @@
}
&[data-overflow="true"] {
padding-right: 0;
overflow-x: auto;
}
}
@@ -1,4 +1,6 @@
.wrapper {
min-width: var(--min-tank-card-size);
--image-height: 6rem;
&[data-compact="true"] {
@@ -11,7 +11,7 @@ import { ClassIcon } from "../ClassIcon";
import { LazyImage } from "../LazyImage";
import { LinkI18nWrapper } from "../LinkI18nWrapper";
import { TankCardSkeleton } from "../TankCardSkeleton";
import { MAX_RECENTLY_VIEWED } from "../TankSearch/constants";
import { MAX_RECENTLY_VIEWED } from "../TankSearchResults/constants";
import { Text, type TextProps } from "../Text";
import styles from "./index.module.css";
@@ -1,13 +1,15 @@
.wrapper {
--min-size: 10rem;
--min-tank-card-size: 10rem;
&[data-compact="true"] {
--min-tank-card-size: 7rem;
gap: var(--space-4);
}
display: grid;
gap: var(--space-5) var(--space-4);
grid-template-columns: repeat(auto-fill, minmax(var(--min-size), 1fr));
&[data-compact="true"] {
--min-size: 7rem;
gap: var(--space-4);
}
grid-template-columns: repeat(
auto-fill,
minmax(var(--min-tank-card-size), 1fr)
);
}
@@ -1 +0,0 @@
export const MAX_RECENTLY_VIEWED = 14;
@@ -1,311 +0,0 @@
import { metaSortTank, SEARCH_KEYS } from "@blitzkit/core";
import { literals } from "@blitzkit/i18n/src/literals";
import type { TankDefinition } from "@blitzkit/protos";
import fuzzysort from "fuzzysort";
import { uniq } from "lodash-es";
import { memo, useMemo } from "react";
import usePromise from "react-promise-suspense";
import type { Vector2Tuple } from "three";
import { api } from "../../api/dynamic";
import { characteristics } from "../../config/characteristics";
import { characteristicRenderConfigs } from "../../config/characteristicsGroups";
import { awaitableTankNames } from "../../core/awaitables/tankNames";
import { filterTanks } from "../../core/blitzkit/filterTanks";
import { useCharacteristicRenderer } from "../../hooks/useCharacteristicRenderer";
import { computeDefaultCharacteristics } from "../../hooks/useCharacteristics";
import { useLocale } from "../../hooks/useLocale";
import { useStrings } from "../../hooks/useStrings";
import { App } from "../../stores/app";
import { TankFilters } from "../../stores/tankFilters";
import {
SortDirection,
TankopediaPersistent,
} from "../../stores/tankopediaPersistent";
import { TankSort } from "../../stores/tankopediaSort";
import { sortableCharacteristics } from "../../tankopedia/sortableCharacteristics";
import {
CharacteristicType,
type ComputedCharacteristics,
} from "../../types/characteristics";
import type { MaybeSkeletonComponentProps } from "../../types/maybeSkeletonComponentProps";
import { Callout } from "../Callout";
import { ExperimentIcon } from "../ExperimentIcon";
import { IncrementalLoader } from "../IncrementalLoader";
import { Link } from "../Link";
import { RecentlyViewedTanks } from "../RecentlyViewedTanks";
import { TankCard } from "../TankCard";
import { TankCardWrapper } from "../TankCardWrapper";
import { TankSearchBar } from "../TankSearchBar";
import { TankSearchFilters } from "../TankSearchFilters";
import { TankSearchNoResults } from "../TankSearchNoResults";
import { Text } from "../Text";
import { MAX_RECENTLY_VIEWED } from "./constants";
import styles from "./index.module.css";
export type TankSearchProps = MaybeSkeletonComponentProps & {
compact?: boolean;
onSelect?: (tank: TankDefinition) => void;
onSelectAll?: (tanks: TankDefinition[]) => void;
};
// TODO: across the project, remove "definitions"
const [gameDefinitions, tankDefinitions, tankNames] = await Promise.all([
api.game(),
api.tanks(),
awaitableTankNames,
]);
const tankDefinitionsArray = Object.values(tankDefinitions.tanks);
// TODO: add compact mode
export const TankSearch = memo<TankSearchProps>(
({ compact, onSelect, onSelectAll, skeleton }) => {
const strings = useStrings();
const locale = useLocale();
const wargaming = App.use((state) => state.logins.wargaming);
const tankopediaSort = TankSort.use();
const tankFilters = TankFilters.use();
const defaultCharacteristics = useMemo(() => {
const computed = new Map<number, ComputedCharacteristics>();
for (const tank of tankDefinitionsArray) {
computed.set(tank.id, computeDefaultCharacteristics(tank));
}
return computed;
}, []);
const filtered = usePromise(
async () => {
let filtered = tankDefinitionsArray;
if (tankopediaSort.by !== null) {
filtered = filtered.filter((tank) =>
defaultCharacteristics.get(tank.id)!.has(tankopediaSort.by!),
);
}
if (tankFilters.search === null) {
filtered = await filterTanks(tankFilters, filtered, wargaming?.id);
} else {
filtered = fuzzysort
.go(tankFilters.search, tankNames, { keys: SEARCH_KEYS })
.map((result) => tankDefinitions.tanks[result.obj.id]);
}
return filtered;
},
// react-promise-suspense has awful type annotations
[tankFilters, tankopediaSort.by] as any,
);
const sorted = useMemo(() => {
if (tankFilters.search !== null) return filtered;
if (
tankopediaSort.by === null ||
!sortableCharacteristics.has(tankopediaSort.by)
) {
const byMeta = metaSortTank([...filtered], gameDefinitions);
return tankopediaSort.direction === SortDirection.Ascending
? byMeta
: byMeta.reverse();
}
const values = new Map<number, number | undefined>();
const by = tankopediaSort.by;
const characteristic = characteristics[by];
for (const tank of filtered) {
const computedCharacteristics = defaultCharacteristics.get(tank.id)!;
if (!computedCharacteristics.has(by)) {
values.set(tank.id, undefined);
continue;
}
const value = computedCharacteristics.get(by);
let sortValue: number | undefined;
switch (characteristic.type) {
case CharacteristicType.Number: {
sortValue = value as number;
break;
}
case CharacteristicType.Interval: {
const [low, high] = value as Vector2Tuple;
sortValue = (low + high) / 2;
break;
}
case CharacteristicType.NumberList: {
const values = value as number[];
if (values.length === 0) {
sortValue = undefined;
break;
}
let sum = 0;
for (const item of values) {
sum += item;
}
sortValue = sum / values.length;
break;
}
default:
throw new Error(
`Unsortable characteristic type ${characteristic.type}`,
);
}
values.set(tank.id, sortValue);
}
const direction =
tankopediaSort.direction === SortDirection.Ascending ? 1 : -1;
return [...filtered].sort((a, b) => {
const aValue = values.get(a.id);
const bValue = values.get(b.id);
if (aValue === undefined) return bValue === undefined ? 0 : 1;
if (bValue === undefined) return -1;
if (aValue === bValue) return 0;
return (aValue < bValue ? -1 : 1) * direction;
});
}, [tankFilters, tankopediaSort]);
const sortConfig =
tankopediaSort.by !== null &&
sortableCharacteristics.has(tankopediaSort.by)
? tankopediaSort.by
: undefined;
const renderCharacteristic = useCharacteristicRenderer();
const data = sorted.map((tank) => {
const tankDefaultCharacteristics = defaultCharacteristics.get(tank.id)!;
const shouldRenderDiscriminator =
tankopediaSort.by !== null &&
tankDefaultCharacteristics.has(tankopediaSort.by);
return {
key: `${tank.id}`,
tank,
discriminator: shouldRenderDiscriminator
? renderCharacteristic(
tankDefaultCharacteristics.get(tankopediaSort.by!)!,
characteristicRenderConfigs.get(tankopediaSort.by!)!,
)
: null,
onTankSelect: onSelect,
};
});
return (
<div className={styles.container}>
<TankSearchBar
skeleton={skeleton}
topResult={sorted[0]}
onSelect={onSelect}
/>
{!tankFilters.search && <TankSearchFilters />}
{!skeleton && !compact && <RecentlyViewedTanks />}
{sorted.length > 0 && (
<div className={styles.label}>
<Text lowContrast className={styles.count}>
{sorted.length === 1
? strings.website.common.tank_search.count_singular
: literals(strings.website.common.tank_search.count_plural, {
count: sorted.length.toLocaleString(locale),
})}
{sortConfig && (
<>
{" - "}
{literals(strings.website.common.tank_search.sorting_by, {
name: (
strings.tanks.characteristics.items as Record<
string,
string
>
)[sortConfig],
})}
,{" "}
{
strings.website.common.tank_search.sort.direction[
tankopediaSort.direction
]
}
</>
)}
{onSelectAll && (
<>
{" "}
<Link
underline="always"
href="#"
onClick={(event) => {
event.preventDefault();
onSelectAll(sorted);
TankopediaPersistent.mutate((draft) => {
draft.recentlyViewed = uniq([
...sorted.map(({ id }) => id),
...draft.recentlyViewed,
])
.filter((id) => id in tankDefinitions.tanks)
.slice(0, MAX_RECENTLY_VIEWED);
});
}}
>
{strings.website.common.tank_search.select_all}
</Link>
</>
)}
</Text>
</div>
)}
{tankFilters.showTesting && !tankFilters.showNonTesting && (
<div className={styles["test-warning"]}>
<Callout color="amber">
<ExperimentIcon style={{ width: "1em", height: "1em" }} />
{strings.website.common.warnings.test}
</Callout>
</div>
)}
<TankCardWrapper>
<IncrementalLoader
skeleton={skeleton}
initial={5 * 5}
intermediate={5 * 2}
data={data}
Component={TankCard}
/>
</TankCardWrapper>
{!skeleton && sorted.length === 0 && (
<TankSearchNoResults type="search" />
)}
</div>
);
},
);
@@ -6,22 +6,20 @@ import {
useEffect,
useRef,
} from "react";
import { withLocale } from "../../hocs/withLocale";
import { useStrings } from "../../hooks/useStrings";
import { TankFilters } from "../../stores/tankFilters";
import type { MaybeSkeletonComponentProps } from "../../types/maybeSkeletonComponentProps";
import { TankSearchSort } from "../TankSearchSort";
import { TextField } from "../TextField";
type SearchBarProps = MaybeSkeletonComponentProps & {
type SearchBarProps = {
topResult?: TankDefinition;
onSelect?: (tank: TankDefinition) => void;
};
export function TankSearchBar({
topResult,
skeleton,
onSelect,
}: SearchBarProps) {
export const TankSearchBar = withLocale(Content);
function Content({ topResult, onSelect }: SearchBarProps) {
const strings = useStrings();
const search = TankFilters.use((state) => state.search);
@@ -56,13 +54,12 @@ export function TankSearchBar({
window.location.href = `/tanks/${topResult.slug}`;
}
},
[topResult]
[topResult],
);
return (
<div style={{ display: "flex", gap: "var(--space-3)" }}>
<TextField
disabled={skeleton}
defaultValue={search ?? undefined}
style={{ flex: 1 }}
ref={input}
@@ -1,6 +1,5 @@
.filters {
display: flex;
flex-wrap: wrap;
gap: var(--space-3);
@@ -13,6 +13,7 @@ import {
import { Fragment } from "react";
import { api } from "../../api/dynamic";
import { awaitableTiers } from "../../core/awaitables/tiers";
import { withLocale } from "../../hocs/withLocale";
import { useStrings } from "../../hooks/useStrings";
import { useUnwrapper } from "../../hooks/useUnwrapper";
import { App } from "../../stores/app";
@@ -149,7 +150,9 @@ const MAX_ICONS = 4;
const TIERS = await awaitableTiers;
export function TankSearchFilters() {
export const TankSearchFilters = withLocale(Content);
function Content() {
return (
<div className={styles.filters}>
<TiersFilter />
@@ -310,7 +313,10 @@ function NationsFilter() {
<div
className={styles.flag}
style={{
backgroundImage: `url(${alias("api", `/flags/scratched/${nation}.webp`)})`,
backgroundImage: `url(${alias(
"api",
`/flags/scratched/${nation}.webp`,
)})`,
}}
/>
@@ -609,7 +615,9 @@ function IndividualShellFilter({
<LazyImage
src={alias(
"api",
`/icons/shells/${shellTypeIcons[shells[index]]}${premium ? "_premium" : ""}.webp`,
`/icons/shells/${shellTypeIcons[shells[index]]}${
premium ? "_premium" : ""
}.webp`,
)}
/>
)}
@@ -934,7 +942,9 @@ function ProvisionsFilter() {
{unwrap(provisionDefinition.name!)}
<LazyImage src={alias("api", `/icons/provisions/${provision}.webp`)} />
<LazyImage
src={alias("api", `/icons/provisions/${provision}.webp`)}
/>
</DropdownMenu.CheckboxItem>
);
})}
@@ -0,0 +1 @@
export const MAX_RECENTLY_VIEWED = 28;
@@ -0,0 +1,296 @@
import { metaSortTank, SEARCH_KEYS } from "@blitzkit/core";
import { literals } from "@blitzkit/i18n/src/literals";
import type { TankDefinition } from "@blitzkit/protos";
import fuzzysort from "fuzzysort";
import { uniq } from "lodash-es";
import { memo, useMemo } from "react";
import usePromise from "react-promise-suspense";
import type { Vector2Tuple } from "three";
import { api } from "../../api/dynamic";
import { characteristics } from "../../config/characteristics";
import { characteristicRenderConfigs } from "../../config/characteristicsGroups";
import { awaitableTankNames } from "../../core/awaitables/tankNames";
import { filterTanks } from "../../core/blitzkit/filterTanks";
import { withLocale } from "../../hocs/withLocale";
import { useCharacteristicRenderer } from "../../hooks/useCharacteristicRenderer";
import { computeDefaultCharacteristics } from "../../hooks/useCharacteristics";
import { useLocale } from "../../hooks/useLocale";
import { useStrings } from "../../hooks/useStrings";
import { App } from "../../stores/app";
import { TankFilters } from "../../stores/tankFilters";
import {
SortDirection,
TankopediaPersistent,
} from "../../stores/tankopediaPersistent";
import { TankSort } from "../../stores/tankopediaSort";
import { sortableCharacteristics } from "../../tankopedia/sortableCharacteristics";
import {
CharacteristicType,
type ComputedCharacteristics,
} from "../../types/characteristics";
import { Callout } from "../Callout";
import { ExperimentIcon } from "../ExperimentIcon";
import { IncrementalLoader } from "../IncrementalLoader";
import { Link } from "../Link";
import { TankCard } from "../TankCard";
import { TankCardWrapper } from "../TankCardWrapper";
import { TankSearchNoResults } from "../TankSearchNoResults";
import { Text } from "../Text";
import { MAX_RECENTLY_VIEWED } from "./constants";
import styles from "./index.module.css";
export type TankSearchResultsProps = {
compact?: boolean;
onSelect?: (tank: TankDefinition) => void;
onSelectAll?: (tanks: TankDefinition[]) => void;
};
// TODO: across the project, remove "definitions"
const [gameDefinitions, tankDefinitions, tankNames] = await Promise.all([
api.game(),
api.tanks(),
awaitableTankNames,
]);
const tankDefinitionsArray = Object.values(tankDefinitions.tanks);
// TODO: add compact mode
export const TankSearchResults = withLocale(
memo<TankSearchResultsProps>(Content),
);
function Content({ onSelect, onSelectAll }: TankSearchResultsProps) {
const strings = useStrings();
const locale = useLocale();
const wargaming = App.use((state) => state.logins.wargaming);
const tankopediaSort = TankSort.use();
const tankFilters = TankFilters.use();
const defaultCharacteristics = useMemo(() => {
const computed = new Map<number, ComputedCharacteristics>();
for (const tank of tankDefinitionsArray) {
computed.set(tank.id, computeDefaultCharacteristics(tank));
}
return computed;
}, []);
const filtered = usePromise(
async () => {
let filtered = tankDefinitionsArray;
if (tankopediaSort.by !== null) {
filtered = filtered.filter((tank) =>
defaultCharacteristics.get(tank.id)!.has(tankopediaSort.by!),
);
}
if (tankFilters.search === null) {
filtered = await filterTanks(tankFilters, filtered, wargaming?.id);
} else {
filtered = fuzzysort
.go(tankFilters.search, tankNames, { keys: SEARCH_KEYS })
.map((result) => tankDefinitions.tanks[result.obj.id]);
}
return filtered;
},
// react-promise-suspense has awful type annotations
[tankFilters, tankopediaSort.by] as any,
);
const sorted = useMemo(() => {
if (tankFilters.search !== null) return filtered;
if (
tankopediaSort.by === null ||
!sortableCharacteristics.has(tankopediaSort.by)
) {
const byMeta = metaSortTank([...filtered], gameDefinitions);
return tankopediaSort.direction === SortDirection.Ascending
? byMeta
: byMeta.reverse();
}
const values = new Map<number, number | undefined>();
const by = tankopediaSort.by;
const characteristic = characteristics[by];
for (const tank of filtered) {
const computedCharacteristics = defaultCharacteristics.get(tank.id)!;
if (!computedCharacteristics.has(by)) {
values.set(tank.id, undefined);
continue;
}
const value = computedCharacteristics.get(by);
let sortValue: number | undefined;
switch (characteristic.type) {
case CharacteristicType.Number: {
sortValue = value as number;
break;
}
case CharacteristicType.Interval: {
const [low, high] = value as Vector2Tuple;
sortValue = (low + high) / 2;
break;
}
case CharacteristicType.NumberList: {
const values = value as number[];
if (values.length === 0) {
sortValue = undefined;
break;
}
let sum = 0;
for (const item of values) {
sum += item;
}
sortValue = sum / values.length;
break;
}
default:
throw new Error(
`Unsortable characteristic type ${characteristic.type}`,
);
}
values.set(tank.id, sortValue);
}
const direction =
tankopediaSort.direction === SortDirection.Ascending ? 1 : -1;
return [...filtered].sort((a, b) => {
const aValue = values.get(a.id);
const bValue = values.get(b.id);
if (aValue === undefined) return bValue === undefined ? 0 : 1;
if (bValue === undefined) return -1;
if (aValue === bValue) return 0;
return (aValue < bValue ? -1 : 1) * direction;
});
}, [tankFilters, tankopediaSort]);
const sortConfig =
tankopediaSort.by !== null && sortableCharacteristics.has(tankopediaSort.by)
? tankopediaSort.by
: undefined;
const renderCharacteristic = useCharacteristicRenderer();
const data = sorted.map((tank) => {
const tankDefaultCharacteristics = defaultCharacteristics.get(tank.id)!;
const shouldRenderDiscriminator =
tankopediaSort.by !== null &&
tankDefaultCharacteristics.has(tankopediaSort.by);
return {
key: `${tank.id}`,
tank,
discriminator: shouldRenderDiscriminator
? renderCharacteristic(
tankDefaultCharacteristics.get(tankopediaSort.by!)!,
characteristicRenderConfigs.get(tankopediaSort.by!)!,
)
: null,
onTankSelect: onSelect,
};
});
return (
<div className={styles.container}>
{sorted.length > 0 && (
<div className={styles.label}>
<Text lowContrast className={styles.count}>
{sorted.length === 1
? strings.website.common.tank_search.count_singular
: literals(strings.website.common.tank_search.count_plural, {
count: sorted.length.toLocaleString(locale),
})}
{sortConfig && (
<>
{" - "}
{literals(strings.website.common.tank_search.sorting_by, {
name: (
strings.tanks.characteristics.items as Record<
string,
string
>
)[sortConfig],
})}
,{" "}
{
strings.website.common.tank_search.sort.direction[
tankopediaSort.direction
]
}
</>
)}
{onSelectAll && (
<>
{" "}
<Link
underline="always"
href="#"
onClick={(event) => {
event.preventDefault();
onSelectAll(sorted);
TankopediaPersistent.mutate((draft) => {
draft.recentlyViewed = uniq([
...sorted.map(({ id }) => id),
...draft.recentlyViewed,
])
.filter((id) => id in tankDefinitions.tanks)
.slice(0, MAX_RECENTLY_VIEWED);
});
}}
>
{strings.website.common.tank_search.select_all}
</Link>
</>
)}
</Text>
</div>
)}
{tankFilters.showTesting && !tankFilters.showNonTesting && (
<div className={styles["test-warning"]}>
<Callout color="amber">
<ExperimentIcon style={{ width: "1em", height: "1em" }} />
{strings.website.common.warnings.test}
</Callout>
</div>
)}
<TankCardWrapper>
<IncrementalLoader
initial={2 ** 6}
intermediate={2 ** 4}
data={data}
Component={TankCard}
/>
</TankCardWrapper>
{sorted.length === 0 && <TankSearchNoResults type="search" />}
</div>
);
}
@@ -8,7 +8,7 @@ import { Duel } from "../../stores/duel";
import { TankopediaPersistent } from "../../stores/tankopediaPersistent";
import { AesonPlug } from "../AesonPlug";
import { ExperimentIcon } from "../ExperimentIcon";
import { MAX_RECENTLY_VIEWED } from "../TankSearch/constants";
import { MAX_RECENTLY_VIEWED } from "../TankSearchResults/constants";
const tankDefinitions = await api.tanks();
@@ -40,6 +40,9 @@ const { locale, accent, solidNavbar = false, tool } = Astro.props;
interpolate-size: allow-keywords;
background-color: var(--gray-1);
}
:global(*) {
scrollbar-width: none;
&::-webkit-scrollbar {
@@ -1,7 +0,0 @@
import { TankSearch } from "../../../../components/TankSearch";
import { withLocale } from "../../../../hocs/withLocale";
import type { MaybeSkeletonComponentProps } from "../../../../types/maybeSkeletonComponentProps";
export const Page = withLocale<MaybeSkeletonComponentProps>(({ skeleton }) => (
<TankSearch skeleton={skeleton} />
));
@@ -1,10 +1,14 @@
---
import ColorScale from "../../../../components/ColorScale.astro";
import { RecentlyViewedTanks } from "../../../../components/RecentlyViewedTanks";
import { ScrollerCurtains } from "../../../../components/ScrollerCurtains";
import { Section } from "../../../../components/Section";
import { TankSearchBar } from "../../../../components/TankSearchBar";
import { TankSearchFilters } from "../../../../components/TankSearchFilters";
import { TankSearchResults } from "../../../../components/TankSearchResults";
import ToolBanner from "../../../../components/ToolBanner.astro";
import { tools } from "../../../../constants/tools";
import BaseLayout from "../../../../layouts/BaseLayout.astro";
import { Page } from "./_index";
export { getStaticPaths } from "../index.astro";
@@ -18,10 +22,21 @@ const { locale } = Astro.props;
<BaseLayout tool={tools.tanks} {locale} accent="purple">
<ToolBanner {locale} tool={tools.tanks} />
<!-- TODO: eliminate all client:only's -->
<Section overflow>
<ScrollerCurtains client:load />
<RecentlyViewedTanks {locale} client:load />
</Section>
<Section>
<Page {locale} client:only="react">
<Page {locale} skeleton slot="fallback" />
</Page>
<TankSearchBar {locale} client:load />
</Section>
<Section overflow>
<ScrollerCurtains client:load />
<TankSearchFilters {locale} client:load />
</Section>
<Section>
<TankSearchResults {locale} client:load />
</Section>
</BaseLayout>