diff --git a/app/features/availability/core/ScheduleWeek.ts b/app/features/availability/core/ScheduleWeek.ts index 3d695a4a2..ccae275dd 100644 --- a/app/features/availability/core/ScheduleWeek.ts +++ b/app/features/availability/core/ScheduleWeek.ts @@ -1,5 +1,10 @@ import * as R from "remeda"; -import type { BusyBlock, TimeRange } from "../availability-types"; +import { AVAILABILITY } from "../availability-constants"; +import type { + BusyBlock, + PlayableWindowTier, + TimeRange, +} from "../availability-types"; import * as Availability from "./Availability"; const DAY_SECONDS = 24 * 60 * 60; @@ -134,3 +139,64 @@ export function memberRow({ ), }; } + +/** + * The players' free time in the week with commitments cut out and the playable windows it leaves, + * needing `AVAILABILITY.DEFAULT_MIN_PLAYERS` or every player of a smaller roster. + */ +export function teamWindows({ + range, + playerIds, + reportedWeeks, + busyByUserId, +}: { + range: TimeRange; + playerIds: Array; + reportedWeeks: Array; + busyByUserId: Map>; +}) { + const minPlayers = Math.min( + AVAILABILITY.DEFAULT_MIN_PLAYERS, + playerIds.length, + ); + const members = playerIds.map((userId) => ({ + userId, + ranges: Availability.subtract( + Availability.clip( + reportedWeeks + .filter((week) => week.userId === userId) + .flatMap((week) => week.slots), + range, + ), + busyByUserId.get(userId) ?? [], + ), + })); + + return { + members, + minPlayers, + windows: Availability.playableWindows({ members, minPlayers }), + }; +} + +/** Tier of the best playable window starting on the viewer-local day (the day it renders its grid ranges on). */ +export function bestWindowTierOfDay({ + date, + windows, + timezone, +}: { + date: string; + windows: Array; + timezone: string; +}): PlayableWindowTier | null { + const tiers = windows + .filter( + (window) => + Availability.dateInTimezone(window.startsAt, timezone) === date, + ) + .map((window) => window.tier); + + if (tiers.includes("FULL")) return "FULL"; + if (tiers.includes("ONE_SHORT")) return "ONE_SHORT"; + return null; +} diff --git a/app/features/availability/loaders/t.$customUrl.schedule.server.ts b/app/features/availability/loaders/t.$customUrl.schedule.server.ts index c490eba87..80ca390b0 100644 --- a/app/features/availability/loaders/t.$customUrl.schedule.server.ts +++ b/app/features/availability/loaders/t.$customUrl.schedule.server.ts @@ -11,11 +11,7 @@ import type { SerializeFrom } from "~/utils/remix"; import { notFoundIfNullish, parseParams } from "~/utils/remix.server"; import * as AvailabilityRepository from "../AvailabilityRepository.server"; import { AVAILABILITY } from "../availability-constants"; -import type { - BusyBlock, - PlayableWindowTier, - TimeRange, -} from "../availability-types"; +import type { BusyBlock, TimeRange } from "../availability-types"; import * as Availability from "../core/Availability"; import * as ScheduleWeek from "../core/ScheduleWeek"; import * as VisibleSchedules from "../core/VisibleSchedules.server"; @@ -104,26 +100,12 @@ function weekView({ busyByUserId: Map>; teamEvents: Array; }) { - const minPlayers = Math.min( - AVAILABILITY.DEFAULT_MIN_PLAYERS, - playerIds.length, - ); - - const windows = Availability.playableWindows({ - members: playerIds.map((userId) => ({ - userId, - ranges: Availability.subtract( - Availability.clip( - reportedWeeks - .filter((week) => week.userId === userId) - .flatMap((week) => week.slots), - range, - ), - busyByUserId.get(userId) ?? [], - ), - })), - minPlayers, - }).map((window) => R.omit(window, ["userIds"])); + const { minPlayers, windows } = ScheduleWeek.teamWindows({ + range, + playerIds, + reportedWeeks, + busyByUserId, + }); const days = ScheduleWeek.days(range, timezone).map((day) => ({ ...day, @@ -133,7 +115,11 @@ function weekView({ time: "00:00", timezone, }), - windowTier: bestWindowTierOfDay({ date: day.date, windows, timezone }), + windowTier: ScheduleWeek.bestWindowTierOfDay({ + date: day.date, + windows, + timezone, + }), })); const members = memberIds.map((userId) => @@ -154,7 +140,7 @@ function weekView({ timezone, days, members, - windows, + windows: windows.map((window) => R.omit(window, ["userIds"])), minPlayers, teamEvents: teamEvents.filter( (event) => @@ -162,25 +148,3 @@ function weekView({ ), }; } - -/** Tier of the best playable window starting on the viewer-local day (the day it renders its grid ranges on). */ -function bestWindowTierOfDay({ - date, - windows, - timezone, -}: { - date: string; - windows: Array; - timezone: string; -}): PlayableWindowTier | null { - const tiers = windows - .filter( - (window) => - Availability.dateInTimezone(window.startsAt, timezone) === date, - ) - .map((window) => window.tier); - - if (tiers.includes("FULL")) return "FULL"; - if (tiers.includes("ONE_SHORT")) return "ONE_SHORT"; - return null; -} diff --git a/app/features/feed/FeedEventRepository.server.ts b/app/features/feed/FeedEventRepository.server.ts index eb39cc3a5..af46db6ca 100644 --- a/app/features/feed/FeedEventRepository.server.ts +++ b/app/features/feed/FeedEventRepository.server.ts @@ -133,6 +133,15 @@ export function findAllSqPlaysByUserId(userId: number) { "GroupMatch.createdAt as at", "Skill.season", "Skill.ordinal", + eb + .selectFrom("Skill as PreviousSkill") + .select("PreviousSkill.ordinal") + .whereRef("PreviousSkill.userId", "=", "Skill.userId") + .whereRef("PreviousSkill.season", "=", "Skill.season") + .whereRef("PreviousSkill.id", "<", "Skill.id") + .orderBy("PreviousSkill.id", "desc") + .limit(1) + .as("previousOrdinal"), "OwnGroup.tierName as ownTierName", "OwnGroup.tierIsPlus as ownTierIsPlus", "OpponentGroup.tierName as opponentTierName", diff --git a/app/features/feed/FeedRepository.server.ts b/app/features/feed/FeedRepository.server.ts index 8cd1b5dbf..cfcd64137 100644 --- a/app/features/feed/FeedRepository.server.ts +++ b/app/features/feed/FeedRepository.server.ts @@ -299,7 +299,8 @@ export function findTopTeammatesByUserId(userId: number) { .execute(); } -export function findWeaponUsageCounts({ +/** How many maps each player played on each weapon in SendouQ matches created in `[from, to)` */ +export function findWeaponPicksByUser({ from, to, }: { @@ -310,12 +311,13 @@ export function findWeaponUsageCounts({ .selectFrom("ReportedWeapon") .innerJoin("GroupMatch", "GroupMatch.id", "ReportedWeapon.groupMatchId") .select(({ fn }) => [ + "ReportedWeapon.userId", "ReportedWeapon.weaponSplId", fn.countAll().as("count"), ]) - .where("GroupMatch.createdAt", ">", from) + .where("GroupMatch.createdAt", ">=", from) .where("GroupMatch.createdAt", "<", to) - .groupBy("ReportedWeapon.weaponSplId") + .groupBy(["ReportedWeapon.userId", "ReportedWeapon.weaponSplId"]) .execute(); } @@ -1248,36 +1250,6 @@ export function findLatestAddedUpcomingTeamEvent({ .executeTakeFirst(); } -export function findAvailabilitySlotsOfTeamWeek({ - teamId, - weekStartsAt, -}: { - teamId: number; - weekStartsAt: number; -}) { - return db - .selectFrom("AvailabilitySlot") - .innerJoin( - "AvailabilityWeek", - "AvailabilityWeek.id", - "AvailabilitySlot.availabilityWeekId", - ) - .innerJoin( - "AllTeamMember", - "AllTeamMember.userId", - "AvailabilityWeek.userId", - ) - .select([ - "AvailabilityWeek.userId", - "AvailabilitySlot.startsAt", - "AvailabilitySlot.endsAt", - ]) - .where("AllTeamMember.teamId", "=", teamId) - .where("AllTeamMember.leftAt", "is", null) - .where("AvailabilityWeek.weekStartsAt", "=", weekStartsAt) - .execute(); -} - /** * Team scrim posts still open for requests at `now` that the viewer can see or has requested: not * canceled, nothing accepted, not started yet ("looking now" posts until `lookingNowFrom`). Posts the diff --git a/app/features/feed/components/CommunityItems.module.css b/app/features/feed/components/CommunityItems.module.css index ef41a2b1c..656fbc2e5 100644 --- a/app/features/feed/components/CommunityItems.module.css +++ b/app/features/feed/components/CommunityItems.module.css @@ -32,6 +32,10 @@ aspect-ratio: 16 / 9; object-fit: cover; border-radius: max(2px, calc(var(--radius-box) - var(--s-2))); + + @container (width < 400px) { + width: 72px; + } } .rotationStageOff { diff --git a/app/features/feed/components/CommunityItems.tsx b/app/features/feed/components/CommunityItems.tsx index 75516fcdd..d7cde83a5 100644 --- a/app/features/feed/components/CommunityItems.tsx +++ b/app/features/feed/components/CommunityItems.tsx @@ -164,6 +164,7 @@ export function communityItemContent( ) : null} ), + href: plusSuggestionPage({ tier: data.tier }), }; } case "ARTICLE_NEW": { @@ -247,7 +248,7 @@ export function communityItemContent( key={`${rotation.type}-${rotation.startsAt}`} className={styles.rotationRow} > -
+
- + {rotationTypeLabel(rotation.type)}
diff --git a/app/features/feed/components/CreatorItems.tsx b/app/features/feed/components/CreatorItems.tsx index 83739a98c..ba8b4c7b7 100644 --- a/app/features/feed/components/CreatorItems.tsx +++ b/app/features/feed/components/CreatorItems.tsx @@ -11,7 +11,7 @@ import { smallImageFileName, vodVideoPage } from "~/utils/urls"; import type { FeedItem } from "../core/FeedItems.server"; import styles from "./CreatorItems.module.css"; import type { FeedItemContent } from "./FeedItemCard"; -import { countText, LogoAvatar, UserName } from "./FeedParts"; +import { countText, UnknownWeaponImage, UserName } from "./FeedParts"; import partsStyles from "./FeedParts.module.css"; export function creatorItemContent(item: FeedItem): FeedItemContent | null { @@ -108,7 +108,7 @@ export function creatorItemContent(item: FeedItem): FeedItemContent | null { case "VOD_NEW": { const { data } = item; return { - avatar: , + avatar: , line: ( <> New {data.type.toLowerCase()} VoD:{" "} @@ -158,6 +158,7 @@ export function creatorItemContent(item: FeedItem): FeedItemContent | null {
), + href: vodVideoPage(data.videoId), }; } case "XRANK_TOP_500": { @@ -258,9 +259,16 @@ export function creatorItemContent(item: FeedItem): FeedItemContent | null { variant="build" size={22} /> - ) : null} + ) : ( + + )} - + {player.name ?? "?"} diff --git a/app/features/feed/components/Feed.tsx b/app/features/feed/components/Feed.tsx index 2d210a62b..94be86a0b 100644 --- a/app/features/feed/components/Feed.tsx +++ b/app/features/feed/components/Feed.tsx @@ -27,15 +27,12 @@ export function Feed({ canViewAs = false, headerEnd, footer, - scoreShown = false, }: { data: FeedPageData; /** Dev only: lets the feed of any user be picked */ canViewAs?: boolean; headerEnd?: React.ReactNode; footer?: React.ReactNode; - /** Shows how each post's ranking score was calculated */ - scoreShown?: boolean; }) { const [tabParam, setTabParam] = useSearchParam(feedSearchParams, "tab"); const [viewAs] = useSearchParam(feedSearchParams, "viewAs"); @@ -54,7 +51,7 @@ export function Feed({ return definition.category === filter; }); - const card = (item: FeedItem, score?: ScoreBreakdown) => ( + const card = (item: FeedItem, score?: ScoreBreakdown | null) => ( {filter === "ALL" ? data.pinned.map((item) => card(item)) : null} - {activity.map((item) => - card(item, scoreShown ? item.score : undefined), - )} + {activity.map((item) => card(item, item.score))}
All caught up! diff --git a/app/features/feed/components/FeedItemCard.module.css b/app/features/feed/components/FeedItemCard.module.css index 3f43ba7f8..f84a875c2 100644 --- a/app/features/feed/components/FeedItemCard.module.css +++ b/app/features/feed/components/FeedItemCard.module.css @@ -78,6 +78,7 @@ display: grid; gap: var(--s-1-5); min-width: 0; + container-type: inline-size; } .meta { @@ -140,6 +141,12 @@ } } +@container (width < 400px) { + .feedbackLabel { + display: none; + } +} + .text { margin: 0; font-size: 0.95rem; @@ -161,6 +168,7 @@ .postAction { justify-self: start; + margin-top: var(--s-1); } .actions { @@ -207,15 +215,21 @@ } .math { - margin-bottom: var(--s-2); - padding: var(--s-1-5) var(--s-2); + display: grid; + gap: var(--s-1-5); font-family: monospace; - font-size: var(--font-2xs); - color: var(--color-text-high); - background-color: var(--color-bg-high); - border-radius: var(--radius-field); + font-size: var(--font-xs); & b { color: var(--color-fg-accent); } } + +.mathTable { + border-collapse: collapse; + + & td { + padding: var(--s-0-5) var(--s-1); + white-space: nowrap; + } +} diff --git a/app/features/feed/components/FeedItemCard.tsx b/app/features/feed/components/FeedItemCard.tsx index 7d83fba21..9b49b0f58 100644 --- a/app/features/feed/components/FeedItemCard.tsx +++ b/app/features/feed/components/FeedItemCard.tsx @@ -1,5 +1,6 @@ import clsx from "clsx"; import { + Calculator, EyeOff, Heart, MessageCircle, @@ -13,6 +14,7 @@ import * as React from "react"; import { Link, useNavigate } from "react-router"; import { SendouButton } from "~/components/elements/Button"; import { SendouMenu, SendouMenuItem } from "~/components/elements/Menu"; +import { SendouPopover } from "~/components/elements/Popover"; import { toastQueue } from "~/components/elements/Toast"; import { Image } from "~/components/Image"; import { useUser } from "~/features/auth/core/user"; @@ -92,7 +94,8 @@ const FEED_FEEDBACK_OPTIONS: Record< const FROM_FEED_STATE: FeedItemPageState = { fromFeed: true }; -const INTERACTIVE_SELECTOR = "a, button, input, label, [role='menuitem']"; +const INTERACTIVE_SELECTOR = + "a, button, input, label, [role='menuitem'], [role='dialog']"; export function FeedItemCard({ item, @@ -112,7 +115,8 @@ export function FeedItemCard({ href?: string; /** Shown at the end of the header line, e.g. a back link on the post page */ headerAction?: React.ReactNode; - score?: ScoreBreakdown; + /** Ranking score breakdown, shown in a popover */ + score?: ScoreBreakdown | null; }) { const navigate = useNavigate(); const definition: FeedItemTypeDefinition = FEED_ITEM_TYPES[item.type]; @@ -192,6 +196,13 @@ export function FeedItemCard({ {relativeTime(item.at, now)} )}
+ {score ? ( + + ) : null} sendFeedback(kind, null)} /> {headerAction ? (
{headerAction}
@@ -211,13 +222,6 @@ export function FeedItemCard({ href={href} /> )} - {score ? ( - - ) : null}
); @@ -352,9 +356,13 @@ function FeedbackMenu({ + } > @@ -431,7 +439,7 @@ function FeedbackPanel({ ); } -function RankingMath({ +function ScorePopover({ score, definition, relation, @@ -440,21 +448,59 @@ function RankingMath({ definition: FeedItemTypeDefinition; relation: FeedRelation | null; }) { + const rows = [ + { label: "base", value: score.base, note: null }, + { label: "weight", value: score.weight.toFixed(2), note: null }, + { + label: "affinity", + value: score.affinity, + note: relation ? relation.toLowerCase() : "no relation", + }, + { label: "weapon", value: score.weaponAffinity, note: null }, + { + label: "recency", + value: score.recency.toFixed(2), + note: `${durationText(score.ageHours * 3600)} old, half-life ${definition.halfLifeHours}h`, + }, + { label: "diversity", value: score.diversity.toFixed(2), note: null }, + ]; + return ( -
- {definition.name}: base {score.base} - {score.weight !== 1 ? ( - <> - {" "} - × weight {score.weight.toFixed(2)} - - ) : null}{" "} - × affinity {score.affinity} - {relation ? ` (${relation.toLowerCase()})` : null} × recency{" "} - {score.recency.toFixed(2)} ({durationText(score.ageHours * 3600)}{" "} - old, half-life {definition.halfLifeHours}h) × diversity{" "} - {score.diversity.toFixed(2)} = {score.total.toFixed(3)} -
+ + + {score.total.toFixed(3)} + + } + > +
+ {definition.name} + + + {rows.map((row, i) => ( + + + + + + + ))} + + + + + + +
{i === 0 ? null : "×"}{row.label} + {row.value} + {row.note}
=total + {score.total.toFixed(3)} + +
+
+
); } diff --git a/app/features/feed/components/FeedParts.module.css b/app/features/feed/components/FeedParts.module.css index 056afc538..5979ac072 100644 --- a/app/features/feed/components/FeedParts.module.css +++ b/app/features/feed/components/FeedParts.module.css @@ -216,6 +216,10 @@ color-mix(in oklch, var(--hero-tint) 14%, var(--color-bg-high)), var(--color-bg-high) 65% ); + + @container (width < 400px) { + padding: var(--s-3); + } } .heroAccent { @@ -272,11 +276,28 @@ & tr:last-child td { border-bottom: 0; } + + @container (width < 400px) { + & td, + & th { + padding-inline: var(--s-1-5); + } + + & .rowNoWrap { + gap: var(--s-1-5); + } + } } .numeric { text-align: right; font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.fillCell { + width: 100%; + max-width: 0; } .rankCell { @@ -364,6 +385,12 @@ align-items: center; gap: var(--s-3); text-align: center; + + @container (width < 400px) { + grid-template-columns: minmax(0, 1fr) fit-content(5.5rem) minmax(0, 1fr); + gap: var(--s-1-5); + padding-inline: var(--s-2); + } } .vsSide { @@ -373,6 +400,14 @@ min-width: 0; font-size: var(--font-sm); font-weight: var(--weight-semi); + + & > .ellipsis { + max-width: 100%; + } + + @container (width < 400px) { + font-size: var(--font-xs); + } } .list { diff --git a/app/features/feed/components/FeedParts.tsx b/app/features/feed/components/FeedParts.tsx index 073e4b3f3..801ca239d 100644 --- a/app/features/feed/components/FeedParts.tsx +++ b/app/features/feed/components/FeedParts.tsx @@ -2,7 +2,13 @@ import clsx from "clsx"; import { useTranslation } from "react-i18next"; import { Link } from "react-router"; import { Avatar } from "~/components/Avatar"; -import { Image, ModeImage, StageImage, WeaponImage } from "~/components/Image"; +import { + Image, + ModeImage, + OutlinedImage, + StageImage, + WeaponImage, +} from "~/components/Image"; import { LocaleTime } from "~/components/LocaleTime"; import { SiteLogoMark } from "~/components/SiteLogoMark"; import type { @@ -13,6 +19,7 @@ import type { import { truncateWithOverflow } from "~/utils/arrays"; import type { CommonUser } from "~/utils/kysely.server"; import { + abilityImageUrl, type NavIcon, navIconUrl, tournamentPage, @@ -147,12 +154,22 @@ export function WeaponSlot({ {weaponSplId !== null ? ( ) : ( - "?" + )} ); } +export function UnknownWeaponImage({ size }: { size: number }) { + return ( + + ); +} + export function WeaponName({ weaponSplId }: { weaponSplId: MainWeaponId }) { const { t } = useTranslation(["weapons"]); @@ -189,15 +206,17 @@ export function TournamentRow({ {tournament.name}
- {tournament.organizationName - ? `${tournament.organizationName} · ` - : null} + {tournament.organizationName && tournament.startsAt + ? `${tournament.organizationName}\u00a0· ` + : tournament.organizationName} {tournament.startsAt ? ( - + + + ) : null}
diff --git a/app/features/feed/components/FeedSidebar.module.css b/app/features/feed/components/FeedSidebar.module.css index da7c5ea43..c2fbe517b 100644 --- a/app/features/feed/components/FeedSidebar.module.css +++ b/app/features/feed/components/FeedSidebar.module.css @@ -51,7 +51,7 @@ padding: var(--s-3); & + & { - border-top: 1px solid var(--color-border); + border-top: var(--border-style); } } @@ -60,19 +60,27 @@ align-items: center; gap: var(--s-1-5); min-width: 0; - font-size: var(--font-xs); white-space: nowrap; } -.rotationType { +.rotationMode { + overflow: hidden; + font-size: var(--font-sm); font-weight: var(--weight-bold); + text-overflow: ellipsis; } -.rotationMode { +.rotationType { + flex-shrink: 0; margin-left: auto; - overflow: hidden; - text-overflow: ellipsis; + padding: var(--s-0-5) var(--s-2); + font-size: var(--font-3xs); + font-weight: var(--weight-semi); color: var(--color-text-high); + text-transform: uppercase; + letter-spacing: 0.04em; + background-color: var(--color-bg-higher); + border-radius: var(--radius-full); } .stages { @@ -85,8 +93,17 @@ position: relative; overflow: hidden; aspect-ratio: 16 / 9; - border-radius: max(2px, calc(var(--radius-box) - var(--s-3))); + border-radius: var(--radius-field); background-color: var(--color-bg-higher); + + &::after { + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; + box-shadow: inset 0 0 0 1px rgb(255 255 255 / 0.08); + pointer-events: none; + } } .stageImageContainer { @@ -104,30 +121,35 @@ .stageName { position: absolute; inset: auto 0 0; - padding: var(--s-3) var(--s-1-5) var(--s-1); - overflow: hidden; + padding: var(--s-5) var(--s-2) var(--s-1-5); font-size: var(--font-2xs); - font-weight: var(--weight-semi); + font-weight: var(--weight-bold); + line-height: 1.2; color: white; - text-overflow: ellipsis; - white-space: nowrap; - background: linear-gradient(transparent, rgb(0 0 0 / 0.75)); + text-wrap: balance; + text-shadow: 0 1px 2px rgb(0 0 0 / 0.6); + background: linear-gradient( + transparent, + rgb(0 0 0 / 0.45) 45%, + rgb(0 0 0 / 0.8) + ); } .next { display: flex; align-items: center; - gap: var(--s-1); + gap: var(--s-1-5); min-width: 0; font-size: var(--font-2xs); - color: var(--color-text-high); white-space: nowrap; } .nextLabel { - font-weight: var(--weight-semi); + font-size: var(--font-3xs); + font-weight: var(--weight-bold); + color: var(--color-text-high); text-transform: uppercase; - letter-spacing: 0.04em; + letter-spacing: 0.06em; } .nextStages { @@ -136,12 +158,14 @@ } .credit { - display: block; padding: var(--s-2) var(--s-3); font-size: var(--font-3xs); - color: var(--color-text-high); text-align: right; - border-top: 1px solid var(--color-border); + border-top: var(--border-style); + + & a { + color: var(--color-text-high); + } } .streams { diff --git a/app/features/feed/components/FeedSidebar.tsx b/app/features/feed/components/FeedSidebar.tsx index 92d40a24e..f66e413d7 100644 --- a/app/features/feed/components/FeedSidebar.tsx +++ b/app/features/feed/components/FeedSidebar.tsx @@ -117,13 +117,13 @@ function RotationsPanel({ {rows.map(({ type, current, next }) => (
  • - - - {t(ROTATION_TYPE_LABELS[type])} - + {t(`game-misc:MODE_LONG_${current.mode as ModeShort}`)} + + {t(ROTATION_TYPE_LABELS[type])} +
    {[current.stageId1, current.stageId2].map((stageId) => ( @@ -135,7 +135,7 @@ function RotationsPanel({ containerClassName={styles.stageImageContainer} /> - {shortStageName(t(`game-misc:STAGE_${stageId as StageId}`))} + {t(`game-misc:STAGE_${stageId as StageId}`)}
    ))} @@ -160,14 +160,11 @@ function RotationsPanel({
  • ))} - - {t("front:rotations.credit")} - + ); } diff --git a/app/features/feed/components/PlayItems.module.css b/app/features/feed/components/PlayItems.module.css index d61f5d7e8..e55525c22 100644 --- a/app/features/feed/components/PlayItems.module.css +++ b/app/features/feed/components/PlayItems.module.css @@ -64,6 +64,23 @@ display: grid; grid-template-columns: 1fr 1fr; gap: var(--s-6); + + @container (width < 400px) { + gap: var(--s-3); + } +} + +.columnsStackNarrow { + @container (width < 400px) { + grid-template-columns: minmax(0, 1fr); + gap: var(--s-4); + } +} + +.promotionFrom { + @container (width < 400px) { + display: none; + } } .column { diff --git a/app/features/feed/components/PlayItems.tsx b/app/features/feed/components/PlayItems.tsx index 768170345..fbab61d1b 100644 --- a/app/features/feed/components/PlayItems.tsx +++ b/app/features/feed/components/PlayItems.tsx @@ -33,6 +33,7 @@ import { NavIconAvatar, StageName, tierLabel, + UnknownWeaponImage, UserName, UserStack, WeaponName, @@ -72,12 +73,14 @@ export function playItemContent(item: FeedItem): FeedItemContent | null {
    - {tierLabel(data.promotion.from)} →{" "} + + {tierLabel(data.promotion.from)} →{" "} + {tierLabel(data.promotion.to)}
    {data.newSp !== null ? (
    - {data.newSp} SP + {`${data.newSp}\u00a0SP`}
    ) : null}
    @@ -135,7 +138,7 @@ export function playItemContent(item: FeedItem): FeedItemContent | null {
    - {data.newSp} SP + {`${data.newSp}\u00a0SP`} ) : null} @@ -189,7 +192,7 @@ export function playItemContent(item: FeedItem): FeedItemContent | null { {data.tier ? ( - {tierLabel(data.tier)} · {data.sp} SP + {tierLabel(data.tier)} · {`${data.sp}\u00a0SP`} ) : null} @@ -227,10 +230,13 @@ export function playItemContent(item: FeedItem): FeedItemContent | null { #{neighbor.placement} - +
    - + {neighbor.user.username}
    @@ -304,7 +310,7 @@ export function playItemContent(item: FeedItem): FeedItemContent | null { "–" )} - {data.sp} SP + {`${data.sp}\u00a0SP`}
    Maps @@ -330,7 +336,7 @@ export function playItemContent(item: FeedItem): FeedItemContent | null { size={28} /> ) : ( - "–" + )}
    {rank - ? `${tierLabel(rank.tier)} · ${rank.sp} SP` + ? `${tierLabel(rank.tier)} · ${rank.sp}\u00a0SP` : `${data.setCount} ${data.setCount === 1 ? "set" : "sets"} played`}
    {rank ? ( @@ -500,7 +506,7 @@ export function playItemContent(item: FeedItem): FeedItemContent | null { ), body: ( <> -
    +
    Players {data.players.map((player) => ( @@ -515,7 +521,9 @@ export function playItemContent(item: FeedItem): FeedItemContent | null { previousPlacement={player.previousPlacement} /> - + {player.sp.toFixed(1)} {player.weeklyChange ? ( , + avatar: , line: ( <> Weapon trends in SendouQ this week @@ -603,13 +611,15 @@ export function playItemContent(item: FeedItem): FeedItemContent | null { = 0 + row.changePercentage === null || + row.changePercentage > 0 ? styles.plusDelta : styles.minusDelta, )} > - {row.changePercentage > 0 ? "+" : ""} - {row.changePercentage}% + {row.changePercentage === null + ? "New" + : `${row.changePercentage > 0 ? "+" : ""}${row.changePercentage}%`}
    ))} @@ -617,8 +627,8 @@ export function playItemContent(item: FeedItem): FeedItemContent | null { ))}
    - Change in share of picks vs last week · {data.reportCount} weapon - reports + Change in share of play vs last week, weighted towards higher + ranked players · {data.playerCount} players
    ), @@ -643,10 +653,12 @@ export function playItemContent(item: FeedItem): FeedItemContent | null { {data.top.map((player) => ( #{player.placement} - +
    - + + +
    diff --git a/app/features/feed/components/TeamItems.module.css b/app/features/feed/components/TeamItems.module.css index 312efd246..0bb78626a 100644 --- a/app/features/feed/components/TeamItems.module.css +++ b/app/features/feed/components/TeamItems.module.css @@ -42,6 +42,24 @@ } } -.heatBest i { +.heatFull i { background-color: var(--color-success); } + +.heatOneShort i { + border-radius: 0 0 var(--radius-selector) var(--radius-selector); + background-color: var(--color-success-low); + box-shadow: inset 0 0 0 1px var(--color-success); +} + +.tierCounts { + display: flex; + flex-wrap: wrap; + gap: var(--s-1) var(--s-3); +} + +.tierCount { + display: inline-flex; + align-items: center; + gap: var(--s-1-5); +} diff --git a/app/features/feed/components/TeamItems.tsx b/app/features/feed/components/TeamItems.tsx index e00b67d4c..05378027a 100644 --- a/app/features/feed/components/TeamItems.tsx +++ b/app/features/feed/components/TeamItems.tsx @@ -3,6 +3,8 @@ import { Link } from "react-router"; import { Avatar } from "~/components/Avatar"; import { WeaponImage } from "~/components/Image"; import { LocaleTime } from "~/components/LocaleTime"; +import type { PlayableWindowTier } from "~/features/availability/availability-types"; +import { TierDot } from "~/features/availability/components/PlayableWindowsSummary"; import { lfgSearchParams } from "~/features/lfg/lfg-search-params"; import { LFG_PAGE, scrimsPage, teamPage, teamSchedulePage } from "~/utils/urls"; import type { FeedItem } from "../core/FeedItems.server"; @@ -27,6 +29,11 @@ const SCRIM_POST_REASON_TEXTS: Record = { FIT: null, }; +const HEAT_TIER_CLASSES: Record = { + FULL: styles.heatFull, + ONE_SHORT: styles.heatOneShort, +}; + export function teamItemContent(item: FeedItem): FeedItemContent | null { switch (item.type) { case "TEAM_JOIN": { @@ -117,9 +124,12 @@ export function teamItemContent(item: FeedItem): FeedItemContent | null { } case "TEAM_AVAILABILITY": { const { data } = item; - const bestDayIndex = Math.floor( - (data.bestStartsAt - data.days[0].startsAt) / 86400, - ); + const fullDayCount = data.days.filter( + (day) => day.tier === "FULL", + ).length; + const oneShortDayCount = data.days.filter( + (day) => day.tier === "ONE_SHORT", + ).length; return { avatar: , line: ( @@ -133,12 +143,13 @@ export function teamItemContent(item: FeedItem): FeedItemContent | null { body: ( <>
    - {data.days.map((day, i) => ( + {data.days.map((day) => (
    - - Best window{" "} - - - {" "} - –{" "} - + + + + + {countText(fullDayCount, "day")} with{" "} + {data.minPlayers}+ + + + {oneShortDayCount > 0 ? ( + + + + {countText(oneShortDayCount, "day")} with{" "} + {data.minPlayers - 1} + + + ) : null} @@ -174,6 +191,7 @@ export function teamItemContent(item: FeedItem): FeedItemContent | null {
    ), + href: teamSchedulePage(data.team.customUrl), }; } case "TEAM_EVENT_ADDED": { diff --git a/app/features/feed/components/TournamentItems.module.css b/app/features/feed/components/TournamentItems.module.css index 5bd14a5e8..ff305505c 100644 --- a/app/features/feed/components/TournamentItems.module.css +++ b/app/features/feed/components/TournamentItems.module.css @@ -16,9 +16,72 @@ display: inline-flex; align-items: center; gap: var(--s-0-5); + + & img { + flex: none; + } +} + +@container (width < 260px) { + .placementsCell { + display: none; + } +} + +@container (width < 400px) { + .medalCounts { + gap: var(--s-1-5); + } + + .medalTimes { + display: none; + } + + .podiumStack, + .standingsAvatar { + display: none; + } +} + +.showcaseList { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto auto; + + @container (width < 400px) { + grid-template-columns: auto minmax(0, 1fr) auto; + } + + & .showcaseRow { + grid-column: 1 / -1; + grid-template-columns: subgrid; + } +} + +.showcaseEnd { + display: contents; + + & > :last-child { + justify-self: end; + } + + @container (width < 400px) { + display: grid; + justify-items: center; + gap: var(--s-1); + + & > :last-child { + justify-self: center; + } + } +} + +.showcaseTier { + display: flex; + justify-content: center; } .emptySlot { + flex: none; width: 30px; height: 30px; border-radius: 50%; diff --git a/app/features/feed/components/TournamentItems.tsx b/app/features/feed/components/TournamentItems.tsx index 45bc825e3..0cc8be4cd 100644 --- a/app/features/feed/components/TournamentItems.tsx +++ b/app/features/feed/components/TournamentItems.tsx @@ -129,7 +129,9 @@ export function tournamentItemContent(
    -
    {data.team.name}
    +
    + {data.team.name} +
    {ordinalPlacement(data.placement)} of {data.participantCount} ·{" "} {data.setWins}–{data.setLosses} in sets @@ -138,7 +140,9 @@ export function tournamentItemContent( : ""}
    - + + +
    ), }; @@ -220,17 +224,11 @@ export function tournamentItemContent( const { data } = item; return { avatar: , - line: data.isActorWinner ? ( + line: ( <> - 's team, seeded {data.winnerSeed}, knocked out seed {data.loserSeed}{" "} - at - - ) : ( - <> - - 's team, seeded {data.loserSeed}, was knocked out by seed{" "} - {data.winnerSeed} at + 's team (seed {data.winnerSeed}) upset seed {data.loserSeed} at{" "} + ), body: ( @@ -275,13 +273,13 @@ export function tournamentItemContent( {data.note ? (
    {data.note}
    ) : null} -
    +
    {Array.from({ length: data.openSpots }, (_, i) => ( ))} {data.tournament?.startsAt ? ( - + ) : null} @@ -368,7 +366,11 @@ export function tournamentItemContent( # Player - Placements + + Placements + Points @@ -381,13 +383,22 @@ export function tournamentItemContent( })} > {row.placement} - +
    - - {row.user.username} + + + {row.user.username} +
    - + @@ -399,6 +410,12 @@ export function tournamentItemContent( ), + href: data.organization + ? tournamentOrganizationPage({ + organizationSlug: data.organization.slug, + seriesId: data.seriesId, + }) + : undefined, }; } case "TO_VOD": { @@ -493,7 +510,7 @@ export function tournamentItemContent( }> -
    +
    {data.trophy.name}
    {data.tournament?.name} @@ -521,7 +538,7 @@ export function tournamentItemContent( }> -
    +
    {data.trophy.name}
    {data.organizationName ? (
    @@ -592,9 +609,12 @@ export function tournamentItemContent( ), body: ( <> -
    +
    {data.tournaments.map((tournament) => ( -
    +
    -
    +
    {tournament.organization ? ` · ${tournament.organization.name}` : ""}
    -
    - {tournament.tier !== null || - tournament.tentativeTier !== null ? ( - - ) : null} +
    + + {tournament.tier !== null || + tournament.tentativeTier !== null ? ( + + ) : null} + {countText(tournament.teamsCount, "team")} @@ -716,7 +743,7 @@ export function tournamentItemContent( #{row.projectedSeed} - +
    @@ -725,7 +752,12 @@ export function tournamentItemContent( {row.isOwn ? ( You ) : row.known.length > 0 ? ( - + {row.known .map((member) => member.username) .join(", ")} @@ -805,7 +837,9 @@ function PodiumBody({ {team.members.map((member) => member.username).join(", ")}
    - + + +
    ))}
    @@ -826,7 +860,9 @@ function MedalCounts({ {[placements.first, placements.second, placements.third].map( (count, i) => ( - ×{count} + + × + {count} ), )} diff --git a/app/features/feed/core/FeedEvents.test.ts b/app/features/feed/core/FeedEvents.test.ts index 736f234b9..e46aae4d3 100644 --- a/app/features/feed/core/FeedEvents.test.ts +++ b/app/features/feed/core/FeedEvents.test.ts @@ -113,8 +113,8 @@ describe("FeedEvents.derive", () => { const events = derive( [ sqPlay({ at: NOW - 2, ordinal: 15 }), - sqPlay({ at: NOW - 1, ordinal: 25, matchId: 2 }), - sqPlay({ at: NOW, ordinal: 35, matchId: 3 }), + sqPlay({ at: NOW - 1, previousOrdinal: 15, ordinal: 25, matchId: 2 }), + sqPlay({ at: NOW, previousOrdinal: 25, ordinal: 35, matchId: 3 }), ], { name: "DIAMOND", isPlus: false }, ); @@ -129,6 +129,23 @@ describe("FeedEvents.derive", () => { ]); }); + test("emits no promotion for a tier crossed outside the set", () => { + const events = derive([ + sqPlay({ at: NOW - 1, ordinal: 25 }), + sqPlay({ at: NOW, previousOrdinal: 31, ordinal: 35 }), + ]); + + expect(ofType(events, "SQ_PROMOTION")).toEqual([]); + }); + + test("emits no promotion for a lost set", () => { + const events = derive([ + sqPlay({ at: NOW, previousOrdinal: 25, ordinal: 35, isWin: false }), + ]); + + expect(ofType(events, "SQ_PROMOTION")).toEqual([]); + }); + test("emits an upset when beating a group enough tiers higher", () => { const events = derive([ sqPlay({ @@ -183,6 +200,7 @@ function sqPlay(play: Partial): FeedEvents.SqPlay { matchId: 1, season: 1, ordinal: 0, + previousOrdinal: null, isWin: true, ownTier: null, opponentTier: null, diff --git a/app/features/feed/core/FeedEvents.ts b/app/features/feed/core/FeedEvents.ts index 6e1e9ddb3..868b581fd 100644 --- a/app/features/feed/core/FeedEvents.ts +++ b/app/features/feed/core/FeedEvents.ts @@ -31,6 +31,8 @@ export interface SqPlay { matchId: number; season: number; ordinal: number; + /** Before this set, also counting tournaments of the season. `null` when this set was the first. */ + previousOrdinal: number | null; isWin: boolean; ownTier: FeedTier | null; opponentTier: FeedTier | null; @@ -146,11 +148,7 @@ export function derive({ } } - let previousOfSeason: SqPlay | undefined; for (const [index, play] of sqPlays.entries()) { - const previous = - previousOfSeason?.season === play.season ? previousOfSeason : undefined; - previousOfSeason = play; if (play.at < since) continue; const milestone = SQ_SET_MILESTONES.find((m) => m === index + 1); @@ -163,8 +161,8 @@ export function derive({ } const tiers = tiersOfSeason(play.season); - if (previous && tiers) { - const from = tierOf(tiers.intervals, previous.ordinal); + if (play.isWin && play.previousOrdinal !== null && tiers) { + const from = tierOf(tiers.intervals, play.previousOrdinal); const to = tierOf(tiers.intervals, play.ordinal); const isNotable = !tiers.previousSeasonTier || diff --git a/app/features/feed/core/FeedIndexer.server.ts b/app/features/feed/core/FeedIndexer.server.ts index 467ded6ad..1a738afad 100644 --- a/app/features/feed/core/FeedIndexer.server.ts +++ b/app/features/feed/core/FeedIndexer.server.ts @@ -85,6 +85,7 @@ async function reindexUser({ userId, now }: { userId: number; now: number }) { matchId: row.matchId, season: row.season, ordinal: row.ordinal, + previousOrdinal: row.previousOrdinal, isWin: row.mapWins > row.mapsPlayed - row.mapWins, ownTier: row.ownTierName ? { name: row.ownTierName, isPlus: Boolean(row.ownTierIsPlus) } diff --git a/app/features/feed/core/FeedItems.server.ts b/app/features/feed/core/FeedItems.server.ts index 49e49fd7b..acd5ccc4f 100644 --- a/app/features/feed/core/FeedItems.server.ts +++ b/app/features/feed/core/FeedItems.server.ts @@ -3,6 +3,9 @@ import { hoursToMilliseconds, subDays } from "date-fns"; import * as R from "remeda"; import { Config } from "~/config"; import { mostRecentArticles } from "~/features/articles/core/list.server"; +import * as Availability from "~/features/availability/core/Availability"; +import * as ScheduleWeek from "~/features/availability/core/ScheduleWeek"; +import * as VisibleSchedules from "~/features/availability/core/VisibleSchedules.server"; import { allEntries as allChangelogEntries } from "~/features/changelog/core/entries.server"; import * as FriendRepository from "~/features/friends/FriendRepository.server"; import * as ShowcaseTournaments from "~/features/front-page/core/ShowcaseTournaments.server"; @@ -28,6 +31,7 @@ import { parseLutiDiv, serializeLutiDiv } from "~/features/scrims/scrims-utils"; import * as ReportedWeaponRepository from "~/features/sendouq-match/ReportedWeaponRepository.server"; import * as SQMatchRepository from "~/features/sendouq-match/SQMatchRepository.server"; import * as SplatoonRotationRepository from "~/features/splatoon-rotations/SplatoonRotationRepository.server"; +import { getViewerTimezone } from "~/features/timezone/timezone-context.server"; import { eventLeaderboards } from "~/features/tournament-organization/core/leaderboards.server"; import type { BuildAbilitiesTuple, @@ -87,6 +91,7 @@ import * as FeedRotations from "./FeedRotations"; import * as FeedSchedule from "./FeedSchedule"; import * as FeedScrimMatch from "./FeedScrimMatch"; import * as FeedSeasonGoal from "./FeedSeasonGoal"; +import * as FeedWeaponTrends from "./FeedWeaponTrends"; const HOUR = 3600; const DAY = 24 * HOUR; @@ -144,6 +149,8 @@ export interface FeedContext { /** Users sharing a current team with the viewer who aren't their friends */ teammateIds: number[]; teammateIdSet: Set; + /** Weapons of the viewer's weapon pool, see `RankableItem.weaponSplIds` */ + weaponPool: MainWeaponId[]; /** Database timestamp everything is relative to */ now: number; season: number | null; @@ -166,6 +173,8 @@ interface BuiltItem { relation?: FeedRelation | null; /** See `RankableItem.weight` */ weight?: number; + /** See `RankableItem.weaponSplIds` */ + weaponSplIds?: MainWeaponId[]; data: D; } @@ -256,6 +265,7 @@ export type FeedItem = { actorKey: string; relation: FeedRelation | null; weight: number; + weaponSplIds: MainWeaponId[]; data: FeedItemData; }; }[FeedItemType]; @@ -271,6 +281,7 @@ export async function contextFor({ const friendIds = await FriendRepository.findFriendIds(viewerId); const friendIdSet = new Set(friendIds); const teammateIds = await teammateIdsOf({ viewerId, friendIdSet }); + const weaponPool = await FeedRepository.findWeaponPoolByUserId(viewerId); const now = mode === "TEST" ? await testNow() : databaseTimestampNow(); const nowDate = databaseTimestampToDate(now); @@ -281,6 +292,7 @@ export async function contextFor({ friendIdSet, teammateIds, teammateIdSet: new Set(teammateIds), + weaponPool: weaponPool.map((weapon) => weapon.weaponSplId), now, season: Seasons.currentOrPrevious(nowDate)?.nth ?? null, previousSeason: Seasons.previous(nowDate)?.nth ?? null, @@ -316,6 +328,7 @@ async function buildItemsOfType( at: Math.min(item.at, ctx.now), relation: item.relation ?? null, weight: item.weight ?? 1, + weaponSplIds: item.weaponSplIds ?? [], } as FeedItem; }, ); @@ -859,48 +872,36 @@ async function buildSqMeta(ctx: SharedFeedContext) { weekday: FeedSchedule.WEEKDAY.MONDAY, }), ); - const thisWeek = await FeedRepository.findWeaponUsageCounts({ + const thisWeek = await FeedRepository.findWeaponPicksByUser({ from: publishedAt - 7 * DAY, to: publishedAt, }); - const lastWeek = await FeedRepository.findWeaponUsageCounts({ + const lastWeek = await FeedRepository.findWeaponPicksByUser({ from: publishedAt - 14 * DAY, to: publishedAt - 7 * DAY, }); - const totalThisWeek = R.sumBy(thisWeek, (row) => row.count); - const totalLastWeek = R.sumBy(lastWeek, (row) => row.count); - if (totalThisWeek < 100 || totalLastWeek < 100) return null; - const changes = R.sortBy( - thisWeek - .filter((row) => row.count >= totalThisWeek / 50) - .map((row) => { - const share = row.count / totalThisWeek; - const previousCount = - lastWeek.find((previous) => previous.weaponSplId === row.weaponSplId) - ?.count ?? 0; - const previousShare = previousCount / totalLastWeek; + const ordinals = new Map(); + for (const season of [ctx.previousSeason, ctx.season]) { + if (season === null) continue; + for (const [userId, skill] of Object.entries( + (await userSkills(season)).userSkills, + )) { + ordinals.set(Number(userId), skill.ordinal); + } + } - return { - weaponSplId: row.weaponSplId, - sharePercentage: Math.round(share * 1000) / 10, - changePercentage: previousShare - ? Math.round((share / previousShare - 1) * 100) - : 100, - }; - }), - [(change) => change.changePercentage, "desc"], - ); - if (changes.length < 5) return null; + const trends = FeedWeaponTrends.risersAndFallers({ + thisWeek, + lastWeek, + ordinals, + }); + if (!trends) return null; return { at: publishedAt, actorKey: "SQ_META", - data: { - rising: changes.slice(0, 3), - falling: changes.slice(-2).reverse(), - reportCount: totalThisWeek, - }, + data: trends, }; } @@ -1232,15 +1233,13 @@ async function buildTournamentUpset(ctx: FeedContext) { | (TournamentUpset & { tournamentId: number; userId: number; - isUserWinner: boolean; }) | null = null; for (const tournamentId of R.unique( results.map((result) => result.tournamentId), )) { for (const upset of await tournamentUpsets(tournamentId)) { - const winnerUserId = userIdByTeamId.get(upset.winnerId); - const userId = winnerUserId ?? userIdByTeamId.get(upset.loserId); + const userId = userIdByTeamId.get(upset.winnerId); if (userId === undefined) continue; if ( best && @@ -1253,7 +1252,6 @@ async function buildTournamentUpset(ctx: FeedContext) { ...upset, tournamentId, userId, - isUserWinner: winnerUserId !== undefined, }; } } @@ -1270,7 +1268,6 @@ async function buildTournamentUpset(ctx: FeedContext) { data: { tournament, actor: users.get(best.userId)!, - isActorWinner: best.isUserWinner, winner: teams.get(best.winnerId)!, loser: teams.get(best.loserId)!, winnerSeed: best.winnerSeed, @@ -2150,39 +2147,56 @@ async function buildTeamAvailability(ctx: FeedContext) { : undefined); if (!week) return null; - const slots = await FeedRepository.findAvailabilitySlotsOfTeamWeek({ - teamId: week.teamId, - weekStartsAt: week.weekStartsAt, + const [team] = await FeedRepository.findTeamsByIds([week.teamId]); + const timezone = getViewerTimezone() ?? "UTC"; + // midweek so a week started in another timezone still lands on the same viewer week + const range = Availability.weekRange( + databaseTimestampToDate(week.weekStartsAt + 3.5 * DAY), + timezone, + ); + const memberIds = team.members.map((member) => member.id); + const { reportedWeeks, busyByUserId } = await VisibleSchedules.findByUserIds({ + userIds: memberIds, + viewerId: ctx.viewerId, + bypassVisibility: ctx.mode === "TEST", + ...range, + }); + const { members, minPlayers, windows } = ScheduleWeek.teamWindows({ + range, + playerIds: memberIds, + reportedWeeks, + busyByUserId, }); - const freeUsersByHour = new Map>(); - for (const slot of slots) { - for (let hour = slot.startsAt; hour < slot.endsAt; hour += HOUR) { - const users = freeUsersByHour.get(hour) ?? new Set(); - users.add(slot.userId); - freeUsersByHour.set(hour, users); - } - } const best = R.firstBy( - [...freeUsersByHour.entries()], - [([, users]) => users.size, "desc"], - [([hour]) => hour, "asc"], + windows, + [(window) => window.userIds.length, "desc"], + [(window) => window.startsAt, "asc"], ); if (!best) return null; - let bestEndsAt = best[0] + HOUR; - while (freeUsersByHour.get(bestEndsAt)?.size === best[1].size) - bestEndsAt += HOUR; + const segments = Availability.availabilitySegments(members); + const weekDays = ScheduleWeek.days(range, timezone); + const dayStarts = weekDays.map((day) => + Availability.localToTimestamp({ date: day.date, time: "00:00", timezone }), + ); + const days = weekDays.map((day, dayIndex) => { + const startsAt = dayStarts[dayIndex]; + const endsAt = dayStarts[dayIndex + 1] ?? range.endsAt; - const [team] = await FeedRepository.findTeamsByIds([week.teamId]); - const days = R.range(0, 7).map((dayIndex) => { - const dayStartsAt = week.weekStartsAt + dayIndex * DAY; return { - startsAt: dayStartsAt, + startsAt, + tier: ScheduleWeek.bestWindowTierOfDay({ + date: day.date, + windows, + timezone, + }), maxFree: Math.max( 0, - ...R.range(0, 24).map( - (hour) => freeUsersByHour.get(dayStartsAt + hour * HOUR)?.size ?? 0, - ), + ...segments + .filter( + (segment) => segment.startsAt < endsAt && segment.endsAt > startsAt, + ) + .map((segment) => segment.userIds.length), ), }; }); @@ -2192,10 +2206,11 @@ async function buildTeamAvailability(ctx: FeedContext) { actorKey: `team-${week.teamId}`, data: { team, - freeCount: best[1].size, - bestStartsAt: best[0], - bestEndsAt, - freeUsers: team.members.filter((member) => best[1].has(member.id)), + freeCount: best.userIds.length, + freeUsers: team.members.filter((member) => + best.userIds.includes(member.id), + ), + minPlayers, days, }, }; @@ -2712,6 +2727,7 @@ async function buildBuildNew(ctx: FeedContext) { at: card.at, actorKey: String(card.ownerId), relation: relationOf(ctx, card.ownerId), + weaponSplIds: card.card.build.weapons.map((weapon) => weapon.weaponSplId), data: card.card, }; }); @@ -2754,16 +2770,23 @@ async function buildVodNew(ctx: SharedFeedContext) { video.matches.flatMap((match) => match.players), (player) => player.playerUserId ?? player.playerName, ).slice(0, 4); - const users = await usersById( - players.flatMap((player) => + const users = await usersById([ + video.submitterUserId, + ...players.flatMap((player) => player.playerUserId ? [player.playerUserId] : [], ), - ); + ]); return { at: video.youtubePublishedAt, actorKey: `video-${video.id}`, + weaponSplIds: R.unique( + video.matches.flatMap((match) => + match.players.map((player) => player.weaponSplId as MainWeaponId), + ), + ), data: { + submitter: users.get(video.submitterUserId)!, videoId: video.id, title: video.title, type: video.type, diff --git a/app/features/feed/core/FeedPage.server.ts b/app/features/feed/core/FeedPage.server.ts index 649d74920..54981558d 100644 --- a/app/features/feed/core/FeedPage.server.ts +++ b/app/features/feed/core/FeedPage.server.ts @@ -18,11 +18,14 @@ export async function load({ viewerId, userId, mode, + isScoreShown, }: { viewerId: number; /** The logged in user, differs from `viewerId` when a dev views someone else's feed */ userId: number; mode: FeedItems.FeedMode; + /** Whether each post's ranking score breakdown is included */ + isScoreShown: boolean; }) { const ctx = await FeedItems.contextFor({ viewerId, mode }); const items = (await FeedItems.buildAll(ctx)).filter( @@ -50,7 +53,8 @@ export async function load({ activity: FeedRanking.rank( items.filter((item) => !definitionOf(item).isPinned), ctx.now, - ), + ctx.weaponPool, + ).map((item) => ({ ...item, score: isScoreShown ? item.score : null })), rotations: await FeedItems.allRotations(), rotationsNow: databaseTimestampNow(), interactions: Object.fromEntries( diff --git a/app/features/feed/core/FeedRanking.test.ts b/app/features/feed/core/FeedRanking.test.ts index 3dcf906a1..597fa8d69 100644 --- a/app/features/feed/core/FeedRanking.test.ts +++ b/app/features/feed/core/FeedRanking.test.ts @@ -1,5 +1,8 @@ import { describe, expect, test } from "vitest"; -import { FEED_AUDIENCE_AFFINITY } from "../feed-constants"; +import { + FEED_AUDIENCE_AFFINITY, + FEED_WEAPON_AFFINITY, +} from "../feed-constants"; import * as FeedRanking from "./FeedRanking"; const NOW = 1_800_000_000; @@ -52,9 +55,9 @@ describe("FeedRanking.score", () => { test.each([ { - why: "no relation: the closest audience of the type", + why: "no relation: the widest audience of the type", relation: null, - expected: FEED_AUDIENCE_AFFINITY.FOLLOWING, + expected: FEED_AUDIENCE_AFFINITY.EVERYONE, }, { why: "self", relation: "SELF", expected: FEED_AUDIENCE_AFFINITY.SELF }, { @@ -77,6 +80,101 @@ describe("FeedRanking.score", () => { }); }); +describe("FeedRanking.score", () => { + const SPLATTERSHOT = 40; + const TENTATEK_SPLATTERSHOT = 41; + const HERO_SHOT_REPLICA = 45; + const SPLASH_O_MATIC = 20; + const SPLAT_CHARGER = 2010; + + test.each([ + { + why: "same weapon", + weaponSplIds: [SPLATTERSHOT], + expected: FEED_WEAPON_AFFINITY.SAME_WEAPON, + }, + { + why: "kit of the same base weapon", + weaponSplIds: [TENTATEK_SPLATTERSHOT], + expected: FEED_WEAPON_AFFINITY.SAME_WEAPON, + }, + { + why: "skin of the same base weapon", + weaponSplIds: [HERO_SHOT_REPLICA], + expected: FEED_WEAPON_AFFINITY.SAME_WEAPON, + }, + { + why: "same weapon among others", + weaponSplIds: [SPLASH_O_MATIC, SPLAT_CHARGER, SPLATTERSHOT], + expected: FEED_WEAPON_AFFINITY.SAME_WEAPON, + }, + { + why: "same category", + weaponSplIds: [SPLASH_O_MATIC], + expected: FEED_WEAPON_AFFINITY.SAME_CATEGORY, + }, + { + why: "other category", + weaponSplIds: [SPLAT_CHARGER], + expected: FEED_WEAPON_AFFINITY.NONE, + }, + { + why: "no weapons", + weaponSplIds: [], + expected: FEED_WEAPON_AFFINITY.NONE, + }, + ] as const)("$why", ({ weaponSplIds, expected }) => { + const result = FeedRanking.score( + { + type: "VOD_NEW", + at: NOW, + relation: null, + weaponSplIds: [...weaponSplIds], + }, + NOW, + [TENTATEK_SPLATTERSHOT], + ); + + expect(result.weaponAffinity).toBe(expected); + }); + + test("is none without a weapon pool", () => { + const result = FeedRanking.score( + { + type: "VOD_NEW", + at: NOW, + relation: null, + weaponSplIds: [SPLATTERSHOT], + }, + NOW, + ); + + expect(result.weaponAffinity).toBe(FEED_WEAPON_AFFINITY.NONE); + }); + + test("scales the score by the weapon affinity", () => { + const plain = FeedRanking.score( + { type: "BUILD_NEW", at: NOW, relation: null }, + NOW, + [SPLATTERSHOT], + ); + const matching = FeedRanking.score( + { + type: "BUILD_NEW", + at: NOW, + relation: null, + weaponSplIds: [SPLATTERSHOT], + }, + NOW, + [SPLATTERSHOT], + ); + + expect(matching.total).toBeCloseTo( + plain.total * FEED_WEAPON_AFFINITY.SAME_WEAPON, + ); + }); +}); + describe("FeedRanking.rank", () => { test("orders by score", () => { const ranked = FeedRanking.rank( diff --git a/app/features/feed/core/FeedRanking.ts b/app/features/feed/core/FeedRanking.ts index 48260104c..66ecb0ede 100644 --- a/app/features/feed/core/FeedRanking.ts +++ b/app/features/feed/core/FeedRanking.ts @@ -1,3 +1,8 @@ +import type { MainWeaponId } from "~/modules/in-game-lists/types"; +import { + weaponIdToBaseWeaponId, + weaponIdToCategory, +} from "~/modules/in-game-lists/weapon-ids"; import { FEED_AUDIENCE_AFFINITY, FEED_ITEM_TYPES, @@ -6,6 +11,7 @@ import { FEED_SAME_ACTOR_PENALTY, FEED_SAME_CATEGORY_PENALTY, FEED_SAME_TYPE_REPEAT_PENALTY, + FEED_WEAPON_AFFINITY, type FeedItemType, type FeedItemTypeDefinition, type FeedRelation, @@ -21,12 +27,15 @@ export interface RankableItem { relation: FeedRelation | null; /** How strong the item is among those of its type, 0–1, 1 when left out */ weight?: number; + /** Weapons the item is about, matched against the viewer's weapon pool */ + weaponSplIds?: MainWeaponId[]; } export interface ScoreBreakdown { base: number; weight: number; affinity: number; + weaponAffinity: number; recency: number; ageHours: number; diversity: number; @@ -35,17 +44,21 @@ export interface ScoreBreakdown { /** * Score of an item before the diversity pass: base score of its type × the item's weight × affinity × - * exponential recency decay by the type's half-life. Affinity is that of the item's relation, or without - * one the closest audience of its type. + * weapon affinity × exponential recency decay by the type's half-life. Affinity is that of the item's + * relation, or without one the widest audience of its type. */ export function score( - item: Pick, + item: Pick< + RankableItem, + "type" | "at" | "relation" | "weight" | "weaponSplIds" + >, now: number, + weaponPool: MainWeaponId[] = [], ): Omit { const definition: FeedItemTypeDefinition = FEED_ITEM_TYPES[item.type]; const affinity = item.relation ? FEED_AUDIENCE_AFFINITY[FEED_RELATION_AUDIENCE[item.relation]] - : Math.max( + : Math.min( ...definition.audience.map( (audience) => FEED_AUDIENCE_AFFINITY[audience], ), @@ -53,14 +66,16 @@ export function score( const ageHours = Math.max(0, (now - item.at) / 3600); const recency = 0.5 ** (ageHours / definition.halfLifeHours); const weight = item.weight ?? 1; + const weaponAffinity = weaponAffinityOf(item.weaponSplIds ?? [], weaponPool); return { base: definition.baseScore, weight, affinity, + weaponAffinity, recency, ageHours, - total: definition.baseScore * weight * affinity * recency, + total: definition.baseScore * weight * affinity * weaponAffinity * recency, }; } @@ -82,8 +97,12 @@ export function isStale(item: Pick, now: number) { export function rank( items: T[], now: number, + weaponPool: MainWeaponId[] = [], ): Array { - const pool = items.map((item) => ({ item, ...score(item, now) })); + const pool = items.map((item) => ({ + item, + ...score(item, now, weaponPool), + })); const result: Array = []; const pickedCountByType = new Map(); @@ -127,6 +146,7 @@ export function rank( base: best.base, weight: best.weight, affinity: best.affinity, + weaponAffinity: best.weaponAffinity, recency: best.recency, ageHours: best.ageHours, diversity: bestDiversity, @@ -137,3 +157,20 @@ export function rank( return result; } + +function weaponAffinityOf( + weaponSplIds: MainWeaponId[], + weaponPool: MainWeaponId[], +) { + const poolBaseIds = new Set(weaponPool.map(weaponIdToBaseWeaponId)); + if (weaponSplIds.some((id) => poolBaseIds.has(weaponIdToBaseWeaponId(id)))) { + return FEED_WEAPON_AFFINITY.SAME_WEAPON; + } + + const poolCategories = new Set(weaponPool.map(weaponIdToCategory)); + if (weaponSplIds.some((id) => poolCategories.has(weaponIdToCategory(id)))) { + return FEED_WEAPON_AFFINITY.SAME_CATEGORY; + } + + return FEED_WEAPON_AFFINITY.NONE; +} diff --git a/app/features/feed/core/FeedWeaponTrends.test.ts b/app/features/feed/core/FeedWeaponTrends.test.ts new file mode 100644 index 000000000..1d3a46e3d --- /dev/null +++ b/app/features/feed/core/FeedWeaponTrends.test.ts @@ -0,0 +1,118 @@ +import { describe, expect, test } from "vitest"; +import type { MainWeaponId } from "~/modules/in-game-lists/types"; +import * as FeedWeaponTrends from "./FeedWeaponTrends"; + +const PLAYER_COUNT = 100; + +describe("FeedWeaponTrends.risersAndFallers", () => { + test("returns null when a week has too few players", () => { + const week = players({ count: 10, weaponSplId: 0 }); + + expect( + FeedWeaponTrends.risersAndFallers({ + thisWeek: week, + lastWeek: week, + ordinals: new Map(), + }), + ).toBeNull(); + }); + + test("counts each player once no matter how many maps they played", () => { + const lastWeek = players({ count: PLAYER_COUNT, weaponSplId: 0 }); + const thisWeek = players({ count: PLAYER_COUNT, weaponSplId: 0 }); + thisWeek[0] = { userId: 0, weaponSplId: 10, count: 1000 }; + thisWeek[1] = { userId: 1, weaponSplId: 10, count: 1 }; + thisWeek[2] = { userId: 2, weaponSplId: 10, count: 1 }; + + expect( + FeedWeaponTrends.risersAndFallers({ + thisWeek, + lastWeek, + ordinals: new Map(), + })?.rising, + ).toEqual([ + { weaponSplId: 10, sharePercentage: 3, changePercentage: null }, + ]); + }); + + test("weighs higher ranked players more", () => { + const lastWeek = players({ count: PLAYER_COUNT, weaponSplId: 0 }); + const thisWeek = players({ count: PLAYER_COUNT, weaponSplId: 0 }); + for (const userId of [0, 1, 2, 3, 4]) { + thisWeek[userId] = { userId, weaponSplId: 10, count: 1 }; + } + const ordinals = new Map( + Array.from({ length: PLAYER_COUNT }, (_, userId) => [userId, userId]), + ); + const reversedOrdinals = new Map( + Array.from({ length: PLAYER_COUNT }, (_, userId) => [userId, -userId]), + ); + + const highRankedShare = FeedWeaponTrends.risersAndFallers({ + thisWeek, + lastWeek, + ordinals: reversedOrdinals, + })?.rising[0].sharePercentage; + const lowRankedShare = FeedWeaponTrends.risersAndFallers({ + thisWeek, + lastWeek, + ordinals, + })?.rising[0].sharePercentage; + + expect(highRankedShare).toBeGreaterThan(lowRankedShare!); + }); + + test("finds a weapon that fell below the minimum share", () => { + const lastWeek = [ + ...players({ count: 90, weaponSplId: 0 }), + ...players({ count: 10, weaponSplId: 10, firstUserId: 90 }), + ]; + const thisWeek = [ + ...players({ count: 90, weaponSplId: 20 }), + ...players({ count: 10, weaponSplId: 0, firstUserId: 90 }), + ]; + + expect( + FeedWeaponTrends.risersAndFallers({ + thisWeek, + lastWeek, + ordinals: new Map(), + })?.falling.map((trend) => trend.weaponSplId), + ).toEqual([10, 0]); + }); + + test("leaves out moves smaller than a percentage point", () => { + const lastWeek = [ + ...players({ count: 196, weaponSplId: 0 }), + ...players({ count: 4, weaponSplId: 10, firstUserId: 196 }), + ]; + const thisWeek = [ + ...players({ count: 195, weaponSplId: 0 }), + ...players({ count: 5, weaponSplId: 10, firstUserId: 195 }), + ]; + + expect( + FeedWeaponTrends.risersAndFallers({ + thisWeek, + lastWeek, + ordinals: new Map(), + }), + ).toBeNull(); + }); +}); + +function players({ + count, + weaponSplId, + firstUserId = 0, +}: { + count: number; + weaponSplId: MainWeaponId; + firstUserId?: number; +}): FeedWeaponTrends.WeaponPicks[] { + return Array.from({ length: count }, (_, index) => ({ + userId: firstUserId + index, + weaponSplId, + count: 3, + })); +} diff --git a/app/features/feed/core/FeedWeaponTrends.ts b/app/features/feed/core/FeedWeaponTrends.ts new file mode 100644 index 000000000..6391fc76a --- /dev/null +++ b/app/features/feed/core/FeedWeaponTrends.ts @@ -0,0 +1,140 @@ +import * as R from "remeda"; +import type { MainWeaponId } from "~/modules/in-game-lists/types"; + +/** How much the week's highest ranked player counts compared to its lowest ranked one */ +const TOP_PLAYER_WEIGHT = 3; +const MIN_PLAYERS = 50; +/** Weapons below this share in both weeks are left out */ +const MIN_SHARE = 0.02; +/** Smaller week-to-week moves are treated as noise */ +const MIN_SHARE_CHANGE = 0.01; +const RISING_COUNT = 3; +const FALLING_COUNT = 2; + +export interface WeaponPicks { + userId: number; + weaponSplId: MainWeaponId; + count: number; +} + +interface WeaponTrend { + weaponSplId: MainWeaponId; + sharePercentage: number; + /** `null` when the weapon wasn't played at all last week */ + changePercentage: number | null; +} + +/** + * Weapons whose share of play rose and fell the most from last week to this week. Every player's weapon mix + * counts once, weighted from 1 (lowest ranked or unranked) to `TOP_PLAYER_WEIGHT` (highest ranked) by their + * ordinal among the week's players. `null` when either week has too few players or there is no clear riser and faller. + */ +export function risersAndFallers({ + thisWeek, + lastWeek, + ordinals, +}: { + thisWeek: WeaponPicks[]; + lastWeek: WeaponPicks[]; + /** Skill ordinal by user id */ + ordinals: Map; +}) { + const playerCount = R.unique(thisWeek.map((picks) => picks.userId)).length; + const previousPlayerCount = R.unique( + lastWeek.map((picks) => picks.userId), + ).length; + if (playerCount < MIN_PLAYERS || previousPlayerCount < MIN_PLAYERS) { + return null; + } + + const shares = weightedShares(thisWeek, ordinals); + const previousShares = weightedShares(lastWeek, ordinals); + + const trends = R.unique([...shares.keys(), ...previousShares.keys()]) + .map((weaponSplId) => ({ + weaponSplId, + share: shares.get(weaponSplId) ?? 0, + previousShare: previousShares.get(weaponSplId) ?? 0, + })) + .filter( + ({ share, previousShare }) => + Math.max(share, previousShare) >= MIN_SHARE && + Math.abs(share - previousShare) >= MIN_SHARE_CHANGE, + ); + + const rising = R.sortBy( + trends.filter(({ share, previousShare }) => share > previousShare), + [ + ({ share, previousShare }) => + previousShare === 0 ? Number.POSITIVE_INFINITY : share / previousShare, + "desc", + ], + ).slice(0, RISING_COUNT); + const falling = R.sortBy( + trends.filter(({ share, previousShare }) => share < previousShare), + ({ share, previousShare }) => share / previousShare, + ).slice(0, FALLING_COUNT); + if (rising.length === 0 || falling.length === 0) return null; + + return { + rising: rising.map(toWeaponTrend), + falling: falling.map(toWeaponTrend), + playerCount, + }; +} + +function weightedShares(picks: WeaponPicks[], ordinals: Map) { + const picksByUserId = Map.groupBy(picks, (pick) => pick.userId); + const weights = rankWeights([...picksByUserId.keys()], ordinals); + const totalWeight = R.sum([...weights.values()]); + + const result = new Map(); + for (const [userId, userPicks] of picksByUserId) { + const userPickCount = R.sumBy(userPicks, (pick) => pick.count); + const userShare = weights.get(userId)! / totalWeight; + + for (const pick of userPicks) { + result.set( + pick.weaponSplId, + (result.get(pick.weaponSplId) ?? 0) + + (userShare * pick.count) / userPickCount, + ); + } + } + + return result; +} + +function rankWeights(userIds: number[], ordinals: Map) { + const rankedLowestFirst = R.sortBy( + userIds.filter((userId) => ordinals.has(userId)), + (userId) => ordinals.get(userId)!, + ); + const lastIndex = Math.max(rankedLowestFirst.length - 1, 1); + + const result = new Map(userIds.map((userId) => [userId, 1])); + for (const [index, userId] of rankedLowestFirst.entries()) { + result.set(userId, 1 + ((TOP_PLAYER_WEIGHT - 1) * index) / lastIndex); + } + + return result; +} + +function toWeaponTrend({ + weaponSplId, + share, + previousShare, +}: { + weaponSplId: MainWeaponId; + share: number; + previousShare: number; +}): WeaponTrend { + return { + weaponSplId, + sharePercentage: Math.round(share * 1000) / 10, + changePercentage: + previousShare === 0 + ? null + : Math.round((share / previousShare - 1) * 100), + }; +} diff --git a/app/features/feed/feed-constants.ts b/app/features/feed/feed-constants.ts index 9c293af3a..4c237ab77 100644 --- a/app/features/feed/feed-constants.ts +++ b/app/features/feed/feed-constants.ts @@ -214,6 +214,7 @@ export const FEED_ITEM_TYPES = { audience: ["SELF"], baseScore: 0.35, halfLifeHours: 96, + isNotice: true, }, TO_VOD: { name: "Tournament VoD", @@ -323,6 +324,7 @@ export const FEED_ITEM_TYPES = { audience: ["TEAM"], baseScore: 0.6, halfLifeHours: 48, + isNotice: true, }, TEAM_EVENT_ADDED: { name: "Team event added", @@ -404,6 +406,7 @@ export const FEED_ITEM_TYPES = { audience: ["FOLLOWING", "EVERYONE"], baseScore: 0.35, halfLifeHours: 72, + isNotice: true, }, XRANK_TOP_500: { name: "X Rank Top 500", @@ -434,6 +437,7 @@ export const FEED_ITEM_TYPES = { audience: ["SELF"], baseScore: 0.4, halfLifeHours: 168, + isNotice: true, }, COMEBACK: { @@ -467,6 +471,7 @@ export const FEED_ITEM_TYPES = { audience: ["SELF"], baseScore: 0.4, halfLifeHours: 48, + isNotice: true, }, ARTICLE_NEW: { name: "New article", @@ -564,6 +569,15 @@ export const FEED_SAME_ACTOR_PENALTY = 0.6; /** Diversity pass: penalty for each item of the same type already picked */ export const FEED_SAME_TYPE_REPEAT_PENALTY = 0.75; +/** Bonus for an item about a weapon the viewer plays, the `weaponAffinity` term of the ranking score */ +export const FEED_WEAPON_AFFINITY = { + /** Same base weapon as one in the viewer's weapon pool */ + SAME_WEAPON: 2, + /** Same category as a weapon in the viewer's weapon pool */ + SAME_CATEGORY: 1.3, + NONE: 1, +} as const; + /** Weeks of match history used to find the hours a user usually plays */ export const FEED_ROTATION_LOOKBACK_WEEKS = 8; /** An hour of the week is a usual play hour once it has matches on this many different weeks */ diff --git a/app/features/feed/feed-sources-constants.ts b/app/features/feed/feed-sources-constants.ts index 313796d3b..9f526b740 100644 --- a/app/features/feed/feed-sources-constants.ts +++ b/app/features/feed/feed-sources-constants.ts @@ -193,10 +193,10 @@ export const FEED_SOURCE_FEATURES: FeedSourceFeature[] = [ }, { item: "TO_UPSET", - when: "A friend's team is in an upset: it beats a team seeded at least 5 places higher, or a team seeded at least 5 places lower beats it. The post says which friend, so it's clear why it's in your feed.", + when: "A friend's team pulls off an upset: it beats a team seeded at least 5 places higher. Only wins, never a friend's team being upset. The post says which friend, so it's clear why it's in your feed.", example: { actor: "Callie", - text: "**Callie**'s team, seeded 10, knocked out seed 1 at **In The Zone 55**", + text: "**Callie**'s team (seed 10) upset seed 1 at **In The Zone 55**", }, }, { @@ -479,7 +479,7 @@ export const FEED_SOURCE_FEATURES: FeedSourceFeature[] = [ when: "Enough of your team has filled in availability for the week to find a shared window.", example: { actor: "Kraken", - text: "**4 of 5** on Kraken Kids are free together · Fri 21:00", + text: "**4 of 5** on Kraken Kids are free together · **3 days** with 4+", }, }, { diff --git a/app/features/front-page/loaders/index.server.ts b/app/features/front-page/loaders/index.server.ts index f272f8407..4cb41e1e9 100644 --- a/app/features/front-page/loaders/index.server.ts +++ b/app/features/front-page/loaders/index.server.ts @@ -33,6 +33,8 @@ export const loader = async ({ request }: LoaderFunctionArgs) => { viewerId: viewAs ?? user.id, userId: user.id, mode: test ? "TEST" : "REAL", + isScoreShown: + user.roles.includes("ADMIN") || user.roles.includes("DEV"), }), }; } diff --git a/app/features/front-page/routes/index.tsx b/app/features/front-page/routes/index.tsx index 56c446897..c09dded11 100644 --- a/app/features/front-page/routes/index.tsx +++ b/app/features/front-page/routes/index.tsx @@ -73,33 +73,22 @@ export default function FrontPage() { function FeedFrontPage({ data }: { data: FeedPageData }) { const [test, setTest] = useSearchParam(feedSearchParams, "test"); - const [showRankingMath, setShowRankingMath] = React.useState(false); return (
    - - setTest(isSelected, { preventScrollReset: true }) - } - size="small" - > - Test items - - - Show ranking math - -
    + + setTest(isSelected, { preventScrollReset: true }) + } + size="small" + > + Test items + } footer={ test ? ( diff --git a/app/features/splatoon-rotations/splatoon-rotations-constants.ts b/app/features/splatoon-rotations/splatoon-rotations-constants.ts index a22c1cd03..677792ed0 100644 --- a/app/features/splatoon-rotations/splatoon-rotations-constants.ts +++ b/app/features/splatoon-rotations/splatoon-rotations-constants.ts @@ -1,3 +1,3 @@ -export const SPLATOON_ROTATION_TYPES = ["SERIES", "OPEN", "X"] as const; +export const SPLATOON_ROTATION_TYPES = ["X", "SERIES", "OPEN"] as const; export type SplatoonRotationType = (typeof SPLATOON_ROTATION_TYPES)[number]; diff --git a/scripts/benchmark-db/cases.ts b/scripts/benchmark-db/cases.ts index 48f288a66..3a692f585 100644 --- a/scripts/benchmark-db/cases.ts +++ b/scripts/benchmark-db/cases.ts @@ -555,8 +555,8 @@ export function buildCases(fx: Fixtures): { fx.topTeammatesUserId, (userId) => FeedRepository.findTopTeammatesByUserId(userId), ); - add("FeedRepository.findWeaponUsageCounts", fx.feedNow, (now) => - FeedRepository.findWeaponUsageCounts({ from: now - 7 * DAY, to: now }), + add("FeedRepository.findWeaponPicksByUser", fx.feedNow, (now) => + FeedRepository.findWeaponPicksByUser({ from: now - 7 * DAY, to: now }), ); add("FeedRepository.findAllLobbiesEndedAfter", fx.feedNow, (now) => FeedRepository.findAllLobbiesEndedAfter( @@ -771,11 +771,6 @@ export function buildCases(fx: Fixtures): { teamIds, }), ); - add( - "FeedRepository.findAvailabilitySlotsOfTeamWeek", - fx.heavyTeamAvailabilityWeek, - (week) => FeedRepository.findAvailabilitySlotsOfTeamWeek(week), - ); add( "FeedRepository.findOpenScrimPostsForViewer", both(fx.heavyTeam, fx.feedNow), diff --git a/scripts/benchmark-db/fixtures.ts b/scripts/benchmark-db/fixtures.ts index b7448cf73..8796d29de 100644 --- a/scripts/benchmark-db/fixtures.ts +++ b/scripts/benchmark-db/fixtures.ts @@ -169,8 +169,6 @@ export interface Fixtures { manyTeamIds: number[] | null; /** Leaderboard series of the organization with the most events. */ heavySeries: { organizationId: number; substringMatches: string[] } | null; - /** Team week with the most availability slots filled. */ - heavyTeamAvailabilityWeek: { teamId: number; weekStartsAt: number } | null; scannedMatchId: number | null; siteTotalCounts: Record | null; /** Posts with the most comments, the heaviest first. Null until users have commented. */ @@ -275,7 +273,6 @@ export async function resolveFixtures(): Promise { await resolveFeedIndexerTournamentResultRowId(feedNow), manyTeamIds: await resolveManyTeamIds(), heavySeries: await resolveHeavySeries(), - heavyTeamAvailabilityWeek: await resolveHeavyTeamAvailabilityWeek(), scannedMatchId: await resolveScannedMatchId(), siteTotalCounts: await resolveSiteTotalCounts(), feedCommentItemIds: await resolveFeedCommentItemIds(), @@ -1757,34 +1754,6 @@ async function resolveHeavySeries() { }; } -async function resolveHeavyTeamAvailabilityWeek() { - const row = await db - .selectFrom("AvailabilitySlot") - .innerJoin( - "AvailabilityWeek", - "AvailabilityWeek.id", - "AvailabilitySlot.availabilityWeekId", - ) - .innerJoin( - "AllTeamMember", - "AllTeamMember.userId", - "AvailabilityWeek.userId", - ) - .select(({ fn }) => [ - "AllTeamMember.teamId", - "AvailabilityWeek.weekStartsAt", - fn.countAll().as("count"), - ]) - .where("AllTeamMember.leftAt", "is", null) - .groupBy(["AllTeamMember.teamId", "AvailabilityWeek.weekStartsAt"]) - .orderBy("count", "desc") - .limit(1) - .executeTakeFirst(); - if (!row) return null; - - return { teamId: row.teamId, weekStartsAt: row.weekStartsAt }; -} - async function resolveScannedMatchId() { const row = await db .selectFrom("IngestedMatch")