From c317ea793e852b216d35c8fc07b5f62017b0256a Mon Sep 17 00:00:00 2001 From: Caleb Bae Date: Tue, 29 Sep 2026 20:49:21 +0000 Subject: [PATCH 1/3] feat(public): serve sponsor/track logos as cacheable URLs and downscale uploads - add keyless GET /v1/public/{sponsors,tracks}/{id}/logo returning raw image bytes with ETag and versioned immutable Cache-Control - public list responses now return logo_url instead of inline logo_data/logo_content_type - portal downscales logos to <=512px WebP on upload --- .../sponsors/components/SponsorFormDialog.tsx | 11 +- .../sponsors/components/SponsorsTable.tsx | 12 +- .../src/pages/admin/sponsors/constants.ts | 14 + .../portal/src/pages/admin/sponsors/store.ts | 25 +- .../tracks/components/TrackFormDialog.tsx | 6 +- .../admin/tracks/components/TracksTable.tsx | 6 +- .../src/pages/admin/tracks/constants.ts | 10 +- client/portal/src/pages/admin/tracks/store.ts | 21 +- client/portal/src/shared/lib/logo-image.ts | 107 ++++++ cmd/api/api.go | 17 +- cmd/api/public.go | 250 +++++++++++++- cmd/api/public_logos_test.go | 325 ++++++++++++++++++ cmd/api/test_utils_test.go | 3 +- docs/docs.go | 223 +++++++++++- 14 files changed, 971 insertions(+), 59 deletions(-) create mode 100644 client/portal/src/pages/admin/sponsors/constants.ts create mode 100644 client/portal/src/shared/lib/logo-image.ts create mode 100644 cmd/api/public_logos_test.go diff --git a/client/portal/src/pages/admin/sponsors/components/SponsorFormDialog.tsx b/client/portal/src/pages/admin/sponsors/components/SponsorFormDialog.tsx index da60e7541..968032a9f 100644 --- a/client/portal/src/pages/admin/sponsors/components/SponsorFormDialog.tsx +++ b/client/portal/src/pages/admin/sponsors/components/SponsorFormDialog.tsx @@ -21,6 +21,7 @@ import { } from "@/components/ui/select"; import { Textarea } from "@/components/ui/textarea"; +import { ALLOWED_LOGO_TYPES, MAX_LOGO_SOURCE_BYTES } from "../constants"; import type { Sponsor, SponsorPayload } from "../types"; const TIER_OPTIONS = [ @@ -31,8 +32,6 @@ const TIER_OPTIONS = [ "Bronze", "Standard", ]; -const ALLOWED_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"]; -const MAX_SIZE_BYTES = 1 * 1024 * 1024; // 1MB interface SponsorFormDialogProps { open: boolean; @@ -70,13 +69,13 @@ function SponsorForm({ const file = e.target.files?.[0]; if (!file) return; - if (!ALLOWED_TYPES.includes(file.type)) { + if (!ALLOWED_LOGO_TYPES.includes(file.type)) { toast.error("Unsupported file type. Use PNG, JPEG, WebP, or GIF."); return; } - if (file.size > MAX_SIZE_BYTES) { - toast.error("File too large. Maximum size is 1MB."); + if (file.size > MAX_LOGO_SOURCE_BYTES) { + toast.error("File too large. Maximum size is 10MB."); return; } @@ -132,7 +131,7 @@ function SponsorForm({ diff --git a/client/portal/src/pages/admin/sponsors/components/SponsorsTable.tsx b/client/portal/src/pages/admin/sponsors/components/SponsorsTable.tsx index 5fbb51e8b..1d54ed771 100644 --- a/client/portal/src/pages/admin/sponsors/components/SponsorsTable.tsx +++ b/client/portal/src/pages/admin/sponsors/components/SponsorsTable.tsx @@ -49,6 +49,7 @@ import { } from "@/components/ui/tooltip"; import { fetchSponsors } from "../api"; +import { ALLOWED_LOGO_TYPES, MAX_LOGO_SOURCE_BYTES } from "../constants"; import type { Sponsor, SponsorPayload } from "../types"; import { SponsorFormDialog } from "./SponsorFormDialog"; @@ -61,9 +62,6 @@ const tierColors: Record = { Standard: "bg-blue-100 text-blue-800", }; -const ALLOWED_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"]; -const MAX_SIZE_BYTES = 1 * 1024 * 1024; // 1MB - interface SponsorsTableProps { sponsors: Sponsor[]; saving: boolean; @@ -203,13 +201,13 @@ export function SponsorsTable({ const sponsorId = logoTargetIdRef.current; if (!file || !sponsorId) return; - if (!ALLOWED_TYPES.includes(file.type)) { + if (!ALLOWED_LOGO_TYPES.includes(file.type)) { toast.error("Unsupported file type. Use PNG, JPEG, WebP, or GIF."); return; } - if (file.size > MAX_SIZE_BYTES) { - toast.error("File too large. Maximum size is 1MB."); + if (file.size > MAX_LOGO_SOURCE_BYTES) { + toast.error("File too large. Maximum size is 10MB."); return; } @@ -264,7 +262,7 @@ export function SponsorsTable({ diff --git a/client/portal/src/pages/admin/sponsors/constants.ts b/client/portal/src/pages/admin/sponsors/constants.ts new file mode 100644 index 000000000..8dd462ce2 --- /dev/null +++ b/client/portal/src/pages/admin/sponsors/constants.ts @@ -0,0 +1,14 @@ +export const ALLOWED_LOGO_TYPES = [ + "image/png", + "image/jpeg", + "image/webp", + "image/gif", +]; + +// Upper bound on the file an admin may pick. Logos are downscaled and +// re-encoded client-side before upload, so this only guards against +// accidentally selecting something enormous. +export const MAX_LOGO_SOURCE_BYTES = 10 * 1024 * 1024; + +// Matches maxLogoBytes on the backend (decoded size after compression). +export const MAX_LOGO_BYTES = 1 * 1024 * 1024; diff --git a/client/portal/src/pages/admin/sponsors/store.ts b/client/portal/src/pages/admin/sponsors/store.ts index bd727c9e9..f1e2a6200 100644 --- a/client/portal/src/pages/admin/sponsors/store.ts +++ b/client/portal/src/pages/admin/sponsors/store.ts @@ -1,5 +1,8 @@ +import { toast } from "sonner"; import { create } from "zustand"; +import { prepareLogoForUpload } from "@/shared/lib/logo-image"; + import { createSponsor as apiCreateSponsor, deleteSponsor as apiDeleteSponsor, @@ -7,6 +10,7 @@ import { updateSponsor as apiUpdateSponsor, uploadSponsorLogo, } from "./api"; +import { MAX_LOGO_BYTES } from "./constants"; import type { Sponsor, SponsorPayload } from "./types"; export interface SponsorsState { @@ -90,18 +94,17 @@ export const useSponsorsStore = create((set) => ({ }, uploadLogo: async (sponsorId: string, file: File) => { - const base64 = await new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => { - const result = reader.result as string; - const base64Data = result.split(",")[1]; - resolve(base64Data); - }; - reader.onerror = reject; - reader.readAsDataURL(file); - }); + const logo = await prepareLogoForUpload(file); + if (logo.byteLength > MAX_LOGO_BYTES) { + toast.error("Logo is still too large after compression."); + return null; + } - const res = await uploadSponsorLogo(sponsorId, base64, file.type); + const res = await uploadSponsorLogo( + sponsorId, + logo.base64, + logo.contentType, + ); if (res.status === 200 && res.data) { set((state) => ({ sponsors: state.sponsors.map((s) => diff --git a/client/portal/src/pages/admin/tracks/components/TrackFormDialog.tsx b/client/portal/src/pages/admin/tracks/components/TrackFormDialog.tsx index f3c935cb0..45b33e60e 100644 --- a/client/portal/src/pages/admin/tracks/components/TrackFormDialog.tsx +++ b/client/portal/src/pages/admin/tracks/components/TrackFormDialog.tsx @@ -14,7 +14,7 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; -import { ALLOWED_LOGO_TYPES, MAX_LOGO_BYTES } from "../constants"; +import { ALLOWED_LOGO_TYPES, MAX_LOGO_SOURCE_BYTES } from "../constants"; import type { Track, TrackPayload, TrackPrize } from "../types"; interface TrackFormDialogProps { @@ -62,8 +62,8 @@ function TrackForm({ return; } - if (file.size > MAX_LOGO_BYTES) { - toast.error("File too large. Maximum size is 750KB."); + if (file.size > MAX_LOGO_SOURCE_BYTES) { + toast.error("File too large. Maximum size is 10MB."); return; } diff --git a/client/portal/src/pages/admin/tracks/components/TracksTable.tsx b/client/portal/src/pages/admin/tracks/components/TracksTable.tsx index 144c3426e..b20417475 100644 --- a/client/portal/src/pages/admin/tracks/components/TracksTable.tsx +++ b/client/portal/src/pages/admin/tracks/components/TracksTable.tsx @@ -36,7 +36,7 @@ import { import { cn } from "@/shared/lib/utils"; import { fetchTracks } from "../api"; -import { ALLOWED_LOGO_TYPES, MAX_LOGO_BYTES } from "../constants"; +import { ALLOWED_LOGO_TYPES, MAX_LOGO_SOURCE_BYTES } from "../constants"; import type { Track, TrackPayload } from "../types"; import { TrackFormDialog } from "./TrackFormDialog"; @@ -171,8 +171,8 @@ export function TracksTable({ return; } - if (file.size > MAX_LOGO_BYTES) { - toast.error("File too large. Maximum size is 750KB."); + if (file.size > MAX_LOGO_SOURCE_BYTES) { + toast.error("File too large. Maximum size is 10MB."); return; } diff --git a/client/portal/src/pages/admin/tracks/constants.ts b/client/portal/src/pages/admin/tracks/constants.ts index f8d3bd1d9..05144e985 100644 --- a/client/portal/src/pages/admin/tracks/constants.ts +++ b/client/portal/src/pages/admin/tracks/constants.ts @@ -5,6 +5,12 @@ export const ALLOWED_LOGO_TYPES = [ "image/gif", ]; -// Matches maxTrackLogoBytes on the backend. readJSON caps the request body at -// 1MB and base64 inflates by ~4/3, so a 1MB decoded limit is unreachable. +// Upper bound on the file an admin may pick. Logos are downscaled and +// re-encoded client-side before upload, so this only guards against +// accidentally selecting something enormous. +export const MAX_LOGO_SOURCE_BYTES = 10 * 1024 * 1024; + +// Matches maxTrackLogoBytes on the backend (decoded size after compression). +// readJSON caps the request body at 1MB and base64 inflates by ~4/3, so a 1MB +// decoded limit is unreachable. export const MAX_LOGO_BYTES = 750 * 1024; diff --git a/client/portal/src/pages/admin/tracks/store.ts b/client/portal/src/pages/admin/tracks/store.ts index 417c94979..7a54818e4 100644 --- a/client/portal/src/pages/admin/tracks/store.ts +++ b/client/portal/src/pages/admin/tracks/store.ts @@ -1,6 +1,8 @@ +import { toast } from "sonner"; import { create } from "zustand"; import { errorAlert } from "@/shared/lib/api"; +import { prepareLogoForUpload } from "@/shared/lib/logo-image"; import { createTrack as apiCreateTrack, @@ -10,6 +12,7 @@ import { updateTrack as apiUpdateTrack, uploadTrackLogo, } from "./api"; +import { MAX_LOGO_BYTES } from "./constants"; import type { Track, TrackPayload } from "./types"; function sortByOrder(tracks: Track[]): Track[] { @@ -108,17 +111,13 @@ export const useTracksStore = create((set) => ({ }, uploadLogo: async (trackId: string, file: File) => { - const base64 = await new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => { - const result = reader.result as string; - resolve(result.split(",")[1]); - }; - reader.onerror = reject; - reader.readAsDataURL(file); - }); - - const res = await uploadTrackLogo(trackId, base64, file.type); + const logo = await prepareLogoForUpload(file); + if (logo.byteLength > MAX_LOGO_BYTES) { + toast.error("Logo is still too large after compression."); + return null; + } + + const res = await uploadTrackLogo(trackId, logo.base64, logo.contentType); if (res.status === 200 && res.data) { const updated = res.data; set((state) => ({ diff --git a/client/portal/src/shared/lib/logo-image.ts b/client/portal/src/shared/lib/logo-image.ts new file mode 100644 index 000000000..64b07476b --- /dev/null +++ b/client/portal/src/shared/lib/logo-image.ts @@ -0,0 +1,107 @@ +/** + * Client-side logo preparation: decode an uploaded image, downscale it so its + * longest side is at most MAX_LOGO_DIMENSION, and re-encode it as WebP. This + * keeps the base64 payload stored by HARP (and served to public consumers) + * roughly an order of magnitude smaller than a raw upload. + * + * Transparency is preserved. Animated GIFs are flattened to their first frame. + * If the browser cannot encode WebP, PNG is used instead; if re-encoding does + * not actually shrink the file, the original bytes are kept. + */ + +export const MAX_LOGO_DIMENSION = 512; +const WEBP_QUALITY = 0.85; + +export interface PreparedLogo { + base64: string; + contentType: string; + byteLength: number; +} + +async function decodeImage( + file: File, +): Promise { + if (typeof createImageBitmap === "function") { + try { + return await createImageBitmap(file); + } catch { + // Fall through to the path for formats createImageBitmap rejects. + } + } + + const url = URL.createObjectURL(file); + try { + return await new Promise((resolve, reject) => { + const img = new Image(); + img.onload = () => resolve(img); + img.onerror = () => reject(new Error("Could not decode image")); + img.src = url; + }); + } finally { + URL.revokeObjectURL(url); + } +} + +function imageSize(source: ImageBitmap | HTMLImageElement): { + width: number; + height: number; +} { + if (source instanceof HTMLImageElement) { + return { width: source.naturalWidth, height: source.naturalHeight }; + } + return { width: source.width, height: source.height }; +} + +function canvasToBlob( + canvas: HTMLCanvasElement, + type: string, + quality?: number, +): Promise { + return new Promise((resolve) => canvas.toBlob(resolve, type, quality)); +} + +async function blobToBase64(blob: Blob): Promise { + const bytes = new Uint8Array(await blob.arrayBuffer()); + let binary = ""; + const chunk = 0x8000; + for (let i = 0; i < bytes.length; i += chunk) { + binary += String.fromCharCode(...bytes.subarray(i, i + chunk)); + } + return btoa(binary); +} + +export async function prepareLogoForUpload(file: File): Promise { + const source = await decodeImage(file); + const { width, height } = imageSize(source); + if (width === 0 || height === 0) { + throw new Error("Could not decode image"); + } + + const scale = Math.min(1, MAX_LOGO_DIMENSION / Math.max(width, height)); + const canvas = document.createElement("canvas"); + canvas.width = Math.max(1, Math.round(width * scale)); + canvas.height = Math.max(1, Math.round(height * scale)); + + const ctx = canvas.getContext("2d"); + if (!ctx) { + throw new Error("Canvas is not supported in this browser"); + } + ctx.imageSmoothingEnabled = true; + ctx.imageSmoothingQuality = "high"; + ctx.drawImage(source, 0, 0, canvas.width, canvas.height); + if ("close" in source) source.close(); + + let encoded = await canvasToBlob(canvas, "image/webp", WEBP_QUALITY); + if (!encoded || encoded.type !== "image/webp") { + encoded = await canvasToBlob(canvas, "image/png"); + } + + const best = + encoded && (encoded.size < file.size || scale < 1) ? encoded : file; + + return { + base64: await blobToBase64(best), + contentType: best.type, + byteLength: best.size, + }; +} diff --git a/cmd/api/api.go b/cmd/api/api.go index 30740e684..5a0fe2903 100644 --- a/cmd/api/api.go +++ b/cmd/api/api.go @@ -192,11 +192,18 @@ func (app *application) mount() http.Handler { // Public API (key auth) r.Route("/public", func(r chi.Router) { - r.Use(app.APIKeyMiddleware) - r.Get("/schedule", app.getPublicScheduleHandler) - r.Get("/sponsors", app.getPublicSponsorsHandler) - r.Get("/faq", app.getPublicFAQHandler) - r.Get("/tracks", app.getPublicTracksHandler) + // Logo bytes are keyless: the URLs go straight into tags and + // image optimizers, which cannot send X-API-Key. + r.Get("/sponsors/{sponsorID}/logo", app.getPublicSponsorLogoHandler) + r.Get("/tracks/{trackID}/logo", app.getPublicTrackLogoHandler) + + r.Group(func(r chi.Router) { + r.Use(app.APIKeyMiddleware) + r.Get("/schedule", app.getPublicScheduleHandler) + r.Get("/sponsors", app.getPublicSponsorsHandler) + r.Get("/faq", app.getPublicFAQHandler) + r.Get("/tracks", app.getPublicTracksHandler) + }) }) // Legal document links. Unauthenticated on purpose: the login page diff --git a/cmd/api/public.go b/cmd/api/public.go index ed8d251c1..8804f1655 100644 --- a/cmd/api/public.go +++ b/cmd/api/public.go @@ -1,9 +1,149 @@ package main import ( + "encoding/base64" + "errors" + "fmt" "net/http" + "strconv" + "strings" + "time" + + "github.com/go-chi/chi/v5" + "github.com/hackutd/harp/internal/store" ) +// Cache lifetime for logo bytes fetched at a versioned URL. The version is the +// row's updated_at, so a new upload produces a new URL and the old one can be +// cached forever. +const publicLogoImmutableMaxAge = 365 * 24 * time.Hour + +// Cache lifetime for logo bytes fetched without (or with a stale) version. +const publicLogoDefaultMaxAge = 5 * time.Minute + +// PublicSponsor is the sponsor shape exposed on the public API. Logos are +// referenced by URL rather than inlined as base64 so consumers can cache them +// as images. +type PublicSponsor struct { + ID string `json:"id"` + Name string `json:"name"` + Tier string `json:"tier"` + LogoURL string `json:"logo_url"` + WebsiteURL string `json:"website_url"` + Description string `json:"description"` + DisplayOrder int `json:"display_order"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +type PublicSponsorListResponse struct { + Sponsors []PublicSponsor `json:"sponsors"` +} + +// PublicTrack is the challenge track shape exposed on the public API. See +// PublicSponsor for why the logo is a URL. +type PublicTrack struct { + ID string `json:"id"` + Title string `json:"title"` + SponsorName string `json:"sponsor_name"` + Description string `json:"description"` + Prizes store.TrackPrizes `json:"prizes"` + LogoURL string `json:"logo_url"` + DisplayOrder int `json:"display_order"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +type PublicTrackListResponse struct { + Tracks []PublicTrack `json:"tracks"` +} + +func logoVersion(updatedAt time.Time) string { + return strconv.FormatInt(updatedAt.Unix(), 10) +} + +// publicLogoURL builds the absolute, versioned URL for a resource's logo, or "" +// when the row has no logo. +func (app *application) publicLogoURL(resource, id, logoData string, updatedAt time.Time) string { + if logoData == "" { + return "" + } + return fmt.Sprintf("%s/v1/public/%s/%s/logo?v=%s", + strings.TrimRight(app.config.appURL, "/"), resource, id, logoVersion(updatedAt)) +} + +func (app *application) toPublicSponsor(s store.Sponsor) PublicSponsor { + return PublicSponsor{ + ID: s.ID, + Name: s.Name, + Tier: s.Tier, + LogoURL: app.publicLogoURL("sponsors", s.ID, s.LogoData, s.UpdatedAt), + WebsiteURL: s.WebsiteURL, + Description: s.Description, + DisplayOrder: s.DisplayOrder, + CreatedAt: s.CreatedAt, + UpdatedAt: s.UpdatedAt, + } +} + +func (app *application) toPublicTrack(t store.Track) PublicTrack { + prizes := t.Prizes + if prizes == nil { + prizes = store.TrackPrizes{} + } + return PublicTrack{ + ID: t.ID, + Title: t.Title, + SponsorName: t.SponsorName, + Description: t.Description, + Prizes: prizes, + LogoURL: app.publicLogoURL("tracks", t.ID, t.LogoData, t.UpdatedAt), + DisplayOrder: t.DisplayOrder, + CreatedAt: t.CreatedAt, + UpdatedAt: t.UpdatedAt, + } +} + +// serveLogo writes a stored base64 logo as raw image bytes with cache headers. +// The response is immutable only when the request carries the current version, +// so a stale or missing ?v never pins an old logo in a shared cache. +func (app *application) serveLogo(w http.ResponseWriter, r *http.Request, logoData, contentType string, updatedAt time.Time) { + if logoData == "" || contentType == "" { + app.notFoundResponse(w, r, errors.New("logo not found")) + return + } + + decoded, err := base64.StdEncoding.DecodeString(logoData) + if err != nil { + app.internalServerError(w, r, fmt.Errorf("stored logo is not valid base64: %w", err)) + return + } + + version := logoVersion(updatedAt) + etag := `"` + version + `"` + + cacheControl := fmt.Sprintf("public, max-age=%d", int(publicLogoDefaultMaxAge.Seconds())) + if r.URL.Query().Get("v") == version { + cacheControl = fmt.Sprintf("public, max-age=%d, immutable", int(publicLogoImmutableMaxAge.Seconds())) + } + + w.Header().Set("Cache-Control", cacheControl) + w.Header().Set("ETag", etag) + + if r.Header.Get("If-None-Match") == etag { + w.WriteHeader(http.StatusNotModified) + return + } + + w.Header().Set("Content-Type", contentType) + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Content-Length", strconv.Itoa(len(decoded))) + w.WriteHeader(http.StatusOK) + if _, err := w.Write(decoded); err != nil { + app.requestLogger(r).Warnw("failed to write logo response", "error", err) + } +} + // getPublicScheduleHandler returns the full schedule (public, API key auth) // // @Summary Get schedule (Public) @@ -22,16 +162,65 @@ func (app *application) getPublicScheduleHandler(w http.ResponseWriter, r *http. // getPublicSponsorsHandler returns all sponsors (public, API key auth) // // @Summary Get sponsors (Public) -// @Description Returns all sponsors, ordered by display order. Logos are returned inline as base64 in logo_data, with the MIME type in logo_content_type — not as URLs. +// @Description Returns all sponsors, ordered by display order. Each sponsor's logo is referenced by logo_url (an absolute, versioned URL to /public/sponsors/{sponsorID}/logo), or "" when the sponsor has no logo. Logo bytes are not inlined. // @Tags public // @Produce json // @Param X-API-Key header string true "API Key" -// @Success 200 {object} SponsorListResponse +// @Success 200 {object} PublicSponsorListResponse // @Failure 401 {object} object{error=string} // @Failure 500 {object} object{error=string} // @Router /public/sponsors [get] func (app *application) getPublicSponsorsHandler(w http.ResponseWriter, r *http.Request) { - app.listSponsorsHandler(w, r) + sponsors, err := app.store.Sponsors.List(r.Context()) + if err != nil { + app.internalServerError(w, r, err) + return + } + + out := make([]PublicSponsor, 0, len(sponsors)) + for _, s := range sponsors { + out = append(out, app.toPublicSponsor(s)) + } + + if err := app.jsonResponse(w, http.StatusOK, PublicSponsorListResponse{Sponsors: out}); err != nil { + app.internalServerError(w, r, err) + } +} + +// getPublicSponsorLogoHandler serves a sponsor's logo as an image (public, no auth) +// +// @Summary Get sponsor logo (Public) +// @Description Returns the sponsor's logo as raw image bytes with the stored content type. No API key is required so the URL can be used directly in an tag or by an image optimizer. Responses carry an ETag; when ?v matches the current version the response is immutable for a year, otherwise it is cacheable for five minutes. +// @Tags public +// @Produce image/png +// @Produce image/jpeg +// @Produce image/webp +// @Produce image/gif +// @Param sponsorID path string true "Sponsor ID" +// @Param v query string false "Logo version (updated_at as unix seconds), as embedded in logo_url" +// @Success 200 {file} binary +// @Success 304 +// @Failure 404 {object} object{error=string} +// @Failure 500 {object} object{error=string} +// @Router /public/sponsors/{sponsorID}/logo [get] +func (app *application) getPublicSponsorLogoHandler(w http.ResponseWriter, r *http.Request) { + id := chi.URLParam(r, "sponsorID") + if id == "" { + app.badRequestResponse(w, r, errors.New("missing sponsor ID")) + return + } + + sponsor, err := app.store.Sponsors.GetByID(r.Context(), id) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + app.notFoundResponse(w, r, errors.New("sponsor not found")) + return + } + app.internalServerError(w, r, err) + return + } + + app.serveLogo(w, r, sponsor.LogoData, sponsor.LogoContentType, sponsor.UpdatedAt) } // getPublicFAQHandler returns all FAQs (public, API key auth) @@ -52,14 +241,63 @@ func (app *application) getPublicFAQHandler(w http.ResponseWriter, r *http.Reque // getPublicTracksHandler returns all challenge tracks (public, API key auth) // // @Summary Get tracks (Public) -// @Description Returns all challenge tracks, ordered by display order. Logos are returned inline as base64 in logo_data, with the MIME type in logo_content_type — not as URLs. +// @Description Returns all challenge tracks, ordered by display order. Each track's logo is referenced by logo_url (an absolute, versioned URL to /public/tracks/{trackID}/logo), or "" when the track has no logo. Logo bytes are not inlined. // @Tags public // @Produce json // @Param X-API-Key header string true "API Key" -// @Success 200 {object} TrackListResponse +// @Success 200 {object} PublicTrackListResponse // @Failure 401 {object} object{error=string} // @Failure 500 {object} object{error=string} // @Router /public/tracks [get] func (app *application) getPublicTracksHandler(w http.ResponseWriter, r *http.Request) { - app.listTracksHandler(w, r) + tracks, err := app.store.Tracks.List(r.Context()) + if err != nil { + app.internalServerError(w, r, err) + return + } + + out := make([]PublicTrack, 0, len(tracks)) + for _, t := range tracks { + out = append(out, app.toPublicTrack(t)) + } + + if err := app.jsonResponse(w, http.StatusOK, PublicTrackListResponse{Tracks: out}); err != nil { + app.internalServerError(w, r, err) + } +} + +// getPublicTrackLogoHandler serves a track's logo as an image (public, no auth) +// +// @Summary Get track logo (Public) +// @Description Returns the track's logo as raw image bytes with the stored content type. No API key is required so the URL can be used directly in an tag or by an image optimizer. Responses carry an ETag; when ?v matches the current version the response is immutable for a year, otherwise it is cacheable for five minutes. +// @Tags public +// @Produce image/png +// @Produce image/jpeg +// @Produce image/webp +// @Produce image/gif +// @Param trackID path string true "Track ID" +// @Param v query string false "Logo version (updated_at as unix seconds), as embedded in logo_url" +// @Success 200 {file} binary +// @Success 304 +// @Failure 404 {object} object{error=string} +// @Failure 500 {object} object{error=string} +// @Router /public/tracks/{trackID}/logo [get] +func (app *application) getPublicTrackLogoHandler(w http.ResponseWriter, r *http.Request) { + id := chi.URLParam(r, "trackID") + if id == "" { + app.badRequestResponse(w, r, errors.New("missing track ID")) + return + } + + track, err := app.store.Tracks.GetByID(r.Context(), id) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + app.notFoundResponse(w, r, errors.New("track not found")) + return + } + app.internalServerError(w, r, err) + return + } + + app.serveLogo(w, r, track.LogoData, track.LogoContentType, track.UpdatedAt) } diff --git a/cmd/api/public_logos_test.go b/cmd/api/public_logos_test.go new file mode 100644 index 000000000..d9b4704ce --- /dev/null +++ b/cmd/api/public_logos_test.go @@ -0,0 +1,325 @@ +package main + +import ( + "encoding/base64" + "encoding/json" + "errors" + "net/http" + "strconv" + "testing" + "time" + + "github.com/hackutd/harp/internal/store" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var testLogoBytes = []byte{0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A} + +func testLogoUpdatedAt() time.Time { + return time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) +} + +func testSponsorWithLogo() *store.Sponsor { + return &store.Sponsor{ + ID: "sponsor-1", + Name: "Acme", + Tier: "gold", + LogoData: base64.StdEncoding.EncodeToString(testLogoBytes), + LogoContentType: "image/png", + WebsiteURL: "https://acme.example", + DisplayOrder: 1, + CreatedAt: testLogoUpdatedAt(), + UpdatedAt: testLogoUpdatedAt(), + } +} + +func testTrackWithLogo() *store.Track { + return &store.Track{ + ID: "track-1", + Title: "Best Use of Acme", + SponsorName: "Acme", + Prizes: store.TrackPrizes{{Place: "1st", Prize: "Widget"}}, + LogoData: base64.StdEncoding.EncodeToString(testLogoBytes), + LogoContentType: "image/webp", + DisplayOrder: 1, + CreatedAt: testLogoUpdatedAt(), + UpdatedAt: testLogoUpdatedAt(), + } +} + +func TestGetPublicSponsorsLogoURL(t *testing.T) { + t.Run("returns logo_url instead of inline logo data", func(t *testing.T) { + app := newTestApplication(t) + mockSponsors := app.store.Sponsors.(*store.MockSponsorsStore) + mux := app.mount() + + withLogo := testSponsorWithLogo() + noLogo := &store.Sponsor{ID: "sponsor-2", Name: "NoLogo", Tier: "silver", DisplayOrder: 2} + mockSponsors.On("List").Return([]store.Sponsor{*withLogo, *noLogo}, nil).Once() + + req, err := http.NewRequest(http.MethodGet, "/v1/public/sponsors", nil) + require.NoError(t, err) + req.Header.Set("X-API-Key", "test-api-key") + + rr := executeRequest(req, mux) + checkResponseCode(t, http.StatusOK, rr.Code) + + var raw struct { + Data struct { + Sponsors []map[string]json.RawMessage `json:"sponsors"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &raw)) + require.Len(t, raw.Data.Sponsors, 2) + + for _, s := range raw.Data.Sponsors { + assert.NotContains(t, s, "logo_data") + assert.NotContains(t, s, "logo_content_type") + assert.Contains(t, s, "logo_url") + } + + var body struct { + Data PublicSponsorListResponse `json:"data"` + } + require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &body)) + wantURL := "http://localhost:8080/v1/public/sponsors/sponsor-1/logo?v=" + + strconv.FormatInt(testLogoUpdatedAt().Unix(), 10) + assert.Equal(t, wantURL, body.Data.Sponsors[0].LogoURL) + assert.Equal(t, "", body.Data.Sponsors[1].LogoURL) + + mockSponsors.AssertExpectations(t) + }) + + t.Run("returns 500 on store error", func(t *testing.T) { + app := newTestApplication(t) + mockSponsors := app.store.Sponsors.(*store.MockSponsorsStore) + mux := app.mount() + + mockSponsors.On("List").Return(nil, errors.New("db error")).Once() + + req, err := http.NewRequest(http.MethodGet, "/v1/public/sponsors", nil) + require.NoError(t, err) + req.Header.Set("X-API-Key", "test-api-key") + + rr := executeRequest(req, mux) + checkResponseCode(t, http.StatusInternalServerError, rr.Code) + + mockSponsors.AssertExpectations(t) + }) +} + +func TestGetPublicTracksLogoURL(t *testing.T) { + t.Run("returns logo_url instead of inline logo data", func(t *testing.T) { + app := newTestApplication(t) + mockTracks := app.store.Tracks.(*store.MockTracksStore) + mux := app.mount() + + withLogo := testTrackWithLogo() + noLogo := &store.Track{ID: "track-2", Title: "NoLogo", DisplayOrder: 2} + mockTracks.On("List").Return([]store.Track{*withLogo, *noLogo}, nil).Once() + + req, err := http.NewRequest(http.MethodGet, "/v1/public/tracks", nil) + require.NoError(t, err) + req.Header.Set("X-API-Key", "test-api-key") + + rr := executeRequest(req, mux) + checkResponseCode(t, http.StatusOK, rr.Code) + + var raw struct { + Data struct { + Tracks []map[string]json.RawMessage `json:"tracks"` + } `json:"data"` + } + require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &raw)) + require.Len(t, raw.Data.Tracks, 2) + for _, tr := range raw.Data.Tracks { + assert.NotContains(t, tr, "logo_data") + assert.NotContains(t, tr, "logo_content_type") + assert.Contains(t, tr, "logo_url") + } + assert.JSONEq(t, `[]`, string(raw.Data.Tracks[1]["prizes"])) + + var body struct { + Data PublicTrackListResponse `json:"data"` + } + require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &body)) + wantURL := "http://localhost:8080/v1/public/tracks/track-1/logo?v=" + + strconv.FormatInt(testLogoUpdatedAt().Unix(), 10) + assert.Equal(t, wantURL, body.Data.Tracks[0].LogoURL) + assert.Equal(t, "", body.Data.Tracks[1].LogoURL) + + mockTracks.AssertExpectations(t) + }) +} + +func TestGetPublicSponsorLogo(t *testing.T) { + version := strconv.FormatInt(testLogoUpdatedAt().Unix(), 10) + + t.Run("serves image bytes without API key", func(t *testing.T) { + app := newTestApplication(t) + mockSponsors := app.store.Sponsors.(*store.MockSponsorsStore) + mux := app.mount() + + mockSponsors.On("GetByID", "sponsor-1").Return(testSponsorWithLogo(), nil).Once() + + req, err := http.NewRequest(http.MethodGet, "/v1/public/sponsors/sponsor-1/logo?v="+version, nil) + require.NoError(t, err) + + rr := executeRequest(req, mux) + checkResponseCode(t, http.StatusOK, rr.Code) + assert.Equal(t, "image/png", rr.Header().Get("Content-Type")) + assert.Equal(t, "public, max-age=31536000, immutable", rr.Header().Get("Cache-Control")) + assert.Equal(t, `"`+version+`"`, rr.Header().Get("ETag")) + assert.Equal(t, "nosniff", rr.Header().Get("X-Content-Type-Options")) + assert.Equal(t, testLogoBytes, rr.Body.Bytes()) + + mockSponsors.AssertExpectations(t) + }) + + t.Run("is not immutable when version is missing or stale", func(t *testing.T) { + app := newTestApplication(t) + mockSponsors := app.store.Sponsors.(*store.MockSponsorsStore) + mux := app.mount() + + mockSponsors.On("GetByID", "sponsor-1").Return(testSponsorWithLogo(), nil).Twice() + + for _, path := range []string{ + "/v1/public/sponsors/sponsor-1/logo", + "/v1/public/sponsors/sponsor-1/logo?v=123", + } { + req, err := http.NewRequest(http.MethodGet, path, nil) + require.NoError(t, err) + + rr := executeRequest(req, mux) + checkResponseCode(t, http.StatusOK, rr.Code) + assert.Equal(t, "public, max-age=300", rr.Header().Get("Cache-Control"), path) + assert.Equal(t, testLogoBytes, rr.Body.Bytes()) + } + + mockSponsors.AssertExpectations(t) + }) + + t.Run("returns 304 when If-None-Match matches", func(t *testing.T) { + app := newTestApplication(t) + mockSponsors := app.store.Sponsors.(*store.MockSponsorsStore) + mux := app.mount() + + mockSponsors.On("GetByID", "sponsor-1").Return(testSponsorWithLogo(), nil).Once() + + req, err := http.NewRequest(http.MethodGet, "/v1/public/sponsors/sponsor-1/logo?v="+version, nil) + require.NoError(t, err) + req.Header.Set("If-None-Match", `"`+version+`"`) + + rr := executeRequest(req, mux) + checkResponseCode(t, http.StatusNotModified, rr.Code) + assert.Empty(t, rr.Body.Bytes()) + assert.Equal(t, `"`+version+`"`, rr.Header().Get("ETag")) + + mockSponsors.AssertExpectations(t) + }) + + t.Run("returns 404 when sponsor has no logo", func(t *testing.T) { + app := newTestApplication(t) + mockSponsors := app.store.Sponsors.(*store.MockSponsorsStore) + mux := app.mount() + + mockSponsors.On("GetByID", "sponsor-2").Return(&store.Sponsor{ID: "sponsor-2", Name: "NoLogo"}, nil).Once() + + req, err := http.NewRequest(http.MethodGet, "/v1/public/sponsors/sponsor-2/logo", nil) + require.NoError(t, err) + + rr := executeRequest(req, mux) + checkResponseCode(t, http.StatusNotFound, rr.Code) + + mockSponsors.AssertExpectations(t) + }) + + t.Run("returns 404 when sponsor does not exist", func(t *testing.T) { + app := newTestApplication(t) + mockSponsors := app.store.Sponsors.(*store.MockSponsorsStore) + mux := app.mount() + + mockSponsors.On("GetByID", "missing").Return(nil, store.ErrNotFound).Once() + + req, err := http.NewRequest(http.MethodGet, "/v1/public/sponsors/missing/logo", nil) + require.NoError(t, err) + + rr := executeRequest(req, mux) + checkResponseCode(t, http.StatusNotFound, rr.Code) + + mockSponsors.AssertExpectations(t) + }) + + t.Run("returns 500 on store error", func(t *testing.T) { + app := newTestApplication(t) + mockSponsors := app.store.Sponsors.(*store.MockSponsorsStore) + mux := app.mount() + + mockSponsors.On("GetByID", "sponsor-1").Return(nil, errors.New("db error")).Once() + + req, err := http.NewRequest(http.MethodGet, "/v1/public/sponsors/sponsor-1/logo", nil) + require.NoError(t, err) + + rr := executeRequest(req, mux) + checkResponseCode(t, http.StatusInternalServerError, rr.Code) + + mockSponsors.AssertExpectations(t) + }) +} + +func TestGetPublicTrackLogo(t *testing.T) { + version := strconv.FormatInt(testLogoUpdatedAt().Unix(), 10) + + t.Run("serves image bytes without API key", func(t *testing.T) { + app := newTestApplication(t) + mockTracks := app.store.Tracks.(*store.MockTracksStore) + mux := app.mount() + + mockTracks.On("GetByID", "track-1").Return(testTrackWithLogo(), nil).Once() + + req, err := http.NewRequest(http.MethodGet, "/v1/public/tracks/track-1/logo?v="+version, nil) + require.NoError(t, err) + + rr := executeRequest(req, mux) + checkResponseCode(t, http.StatusOK, rr.Code) + assert.Equal(t, "image/webp", rr.Header().Get("Content-Type")) + assert.Equal(t, "public, max-age=31536000, immutable", rr.Header().Get("Cache-Control")) + assert.Equal(t, `"`+version+`"`, rr.Header().Get("ETag")) + assert.Equal(t, testLogoBytes, rr.Body.Bytes()) + + mockTracks.AssertExpectations(t) + }) + + t.Run("returns 404 when track has no logo", func(t *testing.T) { + app := newTestApplication(t) + mockTracks := app.store.Tracks.(*store.MockTracksStore) + mux := app.mount() + + mockTracks.On("GetByID", "track-2").Return(&store.Track{ID: "track-2", Title: "NoLogo"}, nil).Once() + + req, err := http.NewRequest(http.MethodGet, "/v1/public/tracks/track-2/logo", nil) + require.NoError(t, err) + + rr := executeRequest(req, mux) + checkResponseCode(t, http.StatusNotFound, rr.Code) + + mockTracks.AssertExpectations(t) + }) + + t.Run("returns 404 when track does not exist", func(t *testing.T) { + app := newTestApplication(t) + mockTracks := app.store.Tracks.(*store.MockTracksStore) + mux := app.mount() + + mockTracks.On("GetByID", "missing").Return(nil, store.ErrNotFound).Once() + + req, err := http.NewRequest(http.MethodGet, "/v1/public/tracks/missing/logo", nil) + require.NoError(t, err) + + rr := executeRequest(req, mux) + checkResponseCode(t, http.StatusNotFound, rr.Code) + + mockTracks.AssertExpectations(t) + }) +} diff --git a/cmd/api/test_utils_test.go b/cmd/api/test_utils_test.go index 81a7a4ae6..a30f8a050 100644 --- a/cmd/api/test_utils_test.go +++ b/cmd/api/test_utils_test.go @@ -66,7 +66,8 @@ func newTestApplication(t *testing.T) *application { return &application{ config: config{ - env: "test", + env: "test", + appURL: "http://localhost:8080", auth: authConfig{ basic: basicConfig{ user: "testuser", diff --git a/docs/docs.go b/docs/docs.go index e7107592c..2cae9f0ca 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -4639,7 +4639,7 @@ const docTemplate = `{ }, "/public/sponsors": { "get": { - "description": "Returns all sponsors, ordered by display order. Logos are returned inline as base64 in logo_data, with the MIME type in logo_content_type — not as URLs.", + "description": "Returns all sponsors, ordered by display order. Each sponsor's logo is referenced by logo_url (an absolute, versioned URL to /public/sponsors/{sponsorID}/logo), or \"\" when the sponsor has no logo. Logo bytes are not inlined.", "produces": [ "application/json" ], @@ -4660,7 +4660,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/main.SponsorListResponse" + "$ref": "#/definitions/main.PublicSponsorListResponse" } }, "401": { @@ -4688,9 +4688,72 @@ const docTemplate = `{ } } }, + "/public/sponsors/{sponsorID}/logo": { + "get": { + "description": "Returns the sponsor's logo as raw image bytes with the stored content type. No API key is required so the URL can be used directly in an \u003cimg\u003e tag or by an image optimizer. Responses carry an ETag; when ?v matches the current version the response is immutable for a year, otherwise it is cacheable for five minutes.", + "produces": [ + "image/png", + "image/jpeg", + "image/webp", + "image/gif" + ], + "tags": [ + "public" + ], + "summary": "Get sponsor logo (Public)", + "parameters": [ + { + "type": "string", + "description": "Sponsor ID", + "name": "sponsorID", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Logo version (updated_at as unix seconds), as embedded in logo_url", + "name": "v", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "file" + } + }, + "304": { + "description": "Not Modified" + }, + "404": { + "description": "Not Found", + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + } + } + } + } + } + }, "/public/tracks": { "get": { - "description": "Returns all challenge tracks, ordered by display order. Logos are returned inline as base64 in logo_data, with the MIME type in logo_content_type — not as URLs.", + "description": "Returns all challenge tracks, ordered by display order. Each track's logo is referenced by logo_url (an absolute, versioned URL to /public/tracks/{trackID}/logo), or \"\" when the track has no logo. Logo bytes are not inlined.", "produces": [ "application/json" ], @@ -4711,7 +4774,7 @@ const docTemplate = `{ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/main.TrackListResponse" + "$ref": "#/definitions/main.PublicTrackListResponse" } }, "401": { @@ -4739,6 +4802,69 @@ const docTemplate = `{ } } }, + "/public/tracks/{trackID}/logo": { + "get": { + "description": "Returns the track's logo as raw image bytes with the stored content type. No API key is required so the URL can be used directly in an \u003cimg\u003e tag or by an image optimizer. Responses carry an ETag; when ?v matches the current version the response is immutable for a year, otherwise it is cacheable for five minutes.", + "produces": [ + "image/png", + "image/jpeg", + "image/webp", + "image/gif" + ], + "tags": [ + "public" + ], + "summary": "Get track logo (Public)", + "parameters": [ + { + "type": "string", + "description": "Track ID", + "name": "trackID", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "Logo version (updated_at as unix seconds), as embedded in logo_url", + "name": "v", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "file" + } + }, + "304": { + "description": "Not Modified" + }, + "404": { + "description": "Not Found", + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + } + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + } + } + } + } + } + }, "/schedule": { "get": { "security": [ @@ -11137,6 +11263,95 @@ const docTemplate = `{ } } }, + "main.PublicSponsor": { + "type": "object", + "properties": { + "created_at": { + "type": "string" + }, + "description": { + "type": "string" + }, + "display_order": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "logo_url": { + "type": "string" + }, + "name": { + "type": "string" + }, + "tier": { + "type": "string" + }, + "updated_at": { + "type": "string" + }, + "website_url": { + "type": "string" + } + } + }, + "main.PublicSponsorListResponse": { + "type": "object", + "properties": { + "sponsors": { + "type": "array", + "items": { + "$ref": "#/definitions/main.PublicSponsor" + } + } + } + }, + "main.PublicTrack": { + "type": "object", + "properties": { + "created_at": { + "type": "string" + }, + "description": { + "type": "string" + }, + "display_order": { + "type": "integer" + }, + "id": { + "type": "string" + }, + "logo_url": { + "type": "string" + }, + "prizes": { + "type": "array", + "items": { + "$ref": "#/definitions/store.TrackPrize" + } + }, + "sponsor_name": { + "type": "string" + }, + "title": { + "type": "string" + }, + "updated_at": { + "type": "string" + } + } + }, + "main.PublicTrackListResponse": { + "type": "object", + "properties": { + "tracks": { + "type": "array", + "items": { + "$ref": "#/definitions/main.PublicTrack" + } + } + } + }, "main.RSVPEnabledResponse": { "type": "object", "properties": { From d9c4c20c4e33cd8ceca99b32a384a2cb51a60906 Mon Sep 17 00:00:00 2001 From: Caleb Bae Date: Tue, 29 Sep 2026 16:34:58 -0500 Subject: [PATCH 2/3] feat: add drag drop for sponsor logos --- .../sponsors/components/SponsorFormDialog.tsx | 44 ++++++++++++++++--- 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/client/portal/src/pages/admin/sponsors/components/SponsorFormDialog.tsx b/client/portal/src/pages/admin/sponsors/components/SponsorFormDialog.tsx index 968032a9f..80fe036ae 100644 --- a/client/portal/src/pages/admin/sponsors/components/SponsorFormDialog.tsx +++ b/client/portal/src/pages/admin/sponsors/components/SponsorFormDialog.tsx @@ -63,12 +63,10 @@ function SponsorForm({ ? `data:${sponsor.logo_content_type};base64,${sponsor.logo_data}` : "", ); + const [isDraggingLogo, setIsDraggingLogo] = useState(false); const logoInputRef = useRef(null); - const handleLogoChange = (e: React.ChangeEvent) => { - const file = e.target.files?.[0]; - if (!file) return; - + const acceptLogoFile = (file: File) => { if (!ALLOWED_LOGO_TYPES.includes(file.type)) { toast.error("Unsupported file type. Use PNG, JPEG, WebP, or GIF."); return; @@ -85,6 +83,31 @@ function SponsorForm({ reader.readAsDataURL(file); }; + const handleLogoChange = (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (file) acceptLogoFile(file); + }; + + const handleLogoDragOver = (e: React.DragEvent) => { + if (!e.dataTransfer.types.includes("Files")) return; + e.preventDefault(); + e.dataTransfer.dropEffect = "copy"; + setIsDraggingLogo(true); + }; + + const handleLogoDragLeave = (e: React.DragEvent) => { + // dragleave also fires when moving onto a child; only reset on real exit. + if (e.currentTarget.contains(e.relatedTarget as Node | null)) return; + setIsDraggingLogo(false); + }; + + const handleLogoDrop = (e: React.DragEvent) => { + e.preventDefault(); + setIsDraggingLogo(false); + const file = e.dataTransfer.files[0]; + if (file) acceptLogoFile(file); + }; + const clearLogo = () => { setLogoFile(null); setLogoPreview( @@ -115,7 +138,16 @@ function SponsorForm({
-
+
{logoPreview ? (

- PNG, JPEG, WebP, or GIF (max 1MB) + Drag and drop or choose a file. PNG, JPEG, WebP, or GIF (max 10MB)

From 5fa0105682c5dc0d3a02ac0bdec677a082dafb1e Mon Sep 17 00:00:00 2001 From: Caleb Bae Date: Tue, 29 Sep 2026 16:38:53 -0500 Subject: [PATCH 3/3] chore: ui --- .../sponsors/components/SponsorFormDialog.tsx | 109 +++++++++--------- 1 file changed, 56 insertions(+), 53 deletions(-) diff --git a/client/portal/src/pages/admin/sponsors/components/SponsorFormDialog.tsx b/client/portal/src/pages/admin/sponsors/components/SponsorFormDialog.tsx index 80fe036ae..f0797ebe2 100644 --- a/client/portal/src/pages/admin/sponsors/components/SponsorFormDialog.tsx +++ b/client/portal/src/pages/admin/sponsors/components/SponsorFormDialog.tsx @@ -88,20 +88,20 @@ function SponsorForm({ if (file) acceptLogoFile(file); }; - const handleLogoDragOver = (e: React.DragEvent) => { + const handleLogoDragOver = (e: React.DragEvent) => { if (!e.dataTransfer.types.includes("Files")) return; e.preventDefault(); e.dataTransfer.dropEffect = "copy"; setIsDraggingLogo(true); }; - const handleLogoDragLeave = (e: React.DragEvent) => { + const handleLogoDragLeave = (e: React.DragEvent) => { // dragleave also fires when moving onto a child; only reset on real exit. if (e.currentTarget.contains(e.relatedTarget as Node | null)) return; setIsDraggingLogo(false); }; - const handleLogoDrop = (e: React.DragEvent) => { + const handleLogoDrop = (e: React.DragEvent) => { e.preventDefault(); setIsDraggingLogo(false); const file = e.dataTransfer.files[0]; @@ -138,61 +138,64 @@ function SponsorForm({
-
- {logoPreview ? ( - Logo preview - ) : ( -
- -
- )} -
- + +
+ + {logoFile && ( - {logoFile && ( - - )} -
+ )}
-

- Drag and drop or choose a file. PNG, JPEG, WebP, or GIF (max 10MB) -