feat: 100% self-hosted Habbo fonts - 6300 char GIFs + local canvas compositor, no habbofont.net dependency

This commit is contained in:
openhands committed 2026-07-03 17:36:34 +02:00
1 parent 00b1d0a267
commit ac75f9c80a
6480 files changed
+259 -222

No files matched your search

@@ -0,0 +1,149 @@
"use client";
import { useEffect, useRef, useState } from "react";
const CHAR_LIST = "abcdefghijklmnopqrstuvwxyz0123456789";
const FONT_BASE = "/assets/fonts/chars";
export function charUrl(font: string, char: string): string {
return `${FONT_BASE}/${font}/${char}.gif`;
}
export function splitText(text: string): string[] {
return text
.toLowerCase()
.split("")
.filter((c) => CHAR_LIST.includes(c) || c === " ");
}
export function HabboFontPreview({
font,
text,
}: {
font: string;
text: string;
}) {
const chars = splitText(text);
return (
<div
style={{
display: "flex",
alignItems: "end",
flexWrap: "wrap",
lineHeight: 0,
}}
>
{chars.map((c, i) =>
c === " " ? (
<span key={i} style={{ display: "inline-block", width: 16, height: 1 }} />
) : (
// biome-ignore lint/performance/noImgElement: static char GIFs
<img
key={i}
src={charUrl(font, c)}
alt=""
style={{ display: "block" }}
/>
),
)}
</div>
);
}
export function useHabboFontCanvas(
font: string,
text: string,
onCanvas?: (canvas: HTMLCanvasElement) => void,
) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const [loaded, setLoaded] = useState(false);
useEffect(() => {
const chars = splitText(text);
if (chars.length === 0 || chars.every((c) => c === " ")) return;
const images: HTMLImageElement[] = [];
let loadedCount = 0;
chars.forEach((c, i) => {
if (c === " ") {
images[i] = null!;
loadedCount++;
return;
}
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => {
loadedCount++;
if (loadedCount === chars.length) {
setLoaded(true);
renderToCanvas();
}
};
img.onerror = () => {
loadedCount++;
if (loadedCount === chars.length) {
setLoaded(true);
renderToCanvas();
}
};
img.src = charUrl(font, c);
images[i] = img;
});
if (loadedCount === chars.length) {
setLoaded(true);
}
function renderToCanvas() {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const dpr = Math.min(window.devicePixelRatio || 1, 3);
if (images.length === 0 || images.some((img) => !img && img !== null)) {
return;
}
const validImages = images.filter(Boolean) as HTMLImageElement[];
let totalWidth = 0;
let maxHeight = 0;
const spaceWidth = 16;
for (let i = 0; i < images.length; i++) {
if (images[i]) {
totalWidth += images[i].naturalWidth || images[i].width;
maxHeight = Math.max(maxHeight, images[i].naturalHeight || images[i].height);
} else {
totalWidth += spaceWidth;
}
}
canvas.width = Math.round(totalWidth * dpr);
canvas.height = Math.round(maxHeight * dpr);
ctx.scale(dpr, dpr);
let x = 0;
for (const img of images) {
if (img) {
ctx.drawImage(img, x, 0);
x += img.naturalWidth || img.width;
} else {
x += spaceWidth;
}
}
onCanvas?.(canvas);
}
if (!images.some((img) => img && !img.complete)) {
renderToCanvas();
}
}, [font, text, onCanvas]);
return { canvasRef, loaded };
}
+3 -3
View File
@@ -263,7 +263,7 @@ export const HABBO_FONT_GROUPS: HabboFontGroup[] = [
},
];
export function buildFontUrl(styleName: string, text: string): string {
const t = text.toLowerCase().replace(/\s/g, "+");
return `/api/font/${styleName}/${t}`;
export function charUrl(styleName: string, char: string): string {
return `/assets/fonts/chars/${styleName}/${char}.gif`;
}
+107 -49
View File
@@ -1,9 +1,79 @@
"use client";
import { useCallback, useMemo, useState, useTransition } from "react";
import { useCallback, 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, charUrl } from "@/components/public/habbo-fonts";
import { HabboFontPreview, splitText } from "@/components/public/habbo-font-renderer";
const CHAR_LIST = "abcdefghijklmnopqrstuvwxyz0123456789";
function renderToCanvas(font: string, text: string): Promise<Blob | null> {
return new Promise((resolve) => {
const chars = splitText(text);
if (chars.length === 0) { resolve(null); return; }
const images: (HTMLImageElement | null)[] = [];
let loaded = 0;
for (let i = 0; i < chars.length; i++) {
if (chars[i] === " ") {
images.push(null);
loaded++;
} else {
const idx = images.length;
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = img.onerror = () => {
loaded++;
if (loaded === chars.length) finish();
};
img.src = charUrl(font, chars[i]);
images.push(img);
}
}
if (loaded === chars.length) finish();
function finish() {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) { resolve(null); return; }
const dpr = Math.min(window.devicePixelRatio || 1, 3);
let totalW = 0;
let maxH = 0;
const spaceW = 16;
for (const img of images) {
if (img) {
totalW += img.naturalWidth || img.width || 10;
maxH = Math.max(maxH, img.naturalHeight || img.height || 20);
} else {
totalW += spaceW;
}
}
if (totalW === 0 || maxH === 0) { resolve(null); return; }
canvas.width = Math.round(totalW * dpr);
canvas.height = Math.round(maxH * dpr);
ctx.scale(dpr, dpr);
let x = 0;
for (const img of images) {
if (img) {
ctx.drawImage(img, x, 0);
x += img.naturalWidth || img.width || 10;
} else {
x += spaceW;
}
}
canvas.toBlob((blob) => resolve(blob), "image/png");
}
});
}
export default function LogoGenerator() {
const [text, setText] = useState("Atom");
@@ -13,7 +83,6 @@ export default function LogoGenerator() {
const [, startTransition] = useTransition();
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),
@@ -35,28 +104,33 @@ export default function LogoGenerator() {
[search],
);
const handleDownload = useCallback(() => {
window.open(gifUrl, "_blank");
}, [gifUrl]);
const handleDownload = useCallback(async () => {
const blob = await renderToCanvas(styleName, safeText);
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);
}, [styleName, safeText]);
const handleSave = useCallback(() => {
setSaveStatus("saving");
startTransition(async () => {
const result = await saveLogoFromUrl(gifUrl);
setSaveStatus(result.success ? "done" : "error");
if (result.success) {
renderToCanvas(styleName, safeText).then((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);
} else {
setTimeout(() => setSaveStatus("idle"), 3000);
}
});
});
}, [gifUrl, startTransition]);
}, [styleName, safeText, 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,19 +138,18 @@ export default function LogoGenerator() {
try {
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 failed = 0;
for (const font of allFonts) {
const blob = await renderToCanvas(font.styleName, safeText);
if (blob) {
folder.file(`${font.styleName}.png`, blob);
} else {
failed++;
}
}
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);
@@ -84,7 +157,7 @@ export default function LogoGenerator() {
a.click();
URL.revokeObjectURL(a.href);
if (failed > 0) {
alert(`${allFonts.length - failed}/${allFonts.length} fonts downloaded. ${failed} failed.`);
alert(`${allFonts.length - failed}/${allFonts.length} fonts rendered. ${failed} failed.`);
}
} catch {
alert("Failed to create ZIP.");
@@ -106,9 +179,6 @@ export default function LogoGenerator() {
placeholder="Your hotel"
maxLength={40}
/>
<span className="muted" style={{ fontSize: "0.78rem" }}>
Text will be lowercased with spaces as + in the GIF URL.
</span>
</label>
<label style={{ display: "grid", gap: "0.3rem" }}>
@@ -147,7 +217,7 @@ export default function LogoGenerator() {
</label>
<button type="button" className="btn btn-primary" onClick={handleDownload}>
⬇️ Download GIF
⬇️ Download PNG
</button>
<button
type="button"
@@ -174,7 +244,7 @@ export default function LogoGenerator() {
</div>
</ContentCard>
<ContentCard icon="👁️" title="Preview" subtitle="Live GIF from habbofont.net.">
<ContentCard icon="👁️" title="Preview" subtitle="Composed from local character images.">
<div
style={{
display: "grid",
@@ -187,20 +257,8 @@ 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",
}}
>
{/* 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" }}
/>
<HabboFontPreview font={styleName} text={safeText} />
</div>
<p className="muted" style={{ marginBottom: 0, marginTop: "0.85rem", wordBreak: "break-all" }}>
Fonts rendered via{" "}
<a href="https://habbofont.net" target="_blank" rel="noopener noreferrer">
habbofont.net
</a>
{" "}and served locally.
</p>
</ContentCard>
</div>
);