feat : Con more reaible

This commit is contained in:
2026-09-26 20:54:40 +07:00 Unverified
parent bfd9f1765d
commit 17c4f21948
11 changed files with 325 additions and 24 deletions
+45
View File
@@ -0,0 +1,45 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { LunarisText } from "@/components/public/lunaris-text";
import type { CatalogTextNode } from "@/lib/catalog/lunaris";
describe("LunarisText", () => {
it("renders source colors and an accessible interactive term", () => {
const nodes: CatalogTextNode[] = [
{
type: "link",
target: "N11500003",
detail: {
name: "Marvelous Splendor",
description: "First line\nSecond line",
},
children: [{ type: "text", value: "Marvelous Splendor" }],
},
{ type: "text", value: " deals " },
{
type: "color",
value: "#99FFFFFF",
children: [{ type: "text", value: "Cryo AoE DMG" }],
},
];
const html = renderToStaticMarkup(
<LunarisText nodes={nodes} fallback="fallback" />,
);
expect(html).toContain("Marvelous Splendor");
expect(html).toContain("aria-label=\"เปิดรายละเอียด Marvelous Splendor\"");
expect(html).toContain("hover:bg-primary/15");
expect(html).toContain("hover:decoration-2 hover:decoration-primary");
expect(html).toContain("color:#99FFFFFF");
expect(html).toContain("Cryo AoE DMG");
expect(html).not.toContain("fallback");
});
it("uses plain text for catalogs without structured nodes", () => {
expect(renderToStaticMarkup(
<LunarisText fallback="Legacy detail" />,
)).toContain("Legacy detail");
});
});
+54
View File
@@ -8,6 +8,7 @@ import {
characterDetailSchema,
cleanLunarisText,
constellationSnapshot,
parseLunarisText,
nameCardImageName,
splashImageName,
supportsWeaponType,
@@ -41,6 +42,58 @@ describe("Lunaris character data", () => {
expect(cleanLunarisText("First line\\n\\n<i>Second line</i>")).toBe("First line\n\nSecond line");
});
it("parses Lunaris links and colors into safe display nodes", () => {
const links = new Map([["N11500003", {
name: "Marvelous Splendor",
description: "A special stack effect.",
}]]);
expect(parseLunarisText(
"Gain {LINK#N11500003}Marvelous Splendor{/LINK} and deal <color=#99FFFFFF>Cryo AoE DMG</color>.",
links,
)).toEqual([
{ type: "text", value: "Gain " },
{
type: "link",
target: "N11500003",
detail: { name: "Marvelous Splendor", description: "A special stack effect." },
children: [{ type: "text", value: "Marvelous Splendor" }],
},
{ type: "text", value: " and deal " },
{
type: "color",
value: "#99FFFFFF",
children: [{ type: "text", value: "Cryo AoE DMG" }],
},
{ type: "text", value: "." },
]);
});
it("resolves named skill links and ignores malformed display tags", () => {
const skills = new Map([["Slow Dance", {
name: "Slow Dance",
description: "Skill detail",
}]]);
expect(parseLunarisText(
"{LINK#S11502}<color=#FFD780FF>Slow Dance</color>{/LINK}</color>\n<color=javascript:alert(1)>Safe</color>",
new Map(),
skills,
)).toEqual([
{
type: "link",
target: "S11502",
detail: { name: "Slow Dance", description: "Skill detail" },
children: [{
type: "color",
value: "#FFD780FF",
children: [{ type: "text", value: "Slow Dance" }],
}],
},
{ type: "text", value: "\nSafe" },
]);
});
it("normalizes constellation levels and icon keys", () => {
const result = constellationSnapshot({
constellations: {
@@ -51,6 +104,7 @@ describe("Lunaris character data", () => {
level: 1,
name: "First",
description: "Detail",
descriptionNodes: [{ type: "text", value: "Detail" }],
iconKey: "catalog/1/constellations/UI_Talent_Test_01.webp",
}]);
});
+119
View File
@@ -4,9 +4,25 @@ export interface CatalogConstellation {
level: number;
name: string;
description: string;
descriptionNodes?: CatalogTextNode[];
iconKey: string | null;
}
export interface CatalogTextDetail {
name: string;
description: string;
}
export type CatalogTextNode =
| { type: "text"; value: string }
| { type: "color"; value: string; children: CatalogTextNode[] }
| {
type: "link";
target: string;
detail: CatalogTextDetail | null;
children: CatalogTextNode[];
};
export interface CatalogTalent {
type: "NA" | "E" | "Q";
name: string;
@@ -52,6 +68,12 @@ const skillSchema = z.object({
icon: z.string(),
});
const hyperlinkSchema = z.object({
id: z.number().int(),
name: z.string(),
description: z.string(),
});
const attributeSchema = z.record(z.string(), z.union([z.number(), z.string()]));
const levelingSchema = z.record(z.string(), z.record(z.string(), z.number().int()));
@@ -62,6 +84,7 @@ export const characterDetailSchema = z.object({
attributes: z.array(attributeSchema).nullish(),
}).nullish(),
constellations: z.record(z.string(), constellationSchema).nullish(),
hyperlinks: z.array(hyperlinkSchema).nullish(),
skills: z.object({
normalattack: skillSchema.optional(),
elementalskill: skillSchema.optional(),
@@ -85,6 +108,79 @@ export function cleanLunarisText(value: string): string {
.trim();
}
const lunarisTagPattern = /(\{LINK#[^}]+\}|\{\/LINK\}|<color=#[0-9a-f]{6}(?:[0-9a-f]{2})?>|<\/color>|<[^>]+>)/giu;
function textFromNodes(nodes: CatalogTextNode[]): string {
return nodes.map((node) =>
node.type === "text" ? node.value : textFromNodes(node.children)
).join("");
}
export function parseLunarisText(
value: string,
linkDetails: ReadonlyMap<string, CatalogTextDetail> = new Map(),
namedDetails: ReadonlyMap<string, CatalogTextDetail> = new Map(),
): CatalogTextNode[] {
const appendText = (children: CatalogTextNode[], text: string) => {
const previous = children.at(-1);
if (previous?.type === "text") previous.value += text;
else children.push({ type: "text", value: text });
};
const root: CatalogTextNode[] = [];
const stack: Array<{
type: "root" | "color" | "link";
children: CatalogTextNode[];
node?: Extract<CatalogTextNode, { type: "color" | "link" }>;
}> = [{ type: "root", children: root }];
const source = value
.replace(/\\n/gu, "\n")
.replace(/^"|"$/gu, "");
let offset = 0;
for (const match of source.matchAll(lunarisTagPattern)) {
const index = match.index;
const current = stack.at(-1)!;
if (index > offset) {
appendText(current.children, source.slice(offset, index));
}
const tag = match[0];
const link = /^\{LINK#([^}]+)\}$/iu.exec(tag);
const color = /^<color=(#[0-9a-f]{6}(?:[0-9a-f]{2})?)>$/iu.exec(tag);
if (link) {
const node: Extract<CatalogTextNode, { type: "link" }> = {
type: "link",
target: link[1],
detail: linkDetails.get(link[1]) ?? null,
children: [],
};
current.children.push(node);
stack.push({ type: "link", children: node.children, node });
} else if (color) {
const node: Extract<CatalogTextNode, { type: "color" }> = {
type: "color",
value: color[1],
children: [],
};
current.children.push(node);
stack.push({ type: "color", children: node.children, node });
} else if (tag.toUpperCase() === "{/LINK}" && stack.at(-1)?.type === "link") {
const frame = stack.pop();
if (frame?.node?.type === "link" && !frame.node.detail) {
frame.node.detail = namedDetails.get(textFromNodes(frame.children).trim()) ?? null;
}
} else if (tag.toLowerCase() === "</color>" && stack.at(-1)?.type === "color") {
stack.pop();
}
offset = index + tag.length;
}
if (offset < source.length) {
appendText(stack.at(-1)!.children, source.slice(offset));
}
return root;
}
export function avatarIconName(value: string): string {
return value.replace(/^UI_Gacha_AvatarIcon_/u, "UI_AvatarIcon_");
}
@@ -113,6 +209,28 @@ export function constellationSnapshot(
iconKey: (icon: string) => string,
): CatalogConstellation[] {
const result: CatalogConstellation[] = [];
const linkDetails = new Map(
(value.hyperlinks ?? []).map((item) => [
`N${item.id}`,
{
name: cleanLunarisText(item.name),
description: cleanLunarisText(item.description),
},
]),
);
const namedDetails = new Map(
[
value.skills?.normalattack,
value.skills?.elementalskill,
value.skills?.elementalburst,
].flatMap((skill) => skill ? [[
cleanLunarisText(skill.name),
{
name: cleanLunarisText(skill.name),
description: cleanLunarisText(skill.description),
},
] as const] : []),
);
for (const index of Array.from({ length: 6 }, (_, itemIndex) => itemIndex)) {
const level = index + 1;
const item = value.constellations?.[`const${level}`];
@@ -121,6 +239,7 @@ export function constellationSnapshot(
level,
name: cleanLunarisText(item.name),
description: cleanLunarisText(item.description),
descriptionNodes: parseLunarisText(item.description, linkDetails, namedDetails),
iconKey: iconKey(item.icon),
});
}
+21 -7
View File
@@ -33,7 +33,8 @@ import { customTravelers, isUpstreamTraveler } from "@/lib/catalog/travelers";
import { withCatalogSyncLock } from "@/lib/catalog/sync-lock";
import { getRedisClient, redisEventPrefix } from "@/lib/redis/client";
import {
compareLunarisVersions,
catalogFormatVersion,
catalogSnapshotIsCurrent,
lunarisVersionSchema,
} from "@/lib/catalog/version";
import { getMediaStorage } from "@/lib/media/storage";
@@ -53,7 +54,10 @@ const versionSchema = z.object({
version: lunarisVersionSchema,
timestamp: z.number().int().optional(),
});
const currentVersionSchema = z.object({ version: lunarisVersionSchema });
const currentVersionSchema = z.object({
version: lunarisVersionSchema,
formatVersion: z.number().int().optional().default(1),
});
const characterSchema = z.record(
z.string(),
z.object({
@@ -636,7 +640,10 @@ async function syncCatalogVersion(version: string, control?: SyncControl): Promi
);
});
await control?.report("database", 1, 1, "บันทึก Catalog แล้ว");
await storage.write("catalog/current.json", JSON.stringify({ version }), {
await storage.write("catalog/current.json", JSON.stringify({
version,
formatVersion: catalogFormatVersion,
}), {
type: "application/json",
acl: "public-read",
});
@@ -717,10 +724,14 @@ async function executeCatalogSyncJob(initial: CatalogSyncJob) {
}
export async function getCurrentCatalogVersion(): Promise<string | null> {
return (await getCurrentCatalogState())?.version ?? null;
}
async function getCurrentCatalogState() {
const storage = await getMediaStorage();
const current = storage.file("catalog/current.json");
if (!(await current.exists())) return null;
return currentVersionSchema.parse(await current.json()).version;
return currentVersionSchema.parse(await current.json());
}
async function hasCatalogRecords(): Promise<boolean> {
@@ -743,10 +754,13 @@ export async function processCatalogSync(
);
return withCatalogSyncLock(async () => {
const currentVersion = await getCurrentCatalogVersion();
const current = await getCurrentCatalogState();
if (
currentVersion &&
compareLunarisVersions(version, currentVersion) <= 0 &&
catalogSnapshotIsCurrent(
version,
current?.version ?? null,
current?.formatVersion ?? null,
) &&
await hasCatalogRecords()
) {
return "unchanged";
+8
View File
@@ -1,6 +1,8 @@
import { describe, expect, it } from "vitest";
import {
catalogFormatVersion,
catalogSnapshotIsCurrent,
compareLunarisVersions,
parseLunarisVersionChange,
} from "./version";
@@ -29,4 +31,10 @@ Odette`),
expect(compareLunarisVersions("7.0.54", "7.0.54.0")).toBe(0);
expect(compareLunarisVersions("7.0.53.2", "7.0.54")).toBe(-1);
});
it("refreshes a same-version catalog when its local format is outdated", () => {
expect(catalogSnapshotIsCurrent("7.0.54", "7.0.54", null)).toBe(false);
expect(catalogSnapshotIsCurrent("7.0.54", "7.0.54", catalogFormatVersion - 1)).toBe(false);
expect(catalogSnapshotIsCurrent("7.0.54", "7.0.54", catalogFormatVersion)).toBe(true);
});
});
+13
View File
@@ -1,6 +1,7 @@
import * as z from "zod";
export const lunarisVersionSchema = z.string().regex(/^\d+(?:\.\d+)+$/u);
export const catalogFormatVersion = 2;
export interface LunarisVersionChange {
previousVersion: string;
@@ -31,3 +32,15 @@ export function compareLunarisVersions(left: string, right: string): number {
}
return 0;
}
export function catalogSnapshotIsCurrent(
requestedVersion: string,
currentVersion: string | null,
currentFormatVersion: number | null,
): boolean {
return Boolean(
currentVersion &&
compareLunarisVersions(requestedVersion, currentVersion) <= 0 &&
currentFormatVersion === catalogFormatVersion
);
}
+1
View File
@@ -472,6 +472,7 @@ async function getGuideContent(slug: string, publicOnly: boolean, selectedSectio
...recommendation,
name: catalog?.name ?? `C${recommendation.level}`,
detail: catalog?.description ?? recommendation.detail,
detailNodes: catalog?.descriptionNodes,
iconUrl: catalog?.iconKey ? publicMediaUrl(catalog.iconKey) : null,
};
}),