Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
"payload": "payload"
},
"dependencies": {
"@jsquash/jpeg": "^1.6.0",
"@jsquash/resize": "^2.1.1",
"@payloadcms/db-postgres": "3.93.0",
"@payloadcms/next": "3.93.0",
"@payloadcms/storage-s3": "3.93.0",
Expand Down
16 changes: 16 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 8 additions & 16 deletions src/app/(frontend)/about/_components/AboutClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,13 @@
import { useEffect } from "react";
import { useLanguage } from "@/context/LanguageContext";
import Carousel from "@/components/ui/Carousel";
import { BilingualPage } from "@/lib/data/content";
import type { BilingualPage, CarouselPhoto } from "@/lib/data/content";

const carouselImages = [
"/images/carousel/argentic.jpg",
"/images/carousel/posing.jpg",
"/images/carousel/leaving.jpg",
"/images/carousel/yesday.jpg",
];
const carouselAlts = [
"Band portrait inside an abandoned warehouse",
"Band posing together in dilapidated building",
"Band leaving the warehouse after rehearsal and shoot",
"Still of the band in Yes Day music video shoot",
];
export default function AboutClient({ french, english }: BilingualPage) {
export default function AboutClient({
french,
english,
carousel,
}: BilingualPage & { carousel: CarouselPhoto[] }) {
const { isFrench } = useLanguage();
const pageContent = isFrench ? french : english;

Expand All @@ -40,8 +32,8 @@ export default function AboutClient({ french, english }: BilingualPage) {
<h1 className="text-4xl font-blanch mb-6">{pageContent.title}</h1>
<p className="text-lg leading-relaxed mb-8">{pageContent.content}</p>
<Carousel
images={carouselImages}
altTexts={carouselAlts}
images={carousel.map(({ src }) => src)}
altTexts={carousel.map(({ alt }) => (isFrench ? alt.french : alt.english))}
caption={
isFrench ? "Galerie de photos du groupe" : "Band photo gallery"
}
Expand Down
2 changes: 2 additions & 0 deletions src/app/(payload)/admin/importMap.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { ImageCompressor as ImageCompressor_2d748e6089b36a77056ec460e02e90cd } from '../../../components/payload/ImageCompressor'
import { ColorField as ColorField_386fb4f018787bb5f9192147d4ea9772 } from '../../../components/payload/ColorField'
import { S3ClientUploadHandler as S3ClientUploadHandler_f97aa6c64367fa259c5bc0567239ef24 } from '@payloadcms/storage-s3/client'
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'

/** @type import('payload').ImportMap */
export const importMap = {
"/components/payload/ImageCompressor#ImageCompressor": ImageCompressor_2d748e6089b36a77056ec460e02e90cd,
"/components/payload/ColorField#ColorField": ColorField_386fb4f018787bb5f9192147d4ea9772,
"@payloadcms/storage-s3/client#S3ClientUploadHandler": S3ClientUploadHandler_f97aa6c64367fa259c5bc0567239ef24,
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
Expand Down
26 changes: 25 additions & 1 deletion src/collections/Media.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import type { CollectionConfig } from "payload";
import {
imageMimeTypes,
jpegQuality,
maxImageSide,
} from "../lib/payload/imageLimits";

export const Media: CollectionConfig = {
slug: "media",
Expand All @@ -15,8 +20,27 @@ export const Media: CollectionConfig = {
required: true,
localized: true,
},
{
name: "compression",
type: "ui",
admin: {
components: {
Field: "/components/payload/ImageCompressor#ImageCompressor",
},
},
},
],
upload: {
mimeTypes: ["image/*"],
mimeTypes: imageMimeTypes,
resizeOptions: {
width: maxImageSide,
height: maxImageSide,
fit: "inside",
withoutEnlargement: true,
},
formatOptions: {
format: "jpeg",
options: { quality: jpegQuality, progressive: true },
},
},
};
59 changes: 59 additions & 0 deletions src/components/payload/ImageCompressor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"use client";

import { useEffect, useState } from "react";
import { useField, useForm } from "@payloadcms/ui";
import type { UIFieldClientComponent } from "payload";
import { compressImage } from "../../lib/payload/compressImage";

const handled = new WeakSet<File>();

const formatSize = (bytes: number) =>
bytes >= 1024 * 1024
? `${(bytes / 1024 / 1024).toFixed(2)} MB`
: `${Math.round(bytes / 1024)} KB`;

type Outcome =
| { status: "done"; original: number; compressed: number }
| { status: "failed" };

export const ImageCompressor: UIFieldClientComponent = () => {
const { value: file, setValue } = useField<File | null>({ path: "file" });
const { getField, setProcessing } = useForm();
const [outcome, setOutcome] = useState<Outcome | null>(null);

useEffect(() => {
if (!(file instanceof File) || handled.has(file)) return;
handled.add(file);
setProcessing(true);
compressImage(file)
.catch(() => null)
.then((compressed) => {
if (compressed) handled.add(compressed);
const current = getField("file")?.value;
// A file picked while this one was compressing owns the form now.
if (current instanceof File && current !== file) return;
setProcessing(false);
if (current !== file) return;
if (!compressed) {
setOutcome({ status: "failed" });
} else if (compressed !== file) {
setValue(compressed);
setOutcome({
status: "done",
original: file.size,
compressed: compressed.size,
});
}
});
}, [file, getField, setValue, setProcessing]);

if (!outcome) return null;

return (
<p role="status" style={{ margin: "0 0 var(--base)" }}>
{outcome.status === "done"
? `Compressed in the browser: ${formatSize(outcome.original)} to ${formatSize(outcome.compressed)}.`
: "This browser could not compress the image, so the original will be uploaded and shrunk by the server."}
</p>
);
};
22 changes: 19 additions & 3 deletions src/globals/pageCopy.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import type { GlobalConfig } from "payload";
import type { Field, GlobalConfig } from "payload";
import { revalidateGlobal } from "../lib/payload/revalidate";

const pageCopy = (slug: string, tag: string): GlobalConfig => ({
const pageCopy = (
slug: string,
tag: string,
extraFields: Field[] = []
): GlobalConfig => ({
slug,
access: {
read: () => true,
Expand All @@ -10,8 +14,20 @@ const pageCopy = (slug: string, tag: string): GlobalConfig => ({
fields: [
{ name: "title", type: "text", required: true, localized: true },
{ name: "content", type: "textarea", required: true, localized: true },
...extraFields,
],
});

export const AboutPage = pageCopy("about-page", "about");
export const AboutPage = pageCopy("about-page", "about", [
{
name: "carousel",
type: "array",
labels: { singular: "Photo", plural: "Photos" },
admin: { description: "Photos in the About page carousel, in order." },
fields: [
{ name: "photo", type: "upload", relationTo: "media", required: true },
{ name: "alt", type: "text", required: true, localized: true },
],
},
]);
export const TourPage = pageCopy("tour-page", "tour");
12 changes: 12 additions & 0 deletions src/lib/data/carouselFallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { CarouselPhoto } from "./sheet";

/** Shown until the About page has photos in Payload; delete with public/images/carousel/. */
export const fallbackCarousel: CarouselPhoto[] = [
["argentic", "Band portrait inside an abandoned warehouse"],
["posing", "Band posing together in dilapidated building"],
["leaving", "Band leaving the warehouse after rehearsal and shoot"],
["yesday", "Still of the band in Yes Day music video shoot"],
].map(([name, alt]) => ({
src: `/images/carousel/${name}.jpg`,
alt: { english: alt, french: alt },
}));
11 changes: 9 additions & 2 deletions src/lib/data/content.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { cacheLife, cacheTag } from "next/cache";
import { fallbackCarousel } from "./carouselFallback";
import * as payloadSource from "./payload";
import * as sheetSource from "./sheet";

export type { BilingualPage } from "./sheet";
export type { BilingualPage, CarouselPhoto } from "./sheet";

// Production reads the sheet until DATABASE_URL is set there (switchover step 4).
const source = process.env.DATABASE_URL ? payloadSource : sheetSource;
Expand All @@ -11,7 +12,13 @@ export async function getAboutPage() {
"use cache";
cacheLife("minutes");
cacheTag("about");
return source.getAboutPage();
const carousel = process.env.DATABASE_URL
? await payloadSource.getCarousel()
: [];
return {
...(await source.getAboutPage()),
carousel: carousel.length ? carousel : fallbackCarousel,
};
}

export async function getTourPage() {
Expand Down
26 changes: 25 additions & 1 deletion src/lib/data/payload.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getPayload } from "payload";
import config from "../../payload.config";
import type { IFrameProps, LyricsProps, TourDateType } from "../../utils/types";
import type { BilingualPage } from "./sheet";
import type { BilingualPage, CarouselPhoto } from "./sheet";

const locales = ["en", "fr"] as const;
const read = { depth: 0, fallbackLocale: "en", limit: 0, pagination: false } as const;
Expand All @@ -24,6 +24,30 @@ async function getPageCopy(
return { french: copy(french), english: copy(english) };
}

export async function getCarousel(): Promise<CarouselPhoto[]> {
const payload = await getPayload({ config });
const [english, french] = await Promise.all(
locales.map((locale) =>
payload.findGlobal({
slug: "about-page",
locale,
depth: 1,
fallbackLocale: "en",
})
)
);
return (english.carousel ?? []).flatMap(({ photo, alt }, index) =>
typeof photo === "object" && photo.url
? [
{
src: photo.url,
alt: { english: alt, french: french.carousel?.[index]?.alt ?? alt },
},
]
: []
);
}

export const getAboutPage = () => getPageCopy("about-page");

export const getTourPage = () => getPageCopy("tour-page");
Expand Down
5 changes: 5 additions & 0 deletions src/lib/data/sheet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ export interface BilingualPage {
english: Page;
}

export interface CarouselPhoto {
src: string;
alt: { english: string; french: string };
}

async function getPage(tabGid: number): Promise<BilingualPage> {
const [french, english] = parsePageCsv(await fetchSheet(tabGid));
if (!french || !english) {
Expand Down
37 changes: 37 additions & 0 deletions src/lib/payload/compressImage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { imageMimeTypes, jpegQuality, maxImageSide } from "./imageLimits";

/** Resizes to at most maxImageSide on the long side (never enlarged) and re-encodes as JPEG with jSquash. */
export async function compressImage(file: File): Promise<File> {
if (!imageMimeTypes.includes(file.type)) return file;
const [{ default: encode }, { default: resize }] = await Promise.all([
import("@jsquash/jpeg/encode"),
import("@jsquash/resize"),
]);

const bitmap = await createImageBitmap(file);
const scale = Math.min(1, maxImageSide / Math.max(bitmap.width, bitmap.height));
const width = Math.round(bitmap.width * scale);
const height = Math.round(bitmap.height * scale);

const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
const context = canvas.getContext("2d");
if (!context) throw new Error("Canvas is not available");
context.fillStyle = "#ffffff";
context.fillRect(0, 0, bitmap.width, bitmap.height);
context.drawImage(bitmap, 0, 0);
bitmap.close();

let pixels = context.getImageData(0, 0, canvas.width, canvas.height);
if (scale < 1) pixels = await resize(pixels, { width, height });

const jpeg = await encode(pixels, {
quality: jpegQuality,
progressive: true,
});
if (jpeg.byteLength >= file.size && file.type === "image/jpeg") return file;

return new File([jpeg], file.name.replace(/\.[^.]+$/, "") + ".jpg", {
type: "image/jpeg",
lastModified: file.lastModified,
});
}
4 changes: 4 additions & 0 deletions src/lib/payload/imageLimits.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const maxImageSide = 2560;
export const jpegQuality = 80;
/** The formats both the browser and the server can re-encode as a still JPEG. */
export const imageMimeTypes = ["image/jpeg", "image/png", "image/webp"];
2 changes: 2 additions & 0 deletions src/lib/security/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ const routePolicies: { path: string; extra: Directives }[] = [
{
path: "admin",
extra: {
// jSquash's WebAssembly codecs compress photos in the browser before upload.
"script-src": ["'wasm-unsafe-eval'"],
"img-src": ["https://www.gravatar.com"],
"connect-src": storage,
"frame-src": ["'self'"],
Expand Down
Loading
Loading