56 lines
2.1 KiB
TypeScript
56 lines
2.1 KiB
TypeScript
import type { Messages } from "@/lib/i18n/messages";
|
|
import type { TermEntry } from "@/lib/content-types";
|
|
|
|
/** clone แบบคงฟังก์ชันไว้ (Messages มีฟังก์ชันเช่น gallery.more — structuredClone ใช้ไม่ได้) */
|
|
function cloneMessages<T>(value: T): T {
|
|
if (Array.isArray(value)) {
|
|
return value.map((item) => cloneMessages(item)) as unknown as T;
|
|
}
|
|
if (value && typeof value === "object") {
|
|
const result: Record<string, unknown> = {};
|
|
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
|
|
result[key] = cloneMessages(child);
|
|
}
|
|
return result as T;
|
|
}
|
|
return value;
|
|
}
|
|
|
|
/** เขียนค่าที่ dot path ที่ระบุ ถ้าปลายทางเป็น string เท่านั้น (ไม่ทับฟังก์ชัน) */
|
|
function setPath(
|
|
target: Record<string, unknown>,
|
|
path: string,
|
|
value: string,
|
|
): void {
|
|
const segments = path.split(".");
|
|
let cursor: Record<string, unknown> = target;
|
|
|
|
for (const segment of segments.slice(0, -1)) {
|
|
const next = cursor[segment];
|
|
if (!next || typeof next !== "object") return;
|
|
cursor = next as Record<string, unknown>;
|
|
}
|
|
|
|
const leaf = segments[segments.length - 1];
|
|
if (typeof cursor[leaf] !== "string") return;
|
|
cursor[leaf] = value;
|
|
}
|
|
|
|
/**
|
|
* รวมคำศัพท์ที่แก้จากหลังบ้านทับข้อความตั้งต้น
|
|
* คำศัพท์ที่ key ไม่ตรงหรือปลายทางไม่ใช่ข้อความจะถูกข้าม (ไม่ทำให้หน้าพัง)
|
|
*/
|
|
export function applyTerms(
|
|
base: Messages,
|
|
terms: TermEntry[],
|
|
locale: string,
|
|
): Messages {
|
|
const draft = cloneMessages(base) as unknown as Record<string, unknown>;
|
|
for (const term of terms) {
|
|
const value = term.values[locale];
|
|
if (typeof value !== "string" || value === "") continue;
|
|
setPath(draft, term.key, value);
|
|
}
|
|
return draft as unknown as Messages;
|
|
}
|