feat: 100% self-hosted Habbo fonts via sprite sheets + client-side compositor
This commit is contained in:
1 parent
8a58bcb252
commit
77ae4838c0
353 files changed
+227
-143
No files matched your search
@@ -1,20 +1,22 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo, useState, useTransition } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useTransition } from "react";
|
||||
import { ContentCard } from "@/components/public/ui";
|
||||
import { saveLogoFromUrl } from "@/actions/save-logo";
|
||||
import { HABBO_FONT_GROUPS, buildFontUrl } from "@/components/public/habbo-fonts";
|
||||
import { saveLogo } from "@/actions/save-logo";
|
||||
import { HABBO_FONT_GROUPS } from "@/components/public/habbo-fonts";
|
||||
import { getFontInfo, measureText, renderToCanvas } from "@/components/public/sprite-font";
|
||||
|
||||
export default function LogoGenerator() {
|
||||
const [text, setText] = useState("Atom");
|
||||
const [styleName, setStyleName] = useState("habbo");
|
||||
const [search, setSearch] = useState("");
|
||||
const [saveStatus, setSaveStatus] = useState<"idle" | "saving" | "done" | "error">("idle");
|
||||
const [imgError, setImgError] = useState(false);
|
||||
const [fontLoaded, setFontLoaded] = useState(false);
|
||||
const [fontError, setFontError] = useState(false);
|
||||
const [, startTransition] = useTransition();
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
|
||||
const safeText = text.trim() || "Your hotel";
|
||||
const gifUrl = useMemo(() => buildFontUrl(styleName, safeText), [styleName, safeText]);
|
||||
|
||||
const currentFont = useMemo(
|
||||
() => HABBO_FONT_GROUPS.flatMap((g) => g.fonts).find((f) => f.styleName === styleName),
|
||||
@@ -36,26 +38,63 @@ export default function LogoGenerator() {
|
||||
[search],
|
||||
);
|
||||
|
||||
// Load font and render preview
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setFontLoaded(false);
|
||||
setFontError(false);
|
||||
|
||||
getFontInfo(styleName)
|
||||
.then((info) => {
|
||||
if (cancelled) return;
|
||||
const canvas = renderToCanvas(info.chars, info.h, info.sheet, safeText, 12);
|
||||
if (canvas && canvasRef.current) {
|
||||
canvasRef.current.width = canvas.width;
|
||||
canvasRef.current.height = canvas.height;
|
||||
const ctx = canvasRef.current.getContext("2d");
|
||||
ctx?.drawImage(canvas, 0, 0);
|
||||
}
|
||||
setFontLoaded(true);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setFontError(true);
|
||||
});
|
||||
|
||||
return () => { cancelled = true; };
|
||||
}, [styleName, safeText]);
|
||||
|
||||
const handleDownload = useCallback(() => {
|
||||
window.open(gifUrl, "_blank");
|
||||
}, [gifUrl]);
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
canvas.toBlob((blob) => {
|
||||
if (!blob) return;
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(blob);
|
||||
a.download = `${safeText.replace(/[^a-z0-9]+/gi, "_") || "logo"}.png`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
}, "image/png");
|
||||
}, [safeText]);
|
||||
|
||||
const handleSave = useCallback(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
setSaveStatus("saving");
|
||||
startTransition(async () => {
|
||||
const result = await saveLogoFromUrl(
|
||||
`${window.location.origin}${gifUrl}`,
|
||||
);
|
||||
setSaveStatus(result.success ? "done" : "error");
|
||||
setTimeout(() => setSaveStatus("idle"), 3000);
|
||||
});
|
||||
}, [gifUrl, startTransition]);
|
||||
canvas.toBlob((blob) => {
|
||||
if (!blob) { setSaveStatus("error"); return; }
|
||||
const file = new File([blob], "logo.png", { type: "image/png" });
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
startTransition(async () => {
|
||||
const result = await saveLogo(fd);
|
||||
setSaveStatus(result.success ? "done" : "error");
|
||||
setTimeout(() => setSaveStatus("idle"), 3000);
|
||||
});
|
||||
}, "image/png");
|
||||
}, [startTransition]);
|
||||
|
||||
const [zipping, setZipping] = useState(false);
|
||||
const allFonts = useMemo(
|
||||
() => HABBO_FONT_GROUPS.flatMap((g) => g.fonts),
|
||||
[],
|
||||
);
|
||||
const allFonts = useMemo(() => HABBO_FONT_GROUPS.flatMap((g) => g.fonts), []);
|
||||
|
||||
const handleDownloadAll = useCallback(async () => {
|
||||
if (zipping) return;
|
||||
@@ -64,26 +103,26 @@ export default function LogoGenerator() {
|
||||
const JSZip = (await import("jszip")).default;
|
||||
const zip = new JSZip();
|
||||
const folder = zip.folder(safeText.replace(/[^a-z0-9]+/gi, "_") || "logo")!;
|
||||
const results = await Promise.allSettled(
|
||||
allFonts.map(async (font) => {
|
||||
const url = buildFontUrl(font.styleName, safeText);
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const blob = await res.blob();
|
||||
folder.file(`${font.styleName}.gif`, blob);
|
||||
}),
|
||||
);
|
||||
let fail = 0;
|
||||
|
||||
for (const font of allFonts) {
|
||||
try {
|
||||
const info = await getFontInfo(font.styleName);
|
||||
const canvas = renderToCanvas(info.chars, info.h, info.sheet, safeText, 12);
|
||||
if (!canvas) { fail++; continue; }
|
||||
const blob = await new Promise<Blob | null>((r) => canvas.toBlob((b) => r(b), "image/png"));
|
||||
if (blob) folder.file(`${font.styleName}.png`, blob);
|
||||
else fail++;
|
||||
} catch { fail++; }
|
||||
}
|
||||
|
||||
const failed = results.filter((r) => r.status === "rejected").length;
|
||||
const content = await zip.generateAsync({ type: "blob" });
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(content);
|
||||
a.download = `${safeText.replace(/[^a-z0-9]+/gi, "_") || "logo"}-all-fonts.zip`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
if (failed > 0) {
|
||||
alert(`${allFonts.length - failed}/${allFonts.length} fonts downloaded. ${failed} failed.`);
|
||||
}
|
||||
if (fail > 0) alert(`${allFonts.length - fail}/${allFonts.length} fonts (${fail} failed)`);
|
||||
} catch {
|
||||
alert("Failed to create ZIP.");
|
||||
} finally {
|
||||
@@ -125,10 +164,7 @@ export default function LogoGenerator() {
|
||||
</span>
|
||||
<select
|
||||
value={styleName}
|
||||
onChange={(e) => {
|
||||
setStyleName(e.target.value);
|
||||
setImgError(false);
|
||||
}}
|
||||
onChange={(e) => setStyleName(e.target.value)}
|
||||
style={{ maxHeight: 320 }}
|
||||
size={Math.min(filteredGroups.flatMap((g) => g.fonts).length + filteredGroups.length, 12)}
|
||||
>
|
||||
@@ -144,14 +180,14 @@ export default function LogoGenerator() {
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<button type="button" className="btn btn-primary" onClick={handleDownload}>
|
||||
⬇️ Download GIF
|
||||
<button type="button" className="btn btn-primary" onClick={handleDownload} disabled={!fontLoaded}>
|
||||
⬇️ Download PNG
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={handleSave}
|
||||
disabled={saveStatus === "saving"}
|
||||
disabled={saveStatus === "saving" || !fontLoaded}
|
||||
>
|
||||
{saveStatus === "saving"
|
||||
? "⏳ Saving..."
|
||||
@@ -172,7 +208,7 @@ export default function LogoGenerator() {
|
||||
</div>
|
||||
</ContentCard>
|
||||
|
||||
<ContentCard icon="👁️" title="Preview" subtitle="Rendered word via local proxy (cached on first load).">
|
||||
<ContentCard icon="👁️" title="Preview" subtitle="Rendered locally from sprite sheets.">
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
@@ -185,17 +221,12 @@ export default function LogoGenerator() {
|
||||
background: "repeating-conic-gradient(color-mix(in srgb, var(--color-text-muted) 14%, transparent) 0% 25%, transparent 0% 50%) 50% / 22px 22px",
|
||||
}}
|
||||
>
|
||||
{imgError ? (
|
||||
<p className="muted">Failed to load preview.</p>
|
||||
{fontError ? (
|
||||
<p className="muted">Failed to load font sprite.</p>
|
||||
) : fontLoaded ? (
|
||||
<canvas ref={canvasRef} style={{ maxWidth: "100%", height: "auto" }} />
|
||||
) : (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={gifUrl}
|
||||
alt={`Logo preview: ${safeText} in ${currentFont?.name ?? styleName} font`}
|
||||
style={{ maxWidth: "100%", height: "auto" }}
|
||||
onError={() => setImgError(true)}
|
||||
onLoad={() => setImgError(false)}
|
||||
/>
|
||||
<p className="muted">Loading font…</p>
|
||||
)}
|
||||
</div>
|
||||
</ContentCard>
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
const CHAR_ORDER = "abcdefghijklmnopqrstuvwxyz0123456789";
|
||||
|
||||
interface CharInfo {
|
||||
char: string;
|
||||
x: number;
|
||||
w: number;
|
||||
}
|
||||
|
||||
const fontCache = new Map<string, { chars: CharInfo[]; h: number; sheet: HTMLImageElement }>();
|
||||
|
||||
function hexPixel(data: Uint8ClampedArray, x: number, y: number, w: number): number {
|
||||
const i = (y * w + x) * 4;
|
||||
return (data[i] << 24) | (data[i + 1] << 16) | (data[i + 2] << 8) | data[i + 3];
|
||||
}
|
||||
|
||||
function isTransparent(data: Uint8ClampedArray, x: number, y: number, w: number): boolean {
|
||||
return data[(y * w + x) * 4 + 3] === 0;
|
||||
}
|
||||
|
||||
function colEmpty(data: Uint8ClampedArray, x: number, w: number, h: number): boolean {
|
||||
for (let y = 0; y < h; y++) {
|
||||
if (!isTransparent(data, x, y, w)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function scanCharWidths(data: Uint8ClampedArray, sw: number, sh: number): CharInfo[] {
|
||||
const chars: CharInfo[] = [];
|
||||
let ci = 0;
|
||||
let x = 0;
|
||||
|
||||
while (x < sw && ci < CHAR_ORDER.length) {
|
||||
// skip transparent columns
|
||||
while (x < sw && colEmpty(data, x, sw, sh)) x++;
|
||||
if (x >= sw) break;
|
||||
|
||||
const start = x;
|
||||
// find end of character
|
||||
while (x < sw && !colEmpty(data, x, sw, sh)) x++;
|
||||
const end = x;
|
||||
|
||||
const w = end - start;
|
||||
if (w > 0) {
|
||||
chars.push({ char: CHAR_ORDER[ci], x: start, w });
|
||||
ci++;
|
||||
}
|
||||
}
|
||||
|
||||
return chars;
|
||||
}
|
||||
|
||||
export async function getFontInfo(font: string): Promise<{ chars: CharInfo[]; h: number; sheet: HTMLImageElement }> {
|
||||
const cached = fontCache.get(font);
|
||||
if (cached) return cached;
|
||||
|
||||
const img = new Image();
|
||||
img.crossOrigin = "anonymous";
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
img.onload = () => resolve();
|
||||
img.onerror = () => reject(new Error(`Failed to load sprite for ${font}`));
|
||||
img.src = `/assets/fonts/sheets/${font}.gif`;
|
||||
});
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = img.naturalWidth;
|
||||
canvas.height = img.naturalHeight;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
ctx.drawImage(img, 0, 0);
|
||||
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
|
||||
const chars = scanCharWidths(imageData.data, canvas.width, canvas.height);
|
||||
|
||||
// measure total height by finding first/last non-empty row
|
||||
let top = canvas.height, bottom = 0;
|
||||
for (let y = 0; y < canvas.height; y++) {
|
||||
for (let x = 0; x < canvas.width; x++) {
|
||||
if (!isTransparent(imageData.data, x, y, canvas.width)) {
|
||||
top = Math.min(top, y);
|
||||
bottom = Math.max(bottom, y);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const h = bottom - top + 1;
|
||||
|
||||
const result = { chars, h, sheet: img };
|
||||
fontCache.set(font, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
export function measureText(chars: CharInfo[], h: number, text: string, spaceW: number): { totalW: number } {
|
||||
const map = new Map(chars.map((c) => [c.char, c]));
|
||||
let totalW = 0;
|
||||
for (const ch of text.toLowerCase()) {
|
||||
if (ch === " ") {
|
||||
totalW += spaceW;
|
||||
} else {
|
||||
const info = map.get(ch);
|
||||
totalW += info?.w ?? spaceW;
|
||||
}
|
||||
}
|
||||
return { totalW };
|
||||
}
|
||||
|
||||
export function renderToCanvas(
|
||||
chars: CharInfo[],
|
||||
h: number,
|
||||
sheet: HTMLImageElement,
|
||||
text: string,
|
||||
spaceW: number,
|
||||
dpr = 1,
|
||||
): HTMLCanvasElement | null {
|
||||
const map = new Map(chars.map((c) => [c.char, c]));
|
||||
const safeText = text.toLowerCase();
|
||||
|
||||
let totalW = 0;
|
||||
for (const ch of safeText) {
|
||||
totalW += ch === " " ? spaceW : (map.get(ch)?.w ?? spaceW);
|
||||
}
|
||||
|
||||
if (totalW === 0) return null;
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.round(totalW * dpr);
|
||||
canvas.height = Math.round(h * dpr);
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return null;
|
||||
ctx.scale(dpr, dpr);
|
||||
|
||||
let x = 0;
|
||||
for (const ch of safeText) {
|
||||
if (ch === " ") {
|
||||
x += spaceW;
|
||||
} else {
|
||||
const info = map.get(ch);
|
||||
if (info) {
|
||||
ctx.drawImage(sheet, info.x, 0, info.w, sheet.naturalHeight, x, 0, info.w, h);
|
||||
x += info.w;
|
||||
} else {
|
||||
x += spaceW;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return canvas;
|
||||
}
|
||||
Reference in new issue
Block a user