From e9a9b06c0f6ff1948e7e792b2ccd86951bf36da2 Mon Sep 17 00:00:00 2001 From: Anthony Santiago Date: Mon, 16 Nov 2026 15:13:06 -0500 Subject: [PATCH 001/135] refactor(sports): one loader, one layout shape, shared helpers No change to what /sports renders. - lib/sportsPage.ts loads everything the page needs, replacing 190 lines in the shared [section] route. The three schools queries are now one. - lib/sportsLayout.ts defines the layout JSON once (it was copied in the editor, the route, /sports/all and a collection comment) and reads it through parseSportsLayout, so a malformed value falls back to its default instead of throwing. HEADLINE_COUNT was defined twice. - lib/troyTime.ts and lib/sidearm.ts replace repeated date formatters and fetch options. - SportsByline, SportsHeading and useScrollEdges replace copies in the page, the carousel, the standings card and the score strip. - Comments: phone scoreboards always use logos; field hockey's Sidearm code differs between RPI Athletics and the Liberty League. --- app/(frontend)/[section]/page.tsx | 246 +----------------- app/(frontend)/sports/all/page.tsx | 19 +- collections/SportsPageLayout.ts | 32 +-- .../Dashboard/SportsLayoutEditor/index.tsx | 71 ++--- components/Sports/SportsAllStories.tsx | 11 +- components/Sports/SportsByline.tsx | 43 +++ components/Sports/SportsFeatured.tsx | 48 +--- components/Sports/SportsHeading.tsx | 25 ++ components/Sports/SportsScoreStrip.tsx | 37 +-- components/Sports/SportsSectionPage.tsx | 49 +--- components/Sports/SportsStandings.tsx | 31 +-- components/Sports/sportsFormat.ts | 13 +- components/Sports/useScrollEdges.ts | 31 +++ lib/schedule.ts | 26 +- lib/sidearm.ts | 14 + lib/sportsLayout.ts | 123 +++++++++ lib/sportsPage.ts | 202 ++++++++++++++ lib/standings.ts | 10 +- lib/standingsSchedule.ts | 14 +- lib/troyTime.ts | 17 ++ scripts/seed-schools.ts | 3 +- 21 files changed, 553 insertions(+), 512 deletions(-) create mode 100644 components/Sports/SportsByline.tsx create mode 100644 components/Sports/SportsHeading.tsx create mode 100644 components/Sports/useScrollEdges.ts create mode 100644 lib/sidearm.ts create mode 100644 lib/sportsLayout.ts create mode 100644 lib/sportsPage.ts create mode 100644 lib/troyTime.ts diff --git a/app/(frontend)/[section]/page.tsx b/app/(frontend)/[section]/page.tsx index 049a5100..b98a7b36 100644 --- a/app/(frontend)/[section]/page.tsx +++ b/app/(frontend)/[section]/page.tsx @@ -7,15 +7,10 @@ import SectionPage from '@/components/SectionPage'; import OpinionSectionPage from '@/components/Opinion/OpinionSectionPage'; import NewsSectionPage from '@/components/News/NewsSectionPage'; import FeaturesSectionPage, { type FeaturesEvent, type SpotlightPhoto } from '@/components/Features/FeaturesSectionPage'; -import SportsSectionPage, { type ScoreboardDate } from '@/components/Sports/SportsSectionPage'; -import type { StandingsTeam } from '@/components/Sports/SportsStandings'; -import type { FeaturedFocus } from '@/components/Sports/sportsFormat'; -import { getSportsStandings, type SportStandings } from '@/lib/standings'; -import { getSportsSchedule, type SportSchedule } from '@/lib/schedule'; -import { STANDINGS_SPORTS, type StandingsOverride } from '@/lib/standingsSchedule'; -import { RPI_SCHOOL_NAME } from '@/collections/Schools'; +import SportsSectionPage from '@/components/Sports/SportsSectionPage'; +import { SPORTS_GAME_SELECT, loadSportsPage } from '@/lib/sportsPage'; import { Article as PayloadArticle, Media } from '@/payload-types'; -import { Article as ComponentArticle, GameTeam } from '@/components/FrontPage/types'; +import { Article as ComponentArticle } from '@/components/FrontPage/types'; import type { SpotlightAuthor } from '@/components/Opinion/AuthorSpotlightCarousel'; import { formatArticle } from '@/utils/formatArticle'; import { opinionGroups } from '@/components/Opinion/opinionGroups'; @@ -29,16 +24,6 @@ export const revalidate = 60; // recent stories but backfills to this many so no column comes up empty. const NEWS_LAYOUT_CAPACITY = 26; -// Sport + game-result fields sports stories carry (opponent populates at depth 1) -const SPORTS_GAME_SELECT = { - sport: true, - opponent: true, - homeAway: true, - rpiScore: true, - opponentScore: true, - gameStatus: true, -} as const; - type Args = { params: Promise<{ section: string; @@ -484,209 +469,8 @@ export default async function SectionPageRoute({ params }: Args) { } } - // Fetch sports page layout — lead (+ scoreboard), below-lead card, headlines, - // featured row - let sportsPinnedLead: ComponentArticle | null = null; - let sportsPinnedBelowLead: ComponentArticle | null = null; - let sportsPinnedBelowLead2: ComponentArticle | null = null; - let sportsPinnedHeadlines: (ComponentArticle | null)[] = []; - let sportsShowScoreboard = true; - let sportsScoreboardDate: ScoreboardDate | null = null; - let sportsRpiTeam: GameTeam | null = null; - let sportsStandings: SportStandings[] = []; - const sportsStandingsTeams: Record = {}; - let sportsSchedule: SportSchedule[] = []; - let sportsPinnedFeatured: (ComponentArticle | null)[] = []; - let sportsFeaturedFocus: FeaturedFocus = {}; - let sportsShowScoreStrip = true; - let sportsLeadTitleOverlay = true; - - if (section === 'sports') { - type SportsLayoutShape = { - lead?: number | null; - showScoreboard?: boolean; - scoreboardDate?: ScoreboardDate | null; - belowLead?: number | null; - belowLead2?: number | null; - headlines?: (number | null)[]; - featured?: (number | null)[]; - featuredFocus?: FeaturedFocus; - showScoreStrip?: boolean; - leadTitleOverlay?: boolean; - standingsOverrides?: StandingsOverride[]; - }; - let standingsOverrides: StandingsOverride[] | undefined; - - // RPI's own school record supplies its side of the scoreboard - try { - const rpiResponse = await payload.find({ - collection: 'schools', - where: { name: { equals: RPI_SCHOOL_NAME } }, - limit: 1, - depth: 0, - // url is derived from filename, so both are needed - select: { name: true, shortName: true, url: true, filename: true, athleticsUrl: true }, - }); - const rpi = rpiResponse.docs[0]; - if (rpi) { - sportsRpiTeam = { - name: rpi.name, - shortName: rpi.shortName || 'RPI', - logo: rpi.url || null, - url: rpi.athleticsUrl || null, - }; - } - } catch { - // Schools table may not exist yet - } - - try { - const layoutResponse = await payload.find({ - collection: 'sports-page-layout', - limit: 1, - depth: 0, - select: { layout: true }, - }); - const doc = layoutResponse.docs[0] as Record | undefined; - const layoutJson = doc?.layout as SportsLayoutShape | undefined; - - if (layoutJson) { - sportsShowScoreboard = layoutJson.showScoreboard ?? true; - sportsScoreboardDate = layoutJson.scoreboardDate ?? null; - sportsFeaturedFocus = layoutJson.featuredFocus ?? {}; - sportsShowScoreStrip = layoutJson.showScoreStrip ?? true; - sportsLeadTitleOverlay = layoutJson.leadTitleOverlay ?? true; - standingsOverrides = layoutJson.standingsOverrides; - - const allPinnedIds = new Set(); - for (const id of [ - layoutJson.lead, - layoutJson.belowLead, - layoutJson.belowLead2, - ...(layoutJson.headlines || []), - ...(layoutJson.featured || []), - ]) { - if (id) allPinnedIds.add(id); - } - - if (allPinnedIds.size > 0) { - const pinnedResponse = await payload.find({ - collection: 'articles', - where: { - and: [ - { id: { in: Array.from(allPinnedIds) } }, - { _status: { equals: 'published' } }, - ], - }, - limit: allPinnedIds.size, - depth: 1, - select: { - title: true, slug: true, subdeck: true, featuredImage: true, - section: true, kicker: true, publishedDate: true, createdAt: true, - authors: true, writeInAuthors: true, isFollytechnic: true, - ...SPORTS_GAME_SELECT, - }, - }); - const pinnedMap = new Map( - pinnedResponse.docs.map((a) => [a.id, formatArticle(a)]), - ); - - // Keeps slot positions: an unpublished pin leaves its slot to auto-fill - const resolve = (id: number | null | undefined): ComponentArticle | null => - (id ? pinnedMap.get(id) ?? null : null); - - sportsPinnedLead = resolve(layoutJson.lead); - sportsPinnedBelowLead = resolve(layoutJson.belowLead); - sportsPinnedBelowLead2 = resolve(layoutJson.belowLead2); - sportsPinnedFeatured = (layoutJson.featured || []).map(resolve); - sportsPinnedHeadlines = (layoutJson.headlines || []).map(resolve); - } - } - } catch { - // Table may not exist yet - } - - // Standings for the sports the calendar (and any editor override) picks. - // The score strip follows the standings' sports, but which ones those are - // is only known once the tables are in, so the schedule is fetched for - // every standings sport alongside them and narrowed afterwards; a slow - // feed then costs one wait instead of two in a row. When editors switch - // the strip off, RPI Athletics isn't contacted at all, and a failure - // falls back to the plain header rather than an error page. - const [standings, schedule] = await Promise.all([ - getSportsStandings({ overrides: standingsOverrides }), - sportsShowScoreStrip - ? getSportsSchedule(STANDINGS_SPORTS.map((s) => s.sport)).catch((err: Error) => { - console.warn(`[schedule] ${err.message}`); - return [] as SportSchedule[]; - }) - : Promise.resolve([] as SportSchedule[]), - ]); - sportsStandings = standings; - - // Logos + athletics links for every team in the tables, matched to - // Schools by short name (falling back to full name) - const teamNames = [...new Set(sportsStandings.flatMap((s) => s.rows.map((r) => r.team)))]; - if (teamNames.length > 0) { - try { - const schoolsResponse = await payload.find({ - collection: 'schools', - where: { or: [{ shortName: { in: teamNames } }, { name: { in: teamNames } }] }, - limit: teamNames.length * 2, - depth: 0, - select: { name: true, shortName: true, url: true, filename: true, athleticsUrl: true }, - }); - for (const school of schoolsResponse.docs) { - const key = school.shortName && teamNames.includes(school.shortName) ? school.shortName : school.name; - if (!sportsStandingsTeams[key]) { - sportsStandingsTeams[key] = { logo: school.url || null, url: school.athleticsUrl || null }; - } - } - } catch { - // Schools table may not exist yet; rows render without logos - } - } - - // Score strip: RPI's recent finals and next game in each standings sport, - // in the standings card's order. Opponents take the short name and logo - // from Schools when there is one, so editors' logo fixes carry over; - // otherwise RPI Athletics' own. - const scheduleBySport = new Map(schedule.map((s) => [s.sport, s])); - sportsSchedule = sportsStandings - .map((s) => scheduleBySport.get(s.sport)) - .filter((s): s is SportSchedule => s !== undefined); - const opponentNames = [...new Set(sportsSchedule.flatMap((s) => s.games.map((g) => g.opponent.name)))]; - if (opponentNames.length > 0) { - try { - const schoolsResponse = await payload.find({ - collection: 'schools', - where: { name: { in: opponentNames } }, - limit: opponentNames.length, - depth: 0, - // url is derived from filename, so both are needed - select: { name: true, shortName: true, url: true, filename: true }, - }); - const schools = new Map(schoolsResponse.docs.map((s) => [s.name, s])); - sportsSchedule = sportsSchedule.map((s) => ({ - ...s, - games: s.games.map((g) => { - const school = schools.get(g.opponent.name); - if (!school) return g; - return { - ...g, - opponent: { - ...g.opponent, - shortName: school.shortName || g.opponent.shortName, - logo: school.url || g.opponent.logo, - }, - }; - }), - })); - } catch { - // Schools table may not exist yet; RPI Athletics' names and logos stay - } - } - } + // Sports: editors' layout and pins, standings, schedule and schools + const sportsPage = section === 'sports' ? await loadSportsPage(payload) : null; return (
@@ -729,24 +513,8 @@ export default async function SectionPageRoute({ params }: Args) { collarCityImages={featuresCollarCityImages} pinnedWide={featuresPinnedWide} /> - ) : section === 'sports' ? ( - + ) : sportsPage ? ( + ) : isNews ? ( formatArticle(a)) .filter((a): a is ComponentArticle => a !== null); - // Stories editors reframed for the featured row keep that framing here - let focus: FeaturedFocus = {}; - try { - const layoutResponse = await payload.find({ collection: 'sports-page-layout', limit: 1, depth: 0, select: { layout: true } }); - const layout = layoutResponse.docs[0]?.layout as { featuredFocus?: FeaturedFocus } | null | undefined; - focus = layout?.featuredFocus ?? {}; - } catch { - // Table may not exist yet; cards use each photo's focal point - } - - const currentMonth = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/New_York', year: 'numeric', month: '2-digit' }).format(new Date()); + // Stories editors reframed for the featured row keep that framing here; + // the rest use each photo's focal point + const { featuredFocus: focus } = await loadSportsLayout(payload); return (
@@ -104,7 +97,7 @@ export default async function SportsAllStoriesPage({ searchParams }: Args) { activeSport={activeSport} page={response.page ?? requestedPage} totalPages={response.totalPages} - currentMonth={currentMonth} + currentMonth={troyMonth(new Date())} focus={focus} />