Unify /subs and /looking

This commit is contained in:
Kalle
2026-03-02 19:55:24 +02:00
parent 1dcfa7c802
commit 9d5dacaa0e
22 changed files with 510 additions and 1015 deletions

View File

@@ -11,6 +11,8 @@ import {
import { errorIsSqliteForeignKeyConstraintFailure } from "~/utils/sql";
import { randomTeamName } from "~/utils/team-name";
// xxx: handle visibility like scrim post
export function startLooking(teamId: number) {
return db
.updateTable("TournamentTeam")
@@ -23,6 +25,7 @@ type CreatePlaceholderTeamArgs = {
tournamentId: number;
userId: number;
isStayAsSub?: boolean;
lfgNote?: string;
};
export function createPlaceholderTeam(args: CreatePlaceholderTeamArgs) {
return db.transaction().execute(async (trx) => {
@@ -34,6 +37,7 @@ export function createPlaceholderTeam(args: CreatePlaceholderTeamArgs) {
inviteCode: shortNanoid(),
isPlaceholder: 1,
isLooking: 1,
lfgNote: args.lfgNote ?? null,
})
.returning("id")
.executeTakeFirstOrThrow();
@@ -62,6 +66,7 @@ type TournamentLFGMemberObject = {
languages: Tables["User"]["languages"];
vc: Tables["User"]["vc"];
pronouns: Tables["User"]["pronouns"];
country: Tables["User"]["country"];
role: Tables["TournamentTeamMember"]["role"];
isStayAsSub: Tables["TournamentTeamMember"]["isStayAsSub"];
weapons: Tables["User"]["qWeaponPool"];
@@ -104,6 +109,8 @@ export async function findLookingTeamsByTournamentId(tournamentId: number) {
languages: eb.ref("User.languages"),
vc: eb.ref("User.vc"),
pronouns: eb.ref("User.pronouns"),
// xxx: is it better to show country rather than languages?
country: eb.ref("User.country"),
role: eb.ref("TournamentTeamMember.role"),
isStayAsSub: eb.ref("TournamentTeamMember.isStayAsSub"),
weapons: eb.ref("User.qWeaponPool"),
@@ -120,6 +127,52 @@ export async function findLookingTeamsByTournamentId(tournamentId: number) {
.execute();
}
export async function findSubGroups(tournamentId: number) {
const rows = await db
.selectFrom("TournamentTeam")
.innerJoin(
"TournamentTeamMember",
"TournamentTeamMember.tournamentTeamId",
"TournamentTeam.id",
)
.innerJoin("User", "User.id", "TournamentTeamMember.userId")
.leftJoin("PlusTier", "PlusTier.userId", "User.id")
.select(({ fn, eb }) => [
"TournamentTeam.id",
"TournamentTeam.lfgNote as message",
fn
.agg("json_group_array", [
jsonBuildObject({
id: eb.ref("User.id"),
username: eb.ref("User.username"),
discordId: eb.ref("User.discordId"),
discordAvatar: eb.ref("User.discordAvatar"),
customUrl: eb.ref("User.customUrl"),
languages: eb.ref("User.languages"),
vc: eb.ref("User.vc"),
pronouns: eb.ref("User.pronouns"),
country: eb.ref("User.country"),
role: eb.ref("TournamentTeamMember.role"),
isStayAsSub: eb.ref("TournamentTeamMember.isStayAsSub"),
weapons: eb.ref("User.qWeaponPool"),
chatNameColor: userChatNameColorForJson,
plusTier: eb.ref("PlusTier.tier"),
}),
])
.$castTo<TournamentLFGMemberObject[]>()
.as("members"),
])
// xxx: is this correct?
.where("TournamentTeam.tournamentId", "=", tournamentId)
.where("TournamentTeam.isPlaceholder", "=", 1)
.where("TournamentTeamMember.isStayAsSub", "=", 1)
.groupBy("TournamentTeam.id")
.having(({ fn }) => fn.countAll<number>(), "=", 1)
.execute();
return rows;
}
// xxx: ensure that the team size does not exceed the max, also filter out in frontend
export function mergeTeams({
survivingTeamId,

View File

@@ -13,6 +13,9 @@ import { lookingSchema } from "../tournament-lfg-schemas.server";
import { survivingTeamId } from "../tournament-lfg-utils";
// xxx: prevent actions in certain cases? like when tournament has started
// xxx: add `requireNotBannedByOrganization` & other checks from deleted to.$id.subs.new.tsx route
// xxx: add `clearTournamentDataCache`
export const action = async ({ request, params }: ActionFunctionArgs) => {
const user = requireUser();
const { id: tournamentId } = parseParams({ params, schema: idObject });
@@ -199,6 +202,52 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
break;
}
case "ADD_SUB": {
const tournament = await tournamentFromDBCached({
tournamentId,
user,
});
errorToastIfFalsy(
tournament.canAddNewSubPost,
"Cannot add sub post at this time",
);
const team = tournament.teamMemberOfByUser(user);
errorToastIfFalsy(!team, "Already on a team");
const existingSubGroups =
await TournamentLFGRepository.findSubGroups(tournamentId);
const hasExistingSubPost = existingSubGroups.some((g) =>
g.members.some((m) => m.id === user.id),
);
errorToastIfFalsy(!hasExistingSubPost, "Already have a sub post");
await TournamentLFGRepository.createPlaceholderTeam({
tournamentId,
userId: user.id,
isStayAsSub: true,
lfgNote: data.message,
});
break;
}
case "DELETE_SUB": {
const tournament = await tournamentFromDBCached({
tournamentId,
user,
});
errorToastIfFalsy(
user.id === data.userId || tournament.isOrganizer(user),
"You can only delete your own sub post",
);
await TournamentLFGRepository.leaveLfg({
userId: data.userId,
tournamentId,
});
break;
}
default: {
assertUnreachable(data);
}

View File

@@ -3,15 +3,42 @@ import type { Pronouns } from "~/db/tables";
import { getUser } from "~/features/auth/core/user.server";
import { tournamentFromDBCached } from "~/features/tournament-bracket/core/Tournament.server";
import type { MainWeaponId } from "~/modules/in-game-lists/types";
import type { SerializeFrom } from "~/utils/remix";
import { parseParams } from "~/utils/remix.server";
import { idObject } from "~/utils/zod";
import type { LFGGroup, LFGGroupMember } from "../components/LFGGroupCard";
import * as TournamentLFGRepository from "../TournamentLFGRepository.server";
export type SubEntry = Extract<
LookingLoaderData,
{ mode: "subs" }
>["subs"][number];
export type LookingLoaderData = SerializeFrom<typeof loader>;
export const loader = async ({ params }: LoaderFunctionArgs) => {
const user = getUser();
const { id: tournamentId } = parseParams({ params, schema: idObject });
const tournament = await tournamentFromDBCached({
tournamentId,
user,
});
if (tournament.registrationOpen) {
return lookingMode({ tournamentId, user });
}
return subsMode({ tournamentId, user });
};
async function lookingMode({
tournamentId,
user,
}: {
tournamentId: number;
user: ReturnType<typeof getUser>;
}) {
const rawGroups =
await TournamentLFGRepository.findLookingTeamsByTournamentId(tournamentId);
@@ -45,14 +72,56 @@ export const loader = async ({ params }: LoaderFunctionArgs) => {
});
return {
mode: "looking" as const,
groups: otherGroups,
ownGroup,
ownTeam,
likes,
lastUpdated: Date.now(),
tournamentId,
};
};
}
async function subsMode({
tournamentId,
user,
}: {
tournamentId: number;
user: ReturnType<typeof getUser>;
}) {
const rawSubGroups =
await TournamentLFGRepository.findSubGroups(tournamentId);
const subs = rawSubGroups.map((group) => {
const member = group.members[0];
const weapons = parseWeapons(member.weapons);
const languages =
typeof member.languages === "string"
? member.languages.split(",").filter(Boolean)
: [];
return {
teamId: group.id,
userId: member.id,
username: member.username,
discordId: member.discordId,
discordAvatar: member.discordAvatar,
customUrl: member.customUrl,
vc: member.vc,
languages,
plusTier: member.plusTier,
weapons,
message: group.message ?? null,
};
});
return {
mode: "subs" as const,
subs,
hasOwnSubPost: subs.some((sub) => sub.userId === user?.id),
tournamentId,
};
}
async function resolveOwnTeam({
user,

View File

@@ -34,3 +34,110 @@
margin: 5px;
border-radius: var(--rounded);
}
.subsContainer {
max-width: 52rem;
display: flex;
flex-direction: column;
gap: var(--s-8);
margin-inline: auto;
}
.subsTextarea {
width: 100%;
resize: vertical;
}
.subsSection {
display: grid;
grid-template-columns: max-content 1fr;
grid-template-areas:
"avatar name"
"avatar info"
"spacer spacer"
"weapon-top-text weapon-top-images"
"message message";
border-radius: var(--rounded);
background-color: var(--bg-lighter);
padding: var(--s-4);
column-gap: var(--s-2-5);
border: var(--border-style);
}
.subsSectionAvatar {
grid-area: avatar;
align-self: center;
}
.subsSectionName {
grid-area: name;
align-self: flex-end;
}
.subsSectionInfo {
grid-area: info;
font-size: var(--fonts-sm);
gap: var(--s-2);
color: var(--text-lighter);
display: flex;
height: 32px;
white-space: nowrap;
align-items: center;
}
.subsInfoVc {
display: flex;
align-items: center;
gap: var(--s-0-5);
}
.subsInfoVc > svg {
width: 18px;
}
.subsSectionMessage {
grid-area: message;
font-size: var(--fonts-sm);
padding-block-start: var(--s-4);
white-space: pre-wrap;
}
.subsSectionWeaponText {
font-weight: var(--semi-bold);
font-size: var(--fonts-xs);
align-self: center;
}
.subsSectionWeaponTopText {
grid-area: weapon-top-text;
}
.subsSectionWeaponImages {
display: flex;
gap: var(--s-1);
width: 11rem;
align-items: center;
}
.subsSectionWeaponTopImages {
grid-area: weapon-top-images;
}
.subsSectionSpacer {
grid-area: spacer;
height: 18px;
}
@media screen and (min-width: 640px) {
.subsSection {
grid-template-columns: max-content 1fr max-content max-content;
grid-template-areas:
"avatar name weapon-top-text weapon-top-images"
"avatar info . ."
"message message message message";
}
.subsSectionSpacer {
display: none;
}
}

View File

@@ -1,8 +1,9 @@
import clsx from "clsx";
import type * as React from "react";
import * as React from "react";
import { Flipper } from "react-flip-toolkit";
import { useTranslation } from "react-i18next";
import { useFetcher, useLoaderData } from "react-router";
import { Link, useFetcher, useLoaderData } from "react-router";
import { Avatar } from "~/components/Avatar";
import { SendouButton } from "~/components/elements/Button";
import {
SendouTab,
@@ -11,25 +12,34 @@ import {
SendouTabs,
} from "~/components/elements/Tabs";
import { FormWithConfirm } from "~/components/FormWithConfirm";
import { WeaponImage } from "~/components/Image";
import { MicrophoneIcon } from "~/components/icons/Microphone";
import { TrashIcon } from "~/components/icons/Trash";
import { Placeholder } from "~/components/Placeholder";
import { SubmitButton } from "~/components/SubmitButton";
import { useUser } from "~/features/auth/core/user";
import { useTournament } from "~/features/tournament/routes/to.$id";
import { SendouForm } from "~/form/SendouForm";
import { useAutoRefresh } from "~/hooks/useAutoRefresh";
import { useIsMounted } from "~/hooks/useIsMounted";
import { useWindowSize } from "~/hooks/useWindowSize";
import type { SendouRouteHandle } from "~/utils/remix.server";
import { userPage } from "~/utils/urls";
import { LFGGroupCard } from "../components/LFGGroupCard";
import type { loader } from "../loaders/to.$id.looking.server";
import {
type LookingLoaderData,
loader,
type SubEntry,
} from "../loaders/to.$id.looking.server";
import { TOURNAMENT_LFG } from "../tournament-lfg-constants";
import { joinQueueFormSchema } from "../tournament-lfg-schemas";
export { action } from "../actions/to.$id.looking.server";
export { loader } from "../loaders/to.$id.looking.server";
export { loader };
import styles from "./to.$id.looking.module.css";
export const handle: SendouRouteHandle = {
i18n: ["q", "tournament", "forms"],
i18n: ["q", "tournament", "forms", "common"],
};
export default function TournamentLFGShell() {
@@ -45,14 +55,19 @@ export default function TournamentLFGShell() {
// xxx: can we reuse the column layout with sendouq?
function TournamentLFGPage() {
const data = useLoaderData<typeof loader>();
useAutoRefresh(data.lastUpdated);
if (data.mode === "subs") {
return <SubsView data={data} />;
}
return <Groups />;
return <GroupsView data={data} />;
}
function Groups() {
function GroupsView({
data,
}: {
data: Extract<LookingLoaderData, { mode: "looking" }>;
}) {
const { t } = useTranslation(["q"]);
const data = useLoaderData<typeof loader>();
const tournament = useTournament();
const { width } = useWindowSize();
@@ -215,6 +230,178 @@ function Groups() {
);
}
function SubsView({
data,
}: {
data: Extract<LookingLoaderData, { mode: "subs" }>;
}) {
const user = useUser();
const tournament = useTournament();
const isOnTeam = Boolean(tournament.teamMemberOfByUser(user));
return (
<div className={styles.subsContainer}>
{tournament.canAddNewSubPost &&
!data.hasOwnSubPost &&
user &&
!isOnTeam ? (
<AddSubForm />
) : null}
{data.subs.map((sub) => (
<SubCard key={sub.userId} sub={sub} />
))}
</div>
);
}
// xxx: use SendouForm
function AddSubForm() {
const { t } = useTranslation(["tournament", "common"]);
const fetcher = useFetcher();
const [showForm, setShowForm] = React.useState(false);
if (!showForm) {
return (
<div className="stack items-end">
<SendouButton size="small" onPress={() => setShowForm(true)}>
{t("tournament:subs.addPost")}
</SendouButton>
</div>
);
}
return (
<fetcher.Form method="post" className="stack sm">
<textarea
name="message"
maxLength={TOURNAMENT_LFG.PUBLIC_NOTE_MAX_LENGTH}
placeholder={t("tournament:subs.message.header")}
className={styles.subsTextarea}
rows={3}
/>
<div className="stack horizontal sm justify-end">
<SendouButton
size="small"
variant="minimal"
onPress={() => setShowForm(false)}
>
{t("common:actions.cancel")}
</SendouButton>
<SubmitButton _action="ADD_SUB" state={fetcher.state} size="small">
{t("common:actions.save")}
</SubmitButton>
</div>
</fetcher.Form>
);
}
function SubCard({ sub }: { sub: SubEntry }) {
const { t } = useTranslation(["common", "tournament"]);
const user = useUser();
const tournament = useTournament();
const infos = [
<div key="vc" className={styles.subsInfoVc}>
<MicrophoneIcon
className={
sub.vc === "YES"
? "text-success"
: sub.vc === "LISTEN_ONLY"
? "text-warning"
: "text-error"
}
/>
{sub.vc === "YES"
? t("tournament:subs.canVC")
: sub.vc === "LISTEN_ONLY"
? t("tournament:subs.listenOnlyVC")
: t("tournament:subs.noVC")}
</div>,
];
if (sub.plusTier) {
infos.push(
<React.Fragment key="dot-1">{"\u00B7"}</React.Fragment>,
<div key="plus">+{sub.plusTier}</div>,
);
}
if (sub.languages.length > 0) {
infos.push(
<React.Fragment key="dot-2">{"\u00B7"}</React.Fragment>,
<div key="languages">
{sub.languages.map((lang) => lang.toUpperCase()).join(" / ")}
</div>,
);
}
return (
<div>
<section className={styles.subsSection}>
<Avatar user={sub} size="sm" className={styles.subsSectionAvatar} />
<Link to={userPage(sub)} className={styles.subsSectionName}>
{sub.username}
</Link>
<div className={styles.subsSectionSpacer} />
<div className={styles.subsSectionInfo}>{infos}</div>
{sub.weapons ? (
<>
<div
className={clsx(
styles.subsSectionWeaponTopText,
styles.subsSectionWeaponText,
)}
>
{t("tournament:subs.prefersToPlay")}
</div>
<div
className={clsx(
styles.subsSectionWeaponTopImages,
styles.subsSectionWeaponImages,
)}
>
{sub.weapons.map((wpn) => (
<WeaponImage
key={wpn.weaponSplId}
weaponSplId={wpn.weaponSplId}
size={32}
variant="badge"
/>
))}
</div>
</>
) : null}
{sub.message ? (
<div className={styles.subsSectionMessage}>{sub.message}</div>
) : null}
</section>
{user?.id === sub.userId || tournament.isOrganizer(user) ? (
<div className="stack mt-1 items-end">
<FormWithConfirm
dialogHeading={
user?.id === sub.userId
? "Delete your sub post?"
: `Delete sub post by ${sub.username}?`
}
fields={[
["_action", "DELETE_SUB"],
["userId", sub.userId],
]}
>
<SendouButton
variant="minimal-destructive"
size="small"
type="submit"
icon={<TrashIcon />}
>
{t("common:actions.delete")}
</SendouButton>
</FormWithConfirm>
</div>
) : null}
</div>
);
}
function ColumnHeader({ children }: { children: React.ReactNode }) {
const { width } = useWindowSize();
@@ -240,7 +427,10 @@ function JoinQueueForm() {
function TeamQueueSection() {
const { t } = useTranslation(["q"]);
const data = useLoaderData<typeof loader>();
const data = useLoaderData<typeof loader>() as Extract<
LookingLoaderData,
{ mode: "looking" }
>;
const tournament = useTournament();
const fetcher = useFetcher();

View File

@@ -40,4 +40,12 @@ export const lookingSchema = z.union([
z.object({
_action: _action("LEAVE_GROUP"),
}),
z.object({
_action: _action("ADD_SUB"),
message: z.string().max(TOURNAMENT_LFG.PUBLIC_NOTE_MAX_LENGTH).optional(),
}),
z.object({
_action: _action("DELETE_SUB"),
userId: id,
}),
]);

View File

@@ -1,164 +0,0 @@
import { sql } from "kysely";
import { db } from "~/db/sql";
import type { TablesInsertable } from "~/db/tables";
import type { MainWeaponId } from "~/modules/in-game-lists/types";
export async function findSubsVisibleToUser({
tournamentId,
userId,
}: {
tournamentId: number;
userId?: number;
}) {
const userPlusTier = await getUserPlusTier(userId);
const rows = await baseQuery(tournamentId)
.where((eb) =>
eb.or([
eb("TournamentSub.visibility", "=", "ALL"),
eb.and([
eb("TournamentSub.visibility", "=", "+1"),
eb(sql`${userPlusTier}`, "=", 1),
]),
eb.and([
eb("TournamentSub.visibility", "=", "+2"),
eb(sql`${userPlusTier}`, "<=", 2),
]),
eb.and([
eb("TournamentSub.visibility", "=", "+3"),
eb(sql`${userPlusTier}`, "<=", 3),
]),
]),
)
.orderBy((eb) =>
eb
.case()
.when("TournamentSub.userId", "=", userId ?? null)
.then(0)
.else(1)
.end(),
)
.orderBy((eb) =>
eb
.case()
.when(eb("PlusTier.tier", "is", null))
.then(4)
.else(eb.ref("PlusTier.tier"))
.end(),
)
.orderBy("TournamentSub.createdAt", "desc")
.execute();
return mapRows(rows);
}
export async function findUserSubPost({
tournamentId,
userId,
}: {
tournamentId: number;
userId: number;
}) {
const row = await baseQuery(tournamentId)
.where("TournamentSub.userId", "=", userId)
.executeTakeFirst();
if (!row) return null;
return mapRows([row])[0];
}
export function upsert(
args: Omit<TablesInsertable["TournamentSub"], "bestWeapons" | "okWeapons"> & {
bestWeapons: MainWeaponId[];
okWeapons: MainWeaponId[];
},
) {
return db.transaction().execute(async (trx) => {
const bestWeaponsStr = args.bestWeapons.join(",");
const okWeaponsStr =
args.okWeapons.length > 0 ? args.okWeapons.join(",") : null;
await trx
.insertInto("TournamentSub")
.values({
userId: args.userId,
tournamentId: args.tournamentId,
canVc: args.canVc,
bestWeapons: bestWeaponsStr,
okWeapons: okWeaponsStr,
message: args.message,
visibility: args.visibility,
})
.onConflict((oc) =>
oc.columns(["userId", "tournamentId"]).doUpdateSet({
canVc: args.canVc,
bestWeapons: bestWeaponsStr,
okWeapons: okWeaponsStr,
message: args.message,
visibility: args.visibility,
}),
)
.execute();
await trx
.updateTable("User")
.set({ lastSubMessage: args.message })
.where("id", "=", args.userId)
.execute();
});
}
async function getUserPlusTier(userId?: number) {
if (!userId) return 4;
const row = await db
.selectFrom("PlusTier")
.select("tier")
.where("userId", "=", userId)
.executeTakeFirst();
return row?.tier ?? 4;
}
function baseQuery(tournamentId: number) {
return db
.selectFrom("TournamentSub")
.innerJoin("User", "User.id", "TournamentSub.userId")
.leftJoin("PlusTier", "PlusTier.userId", "User.id")
.select([
"TournamentSub.canVc",
"TournamentSub.bestWeapons",
"TournamentSub.okWeapons",
"TournamentSub.message",
"TournamentSub.visibility",
"TournamentSub.createdAt",
"TournamentSub.userId",
"User.username",
"User.discordAvatar",
"User.country",
"User.discordId",
"User.customUrl",
"PlusTier.tier as plusTier",
])
.where("TournamentSub.tournamentId", "=", tournamentId);
}
function mapRows<
T extends {
bestWeapons: string;
okWeapons: string | null;
},
>(rows: T[]) {
return rows.map((row) => ({
...row,
bestWeapons: parseWeaponsArray(row.bestWeapons)!,
okWeapons: parseWeaponsArray(row.okWeapons),
}));
}
function parseWeaponsArray(value: string | null) {
if (!value) return null;
return value.split(",").map(Number) as MainWeaponId[];
}

View File

@@ -1,54 +0,0 @@
import { type ActionFunction, redirect } from "react-router";
import { requireUser } from "~/features/auth/core/user.server";
import { requireNotBannedByOrganization } from "~/features/tournament/tournament-utils.server";
import {
clearTournamentDataCache,
tournamentFromDB,
} from "~/features/tournament-bracket/core/Tournament.server";
import {
errorToastIfFalsy,
parseParams,
parseRequestPayload,
} from "~/utils/remix.server";
import { tournamentSubsPage } from "~/utils/urls";
import { idObject } from "~/utils/zod";
import * as TournamentSubRepository from "../TournamentSubRepository.server";
import { subSchema } from "../tournament-subs-schemas.server";
export const action: ActionFunction = async ({ params, request }) => {
const user = requireUser();
const data = await parseRequestPayload({
request,
schema: subSchema,
});
const { id: tournamentId } = parseParams({
params,
schema: idObject,
});
const tournament = await tournamentFromDB({ tournamentId, user });
await requireNotBannedByOrganization({ tournament, user });
errorToastIfFalsy(!tournament.everyBracketOver, "Tournament is over");
errorToastIfFalsy(
tournament.canAddNewSubPost,
"Registration is closed or subs feature disabled",
);
errorToastIfFalsy(
!tournament.teamMemberOfByUser(user),
"Can't register as a sub and be in a team at the same time",
);
await TournamentSubRepository.upsert({
bestWeapons: data.bestWeapons,
okWeapons: data.okWeapons,
canVc: data.canVc,
visibility: data.visibility,
message: data.message ?? null,
tournamentId,
userId: user.id,
});
clearTournamentDataCache(tournamentId);
throw redirect(tournamentSubsPage(tournamentId));
};

View File

@@ -1,41 +0,0 @@
import type { ActionFunction } from "react-router";
import { requireUser } from "~/features/auth/core/user.server";
import {
clearTournamentDataCache,
tournamentFromDB,
} from "~/features/tournament-bracket/core/Tournament.server";
import {
errorToastIfFalsy,
parseParams,
parseRequestPayload,
} from "~/utils/remix.server";
import { idObject } from "~/utils/zod";
import { deleteSub } from "../queries/deleteSub.server";
import { deleteSubSchema } from "../tournament-subs-schemas.server";
export const action: ActionFunction = async ({ request, params }) => {
const user = requireUser();
const { id: tournamentId } = parseParams({
params,
schema: idObject,
});
const tournament = await tournamentFromDB({ tournamentId, user });
const data = await parseRequestPayload({
request,
schema: deleteSubSchema,
});
errorToastIfFalsy(
user.id === data.userId || tournament.isOrganizer(user),
"You can only delete your own sub post",
);
deleteSub({
tournamentId,
userId: data.userId,
});
clearTournamentDataCache(tournamentId);
return null;
};

View File

@@ -1,29 +0,0 @@
import { type LoaderFunctionArgs, redirect } from "react-router";
import { requireUser } from "~/features/auth/core/user.server";
import { tournamentFromDB } from "~/features/tournament-bracket/core/Tournament.server";
import * as UserRepository from "~/features/user-page/UserRepository.server";
import { parseParams } from "~/utils/remix.server";
import { tournamentSubsPage } from "~/utils/urls";
import { idObject } from "~/utils/zod";
import * as TournamentSubRepository from "../TournamentSubRepository.server";
export const loader = async ({ params }: LoaderFunctionArgs) => {
const user = requireUser();
const { id: tournamentId } = parseParams({
params,
schema: idObject,
});
const tournament = await tournamentFromDB({ tournamentId, user });
if (!tournament.canAddNewSubPost) {
throw redirect(tournamentSubsPage(tournamentId));
}
return {
sub: await TournamentSubRepository.findUserSubPost({
tournamentId,
userId: user.id,
}),
userDefaults: await UserRepository.findSubDefaultsByUserId(user.id),
};
};

View File

@@ -1,30 +1,13 @@
import { type LoaderFunctionArgs, redirect } from "react-router";
import { getUser } from "~/features/auth/core/user.server";
import { tournamentFromDB } from "~/features/tournament-bracket/core/Tournament.server";
import { parseParams } from "~/utils/remix.server";
import { tournamentRegisterPage } from "~/utils/urls";
import { tournamentSubsPage } from "~/utils/urls";
import { idObject } from "~/utils/zod";
import * as TournamentSubRepository from "../TournamentSubRepository.server";
export const loader = async ({ params }: LoaderFunctionArgs) => {
const user = getUser();
const { id: tournamentId } = parseParams({
params,
schema: idObject,
});
const tournament = await tournamentFromDB({ tournamentId, user });
if (!tournament.subsFeatureEnabled) {
throw redirect(tournamentRegisterPage(tournamentId));
}
const subs = await TournamentSubRepository.findSubsVisibleToUser({
tournamentId,
userId: user?.id,
});
return {
subs,
hasOwnSubPost: subs.some((sub) => sub.userId === user?.id),
};
throw redirect(tournamentSubsPage(tournamentId));
};

View File

@@ -1,109 +0,0 @@
.listPageContainer {
max-width: 52rem;
display: flex;
flex-direction: column;
gap: var(--s-8);
margin-inline: auto;
}
.section {
display: grid;
grid-template-columns: max-content 1fr;
grid-template-areas:
"avatar name"
"avatar info"
"spacer spacer"
"weapon-top-text weapon-top-images"
"weapon-bottom-text weapon-bottom-images"
"message message";
border-radius: var(--rounded);
background-color: var(--bg-lighter);
padding: var(--s-4);
column-gap: var(--s-2-5);
}
.sectionAvatar {
grid-area: avatar;
align-self: center;
}
.sectionName {
grid-area: name;
align-self: flex-end;
}
.sectionInfo {
grid-area: info;
font-size: var(--fonts-sm);
gap: var(--s-2);
color: var(--text-lighter);
display: flex;
height: 32px;
white-space: nowrap;
align-items: center;
}
.sectionInfoVc {
display: flex;
align-items: center;
gap: var(--s-0-5);
}
.sectionInfoVc > svg {
width: 18px;
}
.sectionMessage {
grid-area: message;
font-size: var(--fonts-sm);
padding-block-start: var(--s-4);
white-space: pre-wrap;
}
.sectionWeaponText {
font-weight: var(--semi-bold);
font-size: var(--fonts-xs);
align-self: center;
}
.sectionWeaponTopText {
grid-area: weapon-top-text;
}
.sectionWeaponBottomText {
grid-area: weapon-bottom-text;
}
.sectionWeaponImages {
display: flex;
gap: var(--s-1);
width: 11rem;
align-items: center;
}
.sectionWeaponTopImages {
grid-area: weapon-top-images;
}
.sectionWeaponBottomImages {
grid-area: weapon-bottom-images;
}
.sectionSpacer {
grid-area: spacer;
height: 18px;
}
@media screen and (min-width: 640px) {
.section {
grid-template-columns: max-content 1fr max-content max-content;
grid-template-areas:
"avatar name weapon-top-text weapon-top-images"
"avatar info weapon-bottom-text weapon-bottom-images"
"message message message message";
}
.sectionSpacer {
display: none;
}
}

View File

@@ -1,9 +0,0 @@
.selectedWeapon {
padding: var(--s-2);
border-radius: 100%;
background-color: var(--bg-lighter);
}
.weaponPool {
width: 20rem;
}

View File

@@ -1,296 +0,0 @@
import React from "react";
import { useTranslation } from "react-i18next";
import { Form, Link, useLoaderData } from "react-router";
import { SendouButton } from "~/components/elements/Button";
import { FormMessage } from "~/components/FormMessage";
import { WeaponImage } from "~/components/Image";
import { TrashIcon } from "~/components/icons/Trash";
import { Label } from "~/components/Label";
import { RequiredHiddenInput } from "~/components/RequiredHiddenInput";
import { SubmitButton } from "~/components/SubmitButton";
import { WeaponSelect } from "~/components/WeaponSelect";
import { useUser } from "~/features/auth/core/user";
import type { MainWeaponId } from "~/modules/in-game-lists/types";
import type { SendouRouteHandle } from "~/utils/remix.server";
import { SENDOUQ_SETTINGS_PAGE } from "~/utils/urls";
import { action } from "../actions/to.$id.subs.new.server";
import { loader } from "../loaders/to.$id.subs.new.server";
import { TOURNAMENT_SUB } from "../tournament-subs-constants";
export { action, loader };
import clsx from "clsx";
import styles from "./to.$id.subs.new.module.css";
export const handle: SendouRouteHandle = {
i18n: ["user"],
};
export default function NewTournamentSubPage() {
const user = useUser();
const { t } = useTranslation(["common", "tournament"]);
const data = useLoaderData<typeof loader>();
const [bestWeapons, setBestWeapons] = React.useState<MainWeaponId[]>(
data.sub ? data.sub.bestWeapons : (data.userDefaults?.bestWeapons ?? []),
);
const [okWeapons, setOkWeapons] = React.useState<MainWeaponId[]>(
data.sub
? (data.sub.okWeapons ?? [])
: (data.userDefaults?.okWeapons ?? []),
);
return (
<div className="half-width">
<Form method="post" className="stack md items-start">
<div className="stack">
<h2>{t("tournament:subs.addPost")}</h2>
<FormMessage type="info">
{t("tournament:subs.defaultsNote")}{" "}
<Link to={SENDOUQ_SETTINGS_PAGE}>
{t("tournament:subs.defaultsPage")}
</Link>
</FormMessage>
</div>
<VCRadios />
<WeaponPoolSelect
label={t("tournament:subs.weapons.prefer.header")}
weapons={bestWeapons}
otherWeapons={okWeapons}
setWeapons={setBestWeapons}
id="bestWeapons"
infoText={t("tournament:subs.weapons.info", {
min: 1,
max: TOURNAMENT_SUB.WEAPON_POOL_MAX_SIZE,
})}
required
/>
<WeaponPoolSelect
label={t("tournament:subs.weapons.ok.header")}
weapons={okWeapons}
otherWeapons={bestWeapons}
setWeapons={setOkWeapons}
id="okWeapons"
infoText={t("tournament:subs.weapons.info", {
min: 0,
max: TOURNAMENT_SUB.WEAPON_POOL_MAX_SIZE,
})}
/>
<Message />
{user?.plusTier ? <VisibilityRadios /> : null}
<SubmitButton>{t("common:actions.save")}</SubmitButton>
</Form>
</div>
);
}
function VCRadios() {
const { t } = useTranslation(["common", "tournament"]);
const data = useLoaderData<typeof loader>();
const isDefaultChecked = (value: number) => {
if (data.sub) {
return data.sub.canVc === value;
}
const defaultCanVc = data.userDefaults?.canVc ?? 1;
return defaultCanVc === value;
};
return (
<div>
<Label required>{t("tournament:subs.vc.header")}</Label>
<div className="stack xs">
<div className="stack horizontal sm items-center">
<input
type="radio"
id="vc-true"
name="canVc"
value="1"
required
defaultChecked={isDefaultChecked(1)}
/>
<label htmlFor="vc-true" className="mb-0">
{t("common:yes")}
</label>
</div>
<div className="stack horizontal sm items-center">
<input
type="radio"
id="vc-false"
name="canVc"
value="0"
defaultChecked={isDefaultChecked(0)}
/>
<label htmlFor="vc-false" className="mb-0">
{t("common:no")}
</label>
</div>
<div className="stack horizontal sm items-center">
<input
type="radio"
id="vc-listen-only"
name="canVc"
value="2"
defaultChecked={isDefaultChecked(2)}
/>
<label htmlFor="vc-listen-only" className="mb-0">
{t("tournament:subs.listenOnlyVC")}
</label>
</div>
</div>
</div>
);
}
function Message() {
const { t } = useTranslation(["tournament"]);
const data = useLoaderData<typeof loader>();
const [value, setValue] = React.useState(
data.sub?.message ?? data.userDefaults?.message ?? "",
);
return (
<div className="u-edit__bio-container">
<Label
htmlFor="message"
valueLimits={{
current: value.length,
max: TOURNAMENT_SUB.MESSAGE_MAX_LENGTH,
}}
>
{t("tournament:subs.message.header")}
</Label>
<textarea
id="message"
name="message"
value={value}
onChange={(e) => setValue(e.target.value)}
maxLength={TOURNAMENT_SUB.MESSAGE_MAX_LENGTH}
/>
</div>
);
}
function VisibilityRadios() {
const { t } = useTranslation(["tournament"]);
const data = useLoaderData<typeof loader>();
const user = useUser();
const userPlusTier = user?.plusTier ?? 4;
return (
<div>
<Label required>{t("tournament:subs.visibility.header")}</Label>
<div className="stack xs">
{[1, 2, 3]
.filter((tier) => tier >= userPlusTier)
.map((tier) => {
const id = `+${tier}`;
return (
<div key={tier} className="stack horizontal sm items-center">
<input
type="radio"
id={id}
name="visibility"
value={id}
defaultChecked={data.sub?.visibility === id}
/>
<label htmlFor={id} className="mb-0">
+{tier} {tier !== 1 && "(and above)"}
</label>
</div>
);
})}
<div className="stack horizontal sm items-center">
<input
type="radio"
id="all"
name="visibility"
value="ALL"
required
defaultChecked={data.sub?.visibility === "ALL"}
/>
<label htmlFor="all" className="mb-0">
{t("tournament:subs.visibility.everyone")}
</label>
</div>
</div>
</div>
);
}
function WeaponPoolSelect({
weapons,
otherWeapons,
setWeapons,
label,
id,
infoText,
required = false,
}: {
weapons: Array<MainWeaponId>;
otherWeapons: Array<MainWeaponId>;
setWeapons: (weapons: Array<MainWeaponId>) => void;
label: string;
id: string;
infoText: string;
required?: boolean;
}) {
const { t } = useTranslation(["user"]);
return (
<div className={clsx("stack md", styles.weaponPool)}>
<RequiredHiddenInput
isValid={!required || weapons.length > 0}
name={id}
value={JSON.stringify(weapons)}
/>
{weapons.length < TOURNAMENT_SUB.WEAPON_POOL_MAX_SIZE ? (
<>
<WeaponSelect
label={label}
onChange={(weaponId) => {
setWeapons([...weapons, weaponId]);
}}
disabledWeaponIds={[...weapons, ...otherWeapons]}
// empty on selection
key={weapons[weapons.length - 1]}
/>
<FormMessage type="info">{infoText}</FormMessage>
</>
) : (
<span className="text-xs text-warning">
{t("user:forms.errors.maxWeapons")}
</span>
)}
{weapons.length > 0 ? (
<div className="stack horizontal sm justify-center">
{weapons.map((weapon) => {
return (
<div key={weapon} className="stack xs">
<div className={styles.selectedWeapon}>
<WeaponImage
weaponSplId={weapon}
variant="badge"
width={38}
height={38}
/>
</div>
<SendouButton
icon={<TrashIcon />}
variant="minimal-destructive"
aria-label="Delete weapon"
onPress={() =>
setWeapons(weapons.filter((w) => w !== weapon))
}
/>
</div>
);
})}
</div>
) : null}
</div>
);
}

View File

@@ -1,197 +1 @@
import clsx from "clsx";
import React from "react";
import { useTranslation } from "react-i18next";
import { Link, useLoaderData } from "react-router";
import { Avatar } from "~/components/Avatar";
import { LinkButton, SendouButton } from "~/components/elements/Button";
import { SendouPopover } from "~/components/elements/Popover";
import { Flag } from "~/components/Flag";
import { FormWithConfirm } from "~/components/FormWithConfirm";
import { WeaponImage } from "~/components/Image";
import { MicrophoneIcon } from "~/components/icons/Microphone";
import { TrashIcon } from "~/components/icons/Trash";
import { Redirect } from "~/components/Redirect";
import { useUser } from "~/features/auth/core/user";
import { useTournament } from "~/features/tournament/routes/to.$id";
import type { SerializeFrom } from "~/utils/remix";
import { tournamentRegisterPage, userPage } from "~/utils/urls";
import { action } from "../actions/to.$id.subs.server";
import { loader } from "../loaders/to.$id.subs.server";
export { action, loader };
import styles from "./to.$id.subs.module.css";
export default function TournamentSubsPage() {
const user = useUser();
const data = useLoaderData<typeof loader>();
const tournament = useTournament();
if (tournament.everyBracketOver) {
return <Redirect to={tournamentRegisterPage(tournament.ctx.id)} />;
}
return (
<div className={styles.listPageContainer}>
{!tournament.teamMemberOfByUser(user) && user ? (
<div className="stack items-end">
<AddOrEditSubButton />
</div>
) : null}
{data.subs.map((sub) => {
return <SubInfoSection key={sub.userId} sub={sub} />;
})}
</div>
);
}
function AddOrEditSubButton() {
const { t } = useTranslation(["tournament"]);
const data = useLoaderData<typeof loader>();
const tournament = useTournament();
const buttonText = data.hasOwnSubPost
? t("tournament:subs.editPost")
: t("tournament:subs.addPost");
if (!tournament.canAddNewSubPost) {
return (
<SendouPopover
trigger={<SendouButton size="small">{buttonText}</SendouButton>}
>
{data.hasOwnSubPost
? "Sub post can't be edited anymore since registration has closed"
: "Sub post can't be added anymore since registration has closed"}
</SendouPopover>
);
}
return (
<LinkButton to="new" size="small">
{buttonText}
</LinkButton>
);
}
function SubInfoSection({
sub,
}: {
sub: SerializeFrom<typeof loader>["subs"][number];
}) {
const { t } = useTranslation(["common", "tournament"]);
const user = useUser();
const tournament = useTournament();
const infos = [
<div key="vc" className={styles.sectionInfoVc}>
<MicrophoneIcon
className={
sub.canVc === 1
? "text-success"
: sub.canVc === 2
? "text-warning"
: "text-error"
}
/>
{sub.canVc === 1
? t("tournament:subs.canVC")
: sub.canVc === 2
? t("tournament:subs.listenOnlyVC")
: t("tournament:subs.noVC")}
</div>,
];
if (sub.plusTier) {
infos.push(<React.Fragment key="slash-1">/</React.Fragment>);
infos.push(<div key="plus">+{sub.plusTier}</div>);
}
if (sub.country) {
infos.push(<React.Fragment key="slash-2">/</React.Fragment>);
infos.push(<Flag key="flag" countryCode={sub.country} tiny />);
}
return (
<div>
<section className={styles.section}>
<Avatar user={sub} size="sm" className={styles.sectionAvatar} />
<Link to={userPage(sub)} className={styles.sectionName}>
{sub.username}
</Link>
<div className={styles.sectionSpacer} />
<div className={styles.sectionInfo}>{infos}</div>
<div
className={clsx(
styles.sectionWeaponTopText,
styles.sectionWeaponText,
)}
>
{t("tournament:subs.prefersToPlay")}
</div>
<div
className={clsx(
styles.sectionWeaponTopImages,
styles.sectionWeaponImages,
)}
>
{sub.bestWeapons.map((wpn) => (
<WeaponImage
key={wpn}
weaponSplId={wpn}
size={32}
variant="badge"
/>
))}
</div>
{sub.okWeapons ? (
<>
<div
className={clsx(
styles.sectionWeaponBottomText,
styles.sectionWeaponText,
)}
>
{t("tournament:subs.canPlay")}
</div>
<div
className={clsx(
styles.sectionWeaponBottomImages,
styles.sectionWeaponImages,
)}
>
{sub.okWeapons.map((wpn) => (
<WeaponImage
key={wpn}
weaponSplId={wpn}
size={32}
variant="badge"
/>
))}
</div>
</>
) : null}
{sub.message ? (
<div className={styles.sectionMessage}>{sub.message}</div>
) : null}
</section>
{user?.id === sub.userId || tournament.isOrganizer(user) ? (
<div className="stack mt-1 items-end">
<FormWithConfirm
dialogHeading={
user?.id === sub.userId
? "Delete your sub post?"
: `Delete sub post by ${sub.username}?`
}
fields={[["userId", sub.userId]]}
>
<SendouButton
variant="minimal-destructive"
size="small"
type="submit"
icon={<TrashIcon />}
>
{t("common:actions.delete")}
</SendouButton>
</FormWithConfirm>
</div>
) : null}
</div>
);
}
export { loader } from "../loaders/to.$id.subs.server";

View File

@@ -1,4 +0,0 @@
export const TOURNAMENT_SUB = {
WEAPON_POOL_MAX_SIZE: 5,
MESSAGE_MAX_LENGTH: 280,
};

View File

@@ -1,27 +0,0 @@
import { z } from "zod";
import {
id,
processMany,
removeDuplicates,
safeJSONParse,
weaponSplId,
} from "~/utils/zod";
import { TOURNAMENT_SUB } from "./tournament-subs-constants";
export const subSchema = z.object({
canVc: z.coerce.number().int().min(0).max(2),
bestWeapons: z.preprocess(
processMany(safeJSONParse, removeDuplicates),
z.array(weaponSplId).min(1).max(TOURNAMENT_SUB.WEAPON_POOL_MAX_SIZE),
),
okWeapons: z.preprocess(
processMany(safeJSONParse, removeDuplicates),
z.array(weaponSplId).max(TOURNAMENT_SUB.WEAPON_POOL_MAX_SIZE),
),
message: z.string().max(TOURNAMENT_SUB.MESSAGE_MAX_LENGTH).nullish(),
visibility: z.enum(["+1", "+2", "+3", "ALL"]).default("ALL"),
});
export const deleteSubSchema = z.object({
userId: id,
});

View File

@@ -122,13 +122,20 @@ export async function findById(id: number) {
).as("staff"),
jsonArrayFrom(
eb
.selectFrom("TournamentSub")
.selectFrom("TournamentTeamMember")
.innerJoin(
"TournamentTeam",
"TournamentTeam.id",
"TournamentTeamMember.tournamentTeamId",
)
.select(({ fn }) => [
"TournamentSub.visibility",
sql<string>`'ALL'`.as("visibility"),
fn.countAll<number>().as("count"),
])
.where("TournamentSub.tournamentId", "=", id)
.groupBy("TournamentSub.visibility"),
.where("TournamentTeam.tournamentId", "=", id)
// xxx: this is not correct
.where("TournamentTeam.isPlaceholder", "=", 1)
.where("TournamentTeamMember.isStayAsSub", "=", 1),
).as("subCounts"),
jsonArrayFrom(
eb

View File

@@ -197,17 +197,13 @@ export function TournamentLayout() {
>
{t("tournament:tabs.teams", { count: tournament.ctx.teams.length })}
</SubNavLink>
{!tournament.hasStarted && !tournament.isInvitational ? (
<SubNavLink to="looking">{t("tournament:tabs.looking")}</SubNavLink>
{!tournament.isInvitational && !tournament.everyBracketOver ? (
<SubNavLink to="looking">
{tournament.registrationOpen
? t("tournament:tabs.looking")
: t("tournament:tabs.subs", { count: subsCount() })}
</SubNavLink>
) : null}
{/** xxx: do we still have a separate subs tab or just reuse /looking? */}
{tournament.hasStarted &&
!tournament.everyBracketOver &&
tournament.subsFeatureEnabled && (
<SubNavLink to="subs" end={false}>
{t("tournament:tabs.subs", { count: subsCount() })}
</SubNavLink>
)}
{tournament.hasStarted && !tournament.everyBracketOver ? (
<SubNavLink to="streams">
{t("tournament:tabs.streams", {

View File

@@ -369,43 +369,6 @@ export function findByFriendCode(friendCode: string) {
.execute();
}
export async function findSubDefaultsByUserId(userId: number) {
const user = await db
.selectFrom("User")
.select(["User.vc", "User.qWeaponPool", "User.lastSubMessage"])
.where("User.id", "=", userId)
.executeTakeFirst();
if (!user) return null;
const vcToCanVc = (vc: "YES" | "NO" | "LISTEN_ONLY"): 0 | 1 | 2 => {
if (vc === "YES") return 1;
if (vc === "NO") return 0;
return 2;
};
const qWeaponPool = user.qWeaponPool ?? [];
let bestWeapons = qWeaponPool
.filter((w) => w.isFavorite === 1)
.map((w) => w.weaponSplId);
let okWeapons = qWeaponPool
.filter((w) => w.isFavorite === 0)
.map((w) => w.weaponSplId);
if (bestWeapons.length === 0) {
bestWeapons = okWeapons;
okWeapons = [];
}
return {
canVc: vcToCanVc(user.vc),
bestWeapons,
okWeapons,
message: user.lastSubMessage,
};
}
export async function findLeanById(id: number) {
const user = await db
.selectFrom("User")

View File

@@ -111,7 +111,6 @@ export default [
route("looking", "features/tournament-lfg/routes/to.$id.looking.tsx"),
route("subs", "features/tournament-subs/routes/to.$id.subs.tsx"),
route("subs/new", "features/tournament-subs/routes/to.$id.subs.new.tsx"),
route(
"divisions",

View File

@@ -356,7 +356,7 @@ export const tournamentJoinPage = ({
inviteCode: string;
}) => `/to/${tournamentId}/join?code=${inviteCode}`;
export const tournamentSubsPage = (tournamentId: number) => {
return `/to/${tournamentId}/subs`;
return `/to/${tournamentId}/looking`;
};
export const tournamentStreamsPage = (tournamentId: number) => {
return `/to/${tournamentId}/streams`;