Compare commits

..
5 Commits
13 changed files with 894 additions and 2572 deletions

No files matched your search

+480 -2461
View File
File diff suppressed because it is too large. Load diff
+13 -13
View File
@@ -6,6 +6,7 @@ import { shuffleArray } from "@lib/utils";
interface Props { interface Props {
images: Array<ImageMetadata>; images: Array<ImageMetadata>;
id?: string;
class: string; class: string;
altText?: string | ((index: number) => string); altText?: string | ((index: number) => string);
interval?: number; interval?: number;
@@ -23,6 +24,7 @@ interface Props {
const { const {
images, images,
id = "carousel",
class: className, class: className,
altText = null, altText = null,
interval = 5000, interval = 5000,
@@ -38,8 +40,6 @@ const {
shuffle = false shuffle = false
} = Astro.props as Props; } = Astro.props as Props;
const IDs: string[] = [];
const imagesArray = shuffle ? shuffleArray(images) : images; const imagesArray = shuffle ? shuffleArray(images) : images;
--- ---
@@ -50,12 +50,9 @@ const imagesArray = shuffle ? shuffleArray(images) : images;
{ {
imagesArray.map((image, index) => { imagesArray.map((image, index) => {
const ID = `image-carousel-${Math.random().toString(36)}`;
IDs.push(ID);
return ( return (
<Image <Image
data-id={`${ID}`} data-id={`${id}-${index}`}
class:list={[ class:list={[
"absolute !h-full w-full object-cover object-center transition-opacity", "absolute !h-full w-full object-cover object-center transition-opacity",
transitionStyle, transitionStyle,
@@ -89,16 +86,19 @@ const imagesArray = shuffle ? shuffleArray(images) : images;
<slot /> <slot />
</div> </div>
<script define:vars={{ imagesArray, interval, IDs }}> <script
define:vars={{ imageCount: imagesArray.length, carouselId: id, interval }}
>
let currentIndex = 0; let currentIndex = 0;
setInterval(() => { setInterval(() => {
const total = imagesArray.length;
const current = document.querySelectorAll( const current = document.querySelectorAll(
`[data-id="${IDs[currentIndex]}"]` `[data-id="${carouselId}-${currentIndex}"]`
)[0];
const nextIndex = (currentIndex + 1) % imageCount;
const next = document.querySelectorAll(
`[data-id="${carouselId}-${nextIndex}"]`
)[0]; )[0];
const nextIndex = (currentIndex + 1) % total;
const next = document.querySelectorAll(`[data-id="${IDs[nextIndex]}"]`)[0];
if (!current || !next) return; if (!current || !next) return;
@@ -109,9 +109,9 @@ const imagesArray = shuffle ? shuffleArray(images) : images;
next.classList.remove("opacity-0", "hidden"); next.classList.remove("opacity-0", "hidden");
next.setAttribute("aria-hidden", "false"); next.setAttribute("aria-hidden", "false");
const preloadIndex = (nextIndex + 1) % total; const preloadIndex = (nextIndex + 1) % imageCount;
const preloadImage = document.querySelectorAll( const preloadImage = document.querySelectorAll(
`[data-id="${IDs[preloadIndex]}"]` `[data-id="${carouselId}-${preloadIndex}"]`
)[0]; )[0];
if (preloadImage) { if (preloadImage) {
preloadImage.classList.add("opacity-0"); preloadImage.classList.add("opacity-0");
+263 -46
View File
@@ -35,7 +35,7 @@ const initialQueue = await Promise.all(
}) })
); );
const playerArtworkBlur = "10px"; const playerArtworkBlur = "15px";
const playerArtworkOpacity = 0.4; const playerArtworkOpacity = 0.4;
--- ---
@@ -62,6 +62,12 @@ const playerArtworkOpacity = 0.4;
</div> </div>
<div <div
id="player:time:progress" id="player:time:progress"
role="slider"
tabindex="0"
aria-label="Seek"
aria-valuemin="0"
aria-valuemax="100"
aria-valuenow="0"
class="relative top-0 right-0 left-0 m-0 h-2 w-full rounded-t p-0 hover:cursor-pointer" class="relative top-0 right-0 left-0 m-0 h-2 w-full rounded-t p-0 hover:cursor-pointer"
> >
<div <div
@@ -89,8 +95,7 @@ const playerArtworkOpacity = 0.4;
title="Minimise player" title="Minimise player"
aria-label="Minimise player" aria-label="Minimise player"
class="col-span-1 rounded-full px-3 py-1 text-gray-400 hover:cursor-pointer hover:text-white" class="col-span-1 rounded-full px-3 py-1 text-gray-400 hover:cursor-pointer hover:text-white"
> ><Icon name="fa7-solid:chevron-down" class="pointer-events-none" />
<Icon name="fa7-solid:chevron-down" class="pointer-events-none" />
</button> </button>
<span id="player:times:duration" class="col-span-1 text-right" <span id="player:times:duration" class="col-span-1 text-right"
>0:00</span >0:00</span
@@ -99,21 +104,72 @@ const playerArtworkOpacity = 0.4;
<div <div
class="flex h-full flex-row items-center justify-center align-middle" class="flex h-full flex-row items-center justify-center align-middle"
> >
<div class="m-0 flex grow-0 flex-row space-x-2 p-0 text-3xl"> <div class="m-0 flex grow-0 flex-col p-0">
<span> <div class="mt-2 flex flex-row items-center space-x-4 text-2xl">
<Icon name="fa7-solid:backward" id="player:controls:previous" /> <button
</span> type="button"
<span> id="player:controls:previous"
<Icon name="fa7-solid:play" id="player:controls:play" /> aria-label="Previous track"
<Icon class="rounded-full bg-transparent p-0 hover:cursor-pointer"
name="fa7-solid:pause" ><Icon name="fa7-solid:backward" class="pointer-events-none" />
</button>
<button
type="button"
id="player:controls:play"
aria-label="Play"
class="rounded-full bg-transparent p-0 hover:cursor-pointer"
><Icon name="fa7-solid:play" class="pointer-events-none" />
</button>
<button
type="button"
id="player:controls:pause" id="player:controls:pause"
class="hidden" aria-label="Pause"
/> class="hidden rounded-full bg-transparent p-0 hover:cursor-pointer"
</span> ><Icon name="fa7-solid:pause" class="pointer-events-none" />
<span> </button>
<Icon name="fa7-solid:forward" id="player:controls:next" /> <button
</span> type="button"
id="player:controls:next"
aria-label="Next track"
class="rounded-full bg-transparent p-0 hover:cursor-pointer"
><Icon name="fa7-solid:forward" class="pointer-events-none" />
</button>
</div>
<div
class="mt-3 flex hidden flex-row items-center space-x-2 pt-1 text-sm md:flex"
>
<span class="flex w-9 items-center justify-center">
<button
type="button"
id="player:controls:mute"
aria-label="Mute"
aria-pressed="false"
class="rounded-full bg-transparent p-0 hover:cursor-pointer"
>
<Icon
name="fa7-solid:volume-high"
id="player:controls:volume-on"
class="pointer-events-none"
/>
<Icon
name="fa7-solid:volume-xmark"
id="player:controls:volume-off"
class="pointer-events-none hidden"
/>
</button>
</span>
<span class="flex w-14 items-center md:w-16">
<input
type="range"
id="player:controls:volume"
aria-label="Volume"
min="0"
max="100"
value="100"
class="accent-primary w-full cursor-pointer"
/>
</span>
</div>
</div> </div>
<div class="flex flex-grow flex-col text-sm"> <div class="flex flex-grow flex-col text-sm">
<span <span
@@ -176,21 +232,26 @@ const playerArtworkOpacity = 0.4;
<button <button
id="player:face:controls:toggle" id="player:face:controls:toggle"
type="button" type="button"
title="Play / pause" title="Play"
aria-label="Play / pause" aria-label="Play"
class="absolute top-1/2 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full bg-black/55 text-white opacity-100 backdrop-blur-sm hover:cursor-pointer hover:bg-black/70 md:h-9 md:w-9 md:opacity-0 md:group-focus-within:opacity-100 md:group-hover:opacity-100" class="absolute top-1/2 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full bg-black/55 text-white opacity-100 backdrop-blur-sm hover:cursor-pointer hover:bg-black/70 md:h-9 md:w-9 md:opacity-0 md:group-focus-within:opacity-100 md:group-hover:opacity-100"
> ><Icon
<Icon
name="fa7-solid:play" name="fa7-solid:play"
id="player:face:controls:play" id="player:face:controls:play"
class="pointer-events-none text-sm drop-shadow" class="pointer-events-none text-sm drop-shadow"
/> /><Icon
<Icon
name="fa7-solid:pause" name="fa7-solid:pause"
id="player:face:controls:pause" id="player:face:controls:pause"
class="pointer-events-none hidden text-sm drop-shadow" class="pointer-events-none hidden text-sm drop-shadow"
/> />
</button> </button>
<button
id="player:face:controls:expand"
type="button"
aria-label="Expand player"
class="sr-only"
>Expand player
</button>
</div> </div>
</div> </div>
<div id="player:spacer" class:list={[height, "bg-gray-900"]}></div> <div id="player:spacer" class:list={[height, "bg-gray-900"]}></div>
@@ -237,6 +298,40 @@ const playerArtworkOpacity = 0.4;
display: none; display: none;
} }
/* Slim volume slider */
#player\:controls\:volume {
-webkit-appearance: none;
appearance: none;
background: transparent;
height: 12px;
}
#player\:controls\:volume::-webkit-slider-runnable-track {
height: 3px;
border-radius: 9999px;
background: rgba(255, 255, 255, 0.25);
}
#player\:controls\:volume::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 10px;
height: 10px;
margin-top: -3.5px;
border-radius: 9999px;
background: #ff2d00;
}
#player\:controls\:volume::-moz-range-track {
height: 3px;
border-radius: 9999px;
background: rgba(255, 255, 255, 0.25);
}
#player\:controls\:volume::-moz-range-thumb {
width: 10px;
height: 10px;
border: none;
border-radius: 9999px;
background: #ff2d00;
}
/* Outgoing layer fades fast, incoming fades in late */ /* Outgoing layer fades fast, incoming fades in late */
.player-full { .player-full {
transition: transition:
@@ -301,6 +396,11 @@ const playerArtworkOpacity = 0.4;
this.playlist = window.player?.playlist ?? playlist; this.playlist = window.player?.playlist ?? playlist;
this.index = window.player?.index ?? 0; this.index = window.player?.index ?? 0;
this.minimised = window.player?.minimised ?? false; this.minimised = window.player?.minimised ?? false;
// Seek fraction requested before anything was loaded.
this.pendingSeek = null;
// Playback volume (0-1); restored from storage below.
this.volume = 1;
this.lastVolume = 1;
this.RING_C = 182.2; // 2 * PI * 29, must match dasharray in markup this.RING_C = 182.2; // 2 * PI * 29, must match dasharray in markup
@@ -314,7 +414,11 @@ const playerArtworkOpacity = 0.4;
pause: $("player:controls:pause"), pause: $("player:controls:pause"),
previous: $("player:controls:previous"), previous: $("player:controls:previous"),
next: $("player:controls:next"), next: $("player:controls:next"),
minimise: $("player:controls:minimise") minimise: $("player:controls:minimise"),
mute: $("player:controls:mute"),
volumeOn: $("player:controls:volume-on"),
volumeOff: $("player:controls:volume-off"),
volume: $("player:controls:volume")
}, },
times: { times: {
current: $("player:times:current"), current: $("player:times:current"),
@@ -344,7 +448,8 @@ const playerArtworkOpacity = 0.4;
faceControls: { faceControls: {
toggle: $("player:face:controls:toggle"), toggle: $("player:face:controls:toggle"),
play: $("player:face:controls:play"), play: $("player:face:controls:play"),
pause: $("player:face:controls:pause") pause: $("player:face:controls:pause"),
expand: $("player:face:controls:expand")
} }
}; };
@@ -396,6 +501,25 @@ const playerArtworkOpacity = 0.4;
e.stopPropagation(); e.stopPropagation();
window.player.setminimised(true); window.player.setminimised(true);
}); });
this.UI.controls.mute.addEventListener("click", (e) => {
e.stopPropagation();
window.player.toggleMute();
});
this.UI.controls.volume.addEventListener("input", (e) => {
e.stopPropagation();
window.player.setVolume(e.target.value / 100);
});
try {
const stored = parseFloat(localStorage.getItem("player-volume"));
if (Number.isFinite(stored)) {
this.volume = Math.min(Math.max(stored, 0), 1);
this.lastVolume = this.volume > 0 ? this.volume : 1;
}
} catch (e) {
/* ignore */
}
this.syncVolumeUI();
this.UI.progress.bar.addEventListener("click", function (event) { this.UI.progress.bar.addEventListener("click", function (event) {
event.stopPropagation(); event.stopPropagation();
@@ -405,6 +529,34 @@ const playerArtworkOpacity = 0.4;
window.player.seek(Math.min(Math.max(per, 0), 1)); window.player.seek(Math.min(Math.max(per, 0), 1));
}); });
this.UI.progress.bar.addEventListener("keydown", (event) => {
if (
event.key !== "ArrowLeft" &&
event.key !== "ArrowRight" &&
event.key !== "Home" &&
event.key !== "End"
) {
return;
}
event.preventDefault();
event.stopPropagation();
const player = window.player;
const current = player.playlist[player.index];
if (!current) return;
const sound = current.howl;
const duration = sound?.duration() || 0 || current.duration || 0;
if (duration <= 0) return;
const position = sound
? sound.seek() || 0
: (player.pendingSeek ?? 0) * duration;
let target = position;
if (event.key === "ArrowLeft") target = position - 5;
if (event.key === "ArrowRight") target = position + 5;
if (event.key === "Home") target = 0;
if (event.key === "End") target = duration;
window.player.seek(duration > 0 ? target / duration : 0);
});
// Tap the circle to expand (not the play button). // Tap the circle to expand (not the play button).
const expand = (e) => { const expand = (e) => {
if (!window.player.minimised) return; if (!window.player.minimised) return;
@@ -414,12 +566,14 @@ const playerArtworkOpacity = 0.4;
) { ) {
return; return;
} }
if (e.type === "keydown" && e.key !== "Enter" && e.key !== " ") return;
e.preventDefault(); e.preventDefault();
window.player.setminimised(false); window.player.setminimised(false);
}; };
this.UI.root.addEventListener("click", expand); this.UI.root.addEventListener("click", expand);
this.UI.root.addEventListener("keydown", expand); this.UI.faceControls.expand.addEventListener("click", (e) => {
e.stopPropagation();
window.player.setminimised(false);
});
this.UI.faceControls.toggle.addEventListener("click", (e) => { this.UI.faceControls.toggle.addEventListener("click", (e) => {
e.stopPropagation(); e.stopPropagation();
const sound = window.player.playlist[window.player.index].howl; const sound = window.player.playlist[window.player.index].howl;
@@ -433,6 +587,38 @@ const playerArtworkOpacity = 0.4;
window.playerIsInitialised = true; window.playerIsInitialised = true;
} }
syncVolumeUI() {
Howler.volume(this.volume);
this.UI.controls.volume.value = String(Math.round(this.volume * 100));
const muted = this.volume <= 0;
this.UI.controls.volumeOn.classList.toggle("hidden", muted);
this.UI.controls.volumeOff.classList.toggle("hidden", !muted);
this.UI.controls.mute.setAttribute(
"aria-label",
muted ? "Unmute" : "Mute"
);
this.UI.controls.mute.setAttribute(
"aria-pressed",
muted ? "true" : "false"
);
try {
localStorage.setItem("player-volume", String(this.volume));
} catch (e) {
/* ignore */
}
}
setVolume(volume) {
if (!Number.isFinite(volume)) return;
this.volume = Math.min(Math.max(volume, 0), 1);
if (this.volume > 0) this.lastVolume = this.volume;
this.syncVolumeUI();
}
toggleMute() {
this.setVolume(this.volume > 0 ? 0 : this.lastVolume || 1);
}
setminimised(minimised) { setminimised(minimised) {
this.minimised = minimised; this.minimised = minimised;
try { try {
@@ -444,29 +630,17 @@ const playerArtworkOpacity = 0.4;
} }
// One class drives the morph; re-applying is a no-op. // One class drives the morph; re-applying is a no-op.
// Note: the shell stays a plain div so the face buttons inside it are
// never nested interactives; keyboard users get dedicated buttons.
applyminimised() { applyminimised() {
if (!this.UI.root) return; if (!this.UI.root) return;
if (this.minimised) { if (this.minimised) {
this.UI.root.classList.add("player--minimised"); this.UI.root.classList.add("player--minimised");
this.UI.root.setAttribute("role", "button");
this.UI.root.setAttribute("tabindex", "0");
this.UI.root.setAttribute(
"title",
"Expand player — click to restore full size"
);
this.UI.root.setAttribute(
"aria-label",
"Expand player — click to restore full size"
);
this.UI.spacer?.classList.add("player-spacer--hidden"); this.UI.spacer?.classList.add("player-spacer--hidden");
this.UI.full?.setAttribute("aria-hidden", "true"); this.UI.full?.setAttribute("aria-hidden", "true");
this.UI.face?.setAttribute("aria-hidden", "false"); this.UI.face?.setAttribute("aria-hidden", "false");
} else { } else {
this.UI.root.classList.remove("player--minimised"); this.UI.root.classList.remove("player--minimised");
this.UI.root.removeAttribute("role");
this.UI.root.removeAttribute("tabindex");
this.UI.root.removeAttribute("title");
this.UI.root.removeAttribute("aria-label");
this.UI.spacer?.classList.remove("player-spacer--hidden"); this.UI.spacer?.classList.remove("player-spacer--hidden");
this.UI.full?.removeAttribute("aria-hidden"); this.UI.full?.removeAttribute("aria-hidden");
this.UI.face?.setAttribute("aria-hidden", "true"); this.UI.face?.setAttribute("aria-hidden", "true");
@@ -506,6 +680,14 @@ const playerArtworkOpacity = 0.4;
set.pause.classList.toggle("hidden", !isPlaying); set.pause.classList.toggle("hidden", !isPlaying);
set.play.classList.toggle("hidden", isPlaying); set.play.classList.toggle("hidden", isPlaying);
} }
this.UI.faceControls.toggle?.setAttribute(
"aria-label",
isPlaying ? "Pause" : "Play"
);
this.UI.faceControls.toggle?.setAttribute(
"title",
isPlaying ? "Pause" : "Play"
);
} }
setRingProgress(el, per) { setRingProgress(el, per) {
@@ -559,6 +741,17 @@ const playerArtworkOpacity = 0.4;
// Begin playing the sound. // Begin playing the sound.
sound.play(); sound.play();
// Apply a seek requested before anything was loaded.
if (this.pendingSeek != null) {
const target = data.duration * this.pendingSeek;
this.pendingSeek = null;
if (sound.state() === "loaded") {
sound.seek(target);
} else {
sound.once("load", () => sound.seek(target));
}
}
// Update the track display. // Update the track display.
this.UI.metadata.title.textContent = data.metadata.title; this.UI.metadata.title.textContent = data.metadata.title;
this.UI.metadata.subtitle.textContent = data.metadata.subtitle; this.UI.metadata.subtitle.textContent = data.metadata.subtitle;
@@ -618,6 +811,9 @@ const playerArtworkOpacity = 0.4;
* @param {Number} index Index in the playlist. * @param {Number} index Index in the playlist.
*/ */
skipTo(index) { skipTo(index) {
// A pre-play seek belongs to the old track: drop it.
this.pendingSeek = null;
// Stop the current track. // Stop the current track.
if (this.playlist[this.index].howl) { if (this.playlist[this.index].howl) {
this.playlist[this.index].howl.stop(); this.playlist[this.index].howl.stop();
@@ -637,13 +833,30 @@ const playerArtworkOpacity = 0.4;
* @param {Number} per Percentage through the song to skip. * @param {Number} per Percentage through the song to skip.
*/ */
seek(per) { seek(per) {
// Get the Howl we want to manipulate. const entry = this.playlist[this.index];
var sound = this.playlist[this.index].howl; if (!entry) return;
const clamped = Math.min(Math.max(per, 0), 1);
const total = entry.duration || 0;
const target = total * clamped;
if (sound.playing()) { var sound = entry.howl;
// Convert the percent into a seek position. if (!sound) {
sound.seek(sound.duration() * per); // Nothing loaded yet: remember the request for play().
this.pendingSeek = clamped;
} else {
this.pendingSeek = null;
sound.seek((sound.duration() || total) * clamped);
} }
// Refresh the position display even when paused or unloaded.
this.UI.times.current.textContent = this.formatTime(Math.round(target));
const playedPer = total > 0 ? clamped : 0;
this.UI.progress.played.style.width = playedPer * 100 + "%";
this.UI.progress.bar.setAttribute(
"aria-valuenow",
String(Math.round(playedPer * 100))
);
this.setRingProgress(this.UI.faceProgress.played, playedPer);
} }
/** /**
@@ -657,6 +870,10 @@ const playerArtworkOpacity = 0.4;
this.UI.times.current.textContent = this.formatTime(Math.round(seek)); this.UI.times.current.textContent = this.formatTime(Math.round(seek));
const playedPer = seek / sound.duration() || 0; const playedPer = seek / sound.duration() || 0;
this.UI.progress.played.style.width = playedPer * 100 + "%"; this.UI.progress.played.style.width = playedPer * 100 + "%";
this.UI.progress.bar.setAttribute(
"aria-valuenow",
String(Math.round(playedPer * 100))
);
this.setRingProgress(this.UI.faceProgress.played, playedPer); this.setRingProgress(this.UI.faceProgress.played, playedPer);
const bufferedPercent = this.getBufferedAmount(sound).bufferedPercent; const bufferedPercent = this.getBufferedAmount(sound).bufferedPercent;
+5 -2
View File
@@ -6,6 +6,7 @@ interface Props extends HTMLAttributes<"span"> {
textColour?: String; textColour?: String;
size?: String; size?: String;
hover?: String; hover?: String;
as?: "span" | "button";
} }
const { const {
@@ -14,11 +15,13 @@ const {
size = "text-xs", size = "text-xs",
hover = "hover:bg-white hover:text-primary hover:ring-primary hover:ring-2", hover = "hover:bg-white hover:text-primary hover:ring-primary hover:ring-2",
class: className, class: className,
as: Tag = "span",
...attrs ...attrs
} = Astro.props as Props; } = Astro.props as Props;
--- ---
<span <Tag
type={Tag === "button" ? "button" : undefined}
class:list={[ class:list={[
"inline-block rounded px-2 py-1 font-bold uppercase", "inline-block rounded px-2 py-1 font-bold uppercase",
colour, colour,
@@ -27,5 +30,5 @@ const {
size, size,
hover hover
]} ]}
{...attrs}><slot /></span {...attrs}><slot /></Tag
> >
+7 -5
View File
@@ -20,7 +20,9 @@ if (!track.data.card) {
} }
--- ---
<div <button
type="button"
aria-label={`Play ${track.data.card.text.primary}`}
class:list={[ class:list={[
"relative flex min-h-42 flex-auto hover:cursor-pointer", "relative flex min-h-42 flex-auto hover:cursor-pointer",
index < 2 ? "lg:w-1/2" : "sm:w-1/2 md:w-1/3 lg:w-1/4" index < 2 ? "lg:w-1/2" : "sm:w-1/2 md:w-1/3 lg:w-1/4"
@@ -33,8 +35,8 @@ if (!track.data.card) {
class="h-full w-full object-cover" class="h-full w-full object-cover"
/> />
<div <span
class="bg-primary absolute inset-0 z-10 flex h-full w-full flex-col items-center justify-center p-16 text-center opacity-0 transition duration-300 hover:opacity-90" class="bg-primary absolute inset-0 z-10 flex h-full w-full flex-col items-center justify-center p-16 text-center opacity-0 transition duration-300 hover:opacity-90 focus-visible:opacity-90"
> >
<span class="text-md md:text-l block font-bold text-gray-100" <span class="text-md md:text-l block font-bold text-gray-100"
>{track.data.card.text.secondary}</span >{track.data.card.text.secondary}</span
@@ -42,5 +44,5 @@ if (!track.data.card) {
<span class="block text-xl font-extrabold uppercase md:text-2xl" <span class="block text-xl font-extrabold uppercase md:text-2xl"
>{track.data.card.text.primary}</span >{track.data.card.text.primary}</span
> >
</div> </span>
</div> </button>
+4 -2
View File
@@ -21,7 +21,9 @@ const fullFilePath = join(process.cwd(), "public", track.data.src);
const duration = await getAudioDurationInSeconds(fullFilePath); const duration = await getAudioDurationInSeconds(fullFilePath);
--- ---
<div <button
type="button"
aria-label={`Play ${track.data.metadata.title}`}
class:list={[ class:list={[
"text-primary flex items-center transition hover:cursor-pointer hover:text-gray-300", "text-primary flex items-center transition hover:cursor-pointer hover:text-gray-300",
className className
@@ -31,4 +33,4 @@ const duration = await getAudioDurationInSeconds(fullFilePath);
> >
<Icon name="fa7-solid:play-circle" class="mr-2 inline-block" /> <Icon name="fa7-solid:play-circle" class="mr-2 inline-block" />
<span class="inline-block">{track.data.metadata.title}</span> <span class="inline-block">{track.data.metadata.title}</span>
</div> </button>
+1 -1
View File
@@ -16,7 +16,7 @@ interface Window {
interface ImportMetaEnv { interface ImportMetaEnv {
readonly EMAIL_USER: string; readonly EMAIL_USER: string;
readonly EMAIL_PASS: string; readonly EMAIL_PASS: string;
readonly EMAIL_PORT: number; readonly EMAIL_PORT: string;
readonly EMAIL_SECURE: "true" | "false"; readonly EMAIL_SECURE: "true" | "false";
readonly EMAIL_HOST: string; readonly EMAIL_HOST: string;
readonly EMAIL_FROM: string; readonly EMAIL_FROM: string;
+24 -5
View File
@@ -11,14 +11,33 @@ interface Email {
name: string; name: string;
} }
export function constructEmailHtml(props: Email) { export function escapeHtml(input: string): string {
return `<div>${props.message}</div>`; return input
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
} }
export default async function (props: Email) { export function constructEmailHtml(props: Email) {
return `<div>${escapeHtml(props.message)}</div>`;
}
export default async function sendContactEmail(props: Email) {
const port = parseInt(
process.env.EMAIL_PORT || import.meta.env.EMAIL_PORT || "",
10
);
const fromMailbox =
process.env.EMAIL_FROM || import.meta.env.EMAIL_FROM || "";
if (!Number.isFinite(port) || !fromMailbox) {
throw new Error("Email transport is not configured.");
}
const transporter = createTransport({ const transporter = createTransport({
host: process.env.EMAIL_HOST || import.meta.env.EMAIL_HOST, host: process.env.EMAIL_HOST || import.meta.env.EMAIL_HOST,
port: process.env.EMAIL_PORT || import.meta.env.EMAIL_PORT, port,
secure: secure:
process.env.EMAIL_SECURE === "true" || process.env.EMAIL_SECURE === "true" ||
import.meta.env.EMAIL_SECURE === "true", import.meta.env.EMAIL_SECURE === "true",
@@ -33,7 +52,7 @@ export default async function (props: Email) {
} }
const message: Options = { const message: Options = {
from: `${props.name} (Website) <${process.env.EMAIL_FROM || import.meta.env.EMAIL_FROM}>`, from: `Website Contact <${fromMailbox}>`,
to: "nathan@nathancummins.com.au", to: "nathan@nathancummins.com.au",
replyTo: props.email, replyTo: props.email,
subject: props.subject, subject: props.subject,
+1
View File
@@ -14,6 +14,7 @@ const heroImagesArray = await convertEagerImagesImportGlobToArray(heroImages);
<MainLayout title="Oops! 404" navbarDisplay="transparent"> <MainLayout title="Oops! 404" navbarDisplay="transparent">
<div class="absolute inset-0 h-full w-full bg-black"> <div class="absolute inset-0 h-full w-full bg-black">
<ImageCarousel <ImageCarousel
id="not-found"
images={heroImagesArray} images={heroImagesArray}
class="h-full w-full" class="h-full w-full"
foreground={true} foreground={true}
+83 -34
View File
@@ -1,52 +1,101 @@
import sendEmail from "@lib/email"; import sendEmail, { escapeHtml } from "@lib/email";
import type { APIRoute } from "astro"; import type { APIRoute } from "astro";
export const prerender = false; export const prerender = false;
export const POST: APIRoute = async ({ request }) => { const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const MAX_NAME = 100;
const MAX_EMAIL = 254;
const MAX_SUBJECT = 150;
const MAX_MESSAGE = 5000;
// Minimal in-memory throttle (single instance): 5 sends per IP per 10 min.
const RATE_WINDOW_MS = 10 * 60 * 1000;
const RATE_MAX = 5;
const recentSends = new Map<string, number[]>();
function isRateLimited(ip: string): boolean {
const now = Date.now();
const history = (recentSends.get(ip) ?? []).filter(
(t) => now - t < RATE_WINDOW_MS
);
if (history.length >= RATE_MAX) {
return true;
}
history.push(now);
recentSends.set(ip, history);
return false;
}
function json(message: string, status: number, statusText: string): Response {
return new Response(JSON.stringify({ message }), {
status,
statusText,
headers: { "Content-Type": "application/json" }
});
}
export const POST: APIRoute = async ({ request, clientAddress }) => {
const ip =
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
clientAddress ||
"unknown";
if (isRateLimited(ip)) {
return json(
"Too many messages sent. Please try again later.",
429,
"Too Many Requests"
);
}
const data = await request.formData(); const data = await request.formData();
const email = data.get("email") as string | null; const email = (data.get("email") as string | null)?.trim() ?? "";
const subject = data.get("subject") as string | null; const subject = (data.get("subject") as string | null)?.trim() ?? "";
const message = data.get("message") as string | null; const message = (data.get("message") as string | null)?.trim() ?? "";
const name = data.get("name") as string | null; const name = (data.get("name") as string | null)?.trim() ?? "";
if (!email || !subject || !message || !name) { if (!email || !subject || !message || !name) {
return new Response( return json("Required field missing.", 400, "Bad Request");
JSON.stringify({ message: "Required field missing." }),
{
status: 400,
statusText: "Missing required fields."
}
);
} }
if (
!EMAIL_RE.test(email) ||
email.length > MAX_EMAIL ||
subject.length > MAX_SUBJECT ||
message.length > MAX_MESSAGE ||
name.length > MAX_NAME
) {
return json("Invalid field value.", 400, "Bad Request");
}
// Strip line breaks so values can never smuggle SMTP headers.
const safeSubject = subject.replace(/[\r\n]+/g, " ");
const safeName = name.replace(/[\r\n]+/g, " ");
const html = `<h1>Message Received via Contact Form</h1><br> const html = `<h1>Message Received via Contact Form</h1><br>
<b>Name</b>: ${name}<br> <b>Name</b>: ${escapeHtml(safeName)}<br>
<b>Email</b>: ${email}<br> <b>Email</b>: ${escapeHtml(email)}<br>
<b>Message</b>: ${message}`; <b>Message</b>: ${escapeHtml(message).replace(/\n/g, "<br>")}`;
try { try {
await sendEmail({ email, subject, message, name, html }); await sendEmail({
email,
subject: safeSubject,
message,
name: safeName,
html
});
} catch (error) { } catch (error) {
return new Response( return json(
JSON.stringify({ `Message failed to send with an internal server error. Please contact me directly via a method below.`,
message: `Message failed to send with an internal server error. Please contact me directly via a method below.` 500,
}), "Internal Server Error"
{
status: 500,
statusText: `Message failed to send with an internal server error. Please contact me directly via a method below.`
}
); );
} }
return new Response( return json(
JSON.stringify({ "Thanks for getting in touch! I will try to get back to you as soon as I can.",
message: 200,
"Thanks for getting in touch! I will try to get back to you as soon as I can." "OK"
}),
{
status: 200,
statusText: "OK"
}
); );
}; };
+3
View File
@@ -56,6 +56,7 @@ const tracks = (
<div class="h-screen w-full flex-row"> <div class="h-screen w-full flex-row">
<div class="absolute inset-0 h-full w-full bg-black"> <div class="absolute inset-0 h-full w-full bg-black">
<ImageCarousel <ImageCarousel
id="hero"
images={heroImagesArray} images={heroImagesArray}
class="h-full w-full" class="h-full w-full"
foreground={true} foreground={true}
@@ -108,6 +109,7 @@ const tracks = (
<section id="cta" class="text-white"> <section id="cta" class="text-white">
<div class="flex h-48 w-full items-center justify-center"> <div class="flex h-48 w-full items-center justify-center">
<ImageCarousel <ImageCarousel
id="cta"
images={imagesForCTAArray} images={imagesForCTAArray}
class="h-full w-full" class="h-full w-full"
foreground={true} foreground={true}
@@ -192,6 +194,7 @@ const tracks = (
<section id="fillerUntilServicesIsComplete" class="text-white"> <section id="fillerUntilServicesIsComplete" class="text-white">
<div class="flex h-96 w-full items-center justify-center"> <div class="flex h-96 w-full items-center justify-center">
<ImageCarousel <ImageCarousel
id="filler"
images={imagesForCTAArray} images={imagesForCTAArray}
class="h-full w-full" class="h-full w-full"
foreground={true} foreground={true}
+9 -3
View File
@@ -23,12 +23,16 @@ const types = [...new Set(projects.map((project) => project.data.type))];
<SectionTitle Tag="h1">Recent Projects</SectionTitle> <SectionTitle Tag="h1">Recent Projects</SectionTitle>
<div id="filter-tokens" class="my-8 space-y-2 space-x-2"> <div id="filter-tokens" class="my-8 space-y-2 space-x-2">
<Token <Token
as="button"
aria-pressed="true"
class="filter-token !text-primary ring-primary bg-white ring-2 hover:cursor-pointer" class="filter-token !text-primary ring-primary bg-white ring-2 hover:cursor-pointer"
data-type="all">All</Token data-type="all">All</Token
> >
{ {
types.map((type) => ( types.map((type) => (
<Token <Token
as="button"
aria-pressed="false"
class="filter-token hover:cursor-pointer" class="filter-token hover:cursor-pointer"
data-type={slugify(type)} data-type={slugify(type)}
> >
@@ -70,14 +74,15 @@ const types = [...new Set(projects.map((project) => project.data.type))];
const token = (e.target as Element).closest<HTMLElement>(".filter-token"); const token = (e.target as Element).closest<HTMLElement>(".filter-token");
if (!token) return; if (!token) return;
tokens.forEach((t) => tokens.forEach((t) => {
t.classList.remove( t.classList.remove(
"bg-white", "bg-white",
"!text-primary", "!text-primary",
"ring-primary", "ring-primary",
"ring-2" "ring-2"
) );
); t.setAttribute("aria-pressed", "false");
});
token.classList.add( token.classList.add(
"bg-white", "bg-white",
@@ -85,6 +90,7 @@ const types = [...new Set(projects.map((project) => project.data.type))];
"ring-primary", "ring-primary",
"ring-2" "ring-2"
); );
token.setAttribute("aria-pressed", "true");
const type = token.dataset.type; const type = token.dataset.type;
+1
View File
@@ -65,6 +65,7 @@ import P from "@components/MDX/P.astro";
<section id="title" class="text-white"> <section id="title" class="text-white">
<div class="flex h-100 w-full items-center justify-center"> <div class="flex h-100 w-full items-center justify-center">
<ImageCarousel <ImageCarousel
id="project-hero"
images={images} images={images}
class="h-full w-full" class="h-full w-full"
foreground={true} foreground={true}