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
27 changes: 27 additions & 0 deletions app/api/font-file/[filename]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { readFileSync } from 'fs';
import { join } from 'path';
import { type NextRequest } from 'next/server';

export async function GET(
_req: NextRequest,
{ params }: { params: Promise<{ filename: string }> }
) {
const { filename } = await params;

// Only allow safe filenames (alphanumeric, dashes, spaces, underscores, dots)
if (!/^[\w\-. ]+\.(?:ttf|otf)$/i.test(filename)) {
return new Response('Not found', { status: 404 });
}

try {
const data = readFileSync(join(process.cwd(), 'resources/fonts', filename));
return new Response(data, {
headers: {
'Content-Type': 'font/ttf',
'Cache-Control': 'public, max-age=31536000, immutable',
},
});
} catch {
return new Response('Not found', { status: 404 });
}
}
4 changes: 2 additions & 2 deletions app/api/generate-share/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { type NextRequest } from 'next/server';
import { loadShare } from '@/lib/share-store';
import { parseTemplate, expandSpecialElements } from '@/lib/loader';
import { loadFonts } from '@/lib/fonts';
import { loadAllFonts } from '@/lib/fonts';
import { ImageResponse } from 'next/og';

export async function GET(
Expand All @@ -22,7 +22,7 @@ export async function GET(
try { overlay = _overlay ? JSON.parse(_overlay) : {}; } catch { /* ignore */ }
const template = parseTemplate(_template, overlay);

const fonts = await loadFonts(template.fonts);
const fonts = await loadAllFonts();
const element = expandSpecialElements(template.element, template.palette, template.params, template.defaults);
return new ImageResponse(element as any, {
width: template.output.width,
Expand Down
6 changes: 3 additions & 3 deletions app/api/generate/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ImageResponse } from 'next/og';
import { loadTemplate, expandSpecialElements } from '@/lib/loader';
import { loadFonts } from '@/lib/fonts';
import { loadAllFonts } from '@/lib/fonts';

export async function GET(req: Request): Promise<Response> {
try {
Expand All @@ -21,7 +21,7 @@ export async function GET(req: Request): Promise<Response> {
}

const template = loadTemplate(templateName, params);
const fonts = await loadFonts(template.fonts);
const fonts = await loadAllFonts();
const element = expandSpecialElements(template.element, template.palette, template.params, template.defaults);
return new ImageResponse(element as any, {
width: template.output.width,
Expand Down Expand Up @@ -52,7 +52,7 @@ export async function POST(req: Request): Promise<Response> {
}

const template = loadTemplate(templateName, params);
const fonts = await loadFonts(template.fonts);
const fonts = await loadAllFonts();
const element = expandSpecialElements(template.element, template.palette, template.params, template.defaults);
return new ImageResponse(element as any, {
width: template.output.width,
Expand Down
6 changes: 3 additions & 3 deletions app/api/preview/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { loadTemplate, parseTemplate, expandSpecialElements } from '@/lib/loader';
import { loadFonts } from '@/lib/fonts';
import { loadAllFonts } from '@/lib/fonts';
import { ImageResponse } from 'next/og';

// GET /api/preview?template=simple&title=Hello → PNG (alias of /api/generate)
Expand All @@ -20,7 +20,7 @@ export async function GET(req: Request): Promise<Response> {

try {
const template = loadTemplate(templateName, params);
const fonts = await loadFonts(template.fonts);
const fonts = await loadAllFonts();
const element = expandSpecialElements(template.element, template.palette, template.params, template.defaults);
return new ImageResponse(element as any, {
width: template.output.width,
Expand All @@ -45,7 +45,7 @@ export async function POST(req: Request): Promise<Response> {
};

const template = parseTemplate(yamlStr, params);
const fonts = await loadFonts(template.fonts);
const fonts = await loadAllFonts();
const element = expandSpecialElements(template.element, template.palette, template.params, template.defaults);
return new ImageResponse(element as any, {
width: template.output.width,
Expand Down
18 changes: 15 additions & 3 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Playground } from '@/components/Playground';
import type { TemplateInfo } from '@/lib/types';
import GalleryPage from '@/components/GalleryPage';
import type { TemplateInfo, FontDef } from '@/lib/types';

async function getTemplates(): Promise<TemplateInfo[]> {
try {
Expand All @@ -18,6 +19,7 @@ async function getTemplates(): Promise<TemplateInfo[]> {
palette: template.palette ?? [],
defaults: template.defaults,
output: template.output,
fonts: template.fonts,
});
} catch {
// Skip invalid templates
Expand All @@ -34,7 +36,16 @@ export default async function Home({
}: {
searchParams: Promise<Record<string, string>>;
}) {
const [templates, rawParams] = await Promise.all([getTemplates(), searchParams]);
const { listAllFontDefs } = await import('@/lib/fonts');
const [templates, rawParams, allFontDefs] = await Promise.all([
getTemplates(),
searchParams,
Promise.resolve(listAllFontDefs()),
]);

if (!rawParams.template && !rawParams._share) {
return <GalleryPage templates={templates} />;
}

let initialParams: Record<string, string> = rawParams;

Expand All @@ -54,6 +65,7 @@ export default async function Home({
palette: parsed.palette ?? [],
defaults: parsed.defaults,
output: parsed.output,
fonts: parsed.fonts,
yaml: stored._template,
};
templates.unshift(customTemplate);
Expand All @@ -68,5 +80,5 @@ export default async function Home({
}
}

return <Playground templates={templates} initialParams={initialParams} />;
return <Playground templates={templates} initialParams={initialParams} availableFonts={allFontDefs} />;
}
108 changes: 108 additions & 0 deletions components/FontSelect.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
'use client';
import { useState, useRef, useEffect, useMemo } from 'react';
import type { FontDef } from '@/lib/types';

function familyToFilename(family: string): string {
return family.replace(/ /g, '');
}

interface Props {
value: string;
placeholder?: string;
fonts: FontDef[];
onChange: (name: string | undefined) => void;
className?: string;
}

export function FontSelect({ value, placeholder, fonts, onChange, className }: Props) {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);

// Unique families with their first available weight
const families = useMemo(() => {
const seen = new Set<string>();
const result: { family: string; weight: number }[] = [];
for (const f of fonts) {
if (!seen.has(f.family)) {
seen.add(f.family);
result.push({ family: f.family, weight: f.weight ?? 400 });
}
}
return result;
}, [fonts]);

// Inject @font-face for each unique family
useEffect(() => {
if (families.length === 0) return;
const style = document.createElement('style');
style.textContent = families
.map(f => {
const base = familyToFilename(f.family);
return `@font-face { font-family: "${f.family}"; font-weight: ${f.weight}; font-style: normal; src: url('/api/font-file/${base}-${f.weight}.ttf') format('truetype'); }`;
})
.join('\n');
document.head.appendChild(style);
return () => { document.head.removeChild(style); };
}, [families]);

// Close on outside click
useEffect(() => {
if (!open) return;
const handler = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
};
document.addEventListener('mousedown', handler);
return () => document.removeEventListener('mousedown', handler);
}, [open]);

const selectedEntry = families.find(f => f.family === value);
const inputCls =
'bg-gray-800 border border-gray-700 text-gray-100 rounded px-1.5 py-0.5 focus:outline-none focus:border-blue-500 font-mono text-[11px]';

return (
<div ref={ref} className={`relative ${className ?? ''}`}>
<button
type="button"
onClick={() => setOpen(o => !o)}
className={`${inputCls} flex items-center justify-between gap-1 min-w-0`}
>
<span
className="truncate"
style={
selectedEntry
? { fontFamily: `"${selectedEntry.family}"`, fontWeight: selectedEntry.weight, fontSize: 13 }
: undefined
}
>
{value || <span className="text-gray-500 font-mono text-[11px]">{placeholder ?? '—'}</span>}
</span>
<span className="text-gray-500 text-[9px] shrink-0 ml-1">▾</span>
</button>

{open && (
<div className="absolute z-50 top-full left-0 mt-0.5 min-w-full w-max bg-gray-800 border border-gray-700 rounded shadow-xl overflow-y-auto max-h-52">
{value && (
<button
className="w-full text-left px-2.5 py-1 text-[10px] text-gray-500 hover:bg-gray-700 border-b border-gray-700"
onClick={() => { onChange(undefined); setOpen(false); }}
>
— reset
</button>
)}
{families.map(f => (
<button
key={f.family}
className={`w-full text-left px-2.5 py-2 text-sm hover:bg-gray-700 transition-colors ${
value === f.family ? 'bg-gray-700 text-white' : 'text-gray-200'
}`}
style={{ fontFamily: `"${f.family}"`, fontWeight: f.weight }}
onClick={() => { onChange(f.family); setOpen(false); }}
>
{f.family}
</button>
))}
</div>
)}
</div>
);
}
33 changes: 33 additions & 0 deletions components/GalleryPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import TemplateCard from '@/components/TemplateCard';
import type { TemplateInfo } from '@/lib/types';

export default function GalleryPage({ templates }: { templates: TemplateInfo[] }) {

return (
<div className="min-h-screen bg-gray-950 text-gray-100">
<header className="sticky top-0 z-10 bg-gray-900 border-b border-gray-800 px-6 py-3 flex items-center justify-between">
<span className="text-lg font-semibold text-white">Slide Generator</span>
<a
href="/?template=post_top"
className="px-3 py-1.5 text-sm bg-emerald-700 hover:bg-emerald-600 text-white rounded-md transition-colors"
>
Éditeur →
</a>
</header>

<main className="max-w-7xl mx-auto px-6 py-10">
<div className="flex items-center justify-between mb-6">
<h1 className="text-xl font-semibold text-white">Templates</h1>
<span className="text-sm text-gray-400">{templates.length} templates</span>
</div>

<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{templates.map(t => (
<TemplateCard key={t.name} template={t} />
))}
</div>

</main>
</div>
);
}
Loading
Loading