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
66 changes: 59 additions & 7 deletions app/api/local-images/[...path]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export async function GET(
const getContentType = (path: string): string => {
const ext = path.toLowerCase().split('.').pop()
switch (ext) {
// Images
case 'jpg':
case 'jpeg':
return 'image/jpeg'
Expand All @@ -52,20 +53,71 @@ export async function GET(
return 'image/webp'
case 'svg':
return 'image/svg+xml'
// Documents
case 'pdf':
return 'application/pdf'
case 'doc':
return 'application/msword'
case 'docx':
return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
case 'ppt':
return 'application/vnd.ms-powerpoint'
case 'pptx':
return 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
case 'xls':
return 'application/vnd.ms-excel'
case 'xlsx':
return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
// Code/Text files
case 'txt':
return 'text/plain'
case 'sql':
return 'application/sql'
case 'cs':
return 'text/x-csharp'
case 'json':
return 'application/json'
case 'xml':
return 'application/xml'
case 'csv':
return 'text/csv'
// Media
case 'mp3':
return 'audio/mpeg'
case 'mp4':
return 'video/mp4'
// Other
case 'zip':
return 'application/zip'
case 'ics':
return 'text/calendar'
default:
return 'application/octet-stream'
}
}

const isDownloadableFile = (path: string): boolean => {
const ext = path.toLowerCase().split('.').pop() || ''
const downloadableExts = new Set(['pdf', 'txt', 'zip', 'mp4', 'mp3', 'ics', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'sql', 'cs', 'json', 'xml', 'csv'])
return downloadableExts.has(ext)
}

const mimeType = getContentType(fullImagePath)
const filename = fullImagePath.split(/[/\\]/).pop() || 'download'
const shouldDownload = isDownloadableFile(fullImagePath)

const headers: Record<string, string> = {
'Content-Type': mimeType,
'Content-Length': fileStat.size.toString(),
'Cache-Control': 'public, max-age=31536000, immutable',
}

// Add Content-Disposition header for downloadable files
if (shouldDownload) {
headers['Content-Disposition'] = `attachment; filename="${filename}"`
}

return new NextResponse(new Uint8Array(fileBuffer), {
headers: {
'Content-Type': mimeType,
'Content-Length': fileStat.size.toString(),
'Cache-Control': 'public, max-age=31536000, immutable', // Cache for development
},
})
return new NextResponse(new Uint8Array(fileBuffer), { headers })

} catch (error) {
console.error('Error serving local image:', error)
Expand Down
36 changes: 33 additions & 3 deletions components/typography-components.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,22 @@ const createHeading =
);
};

// File extensions that should be served as downloadable files
const DOWNLOADABLE_EXTS = new Set(["pdf", "txt", "zip", "mp4", "mp3", "ics", "doc", "docx", "ppt", "pptx", "xls", "xlsx", "sql", "cs", "json", "xml", "csv"]);

const isDownloadableFile = (href?: string): boolean => {
if (!href) return false;
const ext = href.split(".").pop()?.toLowerCase() || "";
return DOWNLOADABLE_EXTS.has(ext);
};

const getFilenameFromHref = (href: string): string => {
return href.split("/").pop() || "";
};

const rewriteUploadsToAssets = (href?: string) => {
const TINA_CLIENT_ID = process.env.NEXT_PUBLIC_TINA_CLIENT_ID || "";
const ALLOWED_EXTS = new Set(["pdf", "txt", "zip", "mp4", "mp3", "ics", "doc", "docx", "ppt", "pptx", "xls", "xlsx"]);
const ALLOWED_EXTS = DOWNLOADABLE_EXTS;

if (!href || !TINA_CLIENT_ID || !href.startsWith("/uploads/rules/")) {
return href;
Expand All @@ -63,9 +76,10 @@ const rewriteUploadsToAssets = (href?: string) => {
export const getTypographyComponents = (enableAnchors = false) => ({
p: (props: any) => <p className="mb-4" {...props} />,
a: (props: any) => {
let href = props?.url || props?.href || "";
href = rewriteUploadsToAssets(href);
const originalHref = props?.url || props?.href || "";
const href = rewriteUploadsToAssets(originalHref);
const isInternal = typeof href === "string" && href.startsWith("/") && !href.startsWith("//") && !href.startsWith("/_next");
const isDownloadable = isDownloadableFile(originalHref);

if (isInternal) {
return (
Expand All @@ -75,6 +89,22 @@ export const getTypographyComponents = (enableAnchors = false) => ({
);
}

// Add download attribute for downloadable files to trigger browser download
if (isDownloadable) {
const filename = getFilenameFromHref(originalHref);
return (
<a
className="underline hover:text-ssw-red"
href={href}
download={filename}
target="_blank"
rel="noopener noreferrer"
>
{props.children}
</a>
);
}

return (
<a className="underline hover:text-ssw-red" href={href} {...props}>
{props.children}
Expand Down
7 changes: 5 additions & 2 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@ export function middleware(request: NextRequest) {
// Check if this is an image request that might be from TinaCMS
// Only proxy content images from /uploads/rules/ to avoid interfering with site assets
const isTinaCMSImage = /^\/uploads\/rules\/.*\.(jpg|jpeg|png|gif|webp|svg)$/i.test(pathname)

if (isTinaCMSImage && process.env.LOCAL_CONTENT_RELATIVE_PATH) {

// Check if this is a downloadable file request from /uploads/rules/
const isDownloadableFile = /^\/uploads\/rules\/.*\.(pdf|txt|zip|mp4|mp3|ics|doc|docx|ppt|pptx|xls|xlsx|sql|cs|json|xml|csv)$/i.test(pathname)

if ((isTinaCMSImage || isDownloadableFile) && process.env.LOCAL_CONTENT_RELATIVE_PATH) {
// Proxy to our API route to serve from content repo
const url = request.nextUrl.clone()
url.pathname = `/api/local-images${pathname}`
Expand Down
Loading