refactor(ascii): align layout and UX with Calculate blueprint

Rewrites all four ASCII tool components to share the same design
language and spatial structure as the Calculator & Grapher tool.

Layout
- New responsive 2/5–3/5 grid (was fixed 2+1 col); matches Calculate
- Left panel: text input card + font selector filling remaining height
- Right panel: preview as the dominant full-height element
- Mobile: tabbed Editor / Preview switcher (same pattern as Calculator)

TextInput
- Replace shadcn Textarea with native <textarea>
- Glass border pattern (border-border/40, focus:border-primary/50)
- Monospace font, consistent counter styling

FontSelector
- Replace Card + shadcn Tabs + Button + Input + Empty with native elements
- Glass panel (glass rounded-xl) matching Calculate panel style
- Custom tab strip mirrors Calculator mobile tab pattern
- Native search input with glass border
- Font list items: border-l-2 left accent for selected state,
  hover:bg-primary/8, rose heart for favorites
- Auto-scrolls selected item into view on external changes
- Simplified empty state to single italic line

FontPreview
- Replace Card + Button + Badge + ToggleGroup + Tooltip + Empty
- Glass panel with header row (label + font tag + action buttons)
- Controls row: native toggle buttons with primary/10 active state
- Terminal window: dark #06060e background, macOS-style chrome
  (rose/amber/emerald dots), font name watermark — the hero element
- PNG export captures entire terminal including chrome at 2x
- Inline skeleton loader with pulse animation replaces Skeleton import

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-01 07:46:21 +01:00
parent d161aeba72
commit 141ab1f4e3
4 changed files with 419 additions and 396 deletions

View File

@@ -11,7 +11,9 @@ import { addRecentFont } from '@/lib/storage/favorites';
import { decodeFromUrl, updateUrl, getShareableUrl } from '@/lib/utils/urlSharing';
import { toast } from 'sonner';
import type { ASCIIFont } from '@/types/ascii';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/card';
import { cn } from '@/lib/utils';
type Tab = 'editor' | 'preview';
export function ASCIIConverter() {
const [text, setText] = React.useState('ASCII');
@@ -19,13 +21,11 @@ export function ASCIIConverter() {
const [asciiArt, setAsciiArt] = React.useState('');
const [fonts, setFonts] = React.useState<ASCIIFont[]>([]);
const [isLoading, setIsLoading] = React.useState(false);
const [tab, setTab] = React.useState<Tab>('editor');
const commentedTextRef = React.useRef('');
// Load fonts and check URL params on mount
React.useEffect(() => {
getFontList().then(setFonts);
// Check for URL parameters
const urlState = decodeFromUrl();
if (urlState) {
if (urlState.text) setText(urlState.text);
@@ -33,57 +33,45 @@ export function ASCIIConverter() {
}
}, []);
// Generate ASCII art
const generateAsciiArt = React.useMemo(
() => debounce(async (inputText: string, fontName: string) => {
if (!inputText) {
setAsciiArt('');
setIsLoading(false);
return;
}
setIsLoading(true);
try {
const result = await textToAscii(inputText, fontName);
setAsciiArt(result);
} catch (error) {
console.error('Error generating ASCII art:', error);
setAsciiArt('Error generating ASCII art. Please try a different font.');
} finally {
setIsLoading(false);
}
}, 300),
() =>
debounce(async (inputText: string, fontName: string) => {
if (!inputText) {
setAsciiArt('');
setIsLoading(false);
return;
}
setIsLoading(true);
try {
const result = await textToAscii(inputText, fontName);
setAsciiArt(result);
} catch {
setAsciiArt('Error generating ASCII art. Please try a different font.');
} finally {
setIsLoading(false);
}
}, 300),
[]
);
// Trigger generation when text or font changes
React.useEffect(() => {
generateAsciiArt(text, selectedFont);
// Track recent fonts
if (selectedFont) {
addRecentFont(selectedFont);
}
// Update URL
if (selectedFont) addRecentFont(selectedFont);
updateUrl(text, selectedFont);
}, [text, selectedFont, generateAsciiArt]);
// Copy to clipboard
const handleCopy = async () => {
if (!asciiArt) return;
try {
await navigator.clipboard.writeText(commentedTextRef.current || asciiArt);
toast.success('Copied to clipboard!');
} catch (error) {
console.error('Failed to copy:', error);
} catch {
toast.error('Failed to copy');
}
};
// Download as text file
const handleDownload = () => {
if (!asciiArt) return;
const blob = new Blob([commentedTextRef.current || asciiArt], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
@@ -95,69 +83,101 @@ export function ASCIIConverter() {
URL.revokeObjectURL(url);
};
// Share (copy URL to clipboard)
const handleShare = async () => {
const shareUrl = getShareableUrl(text, selectedFont);
try {
await navigator.clipboard.writeText(shareUrl);
await navigator.clipboard.writeText(getShareableUrl(text, selectedFont));
toast.success('Shareable URL copied!');
} catch (error) {
console.error('Failed to copy URL:', error);
} catch {
toast.error('Failed to copy URL');
}
};
// Random font
const handleRandomFont = () => {
if (fonts.length === 0) return;
const randomIndex = Math.floor(Math.random() * fonts.length);
setSelectedFont(fonts[randomIndex].name);
toast.info(`Random font: ${fonts[randomIndex].name}`);
if (!fonts.length) return;
const font = fonts[Math.floor(Math.random() * fonts.length)];
setSelectedFont(font.name);
toast.info(`Font: ${font.name}`);
};
return (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6 items-stretch lg:max-h-[800px]">
{/* Left Column - Input and Preview */}
<div className="lg:col-span-2 space-y-6 overflow-y-auto custom-scrollbar">
<Card>
<CardHeader>
<CardTitle>Text</CardTitle>
</CardHeader>
<CardContent>
<div className="flex flex-col gap-4">
{/* ── Mobile tab switcher ────────────────────────────────── */}
<div className="flex lg:hidden glass rounded-xl p-1 gap-1">
{(['editor', 'preview'] as Tab[]).map((t) => (
<button
key={t}
onClick={() => setTab(t)}
className={cn(
'flex-1 py-2.5 rounded-lg text-sm font-medium capitalize transition-all',
tab === t
? 'bg-primary text-primary-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'
)}
>
{t === 'editor' ? 'Editor' : 'Preview'}
</button>
))}
</div>
{/* ── Main layout ────────────────────────────────────────── */}
<div
className="grid grid-cols-1 lg:grid-cols-5 gap-4"
style={{ height: 'calc(100svh - 220px)', minHeight: '620px' }}
>
{/* Left panel: text input + font selector */}
<div
className={cn(
'lg:col-span-2 flex flex-col gap-3 overflow-hidden',
tab !== 'editor' && 'hidden lg:flex'
)}
>
{/* Text input */}
<div className="glass rounded-xl p-4 shrink-0">
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest block mb-2">
Text
</span>
<TextInput
value={text}
onChange={setText}
placeholder="Type your text here..."
placeholder="Type your text here"
/>
</CardContent>
</Card>
</div>
{/* Font selector — fills remaining height */}
<div className="flex-1 min-h-0 overflow-hidden">
<FontSelector
fonts={fonts}
selectedFont={selectedFont}
onSelectFont={setSelectedFont}
onRandomFont={handleRandomFont}
className="h-full"
/>
</div>
</div>
<FontPreview
text={asciiArt}
font={selectedFont}
isLoading={isLoading}
onCopy={handleCopy}
onDownload={handleDownload}
onShare={handleShare}
onCommentedTextChange={React.useCallback((t: string) => { commentedTextRef.current = t; }, [])}
/>
</div>
{/* Right Column - Font Selector */}
<div className="lg:col-span-1 h-[500px] lg:h-auto relative">
<div className="lg:absolute lg:inset-0 h-full">
<FontSelector
fonts={fonts}
selectedFont={selectedFont}
onSelectFont={setSelectedFont}
onRandomFont={handleRandomFont}
className="h-full"
{/* Right panel: preview */}
<div
className={cn(
'lg:col-span-3 flex flex-col overflow-hidden',
tab !== 'preview' && 'hidden lg:flex'
)}
>
<FontPreview
text={asciiArt}
font={selectedFont}
isLoading={isLoading}
onCopy={handleCopy}
onDownload={handleDownload}
onShare={handleShare}
onCommentedTextChange={React.useCallback(
(t: string) => { commentedTextRef.current = t; },
[]
)}
/>
</div>
</div>
</div>
);
}

View File

@@ -2,11 +2,6 @@
import * as React from 'react';
import { toPng } from 'html-to-image';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import {
Select,
SelectContent,
@@ -15,18 +10,16 @@ import {
SelectValue,
} from '@/components/ui/select';
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip';
import {
Empty,
EmptyDescription,
EmptyHeader,
EmptyMedia,
EmptyTitle,
} from "@/components/ui/empty"
import { Copy, Download, Share2, Image as ImageIcon, AlignLeft, AlignCenter, AlignRight, Type, MessageSquareCode } from 'lucide-react';
Copy,
Download,
Share2,
Image as ImageIcon,
AlignLeft,
AlignCenter,
AlignRight,
MessageSquareCode,
Type,
} from 'lucide-react';
import { cn } from '@/lib/utils/cn';
import { toast } from 'sonner';
@@ -34,12 +27,12 @@ export type CommentStyle = 'none' | '//' | '#' | '--' | ';' | '/* */' | '<!-- --
const COMMENT_STYLES: { value: CommentStyle; label: string }[] = [
{ value: 'none', label: 'None' },
{ value: '//', label: '// C, JS, Go' },
{ value: '#', label: '# Python, Shell' },
{ value: '--', label: '-- SQL, Lua' },
{ value: ';', label: '; Lisp, ASM' },
{ value: '/* */', label: '/* */ Block' },
{ value: '<!-- -->', label: '<!-- --> HTML' },
{ value: '//', label: '// C / JS / Go' },
{ value: '#', label: '# Python / Shell' },
{ value: '--', label: '-- SQL / Lua' },
{ value: ';', label: '; Lisp / ASM' },
{ value: '/* */', label: '/* Block */' },
{ value: '<!-- -->', label: '<!-- HTML -->' },
{ value: '"""', label: '""" Docstring' },
];
@@ -51,9 +44,9 @@ function applyCommentStyle(text: string, style: CommentStyle): string {
case '#':
case '--':
case ';':
return lines.map(line => `${style} ${line}`).join('\n');
return lines.map((l) => `${style} ${l}`).join('\n');
case '/* */':
return ['/*', ...lines.map(line => ` * ${line}`), ' */'].join('\n');
return ['/*', ...lines.map((l) => ` * ${l}`), ' */'].join('\n');
case '<!-- -->':
return ['<!--', ...lines, '-->'].join('\n');
case '"""':
@@ -73,14 +66,39 @@ export interface FontPreviewProps {
}
type TextAlign = 'left' | 'center' | 'right';
type FontSize = 'xs' | 'sm' | 'base';
export function FontPreview({ text, font, isLoading, onCopy, onDownload, onShare, onCommentedTextChange, className }: FontPreviewProps) {
const previewRef = React.useRef<HTMLDivElement>(null);
const ALIGN_OPTS: { value: TextAlign; icon: React.ElementType; label: string }[] = [
{ value: 'left', icon: AlignLeft, label: 'Left' },
{ value: 'center', icon: AlignCenter, label: 'Center' },
{ value: 'right', icon: AlignRight, label: 'Right' },
];
const SIZE_OPTS: { value: FontSize; label: string }[] = [
{ value: 'xs', label: 'xs' },
{ value: 'sm', label: 'sm' },
{ value: 'base', label: 'md' },
];
export function FontPreview({
text,
font,
isLoading,
onCopy,
onDownload,
onShare,
onCommentedTextChange,
className,
}: FontPreviewProps) {
const terminalRef = React.useRef<HTMLDivElement>(null);
const [textAlign, setTextAlign] = React.useState<TextAlign>('left');
const [fontSize, setFontSize] = React.useState<'xs' | 'sm' | 'base'>('sm');
const [fontSize, setFontSize] = React.useState<FontSize>('sm');
const [commentStyle, setCommentStyle] = React.useState<CommentStyle>('none');
const commentedText = React.useMemo(() => applyCommentStyle(text, commentStyle), [text, commentStyle]);
const commentedText = React.useMemo(
() => applyCommentStyle(text, commentStyle),
[text, commentStyle]
);
const lineCount = commentedText ? commentedText.split('\n').length : 0;
const charCount = commentedText ? commentedText.length : 0;
@@ -89,183 +107,181 @@ export function FontPreview({ text, font, isLoading, onCopy, onDownload, onShare
}, [commentedText, onCommentedTextChange]);
const handleExportPNG = async () => {
if (!previewRef.current || !text) return;
if (!terminalRef.current || !text) return;
try {
const dataUrl = await toPng(previewRef.current, {
backgroundColor: getComputedStyle(previewRef.current).backgroundColor,
const dataUrl = await toPng(terminalRef.current, {
backgroundColor: '#06060e',
pixelRatio: 2,
});
const link = document.createElement('a');
link.download = `ascii-${font || 'export'}-${Date.now()}.png`;
link.href = dataUrl;
link.click();
toast.success('Exported as PNG!');
} catch (error) {
console.error('Failed to export PNG:', error);
} catch {
toast.error('Failed to export PNG');
}
};
const actionBtn =
'flex items-center gap-1 px-2.5 py-1 text-xs glass rounded-md border border-border/30 text-muted-foreground hover:text-primary hover:border-primary/30 hover:bg-primary/10 transition-all';
return (
<Card className={cn('relative', className)}>
<CardHeader className="flex flex-row items-center justify-between flex-wrap gap-2">
<div className={cn('glass rounded-xl p-4 flex flex-col gap-3 flex-1 min-h-0 overflow-hidden', className)}>
{/* ── Header: label + font tag + export actions ─────────── */}
<div className="flex items-center justify-between gap-2 shrink-0 flex-wrap">
<div className="flex items-center gap-2">
<CardTitle>Preview</CardTitle>
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
Preview
</span>
{font && (
<Badge className="text-[10px] font-mono">
<span className="px-2 py-0.5 rounded-md bg-primary/10 text-primary text-[10px] font-mono border border-primary/20">
{font}
</Badge>
</span>
)}
</div>
<div className="flex gap-1.5 flex-wrap">
<div className="flex items-center gap-1.5 flex-wrap">
{onCopy && (
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="xs" onClick={onCopy}>
<Copy className="h-3 w-3 mr-1" />
Copy
</Button>
</TooltipTrigger>
<TooltipContent>Copy to clipboard</TooltipContent>
</Tooltip>
<button onClick={onCopy} className={actionBtn}>
<Copy className="w-3 h-3" /> Copy
</button>
)}
{onShare && (
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="xs" onClick={onShare}>
<Share2 className="h-3 w-3 mr-1" />
Share
</Button>
</TooltipTrigger>
<TooltipContent>Copy shareable URL</TooltipContent>
</Tooltip>
<button onClick={onShare} className={actionBtn}>
<Share2 className="w-3 h-3" /> Share
</button>
)}
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="xs" onClick={handleExportPNG}>
<ImageIcon className="h-3 w-3 mr-1" />
PNG
</Button>
</TooltipTrigger>
<TooltipContent>Export as PNG</TooltipContent>
</Tooltip>
<button onClick={handleExportPNG} className={actionBtn}>
<ImageIcon className="w-3 h-3" /> PNG
</button>
{onDownload && (
<Tooltip>
<TooltipTrigger asChild>
<Button variant="outline" size="xs" onClick={onDownload}>
<Download className="h-3 w-3 mr-1" />
TXT
</Button>
</TooltipTrigger>
<TooltipContent>Download as text file</TooltipContent>
</Tooltip>
<button onClick={onDownload} className={actionBtn}>
<Download className="w-3 h-3" /> TXT
</button>
)}
</div>
</CardHeader>
<CardContent className="space-y-3">
{/* Controls */}
<div className="flex items-center gap-2 flex-wrap">
<ToggleGroup
type="single"
value={textAlign}
onValueChange={(v) => v && setTextAlign(v as TextAlign)}
variant="outline"
size="sm"
disabled={commentStyle !== 'none'}
>
<ToggleGroupItem value="left" aria-label="Align left" className="px-1.5">
<AlignLeft className="h-3 w-3" />
</ToggleGroupItem>
<ToggleGroupItem value="center" aria-label="Align center" className="px-1.5">
<AlignCenter className="h-3 w-3" />
</ToggleGroupItem>
<ToggleGroupItem value="right" aria-label="Align right" className="px-1.5">
<AlignRight className="h-3 w-3" />
</ToggleGroupItem>
</ToggleGroup>
</div>
<ToggleGroup
type="single"
value={fontSize}
onValueChange={(v) => v && setFontSize(v as 'xs' | 'sm' | 'base')}
variant="outline"
size="sm"
>
<ToggleGroupItem value="xs" aria-label="Extra small font" className="px-1.5 text-[10px] uppercase">
xs
</ToggleGroupItem>
<ToggleGroupItem value="sm" aria-label="Small font" className="px-1.5 text-[10px] uppercase">
sm
</ToggleGroupItem>
<ToggleGroupItem value="base" aria-label="Medium font" className="px-1.5 text-[10px] uppercase">
md
</ToggleGroupItem>
</ToggleGroup>
{/* ── Controls: alignment · size · comment style ─────────── */}
<div className="flex items-center gap-2 shrink-0 flex-wrap">
{/* Alignment */}
<div className="flex items-center gap-0.5">
{ALIGN_OPTS.map(({ value, icon: Icon, label }) => (
<button
key={value}
onClick={() => setTextAlign(value)}
disabled={commentStyle !== 'none'}
title={label}
className={cn(
'px-2 py-1 rounded-md transition-all border text-xs',
textAlign === value && commentStyle === 'none'
? 'bg-primary/10 border-primary/30 text-primary'
: 'glass border-transparent text-muted-foreground/55 hover:text-foreground hover:border-border/40',
commentStyle !== 'none' && 'opacity-30 cursor-not-allowed'
)}
>
<Icon className="w-3 h-3" />
</button>
))}
</div>
<Select value={commentStyle} onValueChange={(v) => setCommentStyle(v as CommentStyle)}>
<SelectTrigger size="sm" className="h-8 w-auto gap-1 text-xs">
<MessageSquareCode className="h-3 w-3 text-foreground shrink-0" />
<SelectValue />
</SelectTrigger>
<SelectContent>
{COMMENT_STYLES.map((s) => (
<SelectItem key={s.value} value={s.value}>
{s.label}
</SelectItem>
))}
</SelectContent>
</Select>
{/* Font size */}
<div className="flex items-center gap-0.5">
{SIZE_OPTS.map(({ value, label }) => (
<button
key={value}
onClick={() => setFontSize(value)}
className={cn(
'px-2 py-1 text-[10px] font-mono rounded-md transition-all border uppercase',
fontSize === value
? 'bg-primary/10 border-primary/30 text-primary'
: 'glass border-transparent text-muted-foreground/55 hover:text-foreground hover:border-border/40'
)}
>
{label}
</button>
))}
</div>
{!isLoading && text && (
<div className="flex gap-2 text-[10px] text-muted-foreground ml-auto">
<span>{lineCount} lines</span>
<span>{charCount} chars</span>
</div>
{/* Comment style */}
<Select value={commentStyle} onValueChange={(v) => setCommentStyle(v as CommentStyle)}>
<SelectTrigger className="h-7 w-auto gap-1.5 text-xs border-border/30 bg-transparent hover:border-primary/30 transition-colors">
<MessageSquareCode className="w-3 h-3 text-muted-foreground/60 shrink-0" />
<SelectValue />
</SelectTrigger>
<SelectContent>
{COMMENT_STYLES.map((s) => (
<SelectItem key={s.value} value={s.value}>
{s.label}
</SelectItem>
))}
</SelectContent>
</Select>
{/* Stats */}
{!isLoading && text && (
<span className="ml-auto text-[10px] text-muted-foreground/30 font-mono tabular-nums">
{lineCount}L · {charCount}C
</span>
)}
</div>
{/* ── Terminal window ────────────────────────────────────── */}
<div
ref={terminalRef}
className="flex-1 min-h-0 flex flex-col rounded-xl overflow-hidden border border-white/5"
style={{ background: '#06060e' }}
>
{/* Terminal chrome */}
<div className="flex items-center gap-1.5 px-3.5 py-2 border-b border-white/5 shrink-0">
<div className="w-2.5 h-2.5 rounded-full bg-rose-500/55" />
<div className="w-2.5 h-2.5 rounded-full bg-amber-400/55" />
<div className="w-2.5 h-2.5 rounded-full bg-emerald-500/55" />
{font && (
<span className="ml-2 text-[10px] font-mono text-white/20 tracking-wider select-none">
{font}
</span>
)}
</div>
{/* Content */}
<div
ref={previewRef}
className={cn(
'relative min-h-[200px] bg-muted/50 rounded-lg p-4 overflow-x-auto',
commentStyle === 'none' && textAlign === 'center' && 'text-center',
commentStyle === 'none' && textAlign === 'right' && 'text-right'
)}
className="flex-1 overflow-auto p-4 scrollbar-thin scrollbar-thumb-white/8 scrollbar-track-transparent"
style={{ textAlign: commentStyle === 'none' ? textAlign : 'left' }}
>
{isLoading ? (
<div className="space-y-3">
<Skeleton className="h-6 w-3/4" />
<Skeleton className="h-6 w-full" />
<Skeleton className="h-6 w-5/6" />
<Skeleton className="h-6 w-2/3" />
<Skeleton className="h-6 w-full" />
<Skeleton className="h-6 w-4/5" />
<div className="space-y-2 animate-pulse">
{[0.7, 1, 0.85, 0.55, 1, 0.9, 0.75].map((w, i) => (
<div
key={i}
className="h-3.5 rounded-sm bg-white/5"
style={{ width: `${w * 100}%` }}
/>
))}
</div>
) : text ? (
<pre className={cn(
'font-mono whitespace-pre overflow-x-auto animate-in',
fontSize === 'xs' && 'text-[10px]',
fontSize === 'sm' && 'text-xs sm:text-sm',
fontSize === 'base' && 'text-sm sm:text-base'
)}>
<pre
className={cn(
'font-mono whitespace-pre text-white/85 leading-snug',
fontSize === 'xs' && 'text-[9px]',
fontSize === 'sm' && 'text-[11px] sm:text-xs',
fontSize === 'base' && 'text-xs sm:text-sm'
)}
>
{commentedText}
</pre>
) : (
<Empty>
<EmptyHeader>
<EmptyMedia variant="icon">
<Type />
</EmptyMedia>
<EmptyTitle>Start typing to see your ASCII art</EmptyTitle>
<EmptyDescription>Enter text in the input field above to generate ASCII art with the selected font</EmptyDescription>
</EmptyHeader>
</Empty>
<div className="h-full flex flex-col items-center justify-center gap-2 text-center">
<Type className="w-6 h-6 text-white/10" />
<p className="text-xs text-white/20 font-mono">
Start typing to see your ASCII art
</p>
</div>
)}
</div>
</CardContent>
</Card>
</div>
</div>
);
}

View File

@@ -2,19 +2,8 @@
import * as React from 'react';
import Fuse from 'fuse.js';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
Empty,
EmptyDescription,
EmptyHeader,
EmptyMedia,
EmptyTitle,
} from "@/components/ui/empty"
import { Search, X, Heart, Clock, List, Shuffle } from 'lucide-react';
import { cn } from '@/lib/utils/cn';
import { Button } from '@/components/ui/button';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import type { ASCIIFont } from '@/types/ascii';
import { getFavorites, getRecentFonts, toggleFavorite, isFavorite } from '@/lib/storage/favorites';
@@ -28,62 +17,52 @@ export interface FontSelectorProps {
type FilterType = 'all' | 'favorites' | 'recent';
const FILTERS: { value: FilterType; icon: React.ElementType; label: string }[] = [
{ value: 'all', icon: List, label: 'All' },
{ value: 'favorites', icon: Heart, label: 'Fav' },
{ value: 'recent', icon: Clock, label: 'Recent' },
];
export function FontSelector({
fonts,
selectedFont,
onSelectFont,
onRandomFont,
className
className,
}: FontSelectorProps) {
const [searchQuery, setSearchQuery] = React.useState('');
const [filter, setFilter] = React.useState<FilterType>('all');
const [favorites, setFavorites] = React.useState<string[]>([]);
const [recentFonts, setRecentFonts] = React.useState<string[]>([]);
const searchInputRef = React.useRef<HTMLInputElement>(null);
const selectedRef = React.useRef<HTMLButtonElement>(null);
// Load favorites and recent fonts
React.useEffect(() => {
setFavorites(getFavorites());
setRecentFonts(getRecentFonts());
}, []);
// Initialize Fuse.js for fuzzy search
const fuse = React.useMemo(() => {
return new Fuse(fonts, {
keys: ['name', 'fileName'],
threshold: 0.3,
includeScore: true,
});
}, [fonts]);
// Keep selected item in view when font changes externally (e.g. random)
React.useEffect(() => {
selectedRef.current?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}, [selectedFont]);
const fuse = React.useMemo(
() => new Fuse(fonts, { keys: ['name', 'fileName'], threshold: 0.3, includeScore: true }),
[fonts]
);
const filteredFonts = React.useMemo(() => {
let fontsToFilter = fonts;
// Apply category filter
let base = fonts;
if (filter === 'favorites') {
fontsToFilter = fonts.filter(f => favorites.includes(f.name));
base = fonts.filter((f) => favorites.includes(f.name));
} else if (filter === 'recent') {
fontsToFilter = fonts.filter(f => recentFonts.includes(f.name));
// Sort by recent order
fontsToFilter.sort((a, b) => {
return recentFonts.indexOf(a.name) - recentFonts.indexOf(b.name);
});
base = [...fonts.filter((f) => recentFonts.includes(f.name))].sort(
(a, b) => recentFonts.indexOf(a.name) - recentFonts.indexOf(b.name)
);
}
// Apply search query
if (!searchQuery) return fontsToFilter;
const results = fuse.search(searchQuery);
const searchResults = results.map(result => result.item);
// Filter search results by category
if (filter === 'favorites') {
return searchResults.filter(f => favorites.includes(f.name));
} else if (filter === 'recent') {
return searchResults.filter(f => recentFonts.includes(f.name));
}
return searchResults;
if (!searchQuery) return base;
const hits = fuse.search(searchQuery).map((r) => r.item);
return filter === 'all' ? hits : hits.filter((f) => base.includes(f));
}, [fonts, searchQuery, fuse, filter, favorites, recentFonts]);
const handleToggleFavorite = (fontName: string, e: React.MouseEvent) => {
@@ -92,134 +71,140 @@ export function FontSelector({
setFavorites(getFavorites());
};
return (
<Card className={cn("flex flex-col min-h-0 overflow-hidden", className)}>
<CardHeader className="flex flex-row items-center justify-between flex-wrap gap-2 space-y-0">
<CardTitle>Fonts</CardTitle>
{onRandomFont && (
<Button
variant="outline"
size="xs"
onClick={onRandomFont}
title="Random font"
>
<Shuffle className="h-3 w-3 mr-1" />
Random
</Button>
)}
</CardHeader>
<CardContent className="flex flex-col flex-1 min-h-0 pt-0">
<Tabs
value={filter}
onValueChange={(v) => setFilter(v as FilterType)}
className="mb-3 shrink-0"
>
<TabsList className="w-full">
<TabsTrigger value="all" className="flex-1">
<List className="h-3 w-3" />
All
</TabsTrigger>
<TabsTrigger value="favorites" className="flex-1">
<Heart className="h-3 w-3" />
Fav
</TabsTrigger>
<TabsTrigger value="recent" className="flex-1">
<Clock className="h-3 w-3" />
Recent
</TabsTrigger>
</TabsList>
</Tabs>
const emptyMessage =
filter === 'favorites'
? 'No favorites yet — click ♥ to save'
: filter === 'recent'
? 'No recent fonts'
: searchQuery
? 'No fonts match your search'
: 'Loading fonts…';
{/* Search Input */}
<div className="relative mb-3 shrink-0">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none" />
<Input
ref={searchInputRef}
type="text"
placeholder="Search fonts..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-8 pr-8 h-8 text-sm"
/>
{searchQuery && (
return (
<div className={cn('glass rounded-xl p-3 flex flex-col min-h-0 overflow-hidden', className)}>
{/* ── Header ────────────────────────────────────────────── */}
<div className="flex items-center justify-between mb-3 shrink-0">
<span className="text-[10px] font-semibold text-muted-foreground uppercase tracking-widest">
Fonts
</span>
<div className="flex items-center gap-2.5">
<span className="text-[10px] text-muted-foreground/35 font-mono tabular-nums">
{fonts.length}
</span>
{onRandomFont && (
<button
onClick={() => setSearchQuery('')}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
aria-label="Clear search"
onClick={onRandomFont}
className="text-muted-foreground/50 hover:text-primary transition-colors"
title="Random font"
>
<X className="h-3.5 w-3.5" />
<Shuffle className="w-3.5 h-3.5" />
</button>
)}
</div>
</div>
{/* Font List */}
<div className="flex-1 overflow-y-auto space-y-0.5 pr-1 scrollbar">
{filteredFonts.length === 0 ? (
<Empty>
<EmptyHeader>
<EmptyMedia variant="icon">
{filter === 'favorites' ? <Heart /> : (filter === 'recent' ? <Clock /> : <Search />)}
</EmptyMedia>
<EmptyTitle>{
filter === 'favorites'
? 'No favorite fonts yet'
: filter === 'recent'
? 'No recent fonts'
: 'No fonts found'
}</EmptyTitle>
<EmptyDescription>
{
filter === 'favorites'
? 'Click the heart icon on any font to add it to your favorites'
: filter === 'recent'
? 'Fonts you use will appear here'
: searchQuery
? 'Try a different search term'
: 'Loading fonts...'
}
</EmptyDescription>
</EmptyHeader>
</Empty>
) : (
filteredFonts.map((font) => (
{/* ── Filter tabs ───────────────────────────────────────── */}
<div className="flex glass rounded-lg p-0.5 gap-0.5 mb-3 shrink-0">
{FILTERS.map(({ value, icon: Icon, label }) => (
<button
key={value}
onClick={() => setFilter(value)}
className={cn(
'flex-1 flex items-center justify-center gap-1.5 py-1.5 rounded-md text-xs font-medium transition-all',
filter === value
? 'bg-primary text-primary-foreground shadow-sm'
: 'text-muted-foreground hover:text-foreground'
)}
>
<Icon className="w-3 h-3" />
{label}
</button>
))}
</div>
{/* ── Search ────────────────────────────────────────────── */}
<div className="relative mb-3 shrink-0">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-3 h-3 text-muted-foreground/40 pointer-events-none" />
<input
type="text"
placeholder="Search fonts…"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full bg-transparent border border-border/40 rounded-lg pl-8 pr-7 py-1.5 text-xs font-mono outline-none focus:border-primary/50 transition-colors placeholder:text-muted-foreground/30"
/>
{searchQuery && (
<button
onClick={() => setSearchQuery('')}
className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground/40 hover:text-muted-foreground transition-colors"
>
<X className="w-3 h-3" />
</button>
)}
</div>
{/* ── Font list ─────────────────────────────────────────── */}
<div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin scrollbar-thumb-primary/20 scrollbar-track-transparent space-y-0.5 pr-0.5">
{filteredFonts.length === 0 ? (
<div className="py-10 text-center">
<p className="text-xs text-muted-foreground/35 italic">{emptyMessage}</p>
</div>
) : (
filteredFonts.map((font) => {
const isSelected = selectedFont === font.name;
const fav = isFavorite(font.name);
return (
<div
key={font.name}
className={cn(
'group flex items-center gap-1 px-2 py-1.5 rounded text-xs transition-colors',
'hover:bg-accent hover:text-accent-foreground',
selectedFont === font.name && 'bg-accent text-accent-foreground font-medium'
'group flex items-center gap-1.5 rounded-lg transition-all cursor-pointer',
'border-l-2',
isSelected
? 'bg-primary/10 border-primary text-primary'
: 'border-transparent text-foreground/65 hover:bg-primary/8 hover:text-foreground'
)}
>
<button
ref={isSelected ? selectedRef : undefined}
onClick={() => onSelectFont(font.name)}
className="flex-1 text-left truncate"
className="flex-1 text-left text-xs font-mono truncate px-2 py-1.5"
>
{font.name}
</button>
<button
onClick={(e) => handleToggleFavorite(font.name, e)}
className="p-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0"
aria-label={isFavorite(font.name) ? 'Remove from favorites' : 'Add to favorites'}
className={cn(
'shrink-0 pr-2 transition-all',
fav ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
)}
aria-label={fav ? 'Remove from favorites' : 'Add to favorites'}
>
<Heart
className={cn(
'h-3 w-3 transition-colors',
isFavorite(font.name) ? 'fill-red-500 text-red-500 !opacity-100' : 'text-muted-foreground/50 hover:text-red-500/50'
'w-3 h-3 transition-colors',
fav ? 'fill-rose-500 text-rose-500' : 'text-muted-foreground/40 hover:text-rose-400'
)}
/>
</button>
</div>
))
)}
</div>
);
})
)}
</div>
{/* Stats */}
<div className="mt-3 pt-3 border-t text-[10px] text-muted-foreground shrink-0">
{/* ── Footer ────────────────────────────────────────────── */}
<div className="mt-3 pt-2.5 border-t border-border/25 flex items-center justify-between shrink-0">
<span className="text-[10px] text-muted-foreground/35 font-mono tabular-nums">
{filteredFonts.length} font{filteredFonts.length !== 1 ? 's' : ''}
{filter === 'favorites' && ` · ${favorites.length} favorites`}
{filter === 'recent' && ` · ${recentFonts.length} recent`}
</div>
</CardContent>
</Card>
</span>
{filter === 'favorites' && (
<span className="text-[10px] text-muted-foreground/35">{favorites.length} saved</span>
)}
{filter === 'recent' && (
<span className="text-[10px] text-muted-foreground/35">{recentFonts.length} recent</span>
)}
</div>
</div>
);
}

View File

@@ -2,7 +2,6 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
import { Textarea } from '@/components/ui/textarea';
export interface TextInputProps {
value: string;
@@ -14,14 +13,17 @@ export interface TextInputProps {
export function TextInput({ value, onChange, placeholder, className }: TextInputProps) {
return (
<div className={cn('relative', className)}>
<Textarea
<textarea
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder || 'Type something...'}
className="h-32 resize-none"
placeholder={placeholder || 'Type something'}
rows={4}
maxLength={100}
className="w-full bg-transparent resize-none font-mono text-sm outline-none text-foreground placeholder:text-muted-foreground/35 border border-border/40 rounded-lg px-3 py-2.5 focus:border-primary/50 transition-colors"
spellCheck={false}
autoComplete="off"
/>
<div className="absolute bottom-2 right-2 text-xs text-muted-foreground">
<div className="absolute bottom-3 right-3 text-[10px] text-muted-foreground/35 font-mono pointer-events-none tabular-nums">
{value.length}/100
</div>
</div>