chore: deploy 触发分支改 master,竞品调研/原型/色板/i18n/分享组件/文档等成果入库

This commit is contained in:
Sisyphus committed 2026-08-14 09:58:52 +08:00
1 parent 5a97e6124e
commit 40e2342a02
75 files changed
+6848 -540

No files matched your search

+67 -17
View File
@@ -28,6 +28,11 @@ import {
} from './lib/grid-edit';
import { buildExportCanvas, downloadCanvas } from './lib/drawPattern';
import { consumeCode, redeemCode } from './lib/api';
import { decodePattern } from './lib/share-codec';
import { BRANDS } from './lib/brand-palettes';
import type { ProcessResult } from './lib/image-processor';
import ShareButton from './components/ShareButton';
import { useT } from './i18n';
const DEFAULT_SETTINGS: PatternSettings = {
gridSize: 32,
@@ -40,9 +45,10 @@ const DEFAULT_SETTINGS: PatternSettings = {
const DEFAULT_PLAN: Plan = {
key: 'standard',
name: '常用包',
nameKey: 'pass.plan.standard.name',
price: '12.9',
count: '10 次',
desc: '适合个人多次创作(推荐)',
countKey: 'pass.plan.standard.count',
descKey: 'pass.plan.standard.desc',
featured: true,
};
@@ -52,8 +58,16 @@ type ModalState =
| { kind: 'order'; plan: Plan }
| null;
/** T-067:从 ?share= 分享码解码出的图纸(含品牌与边长信息)。 */
interface SharedPattern {
result: ProcessResult;
size: number;
brandId: string;
}
/** Homepage: NAV → HERO → DOWNLOAD PASS → 工作区三栏 → FOOTER. */
function HomePage() {
const { t } = useT();
const [source, setSource] = useState<SourceImage | null>(null);
const [settings, setSettings] = useState<PatternSettings>(DEFAULT_SETTINGS);
const [runId, setRunId] = useState(0);
@@ -62,6 +76,9 @@ function HomePage() {
const [uploadError, setUploadError] = useState<string | null>(null);
const [modal, setModal] = useState<ModalState>(null);
// T-067 分享:?share= 分享码解码出的图纸(绕过上传直接渲染)。
const [sharedPattern, setSharedPattern] = useState<SharedPattern | null>(null);
// 编辑工具(T-069/T-068):当前网格快照 + 撤销/重做历史。
const [gridState, setGridState] = useState<GridState | null>(null);
const historyRef = useRef<EditHistory | null>(null);
@@ -74,19 +91,44 @@ function HomePage() {
const { result, processing, error } = usePattern(source, settings, runId);
// T-067:加载 ?share= 分享码 → 解码 → 绕过上传直接渲染分享图纸;
// brand 参数仅用于设置品牌(非法/缺失时回退默认 MARD)。
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const code = params.get('share');
if (code === null) return;
const decoded = decodePattern(code);
if (decoded === null) return;
const brandParam = params.get('brand');
const brandId =
brandParam !== null && BRANDS.some((b) => b.id === brandParam)
? brandParam
: DEFAULT_SETTINGS.brandId;
setSharedPattern({
result: gridStateToProcessResult({ grid: decoded.grid, size: decoded.size }),
size: decoded.size,
brandId,
});
setSettings((s) => ({ ...s, gridSize: decoded.size, brandId }));
}, []);
// 分享图纸优先于本地处理结果(用户后续上传图片时清空分享状态)。
const effectiveResult = sharedPattern !== null ? sharedPattern.result : result;
const effectiveSize = sharedPattern !== null ? sharedPattern.size : settings.gridSize;
// 新的管线结果到达时,重置编辑状态(历史不跨图纸保留)。
useEffect(() => {
history.clear();
setGridState(result ? resultToGridState(result, settings.gridSize) : null);
}, [result, settings.gridSize, history]);
setGridState(effectiveResult ? resultToGridState(effectiveResult, effectiveSize) : null);
}, [effectiveResult, effectiveSize, history]);
// 预览/清单/下载统一使用「编辑后的网格」重建的 ProcessResult;
// 结果尚未同步进 state 的首帧直接由原始 result 派生,避免闪烁。
const editedResult = useMemo(() => {
if (!result) return null;
const base = gridState ?? resultToGridState(result, settings.gridSize);
if (!effectiveResult) return null;
const base = gridState ?? resultToGridState(effectiveResult, effectiveSize);
return gridStateToProcessResult(base);
}, [gridState, result, settings.gridSize]);
}, [gridState, effectiveResult, effectiveSize]);
// Revoke object URLs when the source is replaced.
useEffect(() => {
@@ -96,6 +138,7 @@ function HomePage() {
}, [source]);
const handleFileSelected = useCallback((file: File) => {
setSharedPattern(null); // 上传新图后退出分享模式
void loadImageFromFile(file).then(
(next) => {
setSource((prev) => {
@@ -105,12 +148,13 @@ function HomePage() {
setUploadError(null);
},
(err: unknown) => {
setUploadError(err instanceof Error ? err.message : '图片读取失败,请换一张重试');
setUploadError(err instanceof Error ? err.message : t('app.uploadFail'));
},
);
}, []);
}, [t]);
const handleReset = useCallback(() => {
setSharedPattern(null); // 退出分享模式
setSource((prev) => {
if (prev) URL.revokeObjectURL(prev.url);
return null;
@@ -125,7 +169,7 @@ function HomePage() {
const handleDownload = useCallback(async () => {
if (!editedResult || !source || !redeemedCode) return;
const baseName = source.name.replace(/\.[^.]+$/, '') || '拼豆图纸';
const baseName = source.name.replace(/\.[^.]+$/, '') || t('app.downloadBaseName');
try {
// 下载消耗 1 次权益(首次免费),成功后再触发本地图纸导出
await consumeCode({
@@ -137,12 +181,12 @@ function HomePage() {
const canvas = buildExportCanvas(editedResult, settings.gridSize, baseName, settings.brandId);
downloadCanvas(
canvas,
`${baseName}-${settings.gridSize}x${settings.gridSize}-${settings.brandId}拼豆图纸.png`,
`${baseName}-${settings.gridSize}x${settings.gridSize}-${settings.brandId}${t('app.downloadSuffix')}.png`,
);
} catch (err) {
setDownloadError(err instanceof Error ? err.message : '下载失败,请稍后重试');
setDownloadError(err instanceof Error ? err.message : t('app.downloadFail'));
}
}, [editedResult, source, settings.gridSize, settings.brandId, redeemedCode]);
}, [editedResult, source, settings.gridSize, settings.brandId, redeemedCode, t]);
// 编辑工具:在历史中记录新状态后再应用变换(撤销/重做走历史栈)。
const applyEdit = useCallback(
@@ -165,8 +209,8 @@ function HomePage() {
if (next) setGridState(next);
}, [history]);
const beadCount = result?.totalBeads ?? 0;
const colorCount = result?.palette.length ?? 0;
const beadCount = effectiveResult?.totalBeads ?? 0;
const colorCount = effectiveResult?.palette.length ?? 0;
const orderPlan = modal?.kind === 'order' ? modal.plan : null;
return (
@@ -199,8 +243,14 @@ function HomePage() {
redeemed={redeemed}
downloadError={downloadError}
onDownload={handleDownload}
shared={sharedPattern !== null}
shareButton={
gridState ? (
<ShareButton grid={gridState.grid} size={gridState.size} brandId={settings.brandId} />
) : undefined
}
toolbar={
result ? (
effectiveResult ? (
<EditToolbar
canUndo={history.canUndo}
canRedo={history.canRedo}
@@ -233,7 +283,7 @@ function HomePage() {
className="mobile-cta-btn"
onClick={() => setModal({ kind: 'order', plan: DEFAULT_PLAN })}
>
购买 / 兑换 →
{t('app.mobileCta')}
</button>
</div>
+29
View File
@@ -174,6 +174,35 @@
background: var(--success);
}
.chibi-nav-lang {
display: inline-flex;
align-items: center;
border: 1px solid var(--border);
border-radius: var(--radius-full);
overflow: hidden;
height: 24px;
margin-left: 12px;
}
.chibi-nav-lang-btn {
font-size: var(--text-xs);
line-height: 1;
padding: 5px 10px;
min-height: 0;
color: var(--text-secondary);
background: transparent;
border-radius: 0;
}
.chibi-nav-lang-btn:hover {
color: var(--text-primary);
}
.chibi-nav-lang-btn--active {
color: var(--text-on-dark);
background: var(--accent);
}
/* ═══════════════════════ BEAD HERO ═══════════════════════════ */
.chibi-hero {
+206 -134
View File
@@ -1,6 +1,8 @@
import { useEffect, useRef, useState } from "react";
import "./ChibiPage.css";
import { generateChibi, redeemCode } from "./lib/api";
import { useT, type MessageKey } from "./i18n";
import LangSwitcher from "./components/LangSwitcher";
/* ══════════════════════════════════════════════════════════════════════════
* PERLER LAB — AI 拼豆专区 (/chibi)
@@ -12,76 +14,120 @@ const MAX_TAGS = 5;
const MAX_PROMPT_LENGTH = 160;
const MAX_UPLOAD_BYTES = 12 * 1024 * 1024; // 12MB
/* ── 数据:五大类 + 细分 + 提示词标签 (copy-library.md §8.2) ── */
/* ── 数据:五大类 + 细分 + 提示词标签 (copy-library.md §8.2) ──
* name/id 保持中文:作为与服务端枚举 / 提示词的契约;
* nameKey/labelKey 等驱动界面文案(多语言)。
*/
interface Subtype {
name: string;
note: string;
nameKey: MessageKey;
noteKey: MessageKey;
}
interface ChibiTag {
id: string;
labelKey: MessageKey;
}
interface Category {
id: string;
name: string;
note: string;
nameKey: MessageKey;
noteKey: MessageKey;
subtypes: Subtype[];
tags: string[];
tags: ChibiTag[];
}
const CATEGORIES: Category[] = [
{
id: "landscape",
name: "风景",
note: "山川、城市和旅行纪念",
nameKey: "chibi.cat.landscape.name",
noteKey: "chibi.cat.landscape.note",
subtypes: [
{ name: "自然山川", note: "" },
{ name: "城市夜景", note: "" },
{ name: "地标建筑", note: "" },
{ name: "自然山川", nameKey: "chibi.cat.landscape.nature", noteKey: "chibi.cat.landscape.nature.note" },
{ name: "城市夜景", nameKey: "chibi.cat.landscape.city", noteKey: "chibi.cat.landscape.city.note" },
{ name: "地标建筑", nameKey: "chibi.cat.landscape.landmark", noteKey: "chibi.cat.landscape.landmark.note" },
],
tags: [
{ id: "突出主体建筑", labelKey: "chibi.tag.buildings" },
{ id: "减少零碎纹理", labelKey: "chibi.tag.texture" },
{ id: "保留光影氛围", labelKey: "chibi.tag.light" },
{ id: "纯色边框", labelKey: "chibi.tag.border" },
{ id: "高对比轮廓", labelKey: "chibi.tag.contrast" },
{ id: "云端与远山", labelKey: "chibi.tag.clouds" },
],
tags: ["突出主体建筑", "减少零碎纹理", "保留光影氛围", "纯色边框", "高对比轮廓", "云端与远山"],
},
{
id: "people",
name: "人物",
note: "五官、发型和穿搭清楚",
nameKey: "chibi.cat.people.name",
noteKey: "chibi.cat.people.note",
subtypes: [
{ name: "萌系大眼", note: "大眼、圆脸、粗轮廓" },
{ name: "清爽少年", note: "自然五官、利落穿搭" },
{ name: "复古像素", note: "怀旧配色、游戏感" },
{ name: "萌系大眼", nameKey: "chibi.cat.people.bigeye", noteKey: "chibi.cat.people.bigeye.note" },
{ name: "清爽少年", nameKey: "chibi.cat.people.youth", noteKey: "chibi.cat.people.youth.note" },
{ name: "复古像素", nameKey: "chibi.cat.people.retro", noteKey: "chibi.cat.people.retro.note" },
],
tags: [
{ id: "五官更清晰", labelKey: "chibi.tag.face" },
{ id: "保留衣服细节", labelKey: "chibi.tag.clothes" },
{ id: "保留发型", labelKey: "chibi.tag.hair" },
{ id: "保留配饰", labelKey: "chibi.tag.accessory" },
{ id: "包含宠物", labelKey: "chibi.tag.pet" },
{ id: "纯色背景", labelKey: "chibi.tag.bg" },
],
tags: ["五官更清晰", "保留衣服细节", "保留发型", "保留配饰", "包含宠物", "纯色背景"],
},
{
id: "pet",
name: "宠物",
note: "毛色、表情和品种特征",
nameKey: "chibi.cat.pet.name",
noteKey: "chibi.cat.pet.note",
subtypes: [
{ name: "猫咪头像", note: "圆润脸型与花纹" },
{ name: "狗狗全身", note: "耳朵、四肢和毛色" },
{ name: "双宠互动", note: "两只宠物同框" },
{ name: "猫咪头像", nameKey: "chibi.cat.pet.cat", noteKey: "chibi.cat.pet.cat.note" },
{ name: "狗狗全身", nameKey: "chibi.cat.pet.dog", noteKey: "chibi.cat.pet.dog.note" },
{ name: "双宠互动", nameKey: "chibi.cat.pet.duo", noteKey: "chibi.cat.pet.duo.note" },
],
tags: [
{ id: "眼睛更有神", labelKey: "chibi.tag.eyes" },
{ id: "保留毛色花纹", labelKey: "chibi.tag.fur" },
{ id: "突出耳朵轮廓", labelKey: "chibi.tag.ears" },
{ id: "保留项圈配饰", labelKey: "chibi.tag.collar" },
{ id: "完整四肢", labelKey: "chibi.tag.limbs" },
{ id: "纯色背景", labelKey: "chibi.tag.bg" },
],
tags: ["眼睛更有神", "保留毛色花纹", "突出耳朵轮廓", "保留项圈配饰", "完整四肢", "纯色背景"],
},
{
id: "item",
name: "物品",
note: "手办、礼物和纪念物",
nameKey: "chibi.cat.item.name",
noteKey: "chibi.cat.item.note",
subtypes: [
{ name: "手办玩具", note: "造型轮廓优先" },
{ name: "生活用品", note: "保留结构与材质" },
{ name: "礼物纪念", note: "突出包装和装饰" },
{ name: "手办玩具", nameKey: "chibi.cat.item.toy", noteKey: "chibi.cat.item.toy.note" },
{ name: "生活用品", nameKey: "chibi.cat.item.daily", noteKey: "chibi.cat.item.daily.note" },
{ name: "礼物纪念", nameKey: "chibi.cat.item.gift", noteKey: "chibi.cat.item.gift.note" },
],
tags: [
{ id: "保留品牌外形", labelKey: "chibi.tag.shape" },
{ id: "突出结构轮廓", labelKey: "chibi.tag.structure" },
{ id: "减少反光渐变", labelKey: "chibi.tag.gloss" },
{ id: "保留小配件", labelKey: "chibi.tag.details" },
{ id: "居中构图", labelKey: "chibi.tag.center" },
{ id: "纯色背景", labelKey: "chibi.tag.bg" },
],
tags: ["保留品牌外形", "突出结构轮廓", "减少反光渐变", "保留小配件", "居中构图", "纯色背景"],
},
{
id: "food",
name: "食物",
note: "甜品、饮品和特色美食",
nameKey: "chibi.cat.food.name",
noteKey: "chibi.cat.food.note",
subtypes: [
{ name: "甜品蛋糕", note: "奶油与装饰清晰" },
{ name: "咖啡饮品", note: "杯型、分层和配料" },
{ name: "家常美食", note: "主食材清晰可辨" },
{ name: "甜品蛋糕", nameKey: "chibi.cat.food.dessert", noteKey: "chibi.cat.food.dessert.note" },
{ name: "咖啡饮品", nameKey: "chibi.cat.food.drink", noteKey: "chibi.cat.food.drink.note" },
{ name: "家常美食", nameKey: "chibi.cat.food.meal", noteKey: "chibi.cat.food.meal.note" },
],
tags: [
{ id: "突出食物主体", labelKey: "chibi.tag.foodMain" },
{ id: "保留食材层次", labelKey: "chibi.tag.layers" },
{ id: "减少细碎装饰", labelKey: "chibi.tag.decor" },
{ id: "增强色彩对比", labelKey: "chibi.tag.saturation" },
{ id: "俯拍构图", labelKey: "chibi.tag.topdown" },
{ id: "纯色背景", labelKey: "chibi.tag.bg" },
],
tags: ["突出食物主体", "保留食材层次", "减少细碎装饰", "增强色彩对比", "俯拍构图", "纯色背景"],
},
];
@@ -89,24 +135,41 @@ const DEFAULT_CATEGORY_ID = "pet";
/* ── 参数选项 (copy-library.md §8.3) ── */
const GRID_OPTIONS = [
{ value: 48, hint: "简单", recommended: false },
{ value: 64, hint: "推荐", recommended: true },
{ value: 80, hint: "精细", recommended: false },
{ value: 96, hint: "高清", recommended: false },
interface GridOption {
value: number;
hintKey: MessageKey;
recommended?: boolean;
}
interface ColorOption {
value: number;
hintKey: MessageKey;
}
const GRID_OPTIONS: GridOption[] = [
{ value: 48, hintKey: "chibi.grid.simple" },
{ value: 64, hintKey: "chibi.grid.recommended", recommended: true },
{ value: 80, hintKey: "chibi.grid.fine" },
{ value: 96, hintKey: "chibi.grid.hd" },
];
const COLOR_OPTIONS = [
{ value: 16, hint: "省豆", recommended: false },
{ value: 24, hint: "均衡", recommended: false },
{ value: 32, hint: "细腻", recommended: false },
{ value: 40, hint: "高还原", recommended: false },
const COLOR_OPTIONS: ColorOption[] = [
{ value: 16, hintKey: "chibi.colors.save" },
{ value: 24, hintKey: "chibi.colors.balanced" },
{ value: 32, hintKey: "chibi.colors.fine" },
{ value: 40, hintKey: "chibi.colors.high" },
];
const COMPOSITIONS = [
{ id: "特写", label: "主体特写", density: 0.7 },
{ id: "半幅", label: "半幅构图", density: 0.6 },
{ id: "完整", label: "完整构图", density: 0.48 },
interface Composition {
id: string;
labelKey: MessageKey;
density: number;
}
const COMPOSITIONS: Composition[] = [
{ id: "特写", labelKey: "chibi.composition.closeup", density: 0.7 },
{ id: "半幅", labelKey: "chibi.composition.half", density: 0.6 },
{ id: "完整", labelKey: "chibi.composition.full", density: 0.48 },
];
const DEFAULT_GRID = 64;
@@ -214,6 +277,7 @@ interface UploadBoxProps {
}
function UploadBox({ title, hint, value, onChange }: UploadBoxProps) {
const { t } = useT();
const inputRef = useRef<HTMLInputElement>(null);
const [error, setError] = useState<string | null>(null);
@@ -221,7 +285,7 @@ function UploadBox({ title, hint, value, onChange }: UploadBoxProps) {
if (!file) return;
setError(null);
if (file.size > MAX_UPLOAD_BYTES) {
setError("图片不能超过 12MB");
setError(t("chibi.upload.tooBig"));
return;
}
const reader = new FileReader();
@@ -231,7 +295,7 @@ function UploadBox({ title, hint, value, onChange }: UploadBoxProps) {
}
};
reader.onerror = () => {
setError("图片读取失败,请换一张重试");
setError(t("chibi.upload.readFail"));
};
reader.readAsDataURL(file);
};
@@ -249,10 +313,10 @@ function UploadBox({ title, hint, value, onChange }: UploadBoxProps) {
<img className="chibi-upload-thumb" src={value.url} alt={value.name} />
<div className="chibi-upload-meta">
<div className="chibi-upload-name">{value.name}</div>
<div className="chibi-upload-size">{formatBytes(value.size)} · 已就绪</div>
<div className="chibi-upload-size">{formatBytes(value.size)} · {t("chibi.upload.ready")}</div>
</div>
<button type="button" className="chibi-upload-reset" onClick={reset}>
重置
{t("chibi.upload.reset")}
</button>
</div>
) : (
@@ -295,6 +359,7 @@ function PixelSample() {
* ══════════════════════════════════════════════════════════════════════════ */
export function ChibiPage() {
const { t } = useT();
const [categoryId, setCategoryId] = useState<string>(DEFAULT_CATEGORY_ID);
const [subtypeName, setSubtypeName] = useState<string>(CATEGORIES.find((c) => c.id === DEFAULT_CATEGORY_ID)?.subtypes[0]?.name ?? "");
const [gridSize, setGridSize] = useState<number>(DEFAULT_GRID);
@@ -338,19 +403,19 @@ export function ChibiPage() {
const selectedSubtype = subtypes.find((s) => s.name === subtypeName) ?? subtypes[0];
const toggleTag = (tag: string): void => {
if (selectedTags.includes(tag)) {
setSelectedTags(selectedTags.filter((t) => t !== tag));
const toggleTag = (tagId: string): void => {
if (selectedTags.includes(tagId)) {
setSelectedTags(selectedTags.filter((x) => x !== tagId));
setTagHint(null);
return;
}
if (selectedTags.length >= MAX_TAGS) {
setTagHint(`最多选 ${MAX_TAGS} 项`);
setTagHint(t("chibi.tags.hint", { max: MAX_TAGS }));
if (tagHintTimerRef.current !== null) window.clearTimeout(tagHintTimerRef.current);
tagHintTimerRef.current = window.setTimeout(() => setTagHint(null), 2000);
return;
}
setSelectedTags([...selectedTags, tag]);
setSelectedTags([...selectedTags, tagId]);
setTagHint(null);
};
@@ -378,7 +443,7 @@ export function ChibiPage() {
const redeem = async (): Promise<void> => {
const code = codeInput.trim();
if (!code) {
setCodeError("请输入兑换码");
setCodeError(t("chibi.modal.empty"));
return;
}
if (redeemingCode) return;
@@ -390,7 +455,7 @@ export function ChibiPage() {
setCodeInput("");
setCodeModalOpen(false);
} catch (err) {
setCodeError(err instanceof Error ? err.message : "兑换失败,请稍后重试");
setCodeError(err instanceof Error ? err.message : t("chibi.modal.fail"));
} finally {
setRedeemingCode(false);
}
@@ -399,7 +464,7 @@ export function ChibiPage() {
const generate = async (): Promise<void> => {
if (!hasCode || generating || !redeemedCode) return;
if (!originalImage) {
setGenerateError("请先上传需要转换的原图");
setGenerateError(t("chibi.error.noImage"));
return;
}
setGenerating(true);
@@ -420,13 +485,17 @@ export function ChibiPage() {
setGeneratedImage(res.image);
setDownloadGrant(res.downloadGrant);
} catch (err) {
setGenerateError(err instanceof Error ? err.message : "生成失败,请稍后重试");
setGenerateError(err instanceof Error ? err.message : t("chibi.error.generateFail"));
} finally {
setGenerating(false);
}
};
const ctaLabel = generating ? "AI 生成中…" : hasCode ? "生成 →" : "兑换后生成 →";
const ctaLabel = generating
? t("chibi.cta.generating")
: hasCode
? t("chibi.cta.generate")
: t("chibi.cta.redeemFirst");
return (
<div className="chibi-page">
@@ -434,7 +503,7 @@ export function ChibiPage() {
<nav className="chibi-nav">
<div className="chibi-nav-inner">
<a className="chibi-nav-back" href="/">
← 普通拼豆
{t("chibi.nav.back")}
</a>
<a className="chibi-brand" href="/chibi">
<span className="chibi-brand-mark">P</span>
@@ -445,8 +514,9 @@ export function ChibiPage() {
<span className="chibi-nav-spacer" />
<span className="chibi-nav-badge">
<span className="chibi-nav-badge-dot" />
每次生成消耗 1 次权益
{t("chibi.nav.badge")}
</span>
<LangSwitcher base="chibi-nav-lang" />
</div>
</nav>
@@ -454,23 +524,22 @@ export function ChibiPage() {
<header className="chibi-hero">
<span className="chibi-eyebrow">IMAGE TO PERLER</span>
<h1 className="chibi-h1">
先选大类,再定细节,<em>生成结果先保存。</em>
{t("chibi.hero.title.prefix")}
<em>{t("chibi.hero.title.accent")}</em>
</h1>
<p className="chibi-sub">
每次 AI 成功生成扣 1 次;该作品转成正式拼豆图纸并首次下载免费。只有重新生成新作品才再次扣费。
</p>
<p className="chibi-sub">{t("chibi.hero.sub")}</p>
</header>
{/* ── BEAD BUILDER ── */}
<main className="chibi-main">
<section className="chibi-card" aria-label="拼豆生成设置">
<section className="chibi-card" aria-label={t("chibi.card.aria")}>
{/* 01 选择拼豆大类 */}
<div className="chibi-section">
<div className="chibi-section-head">
<span className="chibi-section-num">01</span>
<h2 className="chibi-section-title">选择拼豆大类</h2>
<h2 className="chibi-section-title">{t("chibi.step.category")}</h2>
</div>
<div className="chibi-tabs" role="tablist" aria-label="拼豆大类">
<div className="chibi-tabs" role="tablist" aria-label={t("chibi.tabs.aria")}>
{CATEGORIES.map((c) => {
const selected = c.id === categoryId;
return (
@@ -482,8 +551,8 @@ export function ChibiPage() {
className={`chibi-tab${selected ? " is-selected" : ""}`}
onClick={() => selectCategory(c.id)}
>
<span className="chibi-tab-name">{c.name}</span>
<span className="chibi-tab-note">{c.note}</span>
<span className="chibi-tab-name">{t(c.nameKey)}</span>
<span className="chibi-tab-note">{t(c.noteKey)}</span>
</button>
);
})}
@@ -492,12 +561,12 @@ export function ChibiPage() {
{/* 大类对比图(原图 → 像素拼豆效果) */}
<div className="chibi-compare" aria-hidden="true">
<div className="chibi-compare-box">
<span className="chibi-compare-label">原图</span>
<span className="chibi-compare-label">{t("chibi.compare.original")}</span>
<div className="chibi-compare-source" />
</div>
<span className="chibi-compare-arrow">→</span>
<div className="chibi-compare-box">
<span className="chibi-compare-label">像素拼豆效果</span>
<span className="chibi-compare-label">{t("chibi.compare.result")}</span>
<div className="chibi-compare-pixel">
<PixelSample />
</div>
@@ -505,7 +574,7 @@ export function ChibiPage() {
</div>
{/* 细分选择 */}
<p className="chibi-subtype-title">细分选择 · 同一种类下不同画风</p>
<p className="chibi-subtype-title">{t("chibi.subtype.title")}</p>
<div className="chibi-subtypes">
{subtypes.map((s) => {
const selected = s.name === subtypeName;
@@ -517,8 +586,8 @@ export function ChibiPage() {
className={`chibi-subtype${selected ? " is-selected" : ""}`}
onClick={() => setSubtypeName(s.name)}
>
<span className="chibi-subtype-name">{s.name}</span>
<span className="chibi-subtype-note">{s.note}</span>
<span className="chibi-subtype-name">{t(s.nameKey)}</span>
<span className="chibi-subtype-note">{t(s.noteKey)}</span>
</button>
);
})}
@@ -529,7 +598,7 @@ export function ChibiPage() {
<div className="chibi-section">
<div className="chibi-section-head">
<span className="chibi-section-num">02</span>
<h2 className="chibi-section-title">图纸格数</h2>
<h2 className="chibi-section-title">{t("chibi.step.grid")}</h2>
</div>
<div className="chibi-options">
{GRID_OPTIONS.map((o) => {
@@ -542,9 +611,9 @@ export function ChibiPage() {
className={`chibi-option${selected ? " is-selected" : ""}`}
onClick={() => setGridSize(o.value)}
>
{o.recommended && <span className="chibi-recommend">推荐</span>}
{o.recommended && <span className="chibi-recommend">{t("chibi.recommend")}</span>}
<span className="chibi-option-value">{o.value}</span>
<span className="chibi-option-hint">{o.hint}</span>
<span className="chibi-option-hint">{t(o.hintKey)}</span>
</button>
);
})}
@@ -555,8 +624,8 @@ export function ChibiPage() {
<div className="chibi-section">
<div className="chibi-section-head">
<span className="chibi-section-num">03</span>
<h2 className="chibi-section-title">最大颜色数</h2>
<span className="chibi-section-note">颜色越多还原度越高</span>
<h2 className="chibi-section-title">{t("chibi.step.colors")}</h2>
<span className="chibi-section-note">{t("chibi.step.colors.note")}</span>
</div>
<div className="chibi-options">
{COLOR_OPTIONS.map((o) => {
@@ -570,7 +639,7 @@ export function ChibiPage() {
onClick={() => setMaxColors(o.value)}
>
<span className="chibi-option-value">{o.value}</span>
<span className="chibi-option-hint">{o.hint}</span>
<span className="chibi-option-hint">{t(o.hintKey)}</span>
</button>
);
})}
@@ -581,7 +650,7 @@ export function ChibiPage() {
<div className="chibi-section">
<div className="chibi-section-head">
<span className="chibi-section-num">04</span>
<h2 className="chibi-section-title">主体构图</h2>
<h2 className="chibi-section-title">{t("chibi.step.composition")}</h2>
</div>
<div className="chibi-options is-3col">
{COMPOSITIONS.map((c) => {
@@ -594,7 +663,7 @@ export function ChibiPage() {
className={`chibi-option${selected ? " is-selected" : ""}`}
onClick={() => setComposition(c.id)}
>
<span className="chibi-option-value">{c.label}</span>
<span className="chibi-option-value">{t(c.labelKey)}</span>
</button>
);
})}
@@ -605,29 +674,29 @@ export function ChibiPage() {
<div className="chibi-section">
<div className="chibi-section-head">
<span className="chibi-section-num">05</span>
<h2 className="chibi-section-title">细节提示词</h2>
<span className="chibi-section-note">最多选 {MAX_TAGS} 项</span>
<h2 className="chibi-section-title">{t("chibi.step.tags")}</h2>
<span className="chibi-section-note">{t("chibi.tags.max", { max: MAX_TAGS })}</span>
<span
className={`chibi-tag-count${selectedTags.length >= MAX_TAGS ? " is-full" : ""}`}
aria-live="polite"
>
已选 {selectedTags.length}/{MAX_TAGS}
{t("chibi.tags.selected", { selected: selectedTags.length, max: MAX_TAGS })}
</span>
</div>
<div className="chibi-tags">
{tags.map((tag) => {
const selected = selectedTags.includes(tag);
const selected = selectedTags.includes(tag.id);
const disabled = !selected && selectedTags.length >= MAX_TAGS;
return (
<button
key={tag}
key={tag.id}
type="button"
aria-pressed={selected}
className={`chibi-tag${selected ? " is-selected" : ""}${disabled ? " is-disabled" : ""}`}
onClick={() => toggleTag(tag)}
onClick={() => toggleTag(tag.id)}
>
<span className="chibi-tag-marker">{selected ? "✓" : "+"}</span>
{tag}
{t(tag.labelKey)}
</button>
);
})}
@@ -637,12 +706,12 @@ export function ChibiPage() {
<div className="chibi-detail-row">
<div>
<label className="chibi-field-label" htmlFor="chibi-prompt">
补充描述(选填)
{t("chibi.prompt.label")}
</label>
<textarea
id="chibi-prompt"
className="chibi-textarea"
placeholder="想保留的细节、不想要的元素…"
placeholder={t("chibi.prompt.placeholder")}
maxLength={MAX_PROMPT_LENGTH}
value={promptText}
onChange={(e) => setPromptText(e.target.value)}
@@ -654,10 +723,10 @@ export function ChibiPage() {
</div>
</div>
<div>
<span className="chibi-field-label">上传风格示例图(可选)</span>
<span className="chibi-field-label">{t("chibi.reference.label")}</span>
<UploadBox
title="上传风格示例图"
hint="不会照搬示例主体"
title={t("chibi.reference.title")}
hint={t("chibi.reference.hint")}
value={referenceImage}
onChange={setReferenceImage}
/>
@@ -667,54 +736,57 @@ export function ChibiPage() {
</section>
{/* ── 生成前确认 ── */}
<section className="chibi-card" aria-label="生成前确认">
<section className="chibi-card" aria-label={t("chibi.confirm.aria")}>
<div className="chibi-section-head">
<span className="chibi-section-num">✓</span>
<h2 className="chibi-section-title">生成前确认</h2>
<h2 className="chibi-section-title">{t("chibi.confirm.title")}</h2>
</div>
<div className="chibi-confirm">
<div className="chibi-confirm-left">
<div className="chibi-sample">
<span className="chibi-sample-label">示例</span>
<span className="chibi-sample-label">{t("chibi.sample")}</span>
<PixelSample />
</div>
<span className="chibi-sample-desc">默认像素效果</span>
<span className="chibi-sample-desc">{t("chibi.sample.desc")}</span>
</div>
<div className="chibi-confirm-right">
<div className="chibi-spec">
<div className="chibi-spec-row">
<span className="chibi-spec-label">类别</span>
<span className="chibi-spec-value">{category?.name ?? ""}</span>
<span className="chibi-spec-label">{t("chibi.spec.category")}</span>
<span className="chibi-spec-value">{t(category?.nameKey ?? "chibi.cat.pet.name")}</span>
</div>
<div className="chibi-spec-row">
<span className="chibi-spec-label">细分</span>
<span className="chibi-spec-value">{selectedSubtype?.name ?? ""}</span>
<span className="chibi-spec-label">{t("chibi.spec.subtype")}</span>
<span className="chibi-spec-value">{t(selectedSubtype?.nameKey ?? "chibi.cat.pet.cat")}</span>
</div>
<div className="chibi-spec-row">
<span className="chibi-spec-label">图纸</span>
<span className="chibi-spec-label">{t("chibi.spec.grid")}</span>
<span className="chibi-spec-value">
{gridSize}×{gridSize}
</span>
</div>
<div className="chibi-spec-row">
<span className="chibi-spec-label">预计颗数</span>
<span className="chibi-spec-value">约 {formatNumber(estimatedBeads)} 颗</span>
<span className="chibi-spec-label">{t("chibi.spec.beads")}</span>
<span className="chibi-spec-value">
{t("chibi.spec.beads.value", { count: formatNumber(estimatedBeads) })}
</span>
</div>
</div>
<div className="chibi-confirm-upload-row">
<div className="chibi-upload-title">上传需要转换的原图</div>
<div className="chibi-upload-title">{t("chibi.upload.original.title")}</div>
</div>
<UploadBox
title="上传需要转换的原图"
hint="主体清楚、光线自然效果更好 · 不超过 12MB"
title={t("chibi.upload.original.title")}
hint={t("chibi.upload.original.hint")}
value={originalImage}
onChange={setOriginalImage}
/>
<p className="chibi-confirm-note">
<b>AI 生成属于付费功能。</b>成功生成扣 1 次;本作品转图纸和首次下载免费,失败不扣。
<b>{t("chibi.payNote.title")}</b>
{t("chibi.payNote.body")}
</p>
<div className="chibi-confirm-actions">
@@ -729,7 +801,7 @@ export function ChibiPage() {
</button>
{!hasCode && (
<button type="button" className="chibi-btn-link" onClick={() => setCodeModalOpen(true)}>
输入兑换码
{t("chibi.codeLink")}
</button>
)}
</div>
@@ -740,36 +812,36 @@ export function ChibiPage() {
{/* ── 生成结果 ── */}
{generatedImage && (
<section className="chibi-card" aria-label="生成结果">
<section className="chibi-card" aria-label={t("chibi.result.aria")}>
<div className="chibi-section-head">
<span className="chibi-section-num">✓</span>
<h2 className="chibi-section-title">生成结果</h2>
<h2 className="chibi-section-title">{t("chibi.result.title")}</h2>
</div>
<div className="chibi-result">
<img className="chibi-result-img" src={generatedImage} alt="AI 拼豆生成结果" />
<img className="chibi-result-img" src={generatedImage} alt={t("chibi.result.alt")} />
<p className="chibi-result-note">
{downloadGrant ? "图纸已生成 · 首次下载免费(下载凭据已保存)" : "图纸已生成"}
{downloadGrant ? t("chibi.result.withGrant") : t("chibi.result.plain")}
</p>
</div>
</section>
)}
{/* ── 三大承诺 ── */}
<section className="chibi-promises" aria-label="服务承诺">
<section className="chibi-promises" aria-label={t("chibi.promise.aria")}>
<div className="chibi-promise">
<span className="chibi-promise-icon">{ICON_CLASSIFY}</span>
<h3 className="chibi-promise-title">分类更准确</h3>
<p className="chibi-promise-desc">不同主体使用不同提示词,风景、宠物和食物不再套用人物规则。</p>
<h3 className="chibi-promise-title">{t("chibi.promise.classify")}</h3>
<p className="chibi-promise-desc">{t("chibi.promise.classify.desc")}</p>
</div>
<div className="chibi-promise">
<span className="chibi-promise-icon">{ICON_COUNT}</span>
<h3 className="chibi-promise-title">生成按次计费</h3>
<p className="chibi-promise-desc">每次成功生成扣 1 次权益,失败不扣,避免无限消耗模型费用。</p>
<h3 className="chibi-promise-title">{t("chibi.promise.pay")}</h3>
<p className="chibi-promise-desc">{t("chibi.promise.pay.desc")}</p>
</div>
<div className="chibi-promise">
<span className="chibi-promise-icon">{ICON_SAFE}</span>
<h3 className="chibi-promise-title">结果防丢失</h3>
<p className="chibi-promise-desc">未保存时锁住所有切换操作,并在关闭页面前再次提醒。</p>
<h3 className="chibi-promise-title">{t("chibi.promise.safe")}</h3>
<p className="chibi-promise-desc">{t("chibi.promise.safe.desc")}</p>
</div>
</section>
</main>
@@ -777,9 +849,9 @@ export function ChibiPage() {
{/* ── Footer (AI 专区版) ── */}
<footer className="chibi-footer">
<div className="chibi-footer-inner">
<span className="chibi-footer-text">PERLER LAB · AI 拼豆专区</span>
<span className="chibi-footer-text">{t("chibi.footer")}</span>
<a className="chibi-footer-link" href="/">
返回图片转拼豆 →
{t("chibi.footer.back")}
</a>
</div>
</footer>
@@ -797,7 +869,7 @@ export function ChibiPage() {
</button>
{!hasCode && (
<button type="button" className="chibi-mobile-code" onClick={() => setCodeModalOpen(true)}>
输入兑换码
{t("chibi.codeLink")}
</button>
)}
</div>
@@ -811,16 +883,16 @@ export function ChibiPage() {
if (e.target === e.currentTarget) setCodeModalOpen(false);
}}
>
<div className="chibi-modal" role="dialog" aria-modal="true" aria-label="输入兑换码">
<div className="chibi-modal" role="dialog" aria-modal="true" aria-label={t("chibi.modal.aria")}>
<div className="chibi-modal-head">
<h3 className="chibi-modal-title">输入兑换码</h3>
<button type="button" className="chibi-modal-close" aria-label="关闭" onClick={() => setCodeModalOpen(false)}>
<h3 className="chibi-modal-title">{t("chibi.modal.title")}</h3>
<button type="button" className="chibi-modal-close" aria-label={t("modal.close")} onClick={() => setCodeModalOpen(false)}>
×
</button>
</div>
<input
className="chibi-modal-input"
placeholder="请输入兑换码"
placeholder={t("chibi.modal.placeholder")}
autoFocus
value={codeInput}
onChange={(e) => {
@@ -834,7 +906,7 @@ export function ChibiPage() {
{codeError && <p className="chibi-modal-error">{codeError}</p>}
<div className="chibi-modal-actions">
<button type="button" className="chibi-btn chibi-btn-primary" disabled={redeemingCode} onClick={redeem}>
{redeemingCode ? "兑换中…" : "兑换"}
{redeemingCode ? t("chibi.modal.processing") : t("chibi.modal.submit")}
</button>
</div>
</div>
+19 -10
View File
@@ -1,29 +1,38 @@
import { useT, type MessageKey } from '../i18n';
interface AgencyModalProps {
onClose: () => void;
}
const AGENT_PLANS = [
{ name: '初级代理', price: '¥139', count: '200 次' },
{ name: '标准代理', price: '¥299', count: '500 次' },
{ name: '核心代理', price: '¥499', count: '1000 次' },
const AGENT_PLANS: { nameKey: MessageKey; price: string; countKey: MessageKey }[] = [
{ nameKey: 'agency.plan.basic.name', price: '¥139', countKey: 'agency.plan.basic.count' },
{ nameKey: 'agency.plan.standard.name', price: '¥299', countKey: 'agency.plan.standard.count' },
{ nameKey: 'agency.plan.core.name', price: '¥499', countKey: 'agency.plan.core.count' },
];
/** 代理合作弹窗 (§7.3): three agent tiers. */
export default function AgencyModal({ onClose }: AgencyModalProps) {
const { t } = useT();
return (
<div className="modal-mask" onClick={onClose}>
<div className="modal" role="dialog" aria-modal="true" aria-label="代理合作" onClick={(e) => e.stopPropagation()}>
<button type="button" className="modal-close" aria-label="关闭" onClick={onClose}>
<div
className="modal"
role="dialog"
aria-modal="true"
aria-label={t('agency.aria')}
onClick={(e) => e.stopPropagation()}
>
<button type="button" className="modal-close" aria-label={t('modal.close')} onClick={onClose}>
×
</button>
<h3 className="modal-title">代理合作</h3>
<h3 className="modal-title">{t('agency.title')}</h3>
<div className="pass-cards" style={{ gridTemplateColumns: '1fr' }}>
{AGENT_PLANS.map((plan) => (
<div key={plan.name} className="pass-card">
<span className="pass-card-name">{plan.name}</span>
<div key={plan.nameKey} className="pass-card">
<span className="pass-card-name">{t(plan.nameKey)}</span>
<div className="pass-card-price">
{plan.price}
<small> / {plan.count}</small>
<small> / {t(plan.countKey)}</small>
</div>
</div>
))}
+21 -19
View File
@@ -1,6 +1,7 @@
import { useRef, type CSSProperties } from 'react';
import type { PatternSettings, SourceImage } from '../lib/usePattern';
import { BRANDS } from '../lib/brand-palettes';
import { useT } from '../i18n';
const GRID_MIN = 16;
const GRID_MAX = 128;
@@ -37,6 +38,7 @@ export default function ControlsPanel({
onReset,
onRegenerate,
}: ControlsPanelProps) {
const { t } = useT();
const fileInputRef = useRef<HTMLInputElement | null>(null);
const handleFiles = (files: FileList | null): void => {
@@ -51,10 +53,10 @@ export default function ControlsPanel({
const sizeCm = (settings.gridSize * 0.5).toFixed(0);
return (
<section className="panel" aria-label="01 生成设置">
<section className="panel" aria-label={t('ctrl.aria')}>
<div className="panel-header">
<span className="panel-index">01</span>
<h2 className="panel-title">生成设置</h2>
<h2 className="panel-title">{t('ctrl.title')}</h2>
</div>
<div className="panel-body">
@@ -64,7 +66,7 @@ export default function ControlsPanel({
className={`upload-zone${uploadError ? ' upload-zone--error' : ''}`}
role="button"
tabIndex={0}
aria-label="上传一张图片"
aria-label={t('ctrl.upload.aria')}
onClick={() => fileInputRef.current?.click()}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
@@ -75,8 +77,8 @@ export default function ControlsPanel({
<span className="upload-plus" aria-hidden="true">
+
</span>
<span className="upload-title">上传一张图片</span>
<span className="upload-sub">支持 JPG、PNG、WEBP</span>
<span className="upload-title">{t('ctrl.upload.title')}</span>
<span className="upload-sub">{t('ctrl.upload.sub')}</span>
{uploadError && <span className="upload-error">{uploadError}</span>}
</div>
) : (
@@ -87,11 +89,11 @@ export default function ControlsPanel({
{source.name}
</div>
<div className="file-meta">
{source.element.naturalWidth} × {source.element.naturalHeight} · 已上传
{source.element.naturalWidth} × {source.element.naturalHeight} · {t('ctrl.uploaded')}
</div>
</div>
<button type="button" className="file-reset" onClick={onReset}>
重置
{t('ctrl.reset')}
</button>
</div>
)}
@@ -111,7 +113,7 @@ export default function ControlsPanel({
<div className="control-group">
<div className="control-label-row">
<label className="control-label" id="brand-select-label">
品牌色板
{t('ctrl.brand')}
</label>
<strong className="control-value">{settings.brandId}</strong>
</div>
@@ -129,14 +131,14 @@ export default function ControlsPanel({
</button>
))}
</div>
<p className="control-hint">图纸色号与备料清单将按所选品牌编码</p>
<p className="control-hint">{t('ctrl.brand.hint')}</p>
</div>
{/* 图纸尺寸滑杆 */}
<div className="control-group">
<div className="control-label-row">
<label className="control-label" htmlFor="grid-size">
图纸尺寸
{t('ctrl.grid')}
</label>
<strong className="control-value">
{settings.gridSize} × {settings.gridSize}
@@ -170,14 +172,14 @@ export default function ControlsPanel({
</button>
))}
</div>
<p className="control-hint">成品约 {sizeCm} × {sizeCm} cm(按 5mm 豆计算)</p>
<p className="control-hint">{t('ctrl.grid.hint', { size: sizeCm })}</p>
</div>
{/* 最大颜色数滑杆 */}
<div className="control-group">
<div className="control-label-row">
<label className="control-label" htmlFor="max-colors">
最大颜色数
{t('ctrl.colors')}
</label>
<strong className="control-value">{settings.maxColors}</strong>
</div>
@@ -191,14 +193,14 @@ export default function ControlsPanel({
style={{ '--range-progress': `${colorProgress}%` } as CSSProperties}
onChange={(e) => onChangeSettings({ maxColors: Number(e.target.value) })}
/>
<p className="control-hint">颜色越多,还原度越高;默认推荐 24 色</p>
<p className="control-hint">{t('ctrl.colors.hint')}</p>
</div>
{/* 背景去除 */}
<div className="toggle-row">
<div className="toggle-text">
<span className="toggle-label">一键去除背景</span>
<span className="toggle-desc">只保留人物或主体,不计算背景豆</span>
<span className="toggle-label">{t('ctrl.removeBg')}</span>
<span className="toggle-desc">{t('ctrl.removeBg.desc')}</span>
</div>
<button
type="button"
@@ -214,8 +216,8 @@ export default function ControlsPanel({
{/* 辅助网格 */}
<div className="toggle-row">
<div className="toggle-text">
<span className="toggle-label">显示辅助网格</span>
<span className="toggle-desc">方便逐格定位拼豆</span>
<span className="toggle-label">{t('ctrl.showGrid')}</span>
<span className="toggle-desc">{t('ctrl.showGrid.desc')}</span>
</div>
<button
type="button"
@@ -238,10 +240,10 @@ export default function ControlsPanel({
{processing ? (
<>
<span className="regen-spinner" aria-hidden="true" />
图片处理中…
{t('ctrl.processing')}
</>
) : (
<>↻ 重新生成图纸</>
<>{t('ctrl.regen')}</>
)}
</button>
</div>
+21 -19
View File
@@ -1,4 +1,5 @@
import type { ReactNode } from 'react';
import { useT } from '../i18n';
interface EditToolbarProps {
/** 是否还有可撤销的历史步骤(无图纸或初始状态时禁用)。 */
@@ -93,18 +94,19 @@ export default function EditToolbar({
onMirrorHorizontal,
onFlip,
}: EditToolbarProps) {
const { t } = useT();
return (
<div className="edit-toolbar" role="toolbar" aria-label="编辑工具">
<div className="edit-toolbar" role="toolbar" aria-label={t('edit.aria')}>
<button
type="button"
className="edit-tool-btn"
disabled={!canUndo}
onClick={onUndo}
title="撤销上一步"
aria-label="撤销上一步"
title={t('edit.undo.title')}
aria-label={t('edit.undo.title')}
>
{IconUndo}
<span>撤销</span>
<span>{t('edit.undo')}</span>
</button>
<button
@@ -112,11 +114,11 @@ export default function EditToolbar({
className="edit-tool-btn"
disabled={!canRedo}
onClick={onRedo}
title="重做下一步"
aria-label="重做下一步"
title={t('edit.redo.title')}
aria-label={t('edit.redo.title')}
>
{IconRedo}
<span>重做</span>
<span>{t('edit.redo')}</span>
</button>
<span className="edit-tool-sep" aria-hidden="true" />
@@ -125,44 +127,44 @@ export default function EditToolbar({
type="button"
className="edit-tool-btn"
onClick={onRotate}
title="顺时针旋转 90°"
aria-label="顺时针旋转 90°"
title={t('edit.rotate.title')}
aria-label={t('edit.rotate.title')}
>
{IconRotate}
<span>旋转90°</span>
<span>{t('edit.rotate')}</span>
</button>
<button
type="button"
className="edit-tool-btn"
onClick={onMirrorVertical}
title="左右镜像(左右对调)"
aria-label="左右镜像"
title={t('edit.mirrorV.title')}
aria-label={t('edit.mirrorV.title')}
>
{IconMirrorVertical}
<span>左右镜像</span>
<span>{t('edit.mirrorV')}</span>
</button>
<button
type="button"
className="edit-tool-btn"
onClick={onMirrorHorizontal}
title="上下镜像(上下对调)"
aria-label="上下镜像"
title={t('edit.mirrorH.title')}
aria-label={t('edit.mirrorH.title')}
>
{IconMirrorHorizontal}
<span>上下镜像</span>
<span>{t('edit.mirrorH')}</span>
</button>
<button
type="button"
className="edit-tool-btn"
onClick={onFlip}
title="对角翻转(主对角线对称,可做对称图纸)"
aria-label="对角翻转"
title={t('edit.flip.title')}
aria-label={t('edit.flip.title')}
>
{IconFlip}
<span>对角翻转</span>
<span>{t('edit.flip')}</span>
</button>
</div>
);
+5 -2
View File
@@ -1,10 +1,13 @@
import { useT } from '../i18n';
/** FOOTER (§10): brand + note. */
export default function Footer() {
const { t } = useT();
return (
<footer className="footer">
<div className="footer-inner">
<span className="footer-brand">PERLER LAB · 让每一颗颜色都有位置</span>
<span className="footer-note">图纸仅供个人手作参考</span>
<span className="footer-brand">{t('footer.slogan')}</span>
<span className="footer-note">{t('footer.note')}</span>
</div>
</footer>
);
+8 -6
View File
@@ -1,3 +1,5 @@
import { useT } from '../i18n';
interface HeroProps {
beadCount: number;
colorCount: number;
@@ -5,24 +7,24 @@ interface HeroProps {
/** HERO (§2.4): IMAGE TO BEADS + headline + stats. */
export default function Hero({ beadCount, colorCount }: HeroProps) {
const { t } = useT();
return (
<section className="hero">
<p className="hero-eyebrow">IMAGE TO BEADS</p>
<h1 className="hero-title">
把喜欢的图片,<em>变成一颗颗拼豆。</em>
{t('hero.title.prefix')}
<em>{t('hero.title.accent')}</em>
</h1>
<p className="hero-sub">
免费上传、生成和调整图纸,满意后使用兑换码下载完整高清图纸与用豆清单。
</p>
<p className="hero-sub">{t('hero.sub')}</p>
<div className="hero-stats">
<div className="hero-stat">
<strong>{beadCount.toLocaleString()}</strong>
<span>颗拼豆</span>
<span>{t('hero.stat.beads')}</span>
</div>
<span className="hero-stat-sep" aria-hidden="true" />
<div className="hero-stat">
<strong>{colorCount.toLocaleString()}</strong>
<span>种颜色</span>
<span>{t('hero.stat.colors')}</span>
</div>
</div>
</section>
+24 -20
View File
@@ -1,4 +1,5 @@
import type { ProcessResult } from '../lib/image-processor';
import { useT } from '../i18n';
interface InventoryPanelProps {
result: ProcessResult | null;
@@ -17,18 +18,19 @@ export default function InventoryPanel({
brandId = 'MARD',
onRedeemClick,
}: InventoryPanelProps) {
const { t } = useT();
const totalBeads = result?.totalBeads ?? 0;
const colorCount = result?.palette.length ?? 0;
return (
<section className="panel panel--inventory" aria-label={`03 ${brandId} 备料清单`}>
<section className="panel panel--inventory" aria-label={t('inv.aria', { brand: brandId })}>
<div className="panel-header">
<span className="panel-index">03</span>
<h2 className="panel-title">{brandId} 备料清单</h2>
<h2 className="panel-title">{t('inv.title', { brand: brandId })}</h2>
{redeemed ? (
<span className="inv-unlocked-badge">已解锁</span>
<span className="inv-unlocked-badge">{t('inv.unlocked')}</span>
) : (
<span className="inv-lock-tag">🔒 受保护</span>
<span className="inv-lock-tag">{t('inv.locked')}</span>
)}
</div>
@@ -38,11 +40,11 @@ export default function InventoryPanel({
<div className="inv-stats">
<div className="inv-stat">
<strong>{totalBeads.toLocaleString()}</strong>
<span>实际总颗数</span>
<span>{t('inv.total')}</span>
</div>
<div className="inv-stat">
<strong>{colorCount}</strong>
<span>使用颜色</span>
<span>{t('inv.colors')}</span>
</div>
</div>
@@ -56,17 +58,20 @@ export default function InventoryPanel({
aria-hidden="true"
/>
<span className="inv-code">{entry.code}</span>
<span className="inv-count">{entry.count.toLocaleString()} 颗</span>
<span className="inv-count">
{t('inv.perColor', { count: entry.count.toLocaleString() })}
</span>
</div>
))}
</div>
) : (
<p className="inv-empty">上传图片并生成图纸后,这里会显示 {brandId} 色号清单。</p>
<p className="inv-empty">{t('inv.empty', { brand: brandId })}</p>
)}
<p className="inv-extra">
建议多备 10% · 约{' '}
<strong>{Math.round(totalBeads * 1.1).toLocaleString()}</strong> 颗
{t('inv.extra')}{' '}
<strong>{Math.round(totalBeads * 1.1).toLocaleString()}</strong>
{t('inv.beads')}
</p>
</>
) : (
@@ -75,11 +80,11 @@ export default function InventoryPanel({
<div className="inv-stats">
<div className="inv-stat">
<strong>••••</strong>
<span>实际总颗数</span>
<span>{t('inv.total')}</span>
</div>
<div className="inv-stat">
<strong>••</strong>
<span>使用颜色</span>
<span>{t('inv.colors')}</span>
</div>
</div>
@@ -88,8 +93,8 @@ export default function InventoryPanel({
{Array.from({ length: GHOST_ROWS }, (_, i) => (
<div key={i} className="inv-locked-row">
<span className="inv-ghost-swatch" aria-hidden="true" />
<span className="inv-ghost-text">完整色号已隐藏</span>
<span className="inv-ghost-count">•••• 颗</span>
<span className="inv-ghost-text">{t('inv.ghost.hidden')}</span>
<span className="inv-ghost-count">••••{t('inv.beads')}</span>
</div>
))}
</div>
@@ -99,17 +104,16 @@ export default function InventoryPanel({
<div className="inv-lock-icon" aria-hidden="true">
🔒
</div>
<p className="inv-lock-title">完整备料清单已锁定</p>
<p className="inv-lock-desc">
兑换后可查看全部 {brandId} 色号、每色颗数、总颗数及 10% 备豆建议
</p>
<p className="inv-lock-title">{t('inv.lock.title')}</p>
<p className="inv-lock-desc">{t('inv.lock.desc', { brand: brandId })}</p>
<button type="button" className="inv-unlock-btn" onClick={onRedeemClick}>
输入兑换码解锁
{t('inv.unlock')}
</button>
</div>
<p className="inv-extra">
建议多备 10% · 约 <strong>••••</strong> 颗
{t('inv.extra')} <strong>••••</strong>
{t('inv.beads')}
</p>
</>
)}
@@ -0,0 +1,31 @@
import { useT } from '../i18n';
interface LangSwitcherProps {
/** CSS class prefix: 'nav-lang' (homepage nav) or 'chibi-nav-lang' (AI studio nav). */
base?: string;
}
/** 语言切换器(zh/EN):按钮文案为通用符号,两种语言下均可自解释。 */
export default function LangSwitcher({ base = 'nav-lang' }: LangSwitcherProps) {
const { locale, setLocale, t } = useT();
const btn = `${base}-btn`;
const active = `${btn}--active`;
const renderButton = (target: 'zh-CN' | 'en', label: string): React.ReactNode => (
<button
type="button"
className={locale === target ? `${btn} ${active}` : btn}
aria-pressed={locale === target}
onClick={() => setLocale(target)}
>
{label}
</button>
);
return (
<div className={base} role="group" aria-label={t('nav.lang')}>
{renderButton('zh-CN', '中文')}
{renderButton('en', 'EN')}
</div>
);
}
+10 -5
View File
@@ -1,9 +1,13 @@
import LangSwitcher from './LangSwitcher';
import { useT } from '../i18n';
interface NavProps {
onAgencyClick: () => void;
}
/** NAV (§2.3): brand + links + 代理合作 + status badge. */
/** NAV (§2.3): brand + links + 语言切换 + 代理合作 + status badge. */
export default function Nav({ onAgencyClick }: NavProps) {
const { t } = useT();
return (
<header className="nav">
<div className="nav-inner">
@@ -16,21 +20,22 @@ export default function Nav({ onAgencyClick }: NavProps) {
<nav className="nav-links">
<a className="nav-link nav-link--active" href="#workspace">
图片转拼豆
{t('nav.toPattern')}
</a>
<a className="nav-link" href="/chibi">
AI拼豆专区
{t('nav.chibi')}
<span className="nav-pro-badge">PRO</span>
</a>
</nav>
<div className="nav-right">
<LangSwitcher />
<button type="button" className="nav-agency" onClick={onAgencyClick}>
代理合作
{t('nav.agency')}
</button>
<span className="nav-status">
<span className="nav-status-dot" aria-hidden="true" />
普通预览免费 · AI生成按次付费
{t('nav.status')}
</span>
</div>
</div>
+34 -28
View File
@@ -2,6 +2,7 @@ import { useState } from 'react';
import type { Plan } from './PassSection';
import { createOrder, payCallback, redeemCode } from '../lib/api';
import type { Order, PackageName, PaymentInfo, PaymentMethod } from '../lib/api';
import { useT } from '../i18n';
interface OrderModalProps {
plan: Plan;
@@ -18,6 +19,7 @@ type RedeemState = 'pending' | 'ok' | 'error';
* 模拟支付回调 → 展示兑换码并自动兑换。
*/
export default function OrderModal({ plan, onClose, onRedeemed }: OrderModalProps) {
const { t } = useT();
const [method, setMethod] = useState<PaymentMethod>('wechat');
const [step, setStep] = useState<Step>('method');
const [order, setOrder] = useState<Order | null>(null);
@@ -40,7 +42,7 @@ export default function OrderModal({ plan, onClose, onRedeemed }: OrderModalProp
setPayment(res.payment);
setStep('paying');
} catch (err) {
setError(err instanceof Error ? err.message : '下单失败,请稍后重试');
setError(err instanceof Error ? err.message : t('modal.order.createFail'));
} finally {
setBusy(false);
}
@@ -62,35 +64,43 @@ export default function OrderModal({ plan, onClose, onRedeemed }: OrderModalProp
setRedeemState('error');
}
} catch (err) {
setError(err instanceof Error ? err.message : '支付确认失败,请稍后重试');
setError(err instanceof Error ? err.message : t('modal.order.payFail'));
} finally {
setBusy(false);
}
};
const methodLabel = method === 'wechat' ? '微信' : '支付宝';
const methodLabel = t(
method === 'wechat' ? 'modal.order.methodLabel.wechat' : 'modal.order.methodLabel.alipay',
);
return (
<div className="modal-mask" onClick={onClose}>
<div className="modal" role="dialog" aria-modal="true" aria-label="购买 AI 生成次数" onClick={(e) => e.stopPropagation()}>
<button type="button" className="modal-close" aria-label="关闭" onClick={onClose}>
<div
className="modal"
role="dialog"
aria-modal="true"
aria-label={t('modal.order.aria')}
onClick={(e) => e.stopPropagation()}
>
<button type="button" className="modal-close" aria-label={t('modal.close')} onClick={onClose}>
×
</button>
<h3 className="modal-title">购买 AI 生成次数</h3>
<h3 className="modal-title">{t('modal.order.title')}</h3>
{step === 'method' && (
<>
<div className="pass-card" style={{ marginBottom: '16px' }}>
<span className="pass-card-name">{plan.name}</span>
<span className="pass-card-name">{t(plan.nameKey)}</span>
<div className="pass-card-price">
¥{plan.price}
<small> / {plan.count}</small>
<small> / {t(plan.countKey)}</small>
</div>
</div>
<div className="pass-card" style={{ padding: '12px 16px' }}>
<span className="pass-card-name" style={{ fontSize: '13px' }}>
应付金额 · ¥{plan.price} · {plan.count} 生成
{t('modal.order.amountDue', { price: plan.price, count: t(plan.countKey) })}
</span>
</div>
@@ -101,7 +111,7 @@ export default function OrderModal({ plan, onClose, onRedeemed }: OrderModalProp
style={{ flex: 1 }}
onClick={() => setMethod('wechat')}
>
微信收款码
{t('modal.order.method.wechat')}
</button>
<button
type="button"
@@ -109,17 +119,17 @@ export default function OrderModal({ plan, onClose, onRedeemed }: OrderModalProp
style={{ flex: 1 }}
onClick={() => setMethod('alipay')}
>
支付宝收款码
{t('modal.order.method.alipay')}
</button>
</div>
{error && <p className="redeem-error">{error}</p>}
<button type="button" className="redeem-btn" disabled={busy} onClick={handleCreateOrder}>
{busy ? '下单中…' : '去支付'}
{busy ? t('modal.order.creating') : t('modal.order.goPay')}
</button>
<p className="pass-benefit" style={{ margin: '12px 0 0' }}>
截图或长按保存收款码,再打开对应支付应用扫码支付 · 付款金额请与上方一致
{t('modal.order.note')}
</p>
</>
)}
@@ -128,29 +138,27 @@ export default function OrderModal({ plan, onClose, onRedeemed }: OrderModalProp
<>
<div className="order-pay-info">
<div className="order-pay-row">
<span>订单号</span>
<span>{t('modal.order.no')}</span>
<code>{order.orderNo}</code>
</div>
<div className="order-pay-row">
<span>应付金额</span>
<span>{t('modal.order.amount')}</span>
<strong>¥{(order.amountCents / 100).toFixed(2)}</strong>
</div>
<p className="order-pay-hint">
请使用{methodLabel}扫码支付(或长按识别收款码),付款金额请与上方一致
</p>
<p className="order-pay-hint">{t('modal.order.payHint', { method: methodLabel })}</p>
<p className="order-pay-hint order-pay-hint--url">
支付链接:{payment.url}
{payment.qrCode ? ` · 收款码:${payment.qrCode}` : ''}
{t('modal.order.payUrl', { url: payment.url })}
{payment.qrCode ? t('modal.order.qr', { qr: payment.qrCode }) : ''}
</p>
</div>
{error && <p className="redeem-error">{error}</p>}
<button type="button" className="redeem-btn" disabled={busy} onClick={handlePayCallback}>
{busy ? '确认中…' : '模拟支付完成'}
{busy ? t('modal.order.confirming') : t('modal.order.simulate')}
</button>
<p className="pass-benefit" style={{ margin: '12px 0 0' }}>
模拟环境:点击后直接标记订单已支付并发放兑换码
{t('modal.order.simNote')}
</p>
</>
)}
@@ -158,15 +166,13 @@ export default function OrderModal({ plan, onClose, onRedeemed }: OrderModalProp
{step === 'paid' && accessCode && (
<>
<div className="order-result">
<span className="order-result-label">支付成功 · 权益兑换码</span>
<span className="order-result-label">{t('modal.order.success')}</span>
<code className="order-result-code">{accessCode}</code>
{redeemState === 'ok' && (
<p className="order-result-note">已自动兑换成功,AI 生成权益已到账</p>
<p className="order-result-note">{t('modal.order.redeemed')}</p>
)}
{redeemState === 'error' && (
<p className="redeem-error">
自动兑换失败,可复制兑换码后在「输入兑换码」中手动兑换
</p>
<p className="redeem-error">{t('modal.order.redeemFailed')}</p>
)}
</div>
@@ -175,7 +181,7 @@ export default function OrderModal({ plan, onClose, onRedeemed }: OrderModalProp
className="redeem-btn"
onClick={() => (redeemState === 'ok' ? onRedeemed(accessCode) : onClose())}
>
完成
{t('modal.order.done')}
</button>
</>
)}
+28 -19
View File
@@ -1,9 +1,16 @@
import { useT, type MessageKey } from '../i18n';
interface Plan {
key: string;
/** Server-facing package name (API contract, stays in Chinese). */
name: string;
/** Display name key. */
nameKey: MessageKey;
price: string;
count: string;
desc: string;
/** Display "N runs" key (e.g. '10 次' / '10 runs'). */
countKey: MessageKey;
/** Display description key. */
descKey: MessageKey;
featured?: boolean;
}
@@ -11,24 +18,27 @@ const PLANS: Plan[] = [
{
key: 'basic',
name: '体验包',
nameKey: 'pass.plan.basic.name',
price: '4.9',
count: '3 次',
desc: '适合先体验 AI 拼豆效果',
countKey: 'pass.plan.basic.count',
descKey: 'pass.plan.basic.desc',
},
{
key: 'standard',
name: '常用包',
nameKey: 'pass.plan.standard.name',
price: '12.9',
count: '10 次',
desc: '适合个人多次创作(推荐)',
countKey: 'pass.plan.standard.count',
descKey: 'pass.plan.standard.desc',
featured: true,
},
{
key: 'pro',
name: '进阶包',
nameKey: 'pass.plan.pro.name',
price: '29.9',
count: '30 次',
desc: '适合接单与持续出图',
countKey: 'pass.plan.pro.count',
descKey: 'pass.plan.pro.desc',
},
];
@@ -40,10 +50,11 @@ export type { Plan };
/** DOWNLOAD PASS (§2.5): 3 pricing cards + CTA. */
export default function PassSection({ onPlanClick }: PassSectionProps) {
const { t } = useT();
return (
<section className="pass" aria-label="权益套餐">
<h2 className="pass-title">AI生成权益</h2>
<p className="pass-sub">购买 / 兑换后解锁完整图纸与备料清单</p>
<section className="pass" aria-label={t('pass.aria')}>
<h2 className="pass-title">{t('pass.title')}</h2>
<p className="pass-sub">{t('pass.sub')}</p>
<div className="pass-cards">
{PLANS.map((plan) => (
@@ -51,27 +62,25 @@ export default function PassSection({ onPlanClick }: PassSectionProps) {
key={plan.key}
className={`pass-card${plan.featured ? ' pass-card--featured' : ''}`}
>
{plan.featured && <span className="pass-card-badge">推荐</span>}
<span className="pass-card-name">{plan.name}</span>
{plan.featured && <span className="pass-card-badge">{t('pass.badge')}</span>}
<span className="pass-card-name">{t(plan.nameKey)}</span>
<div className="pass-card-price">
¥{plan.price}
<small> / {plan.count}</small>
<small> / {t(plan.countKey)}</small>
</div>
<p className="pass-card-desc">{plan.desc}</p>
<p className="pass-card-desc">{t(plan.descKey)}</p>
<button
type="button"
className={`pass-cta${plan.featured ? '' : ' pass-cta--outline'}`}
onClick={() => onPlanClick(plan)}
>
购买 / 兑换 →
{t('pass.cta')}
</button>
</div>
))}
</div>
<p className="pass-benefit">
成功生成 1 张作品,消耗 1 次 · 该作品转拼豆图纸及首次高清下载免费
</p>
<p className="pass-benefit">{t('pass.benefit')}</p>
</section>
);
}
+30 -13
View File
@@ -2,6 +2,7 @@ import { useEffect, useRef, type ReactNode } from 'react';
import type { PatternSettings, SourceImage } from '../lib/usePattern';
import type { ProcessResult } from '../lib/image-processor';
import { drawPreview } from '../lib/drawPattern';
import { useT } from '../i18n';
interface PreviewPanelProps {
source: SourceImage | null;
@@ -14,6 +15,10 @@ interface PreviewPanelProps {
onDownload: () => void;
/** 可选的编辑工具栏(撤销/重做/旋转/镜像等),渲染在画布上方。 */
toolbar?: ReactNode;
/** T-067:可选的分享按钮,渲染在下载按钮旁。 */
shareButton?: ReactNode;
/** T-067:当前图纸是否来自分享链接(显示「来自分享」徽标)。 */
shared?: boolean;
}
/** 02 实时预览 panel (§2.6): canvas + ruler + download button. */
@@ -27,7 +32,10 @@ export default function PreviewPanel({
downloadError,
onDownload,
toolbar,
shareButton,
shared = false,
}: PreviewPanelProps) {
const { t } = useT();
const canvasRef = useRef<HTMLCanvasElement | null>(null);
useEffect(() => {
@@ -37,45 +45,51 @@ export default function PreviewPanel({
}
}, [result, settings.gridSize, settings.showGrid]);
const fileName = source ? source.name : '未命名';
const fileName = shared ? t('prev.sharedName') : source ? source.name : t('prev.unnamed');
const beadCount = result?.totalBeads ?? 0;
const downloadReady = Boolean(redeemed && result && source);
return (
<section className="panel" aria-label="02 实时预览">
<section className="panel" aria-label={t('prev.aria')}>
<div className="panel-header">
<span className="panel-index">02</span>
<h2 className="panel-title">
<span className="dot" aria-hidden="true">
●
</span>{' '}
实时预览
{t('prev.title')}
</h2>
<span className="panel-hint">每5格加粗 · 每10格标号</span>
<span className="panel-hint">{t('prev.ruler')}</span>
</div>
{toolbar}
{shared && (
<div className="shared-banner" role="note">
{t('prev.sharedBanner')}
</div>
)}
<div className="preview-canvas-wrap">
{processing ? (
<div className="preview-empty">
<span className="regen-spinner" aria-hidden="true" style={{ borderTopColor: '#b0aca0', borderColor: 'rgba(138,135,125,.3)' }} />
<br />
图片处理中…
{t('ctrl.processing')}
</div>
) : result ? (
<canvas
ref={canvasRef}
className="preview-canvas"
aria-label="拼豆图纸预览"
aria-label={t('prev.canvas.aria')}
/>
) : error ? (
<div className="preview-empty">{error}</div>
) : (
<div className="preview-empty">
上传图片后,这里会实时显示拼豆图纸。
{t('prev.empty')}
<br />
标尺:每5格加粗 · 每10格标号
{t('prev.empty.ruler')}
</div>
)}
</div>
@@ -85,14 +99,17 @@ export default function PreviewPanel({
{fileName}
</span>
<span className="preview-size">
{settings.gridSize} × {settings.gridSize} · 实际使用 {beadCount.toLocaleString()} 颗
{settings.gridSize} × {settings.gridSize} · {t('prev.beads', { count: beadCount.toLocaleString() })}
</span>
</div>
<button type="button" className="download-btn" disabled={!downloadReady} onClick={onDownload}>
↓ 兑换后下载完整图纸
</button>
<p className="download-note">首次下载免费 / 下载普通图纸 · 消耗 1 次</p>
<div className="preview-actions">
{shareButton}
<button type="button" className="download-btn" disabled={!downloadReady} onClick={onDownload}>
{t('prev.download')}
</button>
</div>
<p className="download-note">{t('prev.download.note')}</p>
{downloadError && <p className="download-error">{downloadError}</p>}
</section>
);
+15 -7
View File
@@ -1,4 +1,5 @@
import { useState } from 'react';
import { useT } from '../i18n';
interface RedeemModalProps {
onClose: () => void;
@@ -8,6 +9,7 @@ interface RedeemModalProps {
/** 兑换码弹窗 (§3.5, copy §7.1): validates the code against the server. */
export default function RedeemModal({ onClose, onRedeem }: RedeemModalProps) {
const { t } = useT();
const [code, setCode] = useState('');
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
@@ -15,7 +17,7 @@ export default function RedeemModal({ onClose, onRedeem }: RedeemModalProps) {
const handleRedeem = async (): Promise<void> => {
const trimmed = code.trim();
if (!trimmed) {
setError('兑换失败 / 兑换码不存在,请检查后重试');
setError(t('modal.redeem.empty'));
return;
}
if (submitting) return;
@@ -24,21 +26,27 @@ export default function RedeemModal({ onClose, onRedeem }: RedeemModalProps) {
try {
await onRedeem(trimmed);
} catch (err) {
setError(err instanceof Error ? err.message : '兑换失败,请稍后重试');
setError(err instanceof Error ? err.message : t('modal.redeem.fail'));
setSubmitting(false);
}
};
return (
<div className="modal-mask" onClick={onClose}>
<div className="modal" role="dialog" aria-modal="true" aria-label="输入兑换码" onClick={(e) => e.stopPropagation()}>
<button type="button" className="modal-close" aria-label="关闭" onClick={onClose}>
<div
className="modal"
role="dialog"
aria-modal="true"
aria-label={t('modal.redeem.aria')}
onClick={(e) => e.stopPropagation()}
>
<button type="button" className="modal-close" aria-label={t('modal.close')} onClick={onClose}>
×
</button>
<h3 className="modal-title">输入兑换码</h3>
<h3 className="modal-title">{t('modal.redeem.title')}</h3>
<input
className="redeem-input"
placeholder="请输入兑换码"
placeholder={t('modal.redeem.placeholder')}
value={code}
autoFocus
onChange={(e) => {
@@ -51,7 +59,7 @@ export default function RedeemModal({ onClose, onRedeem }: RedeemModalProps) {
/>
{error && <p className="redeem-error">{error}</p>}
<button type="button" className="redeem-btn" disabled={submitting} onClick={handleRedeem}>
{submitting ? '兑换中…' : '兑换'}
{submitting ? t('modal.redeem.processing') : t('modal.redeem.submit')}
</button>
</div>
</div>
+65
View File
@@ -0,0 +1,65 @@
import { useCallback, useEffect, useState } from 'react';
import type { ShareCell } from '../lib/share-codec';
import { buildShareUrl, encodePattern } from '../lib/share-codec';
import { useT } from '../i18n';
interface ShareButtonProps {
/** 行优先扁平格子(当前预览所见的编辑后网格)。 */
grid: ShareCell[];
/** 图纸边长。 */
size: number;
/** 品牌 ID,随分享链接透传。 */
brandId: string;
}
const TOAST_MS = 2500;
/**
* 分享按钮(T-067):点击后把当前图纸编码为分享码并复制分享链接;
* 支持 Web Share API 时优先弹系统分享面板。复制成功后显示 toast。
*/
export default function ShareButton({ grid, size, brandId }: ShareButtonProps) {
const { t } = useT();
const [toast, setToast] = useState<string | null>(null);
useEffect(() => {
if (toast === null) return;
const timer = setTimeout(() => setToast(null), TOAST_MS);
return () => clearTimeout(timer);
}, [toast]);
const handleShare = useCallback(async () => {
try {
const url = buildShareUrl(encodePattern(grid, size), brandId);
// 优先使用系统分享面板(移动端原生分享,含复制到剪贴板入口)
if (typeof navigator !== 'undefined' && typeof navigator.share === 'function') {
try {
await navigator.share({ title: t('share.title'), text: t('share.text'), url });
return; // 分享面板已打开,无需再复制
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') {
return; // 用户取消分享
}
// 其余失败(如桌面端不支持分享)回退到剪贴板
}
}
await navigator.clipboard.writeText(url);
setToast(t('share.copied'));
} catch {
setToast(t('share.failed'));
}
}, [grid, size, brandId, t]);
return (
<div className="share-wrap">
<button type="button" className="share-btn" onClick={() => void handleShare()}>
{t('share.button')}
</button>
{toast !== null && (
<div className="share-toast" role="status">
{toast}
</div>
)}
</div>
);
}
+155
View File
@@ -0,0 +1,155 @@
/**
* i18n framework tests:
* - zh/en message key parity (identical key sets)
* - t()/translate() {param} interpolation
* - fallback semantics (default locale / missing key)
* - locale detection & resolution rules
* - I18nProvider + useT() wiring (server-side render, no DOM needed)
*/
import { describe, expect, it } from 'vitest';
import { createElement, type ReactNode } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { translate, MESSAGES, I18nProvider, useT } from '../index.js';
import { zhCN, type MessageKey } from '../messages/zh-CN.js';
import { en } from '../messages/en.js';
import {
DEFAULT_LOCALE,
LOCALES,
LOCALE_STORAGE_KEY,
detectLocale,
isLocale,
resolveLocale,
} from '../locale.js';
// ---------------------------------------------------------------------------
// 1. Message key parity — both locales must expose exactly the same keys.
// ---------------------------------------------------------------------------
describe('message catalogs', () => {
it('zh-CN and en expose identical key sets', () => {
expect(Object.keys(en).sort()).toEqual(Object.keys(zhCN).sort());
});
it('contains a non-trivial catalog (all visible UI covered)', () => {
expect(Object.keys(zhCN).length).toBeGreaterThan(100);
});
it('every key resolves through MESSAGES for both locales', () => {
for (const key of Object.keys(zhCN) as MessageKey[]) {
expect(MESSAGES['zh-CN'][key]).toBeDefined();
expect(MESSAGES.en[key]).toBeDefined();
}
});
it('default locale is part of the supported list', () => {
expect(LOCALES).toContain(DEFAULT_LOCALE);
expect(isLocale(DEFAULT_LOCALE)).toBe(true);
});
});
// ---------------------------------------------------------------------------
// 2. translate() — interpolation & fallback.
// ---------------------------------------------------------------------------
describe('translate', () => {
it('returns the zh-CN value for a plain key', () => {
expect(translate('zh-CN', 'nav.toPattern')).toBe('图片转拼豆');
expect(translate('en', 'nav.toPattern')).toBe('Image to Beads');
});
it('interpolates {param} placeholders', () => {
expect(translate('zh-CN', 'ctrl.grid.hint', { size: 32 })).toBe(
'成品约 32 × 32 cm(按 5mm 豆计算)',
);
expect(translate('en', 'ctrl.grid.hint', { size: 32 })).toBe(
'Approx. 32 × 32 cm finished (based on 5mm beads)',
);
});
it('supports number params and repeated placeholders', () => {
const out = translate('en', 'ctrl.grid.hint', { size: 64 });
expect(out).toContain('64 × 64');
expect(out).not.toContain('{size}');
});
it('keeps placeholders untouched when params are missing', () => {
expect(translate('en', 'prev.beads')).toBe('{count} beads used');
});
it('falls back to the default locale when the key is missing in the target locale', () => {
// MESSAGES is complete by construction; simulate a missing en entry.
const missingEn = translate('en', 'hero.title.accent');
expect(missingEn).toBe(en['hero.title.accent']);
expect(translate(DEFAULT_LOCALE, 'hero.title.accent')).toBe(zhCN['hero.title.accent']);
});
it('returns the key itself when it is missing everywhere (graceful)', () => {
const unknown = translate('en', 'no.such.key' as MessageKey);
expect(unknown).toBe('no.such.key');
});
});
// ---------------------------------------------------------------------------
// 3. Locale detection & resolution.
// ---------------------------------------------------------------------------
describe('resolveLocale / detectLocale', () => {
it('stored preference wins over navigator language', () => {
expect(resolveLocale('en', 'zh-CN')).toBe('en');
expect(resolveLocale('zh-CN', 'en-US')).toBe('zh-CN');
});
it('invalid stored values are ignored (falls through to detection)', () => {
expect(resolveLocale('fr', 'en-US')).toBe('en');
expect(resolveLocale('fr', 'zh-TW')).toBe('zh-CN');
});
it('detects zh-* navigator languages as zh-CN', () => {
expect(resolveLocale(null, 'zh-CN')).toBe('zh-CN');
expect(resolveLocale(null, 'zh')).toBe('zh-CN');
expect(resolveLocale(null, 'zh-TW')).toBe('zh-CN');
});
it('any non-Chinese language falls back to en', () => {
expect(resolveLocale(null, 'en-US')).toBe('en');
expect(resolveLocale(null, 'ja-JP')).toBe('en');
expect(resolveLocale(null, 'fr-FR')).toBe('en');
});
it('uses the default locale when nothing is known', () => {
expect(resolveLocale(null, null)).toBe(DEFAULT_LOCALE);
expect(detectLocale()).toBe(DEFAULT_LOCALE); // no navigator in node
});
it('exposes the storage key constant', () => {
expect(LOCALE_STORAGE_KEY).toBe('perler-locale');
});
});
// ---------------------------------------------------------------------------
// 4. I18nProvider + useT() (rendered server-side; effects never run).
// ---------------------------------------------------------------------------
describe('I18nProvider / useT', () => {
function Probe(): ReactNode {
const { t } = useT();
return createElement(
'span',
null,
`${t('nav.toPattern')} | ${t('prev.beads', { count: '1,234' })}`,
);
}
it('provides t() to descendants with the detected default locale', () => {
const html = renderToStaticMarkup(createElement(I18nProvider, null, createElement(Probe)));
expect(html).toContain('图片转拼豆');
expect(html).toContain('实际使用 1,234 颗');
expect(html).not.toContain('{count}');
});
it('throws when useT() is used outside an I18nProvider', () => {
expect(() => renderToStaticMarkup(createElement(Probe))).toThrow(/I18nProvider/);
});
});
+120
View File
@@ -0,0 +1,120 @@
/**
* PERLER LAB — zero-dependency i18n runtime.
*
* - `I18nProvider`: React context provider, locale persisted to
* localStorage under 'perler-locale'.
* - `useT()`: returns `{ t, locale, setLocale }`.
* - `translate(locale, key, params)`: pure function with `{param}`
* interpolation and fallback (missing key → default locale → the key
* itself).
*/
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from 'react';
import { zhCN, type MessageKey, type Messages } from './messages/zh-CN';
import { en } from './messages/en';
import {
DEFAULT_LOCALE,
LOCALE_STORAGE_KEY,
resolveLocale,
type Locale,
} from './locale';
export type { MessageKey, Messages } from './messages/zh-CN';
export {
DEFAULT_LOCALE,
LOCALES,
LOCALE_STORAGE_KEY,
detectLocale,
isLocale,
resolveLocale,
type Locale,
} from './locale';
export const MESSAGES: Record<Locale, Messages> = {
'zh-CN': zhCN,
en,
};
export type TParams = Record<string, string | number>;
export type TFunction = (key: MessageKey, params?: TParams) => string;
/**
* Pure translate: looks up `key` in the given locale, falling back to the
* default locale, then to the key itself. Replaces `{name}` placeholders
* with `params[name]` (unknown placeholders are left untouched).
*/
export function translate(locale: Locale, key: MessageKey, params?: TParams): string {
const template = MESSAGES[locale][key] ?? MESSAGES[DEFAULT_LOCALE][key] ?? key;
if (!params) return template;
return template.replace(/\{(\w+)\}/g, (match, name: string) =>
name in params ? String(params[name]) : match,
);
}
interface I18nContextValue {
locale: Locale;
setLocale: (locale: Locale) => void;
t: TFunction;
}
const I18nContext = createContext<I18nContextValue | null>(null);
function readStoredLocale(): string | null {
if (typeof window === 'undefined') return null;
try {
return window.localStorage.getItem(LOCALE_STORAGE_KEY);
} catch {
return null;
}
}
function readNavigatorLanguage(): string | null {
if (typeof navigator === 'undefined') return null;
return navigator.language ?? null;
}
interface I18nProviderProps {
children: ReactNode;
}
export function I18nProvider({ children }: I18nProviderProps) {
const [locale, setLocaleState] = useState<Locale>(() =>
resolveLocale(readStoredLocale(), readNavigatorLanguage()),
);
// Persist the choice so the next visit keeps it.
useEffect(() => {
try {
window.localStorage.setItem(LOCALE_STORAGE_KEY, locale);
} catch {
// Storage unavailable (private mode, sandboxed iframe…) — in-memory state still works.
}
if (typeof document !== 'undefined') {
document.documentElement.lang = locale;
document.title = translate(locale, 'app.title');
}
}, [locale]);
const setLocale = useCallback((next: Locale) => setLocaleState(next), []);
const t = useCallback<TFunction>((key, params) => translate(locale, key, params), [locale]);
const value = useMemo<I18nContextValue>(() => ({ locale, setLocale, t }), [locale, setLocale, t]);
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
}
export function useT(): I18nContextValue {
const ctx = useContext(I18nContext);
if (!ctx) {
throw new Error('useT must be used within an I18nProvider');
}
return ctx;
}
+49
View File
@@ -0,0 +1,49 @@
/**
* Locale registry for PERLER LAB.
*
* Only two locales are fully translated (zh-CN, en); any other browser
* language falls back to English via `resolveLocale`.
*/
export type Locale = 'zh-CN' | 'en';
/** All supported locales (order = display order in the language switcher). */
export const LOCALES: readonly Locale[] = ['zh-CN', 'en'] as const;
/** Fallback locale used when nothing is stored/detected. */
export const DEFAULT_LOCALE: Locale = 'zh-CN';
/** localStorage key persisting the user's locale choice. */
export const LOCALE_STORAGE_KEY = 'perler-locale';
export function isLocale(value: unknown): value is Locale {
return typeof value === 'string' && (LOCALES as readonly string[]).includes(value);
}
/**
* Deterministic locale resolution:
* 1. a stored (previously persisted) valid locale wins;
* 2. otherwise `navigator.language` is detected (any zh* → zh-CN, else en);
* 3. otherwise the default locale is used.
*/
export function resolveLocale(stored: string | null, navLanguage: string | null): Locale {
if (stored !== null && isLocale(stored)) {
return stored;
}
if (navLanguage !== null) {
const base = navLanguage.toLowerCase();
if (base === 'zh' || base.startsWith('zh-')) {
return 'zh-CN';
}
return 'en';
}
return DEFAULT_LOCALE;
}
/** Detect the locale from the browser environment (navigator.language). */
export function detectLocale(): Locale {
if (typeof navigator === 'undefined') {
return DEFAULT_LOCALE;
}
return resolveLocale(null, navigator.language ?? null);
}
+338
View File
@@ -0,0 +1,338 @@
/**
* PERLER LAB — English UI copy.
*
* Typed as `Messages` (= typeof zhCN) so TypeScript fails the build if any
* key is missing or added in only one locale — key parity is compile-time
* enforced, not just test-time.
*/
import type { Messages } from './zh-CN';
export const en: Messages = {
/* ── Nav ── */
'nav.toPattern': 'Image to Beads',
'nav.chibi': 'AI Beads Studio',
'nav.agency': 'Partnership',
'nav.status': 'Free preview · pay per AI generation',
'nav.lang': 'Language',
/* ── Hero ── */
'hero.title.prefix': 'Turn any image into',
'hero.title.accent': 'beads, one by one.',
'hero.sub':
'Upload, generate and fine-tune patterns for free — redeem a code to download the full HD pattern and bead list.',
'hero.stat.beads': 'beads',
'hero.stat.colors': 'colors',
/* ── PassSection ── */
'pass.aria': 'AI generation plans',
'pass.title': 'AI Generation Plans',
'pass.sub': 'Unlock full patterns & bead lists after purchase / redemption',
'pass.badge': 'Popular',
'pass.cta': 'Buy / Redeem →',
'pass.benefit':
'1 successful generation costs 1 credit · converting a piece to a bead pattern and the first HD download are free',
'pass.plan.basic.name': 'Starter',
'pass.plan.basic.count': '3 runs',
'pass.plan.basic.desc': 'Try out AI bead generation',
'pass.plan.standard.name': 'Standard',
'pass.plan.standard.count': '10 runs',
'pass.plan.standard.desc': 'For regular personal creations (recommended)',
'pass.plan.pro.name': 'Pro',
'pass.plan.pro.count': '30 runs',
'pass.plan.pro.desc': 'For commissions and heavy usage',
/* ── ControlsPanel ── */
'ctrl.aria': '01 Generation settings',
'ctrl.title': 'Generation Settings',
'ctrl.upload.aria': 'Upload an image',
'ctrl.upload.title': 'Upload an image',
'ctrl.upload.sub': 'Supports JPG, PNG, WEBP',
'ctrl.uploaded': 'uploaded',
'ctrl.reset': 'Reset',
'ctrl.brand': 'Brand Palette',
'ctrl.brand.hint': 'Pattern color codes and the bead list follow the selected brand',
'ctrl.grid': 'Pattern Size',
'ctrl.grid.hint': 'Approx. {size} × {size} cm finished (based on 5mm beads)',
'ctrl.colors': 'Max Colors',
'ctrl.colors.hint': 'More colors mean higher fidelity; 24 is recommended',
'ctrl.removeBg': 'Remove Background',
'ctrl.removeBg.desc': 'Keep only the subject — background beads are excluded',
'ctrl.showGrid': 'Show Grid',
'ctrl.showGrid.desc': 'Helps you place each bead precisely',
'ctrl.processing': 'Processing image…',
'ctrl.regen': '↻ Regenerate Pattern',
/* ── PreviewPanel ── */
'prev.aria': '02 Live preview',
'prev.title': 'Live Preview',
'prev.ruler': 'Bold every 5 cells · numbered every 10',
'prev.unnamed': 'Untitled',
'prev.canvas.aria': 'Bead pattern preview',
'prev.empty': 'Upload an image and the bead pattern will appear here in real time.',
'prev.empty.ruler': 'Ruler: bold every 5 cells · numbered every 10',
'prev.beads': '{count} beads used',
'prev.download': '↓ Download Full Pattern After Redemption',
'prev.download.note': 'First download free / normal pattern downloads · cost 1 credit',
'prev.sharedName': 'Shared pattern',
'prev.sharedBanner': 'Shared pattern — upload a new image to generate a new one',
/* ── InventoryPanel ── */
'inv.aria': '03 {brand} bead list',
'inv.title': '{brand} Bead List',
'inv.unlocked': 'Unlocked',
'inv.locked': '🔒 Protected',
'inv.total': 'Total beads',
'inv.colors': 'Colors used',
'inv.perColor': '{count} beads',
'inv.empty': 'Upload an image and generate a pattern to see the {brand} color list here.',
'inv.extra': 'We recommend ordering 10% extra · about',
'inv.beads': ' beads',
'inv.ghost.hidden': 'Full color codes hidden',
'inv.lock.title': 'Full bead list is locked',
'inv.lock.desc':
'Redeem to see all {brand} color codes, bead counts per color, total beads, and the 10% extra suggestion',
'inv.unlock': 'Enter a code to unlock',
/* ── Modals (shared / RedeemModal) ── */
'modal.close': 'Close',
'modal.redeem.aria': 'Enter redemption code',
'modal.redeem.title': 'Enter Redemption Code',
'modal.redeem.placeholder': 'Enter your redemption code',
'modal.redeem.empty': 'Redemption failed / code not found — please check and try again',
'modal.redeem.fail': 'Redemption failed, please try again later',
'modal.redeem.processing': 'Redeeming…',
'modal.redeem.submit': 'Redeem',
/* ── OrderModal ── */
'modal.order.aria': 'Buy AI generation credits',
'modal.order.title': 'Buy AI Generation Credits',
'modal.order.amountDue': 'Amount due · ¥{price} · {count}',
'modal.order.method.wechat': 'WeChat QR code',
'modal.order.method.alipay': 'Alipay QR code',
'modal.order.goPay': 'Go to Pay',
'modal.order.creating': 'Placing order…',
'modal.order.note':
'Screenshot or long-press to save the QR code, then open the matching payment app to scan — the amount must match the order',
'modal.order.no': 'Order No.',
'modal.order.amount': 'Amount Due',
'modal.order.payHint':
'Please scan with {method} (or long-press to recognize the QR code); the amount must match the order',
'modal.order.payUrl': 'Payment link: {url}',
'modal.order.qr': ' · QR code: {qr}',
'modal.order.simulate': 'Simulate Payment',
'modal.order.confirming': 'Confirming…',
'modal.order.simNote':
'Demo environment: marks the order as paid and issues a redemption code instantly',
'modal.order.success': 'Payment successful · redemption code',
'modal.order.redeemed': 'Auto-redeemed — AI generation credits are now in your account',
'modal.order.redeemFailed':
'Auto-redeem failed — copy the code and redeem it manually in “Enter redemption code”',
'modal.order.done': 'Done',
'modal.order.createFail': 'Failed to place order, please try again later',
'modal.order.payFail': 'Payment confirmation failed, please try again later',
'modal.order.methodLabel.wechat': 'WeChat',
'modal.order.methodLabel.alipay': 'Alipay',
/* ── AgencyModal ── */
'agency.aria': 'Partnership',
'agency.title': 'Partnership',
'agency.plan.basic.name': 'Starter Agent',
'agency.plan.basic.count': '200 runs',
'agency.plan.standard.name': 'Standard Agent',
'agency.plan.standard.count': '500 runs',
'agency.plan.core.name': 'Core Agent',
'agency.plan.core.count': '1000 runs',
/* ── EditToolbar ── */
'edit.aria': 'Edit tools',
'edit.undo': 'Undo',
'edit.undo.title': 'Undo last step',
'edit.redo': 'Redo',
'edit.redo.title': 'Redo next step',
'edit.rotate': 'Rotate 90°',
'edit.rotate.title': 'Rotate clockwise 90°',
'edit.mirrorV': 'Mirror L/R',
'edit.mirrorV.title': 'Mirror left-right (flip across the vertical axis)',
'edit.mirrorH': 'Mirror U/D',
'edit.mirrorH.title': 'Mirror top-bottom (flip across the horizontal axis)',
'edit.flip': 'Flip diag',
'edit.flip.title': 'Flip diagonally (main-diagonal symmetry, great for symmetric patterns)',
/* ── Footer ── */
'footer.slogan': 'PERLER LAB · every bead has its place',
'footer.note': 'Patterns are for personal crafting reference only',
/* ── App ── */
'app.title': 'PERLER LAB · Bead Pattern Generator',
'app.mobileCta': 'Buy / Redeem →',
'app.uploadFail': 'Failed to read the image — please try another one',
'app.downloadFail': 'Download failed, please try again later',
'app.downloadBaseName': 'bead-pattern',
'app.downloadSuffix': 'bead-pattern',
/* ── ShareButton ── */
'share.button': 'Share',
'share.title': 'Bead pattern share',
'share.text': 'Check out this bead pattern!',
'share.copied': 'Share link copied',
'share.failed': 'Share failed, please try again later',
/* ── ChibiPage ── */
'chibi.nav.back': '← Normal Beads',
'chibi.nav.badge': 'Each generation costs 1 credit',
'chibi.hero.title.prefix': 'Pick a category, refine the details,',
'chibi.hero.title.accent': 'and save the result first.',
'chibi.hero.sub':
'Each successful AI generation costs 1 credit; converting the piece to a formal bead pattern and the first download are free. Only generating a new piece charges again.',
'chibi.card.aria': 'Bead generation settings',
'chibi.step.category': 'Choose a Bead Category',
'chibi.tabs.aria': 'Bead categories',
'chibi.compare.original': 'Original',
'chibi.compare.result': 'Pixel bead result',
'chibi.subtype.title': 'Subtype · different styles within each category',
'chibi.step.grid': 'Pattern Grid Size',
'chibi.step.colors': 'Max Colors',
'chibi.step.colors.note': 'More colors, higher fidelity',
'chibi.step.composition': 'Composition',
'chibi.step.tags': 'Detail Tags',
'chibi.tags.max': 'Up to {max} tags',
'chibi.tags.selected': '{selected}/{max} selected',
'chibi.recommend': 'Recommended',
'chibi.grid.simple': 'Simple',
'chibi.grid.recommended': 'Recommended',
'chibi.grid.fine': 'Fine',
'chibi.grid.hd': 'HD',
'chibi.colors.save': 'Frugal',
'chibi.colors.balanced': 'Balanced',
'chibi.colors.fine': 'Refined',
'chibi.colors.high': 'High fidelity',
'chibi.composition.closeup': 'Close-up',
'chibi.composition.half': 'Half frame',
'chibi.composition.full': 'Full frame',
'chibi.prompt.label': 'Extra description (optional)',
'chibi.prompt.placeholder': 'Details to keep, elements to avoid…',
'chibi.reference.label': 'Style reference image (optional)',
'chibi.reference.title': 'Upload style reference',
'chibi.reference.hint': 'The subject is not copied from it',
'chibi.confirm.aria': 'Confirm before generating',
'chibi.confirm.title': 'Confirm Before Generating',
'chibi.sample': 'Sample',
'chibi.sample.desc': 'Default pixel look',
'chibi.spec.category': 'Category',
'chibi.spec.subtype': 'Subtype',
'chibi.spec.grid': 'Grid',
'chibi.spec.beads': 'Est. beads',
'chibi.spec.beads.value': '~{count} beads',
'chibi.upload.original.title': 'Upload the original image',
'chibi.upload.original.hint': 'Clear subjects and natural light work best · max 12MB',
'chibi.payNote.title': 'AI generation is a paid feature.',
'chibi.payNote.body':
'Each successful generation costs 1 credit; converting to a pattern and the first download are free; failures are not charged.',
'chibi.cta.generating': 'Generating…',
'chibi.cta.generate': 'Generate →',
'chibi.cta.redeemFirst': 'Redeem to Generate →',
'chibi.codeLink': 'Enter redemption code',
'chibi.result.aria': 'Generation result',
'chibi.result.title': 'Generation Result',
'chibi.result.alt': 'AI bead generation result',
'chibi.result.withGrant': 'Pattern ready · first download free (download grant saved)',
'chibi.result.plain': 'Pattern ready',
'chibi.promise.aria': 'Our promises',
'chibi.promise.classify': 'Smarter classification',
'chibi.promise.classify.desc':
'Different subjects use different prompts — landscapes, pets and food no longer follow portrait rules.',
'chibi.promise.pay': 'Pay per generation',
'chibi.promise.pay.desc':
'Each successful generation costs 1 credit; failures are free, so model costs stay predictable.',
'chibi.promise.safe': 'No lost results',
'chibi.promise.safe.desc':
'While unsaved, all switching is locked and you are reminded again before leaving the page.',
'chibi.footer': 'PERLER LAB · AI Beads Studio',
'chibi.footer.back': 'Back to image-to-beads →',
'chibi.modal.aria': 'Enter redemption code',
'chibi.modal.title': 'Enter Redemption Code',
'chibi.modal.placeholder': 'Enter your redemption code',
'chibi.modal.empty': 'Please enter a redemption code',
'chibi.modal.fail': 'Redemption failed, please try again later',
'chibi.modal.processing': 'Redeeming…',
'chibi.modal.submit': 'Redeem',
'chibi.upload.tooBig': 'Image must be under 12MB',
'chibi.upload.readFail': 'Failed to read the image — please try another one',
'chibi.upload.ready': 'ready',
'chibi.upload.reset': 'Reset',
'chibi.error.noImage': 'Please upload the original image first',
'chibi.error.generateFail': 'Generation failed, please try again later',
'chibi.tags.hint': 'Up to {max} tags',
/* ── ChibiPage data: categories ── */
'chibi.cat.landscape.name': 'Landscape',
'chibi.cat.landscape.note': 'Mountains, cities and travel memories',
'chibi.cat.landscape.nature': 'Nature',
'chibi.cat.landscape.nature.note': '',
'chibi.cat.landscape.city': 'City night',
'chibi.cat.landscape.city.note': '',
'chibi.cat.landscape.landmark': 'Landmarks',
'chibi.cat.landscape.landmark.note': '',
'chibi.cat.people.name': 'People',
'chibi.cat.people.note': 'Clear features, hairstyle and outfit',
'chibi.cat.people.bigeye': 'Cute big eyes',
'chibi.cat.people.bigeye.note': 'Big eyes, round face, bold outline',
'chibi.cat.people.youth': 'Fresh youth',
'chibi.cat.people.youth.note': 'Natural features, clean outfit',
'chibi.cat.people.retro': 'Retro pixel',
'chibi.cat.people.retro.note': 'Vintage palette, game feel',
'chibi.cat.pet.name': 'Pets',
'chibi.cat.pet.note': 'Coat, expression and breed features',
'chibi.cat.pet.cat': 'Cat portrait',
'chibi.cat.pet.cat.note': 'Round face and markings',
'chibi.cat.pet.dog': 'Full-body dog',
'chibi.cat.pet.dog.note': 'Ears, legs and coat color',
'chibi.cat.pet.duo': 'Two pets together',
'chibi.cat.pet.duo.note': 'Two pets in one frame',
'chibi.cat.item.name': 'Objects',
'chibi.cat.item.note': 'Figures, gifts and keepsakes',
'chibi.cat.item.toy': 'Figures & toys',
'chibi.cat.item.toy.note': 'Silhouette first',
'chibi.cat.item.daily': 'Everyday items',
'chibi.cat.item.daily.note': 'Keep structure and material',
'chibi.cat.item.gift': 'Gifts & keepsakes',
'chibi.cat.item.gift.note': 'Highlight wrapping and decor',
'chibi.cat.food.name': 'Food',
'chibi.cat.food.note': 'Desserts, drinks and local specialties',
'chibi.cat.food.dessert': 'Desserts & cakes',
'chibi.cat.food.dessert.note': 'Cream and decoration clear',
'chibi.cat.food.drink': 'Coffee & drinks',
'chibi.cat.food.drink.note': 'Cup, layers and toppings',
'chibi.cat.food.meal': 'Home cooking',
'chibi.cat.food.meal.note': 'Main ingredients recognizable',
/* ── ChibiPage data: prompt tags ── */
'chibi.tag.buildings': 'Highlight the main building',
'chibi.tag.texture': 'Reduce fragmented texture',
'chibi.tag.light': 'Keep light and atmosphere',
'chibi.tag.border': 'Solid color border',
'chibi.tag.contrast': 'High-contrast outline',
'chibi.tag.clouds': 'Sky and distant mountains',
'chibi.tag.face': 'Sharper facial features',
'chibi.tag.clothes': 'Keep clothing details',
'chibi.tag.hair': 'Keep hairstyle',
'chibi.tag.accessory': 'Keep accessories',
'chibi.tag.pet': 'Include a pet',
'chibi.tag.bg': 'Solid background',
'chibi.tag.eyes': 'Livelier eyes',
'chibi.tag.fur': 'Keep coat colors and markings',
'chibi.tag.ears': 'Emphasize ear outlines',
'chibi.tag.collar': 'Keep collar accessories',
'chibi.tag.limbs': 'Complete limbs',
'chibi.tag.shape': 'Keep brand silhouette',
'chibi.tag.structure': 'Emphasize structure outlines',
'chibi.tag.gloss': 'Reduce glare and gradients',
'chibi.tag.details': 'Keep small accessories',
'chibi.tag.center': 'Centered composition',
'chibi.tag.foodMain': 'Highlight the food subject',
'chibi.tag.layers': 'Keep ingredient layers',
'chibi.tag.decor': 'Reduce tiny decorations',
'chibi.tag.saturation': 'Boost color contrast',
'chibi.tag.topdown': 'Top-down composition',
};
+329
View File
@@ -0,0 +1,329 @@
/**
* PERLER LAB — 中文(简体)UI 文案。
*
* 单一来源:所有可见 UI 文本的键必须从这里派生(`MessageKey`),
* en.ts 以 `Messages` 类型约束保证键完全一致(编译期校验)。
*
* 参数插值:模板中使用 `{name}`,由 translate() 以参数替换。
*/
export const zhCN = {
/* ── Nav ── */
'nav.toPattern': '图片转拼豆',
'nav.chibi': 'AI拼豆专区',
'nav.agency': '代理合作',
'nav.status': '普通预览免费 · AI生成按次付费',
'nav.lang': '语言',
/* ── Hero ── */
'hero.title.prefix': '把喜欢的图片,',
'hero.title.accent': '变成一颗颗拼豆。',
'hero.sub': '免费上传、生成和调整图纸,满意后使用兑换码下载完整高清图纸与用豆清单。',
'hero.stat.beads': '颗拼豆',
'hero.stat.colors': '种颜色',
/* ── PassSection(权益套餐) ── */
'pass.aria': '权益套餐',
'pass.title': 'AI生成权益',
'pass.sub': '购买 / 兑换后解锁完整图纸与备料清单',
'pass.badge': '推荐',
'pass.cta': '购买 / 兑换 →',
'pass.benefit': '成功生成 1 张作品,消耗 1 次 · 该作品转拼豆图纸及首次高清下载免费',
'pass.plan.basic.name': '体验包',
'pass.plan.basic.count': '3 次',
'pass.plan.basic.desc': '适合先体验 AI 拼豆效果',
'pass.plan.standard.name': '常用包',
'pass.plan.standard.count': '10 次',
'pass.plan.standard.desc': '适合个人多次创作(推荐)',
'pass.plan.pro.name': '进阶包',
'pass.plan.pro.count': '30 次',
'pass.plan.pro.desc': '适合接单与持续出图',
/* ── ControlsPanel(01 生成设置) ── */
'ctrl.aria': '01 生成设置',
'ctrl.title': '生成设置',
'ctrl.upload.aria': '上传一张图片',
'ctrl.upload.title': '上传一张图片',
'ctrl.upload.sub': '支持 JPG、PNG、WEBP',
'ctrl.uploaded': '已上传',
'ctrl.reset': '重置',
'ctrl.brand': '品牌色板',
'ctrl.brand.hint': '图纸色号与备料清单将按所选品牌编码',
'ctrl.grid': '图纸尺寸',
'ctrl.grid.hint': '成品约 {size} × {size} cm(按 5mm 豆计算)',
'ctrl.colors': '最大颜色数',
'ctrl.colors.hint': '颜色越多,还原度越高;默认推荐 24 色',
'ctrl.removeBg': '一键去除背景',
'ctrl.removeBg.desc': '只保留人物或主体,不计算背景豆',
'ctrl.showGrid': '显示辅助网格',
'ctrl.showGrid.desc': '方便逐格定位拼豆',
'ctrl.processing': '图片处理中…',
'ctrl.regen': '↻ 重新生成图纸',
/* ── PreviewPanel(02 实时预览) ── */
'prev.aria': '02 实时预览',
'prev.title': '实时预览',
'prev.ruler': '每5格加粗 · 每10格标号',
'prev.unnamed': '未命名',
'prev.canvas.aria': '拼豆图纸预览',
'prev.empty': '上传图片后,这里会实时显示拼豆图纸。',
'prev.empty.ruler': '标尺:每5格加粗 · 每10格标号',
'prev.beads': '实际使用 {count} 颗',
'prev.download': '↓ 兑换后下载完整图纸',
'prev.download.note': '首次下载免费 / 下载普通图纸 · 消耗 1 次',
'prev.sharedName': '来自分享的图纸',
'prev.sharedBanner': '来自分享的图纸 · 重新上传图片可生成新图纸',
/* ── InventoryPanel(03 备料清单) ── */
'inv.aria': '03 {brand} 备料清单',
'inv.title': '{brand} 备料清单',
'inv.unlocked': '已解锁',
'inv.locked': '🔒 受保护',
'inv.total': '实际总颗数',
'inv.colors': '使用颜色',
'inv.perColor': '{count} 颗',
'inv.empty': '上传图片并生成图纸后,这里会显示 {brand} 色号清单。',
'inv.extra': '建议多备 10% · 约',
'inv.beads': ' 颗',
'inv.ghost.hidden': '完整色号已隐藏',
'inv.lock.title': '完整备料清单已锁定',
'inv.lock.desc': '兑换后可查看全部 {brand} 色号、每色颗数、总颗数及 10% 备豆建议',
'inv.unlock': '输入兑换码解锁',
/* ── 弹窗通用 / RedeemModal ── */
'modal.close': '关闭',
'modal.redeem.aria': '输入兑换码',
'modal.redeem.title': '输入兑换码',
'modal.redeem.placeholder': '请输入兑换码',
'modal.redeem.empty': '兑换失败 / 兑换码不存在,请检查后重试',
'modal.redeem.fail': '兑换失败,请稍后重试',
'modal.redeem.processing': '兑换中…',
'modal.redeem.submit': '兑换',
/* ── OrderModal ── */
'modal.order.aria': '购买 AI 生成次数',
'modal.order.title': '购买 AI 生成次数',
'modal.order.amountDue': '应付金额 · ¥{price} · {count} 生成',
'modal.order.method.wechat': '微信收款码',
'modal.order.method.alipay': '支付宝收款码',
'modal.order.goPay': '去支付',
'modal.order.creating': '下单中…',
'modal.order.note': '截图或长按保存收款码,再打开对应支付应用扫码支付 · 付款金额请与上方一致',
'modal.order.no': '订单号',
'modal.order.amount': '应付金额',
'modal.order.payHint': '请使用{method}扫码支付(或长按识别收款码),付款金额请与上方一致',
'modal.order.payUrl': '支付链接:{url}',
'modal.order.qr': ' · 收款码:{qr}',
'modal.order.simulate': '模拟支付完成',
'modal.order.confirming': '确认中…',
'modal.order.simNote': '模拟环境:点击后直接标记订单已支付并发放兑换码',
'modal.order.success': '支付成功 · 权益兑换码',
'modal.order.redeemed': '已自动兑换成功,AI 生成权益已到账',
'modal.order.redeemFailed': '自动兑换失败,可复制兑换码后在「输入兑换码」中手动兑换',
'modal.order.done': '完成',
'modal.order.createFail': '下单失败,请稍后重试',
'modal.order.payFail': '支付确认失败,请稍后重试',
'modal.order.methodLabel.wechat': '微信',
'modal.order.methodLabel.alipay': '支付宝',
/* ── AgencyModal ── */
'agency.aria': '代理合作',
'agency.title': '代理合作',
'agency.plan.basic.name': '初级代理',
'agency.plan.basic.count': '200 次',
'agency.plan.standard.name': '标准代理',
'agency.plan.standard.count': '500 次',
'agency.plan.core.name': '核心代理',
'agency.plan.core.count': '1000 次',
/* ── EditToolbar ── */
'edit.aria': '编辑工具',
'edit.undo': '撤销',
'edit.undo.title': '撤销上一步',
'edit.redo': '重做',
'edit.redo.title': '重做下一步',
'edit.rotate': '旋转90°',
'edit.rotate.title': '顺时针旋转 90°',
'edit.mirrorV': '左右镜像',
'edit.mirrorV.title': '左右镜像(左右对调)',
'edit.mirrorH': '上下镜像',
'edit.mirrorH.title': '上下镜像(上下对调)',
'edit.flip': '对角翻转',
'edit.flip.title': '对角翻转(主对角线对称,可做对称图纸)',
/* ── Footer ── */
'footer.slogan': 'PERLER LAB · 让每一颗颜色都有位置',
'footer.note': '图纸仅供个人手作参考',
/* ── App(首页外壳 / 下载 / 错误兜底) ── */
'app.title': 'PERLER LAB · 拼豆图纸生成器',
'app.mobileCta': '购买 / 兑换 →',
'app.uploadFail': '图片读取失败,请换一张重试',
'app.downloadFail': '下载失败,请稍后重试',
'app.downloadBaseName': '拼豆图纸',
'app.downloadSuffix': '拼豆图纸',
/* ── ShareButton(T-067 分享) ── */
'share.button': '分享',
'share.title': '拼豆图纸分享',
'share.text': '看看这张拼豆图纸!',
'share.copied': '分享链接已复制',
'share.failed': '分享失败,请稍后重试',
/* ── ChibiPage(AI 拼豆专区) ── */
'chibi.nav.back': '← 普通拼豆',
'chibi.nav.badge': '每次生成消耗 1 次权益',
'chibi.hero.title.prefix': '先选大类,再定细节,',
'chibi.hero.title.accent': '生成结果先保存。',
'chibi.hero.sub':
'每次 AI 成功生成扣 1 次;该作品转成正式拼豆图纸并首次下载免费。只有重新生成新作品才再次扣费。',
'chibi.card.aria': '拼豆生成设置',
'chibi.step.category': '选择拼豆大类',
'chibi.tabs.aria': '拼豆大类',
'chibi.compare.original': '原图',
'chibi.compare.result': '像素拼豆效果',
'chibi.subtype.title': '细分选择 · 同一种类下不同画风',
'chibi.step.grid': '图纸格数',
'chibi.step.colors': '最大颜色数',
'chibi.step.colors.note': '颜色越多还原度越高',
'chibi.step.composition': '主体构图',
'chibi.step.tags': '细节提示词',
'chibi.tags.max': '最多选 {max} 项',
'chibi.tags.selected': '已选 {selected}/{max}',
'chibi.recommend': '推荐',
'chibi.grid.simple': '简单',
'chibi.grid.recommended': '推荐',
'chibi.grid.fine': '精细',
'chibi.grid.hd': '高清',
'chibi.colors.save': '省豆',
'chibi.colors.balanced': '均衡',
'chibi.colors.fine': '细腻',
'chibi.colors.high': '高还原',
'chibi.composition.closeup': '主体特写',
'chibi.composition.half': '半幅构图',
'chibi.composition.full': '完整构图',
'chibi.prompt.label': '补充描述(选填)',
'chibi.prompt.placeholder': '想保留的细节、不想要的元素…',
'chibi.reference.label': '上传风格示例图(可选)',
'chibi.reference.title': '上传风格示例图',
'chibi.reference.hint': '不会照搬示例主体',
'chibi.confirm.aria': '生成前确认',
'chibi.confirm.title': '生成前确认',
'chibi.sample': '示例',
'chibi.sample.desc': '默认像素效果',
'chibi.spec.category': '类别',
'chibi.spec.subtype': '细分',
'chibi.spec.grid': '图纸',
'chibi.spec.beads': '预计颗数',
'chibi.spec.beads.value': '约 {count} 颗',
'chibi.upload.original.title': '上传需要转换的原图',
'chibi.upload.original.hint': '主体清楚、光线自然效果更好 · 不超过 12MB',
'chibi.payNote.title': 'AI 生成属于付费功能。',
'chibi.payNote.body': '成功生成扣 1 次;本作品转图纸和首次下载免费,失败不扣。',
'chibi.cta.generating': 'AI 生成中…',
'chibi.cta.generate': '生成 →',
'chibi.cta.redeemFirst': '兑换后生成 →',
'chibi.codeLink': '输入兑换码',
'chibi.result.aria': '生成结果',
'chibi.result.title': '生成结果',
'chibi.result.alt': 'AI 拼豆生成结果',
'chibi.result.withGrant': '图纸已生成 · 首次下载免费(下载凭据已保存)',
'chibi.result.plain': '图纸已生成',
'chibi.promise.aria': '服务承诺',
'chibi.promise.classify': '分类更准确',
'chibi.promise.classify.desc': '不同主体使用不同提示词,风景、宠物和食物不再套用人物规则。',
'chibi.promise.pay': '生成按次计费',
'chibi.promise.pay.desc': '每次成功生成扣 1 次权益,失败不扣,避免无限消耗模型费用。',
'chibi.promise.safe': '结果防丢失',
'chibi.promise.safe.desc': '未保存时锁住所有切换操作,并在关闭页面前再次提醒。',
'chibi.footer': 'PERLER LAB · AI 拼豆专区',
'chibi.footer.back': '返回图片转拼豆 →',
'chibi.modal.aria': '输入兑换码',
'chibi.modal.title': '输入兑换码',
'chibi.modal.placeholder': '请输入兑换码',
'chibi.modal.empty': '请输入兑换码',
'chibi.modal.fail': '兑换失败,请稍后重试',
'chibi.modal.processing': '兑换中…',
'chibi.modal.submit': '兑换',
'chibi.upload.tooBig': '图片不能超过 12MB',
'chibi.upload.readFail': '图片读取失败,请换一张重试',
'chibi.upload.ready': '已就绪',
'chibi.upload.reset': '重置',
'chibi.error.noImage': '请先上传需要转换的原图',
'chibi.error.generateFail': '生成失败,请稍后重试',
'chibi.tags.hint': '最多选 {max} 项',
/* ── ChibiPage 数据:五大类 ── */
'chibi.cat.landscape.name': '风景',
'chibi.cat.landscape.note': '山川、城市和旅行纪念',
'chibi.cat.landscape.nature': '自然山川',
'chibi.cat.landscape.nature.note': '',
'chibi.cat.landscape.city': '城市夜景',
'chibi.cat.landscape.city.note': '',
'chibi.cat.landscape.landmark': '地标建筑',
'chibi.cat.landscape.landmark.note': '',
'chibi.cat.people.name': '人物',
'chibi.cat.people.note': '五官、发型和穿搭清楚',
'chibi.cat.people.bigeye': '萌系大眼',
'chibi.cat.people.bigeye.note': '大眼、圆脸、粗轮廓',
'chibi.cat.people.youth': '清爽少年',
'chibi.cat.people.youth.note': '自然五官、利落穿搭',
'chibi.cat.people.retro': '复古像素',
'chibi.cat.people.retro.note': '怀旧配色、游戏感',
'chibi.cat.pet.name': '宠物',
'chibi.cat.pet.note': '毛色、表情和品种特征',
'chibi.cat.pet.cat': '猫咪头像',
'chibi.cat.pet.cat.note': '圆润脸型与花纹',
'chibi.cat.pet.dog': '狗狗全身',
'chibi.cat.pet.dog.note': '耳朵、四肢和毛色',
'chibi.cat.pet.duo': '双宠互动',
'chibi.cat.pet.duo.note': '两只宠物同框',
'chibi.cat.item.name': '物品',
'chibi.cat.item.note': '手办、礼物和纪念物',
'chibi.cat.item.toy': '手办玩具',
'chibi.cat.item.toy.note': '造型轮廓优先',
'chibi.cat.item.daily': '生活用品',
'chibi.cat.item.daily.note': '保留结构与材质',
'chibi.cat.item.gift': '礼物纪念',
'chibi.cat.item.gift.note': '突出包装和装饰',
'chibi.cat.food.name': '食物',
'chibi.cat.food.note': '甜品、饮品和特色美食',
'chibi.cat.food.dessert': '甜品蛋糕',
'chibi.cat.food.dessert.note': '奶油与装饰清晰',
'chibi.cat.food.drink': '咖啡饮品',
'chibi.cat.food.drink.note': '杯型、分层和配料',
'chibi.cat.food.meal': '家常美食',
'chibi.cat.food.meal.note': '主食材清晰可辨',
/* ── ChibiPage 数据:提示词标签 ── */
'chibi.tag.buildings': '突出主体建筑',
'chibi.tag.texture': '减少零碎纹理',
'chibi.tag.light': '保留光影氛围',
'chibi.tag.border': '纯色边框',
'chibi.tag.contrast': '高对比轮廓',
'chibi.tag.clouds': '云端与远山',
'chibi.tag.face': '五官更清晰',
'chibi.tag.clothes': '保留衣服细节',
'chibi.tag.hair': '保留发型',
'chibi.tag.accessory': '保留配饰',
'chibi.tag.pet': '包含宠物',
'chibi.tag.bg': '纯色背景',
'chibi.tag.eyes': '眼睛更有神',
'chibi.tag.fur': '保留毛色花纹',
'chibi.tag.ears': '突出耳朵轮廓',
'chibi.tag.collar': '保留项圈配饰',
'chibi.tag.limbs': '完整四肢',
'chibi.tag.shape': '保留品牌外形',
'chibi.tag.structure': '突出结构轮廓',
'chibi.tag.gloss': '减少反光渐变',
'chibi.tag.details': '保留小配件',
'chibi.tag.center': '居中构图',
'chibi.tag.foodMain': '突出食物主体',
'chibi.tag.layers': '保留食材层次',
'chibi.tag.decor': '减少细碎装饰',
'chibi.tag.saturation': '增强色彩对比',
'chibi.tag.topdown': '俯拍构图',
} as const;
export type Messages = { [K in keyof typeof zhCN]: string };
export type MessageKey = keyof Messages;
@@ -0,0 +1,210 @@
/**
* 分享码编解码测试(T-067)。
*
* 覆盖:编解码往返精确一致(含空格子/多色/长游程/128×128);确定性
* (相同输入 → 相同分享码);非法输入 → null;URL 构造。
*/
import { describe, expect, it } from 'vitest';
import { buildShareUrl, decodePattern, encodePattern } from '../share-codec.js';
import type { GridCell } from '../grid-edit.js';
/** 用字符矩阵构造格子:map 中每个字符对应一种颜色(undefined 字符 = 空格子)。 */
function buildGrid(rows: string[], colors: Record<string, [number, number, number]>, codes: Record<string, string>): GridCell[] {
const grid: GridCell[] = [];
for (const row of rows) {
for (const ch of row) {
const rgb = colors[ch];
if (rgb === undefined) {
grid.push({ rgb: [255, 255, 255] });
} else {
grid.push({ rgb, code: codes[ch] });
}
}
}
return grid;
}
/** 32×32 全同色格子(1024 个 → 强制触发 256 长度的游程分片)。 */
function uniformGrid(size: number, rgb: [number, number, number], code: string): GridCell[] {
return Array.from({ length: size * size }, () => ({ rgb, code }));
}
/** 测试辅助:构造任意字节流对应的 base64url(用于构造非法输入)。 */
function toB64Url(bytes: number[]): string {
return btoa(String.fromCharCode(...bytes))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
}
describe('share-codec 编解码往返', () => {
it('往返后格子与原始完全一致(多色 + 空格子 + 品牌色号)', () => {
const rows = [
'R..R',
'GGRR',
'BBGG',
'.BB.',
];
const grid = buildGrid(rows, {
R: [255, 0, 0],
G: [0, 255, 0],
B: [0, 0, 255],
}, {
R: 'A01',
G: 'B02',
B: 'C03',
});
const code = encodePattern(grid, 4);
const decoded = decodePattern(code);
expect(decoded).not.toBeNull();
expect(decoded!.size).toBe(4);
expect(decoded!.grid).toHaveLength(16);
for (let i = 0; i < 16; i++) {
expect(decoded!.grid[i]!.rgb).toEqual(grid[i]!.rgb);
expect(decoded!.grid[i]!.code ?? null).toBe(grid[i]!.code ?? null);
}
});
it('确定性:相同输入两次编码结果完全相同', () => {
const grid = buildGrid(['RGB', 'GBR', 'BRG'], {
R: [255, 0, 0],
G: [0, 255, 0],
B: [0, 0, 255],
}, { R: 'A01', G: 'A02', B: 'A03' });
expect(encodePattern(grid, 3)).toBe(encodePattern(grid, 3));
});
it('长游程:32×32 全同色(1024 格)往返一致且编码紧凑', () => {
const grid = uniformGrid(32, [250, 250, 250], 'A01');
const code = encodePattern(grid, 32);
// 游程上限 256 → 1024 格 = 4 段游程 + 1 色调色板:字节数应远小于逐格存储
expect(code.length).toBeLessThan(64);
const decoded = decodePattern(code);
expect(decoded).not.toBeNull();
expect(decoded!.grid).toHaveLength(1024);
for (const cell of decoded!.grid) {
expect(cell.rgb).toEqual([250, 250, 250]);
expect(cell.code).toBe('A01');
}
});
it('128×128 大图纸(棋盘格交错)往返一致', () => {
const grid: GridCell[] = [];
for (let y = 0; y < 128; y++) {
for (let x = 0; x < 128; x++) {
const on = (x + y) % 2 === 0;
// 空格子不带 code(与解码输出形态一致)
grid.push(on ? { rgb: [10, 20, 30], code: 'A01' } : { rgb: [240, 240, 240] });
}
}
const decoded = decodePattern(encodePattern(grid, 128));
expect(decoded).not.toBeNull();
expect(decoded!.grid).toEqual(grid);
expect(decoded!.size).toBe(128);
});
it('1×1 单格图纸往返一致', () => {
const grid: GridCell[] = [{ rgb: [5, 6, 7], code: 'X1' }];
const decoded = decodePattern(encodePattern(grid, 1));
expect(decoded).not.toBeNull();
expect(decoded!.grid).toEqual(grid);
expect(decoded!.size).toBe(1);
});
it('含非 ASCII 色号文本的图纸可往返(UTF-8 编解码)', () => {
const grid: GridCell[] = [
{ rgb: [1, 2, 3], code: '漫漫-1' },
{ rgb: [1, 2, 3], code: '漫漫-1' },
{ rgb: [4, 5, 6], code: '咪小窝-2' },
{ rgb: [1, 2, 3], code: '漫漫-1' },
];
const decoded = decodePattern(encodePattern(grid, 2));
expect(decoded).not.toBeNull();
expect(decoded!.grid).toEqual(grid);
});
});
describe('encodePattern 非法输入抛错', () => {
it('格子数量与尺寸不符时抛错', () => {
expect(() => encodePattern([{ rgb: [0, 0, 0] }], 4)).toThrow();
});
it('尺寸越界(0 / 256)时抛错', () => {
expect(() => encodePattern([], 0)).toThrow();
expect(() => encodePattern(uniformGrid(256, [0, 0, 0], 'A'), 256)).toThrow();
});
it('RGB 非 0..255 整数时抛错', () => {
expect(() => encodePattern([{ rgb: [300, 0, 0] }, { rgb: [0, 0, 0] }], 2)).toThrow();
expect(() => encodePattern([{ rgb: [1.5, 0, 0] }, { rgb: [0, 0, 0] }], 2)).toThrow();
});
});
describe('decodePattern 非法输入返回 null', () => {
it('非字符串 / 空串 / 魔数不符返回 null', () => {
expect(decodePattern('')).toBeNull();
expect(decodePattern('PL9abc')).toBeNull();
expect(decodePattern('XYZ123')).toBeNull();
expect(decodePattern('随便什么文本')).toBeNull();
});
it('base64 字符非法返回 null', () => {
expect(decodePattern('PL1!!!')).toBeNull();
expect(decodePattern('PL1AAAA*')).toBeNull();
});
it('字节流被截断(合法前缀 + 半截数据)返回 null', () => {
const code = encodePattern(uniformGrid(8, [9, 9, 9], 'A01'), 8);
expect(decodePattern(code.slice(0, code.length - 3))).toBeNull();
});
it('base64 位数非法(模 4 余 1)返回 null', () => {
expect(decodePattern('PL1A')).toBeNull();
expect(decodePattern('PL1AB')).toBeNull();
expect(decodePattern('PL1ABC')).toBeNull();
});
it('调色板为空 / 游程下标越界 / 末尾多余字节返回 null', () => {
// 调色板数 = 0:magic(3) + size(1) + count(1) = 5 字节
const emptyPalette = 'PL1' + toB64Url([1, 0]);
expect(decodePattern(emptyPalette)).toBeNull();
// 游程指向不存在的调色板下标(count=1,下标 1 越界)
const badIndex = 'PL1' + toB64Url([2, 1, 255, 0, 0, 0, 0, 0, 1, 0]);
expect(decodePattern(badIndex)).toBeNull();
// 游程已铺满 2×2 格子后仍有剩余字节
const trailing = 'PL1' + toB64Url([2, 1, 255, 0, 0, 0, 0, 0, 3, 0, 1]);
expect(decodePattern(trailing)).toBeNull();
});
});
describe('buildShareUrl', () => {
it('拼接 origin、share 与 brand 查询参数', () => {
const url = buildShareUrl('PL1abc-123', 'COCO');
expect(url).toBe('http://localhost/?share=PL1abc-123&brand=COCO');
});
it('含特殊字符的分享码/品牌名被 URL 编码', () => {
const url = buildShareUrl('PL1a+b/c==', '漫漫 1');
expect(url).toContain('share=');
expect(url).toContain('brand=');
// 编解码后的 URL 应可被 URLSearchParams 正确解析
const parsed = new URL(url).searchParams;
expect(parsed.get('share')).toBe('PL1a+b/c==');
expect(parsed.get('brand')).toBe('漫漫 1');
});
it('整条链路:编码 → URL → 解析 → 解码还原图纸', () => {
const grid = buildGrid(['AB', 'BA'], {
A: [200, 100, 50],
B: [50, 100, 200],
}, { A: 'E01', B: 'E02' });
const url = buildShareUrl(encodePattern(grid, 2), 'COCO');
const params = new URLSearchParams(url.split('?')[1]);
const decoded = decodePattern(params.get('share')!);
expect(decoded).not.toBeNull();
expect(decoded!.grid).toEqual(grid);
expect(decoded!.size).toBe(2);
});
});
+242
View File
@@ -0,0 +1,242 @@
/**
* 分享码编解码(T-067 图案分享)。
*
* 把拼豆图纸压缩为紧凑、确定性的分享码 —— 字节流做 RLE(游程编码)+ URL
* 安全的 base64url(无 padding),可直接放进 ?share= 查询参数:
*
* 字节布局:
* [0..2] 魔数 "PL1"
* [3] size(图纸边长,1..255)
* [4] paletteCount(调色板颜色数,1..255)
* [5..] palette 条目 × paletteCount,按首次出现顺序:
* 3 字节 rgb + 1 字节 code 长度 + code UTF-8 字节
* [..] 行优先 RLE 游程:每段 2 字节 [runLen-1][paletteIndex]
*
* 确定性:相同输入永远产出相同的分享码;解码对任何非法输入返回 null。
* 编码时校验尺寸/格子数/RGB 范围,非法输入抛错(由 UI 捕获后提示)。
*/
import type { GridCell, Rgb } from './grid-edit.js';
export interface ShareCell {
rgb: Rgb;
code?: string;
}
export interface DecodedPattern {
grid: GridCell[];
size: number;
}
const MAGIC = 'PL1';
const MAX_SIZE = 255;
const MAX_COLORS = 256;
const B64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
/** Uint8Array → base64url(无 padding)。 */
function toBase64Url(bytes: Uint8Array): string {
let out = '';
for (let i = 0; i < bytes.length; i += 3) {
const rem = Math.min(3, bytes.length - i);
const b0 = bytes[i]!;
const b1 = i + 1 < bytes.length ? bytes[i + 1]! : 0;
const b2 = i + 2 < bytes.length ? bytes[i + 2]! : 0;
out += B64_ALPHABET[(b0 >> 2) & 0x3f]!;
out += B64_ALPHABET[((b0 & 0x03) << 4) | ((b1 >> 4) & 0x0f)]!;
if (rem >= 2) {
out += B64_ALPHABET[((b1 & 0x0f) << 2) | ((b2 >> 6) & 0x03)]!;
}
if (rem >= 3) {
out += B64_ALPHABET[b2 & 0x3f]!;
}
}
return out;
}
/** base64url → Uint8Array;非法字符/位数返回 null。兼容标准 base64(+/ 与 padding)。 */
function fromBase64Url(s: string): Uint8Array | null {
if (s.length === 0) return new Uint8Array(0);
if (s.length % 4 === 1) return null;
const values: number[] = [];
for (const ch of s) {
if (ch === '=') continue; // 容忍 padding
const c = ch.charCodeAt(0);
let v: number | null = null;
if (c >= 65 && c <= 90) v = c - 65; // A-Z
else if (c >= 97 && c <= 122) v = c - 97 + 26; // a-z
else if (c >= 48 && c <= 57) v = c - 48 + 52; // 0-9
else if (c === 43 || c === 45) v = 62; // '+' / '-'
else if (c === 47 || c === 95) v = 63; // '/' / '_'
if (v === null) return null;
values.push(v);
}
const bytes = new Uint8Array(Math.floor((values.length * 3) / 4));
let acc = 0;
let bits = 0;
let out = 0;
for (const v of values) {
acc = (acc << 6) | v;
bits += 6;
if (bits >= 8) {
bits -= 8;
bytes[out] = (acc >> bits) & 0xff;
out += 1;
}
}
// 尾部不足 8 位的剩余位必须全为 0,否则视为非法输入
if (bits > 0 && (acc & ((1 << bits) - 1)) !== 0) return null;
return bytes;
}
function encodeUtf8(text: string): Uint8Array {
return textEncoder.encode(text);
}
function decodeUtf8(bytes: Uint8Array): string {
return textDecoder.decode(bytes);
}
/**
* 将图纸压缩为分享码。`grid` 为行优先扁平数组(长度必须为 size × size)。
*
* @throws 尺寸、格子数或 RGB 非法时抛错(提示信息为中文)。
*/
export function encodePattern(grid: ShareCell[], size: number): string {
if (!Number.isInteger(size) || size < 1 || size > MAX_SIZE) {
throw new Error(`分享码仅支持 1..${MAX_SIZE} 的图纸边长`);
}
if (grid.length !== size * size) {
throw new Error('图纸格子数量与尺寸不匹配,无法生成分享链接');
}
// 1. 调色板:按首次出现顺序收集 (rgb, code),格子映射为颜色下标
const palette: { rgb: Rgb; code: string }[] = [];
const indexOf = new Map<string, number>();
const indices: number[] = new Array<number>(grid.length);
for (let i = 0; i < grid.length; i++) {
const cell = grid[i]!;
const [r, g, b] = cell.rgb;
if (!Number.isInteger(r) || !Number.isInteger(g) || !Number.isInteger(b) || r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) {
throw new Error('格子 RGB 值非法,无法生成分享链接');
}
const code = cell.code ?? '';
const key = `${r},${g},${b}|${code}`;
let idx = indexOf.get(key);
if (idx === undefined) {
if (palette.length >= MAX_COLORS) {
throw new Error('图纸颜色过多,无法生成分享链接(最多 256 色)');
}
idx = palette.length;
indexOf.set(key, idx);
palette.push({ rgb: [r, g, b], code });
}
indices[i] = idx;
}
// 2. RLE 游程编码(run 1..256,存 run-1)
const runs: number[] = [];
for (let i = 0; i < indices.length; ) {
const idx = indices[i]!;
let run = 1;
while (i + run < indices.length && indices[i + run] === idx && run < 256) {
run += 1;
}
runs.push(run - 1, idx);
i += run;
}
// 3. 组装字节流
const codeBytes = palette.map((p) => encodeUtf8(p.code));
const paletteLen = codeBytes.reduce((n, cb) => n + 4 + cb.length, 0);
const bytes = new Uint8Array(5 + paletteLen + runs.length);
bytes[0] = 80; // 'P'
bytes[1] = 76; // 'L'
bytes[2] = 49; // '1'
bytes[3] = size;
bytes[4] = palette.length;
let pos = 5;
for (let i = 0; i < palette.length; i++) {
const entry = palette[i]!;
bytes[pos] = entry.rgb[0];
bytes[pos + 1] = entry.rgb[1];
bytes[pos + 2] = entry.rgb[2];
bytes[pos + 3] = codeBytes[i]!.length;
pos += 4;
bytes.set(codeBytes[i]!, pos);
pos += codeBytes[i]!.length;
}
for (const v of runs) {
bytes[pos] = v;
pos += 1;
}
return MAGIC + toBase64Url(bytes);
}
/**
* 分享码 → 图纸。非法输入(魔数不符、base64 非法、长度/下标越界、末尾
* 多余字节等)一律返回 null,不抛错。
*/
export function decodePattern(code: string): DecodedPattern | null {
try {
if (typeof code !== 'string' || !code.startsWith(MAGIC)) return null;
const bytes = fromBase64Url(code.slice(MAGIC.length));
if (bytes === null || bytes.length < 5) return null;
const size = bytes[3]!;
if (size < 1 || size > MAX_SIZE) return null;
const paletteCount = bytes[4]!;
if (paletteCount < 1) return null;
let pos = 5;
const palette: { rgb: Rgb; code: string }[] = [];
for (let i = 0; i < paletteCount; i++) {
if (pos + 4 > bytes.length) return null;
const r = bytes[pos]!;
const g = bytes[pos + 1]!;
const b = bytes[pos + 2]!;
const codeLen = bytes[pos + 3]!;
pos += 4;
if (pos + codeLen > bytes.length) return null;
const codeText = decodeUtf8(bytes.subarray(pos, pos + codeLen));
pos += codeLen;
palette.push({ rgb: [r, g, b], code: codeText });
}
const cellCount = size * size;
const grid: GridCell[] = [];
while (grid.length < cellCount) {
if (pos + 2 > bytes.length) return null;
const runLen = bytes[pos]! + 1;
const paletteIndex = bytes[pos + 1]!;
pos += 2;
if (paletteIndex >= paletteCount) return null;
if (grid.length + runLen > cellCount) return null;
const entry = palette[paletteIndex]!;
for (let k = 0; k < runLen; k++) {
const rgb: Rgb = [entry.rgb[0], entry.rgb[1], entry.rgb[2]];
grid.push(entry.code === '' ? { rgb } : { rgb, code: entry.code });
}
}
// 严格校验:游程恰好覆盖全部格子且无多余字节(保证确定性)
if (pos !== bytes.length) return null;
return { grid, size };
} catch {
return null;
}
}
/**
* 构造分享 URL,形如 `${origin}/?share=${code}&brand=${brandId}`。
* 测试环境(Node)下 location 不存在时退化为 http://localhost。
*/
export function buildShareUrl(code: string, brandId: string): string {
const origin =
typeof location !== 'undefined' && location.origin !== '' ? location.origin : 'http://localhost';
const params = new URLSearchParams();
params.set('share', code);
params.set('brand', brandId);
return `${origin}/?${params.toString()}`;
}
+4 -1
View File
@@ -1,6 +1,7 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { I18nProvider } from './i18n';
import './styles.css';
const container = document.getElementById('root');
@@ -10,6 +11,8 @@ if (!container) {
createRoot(container).render(
<StrictMode>
<App />
<I18nProvider>
<App />
</I18nProvider>
</StrictMode>,
);
+108
View File
@@ -258,6 +258,34 @@ a {
gap: var(--space-5);
}
.nav-lang {
display: inline-flex;
align-items: center;
border: 1px solid var(--border);
border-radius: var(--radius-full);
overflow: hidden;
}
.nav-lang-btn {
font-size: var(--text-xs);
line-height: 1;
padding: 5px 10px;
min-height: 0;
color: var(--text-secondary);
background: transparent;
border-radius: 0;
}
.nav-lang-btn:hover {
color: var(--text-primary);
}
.nav-lang-btn--active {
color: var(--text-on-dark);
background: var(--accent);
}
.nav-agency {
font-size: var(--text-md);
color: var(--text-secondary);
@@ -849,6 +877,86 @@ a {
padding: 0 var(--space-4) var(--space-3);
}
/* ---- T-067 分享:操作栏 / 分享按钮 / 分享提示 / 来自分享徽标 ---- */
.preview-actions {
display: flex;
align-items: stretch;
gap: var(--space-2);
padding: var(--space-3) var(--space-4);
border-top: 1px solid var(--border);
}
.preview-actions .download-btn {
flex: 1;
justify-content: center;
}
.share-btn {
min-height: var(--touch-min);
padding: 0 var(--space-4);
border-radius: var(--radius-md);
border: 1px solid var(--border-strong);
background: var(--bg-card);
color: var(--text-secondary);
font-size: var(--text-md);
font-weight: var(--weight-medium);
display: inline-flex;
align-items: center;
justify-content: center;
gap: var(--space-2);
cursor: pointer;
transition: border-color 0.15s ease, color 0.15s ease;
}
.share-btn:hover {
border-color: var(--accent);
color: var(--accent);
}
.share-toast {
position: fixed;
left: 50%;
bottom: 72px;
transform: translateX(-50%);
z-index: 100;
padding: var(--space-2) var(--space-4);
border-radius: var(--radius-md);
background: rgba(24, 24, 24, 0.9);
color: #fff;
font-size: var(--text-sm);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.18);
animation: share-toast-in 0.18s ease;
pointer-events: none;
}
@keyframes share-toast-in {
from {
opacity: 0;
transform: translateX(-50%) translateY(6px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
.shared-banner {
display: flex;
align-items: center;
gap: var(--space-2);
padding: var(--space-2) var(--space-3);
border-bottom: 1px solid var(--border);
background: var(--bg-hover);
font-size: var(--text-sm);
color: var(--text-secondary);
}
.shared-banner::before {
content: '●';
color: var(--accent);
font-size: 10px;
}
/* ---- 02 编辑工具栏(撤销/重做/旋转/镜像/翻转) ---- */
.edit-toolbar {
display: flex;