diff --git a/app/api/font-file/[filename]/route.ts b/app/api/font-file/[filename]/route.ts new file mode 100644 index 0000000..e57e0f2 --- /dev/null +++ b/app/api/font-file/[filename]/route.ts @@ -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 }); + } +} diff --git a/app/api/generate-share/[id]/route.ts b/app/api/generate-share/[id]/route.ts index aa6dbfc..7216e96 100644 --- a/app/api/generate-share/[id]/route.ts +++ b/app/api/generate-share/[id]/route.ts @@ -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( @@ -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, diff --git a/app/api/generate/route.ts b/app/api/generate/route.ts index 917687b..529f6d3 100644 --- a/app/api/generate/route.ts +++ b/app/api/generate/route.ts @@ -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 { try { @@ -21,7 +21,7 @@ export async function GET(req: Request): Promise { } 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, @@ -52,7 +52,7 @@ export async function POST(req: Request): Promise { } 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, diff --git a/app/api/preview/route.ts b/app/api/preview/route.ts index 4206550..db21754 100644 --- a/app/api/preview/route.ts +++ b/app/api/preview/route.ts @@ -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) @@ -20,7 +20,7 @@ export async function GET(req: Request): Promise { 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, @@ -45,7 +45,7 @@ export async function POST(req: Request): Promise { }; 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, diff --git a/app/page.tsx b/app/page.tsx index 02eca1c..d499bd2 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -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 { try { @@ -18,6 +19,7 @@ async function getTemplates(): Promise { palette: template.palette ?? [], defaults: template.defaults, output: template.output, + fonts: template.fonts, }); } catch { // Skip invalid templates @@ -34,7 +36,16 @@ export default async function Home({ }: { searchParams: Promise>; }) { - 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 ; + } let initialParams: Record = rawParams; @@ -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); @@ -68,5 +80,5 @@ export default async function Home({ } } - return ; + return ; } diff --git a/components/FontSelect.tsx b/components/FontSelect.tsx new file mode 100644 index 0000000..01cf2e4 --- /dev/null +++ b/components/FontSelect.tsx @@ -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(null); + + // Unique families with their first available weight + const families = useMemo(() => { + const seen = new Set(); + 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 ( +
+ + + {open && ( +
+ {value && ( + + )} + {families.map(f => ( + + ))} +
+ )} +
+ ); +} diff --git a/components/GalleryPage.tsx b/components/GalleryPage.tsx new file mode 100644 index 0000000..087264d --- /dev/null +++ b/components/GalleryPage.tsx @@ -0,0 +1,33 @@ +import TemplateCard from '@/components/TemplateCard'; +import type { TemplateInfo } from '@/lib/types'; + +export default function GalleryPage({ templates }: { templates: TemplateInfo[] }) { + + return ( +
+
+ Slide Generator + + Éditeur → + +
+ +
+
+

Templates

+ {templates.length} templates +
+ +
+ {templates.map(t => ( + + ))} +
+ +
+
+ ); +} diff --git a/components/Playground.tsx b/components/Playground.tsx index c0ccc0b..868be6e 100644 --- a/components/Playground.tsx +++ b/components/Playground.tsx @@ -1,8 +1,9 @@ 'use client'; import { useState, useCallback, useEffect, useRef, useMemo, type ReactNode } from 'react'; -import type { TemplateInfo, ParamDef, StyleDef } from '@/lib/types'; +import type { TemplateInfo, ParamDef, StyleDef, FontDef } from '@/lib/types'; import { YamlEditor } from './YamlEditor'; +import { FontSelect } from './FontSelect'; import yaml from 'js-yaml'; function deepEqual(a: any, b: any): boolean { @@ -42,6 +43,7 @@ function copyStyleDef(style?: StyleDef): StyleDef { interface Props { templates: TemplateInfo[]; initialParams?: Record; + availableFonts?: FontDef[]; } type Tab = 'template' | 'free' | 'og' | 'images'; @@ -140,7 +142,7 @@ element: children: "{{ subtitle }}" `; -export function Playground({ templates, initialParams }: Props) { +export function Playground({ templates, initialParams, availableFonts = [] }: Props) { const initialTpl = initialParams?.template ? (templates.find(t => t.name === initialParams.template) ?? templates[0]) : templates[0]; @@ -615,7 +617,7 @@ export function Playground({ templates, initialParams }: Props) { {/* Header */}
- Slide Generator + Slide Generator v2
@@ -748,6 +750,7 @@ export function Playground({ templates, initialParams }: Props) { ; ogFields: { title: string; description: string; url: string }; copyToFreeLoading: boolean; @@ -999,7 +1004,7 @@ function TemplatePanel({ {selected && currentPalette.length > 0 && (

Defaults

- +
)} @@ -1035,6 +1040,7 @@ function TemplatePanel({ isValueModified={modifiedParamKeys.has(k)} onChange={(v) => onParamChange(k, v)} onStyleChange={(s) => onParamStyleChange(k, s)} + fontEntries={fontEntries} compact />
@@ -1057,6 +1063,7 @@ function TemplatePanel({ isValueModified={modifiedParamKeys.has(key)} onChange={(v) => onParamChange(key, v)} onStyleChange={(s) => onParamStyleChange(key, s)} + fontEntries={fontEntries} subParams={subParamEntries} subValues={Object.fromEntries(subParamEntries.map(([k]) => [k, params[k] ?? '']))} onSubParamChange={(k, v) => onParamChange(k, v)} @@ -1081,6 +1088,7 @@ function ParamField({ onChange, onStyleChange, compact = false, + fontEntries = [], subParams = [], subValues = {}, onSubParamChange, @@ -1095,6 +1103,7 @@ function ParamField({ onChange: (v: string) => void; onStyleChange?: (style: StyleDef) => void; compact?: boolean; + fontEntries?: FontDef[]; subParams?: Array<[string, ParamDef]>; subValues?: Record; onSubParamChange?: (key: string, value: string) => void; @@ -1224,6 +1233,7 @@ function ParamField({ def={d} value={subValues[k] ?? ''} palette={palette} + fontEntries={fontEntries} onChange={(v) => onSubParamChange?.(k, v)} compact /> @@ -1239,6 +1249,7 @@ function ParamField({ currentStyle={currentStyle ?? def.style} defaults={templateDefaults} palette={palette} + fontEntries={fontEntries} onStyleChange={onStyleChange} /> )} @@ -1253,10 +1264,12 @@ function ParamField({ function DefaultsPanel({ defaults, palette, + fontEntries = [], onDefaultsChange, }: { defaults: StyleDef; palette: string[]; + fontEntries?: FontDef[]; onDefaultsChange: (d: StyleDef) => void; }) { const weightOptions = [100, 200, 300, 400, 500, 600, 700, 800, 900]; @@ -1288,11 +1301,11 @@ function DefaultsPanel({
font - updateFont({ name: e.target.value || undefined })} - className={`${inputClass} w-32`} + fonts={fontEntries} + onChange={(name) => updateFont({ name })} + className="w-36" />
@@ -1327,12 +1340,14 @@ function StyleInfoPanel({ currentStyle, defaults, palette, + fontEntries = [], onStyleChange, }: { originalStyle: StyleDef; currentStyle: StyleDef; defaults?: StyleDef; palette: string[]; + fontEntries?: FontDef[]; onStyleChange?: (style: StyleDef) => void; }) { const td = defaults ?? {}; @@ -1400,12 +1415,12 @@ function StyleInfoPanel({ {isOverridden(ps.font?.name, td.font?.name) && ✱}font - updateFont({ name: e.target.value || undefined })} - className={`${inputClass} w-36`} + fonts={fontEntries} + onChange={(name) => updateFont({ name })} + className="w-36" />
diff --git a/components/TemplateCard.tsx b/components/TemplateCard.tsx new file mode 100644 index 0000000..19d1e77 --- /dev/null +++ b/components/TemplateCard.tsx @@ -0,0 +1,80 @@ +'use client'; +import { useState, useEffect, useCallback } from 'react'; +import type { TemplateInfo } from '@/lib/types'; + +function formatName(name: string): string { + return name.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase()); +} + +function Lightbox({ src, alt, onClose }: { src: string; alt: string; onClose: () => void }) { + useEffect(() => { + const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); }; + document.addEventListener('keydown', handler); + return () => document.removeEventListener('keydown', handler); + }, [onClose]); + + return ( +
+ {alt} e.stopPropagation()} + /> +
+ ); +} + +export default function TemplateCard({ template }: { template: TemplateInfo }) { + const { name, palette, output } = template; + const [lightboxOpen, setLightboxOpen] = useState(false); + const previewUrl = `/api/generate?template=${encodeURIComponent(name)}`; + const openLightbox = useCallback(() => setLightboxOpen(true), []); + const closeLightbox = useCallback(() => setLightboxOpen(false), []); + + return ( + <> + {lightboxOpen && } + +
+
+ {`Preview +
+ +
+

{formatName(name)}

+

{output.width} × {output.height}

+ +
+ {palette.slice(0, 6).map((color, i) => ( + + ))} +
+ + + Utiliser → + +
+
+ + ); +} diff --git a/fonts.yaml b/fonts.yaml index 3cf57b1..27e471e 100644 --- a/fonts.yaml +++ b/fonts.yaml @@ -25,3 +25,12 @@ fonts: - family: VT323 weights: [400] styles: [normal] + - family: Bungee + weights: [400] + styles: [normal] + - family: Audiowide + weights: [400] + styles: [normal] + - family: Russo One + weights: [400] + styles: [normal] diff --git a/lib/fonts.ts b/lib/fonts.ts index 176b687..267c5f8 100644 --- a/lib/fonts.ts +++ b/lib/fonts.ts @@ -1,5 +1,6 @@ import fs from 'fs'; import path from 'path'; +import { load } from 'js-yaml'; import type { FontDef } from './types'; export interface SatoriFont { @@ -9,6 +10,12 @@ export interface SatoriFont { style?: 'normal' | 'italic'; } +interface FontsYamlEntry { + family: string; + weights: number[]; + styles: string[]; +} + export async function loadFonts(fonts: FontDef[]): Promise { const results: SatoriFont[] = []; for (const font of fonts) { @@ -31,3 +38,36 @@ export async function loadFonts(fonts: FontDef[]): Promise { } return results; } + +function parseFontsYaml(): FontsYamlEntry[] { + const raw = fs.readFileSync(path.join(process.cwd(), 'fonts.yaml'), 'utf-8'); + return (load(raw) as { fonts: FontsYamlEntry[] }).fonts ?? []; +} + +export function listAllFontDefs(): FontDef[] { + const entries = parseFontsYaml(); + const defs: FontDef[] = []; + for (const entry of entries) { + const baseName = entry.family.replace(/ /g, ''); + for (const weight of entry.weights) { + for (const style of entry.styles) { + const suffix = style === 'italic' ? '-italic' : ''; + defs.push({ + family: entry.family, + path: `resources/fonts/${baseName}-${weight}${suffix}.ttf`, + weight, + style: style as 'normal' | 'italic', + }); + } + } + } + return defs; +} + +let _cachedAllFonts: SatoriFont[] | null = null; + +export async function loadAllFonts(): Promise { + if (_cachedAllFonts) return _cachedAllFonts; + _cachedAllFonts = await loadFonts(listAllFontDefs()); + return _cachedAllFonts; +} diff --git a/lib/types.ts b/lib/types.ts index 339ff69..145d283 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -78,5 +78,6 @@ export interface TemplateInfo { palette: string[]; defaults?: StyleDef; output: { width: number; height: number }; + fonts?: FontDef[]; yaml?: string; } diff --git a/next.config.ts b/next.config.ts index 443781f..46c58df 100644 --- a/next.config.ts +++ b/next.config.ts @@ -39,6 +39,8 @@ const nextConfig: NextConfig = { '/api/validate': ['./profiles/**/*'], '/view/[id]': ['./profiles/**/*', './resources/fonts/**/*'], '/api/generate-share/[id]': ['./profiles/**/*', './resources/fonts/**/*'], + '/api/font-file/[filename]': ['./resources/fonts/**/*'], + '/': ['./fonts.yaml'], }, };