chore: 项目基线提交 - 拼豆图纸生成器 V1.0 核心代码

- 前端: React+Vite 首页/AI专区, 算法库(MARD色板/量化/背景去除), API对接
- 后端: Express+SQLite, 兑换码/订单/支付/chibi生成, 风控+云端同步
- CI/CD: GitHub Actions + Docker + nginx 配置
- 文档: PRD/DESIGN/LAUNCH/ROADMAP/E2E/竞品对照等 15 份
- 工程: 任务看板(taskboard) + 健康巡检(agent-health) + Git流程(gitflow)
This commit is contained in:
Sisyphus (主代理) committed 2026-08-13 21:40:27 +08:00
commit 02762400fb
174 files changed
+28059

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
# 依赖
node_modules
.pnp
.pnp.js
# 构建产物
dist
build
coverage
# 环境与密钥
.env
.env.*
*.pem
*.key
# 日志
logs
*.log
npm-debug.log*
# 编辑器 / 系统
.vscode
.idea
.DS_Store
Thumbs.db
# 测试临时文件
*.tmp
*.temp
*.tsbuildinfo
+40
View File
@@ -0,0 +1,40 @@
# syntax=docker/dockerfile:1
# =============================================================================
# PERLER LAB — 前端 Dockerfile(多阶段构建)
# 构建阶段:node:20-alpine + Vite 构建 React 应用 → dist/
# 运行阶段:nginx:alpine 提供静态资源服务(SPA 路由回退由 nginx.conf 处理)
# =============================================================================
# ── 第一阶段:构建 ──
FROM node:20-alpine AS build
WORKDIR /app
# 复制依赖清单(有 package-lock.json,使用 npm ci 保证可复现)
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund
# 复制 Vite/TS 配置与 HTML 入口
COPY tsconfig.json vite.config.ts index.html ./
# 复制源码与静态资源(public/ 由 Vite 在构建时合并进 dist/)
COPY src ./src
COPY public ./public
# 构建 React 应用 → dist/(与 package.json 的 build 脚本一致:vite build)
RUN npm run build
# ── 第二阶段:Nginx 运行 ──
FROM nginx:1.27-alpine
# 复制 nginx 配置
COPY nginx.conf /etc/nginx/conf.d/default.conf
# 复制构建产物(dist/ 含 index.html + assets/)到 nginx 根目录
COPY --from=build /app/dist /usr/share/nginx/html
# 健康检查
HEALTHCHECK --interval=30s --timeout=5s --retries=3 --start-period=10s \
CMD wget -qO- http://localhost:80/healthz || exit 1
EXPOSE 80
+14
View File
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="PERLER LAB 拼豆图纸生成器 - 把喜欢的图片,变成一颗颗拼豆。" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<title>PERLER LAB · 拼豆图纸生成器</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+105
View File
@@ -0,0 +1,105 @@
# =============================================================================
# PERLER LAB — Nginx 前端服务配置
# 用途:SPA 路由回退 + 静态资源缓存 + 安全头 + Gzip + API 反向代理
# 部署方式:docker-compose 中作为 frontend 服务,/api 反向代理到 server 服务
# =============================================================================
#
# 兼容性说明:
# - 当前 perler-lab 为 Vite + React 单页应用(vite build → dist/)
# - 若未来迁移到 Next.js,需改为 next build + node server 模式,此配置转为
# 上层 Nginx 反代(参考 DEPLOY.md 的域名 HTTPS 方案)
#
# =============================================================================
upstream backend {
# docker-compose 中 backend 服务名为 server,端口 8788
server server:8788;
}
server {
listen 80 default_server;
server_name _;
# ── 静态文件根目录(Vite 构建产物 dist/ 合并至此,index.html 在根目录) ──
root /usr/share/nginx/html;
index index.html;
# ── Gzip 压缩 ──
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml
application/xml+rss
application/octet-stream
image/svg+xml
image/x-icon;
# ── 安全头 ──
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
# 若需 CSP 可在此加,但拼豆工具需要加载用户上传图片,暂不限制过严
# add_header Content-Security-Policy "default-src 'self'; img-src 'self' data: blob:; ..." always;
# ── 静态资源:强缓存(Vite 产物文件名带内容 hash,可 immutable) ──
location /assets/ {
expires 30d;
add_header Cache-Control "public, immutable, max-age=2592000";
access_log off;
}
# ── Favicon ──
location = /favicon.svg {
expires 7d;
add_header Cache-Control "public, max-age=604800";
access_log off;
}
# ── API 反向代理 → 后端服务 ──
location /api/ {
proxy_pass http://backend;
proxy_http_version 1.1;
# 传递客户端真实信息
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 超时配置(后端可能有较长时间计算,酌情调大)
proxy_read_timeout 120s;
proxy_send_timeout 30s;
# 关闭缓冲,便于 SSE / 大响应
proxy_buffering off;
}
# ── 健康检查端点 ──
location = /healthz {
access_log off;
return 200 "OK";
}
# ── SPA 路由回退 ──
location / {
try_files $uri $uri/ /index.html;
}
# ── 拒绝访问隐藏文件 ──
location ~ /\.(?!well-known) {
deny all;
access_log off;
log_not_found off;
}
}
+2196
View File
File diff suppressed because it is too large. Load diff
+38
View File
@@ -0,0 +1,38 @@
{
"name": "perler-lab",
"version": "0.1.0",
"description": "PERLER LAB - 拼豆图纸生成器 core algorithm library (image to bead pattern)",
"type": "module",
"main": "src/lib/index.ts",
"types": "src/lib/index.ts",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "tsc --noEmit"
},
"keywords": [
"perler",
"beads",
"hama",
"mard",
"image-processing",
"kmeans",
"lab-color"
],
"license": "MIT",
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/react": "^18.3.31",
"@types/react-dom": "^18.3.7",
"@vitejs/plugin-react": "^4.7.0",
"typescript": "^5.9.3",
"vite": "^5.4.21",
"vitest": "^2.1.8"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 283 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 339 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 531 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 368 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 381 KiB

File diff suppressed because it is too large. Load diff
+96
View File
@@ -0,0 +1,96 @@
{
"version": "1.0",
"description": "PERLER LAB 素材资源清单 - 资产清单供前端团队使用",
"generated": "2026-08-13",
"assets": {
"chibi-comparisons": {
"description": "竞品 Chibi 风格对比素材(用户原图 vs 像素生成效果)",
"path": "/assets/chibi-comparisons/",
"files": [
{
"filename": "food-original.png",
"size": 98175,
"category": "food",
"type": "original",
"purpose": "用户原图对比"
},
{
"filename": "food-pixel.jpg",
"size": 289310,
"category": "food",
"type": "pixel",
"purpose": "生成效果展示"
},
{
"filename": "landscape-original.png",
"size": 347166,
"category": "landscape",
"type": "original",
"purpose": "用户原图对比"
},
{
"filename": "landscape-pixel.jpg",
"size": 543517,
"category": "landscape",
"type": "pixel",
"purpose": "生成效果展示"
},
{
"filename": "object-original.png",
"size": 234655,
"category": "object",
"type": "original",
"purpose": "用户原图对比"
},
{
"filename": "object-pixel.jpg",
"size": 173824,
"category": "object",
"type": "pixel",
"purpose": "生成效果展示"
},
{
"filename": "person-original.png",
"size": 156221,
"category": "person",
"type": "original",
"purpose": "用户原图对比"
},
{
"filename": "person-pixel.jpg",
"size": 377097,
"category": "person",
"type": "pixel",
"purpose": "生成效果展示"
},
{
"filename": "pet-original.png",
"size": 183125,
"category": "pet",
"type": "original",
"purpose": "用户原图对比"
},
{
"filename": "pet-pixel.jpg",
"size": 390438,
"category": "pet",
"type": "pixel",
"purpose": "生成效果展示"
}
]
},
"favicon": {
"description": "网站图标",
"path": "/favicon.svg",
"filename": "favicon.svg",
"size": 712
},
"demo-pattern": {
"description": "内置演示图案数据集 - 像素猫咪",
"path": "/assets/demo-cat.json",
"filename": "demo-cat.json",
"size": 5903,
"purpose": "首页默认预览图案"
}
}
}
+6
View File
@@ -0,0 +1,6 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M22 19.2727C22 20.779 20.779 22 19.2727 22H14.7273C13.221 22 12 20.779 12 19.2727V12H19.2727C20.779 12 22 13.221 22 14.7273V19.2727Z" fill="#68C4FF"/>
<path d="M20 2C21.1046 2 22 2.89543 22 4V7C22 8.10457 21.1046 9 20 9H17C15.8954 9 15 8.10457 15 7V4C15 2.89543 15.8954 2 17 2H20Z" fill="#0C79D8"/>
<path d="M7 15C8.10457 15 9 15.8954 9 17V20C9 21.1046 8.10457 22 7 22H4C2.89543 22 2 21.1046 2 20V17C2 15.8954 2.89543 15 4 15H7Z" fill="#0C79D8"/>
<path d="M12 12H4.72727C3.22104 12 2 10.779 2 9.27273V4.72727C2 3.22104 3.22104 2 4.72727 2H9.27273C10.779 2 12 3.22104 12 4.72727V12Z" fill="#2E9EFF"/>
</svg>

After

Width:  |  Height:  |  Size: 712 B

+214
View File
@@ -0,0 +1,214 @@
import { useCallback, useEffect, useState } from 'react';
import ChibiPage from './ChibiPage';
import Nav from './components/Nav';
import Hero from './components/Hero';
import PassSection, { type Plan } from './components/PassSection';
import Footer from './components/Footer';
import ControlsPanel from './components/ControlsPanel';
import PreviewPanel from './components/PreviewPanel';
import InventoryPanel from './components/InventoryPanel';
import RedeemModal from './components/RedeemModal';
import AgencyModal from './components/AgencyModal';
import OrderModal from './components/OrderModal';
import {
loadImageFromFile,
usePattern,
type PatternSettings,
type SourceImage,
} from './lib/usePattern';
import { buildExportCanvas, downloadCanvas } from './lib/drawPattern';
import { consumeCode, redeemCode } from './lib/api';
const DEFAULT_SETTINGS: PatternSettings = {
gridSize: 32,
maxColors: 24,
removeBg: false,
showGrid: true,
};
const DEFAULT_PLAN: Plan = {
key: 'standard',
name: '常用包',
price: '12.9',
count: '10 次',
desc: '适合个人多次创作(推荐)',
featured: true,
};
type ModalState =
| { kind: 'redeem' }
| { kind: 'agency' }
| { kind: 'order'; plan: Plan }
| null;
/** Homepage: NAV → HERO → DOWNLOAD PASS → 工作区三栏 → FOOTER. */
function HomePage() {
const [source, setSource] = useState<SourceImage | null>(null);
const [settings, setSettings] = useState<PatternSettings>(DEFAULT_SETTINGS);
const [runId, setRunId] = useState(0);
const [redeemedCode, setRedeemedCode] = useState<string | null>(null);
const [downloadError, setDownloadError] = useState<string | null>(null);
const [uploadError, setUploadError] = useState<string | null>(null);
const [modal, setModal] = useState<ModalState>(null);
const redeemed = redeemedCode !== null;
const { result, processing, error } = usePattern(source, settings, runId);
// Revoke object URLs when the source is replaced.
useEffect(() => {
return () => {
if (source) URL.revokeObjectURL(source.url);
};
}, [source]);
const handleFileSelected = useCallback((file: File) => {
void loadImageFromFile(file).then(
(next) => {
setSource((prev) => {
if (prev) URL.revokeObjectURL(prev.url);
return next;
});
setUploadError(null);
},
(err: unknown) => {
setUploadError(err instanceof Error ? err.message : '图片读取失败,请换一张重试');
},
);
}, []);
const handleReset = useCallback(() => {
setSource((prev) => {
if (prev) URL.revokeObjectURL(prev.url);
return null;
});
setUploadError(null);
setRunId((n) => n + 1);
}, []);
const handleRegenerate = useCallback(() => {
setRunId((n) => n + 1);
}, []);
const handleDownload = useCallback(async () => {
if (!result || !source || !redeemedCode) return;
const baseName = source.name.replace(/\.[^.]+$/, '') || '拼豆图纸';
try {
// 下载消耗 1 次权益(首次免费),成功后再触发本地图纸导出
await consumeCode({
code: redeemedCode,
fileName: `${baseName}.png`,
downloadGrant: '',
});
setDownloadError(null);
const canvas = buildExportCanvas(result, settings.gridSize, baseName);
downloadCanvas(
canvas,
`${baseName}-${settings.gridSize}x${settings.gridSize}-MARD拼豆图纸.png`,
);
} catch (err) {
setDownloadError(err instanceof Error ? err.message : '下载失败,请稍后重试');
}
}, [result, source, settings.gridSize, redeemedCode]);
const beadCount = result?.totalBeads ?? 0;
const colorCount = result?.palette.length ?? 0;
const orderPlan = modal?.kind === 'order' ? modal.plan : null;
return (
<div className="page" id="top">
<Nav onAgencyClick={() => setModal({ kind: 'agency' })} />
<main className="page-main">
<Hero beadCount={beadCount} colorCount={colorCount} />
<PassSection onPlanClick={(plan) => setModal({ kind: 'order', plan })} />
<div className="workspace" id="workspace">
<ControlsPanel
source={source}
settings={settings}
processing={processing}
uploadError={uploadError}
onChangeSettings={(patch) => setSettings((s) => ({ ...s, ...patch }))}
onFileSelected={handleFileSelected}
onReset={handleReset}
onRegenerate={handleRegenerate}
/>
<PreviewPanel
source={source}
settings={settings}
result={result}
processing={processing}
error={error}
redeemed={redeemed}
downloadError={downloadError}
onDownload={handleDownload}
/>
<InventoryPanel
result={result}
redeemed={redeemed}
onRedeemClick={() => setModal({ kind: 'redeem' })}
/>
</div>
</main>
<Footer />
{/* 移动端底部固定 CTA */}
<div className="mobile-cta">
<button
type="button"
className="mobile-cta-btn"
onClick={() => setModal({ kind: 'order', plan: DEFAULT_PLAN })}
>
购买 / 兑换 →
</button>
</div>
{modal?.kind === 'redeem' && (
<RedeemModal
onClose={() => setModal(null)}
onRedeem={async (code) => {
await redeemCode(code);
setRedeemedCode(code);
setModal(null);
}}
/>
)}
{modal?.kind === 'agency' && <AgencyModal onClose={() => setModal(null)} />}
{orderPlan && (
<OrderModal
plan={orderPlan}
onClose={() => setModal(null)}
onRedeemed={(code) => {
setRedeemedCode(code);
setModal(null);
}}
/>
)}
</div>
);
}
/**
* Root component:
* - `/chibi` → AI 拼豆专区
* - 其他路径 → 首页(图片转拼豆)
*/
export default function App() {
const [path, setPath] = useState<string>(() => window.location.pathname);
useEffect(() => {
const onPop = () => setPath(window.location.pathname);
window.addEventListener('popstate', onPop);
return () => window.removeEventListener('popstate', onPop);
}, []);
if (path === '/chibi' || path.startsWith('/chibi/')) {
return <ChibiPage />;
}
return <HomePage />;
}
File diff suppressed because it is too large. Load diff
+839
View File
@@ -0,0 +1,839 @@
import { useEffect, useRef, useState } from "react";
import "./ChibiPage.css";
import { generateChibi, redeemCode } from "./lib/api";
/* ══════════════════════════════════════════════════════════════════════════
* PERLER LAB — AI 拼豆专区 (/chibi)
* DESIGN.md §4 · 文案: competitor-analysis/copy-library.md §8
* 独立页面组件:无路由环境下亦可直接挂载(named export)。
* ══════════════════════════════════════════════════════════════════════════ */
const MAX_TAGS = 5;
const MAX_PROMPT_LENGTH = 160;
const MAX_UPLOAD_BYTES = 12 * 1024 * 1024; // 12MB
/* ── 数据:五大类 + 细分 + 提示词标签 (copy-library.md §8.2) ── */
interface Subtype {
name: string;
note: string;
}
interface Category {
id: string;
name: string;
note: string;
subtypes: Subtype[];
tags: string[];
}
const CATEGORIES: Category[] = [
{
id: "landscape",
name: "风景",
note: "山川、城市和旅行纪念",
subtypes: [
{ name: "自然山川", note: "" },
{ name: "城市夜景", note: "" },
{ name: "地标建筑", note: "" },
],
tags: ["突出主体建筑", "减少零碎纹理", "保留光影氛围", "纯色边框", "高对比轮廓", "云端与远山"],
},
{
id: "people",
name: "人物",
note: "五官、发型和穿搭清楚",
subtypes: [
{ name: "萌系大眼", note: "大眼、圆脸、粗轮廓" },
{ name: "清爽少年", note: "自然五官、利落穿搭" },
{ name: "复古像素", note: "怀旧配色、游戏感" },
],
tags: ["五官更清晰", "保留衣服细节", "保留发型", "保留配饰", "包含宠物", "纯色背景"],
},
{
id: "pet",
name: "宠物",
note: "毛色、表情和品种特征",
subtypes: [
{ name: "猫咪头像", note: "圆润脸型与花纹" },
{ name: "狗狗全身", note: "耳朵、四肢和毛色" },
{ name: "双宠互动", note: "两只宠物同框" },
],
tags: ["眼睛更有神", "保留毛色花纹", "突出耳朵轮廓", "保留项圈配饰", "完整四肢", "纯色背景"],
},
{
id: "item",
name: "物品",
note: "手办、礼物和纪念物",
subtypes: [
{ name: "手办玩具", note: "造型轮廓优先" },
{ name: "生活用品", note: "保留结构与材质" },
{ name: "礼物纪念", note: "突出包装和装饰" },
],
tags: ["保留品牌外形", "突出结构轮廓", "减少反光渐变", "保留小配件", "居中构图", "纯色背景"],
},
{
id: "food",
name: "食物",
note: "甜品、饮品和特色美食",
subtypes: [
{ name: "甜品蛋糕", note: "奶油与装饰清晰" },
{ name: "咖啡饮品", note: "杯型、分层和配料" },
{ name: "家常美食", note: "主食材清晰可辨" },
],
tags: ["突出食物主体", "保留食材层次", "减少细碎装饰", "增强色彩对比", "俯拍构图", "纯色背景"],
},
];
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 },
];
const COLOR_OPTIONS = [
{ value: 16, hint: "省豆", recommended: false },
{ value: 24, hint: "均衡", recommended: false },
{ value: 32, hint: "细腻", recommended: false },
{ value: 40, hint: "高还原", recommended: false },
];
const COMPOSITIONS = [
{ id: "特写", label: "主体特写", density: 0.7 },
{ id: "半幅", label: "半幅构图", density: 0.6 },
{ id: "完整", label: "完整构图", density: 0.48 },
];
const DEFAULT_GRID = 64;
const DEFAULT_COLORS = 24;
const DEFAULT_COMPOSITION = "特写";
/* ── 前端选项 → 服务端枚举映射 (perler-lab-server chibi/prompts.ts) ── */
const CATEGORY_TO_SERVER: Record<string, string> = {
landscape: "landscape",
people: "person",
pet: "pet",
item: "object",
food: "food",
};
const SUBTYPE_TO_KEY: Record<string, string> = {
自然山川: "nature",
城市夜景: "city",
地标建筑: "landmark",
萌系大眼: "big-eye",
清爽少年: "youth",
复古像素: "retro",
猫咪头像: "cat",
狗狗全身: "dog",
双宠互动: "duo",
手办玩具: "toy",
生活用品: "daily",
礼物纪念: "gift",
甜品蛋糕: "dessert",
咖啡饮品: "drink",
家常美食: "meal",
};
const COMPOSITION_TO_SERVER: Record<string, string> = {
特写: "主体特写",
半幅: "半幅构图",
完整: "完整构图",
};
/* ── 像素示例占位(8×8 豆图) ── */
const PIXEL_SAMPLE: string[][] = [
["#f4f3ef", "#edb045", "#f4f3ef", "#f4f3ef", "#f4f3ef", "#f4f3ef", "#edb045", "#f4f3ef"],
["#f4f3ef", "#edb045", "#f4f3ef", "#f4f3ef", "#f4f3ef", "#f4f3ef", "#edb045", "#f4f3ef"],
["#edb045", "#edb045", "#edb045", "#edb045", "#edb045", "#edb045", "#edb045", "#edb045"],
["#edb045", "#f4f3ef", "#171713", "#f4f3ef", "#f4f3ef", "#171713", "#f4f3ef", "#edb045"],
["#edb045", "#edb045", "#edb045", "#edb045", "#edb045", "#edb045", "#edb045", "#edb045"],
["#edb045", "#f4f3ef", "#f4f3ef", "#d99b2b", "#d99b2b", "#f4f3ef", "#f4f3ef", "#edb045"],
["#edb045", "#f4f3ef", "#171713", "#171713", "#d99b2b", "#171713", "#171713", "#edb045"],
["#edb045", "#edb045", "#edb045", "#edb045", "#edb045", "#edb045", "#edb045", "#edb045"],
];
/* ── 小图标(SVG,无 emoji) ── */
const ICON_CLASSIFY = (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<rect x="3" y="3" width="8" height="8" rx="2" />
<rect x="13" y="3" width="8" height="8" rx="2" />
<rect x="3" y="13" width="8" height="8" rx="2" />
<rect x="13" y="13" width="8" height="8" rx="2" />
</svg>
);
const ICON_COUNT = (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<circle cx="12" cy="12" r="8.5" />
<circle cx="12" cy="12" r="4.5" />
<circle cx="12" cy="12" r="1" fill="currentColor" />
</svg>
);
const ICON_SAFE = (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M12 3l7 3v5c0 4.5-3 8.2-7 10-4-1.8-7-5.5-7-10V6l7-3z" />
<path d="M9 12l2 2 4-4" />
</svg>
);
/* ── 工具 ── */
function formatNumber(n: number): string {
return n.toLocaleString("zh-CN");
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}
/* ── 上传组件(原图 / 参考图 共用,12MB 限制) ── */
interface UploadedImage {
name: string;
url: string;
size: number;
}
interface UploadBoxProps {
title: string;
hint: string;
value: UploadedImage | null;
onChange: (image: UploadedImage | null) => void;
}
function UploadBox({ title, hint, value, onChange }: UploadBoxProps) {
const inputRef = useRef<HTMLInputElement>(null);
const [error, setError] = useState<string | null>(null);
const handleFile = (file: File | undefined): void => {
if (!file) return;
setError(null);
if (file.size > MAX_UPLOAD_BYTES) {
setError("图片不能超过 12MB");
return;
}
const reader = new FileReader();
reader.onload = () => {
if (typeof reader.result === "string") {
onChange({ name: file.name, url: reader.result, size: file.size });
}
};
reader.onerror = () => {
setError("图片读取失败,请换一张重试");
};
reader.readAsDataURL(file);
};
const reset = (): void => {
onChange(null);
setError(null);
if (inputRef.current) inputRef.current.value = "";
};
return (
<div>
{value ? (
<div className="chibi-upload-file">
<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>
<button type="button" className="chibi-upload-reset" onClick={reset}>
重置
</button>
</div>
) : (
<button type="button" className="chibi-upload" onClick={() => inputRef.current?.click()}>
<span className="chibi-upload-icon">+</span>
<span className="chibi-upload-title">{title}</span>
<span className="chibi-upload-hint">{hint}</span>
</button>
)}
<input
ref={inputRef}
type="file"
accept="image/jpeg,image/png,image/webp"
onChange={(e) => {
handleFile(e.target.files?.[0]);
e.target.value = "";
}}
style={{ display: "none" }}
aria-label={title}
/>
{error && <p className="chibi-upload-error">{error}</p>}
</div>
);
}
/* ── 像素豆图(占位示例) ── */
function PixelSample() {
return (
<div className="chibi-pixel" aria-hidden="true">
{PIXEL_SAMPLE.flat().map((color, i) => (
<span key={`${color}-${i}`} style={{ background: color }} />
))}
</div>
);
}
/* ══════════════════════════════════════════════════════════════════════════
* ChibiPage
* ══════════════════════════════════════════════════════════════════════════ */
export function ChibiPage() {
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);
const [maxColors, setMaxColors] = useState<number>(DEFAULT_COLORS);
const [composition, setComposition] = useState<string>(DEFAULT_COMPOSITION);
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const [tagHint, setTagHint] = useState<string | null>(null);
const [promptText, setPromptText] = useState<string>("");
const [referenceImage, setReferenceImage] = useState<UploadedImage | null>(null);
const [originalImage, setOriginalImage] = useState<UploadedImage | null>(null);
// 兑换状态
const [redeemedCode, setRedeemedCode] = useState<string | null>(null);
const [redeemingCode, setRedeemingCode] = useState(false);
const [codeModalOpen, setCodeModalOpen] = useState(false);
const [codeInput, setCodeInput] = useState("");
const [codeError, setCodeError] = useState<string | null>(null);
// 生成状态
const [generating, setGenerating] = useState(false);
const [generatedImage, setGeneratedImage] = useState<string | null>(null);
const [downloadGrant, setDownloadGrant] = useState<string | null>(null);
const [generateError, setGenerateError] = useState<string | null>(null);
const tagHintTimerRef = useRef<number | null>(null);
const hasCode = redeemedCode !== null;
const category = CATEGORIES.find((c) => c.id === categoryId) ?? CATEGORIES[0];
const subtypes = category?.subtypes ?? [];
const tags = category?.tags ?? [];
// 切换大类:细分回到第一个,清空标签(标签池随大类变化)
const selectCategory = (id: string): void => {
if (id === categoryId) return;
setCategoryId(id);
const next = CATEGORIES.find((c) => c.id === id);
setSubtypeName(next?.subtypes[0]?.name ?? "");
setSelectedTags([]);
setTagHint(null);
};
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));
setTagHint(null);
return;
}
if (selectedTags.length >= MAX_TAGS) {
setTagHint(`最多选 ${MAX_TAGS} 项`);
if (tagHintTimerRef.current !== null) window.clearTimeout(tagHintTimerRef.current);
tagHintTimerRef.current = window.setTimeout(() => setTagHint(null), 2000);
return;
}
setSelectedTags([...selectedTags, tag]);
setTagHint(null);
};
// 预计颗数 = 格数² × 构图密度(特写 0.7 / 半幅 0.6 / 完整 0.48)
const density = COMPOSITIONS.find((c) => c.id === composition)?.density ?? 0.7;
const estimatedBeads = Math.round(gridSize * gridSize * density);
// Esc 关闭兑换弹窗
useEffect(() => {
if (!codeModalOpen) return;
const onKey = (e: KeyboardEvent): void => {
if (e.key === "Escape") setCodeModalOpen(false);
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [codeModalOpen]);
// 卸载时清理计时器
useEffect(() => {
return () => {
if (tagHintTimerRef.current !== null) window.clearTimeout(tagHintTimerRef.current);
};
}, []);
const redeem = async (): Promise<void> => {
const code = codeInput.trim();
if (!code) {
setCodeError("请输入兑换码");
return;
}
if (redeemingCode) return;
setRedeemingCode(true);
setCodeError(null);
try {
await redeemCode(code);
setRedeemedCode(code);
setCodeInput("");
setCodeModalOpen(false);
} catch (err) {
setCodeError(err instanceof Error ? err.message : "兑换失败,请稍后重试");
} finally {
setRedeemingCode(false);
}
};
const generate = async (): Promise<void> => {
if (!hasCode || generating || !redeemedCode) return;
if (!originalImage) {
setGenerateError("请先上传需要转换的原图");
return;
}
setGenerating(true);
setGenerateError(null);
try {
const res = await generateChibi({
code: redeemedCode,
image: originalImage.url,
referenceImage: referenceImage?.url,
category: CATEGORY_TO_SERVER[categoryId] ?? categoryId,
subtype: SUBTYPE_TO_KEY[subtypeName] ?? subtypeName,
gridSize,
colorCount: maxColors,
composition: COMPOSITION_TO_SERVER[composition] ?? composition,
detailTags: selectedTags,
customPrompt: promptText.trim() || undefined,
});
setGeneratedImage(res.image);
setDownloadGrant(res.downloadGrant);
} catch (err) {
setGenerateError(err instanceof Error ? err.message : "生成失败,请稍后重试");
} finally {
setGenerating(false);
}
};
const ctaLabel = generating ? "AI 生成中…" : hasCode ? "生成 →" : "兑换后生成 →";
return (
<div className="chibi-page">
{/* ── NAV (chibi 版) ── */}
<nav className="chibi-nav">
<div className="chibi-nav-inner">
<a className="chibi-nav-back" href="/">
← 普通拼豆
</a>
<a className="chibi-brand" href="/chibi">
<span className="chibi-brand-mark">P</span>
<span>
PERLER <b>LAB</b>
</span>
</a>
<span className="chibi-nav-spacer" />
<span className="chibi-nav-badge">
<span className="chibi-nav-badge-dot" />
每次生成消耗 1 次权益
</span>
</div>
</nav>
{/* ── BEAD HERO ── */}
<header className="chibi-hero">
<span className="chibi-eyebrow">IMAGE TO PERLER</span>
<h1 className="chibi-h1">
先选大类,再定细节,<em>生成结果先保存。</em>
</h1>
<p className="chibi-sub">
每次 AI 成功生成扣 1 次;该作品转成正式拼豆图纸并首次下载免费。只有重新生成新作品才再次扣费。
</p>
</header>
{/* ── BEAD BUILDER ── */}
<main className="chibi-main">
<section className="chibi-card" aria-label="拼豆生成设置">
{/* 01 选择拼豆大类 */}
<div className="chibi-section">
<div className="chibi-section-head">
<span className="chibi-section-num">01</span>
<h2 className="chibi-section-title">选择拼豆大类</h2>
</div>
<div className="chibi-tabs" role="tablist" aria-label="拼豆大类">
{CATEGORIES.map((c) => {
const selected = c.id === categoryId;
return (
<button
key={c.id}
type="button"
role="tab"
aria-selected={selected}
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>
</button>
);
})}
</div>
{/* 大类对比图(原图 → 像素拼豆效果) */}
<div className="chibi-compare" aria-hidden="true">
<div className="chibi-compare-box">
<span className="chibi-compare-label">原图</span>
<div className="chibi-compare-source" />
</div>
<span className="chibi-compare-arrow">→</span>
<div className="chibi-compare-box">
<span className="chibi-compare-label">像素拼豆效果</span>
<div className="chibi-compare-pixel">
<PixelSample />
</div>
</div>
</div>
{/* 细分选择 */}
<p className="chibi-subtype-title">细分选择 · 同一种类下不同画风</p>
<div className="chibi-subtypes">
{subtypes.map((s) => {
const selected = s.name === subtypeName;
return (
<button
key={s.name}
type="button"
aria-pressed={selected}
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>
</button>
);
})}
</div>
</div>
{/* 02 图纸格数 */}
<div className="chibi-section">
<div className="chibi-section-head">
<span className="chibi-section-num">02</span>
<h2 className="chibi-section-title">图纸格数</h2>
</div>
<div className="chibi-options">
{GRID_OPTIONS.map((o) => {
const selected = o.value === gridSize;
return (
<button
key={o.value}
type="button"
aria-pressed={selected}
className={`chibi-option${selected ? " is-selected" : ""}`}
onClick={() => setGridSize(o.value)}
>
{o.recommended && <span className="chibi-recommend">推荐</span>}
<span className="chibi-option-value">{o.value}</span>
<span className="chibi-option-hint">{o.hint}</span>
</button>
);
})}
</div>
</div>
{/* 03 最大颜色数 */}
<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>
</div>
<div className="chibi-options">
{COLOR_OPTIONS.map((o) => {
const selected = o.value === maxColors;
return (
<button
key={o.value}
type="button"
aria-pressed={selected}
className={`chibi-option${selected ? " is-selected" : ""}`}
onClick={() => setMaxColors(o.value)}
>
<span className="chibi-option-value">{o.value}</span>
<span className="chibi-option-hint">{o.hint}</span>
</button>
);
})}
</div>
</div>
{/* 04 主体构图 */}
<div className="chibi-section">
<div className="chibi-section-head">
<span className="chibi-section-num">04</span>
<h2 className="chibi-section-title">主体构图</h2>
</div>
<div className="chibi-options is-3col">
{COMPOSITIONS.map((c) => {
const selected = c.id === composition;
return (
<button
key={c.id}
type="button"
aria-pressed={selected}
className={`chibi-option${selected ? " is-selected" : ""}`}
onClick={() => setComposition(c.id)}
>
<span className="chibi-option-value">{c.label}</span>
</button>
);
})}
</div>
</div>
{/* 05 细节提示词 */}
<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>
</div>
<div className="chibi-tags">
{tags.map((tag) => {
const selected = selectedTags.includes(tag);
const disabled = !selected && selectedTags.length >= MAX_TAGS;
return (
<button
key={tag}
type="button"
aria-pressed={selected}
className={`chibi-tag${selected ? " is-selected" : ""}${disabled ? " is-disabled" : ""}`}
onClick={() => toggleTag(tag)}
>
<span className="chibi-tag-marker">{selected ? "✓" : "+"}</span>
{tag}
</button>
);
})}
</div>
{tagHint && <p className="chibi-tag-hint">{tagHint}</p>}
<div className="chibi-detail-row">
<div>
<label className="chibi-field-label" htmlFor="chibi-prompt">
补充描述(选填)
</label>
<textarea
id="chibi-prompt"
className="chibi-textarea"
placeholder="想保留的细节、不想要的元素…"
maxLength={MAX_PROMPT_LENGTH}
value={promptText}
onChange={(e) => setPromptText(e.target.value)}
/>
<div className="chibi-char-counter">
{promptText.length}/{MAX_PROMPT_LENGTH}
</div>
</div>
<div>
<span className="chibi-field-label">参考图上传(选填)</span>
<UploadBox
title="上传参考图"
hint="支持 JPG、PNG、WEBP · 不超过 12MB"
value={referenceImage}
onChange={setReferenceImage}
/>
</div>
</div>
</div>
</section>
{/* ── 生成前确认 ── */}
<section className="chibi-card" aria-label="生成前确认">
<div className="chibi-section-head">
<span className="chibi-section-num">✓</span>
<h2 className="chibi-section-title">生成前确认</h2>
</div>
<div className="chibi-confirm">
<div className="chibi-confirm-left">
<div className="chibi-sample">
<span className="chibi-sample-label">示例</span>
<PixelSample />
</div>
<span className="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>
</div>
<div className="chibi-spec-row">
<span className="chibi-spec-label">细分</span>
<span className="chibi-spec-value">{selectedSubtype?.name ?? ""}</span>
</div>
<div className="chibi-spec-row">
<span className="chibi-spec-label">图纸</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>
</div>
</div>
<div className="chibi-confirm-upload-row">
<div className="chibi-upload-title">上传需要转换的原图</div>
</div>
<UploadBox
title="上传需要转换的原图"
hint="主体清楚、光线自然效果更好 · 不超过 12MB"
value={originalImage}
onChange={setOriginalImage}
/>
<p className="chibi-confirm-note">
<b>AI 生成属于付费功能。</b>成功生成扣 1 次;本作品转图纸和首次下载免费,失败不扣。
</p>
<div className="chibi-confirm-actions">
<button
type="button"
className="chibi-btn chibi-btn-primary"
disabled={!hasCode || generating}
onClick={generate}
>
{generating && <span className="chibi-spinner" />}
{ctaLabel}
</button>
{!hasCode && (
<button type="button" className="chibi-btn-link" onClick={() => setCodeModalOpen(true)}>
输入兑换码
</button>
)}
</div>
{generateError && <p className="chibi-upload-error">{generateError}</p>}
</div>
</div>
</section>
{/* ── 生成结果 ── */}
{generatedImage && (
<section className="chibi-card" aria-label="生成结果">
<div className="chibi-section-head">
<span className="chibi-section-num">✓</span>
<h2 className="chibi-section-title">生成结果</h2>
</div>
<div className="chibi-result">
<img className="chibi-result-img" src={generatedImage} alt="AI 拼豆生成结果" />
<p className="chibi-result-note">
{downloadGrant ? "图纸已生成 · 首次下载免费(下载凭据已保存)" : "图纸已生成"}
</p>
</div>
</section>
)}
{/* ── 三大承诺 ── */}
<section className="chibi-promises" aria-label="服务承诺">
<div className="chibi-promise">
<span className="chibi-promise-icon">{ICON_CLASSIFY}</span>
<h3 className="chibi-promise-title">分类更准确</h3>
<p className="chibi-promise-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>
</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>
</div>
</section>
</main>
{/* ── Footer (AI 专区版) ── */}
<footer className="chibi-footer">
<div className="chibi-footer-inner">
<span className="chibi-footer-text">PERLER LAB · AI 拼豆专区</span>
<a className="chibi-footer-link" href="/">
返回图片转拼豆 →
</a>
</div>
</footer>
{/* ── 移动端底部 CTA 条 ── */}
<div className="chibi-mobile-bar">
<button
type="button"
className="chibi-btn chibi-btn-primary"
disabled={!hasCode || generating}
onClick={generate}
>
{generating && <span className="chibi-spinner" />}
{ctaLabel}
</button>
{!hasCode && (
<button type="button" className="chibi-mobile-code" onClick={() => setCodeModalOpen(true)}>
输入兑换码
</button>
)}
</div>
{/* ── 兑换码弹窗 ── */}
{codeModalOpen && (
<div
className="chibi-modal-mask"
role="presentation"
onMouseDown={(e) => {
if (e.target === e.currentTarget) setCodeModalOpen(false);
}}
>
<div className="chibi-modal" role="dialog" aria-modal="true" aria-label="输入兑换码">
<div className="chibi-modal-head">
<h3 className="chibi-modal-title">输入兑换码</h3>
<button type="button" className="chibi-modal-close" aria-label="关闭" onClick={() => setCodeModalOpen(false)}>
×
</button>
</div>
<input
className="chibi-modal-input"
placeholder="请输入兑换码"
autoFocus
value={codeInput}
onChange={(e) => {
setCodeInput(e.target.value);
setCodeError(null);
}}
onKeyDown={(e) => {
if (e.key === "Enter") void redeem();
}}
/>
{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 ? "兑换中…" : "兑换"}
</button>
</div>
</div>
</div>
)}
</div>
);
}
export default ChibiPage;
+34
View File
@@ -0,0 +1,34 @@
interface AgencyModalProps {
onClose: () => void;
}
const AGENT_PLANS = [
{ name: '初级代理', price: '¥139', count: '200 次' },
{ name: '标准代理', price: '¥299', count: '500 次' },
{ name: '核心代理', price: '¥499', count: '1000 次' },
];
/** 代理合作弹窗 (§7.3): three agent tiers. */
export default function AgencyModal({ onClose }: AgencyModalProps) {
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}>
×
</button>
<h3 className="modal-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 className="pass-card-price">
{plan.price}
<small> / {plan.count}</small>
</div>
</div>
))}
</div>
</div>
</div>
);
}
+224
View File
@@ -0,0 +1,224 @@
import { useRef, type CSSProperties } from 'react';
import type { PatternSettings, SourceImage } from '../lib/usePattern';
const GRID_MIN = 16;
const GRID_MAX = 128;
const GRID_STEP = 8;
const GRID_PRESETS = [32, 64, 96, 128];
const COLOR_MIN = 8;
const COLOR_MAX = 48;
const COLOR_STEP = 4;
interface ControlsPanelProps {
source: SourceImage | null;
settings: PatternSettings;
processing: boolean;
uploadError: string | null;
onChangeSettings: (patch: Partial<PatternSettings>) => void;
onFileSelected: (file: File) => void;
onReset: () => void;
onRegenerate: () => void;
}
function progressPercent(value: number, min: number, max: number): number {
return ((value - min) / (max - min)) * 100;
}
/** 01 生成设置 panel (§2.6): upload + sliders + toggles + regen button. */
export default function ControlsPanel({
source,
settings,
processing,
uploadError,
onChangeSettings,
onFileSelected,
onReset,
onRegenerate,
}: ControlsPanelProps) {
const fileInputRef = useRef<HTMLInputElement | null>(null);
const handleFiles = (files: FileList | null): void => {
const file = files?.[0];
if (file) {
onFileSelected(file);
}
};
const gridProgress = progressPercent(settings.gridSize, GRID_MIN, GRID_MAX);
const colorProgress = progressPercent(settings.maxColors, COLOR_MIN, COLOR_MAX);
const sizeCm = (settings.gridSize * 0.5).toFixed(0);
return (
<section className="panel" aria-label="01 生成设置">
<div className="panel-header">
<span className="panel-index">01</span>
<h2 className="panel-title">生成设置</h2>
</div>
<div className="panel-body">
{/* 上传框 */}
{!source ? (
<div
className={`upload-zone${uploadError ? ' upload-zone--error' : ''}`}
role="button"
tabIndex={0}
aria-label="上传一张图片"
onClick={() => fileInputRef.current?.click()}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
fileInputRef.current?.click();
}
}}
>
<span className="upload-plus" aria-hidden="true">
+
</span>
<span className="upload-title">上传一张图片</span>
<span className="upload-sub">支持 JPG、PNG、WEBP</span>
{uploadError && <span className="upload-error">{uploadError}</span>}
</div>
) : (
<div className="file-row">
<img className="file-thumb" src={source.url} alt={source.name} />
<div className="file-info">
<div className="file-name" title={source.name}>
{source.name}
</div>
<div className="file-meta">
{source.element.naturalWidth} × {source.element.naturalHeight} · 已上传
</div>
</div>
<button type="button" className="file-reset" onClick={onReset}>
重置
</button>
</div>
)}
<input
ref={fileInputRef}
type="file"
accept="image/jpeg,image/png,image/webp"
hidden
onChange={(e) => {
handleFiles(e.target.files);
e.target.value = '';
}}
/>
{/* 图纸尺寸滑杆 */}
<div className="control-group">
<div className="control-label-row">
<label className="control-label" htmlFor="grid-size">
图纸尺寸
</label>
<strong className="control-value">
{settings.gridSize} × {settings.gridSize}
</strong>
</div>
<input
id="grid-size"
type="range"
min={GRID_MIN}
max={GRID_MAX}
step={GRID_STEP}
value={settings.gridSize}
style={{ '--range-progress': `${gridProgress}%` } as CSSProperties}
onChange={(e) => onChangeSettings({ gridSize: Number(e.target.value) })}
/>
<div className="range-scale">
<span>{GRID_MIN}</span>
<span>48</span>
<span>80</span>
<span>{GRID_MAX}</span>
</div>
<div className="preset-row">
{GRID_PRESETS.map((preset) => (
<button
key={preset}
type="button"
className={`preset-btn${settings.gridSize === preset ? ' preset-btn--active' : ''}`}
onClick={() => onChangeSettings({ gridSize: preset })}
>
{preset}
</button>
))}
</div>
<p className="control-hint">成品约 {sizeCm} × {sizeCm} cm(按 5mm 豆计算)</p>
</div>
{/* 最大颜色数滑杆 */}
<div className="control-group">
<div className="control-label-row">
<label className="control-label" htmlFor="max-colors">
最大颜色数
</label>
<strong className="control-value">{settings.maxColors}</strong>
</div>
<input
id="max-colors"
type="range"
min={COLOR_MIN}
max={COLOR_MAX}
step={COLOR_STEP}
value={settings.maxColors}
style={{ '--range-progress': `${colorProgress}%` } as CSSProperties}
onChange={(e) => onChangeSettings({ maxColors: Number(e.target.value) })}
/>
<p className="control-hint">颜色越多,还原度越高;默认推荐 24 色</p>
</div>
{/* 背景去除 */}
<div className="toggle-row">
<div className="toggle-text">
<span className="toggle-label">一键去除背景</span>
<span className="toggle-desc">只保留人物或主体,不计算背景豆</span>
</div>
<button
type="button"
role="switch"
aria-checked={settings.removeBg}
className={`toggle${settings.removeBg ? ' toggle--on' : ''}`}
onClick={() => onChangeSettings({ removeBg: !settings.removeBg })}
>
<span className="toggle-knob" />
</button>
</div>
{/* 辅助网格 */}
<div className="toggle-row">
<div className="toggle-text">
<span className="toggle-label">显示辅助网格</span>
<span className="toggle-desc">方便逐格定位拼豆</span>
</div>
<button
type="button"
role="switch"
aria-checked={settings.showGrid}
className={`toggle${settings.showGrid ? ' toggle--on' : ''}`}
onClick={() => onChangeSettings({ showGrid: !settings.showGrid })}
>
<span className="toggle-knob" />
</button>
</div>
{/* 重新生成 */}
<button
type="button"
className="regen-btn"
disabled={!source || processing}
onClick={onRegenerate}
>
{processing ? (
<>
<span className="regen-spinner" aria-hidden="true" />
图片处理中…
</>
) : (
<>↻ 重新生成图纸</>
)}
</button>
</div>
</section>
);
}
+11
View File
@@ -0,0 +1,11 @@
/** FOOTER (§10): brand + note. */
export default function Footer() {
return (
<footer className="footer">
<div className="footer-inner">
<span className="footer-brand">PERLER LAB · 让每一颗颜色都有位置</span>
<span className="footer-note">图纸仅供个人手作参考</span>
</div>
</footer>
);
}
+30
View File
@@ -0,0 +1,30 @@
interface HeroProps {
beadCount: number;
colorCount: number;
}
/** HERO (§2.4): IMAGE TO BEADS + headline + stats. */
export default function Hero({ beadCount, colorCount }: HeroProps) {
return (
<section className="hero">
<p className="hero-eyebrow">IMAGE TO BEADS</p>
<h1 className="hero-title">
把喜欢的图片,<em>变成一颗颗拼豆。</em>
</h1>
<p className="hero-sub">
免费上传、生成和调整图纸,满意后使用兑换码下载完整高清图纸与用豆清单。
</p>
<div className="hero-stats">
<div className="hero-stat">
<strong>{beadCount.toLocaleString()}</strong>
<span>颗拼豆</span>
</div>
<span className="hero-stat-sep" aria-hidden="true" />
<div className="hero-stat">
<strong>{colorCount.toLocaleString()}</strong>
<span>种颜色</span>
</div>
</div>
</section>
);
}
@@ -0,0 +1,112 @@
import type { ProcessResult } from '../lib/image-processor';
interface InventoryPanelProps {
result: ProcessResult | null;
redeemed: boolean;
onRedeemClick: () => void;
}
const GHOST_ROWS = 4;
/** 03 MARD 备料清单 panel (§2.6, §3.4): locked masked state / unlocked list. */
export default function InventoryPanel({ result, redeemed, onRedeemClick }: InventoryPanelProps) {
const totalBeads = result?.totalBeads ?? 0;
const colorCount = result?.palette.length ?? 0;
return (
<section className="panel panel--inventory" aria-label="03 MARD 备料清单">
<div className="panel-header">
<span className="panel-index">03</span>
<h2 className="panel-title">MARD 备料清单</h2>
{redeemed ? (
<span className="inv-unlocked-badge">已解锁</span>
) : (
<span className="inv-lock-tag">🔒 受保护</span>
)}
</div>
<div className="panel-body">
{redeemed && result ? (
<>
<div className="inv-stats">
<div className="inv-stat">
<strong>{totalBeads.toLocaleString()}</strong>
<span>实际总颗数</span>
</div>
<div className="inv-stat">
<strong>{colorCount}</strong>
<span>使用颜色</span>
</div>
</div>
{result.palette.length > 0 ? (
<div className="inv-color-list">
{result.palette.map((entry) => (
<div key={entry.code} className="inv-color-row">
<span
className="inv-swatch"
style={{ background: entry.hex }}
aria-hidden="true"
/>
<span className="inv-code">{entry.code}</span>
<span className="inv-count">{entry.count.toLocaleString()} 颗</span>
</div>
))}
</div>
) : (
<p className="inv-empty">上传图片并生成图纸后,这里会显示 MARD 色号清单。</p>
)}
<p className="inv-extra">
建议多备 10% · 约{' '}
<strong>{Math.round(totalBeads * 1.1).toLocaleString()}</strong> 颗
</p>
</>
) : (
<>
{/* 遮罩统计 */}
<div className="inv-stats">
<div className="inv-stat">
<strong>••••</strong>
<span>实际总颗数</span>
</div>
<div className="inv-stat">
<strong>••</strong>
<span>使用颜色</span>
</div>
</div>
{/* 灰色色号占位行 */}
<div className="inv-locked-rows">
{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>
</div>
))}
</div>
{/* 锁定卡 */}
<div className="inv-lock-card">
<div className="inv-lock-icon" aria-hidden="true">
🔒
</div>
<p className="inv-lock-title">完整备料清单已锁定</p>
<p className="inv-lock-desc">
兑换后可查看全部 MARD 色号、每色颗数、总颗数及 10% 备豆建议
</p>
<button type="button" className="inv-unlock-btn" onClick={onRedeemClick}>
输入兑换码解锁
</button>
</div>
<p className="inv-extra">
建议多备 10% · 约 <strong>••••</strong> 颗
</p>
</>
)}
</div>
</section>
);
}
+39
View File
@@ -0,0 +1,39 @@
interface NavProps {
onAgencyClick: () => void;
}
/** NAV (§2.3): brand + links + 代理合作 + status badge. */
export default function Nav({ onAgencyClick }: NavProps) {
return (
<header className="nav">
<div className="nav-inner">
<a className="nav-brand" href="#top">
<span className="nav-brand-block">P</span>
<span>
PERLER <strong>LAB</strong>
</span>
</a>
<nav className="nav-links">
<a className="nav-link nav-link--active" href="#workspace">
图片转拼豆
</a>
<a className="nav-link" href="/chibi">
AI拼豆专区
<span className="nav-pro-badge">PRO</span>
</a>
</nav>
<div className="nav-right">
<button type="button" className="nav-agency" onClick={onAgencyClick}>
代理合作
</button>
<span className="nav-status">
<span className="nav-status-dot" aria-hidden="true" />
普通预览免费 · AI生成按次付费
</span>
</div>
</div>
</header>
);
}
+185
View File
@@ -0,0 +1,185 @@
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';
interface OrderModalProps {
plan: Plan;
onClose: () => void;
/** Called with the access code once payment is confirmed and auto-redeemed. */
onRedeemed: (code: string) => void;
}
type Step = 'method' | 'paying' | 'paid';
type RedeemState = 'pending' | 'ok' | 'error';
/**
* 订单弹窗 (§3.5, copy §7.2): 选择支付方式 → 下单并展示支付信息 →
* 模拟支付回调 → 展示兑换码并自动兑换。
*/
export default function OrderModal({ plan, onClose, onRedeemed }: OrderModalProps) {
const [method, setMethod] = useState<PaymentMethod>('wechat');
const [step, setStep] = useState<Step>('method');
const [order, setOrder] = useState<Order | null>(null);
const [payment, setPayment] = useState<PaymentInfo | null>(null);
const [accessCode, setAccessCode] = useState<string | null>(null);
const [redeemState, setRedeemState] = useState<RedeemState>('pending');
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const handleCreateOrder = async (): Promise<void> => {
if (busy) return;
setBusy(true);
setError(null);
try {
const res = await createOrder({
packageName: plan.name as PackageName,
paymentMethod: method,
});
setOrder(res.order);
setPayment(res.payment);
setStep('paying');
} catch (err) {
setError(err instanceof Error ? err.message : '下单失败,请稍后重试');
} finally {
setBusy(false);
}
};
const handlePayCallback = async (): Promise<void> => {
if (busy || !order) return;
setBusy(true);
setError(null);
try {
const res = await payCallback(order.orderNo);
setAccessCode(res.accessCode);
setStep('paid');
// 支付成功 → 自动兑换权益码
try {
await redeemCode(res.accessCode);
setRedeemState('ok');
} catch {
setRedeemState('error');
}
} catch (err) {
setError(err instanceof Error ? err.message : '支付确认失败,请稍后重试');
} finally {
setBusy(false);
}
};
const methodLabel = method === 'wechat' ? '微信' : '支付宝';
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}>
×
</button>
<h3 className="modal-title">购买 AI 生成次数</h3>
{step === 'method' && (
<>
<div className="pass-card" style={{ marginBottom: '16px' }}>
<span className="pass-card-name">{plan.name}</span>
<div className="pass-card-price">
¥{plan.price}
<small> / {plan.count}</small>
</div>
</div>
<div className="pass-card" style={{ padding: '12px 16px' }}>
<span className="pass-card-name" style={{ fontSize: '13px' }}>
应付金额 · ¥{plan.price} · {plan.count} 生成
</span>
</div>
<div className="preset-row" style={{ margin: '16px 0' }}>
<button
type="button"
className={`preset-btn${method === 'wechat' ? ' preset-btn--active' : ''}`}
style={{ flex: 1 }}
onClick={() => setMethod('wechat')}
>
微信收款码
</button>
<button
type="button"
className={`preset-btn${method === 'alipay' ? ' preset-btn--active' : ''}`}
style={{ flex: 1 }}
onClick={() => setMethod('alipay')}
>
支付宝收款码
</button>
</div>
{error && <p className="redeem-error">{error}</p>}
<button type="button" className="redeem-btn" disabled={busy} onClick={handleCreateOrder}>
{busy ? '下单中…' : '去支付'}
</button>
<p className="pass-benefit" style={{ margin: '12px 0 0' }}>
截图或长按保存收款码,再打开对应支付应用扫码支付 · 付款金额请与上方一致
</p>
</>
)}
{step === 'paying' && order && payment && (
<>
<div className="order-pay-info">
<div className="order-pay-row">
<span>订单号</span>
<code>{order.orderNo}</code>
</div>
<div className="order-pay-row">
<span>应付金额</span>
<strong>¥{(order.amountCents / 100).toFixed(2)}</strong>
</div>
<p className="order-pay-hint">
请使用{methodLabel}扫码支付(或长按识别收款码),付款金额请与上方一致
</p>
<p className="order-pay-hint order-pay-hint--url">
支付链接:{payment.url}
{payment.qrCode ? ` · 收款码:${payment.qrCode}` : ''}
</p>
</div>
{error && <p className="redeem-error">{error}</p>}
<button type="button" className="redeem-btn" disabled={busy} onClick={handlePayCallback}>
{busy ? '确认中…' : '模拟支付完成'}
</button>
<p className="pass-benefit" style={{ margin: '12px 0 0' }}>
模拟环境:点击后直接标记订单已支付并发放兑换码
</p>
</>
)}
{step === 'paid' && accessCode && (
<>
<div className="order-result">
<span className="order-result-label">支付成功 · 权益兑换码</span>
<code className="order-result-code">{accessCode}</code>
{redeemState === 'ok' && (
<p className="order-result-note">已自动兑换成功,AI 生成权益已到账</p>
)}
{redeemState === 'error' && (
<p className="redeem-error">
自动兑换失败,可复制兑换码后在「输入兑换码」中手动兑换
</p>
)}
</div>
<button
type="button"
className="redeem-btn"
onClick={() => (redeemState === 'ok' ? onRedeemed(accessCode) : onClose())}
>
完成
</button>
</>
)}
</div>
</div>
);
}
+77
View File
@@ -0,0 +1,77 @@
interface Plan {
key: string;
name: string;
price: string;
count: string;
desc: string;
featured?: boolean;
}
const PLANS: Plan[] = [
{
key: 'basic',
name: '体验包',
price: '4.9',
count: '3 次',
desc: '适合先体验 AI 拼豆效果',
},
{
key: 'standard',
name: '常用包',
price: '12.9',
count: '10 次',
desc: '适合个人多次创作(推荐)',
featured: true,
},
{
key: 'pro',
name: '进阶包',
price: '29.9',
count: '30 次',
desc: '适合接单与持续出图',
},
];
interface PassSectionProps {
onPlanClick: (plan: Plan) => void;
}
export type { Plan };
/** DOWNLOAD PASS (§2.5): 3 pricing cards + CTA. */
export default function PassSection({ onPlanClick }: PassSectionProps) {
return (
<section className="pass" aria-label="权益套餐">
<h2 className="pass-title">AI生成权益</h2>
<p className="pass-sub">购买 / 兑换后解锁完整图纸与备料清单</p>
<div className="pass-cards">
{PLANS.map((plan) => (
<div
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>
<div className="pass-card-price">
¥{plan.price}
<small> / {plan.count}</small>
</div>
<p className="pass-card-desc">{plan.desc}</p>
<button
type="button"
className={`pass-cta${plan.featured ? '' : ' pass-cta--outline'}`}
onClick={() => onPlanClick(plan)}
>
购买 / 兑换 →
</button>
</div>
))}
</div>
<p className="pass-benefit">
成功生成 1 张作品,消耗 1 次 · 该作品转拼豆图纸及首次高清下载免费
</p>
</section>
);
}
@@ -0,0 +1,94 @@
import { useEffect, useRef } from 'react';
import type { PatternSettings, SourceImage } from '../lib/usePattern';
import type { ProcessResult } from '../lib/image-processor';
import { drawPreview } from '../lib/drawPattern';
interface PreviewPanelProps {
source: SourceImage | null;
settings: PatternSettings;
result: ProcessResult | null;
processing: boolean;
error: string | null;
redeemed: boolean;
downloadError: string | null;
onDownload: () => void;
}
/** 02 实时预览 panel (§2.6): canvas + ruler + download button. */
export default function PreviewPanel({
source,
settings,
result,
processing,
error,
redeemed,
downloadError,
onDownload,
}: PreviewPanelProps) {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (canvas && result) {
drawPreview(canvas, result, settings.gridSize, settings.showGrid);
}
}, [result, settings.gridSize, settings.showGrid]);
const fileName = source ? source.name : '未命名';
const beadCount = result?.totalBeads ?? 0;
const downloadReady = Boolean(redeemed && result && source);
return (
<section className="panel" aria-label="02 实时预览">
<div className="panel-header">
<span className="panel-index">02</span>
<h2 className="panel-title">
<span className="dot" aria-hidden="true">
●
</span>{' '}
实时预览
</h2>
<span className="panel-hint">每5格加粗 · 每10格标号</span>
</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 />
图片处理中…
</div>
) : result ? (
<canvas
ref={canvasRef}
className="preview-canvas"
aria-label="拼豆图纸预览"
/>
) : error ? (
<div className="preview-empty">{error}</div>
) : (
<div className="preview-empty">
上传图片后,这里会实时显示拼豆图纸。
<br />
标尺:每5格加粗 · 每10格标号
</div>
)}
</div>
<div className="preview-meta">
<span className="preview-file" title={fileName}>
{fileName}
</span>
<span className="preview-size">
{settings.gridSize} × {settings.gridSize} · 实际使用 {beadCount.toLocaleString()} 颗
</span>
</div>
<button type="button" className="download-btn" disabled={!downloadReady} onClick={onDownload}>
↓ 兑换后下载完整图纸
</button>
<p className="download-note">首次下载免费 / 下载普通图纸 · 消耗 1 次</p>
{downloadError && <p className="download-error">{downloadError}</p>}
</section>
);
}
+59
View File
@@ -0,0 +1,59 @@
import { useState } from 'react';
interface RedeemModalProps {
onClose: () => void;
/** Validates the code against the server; rejects with the server's message. */
onRedeem: (code: string) => Promise<void>;
}
/** 兑换码弹窗 (§3.5, copy §7.1): validates the code against the server. */
export default function RedeemModal({ onClose, onRedeem }: RedeemModalProps) {
const [code, setCode] = useState('');
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
const handleRedeem = async (): Promise<void> => {
const trimmed = code.trim();
if (!trimmed) {
setError('兑换失败 / 兑换码不存在,请检查后重试');
return;
}
if (submitting) return;
setSubmitting(true);
setError(null);
try {
await onRedeem(trimmed);
} catch (err) {
setError(err instanceof Error ? err.message : '兑换失败,请稍后重试');
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}>
×
</button>
<h3 className="modal-title">输入兑换码</h3>
<input
className="redeem-input"
placeholder="请输入兑换码"
value={code}
autoFocus
onChange={(e) => {
setCode(e.target.value);
setError(null);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') void handleRedeem();
}}
/>
{error && <p className="redeem-error">{error}</p>}
<button type="button" className="redeem-btn" disabled={submitting} onClick={handleRedeem}>
{submitting ? '兑换中…' : '兑换'}
</button>
</div>
</div>
);
}
@@ -0,0 +1,374 @@
/**
* Algorithm library tests — covers every module of the image-to-beads
* pipeline: CIE LAB math, k-means quantization, background removal,
* MARD palette matching, the full processImage pipeline, and canvas
* pattern rendering.
*/
import { describe, it, expect, vi } from 'vitest';
import { srgbToLab, labDistance } from '../lab.js';
import { kMeansQuantize } from '../quantize.js';
import { removeBackground } from '../background.js';
import { MARD_PALETTE, findNearestColor, nearestColorFromRgb } from '../mard-palette.js';
import { processImage } from '../image-processor.js';
import { renderPattern, drawPaletteLegend, rgbToCss } from '../pattern-renderer.js';
import type { ProcessedCell, ProcessedPaletteEntry } from '../image-processor.js';
// ---------------------------------------------------------------------------
// lab.ts
// ---------------------------------------------------------------------------
describe('srgbToLab', () => {
it('maps pure white to L=100, a=0, b=0', () => {
const [l, a, b] = srgbToLab([255, 255, 255]);
expect(l).toBeCloseTo(100, 1);
expect(a).toBeCloseTo(0, 1);
expect(b).toBeCloseTo(0, 1);
});
it('maps pure black to L=0, a=0, b=0', () => {
const [l, a, b] = srgbToLab([0, 0, 0]);
expect(l).toBeCloseTo(0, 1);
expect(a).toBeCloseTo(0, 1);
expect(b).toBeCloseTo(0, 1);
});
it('maps pure red to the canonical D65 LAB value', () => {
const [l, a, b] = srgbToLab([255, 0, 0]);
expect(l).toBeCloseTo(53.24, 1);
expect(a).toBeCloseTo(80.09, 1);
expect(b).toBeCloseTo(67.2, 1);
});
it('maps mid gray to L=50', () => {
const [l] = srgbToLab([128, 128, 128]);
expect(l).toBeCloseTo(53.59, 1);
});
});
describe('labDistance', () => {
it('is zero for identical colors', () => {
const lab = srgbToLab([10, 200, 30]);
expect(labDistance(lab, lab)).toBe(0);
});
it('is symmetric', () => {
const a = srgbToLab([255, 0, 0]);
const b = srgbToLab([0, 0, 255]);
expect(labDistance(a, b)).toBeCloseTo(labDistance(b, a), 10);
});
it('is positive for different colors and smaller for similar colors', () => {
const red = srgbToLab([255, 0, 0]);
const darkRed = srgbToLab([200, 0, 0]);
const blue = srgbToLab([0, 0, 255]);
expect(labDistance(red, blue)).toBeGreaterThan(labDistance(red, darkRed));
expect(labDistance(red, blue)).toBeGreaterThan(0);
});
});
// ---------------------------------------------------------------------------
// quantize.ts
// ---------------------------------------------------------------------------
describe('kMeansQuantize', () => {
it('returns an empty list for empty input', () => {
expect(kMeansQuantize([], 8)).toEqual([]);
});
it('returns an empty list when maxColors is not positive', () => {
expect(kMeansQuantize([[50, 0, 0]], 0)).toEqual([]);
});
it('collapses a single-color cluster: every centroid equals that color', () => {
const color: [number, number, number] = [55.5, -20, 30];
const colors = Array.from({ length: 12 }, () => color);
const centroids = kMeansQuantize(colors, 4);
// k-means++ on identical points yields up to `maxColors` centers, all
// pinned to the same color (the pipeline dedupes them downstream).
expect(centroids).toHaveLength(4);
for (const centroid of centroids) {
expect(centroid[0]).toBeCloseTo(color[0], 6);
expect(centroid[1]).toBeCloseTo(color[1], 6);
expect(centroid[2]).toBeCloseTo(color[2], 6);
}
});
it('separates two well-spaced clusters into their exact means', () => {
const clusterA: [number, number, number] = [50, 20, 10];
const clusterB: [number, number, number] = [80, -30, 40];
const colors: [number, number, number][] = [
...Array.from({ length: 10 }, () => clusterA),
...Array.from({ length: 10 }, () => clusterB),
];
const centroids = kMeansQuantize(colors, 2);
expect(centroids).toHaveLength(2);
const sorted = [...centroids].sort((a, b) => a[0] - b[0]);
for (const [i, expected] of [clusterA, clusterB].entries()) {
expect(sorted[i]![0]).toBeCloseTo(expected[0], 6);
expect(sorted[i]![1]).toBeCloseTo(expected[1], 6);
expect(sorted[i]![2]).toBeCloseTo(expected[2], 6);
}
});
it('never returns more centroids than distinct points', () => {
const colors: [number, number, number][] = [
[10, 10, 10],
[20, 20, 20],
[30, 30, 30],
];
expect(kMeansQuantize(colors, 8).length).toBeLessThanOrEqual(3);
});
});
// ---------------------------------------------------------------------------
// background.ts
// ---------------------------------------------------------------------------
function solidGrid(size: number, fill: [number, number, number]): [number, number, number][] {
return Array.from({ length: size * size }, () => fill);
}
describe('removeBackground', () => {
const white: [number, number, number] = [255, 255, 255];
const red: [number, number, number] = [255, 0, 0];
it('removes an all-white image entirely', () => {
const grid = solidGrid(4, white);
const removed = removeBackground(grid, 4, 20);
expect(removed.size).toBe(16);
});
it('removes white background but keeps a red center patch', () => {
const grid = solidGrid(4, white);
// Center 2×2 cells are red (indices 5, 6, 9, 10).
for (const idx of [5, 6, 9, 10]) grid[idx] = red;
const removed = removeBackground(grid, 4, 20);
expect(removed.size).toBe(12);
for (const idx of [5, 6, 9, 10]) {
expect(removed.has(idx)).toBe(false);
}
expect(removed.has(0)).toBe(true);
expect(removed.has(15)).toBe(true);
});
it('does not flood across a high-contrast border at low threshold', () => {
const grid = solidGrid(4, white);
for (const idx of [5, 6, 9, 10]) grid[idx] = red;
// With threshold 1, white still matches white; red never floods.
const removed = removeBackground(grid, 4, 1);
expect(removed.size).toBe(12);
});
it('returns an empty set for an empty grid', () => {
expect(removeBackground([], 4, 20).size).toBe(0);
});
});
// ---------------------------------------------------------------------------
// mard-palette.ts
// ---------------------------------------------------------------------------
describe('MARD palette', () => {
it('embeds all 221 competitor colors', () => {
expect(MARD_PALETTE).toHaveLength(221);
});
it('contains well-formed codes and valid hex colors', () => {
for (const entry of MARD_PALETTE) {
expect(entry.code).toMatch(/^[A-Z]\d{1,2}$/);
expect(entry.hex).toMatch(/^#[0-9A-F]{6}$/);
expect(entry.rgb).toHaveLength(3);
expect(entry.lab).toHaveLength(3);
}
});
it('finds the exact palette entry for its own LAB color', () => {
const target = MARD_PALETTE[0]!;
expect(findNearestColor(target.lab).code).toBe(target.code);
});
it('maps a known RGB to its expected code (pure red → a red MARD tone)', () => {
const match = nearestColorFromRgb([255, 0, 0]);
expect(match.code).toMatch(/^[A-Z]\d{1,2}$/);
expect(match.rgb[0]).toBeGreaterThan(match.rgb[2]); // red-dominant
});
it('honors an explicit custom palette', () => {
const custom = [MARD_PALETTE[10]!];
expect(findNearestColor([50, 0, 0], custom).code).toBe(custom[0]!.code);
});
});
// ---------------------------------------------------------------------------
// image-processor.ts
// ---------------------------------------------------------------------------
function buildTestImageData(size: number, paint: (x: number, y: number) => [number, number, number]): ImageData {
const data = new Uint8ClampedArray(size * size * 4);
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
const [r, g, b] = paint(x, y);
const i = (y * size + x) * 4;
data[i] = r;
data[i + 1] = g;
data[i + 2] = b;
data[i + 3] = 255;
}
}
return { data, width: size, height: size } as ImageData;
}
/** 16×16 image: white everywhere except a 4×4 pure-red block at top-left. */
function redOnWhiteImage(): ImageData {
return buildTestImageData(16, (x, y) => (x < 4 && y < 4 ? [255, 0, 0] : [255, 255, 255]));
}
describe('processImage', () => {
const baseOptions = {
gridSize: 4,
maxColors: 8,
removeBg: false,
bgThreshold: 20,
};
it('produces a grid of gridSize² cells and counts every bead', () => {
const result = processImage(redOnWhiteImage(), baseOptions);
expect(result.grid).toHaveLength(16);
expect(result.totalBeads).toBe(16);
expect(result.grid.every((c) => !c.empty)).toBe(true);
});
it('maps the red block cell to a non-empty MARD color', () => {
const result = processImage(redOnWhiteImage(), baseOptions);
const redCell = result.grid.find((c) => c.x === 0 && c.y === 0)!;
expect(redCell.empty).toBe(false);
expect(redCell.code).toMatch(/^[A-Z]\d{1,2}$/);
expect(redCell.rgb[0]).toBeGreaterThan(150); // still red-dominant
});
it('builds a palette sorted by count descending whose counts sum to totalBeads', () => {
const result = processImage(redOnWhiteImage(), baseOptions);
expect(result.palette.length).toBeGreaterThan(0);
for (let i = 1; i < result.palette.length; i++) {
expect(result.palette[i - 1]!.count).toBeGreaterThanOrEqual(result.palette[i]!.count);
}
const sum = result.palette.reduce((acc, e) => acc + e.count, 0);
expect(sum).toBe(result.totalBeads);
});
it('removes white background but keeps the red patch when removeBg is on', () => {
const result = processImage(redOnWhiteImage(), { ...baseOptions, removeBg: true });
expect(result.totalBeads).toBe(1);
const redCell = result.grid.find((c) => c.x === 0 && c.y === 0)!;
expect(redCell.empty).toBe(false);
expect(result.grid.filter((c) => c.empty)).toHaveLength(15);
});
it('yields an empty pattern for a blank image with background removal', () => {
const blank = buildTestImageData(16, () => [255, 255, 255]);
const result = processImage(blank, { ...baseOptions, removeBg: true });
expect(result.totalBeads).toBe(0);
expect(result.palette).toEqual([]);
expect(result.grid.every((c) => c.empty)).toBe(true);
});
it('respects gridSize mapping: cell (x,y) order is row-major', () => {
const result = processImage(redOnWhiteImage(), baseOptions);
const grid4: ProcessedCell[][] = Array.from({ length: 4 }, (_, y) =>
result.grid.filter((c) => c.y === y).sort((a, b) => a.x - b.x),
);
expect(grid4[0]![0]!.code).toBeTruthy();
expect(grid4[1]![0]!.code).toBeTruthy();
});
});
// ---------------------------------------------------------------------------
// pattern-renderer.ts
// ---------------------------------------------------------------------------
function makeMockContext(): CanvasRenderingContext2D {
return {
canvas: { width: 0, height: 0 },
fillStyle: '',
strokeStyle: '',
lineWidth: 1,
fillRect: vi.fn(),
strokeRect: vi.fn(),
beginPath: vi.fn(),
moveTo: vi.fn(),
lineTo: vi.fn(),
stroke: vi.fn(),
fillText: vi.fn(),
measureText: () => ({ width: 10 }),
save: vi.fn(),
restore: vi.fn(),
} as unknown as CanvasRenderingContext2D;
}
function sampleGrid(size: number): ProcessedCell[] {
const cells: ProcessedCell[] = [];
for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
const filled = (x + y) % 2 === 0;
cells.push({
x,
y,
rgb: filled ? [255, 0, 0] : [0, 0, 255],
lab: [50, 0, 0],
code: filled ? 'X1' : '',
empty: !filled,
});
}
}
return cells;
}
describe('renderPattern', () => {
it('sizes the canvas as gridSize × cellSize', () => {
const ctx = makeMockContext();
renderPattern(ctx, sampleGrid(2), 2, { cellSize: 10 });
expect(ctx.canvas.width).toBe(20);
expect(ctx.canvas.height).toBe(20);
});
it('draws one rect per cell plus the base coat', () => {
const ctx = makeMockContext();
const fillRect = vi.mocked(ctx.fillRect);
renderPattern(ctx, sampleGrid(2), 2, { cellSize: 10, drawGrid: false });
// 1 base coat + 2 filled cells + 2 empty cells
expect(fillRect).toHaveBeenCalledTimes(5);
});
it('draws grid lines when drawGrid is enabled', () => {
const ctx = makeMockContext();
renderPattern(ctx, sampleGrid(2), 2, { cellSize: 10, drawGrid: true });
expect(ctx.beginPath).toHaveBeenCalled();
expect(ctx.stroke).toHaveBeenCalled();
});
});
describe('drawPaletteLegend', () => {
const palette: ProcessedPaletteEntry[] = [
{ code: 'A1', hex: '#FAF4C8', rgb: [250, 244, 200], count: 12 },
{ code: 'B2', hex: '#63F347', rgb: [99, 243, 71], count: 4 },
];
it('draws one swatch and one label per palette entry', () => {
const ctx = makeMockContext();
drawPaletteLegend(ctx, palette);
expect(ctx.fillRect).toHaveBeenCalledTimes(2);
expect(ctx.fillText).toHaveBeenCalledTimes(2);
expect(ctx.fillText).toHaveBeenCalledWith('A1 × 12', expect.any(Number), expect.any(Number));
});
});
describe('rgbToCss', () => {
it('formats an sRGB tuple as a CSS color', () => {
expect(rgbToCss([255, 0, 0])).toBe('rgb(255, 0, 0)');
});
});
+168
View File
@@ -0,0 +1,168 @@
/**
* PERLER LAB — backend API client
*
* Thin typed fetch wrappers over the Express server (perler-lab-server, :8788).
* Every endpoint throws `Error` carrying the server's Chinese message on
* failure (e.g. "兑换码不存在", "兑换码已用尽"), or a fallback message when the
* server is unreachable / the body is not the expected {error} shape.
*/
export interface AccessInfo {
code: string;
packageType: string;
remainingUses: number;
totalUses: number;
}
export type PaymentMethod = 'wechat' | 'alipay';
export type PackageName = '体验包' | '常用包' | '进阶包';
export interface Order {
orderNo: string;
packageName: string;
amountCents: number;
paymentMethod: PaymentMethod;
status: string;
createdAt?: string;
}
export interface PaymentInfo {
url: string;
qrCode?: string;
transactionId?: string;
}
export interface RedeemResponse {
access: AccessInfo;
}
export interface ConsumeParams {
code: string;
fileName: string;
downloadGrant: string;
}
export interface ConsumeResponse {
access: AccessInfo;
freeDownload: boolean;
}
export interface CreateOrderParams {
packageName: PackageName;
paymentMethod: PaymentMethod;
}
export interface CreateOrderResponse {
order: Order;
payment: PaymentInfo;
}
export interface PayCallbackResponse {
ok: boolean;
order: Order;
accessCode: string;
}
export interface GenerateChibiParams {
code: string;
image: string;
referenceImage?: string;
category: string;
subtype: string;
gridSize: number;
colorCount: number;
composition: string;
detailTags: string[];
customPrompt?: string;
}
export interface GenerateChibiResponse {
image: string;
access: AccessInfo;
downloadGrant: string;
}
/** Base URL: override with VITE_API_BASE, default to the local dev server. */
const API_BASE: string = import.meta.env.VITE_API_BASE ?? 'http://localhost:8788';
/**
* Shared JSON helper: normalizes headers, then parses the body.
* On a non-2xx response it reads { error } and throws Error(error) so the
* UI can surface the server's Chinese message directly.
*/
async function request<T>(path: string, init?: RequestInit): Promise<T> {
const headers = new Headers(init?.headers);
if (!headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json');
}
let res: Response;
try {
res = await fetch(`${API_BASE}${path}`, { ...init, headers });
} catch {
throw new Error('无法连接服务器,请确认本地服务已启动');
}
let data: unknown;
try {
data = await res.json();
} catch {
throw new Error(`请求失败(HTTP ${res.status})`);
}
if (!res.ok) {
const error = (data as { error?: unknown } | null)?.error;
throw new Error(
typeof error === 'string' && error.length > 0
? error
: `请求失败(HTTP ${res.status})`,
);
}
return data as T;
}
/** POST /api/codes/redeem — validate a code and log the redemption. */
export function redeemCode(code: string): Promise<RedeemResponse> {
return request<RedeemResponse>('/api/codes/redeem', {
method: 'POST',
body: JSON.stringify({ code }),
});
}
/** POST /api/codes/consume — consume one use for a download. */
export function consumeCode(params: ConsumeParams): Promise<ConsumeResponse> {
return request<ConsumeResponse>('/api/codes/consume', {
method: 'POST',
body: JSON.stringify(params),
});
}
/** POST /api/orders — create a payment order for a package. */
export function createOrder(params: CreateOrderParams): Promise<CreateOrderResponse> {
return request<CreateOrderResponse>('/api/orders', {
method: 'POST',
body: JSON.stringify(params),
});
}
/** GET /api/orders?orderNo= — fetch an order by number. */
export function getOrder(orderNo: string): Promise<{ order: Order }> {
return request<{ order: Order }>(`/api/orders?orderNo=${encodeURIComponent(orderNo)}`);
}
/** POST /api/orders/:orderNo/pay-callback — simulate payment completion. */
export function payCallback(orderNo: string): Promise<PayCallbackResponse> {
return request<PayCallbackResponse>(`/api/orders/${encodeURIComponent(orderNo)}/pay-callback`, {
method: 'POST',
});
}
/** POST /api/chibi/generate — generate an AI chibi bead design (uses 1 权益). */
export function generateChibi(params: GenerateChibiParams): Promise<GenerateChibiResponse> {
return request<GenerateChibiResponse>('/api/chibi/generate', {
method: 'POST',
body: JSON.stringify(params),
});
}
+110
View File
@@ -0,0 +1,110 @@
/**
* Background removal via edge-pixel detection + 4-connected BFS flood fill.
*
* Reverse-engineered competitor algorithm:
* 1. Sample the 4 edges of the grid (top row, bottom row, left col, right col).
* 2. Quantize each edge pixel's RGB by /20 (bucket key = "r-g-b"). Take the
* majority bucket's average as the background color.
* 3. Convert the background color to LAB.
* 4. BFS flood-fill from all edge pixels: any pixel whose LAB distance to the
* background color ≤ `threshold` is considered background and removed.
* 5. Returns a Set of grid indices to remove.
*/
import { srgbToLab, labDistance, type Lab3, type Rgb3 } from './lab.js';
const BUCKET_SIZE = 20;
/**
* Detect background pixels via edge-sampling flood fill.
*
* @param grid - Flattened grid of RGB pixels (row-major).
* @param size - Grid dimension (size × size).
* @param threshold - LAB distance threshold (default 20). Lower = more aggressive.
* @returns A Set of indices to remove (background pixels).
*/
export function removeBackground(
grid: readonly Rgb3[],
size: number,
threshold: number = 20,
): Set<number> {
if (grid.length === 0 || size <= 0) {
return new Set();
}
// ---- 1. Collect edge indices ----
const edgeIndices = new Set<number>();
// top row (y=0)
for (let x = 0; x < size; x++) edgeIndices.add(x);
// bottom row (y=size-1)
for (let x = 0; x < size; x++) edgeIndices.add((size - 1) * size + x);
// left column (x=0)
for (let y = 1; y < size - 1; y++) edgeIndices.add(y * size);
// right column (x=size-1)
for (let y = 1; y < size - 1; y++) edgeIndices.add(y * size + size - 1);
// ---- 2. Quantize edge pixels by /20, take majority bucket ----
const bucketMap = new Map<string, { sum: [number, number, number]; n: number }>();
for (const idx of edgeIndices) {
const pixel = grid[idx];
if (!pixel) continue;
const key = `${Math.round(pixel[0] / BUCKET_SIZE)}-${Math.round(pixel[1] / BUCKET_SIZE)}-${Math.round(pixel[2] / BUCKET_SIZE)}`;
const entry = bucketMap.get(key) ?? { sum: [0, 0, 0] as [number, number, number], n: 0 };
entry.sum[0] += pixel[0];
entry.sum[1] += pixel[1];
entry.sum[2] += pixel[2];
entry.n++;
bucketMap.set(key, entry);
}
// Find the bucket with the most votes.
let majorityBucket: { sum: [number, number, number]; n: number } | undefined;
let maxCount = 0;
for (const entry of bucketMap.values()) {
if (entry.n > maxCount) {
maxCount = entry.n;
majorityBucket = entry;
}
}
if (!majorityBucket || majorityBucket.n === 0) {
return new Set();
}
const bgRgb: Rgb3 = [
Math.round(majorityBucket.sum[0] / majorityBucket.n),
Math.round(majorityBucket.sum[1] / majorityBucket.n),
Math.round(majorityBucket.sum[2] / majorityBucket.n),
];
const bgLab: Lab3 = srgbToLab(bgRgb);
// ---- 3. BFS flood fill from edges ----
const removed = new Set<number>();
const queue = [...edgeIndices];
while (queue.length > 0) {
const idx = queue.shift()!;
if (removed.has(idx)) continue;
const pixel = grid[idx];
if (!pixel) continue;
const pixelLab = srgbToLab(pixel);
const distance = labDistance(pixelLab, bgLab);
if (distance > threshold) continue;
removed.add(idx);
const x = idx % size;
const y = Math.floor(idx / size);
// 4-connected neighbours
if (x > 0) queue.push(idx - 1);
if (x < size - 1) queue.push(idx + 1);
if (y > 0) queue.push((y - 1) * size + x);
if (y < size - 1) queue.push((y + 1) * size + x);
}
return removed;
}
+233
View File
@@ -0,0 +1,233 @@
import type { ProcessResult } from './image-processor.js';
import { rgbToCss } from './pattern-renderer.js';
/** Preview cell size in device px. */
const PREVIEW_CELL = 8;
/** Preview ruler label margin. */
const PREVIEW_LABEL = 18;
/**
* Draw the bead pattern onto a preview canvas: bead circles + grid lines
* (每5格加粗 · 每10格标号, per DESIGN.md §2.6).
*/
export function drawPreview(
canvas: HTMLCanvasElement,
result: ProcessResult,
gridSize: number,
showGrid: boolean,
): void {
const ctx = canvas.getContext('2d');
if (!ctx) return;
const size = gridSize * PREVIEW_CELL + PREVIEW_LABEL * 2;
canvas.width = size;
canvas.height = size;
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, size, size);
const radius = PREVIEW_CELL * 0.42;
for (const cell of result.grid) {
const px = PREVIEW_LABEL + cell.x * PREVIEW_CELL;
const py = PREVIEW_LABEL + cell.y * PREVIEW_CELL;
if (!cell.empty) {
ctx.beginPath();
ctx.arc(px + PREVIEW_CELL / 2, py + PREVIEW_CELL / 2, radius, 0, Math.PI * 2);
ctx.fillStyle = rgbToCss(cell.rgb);
ctx.fill();
} else if (showGrid) {
ctx.fillStyle = '#fdfcf9';
ctx.fillRect(px, py, PREVIEW_CELL, PREVIEW_CELL);
}
}
if (showGrid) {
drawGrid(ctx, gridSize, PREVIEW_CELL, PREVIEW_LABEL, PREVIEW_LABEL);
}
// Ruler numbers (every 10 cells) along top + left.
ctx.font = 'bold 10px "Geist Mono", ui-monospace, Consolas, monospace';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = 'rgba(20,20,18,.78)';
for (let i = 10; i <= gridSize; i += 10) {
const pos = PREVIEW_LABEL + i * PREVIEW_CELL;
ctx.fillText(String(i), pos - PREVIEW_CELL / 2, PREVIEW_LABEL / 2);
ctx.save();
ctx.translate(PREVIEW_LABEL / 2, pos - PREVIEW_CELL / 2);
ctx.fillText(String(i), 0, 0);
ctx.restore();
}
}
/** Draw grid lines: light per cell, medium every 5, strong every 10. */
function drawGrid(
ctx: CanvasRenderingContext2D,
gridSize: number,
cell: number,
ox: number,
oy: number,
): void {
ctx.lineWidth = 1;
for (let i = 0; i <= gridSize; i++) {
const isStrong = i % 10 === 0;
const isMedium = i % 5 === 0;
ctx.strokeStyle = isStrong
? 'rgba(20,20,18,.78)'
: isMedium
? 'rgba(30,30,28,.45)'
: 'rgba(30,30,28,.16)';
if (isStrong) ctx.lineWidth = 1.6;
else if (isMedium) ctx.lineWidth = 1.2;
else ctx.lineWidth = 1;
const p = cell * i;
ctx.beginPath();
ctx.moveTo(ox + p, oy);
ctx.lineTo(ox + p, oy + gridSize * cell);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(ox, oy + p);
ctx.lineTo(ox + gridSize * cell, oy + p);
ctx.stroke();
}
}
// ---------------------------------------------------------------------------
// PNG export (DESIGN.md §5)
// ---------------------------------------------------------------------------
const EXPORT_MARGIN = 80;
const EXPORT_TITLE_H = 80;
/** Render a full-size, printable 图纸 canvas (title + grid + 备豆清单). */
export function buildExportCanvas(
result: ProcessResult,
gridSize: number,
title: string,
): HTMLCanvasElement {
const cell = gridSize >= 96 ? 22 : 28;
const gridPx = gridSize * cell;
const paletteColumns = gridPx + EXPORT_MARGIN * 2 > 1800 ? 3 : 4;
const paletteRows = Math.ceil(result.palette.length / paletteColumns);
const paletteRowH = 44;
const paletteTitleH = 56;
const paletteBottom = 24;
const width = gridPx + EXPORT_MARGIN * 2;
const height =
EXPORT_TITLE_H + gridPx + paletteTitleH + paletteRows * paletteRowH + paletteBottom;
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx) return canvas;
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, width, height);
// ---- Title ----
ctx.fillStyle = '#171713';
ctx.font = '700 24px "Geist", system-ui, sans-serif';
ctx.textAlign = 'left';
ctx.textBaseline = 'middle';
ctx.fillText(`${title} · ${gridSize}×${gridSize} · MARD 拼豆图纸`, EXPORT_MARGIN, 40);
// ---- Grid ----
const radius = cell * 0.42;
const codeFontSize = Math.max(7, cell * 0.28);
ctx.font = `700 ${codeFontSize}px "Geist Mono", monospace`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (const c of result.grid) {
const px = EXPORT_MARGIN + c.x * cell;
const py = EXPORT_TITLE_H + c.y * cell;
if (c.empty) continue;
ctx.beginPath();
ctx.arc(px + cell / 2, py + cell / 2, radius, 0, Math.PI * 2);
ctx.fillStyle = rgbToCss(c.rgb);
ctx.fill();
const textColor = c.lab[0] < 52 ? '#ffffff' : '#171713';
ctx.fillStyle = textColor;
ctx.fillText(c.code, px + cell / 2, py + cell / 2);
}
drawGrid(ctx, gridSize, cell, EXPORT_MARGIN, EXPORT_TITLE_H);
// Ruler numbers on export (14px bold every 10 cells).
ctx.font = '700 14px "Geist Mono", monospace';
ctx.fillStyle = 'rgba(20,20,18,.78)';
ctx.textAlign = 'center';
for (let i = 10; i <= gridSize; i += 10) {
const pos = EXPORT_MARGIN + i * cell;
ctx.fillText(String(i), pos - cell / 2, EXPORT_TITLE_H - 14);
ctx.save();
ctx.translate(EXPORT_MARGIN - 14, EXPORT_TITLE_H + pos - EXPORT_MARGIN - cell / 2);
ctx.fillText(String(i), 0, 0);
ctx.restore();
}
// ---- MARD 备豆清单 ----
const paletteTop = EXPORT_TITLE_H + gridPx + 28;
ctx.textAlign = 'left';
ctx.font = '700 28px "Geist", system-ui, sans-serif';
ctx.fillStyle = '#171713';
ctx.fillText('MARD 备豆清单', EXPORT_MARGIN, paletteTop);
ctx.font = '15px "Geist", system-ui, sans-serif';
ctx.fillStyle = '#66645d';
ctx.fillText(
`共 ${result.totalBeads} 颗 · ${result.palette.length} 种颜色 · 建议多备 10% (约 ${Math.round(result.totalBeads * 1.1)} 颗)`,
EXPORT_MARGIN,
paletteTop + 26,
);
const swatchX = EXPORT_MARGIN + 6;
const rowGap = 44;
result.palette.forEach((entry, index) => {
const col = index % paletteColumns;
const row = Math.floor(index / paletteColumns);
const x = swatchX + col * ((gridPx + EXPORT_MARGIN * 2 - EXPORT_MARGIN * 2) / paletteColumns);
const y = paletteTop + 48 + row * rowGap + rowGap / 2;
// swatch circle with ring
ctx.beginPath();
ctx.arc(x, y, 12, 0, Math.PI * 2);
ctx.fillStyle = entry.hex;
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = '#d2cec4';
ctx.stroke();
ctx.textAlign = 'left';
ctx.font = '700 17px "Geist Mono", monospace';
ctx.fillStyle = '#171713';
ctx.fillText(entry.code, x + 22, y);
ctx.font = '15px "Geist", system-ui, sans-serif';
ctx.fillStyle = '#8a877d';
ctx.fillText(`${entry.count} 颗`, x + 22 + ctx.measureText(entry.code).width + 14, y);
});
return canvas;
}
/** Trigger a browser download for a canvas as PNG. */
export function downloadCanvas(canvas: HTMLCanvasElement, filename: string): void {
canvas.toBlob((blob) => {
if (!blob) return;
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}, 'image/png');
}
+217
View File
@@ -0,0 +1,217 @@
/**
* Full image-to-beads pattern pipeline.
*
* Reverse-engineered competitor algorithm:
* 1. 4× supersampled canvas (gridSize × 4), draw image centered, fill rest white.
* 2. Per-cell 4×4 block color bucketing: quantize each pixel by /24, take
* majority bucket average as the cell color.
* 3. Optional background removal via edge-BFS (see `background.ts`).
* 4. k-means++ quantization (5 iterations) to reduce to `maxColors`.
* 5. Map each cluster centroid to the nearest MARD palette color.
* 6. Count beads per color, build the result grid.
*/
import { srgbToLab, type Lab3, type Rgb3 } from './lab.js';
import { kMeansQuantize } from './quantize.js';
import { removeBackground } from './background.js';
import { findNearestColor, MARD_PALETTE, type MardColor } from './mard-palette.js';
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface ProcessedCell {
x: number;
y: number;
rgb: Rgb3;
lab: readonly [number, number, number];
code: string;
empty: boolean;
}
export interface ProcessedPaletteEntry {
code: string;
hex: string;
rgb: Rgb3;
count: number;
}
export interface ProcessOptions {
/** Grid dimension (e.g. 32 → 32×32 grid). */
gridSize: number;
/** Maximum number of distinct colors after quantization. */
maxColors: number;
/** Whether to remove background. */
removeBg: boolean;
/** LAB distance threshold for background removal (default 20). */
bgThreshold: number;
}
export interface ProcessResult {
/** Flattened grid (row-major). */
grid: ProcessedCell[];
/** Color palette used, sorted by count descending. */
palette: ProcessedPaletteEntry[];
/** Total number of non-empty beads. */
totalBeads: number;
}
// ---------------------------------------------------------------------------
// Pipeline
// ---------------------------------------------------------------------------
const CELL_BLOCK = 4; // 4×4 pixels per cell in the supersampled canvas
const BUCKET_BITS = 24; // RGB quantization bucket size for per-cell bucketing
/**
* Run the full image-to-beads pattern pipeline.
*
* @param imageData - Raw pixel data from the supersampled canvas (4× per cell).
* @param options - Pipeline configuration.
* @returns Processed grid, palette, and bead count.
*/
export function processImage(
imageData: ImageData,
options: ProcessOptions,
): ProcessResult {
const { gridSize, maxColors, removeBg, bgThreshold } = options;
const data = imageData.data;
const supersampledSize = gridSize * CELL_BLOCK;
// ---- 1. Per-cell 4×4 block bucketing /24 ----
const cellColors: Rgb3[] = [];
for (let cellY = 0; cellY < gridSize; cellY++) {
for (let cellX = 0; cellX < gridSize; cellX++) {
const bucketMap = new Map<string, { sum: [number, number, number]; n: number }>();
for (let dy = 0; dy < CELL_BLOCK; dy++) {
for (let dx = 0; dx < CELL_BLOCK; dx++) {
const px = (cellY * CELL_BLOCK + dy) * supersampledSize + (cellX * CELL_BLOCK + dx);
const i = px * 4;
const r = data[i] as number;
const g = data[i + 1] as number;
const b = data[i + 2] as number;
const key = `${Math.round(r / BUCKET_BITS)}-${Math.round(g / BUCKET_BITS)}-${Math.round(b / BUCKET_BITS)}`;
const entry = bucketMap.get(key) ?? { sum: [0, 0, 0] as [number, number, number], n: 0 };
entry.sum[0] += r;
entry.sum[1] += g;
entry.sum[2] += b;
entry.n++;
bucketMap.set(key, entry);
}
}
// Take the majority bucket
let majority: { sum: [number, number, number]; n: number } | undefined;
let maxCount = 0;
for (const entry of bucketMap.values()) {
if (entry.n > maxCount) {
maxCount = entry.n;
majority = entry;
}
}
if (majority && majority.n > 0) {
cellColors.push([
Math.round(majority.sum[0] / majority.n),
Math.round(majority.sum[1] / majority.n),
Math.round(majority.sum[2] / majority.n),
]);
} else {
cellColors.push([244, 241, 232]); // fallback white
}
}
}
// ---- 2. Convert cell colors to LAB (used for quantization + mapping) ----
const cellLab: Lab3[] = cellColors.map(srgbToLab);
// ---- 3. Optional background removal ----
let backgroundIndices: Set<number>;
if (removeBg) {
backgroundIndices = removeBackground(cellColors, gridSize, bgThreshold);
} else {
backgroundIndices = new Set();
}
// ---- 4. Filter out background pixels for quantization ----
const foregroundColors = cellColors.filter((_, i) => !backgroundIndices.has(i));
// ---- 5. Convert to LAB and quantize ----
const foregroundLab = foregroundColors.map(srgbToLab);
const centroids = kMeansQuantize(
foregroundLab,
Math.min(maxColors, foregroundLab.length),
);
// ---- 6. Map each centroid to nearest MARD color (deduplicated) ----
const mardColors: MardColor[] = [];
const seenCodes = new Set<string>();
for (const centroid of centroids) {
const mard = findNearestColor(centroid, MARD_PALETTE);
if (!seenCodes.has(mard.code)) {
seenCodes.add(mard.code);
mardColors.push(mard);
}
}
// If quantization produced no colors, fall back to the full palette.
const activePalette = mardColors.length > 0 ? mardColors : MARD_PALETTE;
// ---- 7. Build result grid with bead counts ----
const grid: ProcessedCell[] = [];
const colorCount = new Map<string, number>();
for (let i = 0; i < cellColors.length; i++) {
const x = i % gridSize;
const y = Math.floor(i / gridSize);
if (backgroundIndices.has(i)) {
grid.push({
x,
y,
rgb: cellColors[i]!,
lab: cellLab[i]!,
code: '',
empty: true,
});
continue;
}
// Map pixel to nearest MARD color from the active palette.
const mard = findNearestColor(cellLab[i]!, activePalette);
const count = colorCount.get(mard.code) ?? 0;
colorCount.set(mard.code, count + 1);
grid.push({
x,
y,
rgb: mard.rgb,
lab: mard.lab,
code: mard.code,
empty: false,
});
}
// Build palette sorted by count descending
const palette: ProcessedPaletteEntry[] = [];
for (const [code, count] of colorCount) {
const mard = MARD_PALETTE.find((m) => m.code === code);
if (mard) {
palette.push({
code: mard.code,
hex: mard.hex,
rgb: mard.rgb,
count,
});
}
}
palette.sort((a, b) => b.count - a.count);
return {
grid,
palette,
totalBeads: grid.filter((c) => !c.empty).length,
};
}
+28
View File
@@ -0,0 +1,28 @@
/**
* PERLER LAB algorithm library — barrel export.
*
* Exposes the full image-to-beads pipeline:
* CIE LAB color math → k-means quantization → background removal →
* MARD palette matching → pattern rendering.
*/
export { srgbToLab, labDistance } from './lab.js';
export type { RGB, Lab, Rgb3, Lab3 } from './lab.js';
export { kMeansQuantize } from './quantize.js';
export { removeBackground } from './background.js';
export { MARD_PALETTE, findNearestColor, nearestColorFromRgb } from './mard-palette.js';
export type { MardColor } from './mard-palette-data.js';
export { processImage } from './image-processor.js';
export type {
ProcessedCell,
ProcessedPaletteEntry,
ProcessOptions,
ProcessResult,
} from './image-processor.js';
export { renderPattern, drawPaletteLegend, rgbToCss } from './pattern-renderer.js';
export type { PatternRenderOptions, LegendRenderOptions } from './pattern-renderer.js';
+76
View File
@@ -0,0 +1,76 @@
/**
* CIE LAB color space utilities.
*
* Implements the standard sRGB → CIE LAB (D65 white point) conversion, using
* the gamma 2.4 / 12.92 linearization with the classic 0.4124/0.3576/0.1805
* XYZ matrix, and the D65 reference white (0.95047, 1.00000, 1.08883).
*
* This is a deliberate 1:1 match of the reverse-engineered competitor
* algorithm (see the `o` function in the competitor chunk).
*/
export type RGB = readonly [number, number, number];
export type Lab = readonly [number, number, number];
/** Concrete (non-readonly) tuple aliases used across the pipeline. */
export type Rgb3 = RGB;
export type Lab3 = Lab;
/** Gamma threshold: values below this are treated as linear (sRGB). */
const EPSILON = 0.04045;
/** LAB cube-root threshold. */
const KAPPA_1 = 0.008856;
const KAPPA_2 = 7.787;
const DELTA = 16 / 116;
/** D65 reference white. */
const XN = 0.95047;
const ZN = 1.08883;
/**
* Linearize a single sRGB channel (0..255) using the standard transfer
* function: ((c/255 + 0.055)/1.055)^2.4 when c/255 > 0.04045, else (c/255)/12.92.
*/
function linearizeChannel(v: number): number {
const c = v / 255;
return c > EPSILON ? Math.pow((c + 0.055) / 1.055, 2.4) : c / 12.92;
}
/**
* f(t) helper for LAB: t^(1/3) when t > 0.008856, else 7.787t + 16/116.
*/
function pivot(t: number): number {
return t > KAPPA_1 ? Math.cbrt(t) : KAPPA_2 * t + DELTA;
}
/**
* Convert an sRGB color (channels 0..255) to CIE LAB (D65).
* Returns L in [0,100], a/b typically in [-128,127].
*/
export function srgbToLab(rgb: RGB): Lab {
const [r, g, b] = rgb;
const lr = linearizeChannel(r);
const lg = linearizeChannel(g);
const lb = linearizeChannel(b);
// sRGB → XYZ using the classic matrix (D65).
let x = (0.4124 * lr + 0.3576 * lg + 0.1805 * lb) / XN;
let y = 0.2126 * lr + 0.7152 * lg + 0.0722 * lb;
let z = (0.0193 * lr + 0.1192 * lg + 0.9505 * lb) / ZN;
x = pivot(x);
y = pivot(y);
z = pivot(z);
return [116 * y - 16, 500 * (x - y), 200 * (y - z)];
}
/**
* Euclidean distance between two colors in LAB space.
*/
export function labDistance(a: Lab, b: Lab): number {
const dl = a[0] - b[0];
const da = a[1] - b[1];
const db = a[2] - b[2];
return Math.sqrt(dl * dl + da * da + db * db);
}
+236
View File
@@ -0,0 +1,236 @@
/**
* MARD 拼豆色板 — all colors, extracted from the competitor bundle.
*
* Each entry carries the MARD code, hex, sRGB and precomputed CIE LAB (D65) values.
*/
export interface MardColor {
code: string;
hex: string;
rgb: [number, number, number];
lab: [number, number, number];
}
export const MARD_PALETTE: readonly MardColor[] = [
{ code: 'A1', hex: '#FAF4C8', rgb: [250, 244, 200], lab: [95.66, -4.93, 21.96] },
{ code: 'A2', hex: '#FFFFD5', rgb: [255, 255, 213], lab: [99.06, -6.76, 20.12] },
{ code: 'A3', hex: '#FEFF8B', rgb: [254, 255, 139], lab: [97.82, -15.97, 54.96] },
{ code: 'A4', hex: '#FBED56', rgb: [251, 237, 86], lab: [92.46, -12.26, 71.82] },
{ code: 'A5', hex: '#F4D738', rgb: [244, 215, 56], lab: [86.07, -5.56, 75.99] },
{ code: 'A6', hex: '#FEAC4C', rgb: [254, 172, 76], lab: [76.74, 21.74, 59.67] },
{ code: 'A7', hex: '#FE8B4C', rgb: [254, 139, 76], lab: [69.51, 38.81, 51.92] },
{ code: 'A8', hex: '#FFDA45', rgb: [255, 218, 69], lab: [87.89, -1.95, 73.7] },
{ code: 'A9', hex: '#FF995B', rgb: [255, 153, 91], lab: [72.76, 32.86, 48.22] },
{ code: 'A10', hex: '#F77C31', rgb: [247, 124, 49], lab: [65.29, 42.53, 59.59] },
{ code: 'A11', hex: '#FFDD99', rgb: [255, 221, 153], lab: [89.52, 2.74, 37.71] },
{ code: 'A12', hex: '#FE9F72', rgb: [254, 159, 114], lab: [74.24, 30.96, 38.16] },
{ code: 'A13', hex: '#FFC365', rgb: [255, 195, 101], lab: [82.5, 11.61, 54.64] },
{ code: 'A14', hex: '#FD543D', rgb: [253, 84, 61], lab: [59.49, 62.92, 48.58] },
{ code: 'A15', hex: '#FFF365', rgb: [255, 243, 101], lab: [94.44, -12.69, 67.97] },
{ code: 'A16', hex: '#FFFF9F', rgb: [255, 255, 159], lab: [98.15, -13.6, 45.86] },
{ code: 'A17', hex: '#FFE36E', rgb: [255, 227, 110], lab: [90.47, -4.14, 59.64] },
{ code: 'A18', hex: '#FEBE7D', rgb: [254, 190, 125], lab: [81.5, 15.67, 41.61] },
{ code: 'A19', hex: '#FD7C72', rgb: [253, 124, 114], lab: [66.91, 48.27, 28.71] },
{ code: 'A20', hex: '#FFD568', rgb: [255, 213, 104], lab: [86.92, 2.53, 58.31] },
{ code: 'A21', hex: '#FFE395', rgb: [255, 227, 149], lab: [90.95, -0.73, 41.57] },
{ code: 'A22', hex: '#F4F57D', rgb: [244, 245, 125], lab: [94.32, -16.24, 57.07] },
{ code: 'A23', hex: '#E6C9B7', rgb: [230, 201, 183], lab: [82.92, 7.4, 12.74] },
{ code: 'A24', hex: '#F7F8A2', rgb: [247, 248, 162], lab: [95.8, -12.87, 41.25] },
{ code: 'A25', hex: '#FFD67D', rgb: [255, 214, 125], lab: [87.4, 3.64, 48.96] },
{ code: 'A26', hex: '#FFC830', rgb: [255, 200, 48], lab: [83.33, 6.49, 76.38] },
{ code: 'B1', hex: '#E6EE31', rgb: [230, 238, 49], lab: [90.87, -22.94, 81.8] },
{ code: 'B2', hex: '#63F347', rgb: [99, 243, 71], lab: [85.61, -68.55, 67.68] },
{ code: 'B3', hex: '#9EF780', rgb: [158, 247, 128], lab: [89.56, -48, 48.66] },
{ code: 'B4', hex: '#5DE035', rgb: [93, 224, 53], lab: [79.55, -64.72, 67.6] },
{ code: 'B5', hex: '#35E352', rgb: [53, 227, 82], lab: [79.79, -70.71, 56.94] },
{ code: 'B6', hex: '#65E2A6', rgb: [101, 226, 166], lab: [81.79, -48.55, 19.01] },
{ code: 'B7', hex: '#3DAF80', rgb: [61, 175, 128], lab: [64.33, -43.26, 14.87] },
{ code: 'B8', hex: '#1C9C4F', rgb: [28, 156, 79], lab: [56.67, -50.58, 30.99] },
{ code: 'B9', hex: '#27523A', rgb: [39, 82, 58], lab: [31.28, -21.35, 9.58] },
{ code: 'B10', hex: '#95D3C2', rgb: [149, 211, 194], lab: [80.11, -23.33, 2.08] },
{ code: 'B11', hex: '#5D722A', rgb: [93, 114, 42], lab: [44.98, -19.57, 36.42] },
{ code: 'B12', hex: '#166F41', rgb: [22, 111, 65], lab: [41.09, -36.8, 18.56] },
{ code: 'B13', hex: '#CAEB7B', rgb: [202, 235, 123], lab: [88.64, -27.81, 50.46] },
{ code: 'B14', hex: '#ADE946', rgb: [173, 233, 70], lab: [85.81, -42.1, 69.25] },
{ code: 'B15', hex: '#2E5132', rgb: [46, 81, 50], lab: [31.1, -20.23, 14.37] },
{ code: 'B16', hex: '#C5ED9C', rgb: [197, 237, 156], lab: [89.32, -26.69, 35.11] },
{ code: 'B17', hex: '#9BB13A', rgb: [155, 177, 58], lab: [68.55, -23.98, 55.85] },
{ code: 'B18', hex: '#E6EE49', rgb: [230, 238, 73], lab: [90.99, -21.97, 74.59] },
{ code: 'B19', hex: '#24B88C', rgb: [36, 184, 140], lab: [66.94, -47.72, 11.89] },
{ code: 'B20', hex: '#C2F0CC', rgb: [194, 240, 204], lab: [90.85, -21.61, 12.58] },
{ code: 'B21', hex: '#156A6B', rgb: [21, 106, 107], lab: [40.46, -23.16, -7.55] },
{ code: 'B22', hex: '#0B3C43', rgb: [11, 60, 67], lab: [22.68, -12.92, -8.9] },
{ code: 'B23', hex: '#303A21', rgb: [48, 58, 33], lab: [22.88, -9.44, 14.2] },
{ code: 'B24', hex: '#EEFCA5', rgb: [238, 252, 165], lab: [96.21, -17.83, 40.18] },
{ code: 'B25', hex: '#4E846D', rgb: [78, 132, 109], lab: [50.95, -23.56, 6.83] },
{ code: 'B26', hex: '#8D7A35', rgb: [141, 122, 53], lab: [51.65, -1.4, 39.63] },
{ code: 'B27', hex: '#CCE1AF', rgb: [204, 225, 175], lab: [86.89, -15.61, 22.19] },
{ code: 'B28', hex: '#9EE5B9', rgb: [158, 229, 185], lab: [85.41, -31.13, 14.49] },
{ code: 'B29', hex: '#C5E254', rgb: [197, 226, 84], lab: [85.45, -28.83, 64.01] },
{ code: 'B30', hex: '#E2FCB1', rgb: [226, 252, 177], lab: [95.57, -20.68, 33.21] },
{ code: 'B31', hex: '#B0E792', rgb: [176, 231, 146], lab: [86.23, -32.6, 35.85] },
{ code: 'B32', hex: '#9CAB5A', rgb: [156, 171, 90], lab: [67.23, -17.85, 39.71] },
{ code: 'C1', hex: '#E8FFE7', rgb: [232, 255, 231], lab: [97.81, -11.77, 8.92] },
{ code: 'C2', hex: '#A9F9FC', rgb: [169, 249, 252], lab: [93.11, -23.52, -9.21] },
{ code: 'C3', hex: '#A0E2FB', rgb: [160, 226, 251], lab: [86.42, -14.69, -18.75] },
{ code: 'C4', hex: '#41CCFF', rgb: [65, 204, 255], lab: [77, -20.55, -35.57] },
{ code: 'C5', hex: '#01ACEB', rgb: [1, 172, 235], lab: [66.14, -14.54, -41.72] },
{ code: 'C6', hex: '#50AAF0', rgb: [80, 170, 240], lab: [67.09, -5.25, -42.88] },
{ code: 'C7', hex: '#3677D2', rgb: [54, 119, 210], lab: [50.25, 10.58, -52.89] },
{ code: 'C8', hex: '#0F54C0', rgb: [15, 84, 192], lab: [38.28, 22.85, -61.9] },
{ code: 'C9', hex: '#324BCA', rgb: [50, 75, 202], lab: [37.8, 35.23, -68.47] },
{ code: 'C10', hex: '#3EBCE2', rgb: [62, 188, 226], lab: [71.2, -21.99, -28.89] },
{ code: 'C11', hex: '#28DDDE', rgb: [40, 221, 222], lab: [80.43, -41.19, -12.77] },
{ code: 'C12', hex: '#1C334D', rgb: [28, 51, 77], lab: [20.64, 0.14, -18.71] },
{ code: 'C13', hex: '#CDE8FF', rgb: [205, 232, 255], lab: [90.74, -4.12, -14.09] },
{ code: 'C14', hex: '#D5FDFF', rgb: [213, 253, 255], lab: [96.66, -12.32, -5.24] },
{ code: 'C15', hex: '#22C4C6', rgb: [34, 196, 198], lab: [72.16, -37.34, -12.23] },
{ code: 'C16', hex: '#1557A8', rgb: [21, 87, 168], lab: [37.49, 11.52, -49.05] },
{ code: 'C17', hex: '#04D1F6', rgb: [4, 209, 246], lab: [77.45, -29.71, -30.13] },
{ code: 'C18', hex: '#1D3344', rgb: [29, 51, 68], lab: [20.23, -2.96, -13.27] },
{ code: 'C19', hex: '#1887A2', rgb: [24, 135, 162], lab: [51.98, -19.5, -22.66] },
{ code: 'C20', hex: '#176DAF', rgb: [23, 109, 175], lab: [44.54, 0.32, -41.88] },
{ code: 'C21', hex: '#BEDDFF', rgb: [190, 221, 255], lab: [86.94, -2.86, -19.9] },
{ code: 'C22', hex: '#67B4BE', rgb: [103, 180, 190], lab: [68.93, -21.12, -12.51] },
{ code: 'C23', hex: '#C8E2FF', rgb: [200, 226, 255], lab: [88.87, -2.52, -16.93] },
{ code: 'C24', hex: '#7CC4FF', rgb: [124, 196, 255], lab: [76.67, -6.59, -35.93] },
{ code: 'C25', hex: '#A9E5E5', rgb: [169, 229, 229], lab: [87.06, -18.86, -6.16] },
{ code: 'C26', hex: '#3CAED8', rgb: [60, 174, 216], lab: [66.67, -18.19, -30.42] },
{ code: 'C27', hex: '#D3DFFA', rgb: [211, 223, 250], lab: [88.7, 1.34, -14.49] },
{ code: 'C28', hex: '#BBCFED', rgb: [187, 207, 237], lab: [82.54, -0.43, -17.02] },
{ code: 'C29', hex: '#34488E', rgb: [52, 72, 142], lab: [32.52, 15.47, -41.29] },
{ code: 'D1', hex: '#AEB4F2', rgb: [174, 180, 242], lab: [74.86, 11.47, -31.5] },
{ code: 'D2', hex: '#858EDD', rgb: [133, 142, 221], lab: [61.27, 16.22, -41.35] },
{ code: 'D3', hex: '#2F54AF', rgb: [47, 84, 175], lab: [37.91, 19, -52.47] },
{ code: 'D4', hex: '#182A84', rgb: [24, 42, 132], lab: [22, 28.05, -52.24] },
{ code: 'D5', hex: '#B843C5', rgb: [184, 67, 197], lab: [49.78, 63.76, -45.54] },
{ code: 'D6', hex: '#AC7BDE', rgb: [172, 123, 222], lab: [60.08, 38.08, -43.55] },
{ code: 'D7', hex: '#8854B3', rgb: [136, 84, 179], lab: [45.4, 39.81, -42.43] },
{ code: 'D8', hex: '#E2D3FF', rgb: [226, 211, 255], lab: [86.99, 13.38, -19.58] },
{ code: 'D9', hex: '#D5B9F8', rgb: [213, 185, 248], lab: [79.4, 21.81, -27.49] },
{ code: 'D10', hex: '#361851', rgb: [54, 24, 81], lab: [15.65, 27.23, -29.2] },
{ code: 'D11', hex: '#B9BAE1', rgb: [185, 186, 225], lab: [76.6, 7.58, -19.57] },
{ code: 'D12', hex: '#DE9AD4', rgb: [222, 154, 212], lab: [71.82, 34.45, -19.4] },
{ code: 'D13', hex: '#B90095', rgb: [185, 0, 149], lab: [41.98, 72.3, -29.46] },
{ code: 'D14', hex: '#8B279B', rgb: [139, 39, 155], lab: [36.57, 56.72, -42.19] },
{ code: 'D15', hex: '#2F1F90', rgb: [47, 31, 144], lab: [22.3, 41.44, -59.2] },
{ code: 'D16', hex: '#E3E1EE', rgb: [227, 225, 238], lab: [90.02, 3.05, -6.09] },
{ code: 'D17', hex: '#C4D4F6', rgb: [196, 212, 246], lab: [84.73, 1.64, -18.45] },
{ code: 'D18', hex: '#A45EC7', rgb: [164, 94, 199], lab: [51.86, 46.49, -43.56] },
{ code: 'D19', hex: '#D8C3D7', rgb: [216, 195, 215], lab: [81.04, 10.9, -7.28] },
{ code: 'D20', hex: '#9C32B2', rgb: [156, 50, 178], lab: [42.1, 60.64, -46.95] },
{ code: 'D21', hex: '#9A009B', rgb: [154, 0, 155], lab: [36.44, 67.58, -42.26] },
{ code: 'D22', hex: '#333A95', rgb: [51, 58, 149], lab: [29.16, 27.21, -51.02] },
{ code: 'D23', hex: '#EBDAFC', rgb: [235, 218, 252], lab: [89.31, 11.97, -14.43] },
{ code: 'D24', hex: '#7786E5', rgb: [119, 134, 229], lab: [58.63, 19.79, -50.03] },
{ code: 'D25', hex: '#494FC7', rgb: [73, 79, 199], lab: [39.8, 34.7, -63.4] },
{ code: 'D26', hex: '#DFC2F8', rgb: [223, 194, 248], lab: [82.41, 20.09, -22.83] },
{ code: 'E1', hex: '#FDD3CC', rgb: [253, 211, 204], lab: [87.89, 13.63, 8.96] },
{ code: 'E2', hex: '#FEC0DF', rgb: [254, 192, 223], lab: [84.02, 26.88, -6.77] },
{ code: 'E3', hex: '#FFB7E7', rgb: [255, 183, 231], lab: [82.32, 33.24, -13.56] },
{ code: 'E4', hex: '#E8649E', rgb: [232, 100, 158], lab: [60.55, 56.85, -5.77] },
{ code: 'E5', hex: '#F551A2', rgb: [245, 81, 162], lab: [59.8, 68.98, -8.98] },
{ code: 'E6', hex: '#F13D74', rgb: [241, 61, 116], lab: [55.38, 70.42, 11.59] },
{ code: 'E7', hex: '#C63478', rgb: [198, 52, 120], lab: [46.73, 61.92, -4.28] },
{ code: 'E8', hex: '#FFDBE9', rgb: [255, 219, 233], lab: [90.69, 14.71, -2.22] },
{ code: 'E9', hex: '#E970CC', rgb: [233, 112, 204], lab: [64.38, 57.96, -26.2] },
{ code: 'E10', hex: '#D33793', rgb: [211, 55, 147], lab: [50.32, 67.31, -14.99] },
{ code: 'E11', hex: '#FCDDD2', rgb: [252, 221, 210], lab: [90.35, 8.98, 9.32] },
{ code: 'E12', hex: '#F78FC3', rgb: [247, 143, 195], lab: [71.8, 45.73, -9.76] },
{ code: 'E13', hex: '#B5006D', rgb: [181, 0, 109], lab: [39.46, 67.09, -8.65] },
{ code: 'E14', hex: '#FFD1BA', rgb: [255, 209, 186], lab: [87.2, 12.88, 17.49] },
{ code: 'E15', hex: '#F8C7C9', rgb: [248, 199, 201], lab: [84.49, 17.67, 5.61] },
{ code: 'E16', hex: '#FFF3EB', rgb: [255, 243, 235], lab: [96.56, 2.69, 5.28] },
{ code: 'E17', hex: '#FFE2EA', rgb: [255, 226, 234], lab: [92.4, 11.25, -0.25] },
{ code: 'E18', hex: '#FFC7DB', rgb: [255, 199, 219], lab: [85.62, 22.91, -2.27] },
{ code: 'E19', hex: '#FEBAD5', rgb: [254, 186, 213], lab: [82.37, 28.45, -3.83] },
{ code: 'E20', hex: '#D8C7D1', rgb: [216, 199, 209], lab: [81.86, 7.68, -2.84] },
{ code: 'E21', hex: '#BD9DA1', rgb: [189, 157, 161], lab: [67.65, 12.47, 2.35] },
{ code: 'E22', hex: '#B785A1', rgb: [183, 133, 161], lab: [61.15, 23.62, -7.29] },
{ code: 'E23', hex: '#937A8D', rgb: [147, 122, 141], lab: [54.07, 13.1, -6.67] },
{ code: 'E24', hex: '#E1BCE8', rgb: [225, 188, 232], lab: [80.63, 20.83, -16.94] },
{ code: 'F1', hex: '#FD957B', rgb: [253, 149, 123], lab: [72.1, 36.49, 30.57] },
{ code: 'F2', hex: '#FC3D46', rgb: [252, 61, 70], lab: [56.56, 70.84, 40.45] },
{ code: 'F3', hex: '#F74941', rgb: [247, 73, 65], lab: [57, 65.26, 43.46] },
{ code: 'F4', hex: '#FC283C', rgb: [252, 40, 60], lab: [54.59, 75.7, 43.84] },
{ code: 'F5', hex: '#E7002F', rgb: [231, 0, 47], lab: [48.5, 75.04, 43.4] },
{ code: 'F6', hex: '#943630', rgb: [148, 54, 48], lab: [36.27, 39.18, 24.64] },
{ code: 'F7', hex: '#971937', rgb: [151, 25, 55], lab: [33.03, 51.46, 16.19] },
{ code: 'F8', hex: '#BC0028', rgb: [188, 0, 40], lab: [39.32, 64.42, 35.05] },
{ code: 'F9', hex: '#E2677A', rgb: [226, 103, 122], lab: [59.23, 49.58, 13.09] },
{ code: 'F10', hex: '#8A4526', rgb: [138, 69, 38], lab: [37.48, 26.83, 31.52] },
{ code: 'F11', hex: '#5A2121', rgb: [90, 33, 33], lab: [21.47, 26.26, 13.43] },
{ code: 'F12', hex: '#FD4E6A', rgb: [253, 78, 106], lab: [59.32, 67.45, 23.22] },
{ code: 'F13', hex: '#F35744', rgb: [243, 87, 68], lab: [58.31, 58.76, 43.11] },
{ code: 'F14', hex: '#FFA9AD', rgb: [255, 169, 173], lab: [77.67, 32.13, 11.02] },
{ code: 'F15', hex: '#D30022', rgb: [211, 0, 34], lab: [44.18, 69.9, 44.89] },
{ code: 'F16', hex: '#FEC2A6', rgb: [254, 194, 166], lab: [83.13, 17.81, 22.39] },
{ code: 'F17', hex: '#E69C79', rgb: [230, 156, 121], lab: [70.86, 23.71, 29.51] },
{ code: 'F18', hex: '#D37C46', rgb: [211, 124, 70], lab: [60.52, 29.15, 43.29] },
{ code: 'F19', hex: '#C1444A', rgb: [193, 68, 74], lab: [46.93, 50.37, 23.95] },
{ code: 'F20', hex: '#CD9391', rgb: [205, 147, 145], lab: [66.44, 21.6, 9.76] },
{ code: 'F21', hex: '#F7B4C6', rgb: [247, 180, 198], lab: [79.89, 26.89, 0.54] },
{ code: 'F22', hex: '#FDC0D0', rgb: [253, 192, 208], lab: [83.51, 24.19, 0.51] },
{ code: 'F23', hex: '#F67E66', rgb: [246, 126, 102], lab: [66.12, 43.85, 34.11] },
{ code: 'F24', hex: '#E698AA', rgb: [230, 152, 170], lab: [71, 31.63, 2.72] },
{ code: 'F25', hex: '#E54B4F', rgb: [229, 75, 79], lab: [54.3, 59.57, 31.62] },
{ code: 'G1', hex: '#FFE2CE', rgb: [255, 226, 206], lab: [91.73, 6.88, 13.41] },
{ code: 'G2', hex: '#FFC4AA', rgb: [255, 196, 170], lab: [83.78, 17.63, 21.19] },
{ code: 'G3', hex: '#F4C3A5', rgb: [244, 195, 165], lab: [82.37, 13.36, 21.72] },
{ code: 'G4', hex: '#E1B383', rgb: [225, 179, 131], lab: [76, 10.46, 30.83] },
{ code: 'G5', hex: '#EDB045', rgb: [237, 176, 69], lab: [75.75, 12.21, 61.08] },
{ code: 'G6', hex: '#E99C17', rgb: [233, 156, 23], lab: [70.29, 19.62, 71.22] },
{ code: 'G7', hex: '#9D5B3E', rgb: [157, 91, 62], lab: [45.63, 24.19, 28.19] },
{ code: 'G8', hex: '#753832', rgb: [117, 56, 50], lab: [31.44, 26.13, 16.17] },
{ code: 'G9', hex: '#E6B483', rgb: [230, 180, 131], lab: [76.74, 11.93, 31.9] },
{ code: 'G10', hex: '#D98C39', rgb: [217, 140, 57], lab: [64.81, 22.39, 54.34] },
{ code: 'G11', hex: '#E0C593', rgb: [224, 197, 147], lab: [80.68, 2.39, 28.61] },
{ code: 'G12', hex: '#FFC890', rgb: [255, 200, 144], lab: [84.27, 12.64, 35.45] },
{ code: 'G13', hex: '#B7714A', rgb: [183, 113, 74], lab: [54.42, 23.81, 33.05] },
{ code: 'G14', hex: '#8D614C', rgb: [141, 97, 76], lab: [45.27, 15.2, 19.14] },
{ code: 'G15', hex: '#FCF9E0', rgb: [252, 249, 224], lab: [97.56, -3.14, 12.35] },
{ code: 'G16', hex: '#F2D9BA', rgb: [242, 217, 186], lab: [87.99, 3.92, 18.43] },
{ code: 'G17', hex: '#78524B', rgb: [120, 82, 75], lab: [38.79, 14.91, 10.5] },
{ code: 'G18', hex: '#FFE4CC', rgb: [255, 228, 204], lab: [92.18, 5.57, 15.08] },
{ code: 'G19', hex: '#E07935', rgb: [224, 121, 53], lab: [61.46, 35.16, 53.05] },
{ code: 'G20', hex: '#A94023', rgb: [169, 64, 35], lab: [41.57, 41.62, 39.02] },
{ code: 'G21', hex: '#B88558', rgb: [184, 133, 88], lab: [59.59, 14.3, 31.85] },
{ code: 'H1', hex: '#FDFBFF', rgb: [253, 251, 255], lab: [98.87, 1.37, -1.69] },
{ code: 'H2', hex: '#FEFFFF', rgb: [254, 255, 255], lab: [99.93, -0.32, -0.13] },
{ code: 'H3', hex: '#B6B1BA', rgb: [182, 177, 186], lab: [72.85, 3.46, -3.96] },
{ code: 'H4', hex: '#89858C', rgb: [137, 133, 140], lab: [56.07, 2.88, -3.23] },
{ code: 'H5', hex: '#48464E', rgb: [72, 70, 78], lab: [30.18, 2.64, -4.49] },
{ code: 'H6', hex: '#2F2B2F', rgb: [47, 43, 47], lab: [18.09, 2.74, -1.94] },
{ code: 'H7', hex: '#000000', rgb: [0, 0, 0], lab: [0, 0, 0] },
{ code: 'H8', hex: '#E7D6DB', rgb: [231, 214, 219], lab: [87.09, 6.71, -0.35] },
{ code: 'H9', hex: '#EDEDED', rgb: [237, 237, 237], lab: [93.75, 0, -0.01] },
{ code: 'H10', hex: '#EEE9EA', rgb: [238, 233, 234], lab: [92.75, 1.86, 0.1] },
{ code: 'H11', hex: '#CECDD5', rgb: [206, 205, 213], lab: [82.69, 1.83, -3.85] },
{ code: 'H12', hex: '#FFF5ED', rgb: [255, 245, 237], lab: [97.1, 2, 5.03] },
{ code: 'H13', hex: '#F5ECD2', rgb: [245, 236, 210], lab: [93.48, -1.2, 13.69] },
{ code: 'H14', hex: '#CFD7D3', rgb: [207, 215, 211], lab: [85.29, -3.44, 1.02] },
{ code: 'H15', hex: '#98A6A8', rgb: [152, 166, 168], lab: [67.11, -4.5, -2.73] },
{ code: 'H16', hex: '#1D1414', rgb: [29, 20, 20], lab: [7.33, 4.53, 1.6] },
{ code: 'H17', hex: '#F1EDED', rgb: [241, 237, 237], lab: [94.05, 1.34, 0.46] },
{ code: 'H18', hex: '#FFFDF0', rgb: [255, 253, 240], lab: [99.14, -1.54, 6.44] },
{ code: 'H19', hex: '#F6EFE2', rgb: [246, 239, 226], lab: [94.66, 0.16, 7.11] },
{ code: 'H20', hex: '#949FA3', rgb: [148, 159, 163], lab: [64.75, -3.08, -3.43] },
{ code: 'H21', hex: '#FFFBE1', rgb: [255, 251, 225], lab: [98.31, -2.95, 12.93] },
{ code: 'H22', hex: '#CACAD4', rgb: [202, 202, 212], lab: [81.59, 1.87, -4.97] },
{ code: 'H23', hex: '#9A9D94', rgb: [154, 157, 148], lab: [64.26, -2.78, 4.32] },
{ code: 'M1', hex: '#BCC6B8', rgb: [188, 198, 184], lab: [78.78, -6.01, 5.82] },
{ code: 'M2', hex: '#8AA386', rgb: [138, 163, 134], lab: [64.42, -14.41, 12.21] },
{ code: 'M3', hex: '#697D80', rgb: [105, 125, 128], lab: [50.95, -6.58, -4.08] },
{ code: 'M4', hex: '#E3D2BC', rgb: [227, 210, 188], lab: [85.02, 2.34, 13.03] },
{ code: 'M5', hex: '#D0CCAA', rgb: [208, 204, 170], lab: [81.56, -4.23, 17.47] },
{ code: 'M6', hex: '#B0A782', rgb: [176, 167, 130], lab: [68.37, -2.74, 20.35] },
{ code: 'M7', hex: '#B4A497', rgb: [180, 164, 151], lab: [68.38, 3.61, 8.84] },
{ code: 'M8', hex: '#B38281', rgb: [179, 130, 129], lab: [59.1, 18.75, 8] },
{ code: 'M9', hex: '#A58767', rgb: [165, 135, 103], lab: [58.33, 6.8, 21.51] },
{ code: 'M10', hex: '#C5B2BC', rgb: [197, 178, 188], lab: [74.41, 8.55, -2.61] },
{ code: 'M11', hex: '#9F7594', rgb: [159, 117, 148], lab: [54.27, 21.7, -10.33] },
{ code: 'M12', hex: '#644749', rgb: [100, 71, 73], lab: [33.34, 12.75, 3.72] },
{ code: 'M13', hex: '#D19066', rgb: [209, 144, 102], lab: [65.33, 19.93, 32.14] },
{ code: 'M14', hex: '#C77362', rgb: [199, 115, 98], lab: [57.35, 31.26, 23.74] },
{ code: 'M15', hex: '#757D78', rgb: [117, 125, 120], lab: [51.62, -4, 1.69] },
];
+36
View File
@@ -0,0 +1,36 @@
/**
* MARD 拼豆色板 module — color matching against the full MARD palette.
*
* The palette data lives in `mard-palette-data.ts` (all 221 entries extracted
* from the competitor bundle; read from `competitor-analysis/mard-palette.json`).
*/
import { labDistance, srgbToLab, type Lab3 } from './lab.js';
import { MARD_PALETTE, type MardColor } from './mard-palette-data.js';
export type { MardColor } from './mard-palette-data.js';
export { MARD_PALETTE } from './mard-palette-data.js';
/**
* Find the palette entry whose LAB color is nearest to `lab` (Euclidean
* distance in CIE LAB space). Collisions resolve to the first palette entry.
*/
export function findNearestColor(lab: Lab3, palette: readonly MardColor[] = MARD_PALETTE): MardColor {
let best: MardColor = palette[0]!;
let bestDistance = Number.POSITIVE_INFINITY;
for (const entry of palette) {
const distance = labDistance(lab, entry.lab);
if (distance < bestDistance) {
bestDistance = distance;
best = entry;
}
}
return best;
}
/**
* Convenience: map an sRGB color directly to its nearest MARD entry.
*/
export function nearestColorFromRgb(rgb: readonly [number, number, number]): MardColor {
return findNearestColor(srgbToLab(rgb));
}
+121
View File
@@ -0,0 +1,121 @@
/**
* Pattern rendering — draws a processed bead grid onto a canvas 2D context.
*
* Cells are drawn as solid squares of their matched MARD color; empty
* (background-removed) cells are filled with the background color. An
* optional grid outline and a palette legend with bead counts are supported.
*/
import type { ProcessedCell, ProcessedPaletteEntry } from './image-processor.js';
export interface PatternRenderOptions {
/** Pixel size of one bead cell (default 20). */
cellSize?: number;
/** Fill color for empty / background cells (default '#FFFFFF'). */
backgroundColor?: string;
/** Stroke color for the cell grid (default 'rgba(0, 0, 0, 0.12)'). */
gridColor?: string;
/** Whether to draw cell outlines (default true). */
drawGrid?: boolean;
}
/**
* Render a processed bead grid onto `ctx`, resizing its canvas to
* `gridSize × gridSize` cells of `cellSize` pixels each.
*/
export function renderPattern(
ctx: CanvasRenderingContext2D,
grid: readonly ProcessedCell[],
gridSize: number,
options: PatternRenderOptions = {},
): void {
const cellSize = options.cellSize ?? 20;
const backgroundColor = options.backgroundColor ?? '#FFFFFF';
const gridColor = options.gridColor ?? 'rgba(0, 0, 0, 0.12)';
const drawGrid = options.drawGrid ?? true;
const canvas = ctx.canvas;
canvas.width = gridSize * cellSize;
canvas.height = gridSize * cellSize;
// Base coat: fill the whole canvas with the background color.
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
for (const cell of grid) {
const px = cell.x * cellSize;
const py = cell.y * cellSize;
if (cell.empty) {
// Background cells stay the background color.
ctx.fillStyle = backgroundColor;
ctx.fillRect(px, py, cellSize, cellSize);
} else {
ctx.fillStyle = rgbToCss(cell.rgb);
ctx.fillRect(px, py, cellSize, cellSize);
}
}
if (drawGrid) {
ctx.strokeStyle = gridColor;
ctx.lineWidth = 1;
ctx.beginPath();
for (let i = 1; i < gridSize; i++) {
const pos = i * cellSize;
ctx.moveTo(pos, 0);
ctx.lineTo(pos, canvas.height);
ctx.moveTo(0, pos);
ctx.lineTo(canvas.width, pos);
}
ctx.stroke();
}
}
export interface LegendRenderOptions {
/** Pixel size of each color swatch (default 16). */
swatchSize?: number;
/** Row height (default 20). */
rowHeight?: number;
/** Font for code + count text (default '12px sans-serif'). */
font?: string;
/** Text color (default '#111111'). */
textColor?: string;
}
/**
* Draw a color legend (swatch + code + bead count per palette entry)
* starting at the top-left of the canvas.
*/
export function drawPaletteLegend(
ctx: CanvasRenderingContext2D,
palette: readonly ProcessedPaletteEntry[],
options: LegendRenderOptions = {},
): void {
const swatchSize = options.swatchSize ?? 16;
const rowHeight = options.rowHeight ?? 20;
const font = options.font ?? '12px sans-serif';
const textColor = options.textColor ?? '#111111';
ctx.save();
ctx.font = font;
ctx.fillStyle = textColor;
palette.forEach((entry, i) => {
const y = i * rowHeight;
// Swatch
ctx.fillStyle = rgbToCss(entry.rgb);
ctx.fillRect(0, y, swatchSize, swatchSize);
ctx.strokeStyle = 'rgba(0, 0, 0, 0.3)';
ctx.strokeRect(0, y, swatchSize, swatchSize);
// Code + count
ctx.fillStyle = textColor;
ctx.fillText(`${entry.code} × ${entry.count}`, swatchSize + 6, y + swatchSize - 2);
});
ctx.restore();
}
/** Format an sRGB tuple as a CSS color string. */
export function rgbToCss(rgb: readonly [number, number, number]): string {
return `rgb(${Math.round(rgb[0])}, ${Math.round(rgb[1])}, ${Math.round(rgb[2])})`;
}
+97
View File
@@ -0,0 +1,97 @@
/**
* k-means quantization in LAB color space.
*
* Reverse-engineered competitor algorithm:
* - k-means++ initialization: first center = the pixel at the median-ish
* position of the (already LAB-transformed) color list (`r[Math.floor(len/2)]`
* with fallback `[50,0,0]`), then repeatedly pick the point with the maximum
* minimal distance to any existing center.
* - Exactly 5 iterations of assign-to-nearest-centroid + centroid recompute
* (average of members).
*/
import { labDistance, type Lab3 } from './lab.js';
const FALLBACK_CENTER: Lab3 = [50, 0, 0];
const ITERATIONS = 5;
/**
* Runs k-means on an array of LAB colors and returns the `maxColors` cluster
* centroids (also in LAB space). Fewer centroids than requested may be
* returned when there are fewer distinct points.
*/
export function kMeansQuantize(colors: Lab3[], maxColors: number): Lab3[] {
if (colors.length === 0 || maxColors <= 0) {
return [];
}
const k = Math.min(maxColors, colors.length);
// ---- k-means++ initialization ----
const centers: Lab3[] = [
colors[Math.floor(colors.length / 2)] ?? FALLBACK_CENTER,
];
while (centers.length < k) {
let bestDist = -1;
let bestPoint: Lab3 = colors[0] ?? FALLBACK_CENTER;
for (const point of colors) {
const minDist = minCenterDistance(point, centers);
if (minDist > bestDist) {
bestDist = minDist;
bestPoint = point;
}
}
centers.push(bestPoint);
}
// ---- iterate: assign + update (exactly 5 iterations) ----
for (let iter = 0; iter < ITERATIONS; iter++) {
const buckets: Lab3[][] = centers.map(() => []);
for (const point of colors) {
let bestIndex = 0;
let bestDist = Number.POSITIVE_INFINITY;
for (let i = 0; i < centers.length; i++) {
const d = labDistance(point, centers[i]!);
if (d < bestDist) {
bestDist = d;
bestIndex = i;
}
}
buckets[bestIndex]?.push(point);
}
for (let i = 0; i < buckets.length; i++) {
const bucket = buckets[i];
if (bucket && bucket.length > 0) {
centers[i] = average(bucket);
}
}
}
return centers;
}
/** Distance from `point` to the closest of the given centers. */
function minCenterDistance(point: Lab3, centers: Lab3[]): number {
let min = Number.POSITIVE_INFINITY;
for (const center of centers) {
const d = labDistance(point, center);
if (d < min) min = d;
}
return min;
}
/** Component-wise average of a non-empty list of LAB colors. */
function average(bucket: Lab3[]): Lab3 {
let l = 0;
let a = 0;
let b = 0;
for (const [cl, ca, cb] of bucket) {
l += cl;
a += ca;
b += cb;
}
const n = bucket.length;
return [l / n, a / n, b / n];
}
+149
View File
@@ -0,0 +1,149 @@
import { useEffect, useState } from 'react';
import { processImage, type ProcessResult } from './image-processor.js';
/** Pattern generation settings, mirroring the 01 生成设置 panel. */
export interface PatternSettings {
gridSize: number;
maxColors: number;
removeBg: boolean;
showGrid: boolean;
}
/** A successfully decoded source image. */
export interface SourceImage {
element: HTMLImageElement;
name: string;
/** Object URL for <img> thumbnails; caller revokes it on replace/unmount. */
url: string;
}
export interface PatternState {
result: ProcessResult | null;
processing: boolean;
error: string | null;
}
const SUPERSAMPLE = 4; // matches the library pipeline (gridSize × 4 canvas)
const BG_THRESHOLD = 20;
/** Draw the source image contain-fit centered on a white canvas, return ImageData. */
function sampleImageData(element: HTMLImageElement, gridSize: number): ImageData {
const size = gridSize * SUPERSAMPLE;
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) {
throw new Error('Canvas 2D context unavailable');
}
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, size, size);
const iw = element.naturalWidth;
const ih = element.naturalHeight;
const scale = Math.min(size / iw, size / ih);
const dw = iw * scale;
const dh = ih * scale;
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(element, (size - dw) / 2, (size - dh) / 2, dw, dh);
return ctx.getImageData(0, 0, size, size);
}
/** Run the full pipeline on a decoded image. */
function runPipeline(source: SourceImage, settings: PatternSettings): ProcessResult {
const { gridSize, maxColors, removeBg } = settings;
const imageData = sampleImageData(source.element, gridSize);
return processImage(imageData, {
gridSize,
maxColors,
removeBg,
bgThreshold: BG_THRESHOLD,
});
}
/**
* Reactively run the image → beads pipeline whenever the source image or
* settings change. `runId` forces a re-run (重新生成图纸 button).
*/
export function usePattern(
source: SourceImage | null,
settings: PatternSettings,
runId: number,
): PatternState {
const [result, setResult] = useState<ProcessResult | null>(null);
const [processing, setProcessing] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!source) {
setResult(null);
setProcessing(false);
setError(null);
return;
}
let cancelled = false;
setProcessing(true);
setError(null);
// Yield one frame so the "图片处理中…" / spinner state can paint before
// the (synchronous, CPU-heavy for 128×128) pipeline runs.
const timer = setTimeout(() => {
try {
const res = runPipeline(source, settings);
if (!cancelled) {
setResult(res);
}
} catch {
if (!cancelled) {
setError('图纸生成失败,请稍后重试');
setResult(null);
}
} finally {
if (!cancelled) {
setProcessing(false);
}
}
}, 60);
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [source, settings, runId]);
return { result, processing, error };
}
const MAX_FILE_BYTES = 12 * 1024 * 1024; // 12MB
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
/** Validate a dropped/picked file and decode it into a SourceImage. */
export function loadImageFromFile(file: File): Promise<SourceImage> {
return new Promise((resolve, reject) => {
if (!ALLOWED_TYPES.includes(file.type)) {
reject(new Error('无法解析这张图片,请换一张重试'));
return;
}
if (file.size > MAX_FILE_BYTES) {
reject(new Error('图片不能超过 12MB'));
return;
}
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => {
// Keep the URL alive for thumbnails; the caller revokes it when the
// source is replaced or the app unmounts.
resolve({ element: img, name: file.name, url });
};
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('图片读取失败,请换一张重试'));
};
img.src = url;
});
}
+15
View File
@@ -0,0 +1,15 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import './styles.css';
const container = document.getElementById('root');
if (!container) {
throw new Error('Root container #root not found');
}
createRoot(container).render(
<StrictMode>
<App />
</StrictMode>,
);
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
declare module "*.css";
+10
View File
@@ -0,0 +1,10 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
/** Backend API base URL, e.g. http://localhost:8788 (dev default). */
readonly VITE_API_BASE?: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"strict": true,
"noImplicitAny": true,
"noUncheckedIndexedAccess": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"isolatedModules": true,
"skipLibCheck": true,
"declaration": true,
"outDir": "dist",
"types": ["vitest/globals"]
},
"include": ["src"]
}
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
build: {
target: 'es2020',
outDir: 'dist',
},
});