feat(image-export) : capture guide sections in browser
CI / Verify (push) Successful in 58s
CI / Build immutable images and deploy (push) Successful in 2m54s

This commit is contained in:
2026-09-02 22:28:28 +07:00 Unverified
parent ded10ebb36
commit dd672e5331
6 changed files with 272 additions and 1266 deletions
@@ -1,778 +0,0 @@
/* eslint-disable @next/next/no-img-element */
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { ImageResponse } from "next/og";
import sharp from "sharp";
import { rarityGradient } from "@/lib/catalog/rarity";
import { artifactTierCount } from "@/lib/guides/artifacts";
import { getCachedPublicArtifactExport } from "@/lib/cache/public";
import { imageContentDisposition } from "@/lib/guides/export-image";
import {
normalizeTargetStat,
recommendedStatIconName,
statPriorityColor,
targetStatIconName,
targetStatOptions,
} from "@/lib/guides/stats";
import {
normalizeTalentPriorities,
talentRelationSymbol,
talentTypeLabel,
} from "@/lib/guides/talents";
const anuphanFonts = Promise.all(
[
{ subset: "latin", weight: 400 as const },
{ subset: "thai", weight: 400 as const },
{ subset: "latin", weight: 700 as const },
{ subset: "thai", weight: 700 as const },
].map(async ({ subset, weight }) => {
const response = await fetch(
`https://unpkg.com/@fontsource/[email protected]/files/anuphan-${subset}-${weight}-normal.woff`,
);
if (!response.ok)
throw new Error(`Unable to load Anuphan ${subset} ${weight}`);
return {
name: "Anuphan",
data: await response.arrayBuffer(),
weight,
style: "normal" as const,
};
}),
).catch(() => []);
const relationFont = readFile(
join(process.cwd(), "public", "Kanit-SemiBold.ttf"),
);
function metric(value: string): string {
return `${Number(value).toLocaleString("en-US", { maximumFractionDigits: 2 })}%`;
}
function statLabel(value: string): string {
const labels: Record<string, string> = {
HP: "พลังชีวิต",
ATK: "พลังโจมตี",
DEF: "พลังป้องกัน",
EM: "ความชำนาญธาตุ",
ER: "ฟื้นฟูพลังงาน",
"CRIT RATE": "อัตราคริ",
"CRIT DAMAGE": "ความแรงคริ",
"ATK%": "พลังโจมตี%",
"HP%": "พลังชีวิต%",
"DEF%": "พลังป้องกัน%",
"CRIT Rate%/CRIT DMG%": "อัตราคริ/ความแรงคริ",
"Pyro DMG%": "ความเสียหายธาตุไฟ%",
"Hydro DMG%": "ความเสียหายธาตุน้ำ%",
"Cryo DMG%": "ความเสียหายธาตุน้ำแข็ง%",
"Electro DMG%": "ความเสียหายธาตุไฟฟ้า%",
"Anemo DMG%": "ความเสียหายธาตุลม%",
"Geo DMG%": "ความเสียหายธาตุดิน%",
"Dendro DMG%": "ความเสียหายธาตุไม้%",
"Physical DMG%": "ความเสียหายกายภาพ%",
"Healing Bonus%": "โบนัสการรักษา%",
};
return labels[value] ?? value;
}
async function pngDataUrl(url: string): Promise<string | null> {
try {
const response = await fetch(url);
if (!response.ok) return null;
const png = await sharp(Buffer.from(await response.arrayBuffer()))
.resize(96, 96, { fit: "contain" })
.png()
.toBuffer();
return `data:image/png;base64,${png.toString("base64")}`;
} catch {
return null;
}
}
async function localPngDataUrl(
fileName: string,
size: number | null = 96,
white = false,
): Promise<string> {
let image = sharp(join(process.cwd(), "public", "icon", fileName));
if (white) image = image.negate({ alpha: false });
const png = await (
size === null ? image : image.resize(size, size, { fit: "contain" })
)
.png()
.toBuffer();
return `data:image/png;base64,${png.toString("base64")}`;
}
export async function GET(
_request: Request,
context: RouteContext<"/api/guides/[guideId]/artifacts/image">,
) {
const { guideId } = await context.params;
const guide = await getCachedPublicArtifactExport(guideId);
if (!guide) return new Response("ไม่พบไกด์", { status: 404 });
const talents = normalizeTalentPriorities(guide.profile?.talents ?? []);
const [fontAssets, groupAssets, statIconAssets, talentAssets, targetStatAssets] =
await Promise.all([
Promise.all([anuphanFonts, relationFont]),
Promise.all(
guide.groups.map((group) =>
Promise.all(
group.rows.map(async (row) => ({
first: await pngDataUrl(row.first.imageUrl),
second: row.second ? await pngDataUrl(row.second.imageUrl) : null,
})),
),
),
),
Promise.all([
localPngDataUrl("Icon_Sands_of_Eon.webp"),
localPngDataUrl("Icon_Goblet_of_Eonothem.webp"),
localPngDataUrl("Icon_Circlet_of_Logos.webp"),
]),
Promise.all(
talents.map((talent) => {
const catalogTalent = guide.character.talents.find(
(item) => item.type === talent.type,
);
return catalogTalent?.iconUrl
? pngDataUrl(catalogTalent.iconUrl)
: null;
}),
),
Promise.all(
targetStatOptions.map((stat) =>
localPngDataUrl(`stats/${targetStatIconName(stat)}.webp`, 96, true),
),
),
]);
const [fonts, relationFontData] = fontAssets;
const profile = guide.profile;
const recommendedStatAsset = (value: string) => {
const iconName = recommendedStatIconName(value);
const iconIndex = targetStatOptions.findIndex(
(stat) => targetStatIconName(stat) === iconName,
);
return iconIndex >= 0 ? targetStatAssets[iconIndex] : null;
};
const groupRowHeights = guide.groups.map((group) =>
group.rows.map((row) =>
Math.max(76, 76 + (row.note ? Math.ceil(row.note.length / 58) * 22 : 0)),
),
);
const tierListHeight =
guide.groups.reduce(
(sum, _group, groupIndex) =>
sum +
68 +
groupRowHeights[groupIndex].reduce(
(groupSum, rowHeight) => groupSum + rowHeight,
0,
),
0,
) +
Math.max(0, guide.groups.length - 1) * 16;
const detailHeight = profile
? 60 +
profile.targets.length * 40 +
(profile.talents.length ? 82 : 0) +
(profile.note
? Math.max(48, Math.ceil(profile.note.length / 58) * 24)
: 0)
: 0;
const mainStatExtraHeight = profile
? Math.max(
0,
Math.max(
profile.sands.length,
profile.goblet.length,
profile.circlet.length,
) - 2,
) * 24
: 0;
const profileHeight = profile
? 242 +
mainStatExtraHeight +
(profile.substats.length ? 92 + profile.substats.length * 18 : 0)
: 0;
const leftHeight = tierListHeight + (profile ? profileHeight + 16 : 0);
const rightHeight = detailHeight > 60 ? detailHeight : 0;
const height = Math.max(520, 190 + Math.max(leftHeight, rightHeight));
return new ImageResponse(
<div
style={{
width: "100%",
height: "100%",
display: "flex",
flexDirection: "column",
gap: 20,
color: "#f7f7f7",
background: "#05060a",
padding: "32px 36px",
fontFamily: "Anuphan",
position: "relative",
}}
>
<div
style={{
position: "relative",
zIndex: 1,
display: "flex",
flex: 1,
flexDirection: "column",
gap: 20,
}}
>
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 8,
}}
>
<div
style={{
display: "flex",
color: "#f0b72f",
fontSize: 16,
fontWeight: 700,
}}
>
อาร์ติแฟกต์และสแตทที่แนะนำ
</div>
<div style={{ display: "flex", fontSize: 38, fontWeight: 700 }}>
Artifact & Stats
</div>
</div>
<div style={{ display: "flex", alignItems: "flex-start", gap: 16 }}>
<div
style={{
display: "flex",
flex: detailHeight > 60 ? 1.2 : 1,
flexDirection: "column",
gap: 16,
}}
>
{guide.groups.map((group, groupIndex) => (
<div
key={group.id}
style={{
display: "flex",
flexDirection: "column",
overflow: "hidden",
border: "1px solid #34343d",
borderRadius: 14,
background: "#1d1d25",
}}
>
<div
style={{
display: "flex",
padding: "16px 20px",
fontSize: 22,
fontWeight: 700,
}}
>
{group.name === "Late Game" ? "เลทเกม" : group.name}
</div>
<div
style={{
display: "flex",
flexDirection: "column",
padding: "0 20px 14px",
}}
>
{group.rows.map((row, rowIndex) => (
<div
key={row.id}
style={{
display: "flex",
minHeight: groupRowHeights[groupIndex][rowIndex],
alignItems: "center",
gap: 14,
borderRadius: 6,
background: rowIndex % 2 === 0 ? "#34343d" : "#272730",
padding: "5px 8px",
}}
>
<div
style={{ display: "flex", width: row.second ? 94 : 58 }}
>
{groupAssets[groupIndex][rowIndex].first ? (
<div
style={{
display: "flex",
width: 58,
height: 58,
overflow: "hidden",
border: "1px solid #ffffff2a",
borderRadius: 10,
background: rarityGradient(row.first.rarity),
}}
>
<img
src={groupAssets[groupIndex][rowIndex].first!}
alt=""
width={58}
height={58}
style={{ objectFit: "contain" }}
/>
</div>
) : null}
{row.second &&
groupAssets[groupIndex][rowIndex].second ? (
<div
style={{
display: "flex",
width: 58,
height: 58,
overflow: "hidden",
marginLeft: -22,
border: "1px solid #ffffff2a",
borderRadius: 10,
background: rarityGradient(row.second.rarity),
}}
>
<img
src={groupAssets[groupIndex][rowIndex].second!}
alt=""
width={58}
height={58}
style={{ objectFit: "contain" }}
/>
</div>
) : null}
</div>
<div
style={{
display: "flex",
flex: 1,
flexDirection: "column",
gap: 5,
}}
>
<div
style={{
display: "flex",
fontSize: 18,
fontWeight: 700,
}}
>
{artifactTierCount(row.second?.name ?? null)}{" "}
{row.first.name}
{row.second ? ` + ${row.second.name}` : ""}
</div>
{row.note ? (
<div
style={{
display: "flex",
color: "#b9b9c2",
fontSize: 14,
lineHeight: 1.55,
}}
>
{row.note}
</div>
) : null}
</div>
<div
style={{
display: "flex",
color: "#f0b72f",
fontSize: 26,
fontWeight: 700,
}}
>
{Number(row.percent) === 0 ? "-%" : metric(row.percent)}
</div>
</div>
))}
</div>
</div>
))}
{profile ? (
<div
style={{
display: "flex",
flexDirection: "column",
overflow: "hidden",
border: "1px solid #34343d",
borderRadius: 14,
background: "#1d1d25",
}}
>
<div
style={{
display: "flex",
justifyContent: "center",
background: "#ddb45a",
color: "#211a0d",
padding: "14px 20px",
fontSize: 24,
fontWeight: 700,
}}
>
ออฟหลักที่ดีที่สุด
</div>
<div style={{ display: "flex" }}>
{[
{
label: "นาฬิกา",
values: profile.sands,
icon: statIconAssets[0],
},
{
label: "ถ้วย",
values: profile.goblet,
icon: statIconAssets[1],
},
{
label: "หัว",
values: profile.circlet,
icon: statIconAssets[2],
},
].map((stat) => (
<div
key={stat.label}
style={{
display: "flex",
flex: 1,
minHeight: 176,
flexDirection: "column",
alignItems: "center",
gap: 10,
borderRight:
stat.label === "มงกุฎ" ? "none" : "1px solid #34343d",
padding: "16px 10px",
textAlign: "center",
}}
>
<img
src={stat.icon}
alt=""
width={48}
height={48}
style={{ objectFit: "contain" }}
/>
<div
style={{
display: "flex",
fontSize: 17,
fontWeight: 700,
}}
>
{stat.label}
</div>
<div
style={{
display: "flex",
width: "100%",
borderTop: "1px solid #34343d",
}}
/>
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 4,
fontSize: 14,
lineHeight: 1.45,
}}
>
{stat.values.length
? stat.values.map((value, index) => (
<span
key={`${value}-${index}`}
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: 5,
color: statPriorityColor(index),
whiteSpace: "normal",
wordBreak: "break-word",
}}
>
{recommendedStatAsset(value) ? (
<img
src={recommendedStatAsset(value)!}
alt=""
width={18}
height={18}
style={{ objectFit: "contain" }}
/>
) : null}
{statLabel(value)}
</span>
))
: "-"}
</div>
</div>
))}
</div>
</div>
) : null}
{profile?.substats.length ? (
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 4,
border: "1px solid #34343d",
borderRadius: 14,
background: "#1d1d25",
padding: "16px",
fontSize: 14,
textAlign: "center",
}}
>
<strong>ออฟรองที่ดีที่สุด</strong>
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 2,
}}
>
{profile.substats.map((stat, index) => (
<span
key={`${stat}-${index}`}
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
gap: 5,
color: statPriorityColor(index),
}}
>
{recommendedStatAsset(stat) ? (
<img
src={recommendedStatAsset(stat)!}
alt=""
width={18}
height={18}
style={{ objectFit: "contain" }}
/>
) : null}
{statLabel(stat)}
</span>
))}
</div>
</div>
) : null}
</div>
{profile && detailHeight > 60 ? (
<div
style={{
display: "flex",
flex: 1,
flexDirection: "column",
gap: 16,
}}
>
<div
style={{
display: "flex",
flexDirection: "column",
gap: 14,
border: "1px solid #34343d",
borderRadius: 14,
background: "#1d1d25",
padding: "18px 20px",
}}
>
{profile.targets.length ? (
<div
style={{ display: "flex", flexDirection: "column", gap: 7 }}
>
<div
style={{
display: "flex",
color: "#b9b9c2",
fontSize: 14,
fontWeight: 700,
}}
>
ค่าสถานะต่ำๆที่ควรจะปั้นไว้
</div>
{profile.targets.map((target, index) => {
const iconIndex = targetStatOptions.findIndex(
(stat) => stat === normalizeTargetStat(target.stat),
);
return (
<div
key={`${target.stat}-${target.value}`}
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
gap: 12,
borderRadius: 6,
background: index % 2 === 0 ? "#34343d" : "#272730",
padding: "5px 8px",
fontSize: 15,
}}
>
<span
style={{
display: "flex",
alignItems: "center",
gap: 8,
}}
>
{iconIndex >= 0 ? (
<img
src={targetStatAssets[iconIndex]}
alt=""
width={14}
height={14}
style={{ objectFit: "contain" }}
/>
) : null}
{normalizeTargetStat(target.stat) ?? target.stat}
</span>
<strong>{target.value}</strong>
</div>
);
})}
</div>
) : null}
{talents.length ? (
<div
style={{ display: "flex", flexDirection: "column", gap: 6 }}
>
<div
style={{
display: "flex",
color: "#b9b9c2",
fontSize: 14,
fontWeight: 700,
}}
>
ลำดับการอัพพรสวรรค์
</div>
<div
style={{
display: "flex",
alignItems: "center",
gap: 10,
fontSize: 17,
fontWeight: 700,
}}
>
{talents.map((talent, index) => (
<div
key={talent.type}
style={{
display: "flex",
alignItems: "center",
gap: 8,
}}
>
{talentAssets[index] ? (
<img
src={talentAssets[index]!}
alt=""
width={42}
height={42}
style={{ objectFit: "contain" }}
/>
) : null}
<span
style={{
display: "flex",
flexDirection: "column",
gap: 2,
}}
>
<span>
{talent.type}
{talent.level ? ` เลเวล ${talent.level}+` : ""}
</span>
<span
style={{
color: "#b9b9c2",
fontSize: 13,
fontWeight: 400,
}}
>
{talentTypeLabel(talent.type)}
</span>
</span>
{index < talents.length - 1 ? (
<span style={{ fontFamily: "Kanit" }}>
{talentRelationSymbol(talent.relationToNext)}
</span>
) : null}
</div>
))}
</div>
</div>
) : null}
{profile.note ? (
<div
style={{ display: "flex", flexDirection: "column", gap: 5 }}
>
<div
style={{
display: "flex",
color: "#b9b9c2",
fontSize: 14,
fontWeight: 700,
}}
>
โน็ต
</div>
<div
style={{
display: "flex",
fontSize: 14,
lineHeight: 1.55,
}}
>
{profile.note}
</div>
</div>
) : null}
</div>
</div>
) : null}
</div>
</div>
</div>,
{
width: 1200,
height,
fonts: [
...fonts,
{
name: "Kanit",
data: relationFontData,
weight: 600,
style: "normal",
},
],
headers: {
"Cache-Control": "no-store",
"Content-Disposition": imageContentDisposition(
`${guide.guideName}-Artifact`,
"artifacts",
),
"Content-Type": "image/png",
},
},
);
}
@@ -1,334 +0,0 @@
/* eslint-disable @next/next/no-img-element */
import { ImageResponse } from "next/og";
import sharp from "sharp";
import { rarityGradient, rarityTextColor } from "@/lib/catalog/rarity";
import { getCachedPublicWeaponExport } from "@/lib/cache/public";
import { imageContentDisposition } from "@/lib/guides/export-image";
const anuphanFonts = Promise.all(
[
{ subset: "latin", weight: 400 as const },
{ subset: "thai", weight: 400 as const },
{ subset: "latin", weight: 500 as const },
{ subset: "thai", weight: 500 as const },
{ subset: "latin", weight: 600 as const },
{ subset: "thai", weight: 600 as const },
{ subset: "latin", weight: 700 as const },
{ subset: "thai", weight: 700 as const },
].map(async ({ subset, weight }) => {
const response = await fetch(
`https://unpkg.com/@fontsource/[email protected]/files/anuphan-${subset}-${weight}-normal.woff`,
);
if (!response.ok)
throw new Error(`Unable to load Anuphan ${subset} ${weight}`);
return {
name: "Anuphan",
data: await response.arrayBuffer(),
weight,
style: "normal" as const,
};
}),
).catch(() => []);
function metric(value: string): string {
return Number(value) === 0
? "-%"
: `${Number(value).toLocaleString("en-US", { maximumFractionDigits: 2 })}%`;
}
function wrappedLineCount(value: string, lineLength: number): number {
return value
.split(/\r?\n/u)
.reduce(
(lines, line) => lines + Math.max(1, Math.ceil(line.length / lineLength)),
0,
);
}
async function pngDataUrl(url: string): Promise<string | null> {
try {
const response = await fetch(url);
if (!response.ok) return null;
const png = await sharp(Buffer.from(await response.arrayBuffer()))
.resize(80, 80, { fit: "contain" })
.png()
.toBuffer();
return `data:image/png;base64,${png.toString("base64")}`;
} catch {
return null;
}
}
export async function GET(
_request: Request,
context: { params: Promise<{ guideId: string }> },
) {
const { guideId } = await context.params;
const guide = await getCachedPublicWeaponExport(guideId);
if (!guide) return new Response("ไม่พบไกด์", { status: 404 });
const [fonts, weaponImages] = await Promise.all([
anuphanFonts,
Promise.all(guide.weapons.map((row) => pngDataUrl(row.weapon.imageUrl))),
]);
const weaponHeights = guide.weapons.map((row) => {
const noteLines = row.note ? wrappedLineCount(row.note, 58) : 0;
return Math.max(112, noteLines ? 64 + noteLines * 22 : 112);
});
const noteLines = guide.note ? wrappedLineCount(guide.note, 70) : 0;
const headerHeight = 72 + (noteLines ? 12 + noteLines * 24 : 0);
const height = Math.max(
360,
64 +
headerHeight +
24 +
weaponHeights.reduce((sum, rowHeight) => sum + rowHeight, 0) +
Math.max(0, guide.weapons.length - 1) * 12,
);
return new ImageResponse(
<div
style={{
width: "100%",
height: "100%",
display: "flex",
flexDirection: "column",
color: "#f2eee6",
background: "#06070c",
padding: "32px 36px",
fontFamily: "Anuphan",
}}
>
<div
style={{
display: "flex",
flex: 1,
flexDirection: "column",
gap: 12,
}}
>
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 12,
marginBottom: 12,
}}
>
<div
style={{
display: "flex",
color: "#ebae42",
fontSize: 14,
fontWeight: 500,
lineHeight: 1.43,
}}
>
อาวุธที่แนะนำ
</div>
<div
style={{
display: "flex",
fontSize: 36,
fontWeight: 600,
lineHeight: 1.11,
}}
>
Weapons
</div>
{guide.note ? (
<div
style={{
display: "flex",
maxWidth: 760,
color: "#9b9eaa",
fontSize: 16,
lineHeight: 1.5,
textAlign: "center",
whiteSpace: "pre-wrap",
}}
>
{guide.note}
</div>
) : null}
</div>
{guide.weapons.map((row, index) => (
<div
key={row.id}
style={{
display: "flex",
minHeight: weaponHeights[index],
overflow: "hidden",
border: "1px solid rgba(242, 238, 230, 0.1)",
borderRadius: 14,
background: "#ffffff",
}}
>
<div
style={{
display: "flex",
flex: 3,
overflow: "hidden",
borderBottomRightRadius: 128,
background: rarityGradient(row.weapon.rarity),
color: "white",
padding: 0,
}}
>
<div
style={{
display: "flex",
flex: 1,
alignItems: "center",
gap: 16,
padding: "16px 64px 16px 16px",
}}
>
{weaponImages[index] ? (
<img
src={weaponImages[index]!}
alt=""
width={80}
height={80}
style={{ objectFit: "contain" }}
/>
) : (
<div
style={{
display: "flex",
width: 80,
height: 80,
alignItems: "center",
justifyContent: "center",
fontSize: 32,
}}
>
{index + 1}
</div>
)}
<div
style={{
display: "flex",
flex: 1,
minWidth: 0,
flexDirection: "column",
gap: 4,
}}
>
<div
style={{
display: "flex",
overflow: "hidden",
fontSize: 18,
fontWeight: 600,
lineHeight: 1.55,
textOverflow: "ellipsis",
whiteSpace: "nowrap",
}}
>
{index + 1}. {row.weapon.name} R{row.refinement}
</div>
{row.note ? (
<div
style={{
display: "flex",
fontSize: 14,
lineHeight: 1.43,
whiteSpace: "pre-wrap",
}}
>
{row.note}
</div>
) : null}
</div>
</div>
</div>
<div
style={{
display: "flex",
flex: 1,
alignItems: "center",
justifyContent: "space-around",
gap: 16,
color: "#000000",
padding: "20px 16px",
}}
>
{row.overallPercent ? (
<div
style={{
display: "flex",
flex: 1,
flexDirection: "column",
alignItems: "center",
}}
>
<div
style={{
display: "flex",
color: rarityTextColor(row.weapon.rarity),
fontSize: 48,
fontWeight: 700,
lineHeight: 1,
whiteSpace: "nowrap",
}}
>
{metric(row.overallPercent)}
</div>
<div
style={{ display: "flex", marginTop: 4, fontSize: 16 }}
>
ดาเมททั้งทีม
</div>
</div>
) : null}
{row.personalPercent ? (
<div
style={{
display: "flex",
flex: 1,
flexDirection: "column",
alignItems: "center",
}}
>
<div
style={{
display: "flex",
color: rarityTextColor(row.weapon.rarity),
fontSize: 48,
fontWeight: 700,
lineHeight: 1,
whiteSpace: "nowrap",
}}
>
{metric(row.personalPercent)}
</div>
<div
style={{ display: "flex", marginTop: 4, fontSize: 16 }}
>
ดาเมจส่วนตัว
</div>
</div>
) : null}
</div>
</div>
))}
</div>
</div>,
{
width: 1000,
height,
fonts: fonts.length ? fonts : undefined,
headers: {
"Cache-Control": "no-store",
"Content-Disposition": imageContentDisposition(
`${guide.guideName}-Weapon`,
"weapons",
),
"Content-Type": "image/png",
},
},
);
}
+101
View File
@@ -0,0 +1,101 @@
"use client";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { DownloadIcon } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
const EXPORT_WIDTH = 1200;
function downloadFileName(value: string): string {
return value.replace(/[\\/:*?"<>|]/gu, "-");
}
export function GuideImageExport({
children,
fileName,
}: {
children: ReactNode;
fileName: string;
}) {
const captureRef = useRef<HTMLDivElement>(null);
const [capturing, setCapturing] = useState(false);
useEffect(() => {
if (!capturing) return;
let cancelled = false;
async function capture() {
try {
const node = captureRef.current;
if (!node) throw new Error("Capture target is unavailable");
const { domToBlob, waitUntilLoad } = await import("modern-screenshot");
await Promise.all([document.fonts.ready, waitUntilLoad(node)]);
const blob = await domToBlob(node, {
backgroundColor: getComputedStyle(node).backgroundColor,
scale: 1,
width: EXPORT_WIDTH,
});
if (cancelled) return;
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.download = downloadFileName(fileName);
link.href = url;
document.body.append(link);
link.click();
link.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 0);
} catch {
if (!cancelled) toast.error("ส่งออกภาพไม่สำเร็จ กรุณาลองอีกครั้ง");
} finally {
if (!cancelled) setCapturing(false);
}
}
void capture();
return () => {
cancelled = true;
};
}, [capturing, fileName]);
return (
<>
<Button
type="button"
variant="outline"
size="sm"
disabled={capturing}
onClick={() => setCapturing(true)}
>
{capturing ? (
<Spinner data-icon="inline-start" />
) : (
<DownloadIcon data-icon="inline-start" />
)}
{capturing ? "กำลังส่งออก…" : "ส่งออกภาพ"}
</Button>
{capturing
? createPortal(
<div
aria-hidden="true"
className="pointer-events-none fixed top-0 -left-[10000px]"
>
<div
ref={captureRef}
className="w-[1200px] bg-background p-10 text-foreground"
>
{children}
</div>
</div>,
document.body,
)
: null}
</>
);
}
+171 -38
View File
@@ -1,9 +1,8 @@
import Image from "next/image"; import Image from "next/image";
import Link from "next/link"; import Link from "next/link";
import { ArrowUpRightIcon, ChevronLeftIcon, DownloadIcon } from "lucide-react"; import { ArrowUpRightIcon, ChevronLeftIcon } from "lucide-react";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { import {
Card, Card,
CardAction, CardAction,
@@ -16,6 +15,7 @@ import { Separator } from "@/components/ui/separator";
import { SiteHeader } from "@/components/public/site-header"; import { SiteHeader } from "@/components/public/site-header";
import { ScrollableNav } from "@/components/public/scrollable-nav"; import { ScrollableNav } from "@/components/public/scrollable-nav";
import { TeamSearch } from "@/components/public/team-search"; import { TeamSearch } from "@/components/public/team-search";
import { GuideImageExport } from "@/components/public/guide-image-export";
import { LiveRefresh } from "@/components/live-refresh"; import { LiveRefresh } from "@/components/live-refresh";
import { rarityGradientClass, rarityTextClass } from "@/lib/catalog/rarity"; import { rarityGradientClass, rarityTextClass } from "@/lib/catalog/rarity";
import type { PublicGuide } from "@/lib/guides/queries"; import type { PublicGuide } from "@/lib/guides/queries";
@@ -262,6 +262,27 @@ function metric(value: string | null) {
} }
function WeaponSection({ guide }: { guide: PublicGuide }) { function WeaponSection({ guide }: { guide: PublicGuide }) {
return (
<WeaponSectionContent
guide={guide}
action={
<GuideImageExport fileName={`${guide.name}-Weapon.png`}>
<WeaponSectionContent guide={guide} exporting />
</GuideImageExport>
}
/>
);
}
function WeaponSectionContent({
guide,
action,
exporting = false,
}: {
guide: PublicGuide;
action?: React.ReactNode;
exporting?: boolean;
}) {
const note = guide.sections.find( const note = guide.sections.find(
(section) => section.slug === "weapon", (section) => section.slug === "weapon",
)?.note; )?.note;
@@ -277,22 +298,25 @@ function WeaponSection({ guide }: { guide: PublicGuide }) {
{note} {note}
</p> </p>
) : null} ) : null}
<a {action}
href={`/api/guides/${guide.id}/weapons/image`}
download
className={buttonVariants({ variant: "outline", size: "sm" })}
>
<DownloadIcon data-icon="inline-start" />
ส่งออกภาพ
</a>
</header> </header>
<div className="grid gap-3"> <div className="grid gap-3">
{guide.weapons.map((row, index) => ( {guide.weapons.map((row, index) => (
<Card key={row.id} size="sm" className="bg-white py-0"> <Card key={row.id} size="sm" className="bg-white py-0">
<CardContent className="grid p-0 md:grid-cols-[minmax(0,3fr)_minmax(0,1fr)]"> <CardContent
className={cn(
"grid p-0",
exporting
? "grid-cols-[minmax(0,3fr)_minmax(0,1fr)]"
: "md:grid-cols-[minmax(0,3fr)_minmax(0,1fr)]",
)}
>
<div <div
className={cn( className={cn(
"flex min-h-28 min-w-0 items-center gap-4 rounded-br-[4rem] p-4 pr-10 text-white md:rounded-br-[8rem] md:pr-16", "flex min-h-28 min-w-0 items-center gap-4 rounded-br-[4rem] p-4 pr-10 text-white",
exporting
? "rounded-br-[8rem] pr-16"
: "md:rounded-br-[8rem] md:pr-16",
rarityGradientClass(row.weapon.rarity), rarityGradientClass(row.weapon.rarity),
)} )}
> >
@@ -301,12 +325,18 @@ function WeaponSection({ guide }: { guide: PublicGuide }) {
src={row.weapon.imageUrl} src={row.weapon.imageUrl}
alt={row.weapon.name} alt={row.weapon.name}
fill fill
loading={exporting ? "eager" : undefined}
sizes="(min-width: 768px) 5rem, 4rem" sizes="(min-width: 768px) 5rem, 4rem"
className="object-contain" className="object-contain"
/> />
</div> </div>
<div className="flex min-w-0 flex-col gap-1"> <div className="flex min-w-0 flex-col gap-1">
<p className="truncate text-base font-semibold sm:text-lg"> <p
className={cn(
"truncate font-semibold",
exporting ? "text-lg" : "text-base sm:text-lg",
)}
>
{index + 1}. {row.weapon.name} R{row.refinement} {index + 1}. {row.weapon.name} R{row.refinement}
</p> </p>
{row.note ? ( {row.note ? (
@@ -319,7 +349,8 @@ function WeaponSection({ guide }: { guide: PublicGuide }) {
<div className="flex-1 text-center"> <div className="flex-1 text-center">
<p <p
className={cn( className={cn(
"whitespace-nowrap text-4xl leading-none font-bold sm:text-5xl", "whitespace-nowrap leading-none font-bold",
exporting ? "text-5xl" : "text-4xl sm:text-5xl",
rarityTextClass(row.weapon.rarity), rarityTextClass(row.weapon.rarity),
)} )}
> >
@@ -327,14 +358,22 @@ function WeaponSection({ guide }: { guide: PublicGuide }) {
? "-%" ? "-%"
: metric(row.overallPercent)} : metric(row.overallPercent)}
</p> </p>
<p className="mt-1 text-sm sm:text-base">ดาเมททั้งทีม</p> <p
className={cn(
"mt-1",
exporting ? "text-base" : "text-sm sm:text-base",
)}
>
ดาเมททั้งทีม
</p>
</div> </div>
) : null} ) : null}
{row.personalPercent ? ( {row.personalPercent ? (
<div className="flex-1 text-center"> <div className="flex-1 text-center">
<p <p
className={cn( className={cn(
"whitespace-nowrap text-4xl leading-none font-bold sm:text-5xl", "whitespace-nowrap leading-none font-bold",
exporting ? "text-5xl" : "text-4xl sm:text-5xl",
rarityTextClass(row.weapon.rarity), rarityTextClass(row.weapon.rarity),
)} )}
> >
@@ -342,7 +381,14 @@ function WeaponSection({ guide }: { guide: PublicGuide }) {
? "-%" ? "-%"
: metric(row.personalPercent)} : metric(row.personalPercent)}
</p> </p>
<p className="mt-1 text-sm sm:text-base">ดาเมจส่วนตัว</p> <p
className={cn(
"mt-1",
exporting ? "text-base" : "text-sm sm:text-base",
)}
>
ดาเมจส่วนตัว
</p>
</div> </div>
) : null} ) : null}
</div> </div>
@@ -355,6 +401,27 @@ function WeaponSection({ guide }: { guide: PublicGuide }) {
} }
function ArtifactSection({ guide }: { guide: PublicGuide }) { function ArtifactSection({ guide }: { guide: PublicGuide }) {
return (
<ArtifactSectionContent
guide={guide}
action={
<GuideImageExport fileName={`${guide.name}-Artifact.png`}>
<ArtifactSectionContent guide={guide} exporting />
</GuideImageExport>
}
/>
);
}
function ArtifactSectionContent({
guide,
action,
exporting = false,
}: {
guide: PublicGuide;
action?: React.ReactNode;
exporting?: boolean;
}) {
const profile = guide.artifactProfile; const profile = guide.artifactProfile;
return ( return (
<section className="flex flex-col gap-6"> <section className="flex flex-col gap-6">
@@ -365,16 +432,14 @@ function ArtifactSection({ guide }: { guide: PublicGuide }) {
<h1 className="font-heading text-4xl font-semibold"> <h1 className="font-heading text-4xl font-semibold">
Artifact & Stats Artifact & Stats
</h1> </h1>
<a {action}
href={`/api/guides/${guide.id}/artifacts/image`}
download
className={buttonVariants({ variant: "outline", size: "sm" })}
>
<DownloadIcon data-icon="inline-start" />
ส่งออกภาพ
</a>
</header> </header>
<div className="grid gap-5 lg:grid-cols-[1.2fr_1fr]"> <div
className={cn(
"grid gap-5",
exporting ? "grid-cols-[1.2fr_1fr]" : "lg:grid-cols-[1.2fr_1fr]",
)}
>
{" "} {" "}
<div className="flex flex-col gap-5"> <div className="flex flex-col gap-5">
{profile ? ( {profile ? (
@@ -387,16 +452,19 @@ function ArtifactSection({ guide }: { guide: PublicGuide }) {
iconSrc="/icon/Icon_Sands_of_Eon.webp" iconSrc="/icon/Icon_Sands_of_Eon.webp"
label="นาฬิกา" label="นาฬิกา"
values={profile.sands} values={profile.sands}
exporting={exporting}
/> />
<ArtifactStat <ArtifactStat
iconSrc="/icon/Icon_Goblet_of_Eonothem.webp" iconSrc="/icon/Icon_Goblet_of_Eonothem.webp"
label="ถ้วย" label="ถ้วย"
values={profile.goblet} values={profile.goblet}
exporting={exporting}
/> />
<ArtifactStat <ArtifactStat
iconSrc="/icon/Icon_Circlet_of_Logos.webp" iconSrc="/icon/Icon_Circlet_of_Logos.webp"
label="หัว" label="หัว"
values={profile.circlet} values={profile.circlet}
exporting={exporting}
/> />
</CardContent> </CardContent>
</Card> </Card>
@@ -411,6 +479,7 @@ function ArtifactSection({ guide }: { guide: PublicGuide }) {
key={`${stat}-${index}`} key={`${stat}-${index}`}
value={stat} value={stat}
index={index} index={index}
exporting={exporting}
/> />
))} ))}
</div> </div>
@@ -441,7 +510,8 @@ function ArtifactSection({ guide }: { guide: PublicGuide }) {
<div className="flex -space-x-3"> <div className="flex -space-x-3">
<div <div
className={cn( className={cn(
"relative size-14 overflow-hidden rounded-lg border sm:size-16", "relative overflow-hidden rounded-lg border",
exporting ? "size-16" : "size-14 sm:size-16",
rarityGradientClass(row.first.rarity), rarityGradientClass(row.first.rarity),
)} )}
> >
@@ -449,6 +519,7 @@ function ArtifactSection({ guide }: { guide: PublicGuide }) {
src={row.first.imageUrl} src={row.first.imageUrl}
alt={row.first.name} alt={row.first.name}
fill fill
loading={exporting ? "eager" : undefined}
sizes="(min-width: 640px) 4rem, 3.5rem" sizes="(min-width: 640px) 4rem, 3.5rem"
className="object-contain" className="object-contain"
/> />
@@ -456,7 +527,8 @@ function ArtifactSection({ guide }: { guide: PublicGuide }) {
{row.second ? ( {row.second ? (
<div <div
className={cn( className={cn(
"relative size-14 overflow-hidden rounded-lg border sm:size-16", "relative overflow-hidden rounded-lg border",
exporting ? "size-16" : "size-14 sm:size-16",
rarityGradientClass(row.second.rarity), rarityGradientClass(row.second.rarity),
)} )}
> >
@@ -464,6 +536,7 @@ function ArtifactSection({ guide }: { guide: PublicGuide }) {
src={row.second.imageUrl} src={row.second.imageUrl}
alt={row.second.name} alt={row.second.name}
fill fill
loading={exporting ? "eager" : undefined}
sizes="(min-width: 640px) 4rem, 3.5rem" sizes="(min-width: 640px) 4rem, 3.5rem"
className="object-contain" className="object-contain"
/> />
@@ -517,6 +590,7 @@ function ArtifactSection({ guide }: { guide: PublicGuide }) {
alt="" alt=""
width={14} width={14}
height={14} height={14}
loading={exporting ? "eager" : undefined}
className="size-3.5 shrink-0 object-contain brightness-0 invert" className="size-3.5 shrink-0 object-contain brightness-0 invert"
/> />
) : null} ) : null}
@@ -537,7 +611,12 @@ function ArtifactSection({ guide }: { guide: PublicGuide }) {
<p className="mb-2 text-sm font-medium"> <p className="mb-2 text-sm font-medium">
ลำดับการอัพพรสวรรค์ ลำดับการอัพพรสวรรค์
</p> </p>
<div className="flex items-start justify-center gap-1 sm:gap-3"> <div
className={cn(
"flex items-start justify-center",
exporting ? "gap-3" : "gap-1 sm:gap-3",
)}
>
{normalizeTalentPriorities(profile.talents).map( {normalizeTalentPriorities(profile.talents).map(
(talent, index, talents) => { (talent, index, talents) => {
const catalogTalent = guide.character.talents.find( const catalogTalent = guide.character.talents.find(
@@ -547,15 +626,29 @@ function ArtifactSection({ guide }: { guide: PublicGuide }) {
return ( return (
<div <div
key={talent.type} key={talent.type}
className="flex min-w-0 items-start gap-1 sm:gap-3" className={cn(
"flex min-w-0 items-start",
exporting ? "gap-3" : "gap-1 sm:gap-3",
)}
> >
<div className="flex w-16 flex-col items-center gap-2 text-center sm:w-28"> <div
<div className="relative size-14 overflow-hidden rounded-xl border bg-muted sm:size-20"> className={cn(
"flex flex-col items-center gap-2 text-center",
exporting ? "w-28" : "w-16 sm:w-28",
)}
>
<div
className={cn(
"relative overflow-hidden rounded-xl border bg-muted",
exporting ? "size-20" : "size-14 sm:size-20",
)}
>
{catalogTalent?.iconUrl ? ( {catalogTalent?.iconUrl ? (
<Image <Image
src={catalogTalent.iconUrl} src={catalogTalent.iconUrl}
alt={talentName} alt={talentName}
fill fill
loading={exporting ? "eager" : undefined}
className="object-contain" className="object-contain"
/> />
) : ( ) : (
@@ -569,16 +662,31 @@ function ArtifactSection({ guide }: { guide: PublicGuide }) {
? `เลเวล ${talent.level}+` ? `เลเวล ${talent.level}+`
: "-"} : "-"}
</Badge> </Badge>
<p className="text-xs font-medium sm:text-sm"> <p
className={cn(
"font-medium",
exporting ? "text-sm" : "text-xs sm:text-sm",
)}
>
{talentName} {talentName}
</p> </p>
<p className="text-[11px] text-muted-foreground sm:text-xs"> <p
className={cn(
"text-muted-foreground",
exporting ? "text-xs" : "text-[11px] sm:text-xs",
)}
>
{talentTypeLabel(talent.type)} {talentTypeLabel(talent.type)}
</p> </p>
</div> </div>
{index < talents.length - 1 ? ( {index < talents.length - 1 ? (
<span <span
className="mt-4 text-xl font-semibold sm:mt-6 sm:text-3xl" className={cn(
"font-semibold",
exporting
? "mt-6 text-3xl"
: "mt-4 text-xl sm:mt-6 sm:text-3xl",
)}
aria-label={ aria-label={
talent.relationToNext === "gte" talent.relationToNext === "gte"
? "มากกว่าหรือเท่ากับ" ? "มากกว่าหรือเท่ากับ"
@@ -644,29 +752,45 @@ function ArtifactStat({
iconSrc, iconSrc,
label, label,
values, values,
exporting = false,
}: { }: {
iconSrc: string; iconSrc: string;
label: string; label: string;
values: string[]; values: string[];
exporting?: boolean;
}) { }) {
return ( return (
<div className="flex min-w-0 flex-col items-center gap-3 border-r p-3 text-center last:border-r-0 sm:p-5"> <div
className={cn(
"flex min-w-0 flex-col items-center gap-3 border-r text-center last:border-r-0",
exporting ? "p-5" : "p-3 sm:p-5",
)}
>
<Image <Image
src={iconSrc} src={iconSrc}
alt="" alt=""
width={48} width={48}
height={48} height={48}
loading={exporting ? "eager" : undefined}
className="size-12 object-contain" className="size-12 object-contain"
/> />
<p className="font-semibold">{label}</p> <p className="font-semibold">{label}</p>
<Separator /> <Separator />
<div className="flex max-w-full flex-col items-center gap-1 text-xs leading-5 sm:text-sm sm:leading-6"> <div
className={cn(
"flex max-w-full flex-col items-center gap-1",
exporting
? "text-sm leading-6"
: "text-xs leading-5 sm:text-sm sm:leading-6",
)}
>
{values.length ? ( {values.length ? (
values.map((value, index) => ( values.map((value, index) => (
<ArtifactStatValue <ArtifactStatValue
key={`${value}-${index}`} key={`${value}-${index}`}
value={value} value={value}
index={index} index={index}
exporting={exporting}
/> />
)) ))
) : ( ) : (
@@ -677,7 +801,15 @@ function ArtifactStat({
); );
} }
function ArtifactStatValue({ value, index }: { value: string; index: number }) { function ArtifactStatValue({
value,
index,
exporting = false,
}: {
value: string;
index: number;
exporting?: boolean;
}) {
const iconName = recommendedStatIconName(value); const iconName = recommendedStatIconName(value);
const hasIcon = const hasIcon =
iconName && iconName &&
@@ -695,6 +827,7 @@ function ArtifactStatValue({ value, index }: { value: string; index: number }) {
alt="" alt=""
width={20} width={20}
height={20} height={20}
loading={exporting ? "eager" : undefined}
className="size-5 shrink-0 object-contain brightness-0 invert" className="size-5 shrink-0 object-contain brightness-0 invert"
/> />
) : null} ) : null}
-18
View File
@@ -4,10 +4,8 @@ import { cacheLife, cacheTag } from "next/cache";
import { getPublicPage, listPublicCharacters } from "@/lib/content/queries"; import { getPublicPage, listPublicCharacters } from "@/lib/content/queries";
import { import {
getPublicArtifactExport,
getPublicGuide, getPublicGuide,
getPublicTeamExport, getPublicTeamExport,
getPublicWeaponExport,
listGuideCards, listGuideCards,
} from "@/lib/guides/queries"; } from "@/lib/guides/queries";
import { import {
@@ -71,19 +69,3 @@ export async function getCachedPublicTeamExport(teamId: string) {
if (result) cacheTag(pageCacheTag(result.guideId)); if (result) cacheTag(pageCacheTag(result.guideId));
return result; return result;
} }
export async function getCachedPublicWeaponExport(guideId: string) {
"use cache: remote";
cacheLife({ stale: 15, revalidate: 60, expire: 60 * 60 });
const result = await getPublicWeaponExport(guideId);
cacheTag(pageCacheTag(guideId));
return result;
}
export async function getCachedPublicArtifactExport(guideId: string) {
"use cache: remote";
cacheLife({ stale: 15, revalidate: 60, expire: 60 * 60 });
const result = await getPublicArtifactExport(guideId);
cacheTag(pageCacheTag(guideId));
return result;
}
-98
View File
@@ -187,102 +187,4 @@ export async function getPublicTeamExport(teamId: string) {
}; };
} }
export async function getPublicWeaponExport(guideId: string) {
const [row] = await getDb()
.select({ guide: guides, note: guideSections.note })
.from(guides)
.innerJoin(
guideSections,
and(
eq(guideSections.guideId, guides.id),
eq(guideSections.slug, "weapon"),
eq(guideSections.enabled, true),
),
)
.where(and(eq(guides.id, guideId), isNull(guides.trashedAt)))
.limit(1);
if (!row) return null;
const weapons = await getDb()
.select({ recommendation: weaponRecommendations, weapon: catalogWeapons })
.from(weaponRecommendations)
.innerJoin(
catalogWeapons,
eq(catalogWeapons.key, weaponRecommendations.weaponKey),
)
.where(eq(weaponRecommendations.guideId, guideId))
.orderBy(asc(weaponRecommendations.sortOrder));
return {
guideName: row.guide.name,
note: row.note,
weapons: weapons.map(({ recommendation, weapon }) => ({
...recommendation,
weapon: { ...weapon, imageUrl: publicMediaUrl(weapon.imageKey) },
})),
};
}
export async function getPublicArtifactExport(guideId: string) {
const [row] = await getDb()
.select({ guide: guides, character: catalogCharacters })
.from(guides)
.innerJoin(
guideSections,
and(
eq(guideSections.guideId, guides.id),
eq(guideSections.slug, "artifact"),
eq(guideSections.enabled, true),
),
)
.innerJoin(
catalogCharacters,
eq(catalogCharacters.key, guides.characterKey),
)
.where(and(eq(guides.id, guideId), isNull(guides.trashedAt)))
.limit(1);
if (!row) return null;
const [groups, profile] = await Promise.all([
getDb().select().from(artifactGroups).where(eq(artifactGroups.guideId, guideId)).orderBy(asc(artifactGroups.sortOrder)),
getDb().select().from(artifactProfiles).where(eq(artifactProfiles.guideId, guideId)).limit(1),
]);
const recommendations = groups.length
? await getDb()
.select({ recommendation: artifactRecommendations, artifact: catalogArtifacts })
.from(artifactRecommendations)
.innerJoin(
catalogArtifacts,
eq(catalogArtifacts.key, artifactRecommendations.firstArtifactKey),
)
.where(inArray(artifactRecommendations.groupId, groups.map((group) => group.id)))
.orderBy(asc(artifactRecommendations.sortOrder))
: [];
const secondKeys = recommendations
.map(({ recommendation }) => recommendation.secondArtifactKey)
.filter((key): key is string => Boolean(key));
const secondArtifacts = secondKeys.length
? await getDb().select().from(catalogArtifacts).where(inArray(catalogArtifacts.key, secondKeys))
: [];
return {
guideName: row.guide.name,
character: catalogCharacterWithUrls(row.character),
groups: groups.map((group) => ({
...group,
rows: recommendations
.filter(({ recommendation }) => recommendation.groupId === group.id)
.map(({ recommendation, artifact }) => {
const second = secondArtifacts.find((item) => item.key === recommendation.secondArtifactKey);
return {
...recommendation,
first: { ...artifact, imageUrl: publicMediaUrl(artifact.imageKey) },
second: second ? { ...second, imageUrl: publicMediaUrl(second.imageKey) } : null,
};
}),
})),
profile: profile[0] ?? null,
};
}
export type PublicGuide = NonNullable<Awaited<ReturnType<typeof getPublicGuide>>>; export type PublicGuide = NonNullable<Awaited<ReturnType<typeof getPublicGuide>>>;