Add audio attachments with a paperclip composer control and a styled timeline player

Hop-State: A_06FP9RVYP3SNM80AM7SMF98
Hop-Proposal: R_06FP9RTB5CCV1SZR9B7YSY0
Hop-Task: T_06FP9QHMNTRHD9BZ3B4BVMG
Hop-Attempt: AT_06FP9QHMNV944FQ20714908
This commit is contained in:
2026-07-15 01:27:38 -07:00
committed by Hop
parent d1442dc903
commit 7f8a97ffe2
8 changed files with 290 additions and 30 deletions
+5 -7
View File
@@ -3,18 +3,16 @@ import { z } from 'zod';
import { requireAuth } from '@/lib/auth'; import { requireAuth } from '@/lib/auth';
import { createUpload, StuffboxApiError } from '@/lib/stuffbox/client'; import { createUpload, StuffboxApiError } from '@/lib/stuffbox/client';
import { getStuffboxAccess } from '@/lib/stuffbox/tokens'; import { getStuffboxAccess } from '@/lib/stuffbox/tokens';
import { ALLOWED_MEDIA_TYPES, MAX_IMAGE_SIZE, MAX_AUDIO_SIZE, MAX_VIDEO_SIZE } from '@/lib/media/upload-policy';
const uploadSchema = z.object({ const uploadSchema = z.object({
filename: z.string().min(1).max(255), filename: z.string().min(1).max(255),
mimeType: z.enum([ mimeType: z.enum(ALLOWED_MEDIA_TYPES),
'image/jpeg', 'image/png', 'image/gif', 'image/webp', size: z.number().int().positive().max(Math.max(MAX_VIDEO_SIZE, MAX_AUDIO_SIZE)),
'video/mp4', 'video/webm', 'video/quicktime',
]),
size: z.number().int().positive().max(100 * 1024 * 1024),
sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(), sha256: z.string().regex(/^[a-f0-9]{64}$/).optional(),
}).superRefine((upload, context) => { }).superRefine((upload, context) => {
if (upload.mimeType.startsWith('image/') && upload.size > 10 * 1024 * 1024) { if (upload.mimeType.startsWith('image/') && upload.size > MAX_IMAGE_SIZE) {
context.addIssue({ code: 'too_big', maximum: 10 * 1024 * 1024, origin: 'number', inclusive: true, path: ['size'], message: 'Images must be 10MB or smaller' }); context.addIssue({ code: 'too_big', maximum: MAX_IMAGE_SIZE, origin: 'number', inclusive: true, path: ['size'], message: 'Images must be 10MB or smaller' });
} }
}); });
+7 -12
View File
@@ -4,11 +4,7 @@ import { requireAuth } from '@/lib/auth';
import { getStorageSession, createStorageSession } from '@/lib/storage/session'; import { getStorageSession, createStorageSession } from '@/lib/storage/session';
import { uploadWithStorageCredentials } from '@/lib/storage/s3'; import { uploadWithStorageCredentials } from '@/lib/storage/s3';
import { v4 as uuidv4 } from 'uuid'; import { v4 as uuidv4 } from 'uuid';
import { getMaxMediaSize, getMediaKind } from '@/lib/media/upload-policy';
const MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10MB for images
const MAX_VIDEO_SIZE = 100 * 1024 * 1024; // 100MB for videos
const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
const ALLOWED_VIDEO_TYPES = ['video/mp4', 'video/webm', 'video/quicktime'];
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
try { try {
@@ -24,20 +20,19 @@ export async function POST(req: NextRequest) {
} }
// Validate file type // Validate file type
const isImage = ALLOWED_IMAGE_TYPES.includes(file.type); const mediaKind = getMediaKind(file.type);
const isVideo = ALLOWED_VIDEO_TYPES.includes(file.type);
if (!isImage && !isVideo) { if (mediaKind === 'unsupported') {
return NextResponse.json({ return NextResponse.json({
error: 'Invalid file type. Allowed: JPEG, PNG, GIF, WebP, MP4, WebM, MOV' error: 'Invalid file type. Upload an image, video, MP3, M4A, AAC, WAV, OGG, or FLAC file.'
}, { status: 400 }); }, { status: 400 });
} }
// Validate file size based on type // Validate file size based on type
const maxSize = isVideo ? MAX_VIDEO_SIZE : MAX_IMAGE_SIZE; const maxSize = getMaxMediaSize(file.type);
if (file.size > maxSize) { if (maxSize !== null && file.size > maxSize) {
return NextResponse.json({ return NextResponse.json({
error: `File too large. Maximum size: ${isVideo ? '100MB' : '10MB'}` error: `File too large. Maximum size: ${mediaKind === 'image' ? '10MB' : '100MB'}`
}, { status: 400 }); }, { status: 400 });
} }
+97
View File
@@ -443,6 +443,79 @@ a.btn-primary:visited {
background: var(--background-tertiary); background: var(--background-tertiary);
} }
.post-media-item.audio {
grid-column: 1 / -1;
overflow: visible;
}
.audio-player {
display: flex;
align-items: center;
gap: 14px;
min-height: 92px;
padding: 16px;
border-radius: var(--radius-md);
background:
radial-gradient(circle at 10% 50%, color-mix(in srgb, var(--accent) 20%, transparent), transparent 42%),
var(--background-secondary);
}
.audio-player-toggle {
display: grid;
place-items: center;
flex: 0 0 48px;
width: 48px;
height: 48px;
padding: 0;
border: 0;
border-radius: 50%;
color: var(--background);
background: var(--accent);
cursor: pointer;
transition: transform 0.15s ease, filter 0.15s ease;
}
.audio-player-toggle:hover {
filter: brightness(1.08);
transform: scale(1.04);
}
.audio-player-body {
min-width: 0;
flex: 1;
}
.audio-player-title {
display: flex;
align-items: center;
gap: 7px;
margin-bottom: 9px;
overflow: hidden;
color: var(--foreground);
font-size: 14px;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.audio-player-progress {
display: block;
width: 100%;
height: 4px;
margin: 0;
accent-color: var(--accent);
cursor: pointer;
}
.audio-player-time {
display: flex;
justify-content: space-between;
margin-top: 7px;
color: var(--foreground-tertiary);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.post-media-item img { .post-media-item img {
width: 100%; width: 100%;
height: auto; height: auto;
@@ -716,6 +789,30 @@ a.btn-primary:visited {
display: block; display: block;
} }
.compose-media-item.audio {
width: min(100%, 320px);
max-height: none;
}
.compose-audio-preview {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
height: 80px;
padding: 0 38px 0 14px;
color: var(--foreground-secondary);
background: color-mix(in srgb, var(--accent) 8%, var(--background-tertiary));
}
.compose-audio-preview span {
overflow: hidden;
font-size: 13px;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.compose-media-remove { .compose-media-remove {
position: absolute; position: absolute;
top: 4px; top: 4px;
+81
View File
@@ -0,0 +1,81 @@
'use client';
import { useRef, useState } from 'react';
import { Music2, Pause, Play } from 'lucide-react';
interface AudioPlayerProps {
src: string;
title?: string;
}
function formatTime(value: number): string {
if (!Number.isFinite(value) || value < 0) return '0:00';
const minutes = Math.floor(value / 60);
const seconds = Math.floor(value % 60);
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
export function AudioPlayer({ src, title = 'Audio track' }: AudioPlayerProps) {
const audioRef = useRef<HTMLAudioElement>(null);
const [isPlaying, setIsPlaying] = useState(false);
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);
const togglePlayback = async () => {
const audio = audioRef.current;
if (!audio) return;
if (audio.paused) {
await audio.play();
} else {
audio.pause();
}
};
const seek = (value: number) => {
const audio = audioRef.current;
if (!audio) return;
audio.currentTime = value;
setCurrentTime(value);
};
return (
<div className="audio-player" onClick={(event) => event.stopPropagation()}>
<audio
ref={audioRef}
src={src}
preload="metadata"
onLoadedMetadata={(event) => setDuration(event.currentTarget.duration)}
onDurationChange={(event) => setDuration(event.currentTarget.duration)}
onTimeUpdate={(event) => setCurrentTime(event.currentTarget.currentTime)}
onPlay={() => setIsPlaying(true)}
onPause={() => setIsPlaying(false)}
onEnded={() => setIsPlaying(false)}
/>
<button
type="button"
className="audio-player-toggle"
onClick={togglePlayback}
aria-label={isPlaying ? `Pause ${title}` : `Play ${title}`}
>
{isPlaying ? <Pause size={20} fill="currentColor" /> : <Play size={20} fill="currentColor" />}
</button>
<div className="audio-player-body">
<div className="audio-player-title"><Music2 size={15} /> {title}</div>
<input
className="audio-player-progress"
type="range"
min={0}
max={duration || 0}
step="0.1"
value={Math.min(currentTime, duration || 0)}
onChange={(event) => seek(Number(event.target.value))}
aria-label={`Seek ${title}`}
/>
<div className="audio-player-time">
<span>{formatTime(currentTime)}</span>
<span>{formatTime(duration)}</span>
</div>
</div>
</div>
);
}
+15 -7
View File
@@ -3,15 +3,17 @@
import { useState, useEffect, useRef } from 'react'; import { useState, useEffect, useRef } from 'react';
import AutoTextarea from '@/components/AutoTextarea'; import AutoTextarea from '@/components/AutoTextarea';
import { Post, Attachment } from '@/lib/types'; import { Post, Attachment } from '@/lib/types';
import { ImageIcon, AlertTriangle, Film } from 'lucide-react'; import { AlertTriangle, Music2, Paperclip } from 'lucide-react';
import { VideoEmbed } from '@/components/VideoEmbed'; import { VideoEmbed } from '@/components/VideoEmbed';
import { useFormattedHandle } from '@/lib/utils/handle'; import { useFormattedHandle } from '@/lib/utils/handle';
import { useAuth } from '@/lib/contexts/AuthContext'; import { useAuth } from '@/lib/contexts/AuthContext';
import { StorageConfigurationPrompt } from '@/components/StorageConfigurationPrompt'; import { StorageConfigurationPrompt } from '@/components/StorageConfigurationPrompt';
import { getStorageProvider, MediaUploadError, uploadMediaFile } from '@/lib/stuffbox/browser-upload'; import { getStorageProvider, MediaUploadError, uploadMediaFile } from '@/lib/stuffbox/browser-upload';
import { getMediaKind } from '@/lib/media/upload-policy';
interface MediaAttachment extends Attachment { interface MediaAttachment extends Attachment {
mimeType?: string; mimeType?: string;
filename?: string;
} }
interface ComposeProps { interface ComposeProps {
@@ -142,6 +144,7 @@ export function Compose({ onPost, replyingTo, onCancelReply, placeholder = "What
url: media.url, url: media.url,
altText: media.altText ?? null, altText: media.altText ?? null,
mimeType: media.mimeType ?? file.type, mimeType: media.mimeType ?? file.type,
filename: file.name,
}); });
} catch (error) { } catch (error) {
if (error instanceof MediaUploadError && error.code === 'STORAGE_NOT_CONFIGURED') { if (error instanceof MediaUploadError && error.code === 'STORAGE_NOT_CONFIGURED') {
@@ -229,11 +232,16 @@ export function Compose({ onPost, replyingTo, onCancelReply, placeholder = "What
{attachments.length > 0 && ( {attachments.length > 0 && (
<div className="compose-media-grid"> <div className="compose-media-grid">
{attachments.map((item) => { {attachments.map((item) => {
const isVideo = item.mimeType?.startsWith('video/'); const mediaKind = getMediaKind(item.mimeType);
return ( return (
<div className="compose-media-item" key={item.id}> <div className={`compose-media-item ${mediaKind === 'audio' ? 'audio' : ''}`} key={item.id}>
{isVideo ? ( {mediaKind === 'video' ? (
<video src={item.url} muted playsInline preload="metadata" /> <video src={item.url} muted playsInline preload="metadata" />
) : mediaKind === 'audio' ? (
<div className="compose-audio-preview">
<Music2 size={22} />
<span>{item.filename || 'Audio track'}</span>
</div>
) : ( ) : (
<img src={item.url} alt={item.altText || 'Upload preview'} /> <img src={item.url} alt={item.altText || 'Upload preview'} />
)} )}
@@ -324,16 +332,16 @@ export function Compose({ onPost, replyingTo, onCancelReply, placeholder = "What
<button <button
type="button" type="button"
className="compose-media-button" className="compose-media-button"
title="Add media" title="Attach media"
onClick={handleAddMedia} onClick={handleAddMedia}
disabled={isUploading || isCheckingStorage || attachments.length >= 4} disabled={isUploading || isCheckingStorage || attachments.length >= 4}
> >
{isUploading || isCheckingStorage ? '...' : <ImageIcon size={20} />} {isUploading || isCheckingStorage ? '...' : <Paperclip size={20} />}
</button> </button>
<input <input
ref={mediaInputRef} ref={mediaInputRef}
type="file" type="file"
accept="image/*,video/mp4,video/webm,video/quicktime" accept="image/*,video/mp4,video/webm,video/quicktime,audio/mpeg,audio/mp4,audio/aac,audio/wav,audio/ogg,audio/flac"
multiple multiple
onChange={handleMediaSelect} onChange={handleMediaSelect}
disabled={isUploading || attachments.length >= 4} disabled={isUploading || attachments.length >= 4}
+10 -3
View File
@@ -16,6 +16,8 @@ import { useDomain } from '@/lib/contexts/ConfigContext';
import { signedAPI } from '@/lib/api/signed-fetch'; import { signedAPI } from '@/lib/api/signed-fetch';
import type { LinkPreviewData } from '@/lib/media/linkPreview'; import type { LinkPreviewData } from '@/lib/media/linkPreview';
import { AvatarImage } from '@/components/AvatarImage'; import { AvatarImage } from '@/components/AvatarImage';
import { AudioPlayer } from '@/components/AudioPlayer';
import { getMediaKind } from '@/lib/media/upload-policy';
// Component for link preview image that hides on error // Component for link preview image that hides on error
function LinkPreviewImage({ src, alt }: { src: string; alt: string }) { function LinkPreviewImage({ src, alt }: { src: string; alt: string }) {
@@ -879,10 +881,10 @@ export function PostCard({ post, onLike, onRepost, onComment, onDelete, onHide,
{post.media && post.media.length > 0 && ( {post.media && post.media.length > 0 && (
<div className="post-media-grid"> <div className="post-media-grid">
{post.media.map((item) => { {post.media.map((item) => {
const isVideo = item.mimeType?.startsWith('video/'); const mediaKind = getMediaKind(item.mimeType);
return ( return (
<div className="post-media-item" key={item.id}> <div className={`post-media-item ${mediaKind === 'audio' ? 'audio' : ''}`} key={item.id}>
{isVideo ? ( {mediaKind === 'video' ? (
<BlurredVideo <BlurredVideo
src={item.url} src={item.url}
onClick={(e) => { onClick={(e) => {
@@ -891,6 +893,11 @@ export function PostCard({ post, onLike, onRepost, onComment, onDelete, onHide,
video.muted = !video.muted; video.muted = !video.muted;
}} }}
/> />
) : mediaKind === 'audio' ? (
<AudioPlayer
src={item.url}
title={`Audio by ${post.author.displayName || post.author.handle}`}
/>
) : ( ) : (
<BlurredImage <BlurredImage
src={item.url} src={item.url}
+21
View File
@@ -0,0 +1,21 @@
import { describe, expect, it } from 'vitest';
import { getMaxMediaSize, getMediaKind, MAX_AUDIO_SIZE, MAX_IMAGE_SIZE } from './upload-policy';
describe('media upload policy', () => {
it('recognizes common audio formats used for music uploads', () => {
expect(getMediaKind('audio/mpeg')).toBe('audio');
expect(getMediaKind('audio/wav')).toBe('audio');
expect(getMediaKind('audio/flac')).toBe('audio');
expect(getMediaKind('audio/mp4')).toBe('audio');
});
it('keeps images on the smaller limit and allows larger audio tracks', () => {
expect(getMaxMediaSize('image/png')).toBe(MAX_IMAGE_SIZE);
expect(getMaxMediaSize('audio/mpeg')).toBe(MAX_AUDIO_SIZE);
});
it('rejects unrelated file types', () => {
expect(getMediaKind('application/pdf')).toBe('unsupported');
expect(getMaxMediaSize('application/pdf')).toBeNull();
});
});
+53
View File
@@ -0,0 +1,53 @@
export const ALLOWED_IMAGE_TYPES = [
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
] as const;
export const ALLOWED_VIDEO_TYPES = [
'video/mp4',
'video/webm',
'video/quicktime',
] as const;
export const ALLOWED_AUDIO_TYPES = [
'audio/mpeg',
'audio/mp3',
'audio/mp4',
'audio/x-m4a',
'audio/aac',
'audio/wav',
'audio/x-wav',
'audio/ogg',
'audio/flac',
'audio/x-flac',
] as const;
export const ALLOWED_MEDIA_TYPES = [
...ALLOWED_IMAGE_TYPES,
...ALLOWED_VIDEO_TYPES,
...ALLOWED_AUDIO_TYPES,
] as const;
export const MAX_IMAGE_SIZE = 10 * 1024 * 1024;
export const MAX_VIDEO_SIZE = 100 * 1024 * 1024;
export const MAX_AUDIO_SIZE = 100 * 1024 * 1024;
export type MediaKind = 'image' | 'video' | 'audio' | 'unsupported';
export function getMediaKind(mimeType?: string | null): MediaKind {
if (!mimeType) return 'unsupported';
if ((ALLOWED_IMAGE_TYPES as readonly string[]).includes(mimeType)) return 'image';
if ((ALLOWED_VIDEO_TYPES as readonly string[]).includes(mimeType)) return 'video';
if ((ALLOWED_AUDIO_TYPES as readonly string[]).includes(mimeType)) return 'audio';
return 'unsupported';
}
export function getMaxMediaSize(mimeType: string): number | null {
const kind = getMediaKind(mimeType);
if (kind === 'image') return MAX_IMAGE_SIZE;
if (kind === 'video') return MAX_VIDEO_SIZE;
if (kind === 'audio') return MAX_AUDIO_SIZE;
return null;
}