fix: restore word-level proxy for Habbo fonts, pre-cache all 175 fonts for 'Atom'
This commit is contained in:
1 parent
ac75f9c80a
commit
8a58bcb252
6481 files changed
+145
-731
No files matched your search
@@ -0,0 +1,93 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { mkdir, writeFile, readFile } from "fs/promises";
|
||||
import { existsSync } from "fs";
|
||||
import path from "path";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const CACHE_DIR = "public/assets/fonts/cache";
|
||||
|
||||
const VALID_STYLES = new Set([
|
||||
"habbo_new","habbo_big","habbo_new_big","habbo_old_big","habbo",
|
||||
"habbo_tiny","habbo_oldschool","habbo_blocky","habjoy","habjoy_light",
|
||||
"paradise","paradise_rounded","habbnew","habbo_clicker","reception",
|
||||
"accessoires","africa","alhambra","arctic","asian","asian_small",
|
||||
"basic","base","bathroom","battlebanzai","bensalem","bensalem_sea",
|
||||
"bling","bling_gold","bones","books","bots","bubble","bubble_blue",
|
||||
"bubble_orange","bunny_run","bunny_run_blue","buttons","candy",
|
||||
"collectibles","crystal","cubie","disco","dreams","dreams_flat",
|
||||
"duckets","emo","exchange","executive","explore","explore_big",
|
||||
"explore_small","faq","fbomb","festival","flags","fx","freehand",
|
||||
"gaming","gallery","goldentemple","gravity","hma","gold_big",
|
||||
"habbo_news","habbo_runway","habbid_red","habbid_blue","habbolife",
|
||||
"habbowood","habbowood_big","hands","hello","horse","ice","iced",
|
||||
"iron","japan","love","marketplace_red","monkey","mushroom",
|
||||
"mushroom_green","neon_blue","neon_green","neon_pink","occasional",
|
||||
"palooza","palooza_blue","pets","pillow_orange","pillow_pink","pipes",
|
||||
"plants","plastic","recycle","retropixel","rugs","sale","shalimar",
|
||||
"shalimar_big","shalimar_small","soccer","soccer_red","soccer_yellow",
|
||||
"space","spaces","special_offers","straypixels","steampunk","scifi",
|
||||
"summer","teleport","theater_lights","tribe","trophies","usva",
|
||||
"unknown_blue","unknown_blue_2","unknown_metal","unknown_white",
|
||||
"unknown_pillow_1","unknown_pillow_2","valentine","western","wood",
|
||||
"yellow_text","jurrasic","halloween","halloween_2","halloween_3",
|
||||
"plastic_playful","dinner_blue","dinner_green","dinner_red",
|
||||
"battleball","lido","soccer_big","hc","hc_big","hc_small",
|
||||
"hc_compact","hc_gold","habboclub","habboclub_banner","habbovip",
|
||||
"habbovip_banner","agenda","mini_white","volter","volter_shadow",
|
||||
"volter_modern","volter_modern_small","black","windows",
|
||||
"windows_lowercase","windows_jungle","windows_blue","windows_green",
|
||||
"windows_pink","windows_red","windows_red_dark","windows_yellow",
|
||||
"windows_purple","beta_big","beta_small","beta_small_old","beta",
|
||||
"habboclub_complete","gift","habboclub_silver","love_full",
|
||||
"marketplace_full","relax","habbo_ribbon",
|
||||
]);
|
||||
|
||||
export async function GET(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ style: string; text: string }> },
|
||||
) {
|
||||
const { style, text } = await params;
|
||||
|
||||
if (!VALID_STYLES.has(style)) {
|
||||
return new NextResponse("Invalid font style", { status: 400 });
|
||||
}
|
||||
|
||||
const sanitized = text.replace(/[^a-z0-9+]/g, "");
|
||||
if (!sanitized) {
|
||||
return new NextResponse("Invalid text", { status: 400 });
|
||||
}
|
||||
|
||||
const cacheFile = `${style}-${sanitized}.gif`;
|
||||
const cachePath = path.join(process.cwd(), CACHE_DIR, cacheFile);
|
||||
|
||||
// Serve from cache if already fetched
|
||||
if (existsSync(cachePath)) {
|
||||
const bytes = await readFile(cachePath);
|
||||
return new NextResponse(bytes, {
|
||||
headers: {
|
||||
"Content-Type": "image/gif",
|
||||
"Cache-Control": "public, max-age=86400",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Fetch from habbofont.net and cache
|
||||
const upstream = `https://habbofont.net/font/${style}/${sanitized}.gif`;
|
||||
const res = await fetch(upstream);
|
||||
|
||||
if (!res.ok) {
|
||||
return new NextResponse("Font render error", { status: 502 });
|
||||
}
|
||||
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
await mkdir(path.dirname(cachePath), { recursive: true });
|
||||
await writeFile(cachePath, buffer);
|
||||
|
||||
return new NextResponse(buffer, {
|
||||
headers: {
|
||||
"Content-Type": "image/gif",
|
||||
"Cache-Control": "public, max-age=86400",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
"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 };
|
||||
}
|
||||
@@ -263,7 +263,9 @@ export const HABBO_FONT_GROUPS: HabboFontGroup[] = [
|
||||
},
|
||||
];
|
||||
|
||||
export function charUrl(styleName: string, char: string): string {
|
||||
return `/assets/fonts/chars/${styleName}/${char}.gif`;
|
||||
export function buildFontUrl(styleName: string, text: string): string {
|
||||
const t = text.toLowerCase().replace(/\s/g, "+");
|
||||
return `/api/font/${styleName}/${t}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,88 +1,20 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo, useRef, useState, useTransition } from "react";
|
||||
import { useCallback, useMemo, useState, useTransition } from "react";
|
||||
import { ContentCard } from "@/components/public/ui";
|
||||
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");
|
||||
}
|
||||
});
|
||||
}
|
||||
import { saveLogoFromUrl } from "@/actions/save-logo";
|
||||
import { HABBO_FONT_GROUPS, buildFontUrl } from "@/components/public/habbo-fonts";
|
||||
|
||||
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 [, 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),
|
||||
@@ -104,33 +36,26 @@ export default function LogoGenerator() {
|
||||
[search],
|
||||
);
|
||||
|
||||
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 handleDownload = useCallback(() => {
|
||||
window.open(gifUrl, "_blank");
|
||||
}, [gifUrl]);
|
||||
|
||||
const handleSave = useCallback(() => {
|
||||
setSaveStatus("saving");
|
||||
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);
|
||||
});
|
||||
startTransition(async () => {
|
||||
const result = await saveLogoFromUrl(
|
||||
`${window.location.origin}${gifUrl}`,
|
||||
);
|
||||
setSaveStatus(result.success ? "done" : "error");
|
||||
setTimeout(() => setSaveStatus("idle"), 3000);
|
||||
});
|
||||
}, [styleName, safeText, startTransition]);
|
||||
}, [gifUrl, 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;
|
||||
@@ -139,17 +64,17 @@ 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")!;
|
||||
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 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);
|
||||
}),
|
||||
);
|
||||
|
||||
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);
|
||||
@@ -157,7 +82,7 @@ export default function LogoGenerator() {
|
||||
a.click();
|
||||
URL.revokeObjectURL(a.href);
|
||||
if (failed > 0) {
|
||||
alert(`${allFonts.length - failed}/${allFonts.length} fonts rendered. ${failed} failed.`);
|
||||
alert(`${allFonts.length - failed}/${allFonts.length} fonts downloaded. ${failed} failed.`);
|
||||
}
|
||||
} catch {
|
||||
alert("Failed to create ZIP.");
|
||||
@@ -200,7 +125,10 @@ export default function LogoGenerator() {
|
||||
</span>
|
||||
<select
|
||||
value={styleName}
|
||||
onChange={(e) => setStyleName(e.target.value)}
|
||||
onChange={(e) => {
|
||||
setStyleName(e.target.value);
|
||||
setImgError(false);
|
||||
}}
|
||||
style={{ maxHeight: 320 }}
|
||||
size={Math.min(filteredGroups.flatMap((g) => g.fonts).length + filteredGroups.length, 12)}
|
||||
>
|
||||
@@ -217,7 +145,7 @@ export default function LogoGenerator() {
|
||||
</label>
|
||||
|
||||
<button type="button" className="btn btn-primary" onClick={handleDownload}>
|
||||
⬇️ Download PNG
|
||||
⬇️ Download GIF
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -244,7 +172,7 @@ export default function LogoGenerator() {
|
||||
</div>
|
||||
</ContentCard>
|
||||
|
||||
<ContentCard icon="👁️" title="Preview" subtitle="Composed from local character images.">
|
||||
<ContentCard icon="👁️" title="Preview" subtitle="Rendered word via local proxy (cached on first load).">
|
||||
<div
|
||||
style={{
|
||||
display: "grid",
|
||||
@@ -257,7 +185,18 @@ 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",
|
||||
}}
|
||||
>
|
||||
<HabboFontPreview font={styleName} text={safeText} />
|
||||
{imgError ? (
|
||||
<p className="muted">Failed to load preview.</p>
|
||||
) : (
|
||||
// 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)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</ContentCard>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user