diff --git a/blog.config.js b/blog.config.js
index 85ba892ea98..3b4a438840d 100644
--- a/blog.config.js
+++ b/blog.config.js
@@ -1,26 +1,28 @@
// 注: process.env.XX是Vercel的环境变量,配置方式见:https://docs.tangly1024.com/article/how-to-config-notion-next#c4768010ae7d44609b744e79e2f9959a
const BLOG = {
- API_BASE_URL: process.env.API_BASE_URL || 'https://app.notion.com/api/v3', // API默认请求地址,可以配置成自己的地址例如:https://[xxxxx].notion.site/api/v3
+ API_BASE_URL: process.env.API_BASE_URL || 'https://barryprivate.notion.site/api/v3', // API默认请求地址,可以配置成自己的地址例如:https://[xxxxx].notion.site/api/v3
// Important page_id!!!Duplicate Template from https://tanghh.notion.site/02ab3b8678004aa69e9e415905ef32a5
NOTION_PAGE_ID:
process.env.NOTION_PAGE_ID ||
'02ab3b8678004aa69e9e415905ef32a5,en:7c1d570661754c8fbc568e00a01fd70e',
- THEME: process.env.NEXT_PUBLIC_THEME || 'simple', // 当前主题,在themes文件夹下可找到所有支持的主题;主题名称就是文件夹名,例如 claude,endspace,example,fukasawa,fuwari,gitbook,heo,hexo,landing,matery,medium,next,nobelium,plog,simple
+ THEME: process.env.NEXT_PUBLIC_THEME || 'heo', // 当前主题,在themes文件夹下可找到所有支持的主题;主题名称就是文件夹名,例如 example,fukasawa,gitbook,heo,hexo,landing,matery,medium,next,nobelium,plog,simple
+
LANG: process.env.NEXT_PUBLIC_LANG || 'zh-CN', // e.g 'zh-CN','en-US' see /lib/lang.js for more.
- SINCE: process.env.NEXT_PUBLIC_SINCE || 2021, // e.g if leave this empty, current year will be used.
+ SINCE: process.env.NEXT_PUBLIC_SINCE || 2025, // e.g if leave this empty, current year will be used.
PSEUDO_STATIC: process.env.NEXT_PUBLIC_PSEUDO_STATIC || false, // 伪静态路径,开启后所有文章URL都以 .html 结尾。
NEXT_REVALIDATE_SECOND: process.env.NEXT_PUBLIC_REVALIDATE_SECOND || 60, // 更新缓存间隔 单位(秒);即每个页面有60秒的纯静态期、此期间无论多少次访问都不会抓取notion数据;调大该值有助于节省Vercel资源、同时提升访问速率,但也会使文章更新有延迟。
REVALIDATION_TOKEN: process.env.REVALIDATION_TOKEN || '', // On-Demand Revalidation Token,设置后可通过 POST /api/revalidate 立即刷新页面缓存(解决 Notion 内容更新延迟问题)
- APPEARANCE: process.env.NEXT_PUBLIC_APPEARANCE || 'light', // ['light', 'dark', 'auto'], // light 日间模式 , dark夜间模式, auto根据时间和主题自动夜间模式
- APPEARANCE_DARK_TIME: process.env.NEXT_PUBLIC_APPEARANCE_DARK_TIME || [18, 6], // 夜间模式起至时间,false时关闭根据时间自动切换夜间模式
+ APPEARANCE: process.env.NEXT_PUBLIC_APPEARANCE || 'auto', // ['light', 'dark', 'auto'], // light 日间模式 , dark夜间模式, auto根据时间和主题自动夜间模式
+ APPEARANCE_DARK_TIME: process.env.NEXT_PUBLIC_APPEARANCE_DARK_TIME || [16, 7], // 夜间模式起至时间,false时关闭根据时间自动切换夜间模式
+ AUTHOR: process.env.NEXT_PUBLIC_AUTHOR || 'BarryZed', // 您的昵称 例如 tangly1024
+ BIO: process.env.NEXT_PUBLIC_BIO || '专注于眼前的事物吧。', // 作者简介
+ LINK: process.env.NEXT_PUBLIC_LINK || 'https://www.barryzed.top', // 网站地址
+ KEYWORDS: process.env.NEXT_PUBLIC_KEYWORD || '游戏,编程,个人', // 网站关键词 英文逗号隔开
- AUTHOR: process.env.NEXT_PUBLIC_AUTHOR || 'NotionNext', // 您的昵称 例如 tangly1024
- BIO: process.env.NEXT_PUBLIC_BIO || '一个普通的干饭人🍚', // 作者简介
- LINK: process.env.NEXT_PUBLIC_LINK || 'https://tangly1024.com', // 网站地址
- KEYWORDS: process.env.NEXT_PUBLIC_KEYWORD || 'Notion, 博客', // 网站关键词 英文逗号隔开
BLOG_FAVICON: process.env.NEXT_PUBLIC_FAVICON || '/favicon.ico', // blog favicon 配置, 默认使用 /public/favicon.ico,支持在线图片,如 https://img.imesong.com/favicon.png
+ BEI_AN: process.env.NEXT_PUBLIC_BEI_AN || '黑ICP备2025035555号', // 备案号 闽ICP备XXXXXX
PWA_ENABLE: process.env.NEXT_PUBLIC_PWA_ENABLE || false, // 是否启用 PWA 安装入口;也可在 Notion_Config 中配置 PWA_ENABLE=true
PWA_NAME: process.env.NEXT_PUBLIC_PWA_NAME || '', // PWA 安装名称;默认读取站点标题,通常无需单独配置
PWA_SHORT_NAME: process.env.NEXT_PUBLIC_PWA_SHORT_NAME || '', // PWA 短名称;默认读取站点标题,通常无需单独配置
@@ -31,7 +33,6 @@ const BLOG = {
PWA_ICON_512_MASKABLE: process.env.NEXT_PUBLIC_PWA_ICON_512_MASKABLE || '', // 可选:覆盖 manifest 512x512 maskable 图标;资源应留有足够安全边距
PWA_THEME_COLOR: process.env.NEXT_PUBLIC_PWA_THEME_COLOR || '', // PWA 主题色
PWA_BACKGROUND_COLOR: process.env.NEXT_PUBLIC_PWA_BACKGROUND_COLOR || '', // PWA 启动画面背景色
- BEI_AN: process.env.NEXT_PUBLIC_BEI_AN || '', // 备案号 闽ICP备XXXXXX
BEI_AN_LINK: process.env.NEXT_PUBLIC_BEI_AN_LINK || 'https://beian.miit.gov.cn/', // 备案查询链接,如果用了萌备等备案请在这里填写
BEI_AN_GONGAN: process.env.NEXT_PUBLIC_BEI_AN_GONGAN || '', // 公安备案号,例如 '浙公网安备3xxxxxxxx8号'
@@ -70,18 +71,18 @@ const BLOG = {
CUSTOM_MENU: process.env.NEXT_PUBLIC_CUSTOM_MENU || true, // 支持Menu类型的菜单,替代了3.12版本前的Page类型
// 文章列表相关设置
- CAN_COPY: process.env.NEXT_PUBLIC_CAN_COPY || true, // 是否允许复制页面内容,默认允许;可被文章属性 CAN_COPY / ext.CAN_COPY 覆盖。
+ CAN_COPY: process.env.NEXT_PUBLIC_CAN_COPY || false, // 是否允许复制页面内容,默认允许;可被文章属性 CAN_COPY / ext.CAN_COPY 覆盖。
...require('./conf/techgrow.config'), // 公众号导流插件(TechGrow)
// 侧栏布局 是否反转(左变右,右变左) 已支持主题: hexo next medium fukasawa example
LAYOUT_SIDEBAR_REVERSE:
- process.env.NEXT_PUBLIC_LAYOUT_SIDEBAR_REVERSE || false,
+ process.env.NEXT_PUBLIC_LAYOUT_SIDEBAR_REVERSE || true,
// 欢迎语打字效果,Hexo,Matery主题支持, 英文逗号隔开多个欢迎语。
GREETING_WORDS:
process.env.NEXT_PUBLIC_GREETING_WORDS ||
- 'Hi,我是一个程序员, Hi,我是一个打工人,Hi,我是一个干饭人,欢迎来到我的博客🎉',
+ '我希望事情是本来的样子而不是我臆想的样子。,放下助人情节,尊重他人命运。,童话也是生活的一部分。,你和你喜欢的人一起坐过摩天轮吗?,欸?这狗怎么上来的?',
// 欢迎语打字效果类型速度
GREETING_WORDS_TYPE_SPEED:
@@ -96,7 +97,14 @@ const BLOG = {
// 内嵌 Notion 子页面 URL 跟随父级文章路径,例如 /article/post/{pageId}
INNER_PAGE_URL_PARENT_PATH:
- process.env.NEXT_PUBLIC_INNER_PAGE_URL_PARENT_PATH || false
+ process.env.NEXT_PUBLIC_INNER_PAGE_URL_PARENT_PATH || false,
+
+ // HEO 主题:今日卡牌「每日一句」句子列表(点击「换一个」随机切换)
+ HEO_HERO_QUOTES:
+ process.env.NEXT_PUBLIC_HEO_HERO_QUOTES?.split(',') || [
+ '我的个人朋友圈上线啦!',
+ '喝的多了兑了水的水也会醉。'
+ ]
}
module.exports = BLOG
diff --git a/components/DisableCopy.js b/components/DisableCopy.js
index 44115e12c83..0ed0db3981b 100644
--- a/components/DisableCopy.js
+++ b/components/DisableCopy.js
@@ -5,7 +5,7 @@ export default function DisableCopy() {
const html = document.getElementsByTagName('html')[0]
const handleCopy = event => {
event.preventDefault()
- alert('抱歉,本网页内容不可复制!')
+ alert('抱歉,本网页内容不可复制捏,想要分享的话请分享网址吧 :)\n如需复制代码,请使用代码块右上角的复制按钮(若无复制按钮请刷新页面)。')
}
html.classList.add('forbid-copy')
diff --git a/components/LoadingCover.js b/components/LoadingCover.js
index fc51083d2f6..f874cab3539 100644
--- a/components/LoadingCover.js
+++ b/components/LoadingCover.js
@@ -36,41 +36,35 @@ export default function LoadingCover() {
-
+
) : null
diff --git a/components/SEO.js b/components/SEO.js
index 96f9e224fb6..23d3bdbf8f9 100644
--- a/components/SEO.js
+++ b/components/SEO.js
@@ -159,6 +159,9 @@ const SEO = props => {
)}
{/* 搜索引擎验证 */}
+
+ {/*follow.it认证*/}
+
{SEO_GOOGLE_SITE_VERIFICATION && (
{
+ let timer = null
const handleStart = () => {
- setOnLoading(true)
+ // 仅当路由切换较慢时显示加载遮罩,避免快速切换时闪烁
+ clearTimeout(timer)
+ timer = setTimeout(() => setOnLoading(true), 500)
}
const handleStop = () => {
+ clearTimeout(timer)
setOnLoading(false)
}
@@ -133,6 +137,7 @@ export function GlobalContextProvider(props) {
router.events.on('routeChangeError', handleStop)
router.events.on('routeChangeComplete', handleStop)
return () => {
+ clearTimeout(timer)
router.events.off('routeChangeStart', handleStart)
router.events.off('routeChangeComplete', handleStop)
router.events.off('routeChangeError', handleStop)
diff --git a/lib/lang/en-US.js b/lib/lang/en-US.js
index 20f6a6fb2d4..7ab73ae6913 100644
--- a/lib/lang/en-US.js
+++ b/lib/lang/en-US.js
@@ -44,6 +44,7 @@ export default {
RELATE_POSTS: 'Relate Posts',
COPYRIGHT: 'Copyright',
AUTHOR: 'Author',
+ COMPILER: 'Compiled by',
URL: 'URL',
ANALYTICS: 'Analytics',
NOW: 'NOW',
diff --git a/lib/lang/zh-CN.js b/lib/lang/zh-CN.js
index 899ee0b8965..5030f178780 100644
--- a/lib/lang/zh-CN.js
+++ b/lib/lang/zh-CN.js
@@ -33,7 +33,7 @@ export default {
RECOMMEND_POSTS: '推荐文章',
MORE: '更多',
NO_MORE: '没有更多了',
- LATEST_POSTS: '最新发布',
+ LATEST_POSTS: '最近更新',
TAGS: '标签',
NO_TAG: 'NoTag',
CATEGORY: '分类',
@@ -44,6 +44,7 @@ export default {
RELATE_POSTS: '相关文章',
COPYRIGHT: '声明',
AUTHOR: '作者',
+ COMPILER: '整理',
URL: '链接',
ANALYTICS: '统计',
RECOMMEND_BADGES: '荐',
diff --git a/lib/lang/zh-HK.js b/lib/lang/zh-HK.js
index 7979e6e8f7e..1329a667a36 100644
--- a/lib/lang/zh-HK.js
+++ b/lib/lang/zh-HK.js
@@ -28,6 +28,7 @@ export default {
RELATE_POSTS: '相關文章',
COPYRIGHT: '版權',
AUTHOR: '作者',
+ COMPILER: '整理',
URL: '連結',
ANALYTICS: '分析',
POSTS: '篇文章',
diff --git a/lib/lang/zh-TW.js b/lib/lang/zh-TW.js
index 876a63d249b..532ed819f9e 100644
--- a/lib/lang/zh-TW.js
+++ b/lib/lang/zh-TW.js
@@ -42,6 +42,7 @@ export default {
RELATE_POSTS: '相關文章',
COPYRIGHT: '著作權聲明',
AUTHOR: '作者',
+ COMPILER: '整理',
URL: '網址',
ANALYTICS: '統計',
RECOMMEND_BADGES: '推薦',
diff --git a/lib/utils/slugMap.js b/lib/utils/slugMap.js
new file mode 100644
index 00000000000..bb6ed9baa51
--- /dev/null
+++ b/lib/utils/slugMap.js
@@ -0,0 +1,133 @@
+/**
+ * 分类 / 标签 的 URL slug 映射
+ * 页面内仍显示中文名称,仅链接 URL 使用英文 slug。
+ *
+ * 键(tag/category 名称)会在运行时自动从站点数据中收集,
+ * 这里只需要给想用英文 URL 的名称填上英文即可:
+ * 游戏: 'game', // 分类「游戏」的链接变成 /category/game
+ * 编程: 'program', // 标签「编程」的链接变成 /tag/program
+ * 未填写的名称保持原来的中文 URL。
+ * 名称里带空格的(如 "Internet Download Manager")不用填:
+ * 会自动转成小写连字符 internet-download-manager;想自定义才需要写
+ * 带引号的键,例如 'Apex Legends': 'apex-legends'。
+ */
+const USER_SLUG_MAP = {
+ 编程: 'program',
+ 教程: 'tutorial',
+ 备忘: 'memo',
+ 音乐: 'music',
+ 游戏: 'game',
+ 学习笔记: 'study-notes',
+ 朋友圈: 'moments',
+ NFEU: 'nfeu',
+ 测试category: 'test-category',
+
+ 测试tag: 'test-tag',
+ 笔记本电脑: 'laptop',
+ 原创: 'original',
+ ROG: 'rog',
+ 推荐: 'recommend',
+ 白嫖: 'free',
+ Notion: 'notion',
+ 建站: 'website',
+ 歌词: 'lyrics',
+ 个人: 'personal',
+ Office: 'office',
+ Windows: 'windows',
+ 'Apex Legends': 'apex-legends',
+ 翻译: 'translation',
+ 设定集: 'lore-book',
+ 探索者之书: 'pathfinders-quest',
+ Geebar: 'geebar',
+ ilem: 'ilem',
+ 剪辑: 'editing',
+ 字幕: 'subtitles',
+ 台词: 'dialogue',
+ 高等数学: 'advanced-mathematics',
+ 微分方程: 'differential-equations',
+ 大学物理: 'college-physics',
+ 离散数学: 'discrete-mathematics',
+ 质点运动学: 'particle-kinematics',
+ MARATHON: 'marathon',
+ 大学英语: 'college-english',
+ 图: 'image',
+ 关系: 'relationship',
+ 'C++': 'cpp',
+ 社会实践: 'social-practice',
+ 乐队: 'band',
+ 架子鼓: 'jazz-drum',
+ 'Internet Download Manager': 'idm',
+ 雨中冒险2: 'risk-of-rain-2',
+ mod: 'mod',
+ AI模型: 'ai-model',
+ 概率论: 'probability-theory',
+ 英语: 'english',
+ 排序: 'sorting',
+ 年度总结: 'annual-summary',
+ RSS: 'rss',
+ C: 'c',
+ Java: 'java',
+ Ubuntu: 'ubuntu',
+ VMware: 'vmware',
+ Linux: 'linux',
+ 应用统计学: 'applied-statistics',
+ Python: 'python',
+ 算法: 'algorithm',
+ 机器学习: 'machine-learning',
+ Shell: 'shell',
+ SQL: 'sql',
+ 数据库: 'database'
+}
+
+
+/**
+ * 根据站点实际的 tag/category 名称列表,合并用户映射,生成完整映射表
+ * @param {string[]} names 名称列表
+ * @returns {Object}
+ */
+export function buildSlugMap(names = []) {
+ const map = {}
+ names.forEach(name => {
+ map[name] = normalizeSlug(USER_SLUG_MAP[name] || name)
+ })
+ return map
+}
+
+/**
+ * 规范化 slug:去除首尾空格,连续空格替换为连字符
+ * @param {string} value
+ * @returns {string}
+ */
+function normalizeSlug(value) {
+ return String(value)
+ .trim()
+ .toLowerCase()
+ .replace(/\s+/g, '-')
+}
+
+/**
+ * 名称 -> URL slug;未填映射的原样返回
+ * @param {string} name
+ * @param {Object} slugMap
+ * @returns {string}
+ */
+export function toSlug(name, slugMap) {
+ const value = (slugMap && slugMap[name]) || name
+ return normalizeSlug(value)
+}
+
+/**
+ * URL slug -> 名称;未匹配到映射的原样返回
+ * @param {string} slug
+ * @param {Object} slugMap
+ * @returns {string}
+ */
+export function fromSlug(slug, slugMap) {
+ if (!slugMap) {
+ return slug
+ }
+ const found = Object.keys(slugMap).find(key => slugMap[key] === slug)
+ return found || slug
+}
+
+export default USER_SLUG_MAP
diff --git a/next-env.d.ts b/next-env.d.ts
index a4a7b3f5cfa..254b73c165d 100644
--- a/next-env.d.ts
+++ b/next-env.d.ts
@@ -1,5 +1,6 @@
///
///
+///
// NOTE: This file should not be edited
-// see https://nextjs.org/docs/pages/building-your-application/configuring/typescript for more information.
+// see https://nextjs.org/docs/pages/api-reference/config/typescript for more information.
diff --git a/pages/api/steam-status.js b/pages/api/steam-status.js
new file mode 100644
index 00000000000..cd10e193b93
--- /dev/null
+++ b/pages/api/steam-status.js
@@ -0,0 +1,226 @@
+import CONFIG from '@/themes/heo/config'
+
+const DEFAULT_CACHE_SECONDS = 120
+
+// 内存缓存,避免每次请求都调用 Steam API
+let steamCache = { data: null, updatedAt: 0 }
+// 游戏中文名缓存(Steam 商店接口,24 小时有效)
+const gameNameCache = new Map()
+
+// Steam personastate -> 中文状态
+const PERSONA_STATES = [
+ { code: 0, text: '离线' },
+ { code: 1, text: '在线' },
+ { code: 2, text: '忙碌' },
+ { code: 3, text: '离开' },
+ { code: 4, text: '小睡' },
+ { code: 5, text: '想交易' },
+ { code: 6, text: '想玩游戏' }
+]
+
+function getConfigValue(key) {
+ return process.env[key] || CONFIG[key]
+}
+
+async function getChineseGameName(appid) {
+ if (!appid) {
+ return ''
+ }
+ const key = String(appid)
+ // 优先使用配置中的中文名映射
+ const configured = CONFIG.HEO_STEAM_GAME_NAMES?.[key]
+ if (configured) {
+ return configured
+ }
+ const cached = gameNameCache.get(key)
+ if (cached && Date.now() - cached.ts < 24 * 60 * 60 * 1000) {
+ return cached.name
+ }
+ try {
+ const url =
+ 'https://store.steampowered.com/api/appdetails' +
+ `?appids=${encodeURIComponent(key)}&l=schinese&cc=CN`
+ const response = await fetch(url)
+ if (!response.ok) {
+ throw new Error(`Steam store HTTP ${response.status}`)
+ }
+ const json = await response.json()
+ const name = json?.[key]?.data?.name || ''
+ gameNameCache.set(key, { name, ts: Date.now() })
+ return name
+ } catch {
+ return ''
+ }
+}
+
+/**
+ * 获取最近玩过的游戏(用于离线时展示“xx前玩了[游戏]”)
+ */
+async function fetchLastPlayedGame(apiKey, steamId) {
+ try {
+ const url =
+ 'https://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v0001/' +
+ `?key=${encodeURIComponent(apiKey)}&steamid=${encodeURIComponent(
+ steamId
+ )}&count=5&format=json`
+ const response = await fetch(url)
+ if (!response.ok) {
+ return null
+ }
+ const json = await response.json()
+ const games = json?.response?.games
+ if (!Array.isArray(games) || games.length === 0) {
+ return null
+ }
+ // 以最近两周的游玩时长倒序近似“最近在玩”
+ games.sort((a, b) => (b.playtime_2weeks || 0) - (a.playtime_2weeks || 0))
+ return { appid: games[0].appid, name: games[0].name || '' }
+ } catch {
+ return null
+ }
+}
+
+/**
+ * 统计当前正在玩同一款游戏的好友数量(用于“和 xx 个朋友遨游”文案)
+ */
+async function fetchNumFriendsInGame(apiKey, steamId, gameId) {
+ if (!gameId) {
+ return 0
+ }
+ try {
+ const friendUrl =
+ 'https://api.steampowered.com/ISteamUser/GetFriendList/v0001/' +
+ `?key=${encodeURIComponent(apiKey)}&steamid=${encodeURIComponent(
+ steamId
+ )}&relationship=friend&format=json`
+ const friendResp = await fetch(friendUrl)
+ if (!friendResp.ok) {
+ return 0
+ }
+ const friendJson = await friendResp.json()
+ const friends = friendJson?.friendslist?.friends || []
+ if (!Array.isArray(friends) || friends.length === 0) {
+ return 0
+ }
+ // GetPlayerSummaries 一次最多查询 100 个好友
+ const ids = friends
+ .slice(0, 100)
+ .map(friend => friend.steamid)
+ .join(',')
+ const summaryUrl =
+ 'https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/' +
+ `?key=${encodeURIComponent(apiKey)}&steamids=${encodeURIComponent(
+ ids
+ )}&format=json`
+ const summaryResp = await fetch(summaryUrl)
+ if (!summaryResp.ok) {
+ return 0
+ }
+ const summaryJson = await summaryResp.json()
+ const players = summaryJson?.response?.players || []
+ return players.filter(
+ friend => String(friend.gameid) === String(gameId)
+ ).length
+ } catch {
+ return 0
+ }
+}
+
+async function buildPlayer(player, lastPlayed, numFriendsInGame) {
+ const personaState =
+ PERSONA_STATES.find(item => item.code === player.personastate) ||
+ PERSONA_STATES[0]
+ const inGame = Boolean(player.gameextrainfo)
+ const gameNameCn = inGame ? await getChineseGameName(player.gameid) : ''
+ const lastPlayedGameNameCn = lastPlayed
+ ? await getChineseGameName(lastPlayed.appid)
+ : ''
+ return {
+ personaname: player.personaname || '',
+ avatarfull: player.avatarfull || '',
+ profileurl: player.profileurl || '',
+ personastate: player.personastate ?? 0,
+ personastateText: personaState.text,
+ gameextrainfo: player.gameextrainfo || '',
+ gameid: player.gameid || '',
+ gameNameCn,
+ inGame,
+ numFriendsInGame,
+ lastlogoff: player.lastlogoff || 0,
+ lastPlayedGameId: lastPlayed?.appid || '',
+ lastPlayedGameName: lastPlayed?.name || '',
+ lastPlayedGameNameCn
+ }
+}
+
+/**
+ * 代理 Steam Web API:GetPlayerSummaries
+ * 配置 HEO_STEAM_API_KEY / HEO_STEAM_ID 后即可使用,密钥不会暴露给前端
+ */
+export default async function handler(req, res) {
+ if (req.method !== 'GET') {
+ res.setHeader('Allow', 'GET')
+ return res.status(405).json({ error: 'Method Not Allowed' })
+ }
+
+ // API Key 只从环境变量读取,避免密钥进入前端或代码仓库
+ const apiKey = process.env.HEO_STEAM_API_KEY || ''
+ const steamId = process.env.HEO_STEAM_ID || CONFIG.HEO_STEAM_ID || ''
+ if (!apiKey || !steamId) {
+ return res.status(200).json({ enabled: false })
+ }
+
+ const cacheSeconds = Number(
+ getConfigValue('HEO_STEAM_CACHE_SECONDS') || DEFAULT_CACHE_SECONDS
+ )
+ const ttl =
+ Number.isFinite(cacheSeconds) && cacheSeconds > 0
+ ? cacheSeconds * 1000
+ : DEFAULT_CACHE_SECONDS * 1000
+
+ // 命中缓存直接返回
+ if (steamCache.data && Date.now() - steamCache.updatedAt < ttl) {
+ return res.status(200).json(steamCache.data)
+ }
+
+ try {
+ const summaryUrl =
+ 'https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/' +
+ `?key=${encodeURIComponent(apiKey)}&steamids=${encodeURIComponent(
+ steamId
+ )}&format=json`
+ const [response, lastPlayed] = await Promise.all([
+ fetch(summaryUrl),
+ fetchLastPlayedGame(apiKey, steamId)
+ ])
+ if (!response.ok) {
+ throw new Error(`Steam API HTTP ${response.status}`)
+ }
+ const json = await response.json()
+ const player = json?.response?.players?.[0] || null
+ const numFriendsInGame = player?.gameid
+ ? await fetchNumFriendsInGame(apiKey, steamId, player.gameid)
+ : 0
+ const data = {
+ enabled: true,
+ player: player
+ ? await buildPlayer(player, lastPlayed, numFriendsInGame)
+ : null
+ }
+
+ steamCache = { data, updatedAt: Date.now() }
+ res.setHeader(
+ 'Cache-Control',
+ `public, s-maxage=${Math.round(ttl / 1000)}, stale-while-revalidate=60`
+ )
+ return res.status(200).json(data)
+ } catch (error) {
+ // 请求失败时优先使用缓存兜底,避免瞬时故障影响页面
+ if (steamCache.data) {
+ return res.status(200).json(steamCache.data)
+ }
+ return res
+ .status(502)
+ .json({ enabled: true, player: null, error: 'Steam API 请求失败' })
+ }
+}
diff --git a/pages/category/[category]/index.js b/pages/category/[category]/index.js
index 4a3d9ef887f..aba196ff9e5 100644
--- a/pages/category/[category]/index.js
+++ b/pages/category/[category]/index.js
@@ -1,6 +1,7 @@
import BLOG from '@/blog.config'
import { siteConfig } from '@/lib/config'
import { fetchGlobalAllData } from '@/lib/db/SiteDataApi'
+import { buildSlugMap, fromSlug, toSlug } from '@/lib/utils/slugMap'
import { DynamicLayout } from '@/themes/theme'
/**
@@ -16,6 +17,11 @@ export default function Category(props) {
export async function getStaticProps({ params: { category }, locale }) {
const from = 'category-props'
let props = await fetchGlobalAllData({ from, locale })
+ const slugMap = buildSlugMap(
+ (props.categoryOptions || []).map(c => c.name)
+ )
+ // URL 里的英文 slug 先还原成中文分类名
+ const categoryName = fromSlug(category, slugMap)
// 过滤状态
props.posts = props.allPages?.filter(
@@ -23,7 +29,7 @@ export async function getStaticProps({ params: { category }, locale }) {
)
// 处理过滤
props.posts = props.posts.filter(
- post => post && post.category && post.category.includes(category)
+ post => post && post.category && post.category.includes(categoryName)
)
// 处理文章页数
@@ -45,7 +51,7 @@ export async function getStaticProps({ params: { category }, locale }) {
delete props.allPages
- props = { ...props, category }
+ props = { ...props, category: categoryName }
return {
props,
@@ -63,9 +69,10 @@ export async function getStaticPaths() {
const from = 'category-paths'
const { categoryOptions } = await fetchGlobalAllData({ from })
const categories = Array.isArray(categoryOptions) ? categoryOptions : []
+ const slugMap = buildSlugMap(categories.map(c => c.name))
return {
paths: categories.map(category => ({
- params: { category: category?.name }
+ params: { category: toSlug(category?.name, slugMap) }
})),
fallback: true
}
diff --git a/pages/tag/[tag]/index.js b/pages/tag/[tag]/index.js
index 0e27c03ff42..aae62d3536b 100644
--- a/pages/tag/[tag]/index.js
+++ b/pages/tag/[tag]/index.js
@@ -1,6 +1,7 @@
import BLOG from '@/blog.config'
import { siteConfig } from '@/lib/config'
import { fetchGlobalAllData } from '@/lib/db/SiteDataApi'
+import { buildSlugMap, fromSlug, toSlug } from '@/lib/utils/slugMap'
import { DynamicLayout } from '@/themes/theme'
/**
@@ -16,11 +17,14 @@ const Tag = props => {
export async function getStaticProps({ params: { tag }, locale }) {
const from = 'tag-props'
const props = await fetchGlobalAllData({ from, locale })
+ const slugMap = buildSlugMap(getTagNames(props.tagOptions))
+ // URL 里的英文 slug 先还原成中文标签名
+ const tagName = fromSlug(tag, slugMap)
// 过滤状态
props.posts = props.allPages
?.filter(page => page.type === 'Post' && page.status === 'Published')
- .filter(post => post && post?.tags && post?.tags.includes(tag))
+ .filter(post => post && post?.tags && post?.tags.includes(tagName))
// 处理文章页数
props.postCount = props.posts.length
@@ -40,7 +44,7 @@ export async function getStaticProps({ params: { tag }, locale }) {
)
}
- props.tag = tag
+ props.tag = tagName
delete props.allPages
return {
props,
@@ -74,10 +78,11 @@ export async function getStaticPaths() {
const from = 'tag-static-path'
const { tagOptions } = await fetchGlobalAllData({ from })
const tagNames = getTagNames(tagOptions)
+ const slugMap = buildSlugMap(tagNames)
return {
paths: tagNames.map(tag => ({
- params: { tag }
+ params: { tag: toSlug(tag, slugMap) }
})),
fallback: true
}
diff --git a/public/bead-pattern-generator/css/style.css b/public/bead-pattern-generator/css/style.css
new file mode 100644
index 00000000000..8cd334b4ccf
--- /dev/null
+++ b/public/bead-pattern-generator/css/style.css
@@ -0,0 +1,721 @@
+* {
+ margin: 0;
+ padding: 0;
+ box-sizing: border-box;
+}
+
+:root {
+ --pri: #ffa500;
+ --pri-h: #a16900;
+ --bg: #F6DBB9;
+ --sf: #ffffff;
+ --sf-h: #f1f5f9;
+ --tx: #1e293b;
+ --tx2: #64748b;
+ --bd: #e2e8f0;
+ --r: 5px;
+}
+
+body {
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
+ background: var(--bg);
+ color: var(--tx);
+ min-height: 100vh;
+}
+
+.hidden {
+ display: none !important;
+}
+
+/* ── Header ── */
+header {
+ background: var(--sf);
+ border-bottom: 1px solid var(--bd);
+ padding: 14px 24px;
+ text-align: center;
+}
+
+.header-top {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ position: relative;
+}
+
+header h1 {
+ font-size: 22px;
+ font-weight: 700;
+}
+
+header .subtitle {
+ color: var(--tx2);
+ font-size: 13px;
+ margin-top: 2px;
+}
+
+/* ── Layout ── */
+main {
+ display: flex;
+ max-width: 1440px;
+ margin: 0 auto;
+ padding: 16px;
+ gap: 16px;
+ height: calc(100vh - 16px);
+}
+
+/* ── Sidebar ── */
+.controls {
+ width: 270px;
+ flex-shrink: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ overflow-y: auto;
+}
+
+/* ── 右侧 ── */
+.controls-right {
+ width: 270px;
+}
+
+.pattern-area {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+
+/* 手机端:仍上下排列 */
+@media (max-width: 900px) {
+ main {
+ flex-direction: column;
+ height: auto;
+ }
+
+ .controls,
+ .controls-right {
+ width: 100%;
+ }
+
+ .pattern-container {
+ min-height: 360px;
+ }
+}
+
+.controls section {
+ background: var(--sf);
+ border-radius: var(--r);
+ border: 1px solid var(--bd);
+ padding: 14px;
+}
+
+.controls h3 {
+ font-size: 12px;
+ font-weight: 600;
+ margin-bottom: 10px;
+ color: var(--tx2);
+ text-transform: uppercase;
+ letter-spacing: .5px;
+}
+
+/* ── Drop zone ── */
+.drop-zone {
+ border: 2px dashed var(--bd);
+ border-radius: var(--r);
+ padding: 28px 12px;
+ text-align: center;
+ cursor: pointer;
+ transition: .2s;
+ color: var(--tx2);
+ font-size: 13px;
+ line-height: 1.7;
+}
+
+.drop-zone:hover,
+.drop-zone.dragover {
+ border-color: var(--pri);
+ background: rgba(99, 102, 241, .04);
+ color: var(--pri);
+}
+
+/* ── Preview ── */
+.preview-container {
+ margin-top: 10px;
+ border-radius: var(--r);
+ overflow: hidden;
+ border: 1px solid var(--bd);
+}
+
+.preview-container img {
+ width: 100%;
+ display: block;
+}
+
+.restore-btn {
+ margin: 6px 6px 0;
+ width: calc(100% - 12px);
+ font-size: 12px;
+ padding: 7px 10px;
+}
+
+.restore-status {
+ margin: 6px;
+ padding: 8px 10px;
+ border-radius: 8px;
+ font-size: 12px;
+ line-height: 1.5;
+}
+
+.restore-status-info {
+ background: #eff6ff;
+ color: #1d4ed8;
+ border: 1px solid #bfdbfe;
+}
+
+.restore-status-success {
+ background: #f0fdf4;
+ color: #166534;
+ border: 1px solid #bbf7d0;
+}
+
+.restore-status-error {
+ background: #fef2f2;
+ color: #b91c1c;
+ border: 1px solid #fecaca;
+}
+
+.restore-panel-status {
+ margin: 0 20px 16px;
+ padding: 10px 12px;
+ border-radius: 10px;
+ font-size: 12px;
+ line-height: 1.6;
+}
+
+.restore-panel-status-info {
+ background: #eff6ff;
+ color: #1d4ed8;
+ border: 1px solid #bfdbfe;
+}
+
+.restore-panel-status-success {
+ background: #f0fdf4;
+ color: #166534;
+ border: 1px solid #bbf7d0;
+}
+
+.restore-panel-status-error {
+ background: #fef2f2;
+ color: #b91c1c;
+ border: 1px solid #fecaca;
+}
+
+/* ── Form controls ── */
+.control-group {
+ margin-bottom: 10px;
+}
+
+.control-group label {
+ display: block;
+ font-size: 13px;
+ font-weight: 500;
+ margin-bottom: 3px;
+}
+
+.control-group small {
+ font-size: 11px;
+ color: var(--tx2);
+}
+
+.control-group select,
+.control-group input[type="range"] {
+ width: 100%;
+}
+
+select {
+ padding: 5px 8px;
+ border: 1px solid var(--bd);
+ border-radius: 4px;
+ font-size: 13px;
+ background: var(--sf);
+}
+
+input[type="range"] {
+ margin-top: 3px;
+}
+
+.control-group label input[type="checkbox"] {
+ margin-right: 5px;
+}
+
+/* ── Buttons ── */
+.btn {
+ width: 100%;
+ padding: 9px 14px;
+ border: none;
+ border-radius: var(--r);
+ font-size: 14px;
+ font-weight: 600;
+ cursor: pointer;
+ transition: .2s;
+ margin-bottom: 6px;
+}
+
+.btn:disabled {
+ opacity: .45;
+ cursor: not-allowed;
+}
+
+.btn-primary {
+ background: var(--pri);
+ color: #fff;
+}
+
+.btn-primary:hover:not(:disabled) {
+ background: var(--pri-h);
+}
+
+.btn-secondary {
+ background: var(--sf);
+ color: var(--tx);
+ border: 1px solid var(--bd);
+}
+
+.btn-secondary:hover:not(:disabled) {
+ background: var(--sf-h);
+}
+
+.btn-sm {
+ padding: 4px 12px;
+ font-size: 12px;
+}
+
+.btn-outline {
+ background: transparent;
+ border: 1px solid var(--pri);
+ color: var(--pri);
+ border-radius: 6px;
+ cursor: pointer;
+ transition: .2s;
+}
+
+.btn-outline:hover {
+ background: var(--pri);
+ color: #fff;
+}
+
+/* ── Stats ── */
+.stats-section .stat-item {
+ display: flex;
+ justify-content: space-between;
+ padding: 5px 0;
+ font-size: 13px;
+ border-bottom: 1px solid var(--bd);
+}
+
+.stats-section .stat-item:last-child {
+ border-bottom: none;
+}
+
+.stat-value {
+ font-weight: 600;
+}
+
+/* ── Legend ── */
+.legend-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 4px 0;
+ font-size: 13px;
+}
+
+.legend-color {
+ width: 18px;
+ height: 18px;
+ border-radius: 4px;
+ border: 1px solid var(--bd);
+ flex-shrink: 0;
+}
+
+.legend-code {
+ font-weight: 600;
+ min-width: 36px;
+}
+
+.legend-count {
+ color: var(--tx2);
+ margin-left: auto;
+}
+
+/* ── Pattern area ── */
+.pattern-area {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ min-width: 0;
+ overflow-y: auto;
+ min-height: 0;
+}
+
+.pattern-container {
+ flex: 1;
+ position: relative;
+ background: var(--sf);
+ border: 1px solid var(--bd);
+ border-radius: var(--r);
+ overflow: hidden;
+ min-height: 320px;
+}
+
+.pattern-container.has-pattern {
+ background: #fafafa;
+}
+
+#patternCanvas {
+ width: 100%;
+ height: 100%;
+ display: block;
+ cursor: grab;
+}
+
+#patternCanvas.canvas-edit-mode {
+ cursor: crosshair;
+}
+
+.empty-state {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ color: var(--tx2);
+ font-size: 14px;
+ pointer-events: none;
+ padding: 24px;
+ text-align: center;
+}
+
+.pattern-toolbar {
+ position: absolute;
+ top: 10px;
+ right: 10px;
+ display: flex;
+ gap: 6px;
+ z-index: 5;
+}
+
+.pattern-toolbar .btn {
+ width: auto;
+ margin: 0;
+ padding: 6px 10px;
+ font-size: 12px;
+}
+
+/* ── Crop ── */
+.crop-overlay {
+ position: absolute;
+ inset: 0;
+ background: rgba(0, 0, 0, .25);
+ cursor: crosshair;
+ z-index: 10;
+}
+
+.crop-box {
+ position: absolute;
+ border: 2px solid var(--pri);
+ background: rgba(99, 102, 241, .12);
+ box-shadow: 0 0 0 9999px rgba(0, 0, 0, .35);
+}
+
+.crop-actions {
+ display: flex;
+ gap: 8px;
+ margin-top: 8px;
+}
+
+.crop-actions .btn {
+ margin: 0;
+}
+
+/* ── Tooltip ── */
+.bead-tooltip {
+ position: fixed;
+ z-index: 1000;
+ background: rgba(15, 23, 42, .92);
+ color: #fff;
+ padding: 8px 10px;
+ border-radius: 8px;
+ font-size: 12px;
+ line-height: 1.5;
+ pointer-events: none;
+ max-width: 200px;
+}
+
+.bead-tooltip .tip-swatch {
+ display: inline-block;
+ width: 12px;
+ height: 12px;
+ border-radius: 3px;
+ margin-right: 6px;
+ vertical-align: -1px;
+ border: 1px solid rgba(255, 255, 255, .35);
+}
+
+/* ── Edit mode ── */
+.edit-mode-hint {
+ position: absolute;
+ left: 12px;
+ bottom: 12px;
+ background: rgba(15, 23, 42, .85);
+ color: #fff;
+ padding: 6px 12px;
+ border-radius: 999px;
+ font-size: 12px;
+ z-index: 6;
+}
+
+.bead-picker {
+ position: fixed;
+ z-index: 1100;
+ width: 260px;
+ max-height: 360px;
+ background: #fff;
+ border: 1px solid var(--bd);
+ border-radius: 12px;
+ box-shadow: 0 12px 40px rgba(0, 0, 0, .18);
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+}
+
+.bead-picker-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 12px;
+ border-bottom: 1px solid var(--bd);
+ font-size: 13px;
+ font-weight: 600;
+}
+
+.bead-picker-header button {
+ border: none;
+ background: none;
+ font-size: 16px;
+ cursor: pointer;
+ color: var(--tx2);
+}
+
+.bead-picker-search {
+ padding: 8px 12px;
+ border-bottom: 1px solid var(--bd);
+}
+
+.bead-picker-search input {
+ width: 100%;
+ padding: 7px 10px;
+ border: 1px solid var(--bd);
+ border-radius: 8px;
+ font-size: 13px;
+}
+
+.bead-picker-colors {
+ padding: 10px;
+ overflow-y: auto;
+ display: grid;
+ grid-template-columns: repeat(8, 1fr);
+ gap: 6px;
+}
+
+.bp-swatch {
+ width: 100%;
+ aspect-ratio: 1;
+ border-radius: 6px;
+ border: 2px solid transparent;
+ cursor: pointer;
+}
+
+.bp-swatch:hover {
+ transform: scale(1.08);
+}
+
+.bp-swatch.bp-active {
+ border-color: var(--pri);
+ box-shadow: 0 0 0 2px rgba(99, 102, 241, .25);
+}
+
+/* ── Compare overlay ── */
+.compare-overlay {
+ position: absolute;
+ inset: 0;
+ z-index: 4;
+ pointer-events: none;
+}
+
+.compare-overlay img {
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ opacity: .55;
+}
+
+.compare-slider-wrap {
+ position: absolute;
+ left: 12px;
+ bottom: 12px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ background: rgba(255, 255, 255, .92);
+ border: 1px solid var(--bd);
+ border-radius: 8px;
+ padding: 6px 10px;
+ pointer-events: auto;
+ font-size: 12px;
+}
+
+.compare-slider-wrap input[type="range"] {
+ width: 120px;
+}
+
+/* ── Fullscreen ── */
+.pattern-container.fake-fullscreen {
+ position: fixed;
+ inset: 0;
+ z-index: 999;
+ border-radius: 0;
+ border: none;
+}
+
+/* ── Pixel restore modal ── */
+.modal {
+ position: fixed;
+ inset: 0;
+ background: rgba(15, 23, 42, .45);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 1000;
+ padding: 16px;
+}
+
+.modal-box {
+ background: #fff;
+ border-radius: 14px;
+ width: min(920px, 96vw);
+ max-height: 90vh;
+ overflow: auto;
+ box-shadow: 0 20px 60px rgba(0, 0, 0, .25);
+ position: relative;
+}
+
+.modal-close {
+ position: absolute;
+ top: 10px;
+ right: 14px;
+ border: none;
+ background: none;
+ font-size: 24px;
+ cursor: pointer;
+ color: var(--tx2);
+ line-height: 1;
+}
+
+.restore-modal-body {
+ padding: 20px;
+}
+
+.restore-preview-row {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 16px;
+}
+
+.restore-preview-col {
+ border: 1px solid var(--bd);
+ border-radius: 10px;
+ overflow: hidden;
+ background: #fafafa;
+}
+
+.restore-preview-col h4 {
+ font-size: 13px;
+ padding: 8px 12px;
+ border-bottom: 1px solid var(--bd);
+ background: #fff;
+}
+
+.restore-preview-col img,
+.restore-preview-col canvas {
+ width: 100%;
+ display: block;
+ image-rendering: pixelated;
+ background: #fff;
+}
+
+.restore-controls {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 10px;
+ align-items: center;
+ margin: 14px 0;
+}
+
+.restore-controls button.active {
+ background: var(--pri);
+ color: #fff;
+ border-color: var(--pri);
+}
+
+/* ── Responsive ── */
+@media (max-width: 800px) {
+ main {
+ flex-direction: column;
+ height: auto;
+ min-height: calc(100vh - 80px);
+ }
+
+ .controls {
+ width: 100%;
+ max-height: none;
+ }
+
+ .pattern-area {
+ min-height: 50vh;
+ }
+
+ .pattern-container {
+ min-height: 360px;
+ }
+
+ .restore-preview-row {
+ grid-template-columns: 1fr;
+ }
+}
+
+@media (max-width: 480px) {
+ header {
+ padding: 12px 14px;
+ }
+
+ header h1 {
+ font-size: 18px;
+ }
+
+ main {
+ padding: 10px;
+ gap: 10px;
+ }
+
+ .controls section {
+ padding: 12px;
+ }
+
+ .bead-picker {
+ width: min(280px, 92vw);
+ }
+}
\ No newline at end of file
diff --git a/public/bead-pattern-generator/index.html b/public/bead-pattern-generator/index.html
new file mode 100644
index 00000000000..f4bc6f19bd9
--- /dev/null
+++ b/public/bead-pattern-generator/index.html
@@ -0,0 +1,206 @@
+
+
+
+
+
+
+ 拼豆图纸生成器
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
👈 上传一张图片开始
+
支持 JPG / PNG / WebP
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
🖌️ 像素还原
+
+
+
+
原图
+
![原图]()
+
+
+
还原结果
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/public/bead-pattern-generator/js/app.js b/public/bead-pattern-generator/js/app.js
new file mode 100644
index 00000000000..8f5be5dec98
--- /dev/null
+++ b/public/bead-pattern-generator/js/app.js
@@ -0,0 +1,1341 @@
+/**
+ * BeadPatternApp — 精简版
+ * 上传图片 → 裁剪/调色 → 转拼豆 → 预览编辑 → 导出 PNG/PDF
+ * 依赖:converter.js、colors.js、(可选)pixel-restore.js
+ */
+window.onload = function () {
+ alert(
+ "免责声明\n\n" +
+ "本工具仅用于个人学习、研究与技术交流用途,不用于任何商业目的。\n" +
+ "本工具部分功能设计、交互方式及相关技术方案参考了公开网络中的已有作品。如涉及任何第三方拥有的知识产权、版权或其他合法权益,请权利人通过邮箱(barryzed@163.com)联系,我将在核实相关情况后根据实际情况进行处理。\n" +
+ "本工具生成的拼豆图案、颜色匹配结果及导出内容仅作为制作参考。由于图片质量、颜色空间、显示设备、珠子品牌色卡差异等因素,生成结果可能与实际制作效果存在偏差,请使用者自行判断。\n" +
+ "用户上传的图片、素材及生成内容,其版权及相关权利归原权利人所有。用户应确保自身拥有对相关素材进行使用、修改或转换的合法权限,不得利用本工具制作、传播侵犯他人权益的内容。\n" +
+ "本工具不会主动存储或公开用户上传的图片文件,用户应自行妥善保管相关素材。\n" +
+ "本工具目前仅进行了基础功能测试与验证,可能存在未知问题或兼容性问题。如遇到功能异常,欢迎通过邮箱(barryzed@163.com)反馈。\n\n" +
+ "继续使用本工具即代表您已阅读并同意以上声明。"
+ );
+};
+
+function escapeHtml(value) {
+ return String(value ?? '').replace(/[&<>"']/g, ch => ({
+ '&': '&', '<': '<', '>': '>', '"': '"', "'": '''
+ }[ch]));
+}
+
+class BeadPatternApp {
+ constructor() {
+ this.converter = new BeadConverter();
+ this.canvas = document.getElementById('patternCanvas');
+ this.ctx = this.canvas.getContext('2d');
+ this.emptyState = document.getElementById('emptyState');
+ this.controls = document.querySelector('.controls');
+ this.uploadSection = document.querySelector('.upload-section');
+
+ this.image = null;
+ this.croppedImage = null;
+ this.pattern = null;
+ this._imageDataUrl = '';
+
+ // View
+ this.zoom = 1;
+ this.panX = 0;
+ this.panY = 0;
+ this._panning = false;
+ this._lastX = 0;
+ this._lastY = 0;
+
+ // Render options
+ this.CELL = 24;
+ this.AXIS_M = 30;
+ this.showCodes = true;
+ this.showGrid = true;
+ this.showBoardLines = false;
+ this.hideBg = false;
+ this.bgCode = null;
+
+ // Image adjustments
+ this.brightness = 0;
+ this.contrast = 0;
+ this.saturation = 0;
+
+ // Crop
+ this._cropping = false;
+ this._cropRect = null;
+ this._cropDrag = false;
+ this._cropStart = null;
+
+ // Compare / restore / edit
+ this._comparing = false;
+ this._restoreOriginalDataUrl = '';
+ this._restoredSource = false;
+ this._restoreBusy = false;
+ this._restoreMode = 'sharp';
+ this._restoreScale = 4;
+ this._restorePreviewDataUrl = '';
+ this._restorePreviewMeta = null;
+ this._restoreRenderToken = 0;
+ this.editMode = false;
+ this._editDownPos = null;
+
+ this._bind();
+ this._syncRestoreUI();
+ }
+
+ /* ═══════════ Event binding ═══════════ */
+
+ _bind() {
+ const $ = id => document.getElementById(id);
+
+ // Upload
+ const dropZone = $('dropZone');
+ const fileInput = $('fileInput');
+ if (dropZone && fileInput) {
+ dropZone.addEventListener('click', () => fileInput.click());
+ dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('dragover'); });
+ dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
+ dropZone.addEventListener('drop', e => {
+ e.preventDefault();
+ dropZone.classList.remove('dragover');
+ const f = e.dataTransfer.files[0];
+ if (f && f.type.startsWith('image/')) this._loadImage(f);
+ });
+ fileInput.addEventListener('change', e => {
+ if (e.target.files[0]) this._loadImage(e.target.files[0]);
+ });
+ }
+
+ // Pixel restore
+ if ($('restoreBtn')) $('restoreBtn').addEventListener('click', () => this._restoreSourceImage());
+ if ($('pixelRestoreClose') && $('pixelRestoreModal')) {
+ $('pixelRestoreClose').addEventListener('click', () => this._closeRestoreModal());
+ $('pixelRestoreModal').addEventListener('click', e => {
+ if (e.target === $('pixelRestoreModal')) this._closeRestoreModal();
+ });
+ }
+ document.querySelectorAll('[data-restore-mode]').forEach(btn => {
+ btn.addEventListener('click', () => {
+ this._restoreMode = btn.dataset.restoreMode || 'sharp';
+ this._syncRestorePanelControls();
+ this._renderRestorePreview();
+ });
+ });
+ if ($('restoreScale')) {
+ $('restoreScale').addEventListener('change', e => {
+ this._restoreScale = parseInt(e.target.value, 10) || 4;
+ this._syncRestorePanelControls();
+ this._renderRestorePreview();
+ });
+ }
+ if ($('restoreApplyBtn')) {
+ $('restoreApplyBtn').addEventListener('click', () => this._applyRestorePreview());
+ }
+
+ // Sliders
+ if ($('widthSlider')) {
+ $('widthSlider').addEventListener('input', e => {
+ if ($('widthValue')) $('widthValue').textContent = e.target.value;
+ this._refreshHeightLabel();
+ });
+ }
+ if ($('maxColorsSlider')) {
+ $('maxColorsSlider').addEventListener('input', e => {
+ const v = parseInt(e.target.value);
+ if ($('maxColorsValue')) $('maxColorsValue').textContent = v === 0 ? '不限' : v;
+ });
+ }
+
+ ['brightness', 'contrast', 'saturation'].forEach(name => {
+ const slider = $(name + 'Slider');
+ if (!slider) return;
+ slider.addEventListener('input', e => {
+ this[name] = parseInt(e.target.value);
+ const label = $(name + 'Value');
+ if (label) label.textContent = e.target.value;
+ });
+ });
+ if ($('resetAdjust')) {
+ $('resetAdjust').addEventListener('click', () => {
+ ['brightness', 'contrast', 'saturation'].forEach(name => {
+ this[name] = 0;
+ const slider = $(name + 'Slider');
+ const label = $(name + 'Value');
+ if (slider) slider.value = 0;
+ if (label) label.textContent = '0';
+ });
+ });
+ }
+
+ // Buttons
+ if ($('convertBtn')) $('convertBtn').addEventListener('click', () => this._generate());
+ if ($('exportBtn')) $('exportBtn').addEventListener('click', () => this._export());
+ // if ($('exportPdfBtn')) $('exportPdfBtn').addEventListener('click', () => this._exportPDF());
+ if ($('compareBtn')) $('compareBtn').addEventListener('click', () => this._toggleCompare());
+ if ($('fullscreenBtn')) $('fullscreenBtn').addEventListener('click', () => this._toggleFullscreen());
+
+ document.addEventListener('fullscreenchange', () => this._onFullscreenChange());
+ document.addEventListener('webkitfullscreenchange', () => this._onFullscreenChange());
+ document.addEventListener('keydown', e => {
+ if (e.key === 'Escape' && document.querySelector('.pattern-container.fake-fullscreen')) {
+ e.preventDefault();
+ this._toggleFullscreen();
+ }
+ });
+
+ // Toggles
+ if ($('showCodes')) $('showCodes').addEventListener('change', e => { this.showCodes = e.target.checked; this._draw(); });
+ if ($('showGrid')) $('showGrid').addEventListener('change', e => { this.showGrid = e.target.checked; this._draw(); });
+ if ($('showBoardLines')) $('showBoardLines').addEventListener('change', e => { this.showBoardLines = e.target.checked; this._draw(); });
+ if ($('hideBg')) $('hideBg').addEventListener('change', e => { this.hideBg = e.target.checked; this._draw(); });
+ if ($('editMode')) $('editMode').addEventListener('change', e => {
+ this.editMode = e.target.checked;
+ this._updateEditModeUI();
+ });
+
+ // Canvas hover / zoom / pan
+ this.canvas.addEventListener('mousemove', e => this._onCanvasHover(e));
+ this.canvas.addEventListener('mouseleave', () => {
+ const tip = $('beadTooltip');
+ if (tip) tip.classList.add('hidden');
+ });
+
+ this.canvas.addEventListener('wheel', e => {
+ if (!this.pattern) return;
+ e.preventDefault();
+ const rect = this.canvas.getBoundingClientRect();
+ const mx = e.clientX - rect.left, my = e.clientY - rect.top;
+ const factor = e.deltaY < 0 ? 1.12 : 1 / 1.12;
+ const nz = Math.max(0.05, Math.min(15, this.zoom * factor));
+ this.panX = mx - (mx - this.panX) * (nz / this.zoom);
+ this.panY = my - (my - this.panY) * (nz / this.zoom);
+ this.zoom = nz;
+ this._draw();
+ }, { passive: false });
+
+ this.canvas.addEventListener('mousedown', e => {
+ if (!this.pattern) return;
+ e.preventDefault();
+ this._editDownPos = { x: e.clientX, y: e.clientY };
+ this._panning = true;
+ this._lastX = e.clientX;
+ this._lastY = e.clientY;
+ if (!this.editMode) this.canvas.style.cursor = 'grabbing';
+ });
+ window.addEventListener('mousemove', e => {
+ if (!this._panning) return;
+ this.panX += e.clientX - this._lastX;
+ this.panY += e.clientY - this._lastY;
+ this._lastX = e.clientX;
+ this._lastY = e.clientY;
+ this._draw();
+ });
+ window.addEventListener('mouseup', e => {
+ if (this._panning) {
+ this._panning = false;
+ this.canvas.style.cursor = this.editMode ? 'crosshair' : 'grab';
+ if (this.editMode && this._editDownPos) {
+ const dx = e.clientX - this._editDownPos.x;
+ const dy = e.clientY - this._editDownPos.y;
+ if (Math.abs(dx) < 4 && Math.abs(dy) < 4) this._onBeadClick(e);
+ }
+ }
+ this._editDownPos = null;
+ });
+
+ // Touch
+ let lastTouchDist = 0;
+ this.canvas.addEventListener('touchstart', e => {
+ if (e.touches.length === 1) {
+ this._panning = true;
+ this._lastX = e.touches[0].clientX;
+ this._lastY = e.touches[0].clientY;
+ } else if (e.touches.length === 2) {
+ lastTouchDist = Math.hypot(
+ e.touches[0].clientX - e.touches[1].clientX,
+ e.touches[0].clientY - e.touches[1].clientY
+ );
+ }
+ e.preventDefault();
+ }, { passive: false });
+ this.canvas.addEventListener('touchmove', e => {
+ if (e.touches.length === 1 && this._panning) {
+ this.panX += e.touches[0].clientX - this._lastX;
+ this.panY += e.touches[0].clientY - this._lastY;
+ this._lastX = e.touches[0].clientX;
+ this._lastY = e.touches[0].clientY;
+ this._draw();
+ } else if (e.touches.length === 2) {
+ const dist = Math.hypot(
+ e.touches[0].clientX - e.touches[1].clientX,
+ e.touches[0].clientY - e.touches[1].clientY
+ );
+ if (lastTouchDist > 0) {
+ const factor = dist / lastTouchDist;
+ const nz = Math.max(0.05, Math.min(15, this.zoom * factor));
+ const rect = this.canvas.getBoundingClientRect();
+ const cx = ((e.touches[0].clientX + e.touches[1].clientX) / 2) - rect.left;
+ const cy = ((e.touches[0].clientY + e.touches[1].clientY) / 2) - rect.top;
+ this.panX = cx - (cx - this.panX) * (nz / this.zoom);
+ this.panY = cy - (cy - this.panY) * (nz / this.zoom);
+ this.zoom = nz;
+ this._draw();
+ }
+ lastTouchDist = dist;
+ }
+ e.preventDefault();
+ }, { passive: false });
+ this.canvas.addEventListener('touchend', () => { this._panning = false; lastTouchDist = 0; });
+
+ const container = document.querySelector('.pattern-container');
+ if (container) {
+ const ro = new ResizeObserver(() => { if (this.pattern) this._fitAndDraw(); });
+ ro.observe(container);
+ }
+
+ this._bindCrop();
+ }
+
+ /* ═══════════ Crop ═══════════ */
+
+ _bindCrop() {
+ const $ = id => document.getElementById(id);
+ const overlay = $('cropOverlay');
+ const cropBox = $('cropBox');
+ if (!overlay || !cropBox) return;
+
+ if ($('cropToggle')) {
+ $('cropToggle').addEventListener('click', () => {
+ this._cropping ? this._exitCrop() : this._enterCrop();
+ });
+ }
+ if ($('cropApply')) $('cropApply').addEventListener('click', () => this._applyCrop());
+ if ($('cropCancel')) $('cropCancel').addEventListener('click', () => this._exitCrop());
+
+ overlay.addEventListener('mousedown', e => {
+ e.preventDefault();
+ const rect = overlay.getBoundingClientRect();
+ this._cropDrag = true;
+ this._cropStart = { x: e.clientX - rect.left, y: e.clientY - rect.top };
+ cropBox.style.left = this._cropStart.x + 'px';
+ cropBox.style.top = this._cropStart.y + 'px';
+ cropBox.style.width = '0';
+ cropBox.style.height = '0';
+ });
+ overlay.addEventListener('mousemove', e => {
+ if (!this._cropDrag) return;
+ const rect = overlay.getBoundingClientRect();
+ const cx = e.clientX - rect.left, cy = e.clientY - rect.top;
+ const x = Math.min(this._cropStart.x, cx);
+ const y = Math.min(this._cropStart.y, cy);
+ cropBox.style.left = x + 'px';
+ cropBox.style.top = y + 'px';
+ cropBox.style.width = Math.abs(cx - this._cropStart.x) + 'px';
+ cropBox.style.height = Math.abs(cy - this._cropStart.y) + 'px';
+ });
+ const finishDrag = () => {
+ if (!this._cropDrag) return;
+ this._cropDrag = false;
+ const rect = overlay.getBoundingClientRect();
+ if (!rect.width || !rect.height) return;
+ const boxRect = cropBox.getBoundingClientRect();
+ if (boxRect.width < 5 || boxRect.height < 5) return;
+ this._cropRect = {
+ x: Math.max(0, (boxRect.left - rect.left) / rect.width),
+ y: Math.max(0, (boxRect.top - rect.top) / rect.height),
+ w: Math.min(1, boxRect.width / rect.width),
+ h: Math.min(1, boxRect.height / rect.height),
+ };
+ };
+ overlay.addEventListener('mouseup', finishDrag);
+ window.addEventListener('mouseup', finishDrag);
+ }
+
+ _enterCrop() {
+ if (!this.image) return;
+ this._cropping = true;
+ this._cropRect = null;
+ const overlay = document.getElementById('cropOverlay');
+ const actions = document.getElementById('cropActions');
+ const toggle = document.getElementById('cropToggle');
+ if (overlay) overlay.classList.remove('hidden');
+ if (actions) actions.classList.remove('hidden');
+ if (toggle) toggle.textContent = '✂️ 裁剪中…';
+ }
+
+ _exitCrop() {
+ this._cropping = false;
+ this._cropRect = null;
+ const overlay = document.getElementById('cropOverlay');
+ const actions = document.getElementById('cropActions');
+ const toggle = document.getElementById('cropToggle');
+ if (overlay) overlay.classList.add('hidden');
+ if (actions) actions.classList.add('hidden');
+ if (toggle) toggle.textContent = '✂️ 裁剪图片';
+ }
+
+ _applyCrop() {
+ if (!this._cropRect || !this.image) { this._exitCrop(); return; }
+ const { x, y, w, h } = this._cropRect;
+ if (w < 0.02 || h < 0.02) { this._exitCrop(); return; }
+
+ const img = this.image;
+ const sx = Math.round(x * img.naturalWidth);
+ const sy = Math.round(y * img.naturalHeight);
+ const sw = Math.round(w * img.naturalWidth);
+ const sh = Math.round(h * img.naturalHeight);
+
+ const cvs = document.createElement('canvas');
+ cvs.width = sw; cvs.height = sh;
+ cvs.getContext('2d').drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh);
+
+ const cropped = new Image();
+ cropped.onload = () => {
+ this.croppedImage = cropped;
+ this._imageDataUrl = cropped.src;
+ this._restoreOriginalDataUrl = '';
+ this._restoredSource = false;
+ this._resetRestorePreviewState();
+ const preview = document.getElementById('previewImage');
+ if (preview) preview.src = cropped.src;
+ this._refreshHeightLabel();
+ this._exitCrop();
+ this._setRestoreStatus('');
+ this._syncRestoreUI();
+ };
+ cropped.src = cvs.toDataURL('image/png');
+ }
+
+ /* ═══════════ Image loading ═══════════ */
+
+ _loadImage(file) {
+ const reader = new FileReader();
+ reader.onload = e => {
+ this._applyImageDataUrl(e.target.result).catch(() => {
+ alert('图片加载失败,请换一张图片再试');
+ });
+ };
+ reader.readAsDataURL(file);
+ }
+
+ _applyImageDataUrl(dataUrl, { preserveRestoreBase = false } = {}) {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ img.onload = () => {
+ this.image = img;
+ this.croppedImage = null;
+ this._imageDataUrl = dataUrl;
+ const preview = document.getElementById('previewImage');
+ const previewContainer = document.getElementById('previewContainer');
+ const convertBtn = document.getElementById('convertBtn');
+ if (preview) preview.src = dataUrl;
+ if (previewContainer) previewContainer.classList.remove('hidden');
+ if (convertBtn) convertBtn.disabled = false;
+ this._resetRestorePreviewState();
+ this._refreshHeightLabel();
+ this._exitCrop();
+ if (!preserveRestoreBase) {
+ this._restoreOriginalDataUrl = '';
+ this._restoredSource = false;
+ this._setRestoreStatus('');
+ }
+ this._syncRestoreUI();
+ resolve();
+ };
+ img.onerror = () => reject(new Error('图片加载失败'));
+ img.src = dataUrl;
+ });
+ }
+
+ _getActivePreviewDataUrl() {
+ const preview = document.getElementById('previewImage');
+ if (preview && preview.src && preview.src.startsWith('data:image/')) return preview.src;
+ return this._imageDataUrl || '';
+ }
+
+ _refreshHeightLabel() {
+ const src = this.croppedImage || this.image;
+ if (!src) return;
+ const slider = document.getElementById('widthSlider');
+ const heightValue = document.getElementById('heightValue');
+ if (!slider || !heightValue) return;
+ const w = parseInt(slider.value);
+ heightValue.textContent = Math.round(w * src.height / src.width);
+ }
+
+ /* ═══════════ Pixel restore ═══════════ */
+
+ _resetRestorePreviewState() {
+ this._restorePreviewDataUrl = '';
+ this._restorePreviewMeta = null;
+ this._restoreRenderToken += 1;
+ const canvas = document.getElementById('restoreResultCanvas');
+ if (canvas) { canvas.width = 0; canvas.height = 0; }
+ const meta = document.getElementById('restoreMeta');
+ if (meta) meta.textContent = '';
+ this._setRestorePanelStatus('');
+ }
+
+ _setRestoreStatus(message, tone = 'info') {
+ const el = document.getElementById('restoreStatus');
+ if (!el) return;
+ if (!message) { el.textContent = ''; el.className = 'restore-status hidden'; return; }
+ el.textContent = message;
+ el.className = `restore-status restore-status-${tone}`;
+ }
+
+ _setRestorePanelStatus(message, tone = 'info') {
+ const el = document.getElementById('restorePanelStatus');
+ if (!el) return;
+ if (!message) { el.textContent = ''; el.className = 'restore-panel-status hidden'; return; }
+ el.textContent = message;
+ el.className = `restore-panel-status restore-panel-status-${tone}`;
+ }
+
+ _syncRestoreUI() {
+ const btn = document.getElementById('restoreBtn');
+ if (!btn) return;
+ const hasImage = !!(this.image || this.croppedImage || this._getActivePreviewDataUrl());
+ btn.disabled = this._restoreBusy || !hasImage;
+ btn.textContent = this._restoredSource && this._restoreOriginalDataUrl ? '↺ 恢复导入图' : '🖌️ 像素还原';
+ }
+
+ _syncRestorePanelControls() {
+ document.querySelectorAll('[data-restore-mode]').forEach(btn => {
+ btn.classList.toggle('active', btn.dataset.restoreMode === this._restoreMode);
+ });
+ const scale = document.getElementById('restoreScale');
+ if (scale) scale.value = String(this._restoreScale);
+ const applyBtn = document.getElementById('restoreApplyBtn');
+ if (applyBtn) {
+ applyBtn.disabled = this._restoreBusy || !this._restorePreviewDataUrl;
+ applyBtn.textContent = this._restoreBusy ? '处理中…' : '应用结果到主图';
+ }
+ const meta = document.getElementById('restoreMeta');
+ if (!meta) return;
+ if (this._restorePreviewMeta) {
+ const m = this._restorePreviewMeta;
+ meta.textContent = m.mode === 'smooth'
+ ? `提取 ${m.sampledWidth}×${m.sampledHeight} → 平滑 ${m.scale}x → ${m.outputWidth}×${m.outputHeight}`
+ : `提取 ${m.sampledWidth}×${m.sampledHeight} → 像素 ${m.scale}x → ${m.outputWidth}×${m.outputHeight}`;
+ } else {
+ const width = parseInt(document.getElementById('widthSlider')?.value, 10) || 50;
+ meta.textContent = `将按当前珠子宽度 ${width} 提取格子颜色`;
+ }
+ }
+
+ _openRestoreModal() {
+ const modal = document.getElementById('pixelRestoreModal');
+ const sourceDataUrl = this._getActivePreviewDataUrl();
+ if (!modal || !sourceDataUrl) {
+ this._setRestoreStatus('请先导入一张图片。', 'error');
+ return;
+ }
+ const originalImg = document.getElementById('restoreOriginalImg');
+ if (originalImg) originalImg.src = sourceDataUrl;
+ modal.classList.remove('hidden');
+ this._restorePreviewDataUrl = '';
+ this._restorePreviewMeta = null;
+ this._setRestorePanelStatus('正在本地提取格子颜色并生成预览...', 'info');
+ this._syncRestorePanelControls();
+ this._renderRestorePreview();
+ }
+
+ _closeRestoreModal() {
+ const modal = document.getElementById('pixelRestoreModal');
+ if (modal) modal.classList.add('hidden');
+ }
+
+ async _revertRestoredImage() {
+ this._restoreBusy = true;
+ this._syncRestoreUI();
+ this._setRestoreStatus('正在恢复原导入图...', 'info');
+ try {
+ await this._applyImageDataUrl(this._restoreOriginalDataUrl);
+ this._setRestoreStatus('已恢复原导入图。', 'success');
+ } catch (error) {
+ this._setRestoreStatus(error.message || '恢复失败', 'error');
+ } finally {
+ this._restoreBusy = false;
+ this._syncRestoreUI();
+ this._syncRestorePanelControls();
+ }
+ }
+
+ async _renderRestorePreview() {
+ const srcImage = this.croppedImage || this.image;
+ const restoreCanvas = document.getElementById('restoreResultCanvas');
+ if (!srcImage || !restoreCanvas) return;
+ if (typeof PixelRestoreEngine === 'undefined') {
+ this._setRestorePanelStatus('像素还原模块未加载', 'error');
+ return;
+ }
+ const renderToken = ++this._restoreRenderToken;
+ const gridWidth = parseInt(document.getElementById('widthSlider')?.value, 10) || 50;
+ this._restoreBusy = true;
+ this._restorePreviewDataUrl = '';
+ this._restorePreviewMeta = null;
+ this._syncRestoreUI();
+ this._syncRestorePanelControls();
+ this._setRestorePanelStatus(this._restoreMode === 'smooth' ? '正在生成平滑预览...' : '正在生成像素预览...', 'info');
+
+ await new Promise(r => requestAnimationFrame(r));
+ try {
+ const result = PixelRestoreEngine.restore(srcImage, {
+ gridWidth, mode: this._restoreMode, scale: this._restoreScale,
+ });
+ if (renderToken !== this._restoreRenderToken) return;
+ restoreCanvas.width = result.outputWidth;
+ restoreCanvas.height = result.outputHeight;
+ const ctx = restoreCanvas.getContext('2d');
+ ctx.imageSmoothingEnabled = false;
+ ctx.clearRect(0, 0, restoreCanvas.width, restoreCanvas.height);
+ ctx.drawImage(result.outputCanvas, 0, 0);
+ this._restorePreviewDataUrl = result.outputCanvas.toDataURL('image/png');
+ this._restorePreviewMeta = result;
+ this._setRestorePanelStatus(`已提取 ${result.sampledWidth}×${result.sampledHeight} 格子颜色`, 'success');
+ } catch (error) {
+ if (renderToken !== this._restoreRenderToken) return;
+ this._setRestorePanelStatus(error.message || '还原失败', 'error');
+ } finally {
+ if (renderToken === this._restoreRenderToken) {
+ this._restoreBusy = false;
+ this._syncRestoreUI();
+ this._syncRestorePanelControls();
+ }
+ }
+ }
+
+ async _applyRestorePreview() {
+ if (!this._restorePreviewDataUrl || !this._restorePreviewMeta) {
+ this._setRestorePanelStatus('请先等待预览生成完成。', 'error');
+ return;
+ }
+ const originalPreview = this._getActivePreviewDataUrl();
+ if (!originalPreview) {
+ this._setRestorePanelStatus('请先导入一张图片。', 'error');
+ return;
+ }
+ this._restoreBusy = true;
+ this._syncRestoreUI();
+ this._setRestorePanelStatus('正在应用还原结果...', 'info');
+ try {
+ await this._applyImageDataUrl(this._restorePreviewDataUrl, { preserveRestoreBase: true });
+ this._restoreOriginalDataUrl = originalPreview;
+ this._restoredSource = true;
+ this._closeRestoreModal();
+ this._setRestoreStatus('已应用像素还原结果。', 'success');
+ } catch (error) {
+ this._setRestorePanelStatus(error.message || '应用失败', 'error');
+ } finally {
+ this._restoreBusy = false;
+ this._syncRestoreUI();
+ this._syncRestorePanelControls();
+ }
+ }
+
+ async _restoreSourceImage() {
+ if (this._restoreBusy) return;
+ if (this._restoredSource && this._restoreOriginalDataUrl) {
+ await this._revertRestoredImage();
+ return;
+ }
+ if (!this._getActivePreviewDataUrl()) {
+ this._setRestoreStatus('请先导入一张图片。', 'error');
+ return;
+ }
+ this._openRestoreModal();
+ }
+
+ /* ═══════════ Generate ═══════════ */
+
+ _generate() {
+ const srcImage = this.croppedImage || this.image;
+ if (!srcImage) return;
+
+ const btn = document.getElementById('convertBtn');
+ if (btn) { btn.textContent = '⏳ 生成中…'; btn.disabled = true; }
+
+ requestAnimationFrame(() => {
+ let width = parseInt(document.getElementById('widthSlider')?.value || '50', 10);
+ const brand = document.getElementById('brandSelect')?.value || 'mard';
+ const maxColors = parseInt(document.getElementById('maxColorsSlider')?.value || '0', 10);
+ const whiteBgEl = document.getElementById('whiteBgEmpty');
+ const whiteBgEmpty = whiteBgEl ? whiteBgEl.checked : false;
+ const palette = BEAD_PALETTES[brand].colors;
+
+ const adjustedImage = this._applyAdjustments(srcImage);
+ this.pattern = this.converter.convert(adjustedImage, width, palette, maxColors, { whiteBgEmpty });
+ this.bgCode = this._detectBackgroundCode(this.pattern);
+
+ if (this.emptyState) this.emptyState.classList.add('hidden');
+ document.querySelector('.pattern-container')?.classList.add('has-pattern');
+ this._fitAndDraw();
+ this._renderLegend();
+ this._renderStats();
+
+ const exportBtn = document.getElementById('exportBtn');
+ // const exportPdfBtn = document.getElementById('exportPdfBtn');
+ const compareBtn = document.getElementById('compareBtn');
+ const fullscreenBtn = document.getElementById('fullscreenBtn');
+ if (exportBtn) exportBtn.disabled = false;
+ // if (exportPdfBtn) exportPdfBtn.disabled = false;
+ if (compareBtn) compareBtn.classList.remove('hidden');
+ if (fullscreenBtn) fullscreenBtn.classList.remove('hidden');
+
+ if (btn) { btn.textContent = '🔄 生成图案'; btn.disabled = false; }
+ });
+ }
+
+ _detectBackgroundCode(pattern) {
+ if (!pattern) return null;
+ const { grid, width: W, height: H } = pattern;
+ const edgeCounts = {};
+ let perimeter = 0;
+ const visit = (x, y) => {
+ perimeter++;
+ const c = grid[y] && grid[y][x];
+ if (!c) return;
+ edgeCounts[c.code] = (edgeCounts[c.code] || 0) + 1;
+ };
+ for (let x = 0; x < W; x++) { visit(x, 0); if (H > 1) visit(x, H - 1); }
+ for (let y = 1; y < H - 1; y++) { visit(0, y); if (W > 1) visit(W - 1, y); }
+ const best = Object.entries(edgeCounts).sort((a, b) => b[1] - a[1])[0];
+ if (!best || !perimeter) return null;
+ const [code, count] = best;
+ return count / perimeter >= 0.35 ? code : null;
+ }
+
+ _applyAdjustments(img) {
+ if (this.brightness === 0 && this.contrast === 0 && this.saturation === 0) return img;
+ const cvs = document.createElement('canvas');
+ cvs.width = img.naturalWidth || img.width;
+ cvs.height = img.naturalHeight || img.height;
+ const ctx = cvs.getContext('2d');
+ ctx.filter = `brightness(${100 + this.brightness}%) contrast(${100 + this.contrast}%) saturate(${100 + this.saturation}%)`;
+ ctx.drawImage(img, 0, 0);
+ return cvs;
+ }
+
+ /* ═══════════ Canvas render ═══════════ */
+
+ _fitAndDraw() {
+ const container = document.querySelector('.pattern-container');
+ if (!container) return;
+ this.canvas.width = container.clientWidth;
+ this.canvas.height = container.clientHeight;
+ this.canvas.style.cursor = 'grab';
+ if (!this.pattern) return;
+ const pw = this.pattern.width * this.CELL + this.AXIS_M * 2;
+ const ph = this.pattern.height * this.CELL + this.AXIS_M * 2;
+ this.zoom = Math.min(this.canvas.width / pw, this.canvas.height / ph, 1);
+ this.panX = (this.canvas.width - pw * this.zoom) / 2;
+ this.panY = (this.canvas.height - ph * this.zoom) / 2;
+ this._draw();
+ }
+
+ _draw() {
+ if (!this.pattern) return;
+ const { ctx, CELL, AXIS_M } = this;
+ const { grid, width: W, height: H } = this.pattern;
+
+ ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
+ ctx.save();
+ ctx.translate(this.panX, this.panY);
+ ctx.scale(this.zoom, this.zoom);
+
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(AXIS_M, AXIS_M, W * CELL, H * CELL);
+
+ for (let y = 0; y < H; y++) {
+ for (let x = 0; x < W; x++) {
+ const c = grid[y][x];
+ if (!c) continue;
+ if (this.hideBg && this.bgCode && c.code === this.bgCode) continue;
+ ctx.fillStyle = c.hex;
+ ctx.fillRect(AXIS_M + x * CELL, AXIS_M + y * CELL, CELL, CELL);
+ }
+ }
+
+ if (this.showGrid) {
+ ctx.strokeStyle = 'rgba(0,0,0,0.12)';
+ ctx.lineWidth = 0.5;
+ for (let x = 0; x <= W; x++) {
+ const px = AXIS_M + x * CELL;
+ ctx.beginPath(); ctx.moveTo(px, AXIS_M); ctx.lineTo(px, AXIS_M + H * CELL); ctx.stroke();
+ }
+ for (let y = 0; y <= H; y++) {
+ const py = AXIS_M + y * CELL;
+ ctx.beginPath(); ctx.moveTo(AXIS_M, py); ctx.lineTo(AXIS_M + W * CELL, py); ctx.stroke();
+ }
+ ctx.strokeStyle = 'rgba(0,0,0,0.35)';
+ ctx.lineWidth = 1.2;
+ for (let x = 5; x <= W; x += 5) {
+ const px = AXIS_M + x * CELL;
+ ctx.beginPath(); ctx.moveTo(px, AXIS_M); ctx.lineTo(px, AXIS_M + H * CELL); ctx.stroke();
+ }
+ for (let y = 5; y <= H; y += 5) {
+ const py = AXIS_M + y * CELL;
+ ctx.beginPath(); ctx.moveTo(AXIS_M, py); ctx.lineTo(AXIS_M + W * CELL, py); ctx.stroke();
+ }
+ }
+
+ if (this.showCodes && this.zoom >= 0.35) {
+ const fs = Math.min(10, CELL * 0.42);
+ ctx.font = `bold ${fs}px -apple-system, sans-serif`;
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ for (let y = 0; y < H; y++) {
+ for (let x = 0; x < W; x++) {
+ const c = grid[y][x];
+ if (!c) continue;
+ if (this.hideBg && this.bgCode && c.code === this.bgCode) continue;
+ const brightness = (c.rgb.r * 299 + c.rgb.g * 587 + c.rgb.b * 114) / 1000;
+ ctx.fillStyle = brightness > 140 ? '#000' : '#FFF';
+ ctx.fillText(c.code, AXIS_M + x * CELL + CELL / 2, AXIS_M + y * CELL + CELL / 2);
+ }
+ }
+ }
+
+ ctx.fillStyle = '#555';
+ ctx.font = '9px -apple-system, sans-serif';
+ ctx.textAlign = 'center'; ctx.textBaseline = 'bottom';
+ for (let x = 0; x < W; x++) ctx.fillText(x + 1, AXIS_M + x * CELL + CELL / 2, AXIS_M - 3);
+ ctx.textAlign = 'center'; ctx.textBaseline = 'top';
+ for (let x = 0; x < W; x++) ctx.fillText(x + 1, AXIS_M + x * CELL + CELL / 2, AXIS_M + H * CELL + 3);
+ ctx.textAlign = 'right'; ctx.textBaseline = 'middle';
+ for (let y = 0; y < H; y++) ctx.fillText(y + 1, AXIS_M - 4, AXIS_M + y * CELL + CELL / 2);
+ ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
+ for (let y = 0; y < H; y++) ctx.fillText(y + 1, AXIS_M + W * CELL + 4, AXIS_M + y * CELL + CELL / 2);
+
+ if (this.showBoardLines) {
+ ctx.strokeStyle = '#e53935';
+ ctx.lineWidth = 2;
+ ctx.setLineDash([6, 3]);
+ for (let bx = 29; bx < W; bx += 29) {
+ const px = AXIS_M + bx * CELL;
+ ctx.beginPath(); ctx.moveTo(px, AXIS_M); ctx.lineTo(px, AXIS_M + H * CELL); ctx.stroke();
+ }
+ for (let by = 29; by < H; by += 29) {
+ const py = AXIS_M + by * CELL;
+ ctx.beginPath(); ctx.moveTo(AXIS_M, py); ctx.lineTo(AXIS_M + W * CELL, py); ctx.stroke();
+ }
+ ctx.setLineDash([]);
+ }
+
+ ctx.strokeStyle = '#333';
+ ctx.lineWidth = 1.5;
+ ctx.strokeRect(AXIS_M, AXIS_M, W * CELL, H * CELL);
+ ctx.restore();
+ }
+
+ _onCanvasHover(e) {
+ if (!this.pattern) return;
+ const tip = document.getElementById('beadTooltip');
+ if (!tip) return;
+ const rect = this.canvas.getBoundingClientRect();
+ const mx = e.clientX - rect.left, my = e.clientY - rect.top;
+ const gx = Math.floor(((mx - this.panX) / this.zoom - this.AXIS_M) / this.CELL);
+ const gy = Math.floor(((my - this.panY) / this.zoom - this.AXIS_M) / this.CELL);
+ const { width: W, height: H, grid } = this.pattern;
+ if (gx < 0 || gx >= W || gy < 0 || gy >= H || !grid[gy][gx]) {
+ tip.classList.add('hidden');
+ return;
+ }
+ const c = grid[gy][gx];
+ tip.innerHTML = `${c.code} ${c.name}
坐标 (${gx + 1}, ${gy + 1})`;
+ tip.style.left = (e.clientX + 14) + 'px';
+ tip.style.top = (e.clientY + 14) + 'px';
+ tip.classList.remove('hidden');
+ }
+
+ /* ═══════════ Edit mode ═══════════ */
+
+ _updateEditModeUI() {
+ const container = document.querySelector('.pattern-container');
+ if (this.editMode) {
+ this.canvas.style.cursor = 'crosshair';
+ this.canvas.classList.add('canvas-edit-mode');
+ if (container && !container.querySelector('.edit-mode-hint')) {
+ const hint = document.createElement('div');
+ hint.className = 'edit-mode-hint';
+ hint.textContent = '✏️ 编辑模式:点击珠子更换颜色';
+ container.appendChild(hint);
+ }
+ } else {
+ this.canvas.style.cursor = 'grab';
+ this.canvas.classList.remove('canvas-edit-mode');
+ const hint = container?.querySelector('.edit-mode-hint');
+ if (hint) hint.remove();
+ this._closeBeadPicker();
+ }
+ }
+
+ _screenToGrid(clientX, clientY) {
+ const rect = this.canvas.getBoundingClientRect();
+ const mx = clientX - rect.left, my = clientY - rect.top;
+ return {
+ gx: Math.floor(((mx - this.panX) / this.zoom - this.AXIS_M) / this.CELL),
+ gy: Math.floor(((my - this.panY) / this.zoom - this.AXIS_M) / this.CELL),
+ };
+ }
+
+ _onBeadClick(e) {
+ if (!this.pattern) return;
+ const { gx, gy } = this._screenToGrid(e.clientX, e.clientY);
+ const { width: W, height: H } = this.pattern;
+ if (gx < 0 || gx >= W || gy < 0 || gy >= H) return;
+ this._openBeadPicker(gx, gy, e.clientX, e.clientY);
+ }
+
+ _openBeadPicker(gx, gy, px, py) {
+ const picker = document.getElementById('beadPicker');
+ if (!picker) return;
+ const brand = document.getElementById('brandSelect')?.value || 'mard';
+ const palette = BEAD_PALETTES[brand].colors;
+ const current = this.pattern.grid[gy]?.[gx];
+
+ const vw = window.innerWidth, vh = window.innerHeight;
+ let left = px + 16, top = py - 40;
+ if (left + 270 > vw) left = px - 280;
+ if (top + 360 > vh) top = vh - 370;
+ if (top < 8) top = 8;
+ picker.style.left = left + 'px';
+ picker.style.top = top + 'px';
+
+ const title = document.getElementById('bpTitle');
+ if (title) title.textContent = `坐标 (${gx + 1}, ${gy + 1})` + (current ? ` · ${current.code}` : '');
+ this._editTarget = { gx, gy };
+
+ const container = document.getElementById('bpColors');
+ const searchInput = document.getElementById('bpSearch');
+ if (searchInput) searchInput.value = '';
+
+ const renderSwatches = (filter = '') => {
+ if (!container) return;
+ const lower = filter.toLowerCase();
+ container.innerHTML = palette
+ .filter(c => !filter || c.code.toLowerCase().includes(lower) || c.name.toLowerCase().includes(lower))
+ .map(c => {
+ const active = current && c.code === current.code ? ' bp-active' : '';
+ return ``;
+ }).join('');
+ container.querySelectorAll('.bp-swatch').forEach(el => {
+ el.addEventListener('click', () => this._applyBeadEdit(el.dataset.code));
+ });
+ };
+ renderSwatches();
+ if (searchInput) searchInput.oninput = () => renderSwatches(searchInput.value);
+ const closeBtn = document.getElementById('bpClose');
+ if (closeBtn) closeBtn.onclick = () => this._closeBeadPicker();
+
+ picker.classList.remove('hidden');
+ if (searchInput) searchInput.focus();
+
+ setTimeout(() => {
+ this._pickerOutsideHandler = e => {
+ if (!picker.contains(e.target)) this._closeBeadPicker();
+ };
+ window.addEventListener('mousedown', this._pickerOutsideHandler);
+ }, 100);
+ }
+
+ _closeBeadPicker() {
+ const picker = document.getElementById('beadPicker');
+ if (picker) picker.classList.add('hidden');
+ if (this._pickerOutsideHandler) {
+ window.removeEventListener('mousedown', this._pickerOutsideHandler);
+ this._pickerOutsideHandler = null;
+ }
+ }
+
+ _applyBeadEdit(code) {
+ if (!this._editTarget || !this.pattern) return;
+ const { gx, gy } = this._editTarget;
+ const brand = document.getElementById('brandSelect')?.value || 'mard';
+ const palette = BEAD_PALETTES[brand].colors;
+ const newColor = palette.find(c => c.code === code);
+ if (!newColor) return;
+
+ const rgb = this.converter.hexToRgb(newColor.hex);
+ const lab = this.converter.rgbToLab(rgb.r, rgb.g, rgb.b);
+ const colorObj = { ...newColor, rgb, lab };
+ const oldColor = this.pattern.grid[gy][gx];
+
+ this.pattern.grid[gy][gx] = colorObj;
+ if (oldColor) {
+ this.pattern.colorCounts[oldColor.code]--;
+ if (this.pattern.colorCounts[oldColor.code] <= 0) delete this.pattern.colorCounts[oldColor.code];
+ }
+ this.pattern.colorCounts[code] = (this.pattern.colorCounts[code] || 0) + 1;
+ this.pattern.uniqueColors = Object.keys(this.pattern.colorCounts).length;
+
+ this._draw();
+ this._renderLegend();
+ this._renderStats();
+ this._closeBeadPicker();
+ }
+
+ /* ═══════════ Legend & Stats ═══════════ */
+
+ _renderLegend() {
+ if (!this.pattern) return;
+ const section = document.getElementById('legendSection');
+ const container = document.getElementById('legendContent');
+ if (!section || !container) return;
+ section.classList.remove('hidden');
+ const brand = document.getElementById('brandSelect')?.value || 'mard';
+ const palette = BEAD_PALETTES[brand].colors;
+ const sorted = Object.entries(this.pattern.colorCounts).sort((a, b) => b[1] - a[1]);
+ container.innerHTML = sorted.map(([code, count]) => {
+ const c = palette.find(p => p.code === code);
+ if (!c) return '';
+ return `
+
+
${c.code}
+
${count}颗
+
`;
+ }).join('');
+ }
+
+ _renderStats() {
+ if (!this.pattern) return;
+ const section = document.getElementById('statsSection');
+ const content = document.getElementById('statsContent');
+ if (!section || !content) return;
+ section.classList.remove('hidden');
+ const { width, height, totalBeads, uniqueColors } = this.pattern;
+ const boards = Math.ceil(width / 29) * Math.ceil(height / 29);
+ content.innerHTML = `
+ 尺寸${width} × ${height}
+ 总珠子数${totalBeads.toLocaleString()}
+ 使用颜色${uniqueColors}
+ 拼豆板 (29×29)${boards} 块
+ `;
+ }
+
+ /* ═══════════ Export PNG(每颗珠子带色号) ═══════════ */
+
+ _export() {
+ if (!this.pattern) return;
+ const { grid, width: W, height: H, colorCounts } = this.pattern;
+ const CELL = 24, AXIS = 30;
+ const brand = document.getElementById('brandSelect')?.value || 'mard';
+ const palette = BEAD_PALETTES[brand].colors;
+ const sorted = Object.entries(colorCounts).sort((a, b) => b[1] - a[1]);
+
+ const legendItemW = 140;
+ const legendCols = Math.max(1, Math.floor((W * CELL) / legendItemW));
+ const legendRows = Math.ceil(sorted.length / legendCols);
+ const legendH = 20 + legendRows * 26 + 10;
+ const totalW = AXIS * 2 + W * CELL;
+ const totalH = AXIS * 2 + H * CELL + legendH;
+
+ const cvs = document.createElement('canvas');
+ cvs.width = totalW; cvs.height = totalH;
+ const ctx = cvs.getContext('2d');
+ ctx.fillStyle = '#FFF';
+ ctx.fillRect(0, 0, totalW, totalH);
+
+ for (let y = 0; y < H; y++) {
+ for (let x = 0; x < W; x++) {
+ const c = grid[y][x]; if (!c) continue;
+ if (this.hideBg && this.bgCode && c.code === this.bgCode) continue;
+ ctx.fillStyle = c.hex;
+ ctx.fillRect(AXIS + x * CELL, AXIS + y * CELL, CELL, CELL);
+ const fs = Math.min(10, CELL * 0.42);
+ ctx.font = `bold ${fs}px sans-serif`;
+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
+ const br = (c.rgb.r * 299 + c.rgb.g * 587 + c.rgb.b * 114) / 1000;
+ ctx.fillStyle = br > 140 ? '#000' : '#FFF';
+ ctx.fillText(c.code, AXIS + x * CELL + CELL / 2, AXIS + y * CELL + CELL / 2);
+ }
+ }
+
+ ctx.strokeStyle = 'rgba(0,0,0,0.15)';
+ ctx.lineWidth = 0.5;
+ for (let x = 0; x <= W; x++) {
+ ctx.beginPath(); ctx.moveTo(AXIS + x * CELL, AXIS); ctx.lineTo(AXIS + x * CELL, AXIS + H * CELL); ctx.stroke();
+ }
+ for (let y = 0; y <= H; y++) {
+ ctx.beginPath(); ctx.moveTo(AXIS, AXIS + y * CELL); ctx.lineTo(AXIS + W * CELL, AXIS + y * CELL); ctx.stroke();
+ }
+ ctx.strokeStyle = 'rgba(0,0,0,0.35)'; ctx.lineWidth = 1.2;
+ for (let x = 5; x <= W; x += 5) {
+ ctx.beginPath(); ctx.moveTo(AXIS + x * CELL, AXIS); ctx.lineTo(AXIS + x * CELL, AXIS + H * CELL); ctx.stroke();
+ }
+ for (let y = 5; y <= H; y += 5) {
+ ctx.beginPath(); ctx.moveTo(AXIS, AXIS + y * CELL); ctx.lineTo(AXIS + W * CELL, AXIS + y * CELL); ctx.stroke();
+ }
+ ctx.strokeStyle = '#333'; ctx.lineWidth = 1.5;
+ ctx.strokeRect(AXIS, AXIS, W * CELL, H * CELL);
+
+ if (this.showBoardLines) {
+ ctx.strokeStyle = '#e53935'; ctx.lineWidth = 2;
+ ctx.setLineDash([6, 3]);
+ for (let bx = 29; bx < W; bx += 29) {
+ const px = AXIS + bx * CELL;
+ ctx.beginPath(); ctx.moveTo(px, AXIS); ctx.lineTo(px, AXIS + H * CELL); ctx.stroke();
+ }
+ for (let by = 29; by < H; by += 29) {
+ const py = AXIS + by * CELL;
+ ctx.beginPath(); ctx.moveTo(AXIS, py); ctx.lineTo(AXIS + W * CELL, py); ctx.stroke();
+ }
+ ctx.setLineDash([]);
+ }
+
+ ctx.fillStyle = '#555'; ctx.font = '9px sans-serif';
+ ctx.textAlign = 'center'; ctx.textBaseline = 'bottom';
+ for (let x = 0; x < W; x++) ctx.fillText(x + 1, AXIS + x * CELL + CELL / 2, AXIS - 2);
+ ctx.textAlign = 'center'; ctx.textBaseline = 'top';
+ for (let x = 0; x < W; x++) ctx.fillText(x + 1, AXIS + x * CELL + CELL / 2, AXIS + H * CELL + 2);
+ ctx.textAlign = 'right'; ctx.textBaseline = 'middle';
+ for (let y = 0; y < H; y++) ctx.fillText(y + 1, AXIS - 3, AXIS + y * CELL + CELL / 2);
+ ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
+ for (let y = 0; y < H; y++) ctx.fillText(y + 1, AXIS + W * CELL + 3, AXIS + y * CELL + CELL / 2);
+
+ const legTop = AXIS + H * CELL + AXIS + 4;
+ ctx.font = '11px sans-serif'; ctx.textBaseline = 'middle';
+ sorted.forEach(([code, count], i) => {
+ const c = palette.find(p => p.code === code); if (!c) return;
+ const col = i % legendCols, row = Math.floor(i / legendCols);
+ const lx = AXIS + col * legendItemW, ly = legTop + row * 26;
+ ctx.fillStyle = c.hex;
+ ctx.fillRect(lx, ly, 20, 20);
+ ctx.strokeStyle = '#ccc'; ctx.lineWidth = 0.5;
+ ctx.strokeRect(lx, ly, 20, 20);
+ ctx.fillStyle = '#333'; ctx.textAlign = 'left';
+ ctx.font = 'bold 11px sans-serif';
+ ctx.fillText(code, lx + 24, ly + 7);
+ ctx.font = '10px sans-serif'; ctx.fillStyle = '#666';
+ ctx.fillText(`(${count})`, lx + 24, ly + 18);
+ });
+
+ const a = document.createElement('a');
+ a.download = `bead-pattern-${W}x${H}.png`;
+ a.href = cvs.toDataURL('image/png');
+ a.click();
+ }
+
+ /* ═══════════ Fullscreen / Compare ═══════════ */
+
+ _toggleFullscreen() {
+ const container = document.querySelector('.pattern-container');
+ if (!container) return;
+ const isFs = document.fullscreenElement || document.webkitFullscreenElement;
+ if (isFs) {
+ (document.exitFullscreen || document.webkitExitFullscreen).call(document);
+ return;
+ }
+ if (container.classList.contains('fake-fullscreen')) {
+ container.classList.remove('fake-fullscreen');
+ const btn = document.getElementById('fullscreenBtn');
+ if (btn) btn.textContent = '⛶';
+ this._fitAndDraw();
+ return;
+ }
+ const tryNative = container.requestFullscreen || container.webkitRequestFullscreen;
+ if (tryNative) {
+ const timer = setTimeout(() => {
+ if (!document.fullscreenElement && !document.webkitFullscreenElement) this._fakeFull(container);
+ }, 300);
+ const p = tryNative.call(container);
+ if (p && p.then) p.catch(() => { clearTimeout(timer); this._fakeFull(container); });
+ } else {
+ this._fakeFull(container);
+ }
+ }
+
+ _fakeFull(container) {
+ container.classList.add('fake-fullscreen');
+ const btn = document.getElementById('fullscreenBtn');
+ if (btn) btn.textContent = '✕';
+ this._fitAndDraw();
+ }
+
+ _onFullscreenChange() {
+ const isFs = document.fullscreenElement || document.webkitFullscreenElement;
+ const btn = document.getElementById('fullscreenBtn');
+ if (btn) btn.textContent = isFs ? '✕' : '⛶';
+ }
+
+ _toggleCompare() {
+ const srcImage = this.croppedImage || this.image;
+ if (!this.pattern || !srcImage) return;
+ this._comparing = !this._comparing;
+ const btn = document.getElementById('compareBtn');
+ const container = document.querySelector('.pattern-container');
+ if (!container) return;
+
+ if (this._comparing) {
+ if (btn) btn.textContent = '🔀 隐藏原图';
+ let overlay = container.querySelector('.compare-overlay');
+ if (!overlay) {
+ overlay = document.createElement('div');
+ overlay.className = 'compare-overlay';
+ overlay.innerHTML = `
+
+
+
+
`;
+ container.appendChild(overlay);
+ document.getElementById('compareAlpha')?.addEventListener('input', e => {
+ overlay.querySelector('img').style.opacity = e.target.value / 100;
+ });
+ }
+ overlay.style.display = '';
+ } else {
+ if (btn) btn.textContent = '🔀 对比原图';
+ const overlay = container.querySelector('.compare-overlay');
+ if (overlay) overlay.style.display = 'none';
+ }
+ }
+
+ // /* ═══════════ PDF Export ═══════════ */
+
+ // _exportPDF() {
+ // if (!this.pattern) return;
+ // if (typeof window.jspdf === 'undefined') {
+ // alert('PDF 库加载中,请稍后再试');
+ // return;
+ // }
+ // const { jsPDF } = window.jspdf;
+ // const { grid, width: W, height: H, colorCounts, totalBeads } = this.pattern;
+ // const brand = document.getElementById('brandSelect')?.value || 'mard';
+ // const palette = BEAD_PALETTES[brand].colors;
+ // const sorted = Object.entries(colorCounts).sort((a, b) => b[1] - a[1]);
+
+ // const isWide = W > H;
+ // const doc = new jsPDF({ orientation: isWide ? 'landscape' : 'portrait', unit: 'mm', format: 'a4' });
+ // const pageW = doc.internal.pageSize.getWidth();
+ // const pageH = doc.internal.pageSize.getHeight();
+ // const margin = 10;
+
+ // doc.setFontSize(16);
+ // doc.text('拼豆图案', margin, margin + 6);
+ // doc.setFontSize(9);
+ // doc.text(`${W}×${H} | ${Object.keys(colorCounts).length}色 | ${totalBeads}珠 | ${BEAD_PALETTES[brand].name}`, margin, margin + 12);
+
+ // const cellPx = 12;
+ // const overviewCvs = document.createElement('canvas');
+ // overviewCvs.width = W * cellPx;
+ // overviewCvs.height = H * cellPx;
+ // const oCtx = overviewCvs.getContext('2d');
+ // for (let y = 0; y < H; y++) {
+ // for (let x = 0; x < W; x++) {
+ // const c = grid[y][x]; if (!c) continue;
+ // oCtx.fillStyle = c.hex;
+ // oCtx.fillRect(x * cellPx, y * cellPx, cellPx, cellPx);
+ // }
+ // }
+ // oCtx.strokeStyle = 'rgba(0,0,0,0.15)';
+ // oCtx.lineWidth = 0.5;
+ // for (let x = 0; x <= W; x++) { oCtx.beginPath(); oCtx.moveTo(x * cellPx, 0); oCtx.lineTo(x * cellPx, H * cellPx); oCtx.stroke(); }
+ // for (let y = 0; y <= H; y++) { oCtx.beginPath(); oCtx.moveTo(0, y * cellPx); oCtx.lineTo(W * cellPx, y * cellPx); oCtx.stroke(); }
+
+ // const imgData = overviewCvs.toDataURL('image/png');
+ // const availW = pageW - margin * 2;
+ // const availH = pageH - margin * 2 - 18;
+ // const scale = Math.min(availW / (W * cellPx) * (72 / 25.4), availH / (H * cellPx) * (72 / 25.4), 1);
+ // const drawW = W * cellPx * scale * (25.4 / 72);
+ // const drawH = H * cellPx * scale * (25.4 / 72);
+ // doc.addImage(imgData, 'PNG', margin, margin + 18, drawW, drawH);
+
+ // const BOARD = 29;
+ // const boardCols = Math.ceil(W / BOARD);
+ // const boardRows = Math.ceil(H / BOARD);
+
+ // for (let br = 0; br < boardRows; br++) {
+ // for (let bc = 0; bc < boardCols; bc++) {
+ // doc.addPage();
+ // const startX = bc * BOARD, startY = br * BOARD;
+ // const endX = Math.min(startX + BOARD, W);
+ // const endY = Math.min(startY + BOARD, H);
+ // const bw = endX - startX, bh = endY - startY;
+
+ // doc.setFontSize(10);
+ // doc.text(`拼豆板 ${br * boardCols + bc + 1} / ${boardCols * boardRows}`, margin, margin + 4);
+ // doc.setFontSize(8);
+ // doc.text(`坐标: (${startX + 1},${startY + 1}) ~ (${endX},${endY})`, margin, margin + 9);
+
+ // const boardCellPx = 18, boardAxisPx = 24;
+ // const boardCvs = document.createElement('canvas');
+ // boardCvs.width = boardAxisPx + bw * boardCellPx;
+ // boardCvs.height = boardAxisPx + bh * boardCellPx;
+ // const bCtx = boardCvs.getContext('2d');
+ // bCtx.fillStyle = '#fff';
+ // bCtx.fillRect(0, 0, boardCvs.width, boardCvs.height);
+
+ // for (let y = startY; y < endY; y++) {
+ // for (let x = startX; x < endX; x++) {
+ // const c = grid[y][x]; if (!c) continue;
+ // if (this.hideBg && this.bgCode && c.code === this.bgCode) continue;
+ // const px = boardAxisPx + (x - startX) * boardCellPx;
+ // const py = boardAxisPx + (y - startY) * boardCellPx;
+ // bCtx.fillStyle = c.hex;
+ // bCtx.fillRect(px, py, boardCellPx, boardCellPx);
+ // const fs = Math.min(8, boardCellPx * 0.45);
+ // bCtx.font = `bold ${fs}px sans-serif`;
+ // bCtx.textAlign = 'center'; bCtx.textBaseline = 'middle';
+ // const br2 = (c.rgb.r * 299 + c.rgb.g * 587 + c.rgb.b * 114) / 1000;
+ // bCtx.fillStyle = br2 > 140 ? '#000' : '#FFF';
+ // bCtx.fillText(c.code, px + boardCellPx / 2, py + boardCellPx / 2);
+ // }
+ // }
+ // bCtx.strokeStyle = 'rgba(0,0,0,0.2)'; bCtx.lineWidth = 0.5;
+ // for (let x = 0; x <= bw; x++) {
+ // bCtx.beginPath(); bCtx.moveTo(boardAxisPx + x * boardCellPx, boardAxisPx);
+ // bCtx.lineTo(boardAxisPx + x * boardCellPx, boardAxisPx + bh * boardCellPx); bCtx.stroke();
+ // }
+ // for (let y = 0; y <= bh; y++) {
+ // bCtx.beginPath(); bCtx.moveTo(boardAxisPx, boardAxisPx + y * boardCellPx);
+ // bCtx.lineTo(boardAxisPx + bw * boardCellPx, boardAxisPx + y * boardCellPx); bCtx.stroke();
+ // }
+ // bCtx.fillStyle = '#555'; bCtx.font = '8px sans-serif';
+ // bCtx.textAlign = 'center'; bCtx.textBaseline = 'bottom';
+ // for (let x = 0; x < bw; x++) bCtx.fillText(startX + x + 1, boardAxisPx + x * boardCellPx + boardCellPx / 2, boardAxisPx - 2);
+ // bCtx.textAlign = 'right'; bCtx.textBaseline = 'middle';
+ // for (let y = 0; y < bh; y++) bCtx.fillText(startY + y + 1, boardAxisPx - 3, boardAxisPx + y * boardCellPx + boardCellPx / 2);
+ // bCtx.strokeStyle = '#333'; bCtx.lineWidth = 1;
+ // bCtx.strokeRect(boardAxisPx, boardAxisPx, bw * boardCellPx, bh * boardCellPx);
+
+ // const boardImgData = boardCvs.toDataURL('image/png');
+ // const bAvailW = pageW - margin * 2;
+ // const bAvailH = pageH - margin * 2 - 14;
+ // const bScale = Math.min(bAvailW / boardCvs.width * (72 / 25.4), bAvailH / boardCvs.height * (72 / 25.4), 1);
+ // doc.addImage(boardImgData, 'PNG', margin, margin + 14,
+ // boardCvs.width * bScale * (25.4 / 72),
+ // boardCvs.height * bScale * (25.4 / 72));
+ // }
+ // }
+
+ // doc.addPage();
+ // doc.setFontSize(14);
+ // doc.text('材料清单', margin, margin + 6);
+ // doc.setFontSize(9);
+ // doc.text(`品牌: ${BEAD_PALETTES[brand].name} | 总珠数: ${totalBeads}`, margin, margin + 13);
+
+ // let listY = margin + 20;
+ // doc.setFontSize(8);
+ // sorted.forEach(([code, count]) => {
+ // const c = palette.find(p => p.code === code);
+ // if (!c) return;
+ // const rgb = this.converter.hexToRgb(c.hex);
+ // doc.setFillColor(rgb.r, rgb.g, rgb.b);
+ // doc.rect(margin, listY - 2.5, 4, 4, 'F');
+ // doc.setDrawColor(180, 180, 180);
+ // doc.rect(margin, listY - 2.5, 4, 4, 'S');
+ // doc.setTextColor(0, 0, 0);
+ // doc.text(`${code} ${count}颗`, margin + 6, listY);
+ // listY += 5;
+ // if (listY > pageH - margin) {
+ // doc.addPage();
+ // listY = margin + 8;
+ // }
+ // });
+
+ // doc.save(`bead-pattern-${W}x${H}.pdf`);
+ // }
+}
+
+document.addEventListener('DOMContentLoaded', () => {
+ window.app = new BeadPatternApp();
+});
\ No newline at end of file
diff --git a/public/bead-pattern-generator/js/colors.js b/public/bead-pattern-generator/js/colors.js
new file mode 100644
index 00000000000..c3709bbbd86
--- /dev/null
+++ b/public/bead-pattern-generator/js/colors.js
@@ -0,0 +1,396 @@
+/**
+ * 拼豆色卡数据定义
+ *
+ * 提供 BEAD_PALETTES 常量,包含三大品牌的完整色板:
+ * - MARD 拼豆:官方色卡整理(A 黄 / B 绿 / C 蓝 / D 紫 / E 肤 / F 红 / G 松 / H 灰 / M 暗色 + P 珠光 / Q 温变)
+ * - Perler Beads:英文色号与近似 hex
+ * - Hama Beads:英文色号与近似 hex
+ *
+ * 每个颜色包含 code(色号)、name(中文/英文名)、hex(近似色值),供图案转换、图例、编辑换色等功能使用。
+ */
+
+/**
+ * MARD 拼豆色卡 — 根据官方色卡整理
+ * 包含 A–M + H 共 9 个实色系列, 以及 P珠光/Q温变 特殊系列
+ * hex 值为从色卡取色的近似值
+ */
+const BEAD_PALETTES = {
+
+ mard: {
+ name: 'MARD 拼豆',
+ colors: [
+ // ═══════════ A 黄色系 ═══════════
+ { code: 'A1', name: '奶白', hex: '#FFF8E1' },
+ { code: 'A2', name: '淡柠檬', hex: '#FFF9C4' },
+ { code: 'A3', name: '柠檬黄', hex: '#FFEE58' },
+ { code: 'A4', name: '鲜黄', hex: '#FFD600' },
+ { code: 'A5', name: '琥珀黄', hex: '#FFAB00' },
+ { code: 'A6', name: '深琥珀', hex: '#FF8F00' },
+ { code: 'A7', name: '焦琥珀', hex: '#EF6C00' },
+ { code: 'A8', name: '杏橙', hex: '#FFAD42' },
+ { code: 'A9', name: '亮橙', hex: '#E88A30' },
+ { code: 'A10', name: '焦橙', hex: '#D06020' },
+ { code: 'A11', name: '鲜橙', hex: '#FF7F00' },
+ { code: 'A12', name: '红橙', hex: '#CC4125' },
+ { code: 'A13', name: '棕褐', hex: '#8D6E63' },
+ { code: 'A14', name: '奶黄', hex: '#FFECB3' },
+ { code: 'A15', name: '象牙', hex: '#FFE4B5' },
+ { code: 'A16', name: '暖白', hex: '#FFFDE7' },
+ { code: 'A17', name: '金黄', hex: '#FFD54F' },
+ { code: 'A18', name: '焦糖', hex: '#B57030' },
+ { code: 'A19', name: '深焦糖', hex: '#9E6228' },
+ { code: 'A20', name: '亮金', hex: '#FFCA28' },
+ { code: 'A21', name: '巧克力', hex: '#6D4830' },
+ { code: 'A22', name: '深巧克力', hex: '#5C3D28' },
+ { code: 'A23', name: '咖啡棕', hex: '#503520' },
+ { code: 'A24', name: '深咖啡', hex: '#442D1A' },
+ { code: 'A25', name: '极深棕', hex: '#382515' },
+ { code: 'A26', name: '黑棕', hex: '#2E1E10' },
+
+ // ═══════════ B 绿色系 ═══════════
+ { code: 'B1', name: '荧光绿', hex: '#C6FF00' },
+ { code: 'B2', name: '亮黄绿', hex: '#AEEA00' },
+ { code: 'B3', name: '草绿', hex: '#64DD17' },
+ { code: 'B4', name: '鲜绿', hex: '#4CAF50' },
+ { code: 'B5', name: '翠绿', hex: '#43A047' },
+ { code: 'B6', name: '中绿', hex: '#388E3C' },
+ { code: 'B7', name: '深绿', hex: '#2E7D32' },
+ { code: 'B8', name: '墨绿', hex: '#1B5E20' },
+ { code: 'B9', name: '森林绿', hex: '#33691E' },
+ { code: 'B10', name: '暗绿', hex: '#194D19' },
+ { code: 'B11', name: '橄榄绿', hex: '#558B2F' },
+ { code: 'B12', name: '黄绿', hex: '#689F38' },
+ { code: 'B13', name: '嫩绿', hex: '#8BC34A' },
+ { code: 'B14', name: '春绿', hex: '#66BB6A' },
+ { code: 'B15', name: '薄荷绿', hex: '#81C784' },
+ { code: 'B16', name: '浅薄荷', hex: '#A5D6A7' },
+ { code: 'B17', name: '粉绿', hex: '#C8E6C9' },
+ { code: 'B18', name: '湖绿', hex: '#009688' },
+ { code: 'B19', name: '浅湖绿', hex: '#4DB6AC' },
+ { code: 'B20', name: '淡湖绿', hex: '#80CBC4' },
+ { code: 'B21', name: '水绿', hex: '#B2DFDB' },
+ { code: 'B22', name: '鸭绿', hex: '#00897B' },
+ { code: 'B23', name: '深鸭绿', hex: '#00695C' },
+ { code: 'B24', name: '极深绿', hex: '#004D40' },
+ { code: 'B25', name: '青绿', hex: '#26A69A' },
+ { code: 'B26', name: '苹果绿', hex: '#7CB342' },
+ { code: 'B27', name: '芥末绿', hex: '#827717' },
+ { code: 'B28', name: '深橄榄', hex: '#5D6B1A' },
+ { code: 'B29', name: '军绿', hex: '#4B5320' },
+ { code: 'B30', name: '灰绿', hex: '#6B8E5A' },
+ { code: 'B31', name: '浅灰绿', hex: '#94B576' },
+ { code: 'B32', name: '淡灰绿', hex: '#AED581' },
+
+ // ═══════════ C 蓝色系 ═══════════
+ { code: 'C1', name: '冰蓝', hex: '#E3F2FD' },
+ { code: 'C2', name: '淡天蓝', hex: '#BBDEFB' },
+ { code: 'C3', name: '天蓝', hex: '#90CAF9' },
+ { code: 'C4', name: '浅蓝', hex: '#64B5F6' },
+ { code: 'C5', name: '亮蓝', hex: '#42A5F5' },
+ { code: 'C6', name: '蓝', hex: '#2196F3' },
+ { code: 'C7', name: '钴蓝', hex: '#1E88E5' },
+ { code: 'C8', name: '深蓝', hex: '#1565C0' },
+ { code: 'C9', name: '藏青蓝', hex: '#0D47A1' },
+ { code: 'C10', name: '海军蓝', hex: '#1A237E' },
+ { code: 'C11', name: '群青', hex: '#283593' },
+ { code: 'C12', name: '靛蓝', hex: '#3949AB' },
+ { code: 'C13', name: '宝蓝', hex: '#3F51B5' },
+ { code: 'C14', name: '矢车菊蓝', hex: '#5C6BC0' },
+ { code: 'C15', name: '薰衣草蓝', hex: '#7986CB' },
+ { code: 'C16', name: '浅薰蓝', hex: '#9FA8DA' },
+ { code: 'C17', name: '暗蓝', hex: '#0D47A1' },
+ { code: 'C18', name: '午夜蓝', hex: '#1A1A6B' },
+ { code: 'C19', name: '青蓝', hex: '#0288D1' },
+ { code: 'C20', name: '天青', hex: '#03A9F4' },
+ { code: 'C21', name: '浅天青', hex: '#4FC3F7' },
+ { code: 'C22', name: '粉蓝', hex: '#81D4FA' },
+ { code: 'C23', name: '水蓝', hex: '#B3E5FC' },
+ { code: 'C24', name: '蔚蓝', hex: '#29B6F6' },
+ { code: 'C25', name: '湖蓝', hex: '#0277BD' },
+ { code: 'C26', name: '深湖蓝', hex: '#01579B' },
+ { code: 'C27', name: '蓝灰', hex: '#546E7A' },
+ { code: 'C28', name: '深蓝灰', hex: '#37474F' },
+ { code: 'C29', name: '暗蓝灰', hex: '#263238' },
+
+ // ═══════════ D 紫色系 ═══════════
+ { code: 'D1', name: '淡紫', hex: '#E1BEE7' },
+ { code: 'D2', name: '浅紫', hex: '#CE93D8' },
+ { code: 'D3', name: '丁香紫', hex: '#BA68C8' },
+ { code: 'D4', name: '兰花紫', hex: '#AB47BC' },
+ { code: 'D5', name: '紫', hex: '#9C27B0' },
+ { code: 'D6', name: '深紫', hex: '#8E24AA' },
+ { code: 'D7', name: '暗紫', hex: '#7B1FA2' },
+ { code: 'D8', name: '极暗紫', hex: '#6A1B9A' },
+ { code: 'D9', name: '茄紫', hex: '#4A148C' },
+ { code: 'D10', name: '蓝紫', hex: '#5E35B1' },
+ { code: 'D11', name: '深蓝紫', hex: '#4527A0' },
+ { code: 'D12', name: '暗蓝紫', hex: '#311B92' },
+ { code: 'D13', name: '皇家紫', hex: '#512DA8' },
+ { code: 'D14', name: '浅蓝紫', hex: '#7E57C2' },
+ { code: 'D15', name: '粉紫', hex: '#9575CD' },
+ { code: 'D16', name: '淡粉紫', hex: '#B39DDB' },
+ { code: 'D17', name: '薰衣草', hex: '#D1C4E9' },
+ { code: 'D18', name: '玫瑰紫', hex: '#E040FB' },
+ { code: 'D19', name: '亮紫', hex: '#D500F9' },
+ { code: 'D20', name: '紫红', hex: '#AA00FF' },
+ { code: 'D21', name: '洋紫', hex: '#C51162' },
+ { code: 'D22', name: '暗洋紫', hex: '#880E4F' },
+ { code: 'D23', name: '深洋紫', hex: '#6A0040' },
+ { code: 'D24', name: '紫酱', hex: '#4A0033' },
+ { code: 'D25', name: '梅紫', hex: '#7C1A8E' },
+ { code: 'D26', name: '深梅紫', hex: '#5A0068' },
+
+ // ═══════════ E 肤色系 ═══════════
+ { code: 'E1', name: '瓷白', hex: '#FFF5EE' },
+ { code: 'E2', name: '浅肤', hex: '#FFE8D6' },
+ { code: 'E3', name: '淡肤', hex: '#FFDAB9' },
+ { code: 'E4', name: '嫩肤', hex: '#FFD0A8' },
+ { code: 'E5', name: '暖肤', hex: '#FFC096' },
+ { code: 'E6', name: '蜜肤', hex: '#F5B07A' },
+ { code: 'E7', name: '麦肤', hex: '#E8A465' },
+ { code: 'E8', name: '古铜肤', hex: '#D4944A' },
+ { code: 'E9', name: '深麦肤', hex: '#C68642' },
+ { code: 'E10', name: '棕肤', hex: '#B07030' },
+ { code: 'E11', name: '深棕肤', hex: '#9A5E28' },
+ { code: 'E12', name: '咖啡肤', hex: '#8D5524' },
+ { code: 'E13', name: '深咖啡肤', hex: '#7A4820' },
+ { code: 'E14', name: '巧克力肤', hex: '#6B3A18' },
+ { code: 'E15', name: '深巧克力肤', hex: '#5C3010' },
+ { code: 'E16', name: '玫瑰肤', hex: '#FFB5A0' },
+ { code: 'E17', name: '粉肤', hex: '#FFCCBC' },
+ { code: 'E18', name: '杏肤', hex: '#FFD8C0' },
+ { code: 'E19', name: '驼色', hex: '#D2B48C' },
+ { code: 'E20', name: '暖驼色', hex: '#C4A87A' },
+ { code: 'E21', name: '深驼色', hex: '#A68B5C' },
+ { code: 'E22', name: '沙肤', hex: '#E8D4B8' },
+ { code: 'E23', name: '浅沙', hex: '#F0E0CC' },
+ { code: 'E24', name: '米肤', hex: '#F5E6D0' },
+
+ // ═══════════ F 红色系 ═══════════
+ { code: 'F1', name: '浅粉', hex: '#FCE4EC' },
+ { code: 'F2', name: '淡粉', hex: '#F8BBD0' },
+ { code: 'F3', name: '粉红', hex: '#F48FB1' },
+ { code: 'F4', name: '玫粉', hex: '#EC407A' },
+ { code: 'F5', name: '洋红', hex: '#E91E63' },
+ { code: 'F6', name: '深洋红', hex: '#C2185B' },
+ { code: 'F7', name: '品红', hex: '#AD1457' },
+ { code: 'F8', name: '桃红', hex: '#FF4081' },
+ { code: 'F9', name: '亮红', hex: '#FF1744' },
+ { code: 'F10', name: '正红', hex: '#D32F2F' },
+ { code: 'F11', name: '深红', hex: '#C62828' },
+ { code: 'F12', name: '暗红', hex: '#B71C1C' },
+ { code: 'F13', name: '枣红', hex: '#8B1A1A' },
+ { code: 'F14', name: '酒红', hex: '#7B0D0D' },
+ { code: 'F15', name: '珊瑚红', hex: '#FF6F61' },
+ { code: 'F16', name: '三文鱼', hex: '#FA8072' },
+ { code: 'F17', name: '浅珊瑚', hex: '#FF8A80' },
+ { code: 'F18', name: '西瓜红', hex: '#EF5350' },
+ { code: 'F19', name: '番茄红', hex: '#E53935' },
+ { code: 'F20', name: '砖红', hex: '#C0392B' },
+ { code: 'F21', name: '铁锈红', hex: '#A02B1F' },
+ { code: 'F22', name: '栗红', hex: '#7F1D1D' },
+ { code: 'F23', name: '黑红', hex: '#5C1510' },
+ { code: 'F24', name: '紫红', hex: '#880E4F' },
+ { code: 'F25', name: '深紫红', hex: '#6A1039' },
+
+ // ═══════════ G 松色系 ═══════════
+ { code: 'G1', name: '浅松', hex: '#D8C8A8' },
+ { code: 'G2', name: '淡松', hex: '#D0BF98' },
+ { code: 'G3', name: '暖米', hex: '#C0AE88' },
+ { code: 'G4', name: '米棕', hex: '#B0A078' },
+ { code: 'G5', name: '沙棕', hex: '#A49468' },
+ { code: 'G6', name: '黄棕', hex: '#988860' },
+ { code: 'G7', name: '深沙棕', hex: '#887050' },
+ { code: 'G8', name: '松木棕', hex: '#7A6040' },
+ { code: 'G9', name: '深松木', hex: '#6C5438' },
+ { code: 'G10', name: '核桃棕', hex: '#604A30' },
+ { code: 'G11', name: '深核桃', hex: '#544028' },
+ { code: 'G12', name: '栗棕', hex: '#483820' },
+ { code: 'G13', name: '黑棕', hex: '#3A2E1E' },
+ { code: 'G14', name: '奶茶', hex: '#E0D0B4' },
+ { code: 'G15', name: '浅卡其', hex: '#D5C6A4' },
+ { code: 'G16', name: '卡其', hex: '#C4B494' },
+ { code: 'G17', name: '深卡其', hex: '#B4A282' },
+ { code: 'G18', name: '暗卡其', hex: '#9A8A6E' },
+ { code: 'G19', name: '灰棕', hex: '#7E7058' },
+ { code: 'G20', name: '深灰棕', hex: '#605040' },
+ { code: 'G21', name: '暗灰棕', hex: '#484038' },
+
+ // ═══════════ H 灰色系 ═══════════
+ { code: 'H1', name: '灰黑', hex: '#333333' },
+ { code: 'H2', name: '灰色', hex: '#B0B0B0' },
+ { code: 'H3', name: '浅灰', hex: '#D0D0D0' },
+ { code: 'H4', name: '银灰', hex: '#C0C0C0' },
+ { code: 'H5', name: '中灰', hex: '#9E9E9E' },
+ { code: 'H6', name: '深灰', hex: '#707070' },
+ { code: 'H7', name: '暗灰', hex: '#606060' },
+ { code: 'H8', name: '雪白', hex: '#F5F5F5' },
+ { code: 'H9', name: '珍珠白', hex: '#EEEEEE' },
+ { code: 'H10', name: '烟灰', hex: '#A0A0A0' },
+ { code: 'H11', name: '铅灰', hex: '#888888' },
+ { code: 'H12', name: '石板灰', hex: '#78909C' },
+ { code: 'H13', name: '冷灰', hex: '#90A4AE' },
+ { code: 'H14', name: '暖灰', hex: '#A89890' },
+ { code: 'H15', name: '浅暖灰', hex: '#C0B4A8' },
+ { code: 'H16', name: '钢灰', hex: '#6B6B6B' },
+ { code: 'H17', name: '铁灰', hex: '#505050' },
+ { code: 'H18', name: '炭黑', hex: '#2A2A2A' },
+ { code: 'H19', name: '纯白', hex: '#FFFFFF' },
+ { code: 'H20', name: '象牙灰', hex: '#E8E0D8' },
+ { code: 'H21', name: '深炭灰', hex: '#404040' },
+ { code: 'H22', name: '墨灰', hex: '#383838' },
+ { code: 'H23', name: '纯黑', hex: '#1A1A1A' },
+
+ // ═══════════ M 暗色系 ═══════════
+ { code: 'M1', name: '暗蓝', hex: '#0A2540' },
+ { code: 'M2', name: '暗紫', hex: '#2D1B4E' },
+ { code: 'M3', name: '暗青', hex: '#004040' },
+ { code: 'M4', name: '暗橄榄', hex: '#2B3A1A' },
+ { code: 'M5', name: '暗棕', hex: '#3E2215' },
+ { code: 'M6', name: '暗红棕', hex: '#421515' },
+ { code: 'M7', name: '暗森林', hex: '#1A3018' },
+ { code: 'M8', name: '暗藏青', hex: '#1A1A40' },
+ { code: 'M9', name: '暗酒红', hex: '#400D14' },
+ { code: 'M10', name: '暗铁红', hex: '#5A1818' },
+ { code: 'M11', name: '暗墨绿', hex: '#1A3A20' },
+ { code: 'M12', name: '暗深蓝', hex: '#102040' },
+ { code: 'M13', name: '暗咖', hex: '#302018' },
+ { code: 'M14', name: '暗灰紫', hex: '#382838' },
+ { code: 'M15', name: '暗墨', hex: '#1A2020' },
+
+ // ═══════════ P 珠光系 ═══════════
+ { code: 'P1', name: '珠光白', hex: '#F8F8FF' },
+ { code: 'P2', name: '珠光粉', hex: '#FFE4E1' },
+ { code: 'P3', name: '珠光蓝', hex: '#B0C4DE' },
+ { code: 'P4', name: '珠光绿', hex: '#B0E0C8' },
+ { code: 'P5', name: '珠光紫', hex: '#D8BFD8' },
+ { code: 'P6', name: '珠光金', hex: '#FFE4B5' },
+ { code: 'P7', name: '珠光银', hex: '#D8D8D8' },
+ { code: 'P8', name: '珠光红', hex: '#FFB4B4' },
+ { code: 'P9', name: '珠光橙', hex: '#FFDAB0' },
+ { code: 'P10', name: '珠光黄', hex: '#FAFAD2' },
+ { code: 'P11', name: '珠光青', hex: '#AFEEEE' },
+ { code: 'P12', name: '珠光棕', hex: '#CDAA7D' },
+ { code: 'P13', name: '珠光灰', hex: '#C0C0C0' },
+ { code: 'P14', name: '珠光黑', hex: '#3A3A3A' },
+ { code: 'P15', name: '珠光玫红', hex: '#FFB0C0' },
+ { code: 'P16', name: '珠光玫紫', hex: '#E0B0FF' },
+ { code: 'P17', name: '珠光薰蓝', hex: '#A6CAF0' },
+ { code: 'P18', name: '珠光薄荷', hex: '#A0E8C0' },
+ { code: 'P19', name: '珠光湖蓝', hex: '#87CEEB' },
+ { code: 'P20', name: '珠光暖白', hex: '#FFF8EA' },
+ { code: 'P21', name: '珠光象牙', hex: '#F5E8D0' },
+ { code: 'P22', name: '珠光暗红', hex: '#CD9B9B' },
+ { code: 'P23', name: '珠光墨绿', hex: '#7AB888' },
+
+ // ═══════════ Q 温变系 ═══════════
+ { code: 'Q1', name: '温变粉', hex: '#FFB6C1' },
+ { code: 'Q2', name: '温变蓝', hex: '#87CEFA' },
+ { code: 'Q3', name: '温变紫', hex: '#DDA0DD' },
+ { code: 'Q4', name: '温变绿', hex: '#90EE90' },
+ { code: 'Q5', name: '温变橙', hex: '#FFA07A' },
+ ]
+ },
+
+ perler: {
+ name: 'Perler Beads',
+ colors: [
+ { code: 'P01', name: 'White', hex: '#F4F4F4' },
+ { code: 'P02', name: 'Cream', hex: '#F5E6C8' },
+ { code: 'P03', name: 'Yellow', hex: '#FFD800' },
+ { code: 'P04', name: 'Orange', hex: '#F58220' },
+ { code: 'P05', name: 'Red', hex: '#E4002B' },
+ { code: 'P06', name: 'Bubblegum', hex: '#F27DA0' },
+ { code: 'P07', name: 'Purple', hex: '#7B2D8E' },
+ { code: 'P08', name: 'Dark Blue', hex: '#003DA5' },
+ { code: 'P09', name: 'Light Blue', hex: '#69B3E7' },
+ { code: 'P10', name: 'Dark Green', hex: '#007A33' },
+ { code: 'P11', name: 'Pearl Green', hex: '#53B17F' },
+ { code: 'P12', name: 'Brown', hex: '#6C4B2A' },
+ { code: 'P13', name: 'Grey', hex: '#A7A8AA' },
+ { code: 'P14', name: 'Black', hex: '#231F20' },
+ { code: 'P15', name: 'Rust', hex: '#B33D26' },
+ { code: 'P16', name: 'Light Brown', hex: '#8B6F4E' },
+ { code: 'P17', name: 'Peach', hex: '#FFCBA4' },
+ { code: 'P18', name: 'Tan', hex: '#D2B48C' },
+ { code: 'P19', name: 'Magenta', hex: '#CE1485' },
+ { code: 'P20', name: 'Neon Yellow', hex: '#DFFF00' },
+ { code: 'P21', name: 'Neon Orange', hex: '#FF6700' },
+ { code: 'P22', name: 'Neon Green', hex: '#39FF14' },
+ { code: 'P23', name: 'Neon Pink', hex: '#FF6EC7' },
+ { code: 'P24', name: 'Pastel Blue', hex: '#AEC6CF' },
+ { code: 'P25', name: 'Pastel Green', hex: '#B2E0B2' },
+ { code: 'P26', name: 'Pastel Lavender', hex: '#C5B9E8' },
+ { code: 'P27', name: 'Pastel Yellow', hex: '#FDFD96' },
+ { code: 'P28', name: 'Pastel Pink', hex: '#FFD1DC' },
+ { code: 'P29', name: 'Cheddar', hex: '#FFA600' },
+ { code: 'P30', name: 'Toothpaste', hex: '#B2DFDB' },
+ { code: 'P31', name: 'Hot Coral', hex: '#F7464A' },
+ { code: 'P32', name: 'Plum', hex: '#663046' },
+ { code: 'P33', name: 'Kiwi Lime', hex: '#8DB600' },
+ { code: 'P34', name: 'Cyan', hex: '#00BCD4' },
+ { code: 'P35', name: 'Blueberry Cream', hex: '#4F86C6' },
+ { code: 'P36', name: 'Periwinkle Blue', hex: '#6F72AF' },
+ { code: 'P37', name: 'Light Pink', hex: '#FFB3C1' },
+ { code: 'P38', name: 'Bright Green', hex: '#00C853' },
+ { code: 'P39', name: 'Robin Egg Blue', hex: '#00CCCC' },
+ { code: 'P40', name: 'Flamingo', hex: '#EF7C8E' },
+ { code: 'P41', name: 'Prickly Pear', hex: '#A6D785' },
+ { code: 'P42', name: 'Light Grey', hex: '#C8C8C8' },
+ { code: 'P43', name: 'Dark Grey', hex: '#6E6E6E' },
+ { code: 'P44', name: 'Sand', hex: '#C2B280' },
+ { code: 'P45', name: 'Butterscotch', hex: '#E39B3F' },
+ { code: 'P46', name: 'Fawn', hex: '#C8A882' },
+ { code: 'P47', name: 'Cherry', hex: '#9B111E' },
+ { code: 'P48', name: 'Cranapple', hex: '#9B5B5B' },
+ ]
+ },
+
+ hama: {
+ name: 'Hama Beads',
+ colors: [
+ { code: 'H01', name: 'White', hex: '#FFFFFF' },
+ { code: 'H02', name: 'Cream', hex: '#F6E6C5' },
+ { code: 'H03', name: 'Yellow', hex: '#FFE600' },
+ { code: 'H04', name: 'Orange', hex: '#F18A00' },
+ { code: 'H05', name: 'Red', hex: '#CC0033' },
+ { code: 'H06', name: 'Pink', hex: '#F06EAA' },
+ { code: 'H07', name: 'Purple', hex: '#6F2B91' },
+ { code: 'H08', name: 'Blue', hex: '#0054A6' },
+ { code: 'H09', name: 'Light Blue', hex: '#55A8DE' },
+ { code: 'H10', name: 'Green', hex: '#009640' },
+ { code: 'H11', name: 'Light Green', hex: '#5EBD3E' },
+ { code: 'H12', name: 'Brown', hex: '#6B3A2A' },
+ { code: 'H13', name: 'Grey', hex: '#9B9B9B' },
+ { code: 'H14', name: 'Black', hex: '#1A1A1A' },
+ { code: 'H15', name: 'Claret', hex: '#82202D' },
+ { code: 'H16', name: 'Tan', hex: '#C7A87C' },
+ { code: 'H17', name: 'Flesh', hex: '#F0C0A0' },
+ { code: 'H18', name: 'Neon Yellow', hex: '#CCFF00' },
+ { code: 'H19', name: 'Neon Orange', hex: '#FF6600' },
+ { code: 'H20', name: 'Neon Red', hex: '#FF0040' },
+ { code: 'H21', name: 'Neon Pink', hex: '#FF5ECD' },
+ { code: 'H22', name: 'Neon Green', hex: '#33FF00' },
+ { code: 'H23', name: 'Pastel Yellow', hex: '#FFF5A0' },
+ { code: 'H24', name: 'Pastel Orange', hex: '#FCB97D' },
+ { code: 'H25', name: 'Pastel Pink', hex: '#FFDEE0' },
+ { code: 'H26', name: 'Pastel Purple', hex: '#D5A0E0' },
+ { code: 'H27', name: 'Pastel Blue', hex: '#A0C8F0' },
+ { code: 'H28', name: 'Pastel Green', hex: '#A8E0B0' },
+ { code: 'H29', name: 'Plum', hex: '#663366' },
+ { code: 'H30', name: 'Teddy Bear', hex: '#B5651D' },
+ { code: 'H31', name: 'Turquoise', hex: '#00B4D8' },
+ { code: 'H32', name: 'Dark Green', hex: '#1B5E20' },
+ { code: 'H33', name: 'Dark Grey', hex: '#555555' },
+ { code: 'H34', name: 'Raspberry', hex: '#B91C6E' },
+ { code: 'H35', name: 'Old Rose', hex: '#C08081' },
+ { code: 'H36', name: 'Azure', hex: '#007FFF' },
+ { code: 'H37', name: 'Olive', hex: '#556B2F' },
+ { code: 'H38', name: 'Light Pink', hex: '#FFB6C1' },
+ { code: 'H39', name: 'Bright Green', hex: '#00AA00' },
+ { code: 'H40', name: 'Gold', hex: '#DAA520' },
+ { code: 'H41', name: 'Ivory', hex: '#FFFFF0' },
+ { code: 'H42', name: 'Sand', hex: '#C2B280' },
+ ]
+ }
+};
diff --git a/public/bead-pattern-generator/js/converter.js b/public/bead-pattern-generator/js/converter.js
new file mode 100644
index 00000000000..4a598b956c0
--- /dev/null
+++ b/public/bead-pattern-generator/js/converter.js
@@ -0,0 +1,903 @@
+/**
+ * BeadConverter — 图片转拼豆图案核心引擎
+ *
+ * 将任意图片按目标宽度缩放到网格尺寸,再映射为拼豆色号:
+ * - 颜色空间转换:sRGB → CIE-Lab
+ * - 用 CIEDE2000(及 ΔE76)计算感知距离,匹配最近色板颜色
+ * - 双通道下采样(平滑 + 最近邻)结合原图多点采样,尽量保留细线、眼睛、高光、胡须等细节
+ * - 相似源色聚类,避免左右对称部位因微小 RGB 差异映射成不同珠色
+ * - 可选「白底变空」:从边缘洪水填充清除近白背景,同时硬化描边抗锯齿灰阶
+ * - 合并抗锯齿产生的低频噪声色,保护小而鲜艳的特征色
+ * - 可选限制最大颜色数(频率 + 感知多样性贪心选取)
+ * - 输出网格、宽高、各色用量、总珠数、使用颜色数
+ */
+
+/**
+ * BeadConverter — image → bead-pattern conversion engine.
+ *
+ * Pipeline:
+ * 1. Resize image to target grid dimensions (pixelation)
+ * 2. Convert each pixel RGB → CIE-Lab
+ * 3. Match to nearest bead color using Delta-E (CIEDE2000)
+ * 4. Optionally reduce to max N colors
+ */
+class BeadConverter {
+ constructor() {
+ this._labCache = new Map(); // pixel RGB → nearest color cache
+ this._paletteLab = []; // palette pre-computed Lab values
+ }
+
+ /* ── Colour-space helpers ─────────────────────────────── */
+
+ hexToRgb(hex) {
+ const v = parseInt(hex.slice(1), 16);
+ return { r: (v >> 16) & 0xFF, g: (v >> 8) & 0xFF, b: v & 0xFF };
+ }
+
+ rgbToLab(r, g, b) {
+ // sRGB → linear
+ let rr = r / 255, gg = g / 255, bb = b / 255;
+ rr = rr > 0.04045 ? Math.pow((rr + 0.055) / 1.055, 2.4) : rr / 12.92;
+ gg = gg > 0.04045 ? Math.pow((gg + 0.055) / 1.055, 2.4) : gg / 12.92;
+ bb = bb > 0.04045 ? Math.pow((bb + 0.055) / 1.055, 2.4) : bb / 12.92;
+ // linear RGB → XYZ (D65)
+ let x = (rr * 0.4124564 + gg * 0.3575761 + bb * 0.1804375) / 0.95047;
+ let y = (rr * 0.2126729 + gg * 0.7151522 + bb * 0.0721750);
+ let z = (rr * 0.0193339 + gg * 0.1191920 + bb * 0.9503041) / 1.08883;
+ // XYZ → Lab
+ const f = t => t > 0.008856 ? Math.cbrt(t) : 7.787 * t + 16 / 116;
+ x = f(x); y = f(y); z = f(z);
+ return [116 * y - 16, 500 * (x - y), 200 * (y - z)];
+ }
+
+ deltaE76(a, b) {
+ return Math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2);
+ }
+
+ deltaE2000(a, b) {
+ const [l1, a1, b1] = a;
+ const [l2, a2, b2] = b;
+ const c1 = Math.hypot(a1, b1);
+ const c2 = Math.hypot(a2, b2);
+ const avgC = (c1 + c2) / 2;
+ const pow25To7 = 6103515625;
+ const g = 0.5 * (1 - Math.sqrt((avgC ** 7) / ((avgC ** 7) + pow25To7)));
+ const a1p = (1 + g) * a1;
+ const a2p = (1 + g) * a2;
+ const c1p = Math.hypot(a1p, b1);
+ const c2p = Math.hypot(a2p, b2);
+ const avgCp = (c1p + c2p) / 2;
+ const h1p = (Math.atan2(b1, a1p) * 180 / Math.PI + 360) % 360;
+ const h2p = (Math.atan2(b2, a2p) * 180 / Math.PI + 360) % 360;
+
+ const deltaLp = l2 - l1;
+ const deltaCp = c2p - c1p;
+
+ let deltaHpDeg = 0;
+ if (c1p * c2p !== 0) {
+ deltaHpDeg = h2p - h1p;
+ if (deltaHpDeg > 180) deltaHpDeg -= 360;
+ else if (deltaHpDeg < -180) deltaHpDeg += 360;
+ }
+ const deltaHp = 2 * Math.sqrt(c1p * c2p) * Math.sin((deltaHpDeg * Math.PI / 180) / 2);
+
+ const avgLp = (l1 + l2) / 2;
+ let avgHp = h1p + h2p;
+ if (c1p * c2p === 0) {
+ avgHp = h1p + h2p;
+ } else if (Math.abs(h1p - h2p) > 180) {
+ avgHp = h1p + h2p < 360 ? (h1p + h2p + 360) / 2 : (h1p + h2p - 360) / 2;
+ } else {
+ avgHp = (h1p + h2p) / 2;
+ }
+
+ const avgHpRad = avgHp * Math.PI / 180;
+ const t = 1
+ - 0.17 * Math.cos(avgHpRad - Math.PI / 6)
+ + 0.24 * Math.cos(2 * avgHpRad)
+ + 0.32 * Math.cos(3 * avgHpRad + Math.PI / 30)
+ - 0.20 * Math.cos(4 * avgHpRad - 63 * Math.PI / 180);
+ const deltaTheta = 30 * Math.exp(-(((avgHp - 275) / 25) ** 2));
+ const rc = 2 * Math.sqrt((avgCp ** 7) / ((avgCp ** 7) + pow25To7));
+ const sl = 1 + (0.015 * ((avgLp - 50) ** 2)) / Math.sqrt(20 + ((avgLp - 50) ** 2));
+ const sc = 1 + 0.045 * avgCp;
+ const sh = 1 + 0.015 * avgCp * t;
+ const rt = -Math.sin(2 * deltaTheta * Math.PI / 180) * rc;
+
+ const lTerm = deltaLp / sl;
+ const cTerm = deltaCp / sc;
+ const hTerm = deltaHp / sh;
+ return Math.sqrt(
+ lTerm * lTerm +
+ cTerm * cTerm +
+ hTerm * hTerm +
+ rt * cTerm * hTerm
+ );
+ }
+
+ matteToWhite(r, g, b, a) {
+ const alpha = a / 255;
+ return [
+ Math.round(r * alpha + 255 * (1 - alpha)),
+ Math.round(g * alpha + 255 * (1 - alpha)),
+ Math.round(b * alpha + 255 * (1 - alpha)),
+ ];
+ }
+
+ _sampleWeight(samples) {
+ let total = 0;
+ for (const sample of samples) total += sample.weight;
+ return total;
+ }
+
+ _weightedAverageRgb(samples) {
+ const total = this._sampleWeight(samples);
+ if (!total) return null;
+
+ let r = 0, g = 0, b = 0;
+ for (const sample of samples) {
+ r += sample.rgb[0] * sample.weight;
+ g += sample.rgb[1] * sample.weight;
+ b += sample.rgb[2] * sample.weight;
+ }
+ return [Math.round(r / total), Math.round(g / total), Math.round(b / total)];
+ }
+
+ _weightedAverageLab(samples) {
+ const total = this._sampleWeight(samples);
+ if (!total) return null;
+
+ let l = 0, a = 0, b = 0;
+ for (const sample of samples) {
+ l += sample.lab[0] * sample.weight;
+ a += sample.lab[1] * sample.weight;
+ b += sample.lab[2] * sample.weight;
+ }
+ return [l / total, a / total, b / total];
+ }
+
+ _centerScore(samples) {
+ const total = this._sampleWeight(samples);
+ if (!total) return 0;
+
+ let score = 0;
+ for (const sample of samples) score += sample.weight * sample.center;
+ return score / total;
+ }
+
+ _sampleSpan(samples, axis) {
+ let min = Infinity;
+ let max = -Infinity;
+ for (const sample of samples) {
+ const value = sample[axis];
+ if (value < min) min = value;
+ if (value > max) max = value;
+ }
+ return max >= min ? (max - min + 1) : 0;
+ }
+
+ _selectDarkestSamples(samples, threshold = 8) {
+ if (!samples.length) return samples;
+
+ let darkest = Infinity;
+ for (const sample of samples) {
+ if (sample.lab[0] < darkest) darkest = sample.lab[0];
+ }
+
+ const picked = samples.filter(sample => sample.lab[0] <= darkest + threshold);
+ return picked.length ? picked : samples;
+ }
+
+ _clusterCellSamples(samples, threshold = 18) {
+ const clusters = [];
+
+ for (const sample of samples) {
+ let best = null;
+ let bestDistance = threshold;
+ for (const cluster of clusters) {
+ const distance = this.deltaE76(sample.lab, cluster.seedLab);
+ if (distance < bestDistance) {
+ bestDistance = distance;
+ best = cluster;
+ }
+ }
+
+ if (!best) {
+ best = { seedLab: sample.lab, samples: [] };
+ clusters.push(best);
+ }
+ best.samples.push(sample);
+ }
+
+ return clusters.map(cluster => {
+ const rgb = this._weightedAverageRgb(cluster.samples);
+ return {
+ samples: cluster.samples,
+ rgb,
+ lab: this.rgbToLab(rgb[0], rgb[1], rgb[2]),
+ weight: this._sampleWeight(cluster.samples),
+ };
+ });
+ }
+
+ _sampleCellRepresentative(originalData, sourceWidth, sourceHeight, gridWidth, gridHeight, cellX, cellY) {
+ const x0 = cellX * sourceWidth / gridWidth;
+ const x1 = (cellX + 1) * sourceWidth / gridWidth;
+ const y0 = cellY * sourceHeight / gridHeight;
+ const y1 = (cellY + 1) * sourceHeight / gridHeight;
+ const cellSpan = Math.max(x1 - x0, y1 - y0);
+ const sampleGrid = cellSpan >= 12 ? 6 : (cellSpan >= 8 ? 5 : (cellSpan >= 4 ? 4 : 3));
+ const samples = [];
+
+ for (let sy = 0; sy < sampleGrid; sy++) {
+ const fy = y0 + (sy + 0.5) * (y1 - y0) / sampleGrid;
+ const py = Math.min(sourceHeight - 1, Math.max(0, Math.floor(fy)));
+ for (let sx = 0; sx < sampleGrid; sx++) {
+ const fx = x0 + (sx + 0.5) * (x1 - x0) / sampleGrid;
+ const px = Math.min(sourceWidth - 1, Math.max(0, Math.floor(fx)));
+ const index = (py * sourceWidth + px) * 4;
+ const alpha = originalData[index + 3];
+ if (alpha < 24) continue;
+
+ const rgb = this.matteToWhite(
+ originalData[index],
+ originalData[index + 1],
+ originalData[index + 2],
+ alpha,
+ );
+ const dx = (sx + 0.5) / sampleGrid - 0.5;
+ const dy = (sy + 0.5) / sampleGrid - 0.5;
+ const center = Math.max(0, 1 - Math.hypot(dx, dy) / 0.7071067811865476);
+ samples.push({
+ rgb,
+ lab: this.rgbToLab(rgb[0], rgb[1], rgb[2]),
+ weight: 0.7 + 0.6 * center,
+ center,
+ sx,
+ sy,
+ });
+ }
+ }
+
+ if (!samples.length) return null;
+
+ const totalWeight = this._sampleWeight(samples);
+ const avgRgb = this._weightedAverageRgb(samples);
+ const avgLab = this.rgbToLab(avgRgb[0], avgRgb[1], avgRgb[2]);
+ const avgChroma = Math.hypot(avgLab[1], avgLab[2]);
+ const clusters = this._clusterCellSamples(samples);
+ clusters.sort((a, b) => b.weight - a.weight);
+ const dominant = clusters[0];
+ const dominantShare = dominant.weight / totalWeight;
+ const dominantChroma = Math.hypot(dominant.lab[1], dominant.lab[2]);
+ const allowNeutralDarkGlint = (
+ dominantShare <= 0.42 ||
+ (dominantShare <= 0.78 && avgLab[0] <= 45 && avgChroma <= 6)
+ );
+
+ // Preserve thin strokes and text on white backgrounds.
+ // Without this, small green or dark glyph fragments get averaged into white.
+ if (
+ dominant.lab[0] >= 92 &&
+ dominantChroma <= 8 &&
+ avgLab[0] >= 82 &&
+ dominant.lab[0] - avgLab[0] <= 16
+ ) {
+ let strokeCluster = null;
+ let bestScore = -Infinity;
+ for (const cluster of clusters.slice(1)) {
+ const share = cluster.weight / totalWeight;
+ const centerScore = this._centerScore(cluster.samples);
+ const clusterChroma = Math.hypot(cluster.lab[1], cluster.lab[2]);
+ const contrast = this.deltaE76(cluster.lab, dominant.lab);
+ const darkness = dominant.lab[0] - cluster.lab[0];
+ const score = contrast * share * (0.6 + centerScore);
+ const sampleCount = cluster.samples.length;
+ const centeredStroke = (
+ share >= 0.18 &&
+ centerScore >= 0.22 &&
+ contrast >= 18 &&
+ (clusterChroma >= 12 || darkness >= 12)
+ );
+ const thinHighContrastStroke = (
+ (share >= 0.12 || sampleCount >= 3) &&
+ contrast >= 24 &&
+ (clusterChroma >= 18 || darkness >= 18)
+ );
+ if (
+ (centeredStroke || thinHighContrastStroke) &&
+ score > bestScore
+ ) {
+ bestScore = score;
+ strokeCluster = cluster;
+ }
+ }
+ if (strokeCluster) {
+ const darkNeutralStroke = (
+ strokeCluster.lab[0] <= 34 &&
+ Math.hypot(strokeCluster.lab[1], strokeCluster.lab[2]) <= 14
+ );
+ if (darkNeutralStroke) {
+ return this._weightedAverageRgb(this._selectDarkestSamples(strokeCluster.samples));
+ }
+ return strokeCluster.rgb;
+ }
+ }
+
+ // Preserve thin dark horizontal strokes on neutral fills, even when they hug
+ // a cell edge. This keeps whiskers and similar line art from averaging away.
+ if (
+ dominant.lab[0] >= 38 &&
+ dominant.lab[0] <= 88 &&
+ dominantChroma <= 18 &&
+ avgChroma <= 18
+ ) {
+ let strokeCluster = null;
+ let bestScore = -Infinity;
+ for (const cluster of clusters.slice(1)) {
+ const share = cluster.weight / totalWeight;
+ const clusterChroma = Math.hypot(cluster.lab[1], cluster.lab[2]);
+ const contrast = this.deltaE76(cluster.lab, dominant.lab);
+ const darkness = dominant.lab[0] - cluster.lab[0];
+ const sampleCount = cluster.samples.length;
+ const rowSpan = this._sampleSpan(cluster.samples, 'sy');
+ const colSpan = this._sampleSpan(cluster.samples, 'sx');
+ const horizontalStroke = colSpan >= 3 && rowSpan > 0 && colSpan >= rowSpan + 1;
+ const thinDarkStroke = (
+ horizontalStroke &&
+ (share >= 0.08 || sampleCount >= 3) &&
+ share <= 0.38 &&
+ cluster.lab[0] <= 34 &&
+ clusterChroma <= 14 &&
+ darkness >= 14 &&
+ contrast >= 16
+ );
+ if (!thinDarkStroke) continue;
+
+ const strokeBonus = 1 + Math.min(2, colSpan - rowSpan) * 0.25;
+ const score = contrast * (share + sampleCount * 0.03) * strokeBonus;
+ if (score > bestScore) {
+ bestScore = score;
+ strokeCluster = cluster;
+ }
+ }
+ if (strokeCluster) return strokeCluster.rgb;
+ }
+
+ // Preserve compact dark facial features on bright backgrounds, such as eyes
+ // and the black outline around a small coloured nose.
+ if (
+ dominant.lab[0] >= 92 &&
+ dominantChroma <= 8 &&
+ avgLab[0] >= 72
+ ) {
+ let compactDarkCluster = null;
+ let bestScore = -Infinity;
+ for (const cluster of clusters.slice(1)) {
+ const share = cluster.weight / totalWeight;
+ const centerScore = this._centerScore(cluster.samples);
+ const clusterChroma = Math.hypot(cluster.lab[1], cluster.lab[2]);
+ const contrast = this.deltaE76(cluster.lab, dominant.lab);
+ const darkness = dominant.lab[0] - cluster.lab[0];
+ const sampleCount = cluster.samples.length;
+ const rowSpan = this._sampleSpan(cluster.samples, 'sy');
+ const colSpan = this._sampleSpan(cluster.samples, 'sx');
+ const compactFeature = rowSpan <= 5 && colSpan <= 5;
+ const darkNeutralFeature = (
+ compactFeature &&
+ cluster.lab[0] <= 34 &&
+ clusterChroma <= 14 &&
+ (share >= 0.08 || sampleCount >= 3) &&
+ share <= 0.36 &&
+ contrast >= 20 &&
+ darkness >= 18 &&
+ (centerScore >= 0.14 || sampleCount >= 4)
+ );
+ if (!darkNeutralFeature) continue;
+
+ const score = contrast * (share + sampleCount * 0.035) * (0.55 + centerScore);
+ if (score > bestScore) {
+ bestScore = score;
+ compactDarkCluster = cluster;
+ }
+ }
+ if (compactDarkCluster) {
+ return this._weightedAverageRgb(this._selectDarkestSamples(compactDarkCluster.samples));
+ }
+ }
+
+ // Preserve tiny white highlights inside dark regions, such as eye glints.
+ // Without this, a small bright cluster gets swallowed by the surrounding dark fill.
+ if (dominant.lab[0] <= 40 && dominantChroma <= 24 && allowNeutralDarkGlint) {
+ let highlightCluster = null;
+ let bestScore = -Infinity;
+ for (const cluster of clusters.slice(1)) {
+ const share = cluster.weight / totalWeight;
+ const centerScore = this._centerScore(cluster.samples);
+ const clusterChroma = Math.hypot(cluster.lab[1], cluster.lab[2]);
+ const contrast = this.deltaE76(cluster.lab, dominant.lab);
+ const lightnessGain = cluster.lab[0] - dominant.lab[0];
+ const sampleCount = cluster.samples.length;
+ const score = contrast * (share + sampleCount * 0.035) * (0.45 + centerScore);
+ const brightNeutralHighlight = (
+ (share >= 0.11 || sampleCount >= 2) &&
+ share <= 0.24 &&
+ centerScore >= 0.16 &&
+ cluster.lab[0] >= 82 &&
+ clusterChroma <= 14 &&
+ lightnessGain >= 38 &&
+ contrast >= 28
+ );
+ const crispSpecularHighlight = (
+ (share >= 0.08 || sampleCount >= 2) &&
+ share <= 0.2 &&
+ centerScore >= 0.08 &&
+ cluster.lab[0] >= 88 &&
+ clusterChroma <= 10 &&
+ lightnessGain >= 44 &&
+ contrast >= 34
+ );
+ if (
+ (brightNeutralHighlight || crispSpecularHighlight) &&
+ score > bestScore
+ ) {
+ bestScore = score;
+ highlightCluster = cluster;
+ }
+ }
+ if (highlightCluster) {
+ const brightSamples = highlightCluster.samples.filter(sample => (
+ sample.lab[0] >= Math.max(84, highlightCluster.lab[0] - 6) &&
+ Math.hypot(sample.lab[1], sample.lab[2]) <= 16
+ ));
+ if (brightSamples.length) {
+ return this._weightedAverageRgb(brightSamples);
+ }
+ return highlightCluster.rgb;
+ }
+ }
+
+ if (
+ dominant.lab[0] <= 10 &&
+ dominantChroma <= 8 &&
+ dominantShare >= 0.72
+ ) {
+ return this._weightedAverageRgb(this._selectDarkestSamples(dominant.samples, 5));
+ }
+
+ const darkSamples = samples.filter(sample => sample.lab[0] + 14 < avgLab[0]);
+ if (darkSamples.length) {
+ const darkWeight = this._sampleWeight(darkSamples);
+ const darkLab = this._weightedAverageLab(darkSamples);
+ if (
+ darkWeight / totalWeight >= 0.22 &&
+ this._centerScore(darkSamples) >= 0.42 &&
+ avgLab[0] - darkLab[0] >= 18
+ ) {
+ return this._weightedAverageRgb(darkSamples);
+ }
+ }
+
+ const vividSamples = samples.filter(sample => Math.hypot(sample.lab[1], sample.lab[2]) > avgChroma + 10);
+ if (vividSamples.length) {
+ const vividWeight = this._sampleWeight(vividSamples);
+ const vividLab = this._weightedAverageLab(vividSamples);
+ if (
+ vividWeight / totalWeight >= 0.22 &&
+ this._centerScore(vividSamples) >= 0.42 &&
+ Math.hypot(vividLab[1], vividLab[2]) - avgChroma >= 12 &&
+ this.deltaE76(vividLab, avgLab) >= 18
+ ) {
+ return this._weightedAverageRgb(vividSamples);
+ }
+ }
+
+ if (dominant && dominant.weight / totalWeight >= 0.58 && this.deltaE76(dominant.lab, avgLab) <= 10) {
+ return dominant.rgb;
+ }
+
+ return avgRgb;
+ }
+
+ /* ── Palette preparation ──────────────────────────────── */
+
+ preparePalette(colors) {
+ return colors.map(c => {
+ const rgb = this.hexToRgb(c.hex);
+ return { ...c, rgb, lab: this.rgbToLab(rgb.r, rgb.g, rgb.b) };
+ });
+ }
+
+ /* ── Nearest-colour lookup (with hash cache) ──────────── */
+
+ findNearest(r, g, b, palette) {
+ const key = (r << 16) | (g << 8) | b;
+ if (this._labCache.has(key)) return this._labCache.get(key);
+
+ const lab = this.rgbToLab(r, g, b);
+ let best = null, bestD = Infinity;
+ for (const c of palette) {
+ const d = this.deltaE2000(lab, c.lab);
+ if (d < bestD) { bestD = d; best = c; }
+ }
+ this._labCache.set(key, best);
+ return best;
+ }
+
+ /* ── Main conversion ──────────────────────────────────── */
+
+ convert(image, gridWidth, rawPalette, maxColors = 0, options = {}) {
+ const whiteBgEmpty = !!options.whiteBgEmpty;
+ this._labCache.clear();
+ const palette = this.preparePalette(rawPalette);
+
+ // Determine grid dimensions keeping aspect ratio
+ const aspect = image.height / image.width;
+ const gridHeight = Math.round(gridWidth * aspect);
+
+ // Down-sample via off-screen canvas
+ const cvs = document.createElement('canvas');
+ cvs.width = gridWidth;
+ cvs.height = gridHeight;
+ const ctx = cvs.getContext('2d', { willReadFrequently: true });
+
+ // Smooth pass: better color gradients
+ ctx.imageSmoothingEnabled = true;
+ ctx.imageSmoothingQuality = 'high';
+ ctx.drawImage(image, 0, 0, gridWidth, gridHeight);
+ const smData = new Uint8ClampedArray(ctx.getImageData(0, 0, gridWidth, gridHeight).data);
+
+ // NN pass: accurate alpha (edges) — smooth blurs alpha near transparency boundaries
+ ctx.clearRect(0, 0, gridWidth, gridHeight);
+ ctx.imageSmoothingEnabled = false;
+ ctx.drawImage(image, 0, 0, gridWidth, gridHeight);
+ const nnData = ctx.getImageData(0, 0, gridWidth, gridHeight).data;
+
+ const sourceCanvas = document.createElement('canvas');
+ sourceCanvas.width = image.width;
+ sourceCanvas.height = image.height;
+ const sourceCtx = sourceCanvas.getContext('2d', { willReadFrequently: true });
+ sourceCtx.drawImage(image, 0, 0, image.width, image.height);
+ const originalData = sourceCtx.getImageData(0, 0, image.width, image.height).data;
+
+ // Build a detail-preserving representative color for each output cell.
+ const sourceData = new Uint8ClampedArray(smData.length);
+ for (let y = 0; y < gridHeight; y++) {
+ for (let x = 0; x < gridWidth; x++) {
+ const j = (y * gridWidth + x) * 4;
+ const smoothRgb = this.matteToWhite(smData[j], smData[j + 1], smData[j + 2], smData[j + 3]);
+ const nnRgb = this.matteToWhite(nnData[j], nnData[j + 1], nnData[j + 2], nnData[j + 3]);
+
+ const effAlpha = Math.max(nnData[j + 3], smData[j + 3]);
+ if (effAlpha < 24) {
+ sourceData[j + 3] = 0;
+ continue;
+ }
+
+ const smoothLab = this.rgbToLab(smoothRgb[0], smoothRgb[1], smoothRgb[2]);
+ const nnLab = this.rgbToLab(nnRgb[0], nnRgb[1], nnRgb[2]);
+ const detailDelta = this.deltaE76(smoothLab, nnLab);
+ const smoothChroma = Math.hypot(smoothLab[1], smoothLab[2]);
+ const nnChroma = Math.hypot(nnLab[1], nnLab[2]);
+ const preferNn = effAlpha >= 220 && detailDelta >= 18 && (
+ nnLab[0] + 10 < smoothLab[0] ||
+ nnChroma > smoothChroma + 12
+ );
+ const preferBrightNn = effAlpha >= 220 && detailDelta >= 20 && (
+ nnLab[0] >= smoothLab[0] + 22 &&
+ nnLab[0] >= 88 &&
+ nnChroma <= 10
+ );
+
+ let chosenRgb = (preferNn || preferBrightNn) ? nnRgb : smoothRgb;
+ const shouldRefine = effAlpha >= 180 && (
+ detailDelta >= 4 ||
+ smoothLab[0] <= 45 ||
+ nnLab[0] <= 45 ||
+ (smoothLab[0] >= 84 && nnLab[0] >= 84)
+ );
+ if (shouldRefine) {
+ const refinedRgb = this._sampleCellRepresentative(
+ originalData,
+ image.width,
+ image.height,
+ gridWidth,
+ gridHeight,
+ x,
+ y,
+ );
+ if (refinedRgb) chosenRgb = refinedRgb;
+ }
+
+ sourceData[j] = chosenRgb[0];
+ sourceData[j + 1] = chosenRgb[1];
+ sourceData[j + 2] = chosenRgb[2];
+ sourceData[j + 3] = 255;
+ }
+ }
+
+ // ── Pre-cluster similar source colours (leader algorithm in Lab) ───
+ // Down-sampling introduces sub-pixel RGB drift: two regions that are
+ // visually identical (e.g. both eyes of a character) may differ by a
+ // few RGB levels. Clustering merges them so they map to the same bead.
+ const _uniqueRgb = new Map(); // packed-RGB → Lab
+ for (let j = 0; j < sourceData.length; j += 4) {
+ if (sourceData[j + 3] === 0) continue;
+ const pk = (sourceData[j] << 16) | (sourceData[j + 1] << 8) | sourceData[j + 2];
+ if (!_uniqueRgb.has(pk))
+ _uniqueRgb.set(pk, this.rgbToLab(sourceData[j], sourceData[j + 1], sourceData[j + 2]));
+ }
+ const CLUSTER_DE = 8; // ΔE merge threshold
+ const _leaders = []; // [{lab, pk}]
+ const _clusterMap = new Map(); // packed-RGB → leader pk
+ for (const [pk, lab] of _uniqueRgb) {
+ let matched = null;
+ for (const ld of _leaders) {
+ if (this.deltaE76(lab, ld.lab) < CLUSTER_DE) { matched = ld; break; }
+ }
+ if (matched) { _clusterMap.set(pk, matched.pk); }
+ else { _leaders.push({ lab, pk }); _clusterMap.set(pk, pk); }
+ }
+
+ // First pass — map every pixel to nearest bead colour
+ const grid = [];
+ const counts = {};
+
+ for (let y = 0; y < gridHeight; y++) {
+ const row = [];
+ for (let x = 0; x < gridWidth; x++) {
+ const i = (y * gridWidth + x) * 4;
+ // Use the MORE opaque of NN and smooth alpha — avoids NN sampling
+ // a single transparent edge pixel and blanking a mostly-opaque cell.
+ const effAlpha = Math.max(nnData[i + 3], smData[i + 3]);
+ if (effAlpha < 24) { row.push(null); continue; } // truly transparent → empty
+ // Use clustered representative colour for matching
+ const pk = (sourceData[i] << 16) | (sourceData[i + 1] << 8) | sourceData[i + 2];
+ const rk = _clusterMap.get(pk) ?? pk;
+ const c = this.findNearest((rk >> 16) & 0xFF, (rk >> 8) & 0xFF, rk & 0xFF, palette);
+ row.push(c);
+ counts[c.code] = (counts[c.code] || 0) + 1;
+ }
+ grid.push(row);
+ }
+
+ // ── White-background auto-empty (edge-connected flood fill) ──────
+ // Removes near-white cells that are connected to the image border, so a
+ // white photo/JPG background becomes empty space while interior white
+ // (enclosed by darker outlines, e.g. a character's white face) is kept.
+ if (whiteBgEmpty) {
+ // First harden anti-aliasing halos: the grey ramp between a black
+ // outline and the white background is the #1 source of "muddy" output.
+ this._hardenAntialiasEdges(grid, gridWidth, gridHeight, palette);
+ this._removeWhiteBackground(grid, gridWidth, gridHeight, sourceData);
+ // Recompute counts so colour reduction ignores removed cells.
+ for (const k in counts) delete counts[k];
+ for (let y = 0; y < gridHeight; y++) {
+ for (let x = 0; x < gridWidth; x++) {
+ const c = grid[y][x];
+ if (c) counts[c.code] = (counts[c.code] || 0) + 1;
+ }
+ }
+ }
+
+ // ── Merge anti-aliasing noise / tiny tail colours ───────────────
+ // Edge anti-aliasing creates a ramp of intermediate shades (e.g. a grey
+ // ladder between a black outline and white fill) that shows up as many
+ // 2–5 bead "junk" colours. Fold them into the nearest dominant colour,
+ // while protecting vivid distinct small features (e.g. a coloured nose).
+ this._mergeNoiseColors(grid, gridWidth, gridHeight, palette, counts);
+ for (const k in counts) delete counts[k];
+ for (let y = 0; y < gridHeight; y++) {
+ for (let x = 0; x < gridWidth; x++) {
+ const c = grid[y][x];
+ if (c) counts[c.code] = (counts[c.code] || 0) + 1;
+ }
+ }
+
+ // Optional colour reduction
+ if (maxColors > 0 && Object.keys(counts).length > maxColors) {
+ this._reduceColors(grid, gridWidth, gridHeight, palette, counts, maxColors);
+ }
+
+ // Rebuild counts after possible reduction
+ const finalCounts = {};
+ let total = 0;
+ for (const row of grid) {
+ for (const c of row) {
+ if (!c) continue;
+ finalCounts[c.code] = (finalCounts[c.code] || 0) + 1;
+ total++;
+ }
+ }
+
+ return {
+ grid,
+ width: gridWidth,
+ height: gridHeight,
+ colorCounts: finalCounts,
+ totalBeads: total,
+ uniqueColors: Object.keys(finalCounts).length,
+ };
+ }
+
+ /* ── Remove edge-connected near-white background ───────── */
+
+ _removeWhiteBackground(grid, w, h, sourceData) {
+ // A cell is "white-ish" if its representative colour is bright and
+ // nearly neutral (low saturation). Background = white-ish cells (or
+ // already-empty cells) reachable from the border via 4-connectivity.
+ const isWhiteish = (x, y) => {
+ const i = (y * w + x) * 4;
+ if (sourceData[i + 3] === 0) return true; // already empty → passable
+ const r = sourceData[i], g = sourceData[i + 1], b = sourceData[i + 2];
+ const mx = Math.max(r, g, b), mn = Math.min(r, g, b);
+ return mn >= 232 && (mx - mn) <= 16; // near white, low chroma
+ };
+
+ const visited = new Uint8Array(w * h);
+ const stack = [];
+ const pushIf = (x, y) => {
+ if (x < 0 || y < 0 || x >= w || y >= h) return;
+ const idx = y * w + x;
+ if (visited[idx]) return;
+ visited[idx] = 1;
+ if (isWhiteish(x, y)) stack.push(idx);
+ };
+
+ // Seed from every border cell.
+ for (let x = 0; x < w; x++) { pushIf(x, 0); pushIf(x, h - 1); }
+ for (let y = 0; y < h; y++) { pushIf(0, y); pushIf(w - 1, y); }
+
+ while (stack.length) {
+ const idx = stack.pop();
+ const x = idx % w, y = (idx - x) / w;
+ grid[y][x] = null; // background → empty
+ pushIf(x + 1, y); pushIf(x - 1, y);
+ pushIf(x, y + 1); pushIf(x, y - 1);
+ }
+ }
+
+ /* ── Harden anti-aliasing halos around dark outlines ──── */
+
+ _hardenAntialiasEdges(grid, w, h, palette) {
+ // The grey ramp that softens a black outline against a white background is
+ // the main source of muddy output. It survives colour-count thresholds
+ // (the halo can be several percent of all beads) and breaks left/right
+ // symmetry because the two sides anti-alias slightly differently.
+ //
+ // Geometry-based snapping fails on 2-px halos (the middle greys touch
+ // neither the pure outline nor the pure background), so instead do a
+ // GLOBAL two-level posterisation of *neutral* (near-grey) cells: every
+ // low-chroma cell collapses to either the outline colour or white, based
+ // on luminance. Coloured cells (pink body, yellow nose) have high chroma
+ // and are never touched. This is gated on whiteBgEmpty ("clean" mode), so
+ // genuine greyscale photos are unaffected.
+ const lum = (c) => 0.299 * c.rgb.r + 0.587 * c.rgb.g + 0.114 * c.rgb.b;
+ const chroma = (c) => Math.max(c.rgb.r, c.rgb.g, c.rgb.b) - Math.min(c.rgb.r, c.rgb.g, c.rgb.b);
+
+ // Pick the darkest neutral palette entry as the outline colour, and the
+ // brightest neutral entry as white.
+ let outline = null, white = null;
+ for (const p of palette) {
+ const ch = Math.max(p.rgb.r, p.rgb.g, p.rgb.b) - Math.min(p.rgb.r, p.rgb.g, p.rgb.b);
+ if (ch > 24) continue; // not neutral
+ const L = 0.299 * p.rgb.r + 0.587 * p.rgb.g + 0.114 * p.rgb.b;
+ if (!outline || L < (0.299 * outline.rgb.r + 0.587 * outline.rgb.g + 0.114 * outline.rgb.b)) outline = p;
+ if (!white || L > (0.299 * white.rgb.r + 0.587 * white.rgb.g + 0.114 * white.rgb.b)) white = p;
+ }
+ if (!outline || !white) return;
+
+ // Luminance split point. Greys darker than this join the outline; lighter
+ // greys become white. 150 keeps outlines crisp without bloating them.
+ const SPLIT = 150;
+ this._labCache.clear();
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const c = grid[y][x];
+ if (!c) continue;
+ if (chroma(c) > 26) continue; // coloured → keep
+ const L = lum(c);
+ if (L <= 80 || L >= 232) continue; // already pure outline / pure white
+ grid[y][x] = L < SPLIT ? outline : white;
+ }
+ }
+ }
+
+ /* ── Merge anti-aliasing noise / tiny tail colours into nearest kept ── */
+
+ _mergeNoiseColors(grid, w, h, palette, counts) {
+ const codes = Object.keys(counts);
+ if (codes.length <= 3) return; // already minimal
+
+ let total = 0;
+ for (const k of codes) total += counts[k];
+ if (total <= 0) return;
+ // A colour used by fewer than ~0.8% of beads is treated as edge noise.
+ const minKeep = Math.max(2, Math.round(total * 0.008));
+
+ const info = codes.map((code) => {
+ const c = palette.find((p) => p.code === code);
+ const lab = c ? this.rgbToLab(c.rgb.r, c.rgb.g, c.rgb.b) : [0, 0, 0];
+ return { code, color: c, count: counts[code], lab, chroma: Math.hypot(lab[1], lab[2]) };
+ });
+
+ const kept = info.filter((i) => i.count >= minKeep && i.color);
+ const tail = info.filter((i) => i.count < minKeep && i.color)
+ .sort((a, b) => a.count - b.count);
+ if (!kept.length || !tail.length) return;
+
+ const remap = new Map(); // tail code → kept colour object
+ for (const t of tail) {
+ let best = null, bestD = Infinity;
+ for (const k of kept) {
+ const d = this.deltaE2000(t.lab, k.lab);
+ if (d < bestD) { bestD = d; best = k; }
+ }
+ // Protect a small but vivid, perceptually distinct feature (e.g. nose).
+ if (t.chroma >= 45 && bestD >= 22) { kept.push(t); continue; }
+ if (best) remap.set(t.code, best.color);
+ }
+ if (!remap.size) return;
+
+ this._labCache.clear();
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const c = grid[y][x];
+ if (!c) continue;
+ const r = remap.get(c.code);
+ if (r) grid[y][x] = r;
+ }
+ }
+ }
+
+ /* ── Reduce to N most-used colours ────────────────────── */
+
+ _reduceColors(grid, w, h, palette, counts, maxN) {
+ // Select N colors using frequency + color diversity (greedy max-min distance)
+ // 1. Build color info with Lab values
+ const colorInfo = Object.entries(counts).map(([code, cnt]) => {
+ const c = palette.find(p => p.code === code);
+ return { code, count: cnt, lab: c ? this.rgbToLab(c.rgb.r, c.rgb.g, c.rgb.b) : [0, 0, 0] };
+ });
+
+ // 2. Start with the most frequent color
+ const selected = [];
+ const remaining = [...colorInfo];
+ remaining.sort((a, b) => b.count - a.count);
+ selected.push(remaining.shift());
+
+ // 3. Greedily pick next color that maximizes: diversity_score * frequency_weight
+ while (selected.length < maxN && remaining.length > 0) {
+ let bestIdx = 0, bestScore = -1;
+ for (let i = 0; i < remaining.length; i++) {
+ const cand = remaining[i];
+ // Min distance to any already-selected color
+ let minDist = Infinity;
+ for (const sel of selected) {
+ const d = this.deltaE2000(cand.lab, sel.lab);
+ if (d < minDist) minDist = d;
+ }
+ // Score = distance * sqrt(frequency) — balances diversity and importance
+ const score = minDist * Math.sqrt(cand.count);
+ if (score > bestScore) { bestScore = score; bestIdx = i; }
+ }
+ selected.push(remaining.splice(bestIdx, 1)[0]);
+ }
+
+ const keep = new Set(selected.map(s => s.code));
+ const kept = palette.filter(c => keep.has(c.code));
+
+ // Clear cache for reduced palette lookups
+ this._labCache.clear();
+
+ // Remap non-kept colors to nearest kept color
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const c = grid[y][x];
+ if (!c) continue;
+ if (keep.has(c.code)) continue;
+ grid[y][x] = this.findNearest(c.rgb.r, c.rgb.g, c.rgb.b, kept);
+ }
+ }
+ }
+}
diff --git a/public/bead-pattern-generator/js/pixel-restore.js b/public/bead-pattern-generator/js/pixel-restore.js
new file mode 100644
index 00000000000..1c86b067387
--- /dev/null
+++ b/public/bead-pattern-generator/js/pixel-restore.js
@@ -0,0 +1,261 @@
+/**
+ * PixelRestoreEngine — 像素还原引擎(浏览器本地)
+ *
+ * 从低清/截图图中按当前珠子宽度提取每个格子的代表色,再放大输出:
+ * - 格子采样:内缩后多点取中位数颜色,抗锯齿与压缩噪点
+ * - sharp 模式:最近邻整数倍放大,得到清晰像素底图
+ * - smooth 模式:分步平滑放大 + 轻微模糊与饱和度微调,得到插画感输出
+ * - 支持 2x / 4x / 8x 倍率
+ *
+ * 结果可应用回主图,用于后续拼豆转换。
+ */
+class PixelRestoreEngine {
+ static _matteToWhite(r, g, b, a) {
+ const alpha = a / 255;
+ return [
+ Math.round(r * alpha + 255 * (1 - alpha)),
+ Math.round(g * alpha + 255 * (1 - alpha)),
+ Math.round(b * alpha + 255 * (1 - alpha)),
+ ];
+ }
+
+ static _median(values) {
+ if (!values.length) return 255;
+ const sorted = values.slice().sort((a, b) => a - b);
+ const mid = Math.floor(sorted.length / 2);
+ if (sorted.length % 2 === 1) return sorted[mid];
+ return Math.round((sorted[mid - 1] + sorted[mid]) / 2);
+ }
+
+ static _getSourceSize(image) {
+ return {
+ width: image.naturalWidth || image.width || 0,
+ height: image.naturalHeight || image.height || 0,
+ };
+ }
+
+ static _normalizeGridWidth(image, gridWidth) {
+ const { width } = this._getSourceSize(image);
+ const requested = Math.max(1, parseInt(gridWidth, 10) || width || 1);
+ return Math.max(1, Math.min(width || requested, requested));
+ }
+
+ static _normalizeScale(scale) {
+ const allowed = [2, 4, 8];
+ const requested = parseInt(scale, 10) || 4;
+ return allowed.includes(requested) ? requested : 4;
+ }
+
+ static _sampleCellColor(sourceData, sourceWidth, sourceHeight, x0, y0, x1, y1) {
+ const spanX = Math.max(1, x1 - x0);
+ const spanY = Math.max(1, y1 - y0);
+ const insetRatio = 0.18;
+ const innerX0 = x0 + spanX * insetRatio;
+ const innerX1 = x1 - spanX * insetRatio;
+ const innerY0 = y0 + spanY * insetRatio;
+ const innerY1 = y1 - spanY * insetRatio;
+ const sampleCols = spanX >= 18 ? 7 : spanX >= 10 ? 6 : 5;
+ const sampleRows = spanY >= 18 ? 7 : spanY >= 10 ? 6 : 5;
+ const reds = [];
+ const greens = [];
+ const blues = [];
+
+ for (let sampleY = 0; sampleY < sampleRows; sampleY++) {
+ const fy = innerY0 + (sampleY + 0.5) * (innerY1 - innerY0) / sampleRows;
+ const py = Math.max(0, Math.min(sourceHeight - 1, Math.floor(fy)));
+ for (let sampleX = 0; sampleX < sampleCols; sampleX++) {
+ const fx = innerX0 + (sampleX + 0.5) * (innerX1 - innerX0) / sampleCols;
+ const px = Math.max(0, Math.min(sourceWidth - 1, Math.floor(fx)));
+ const index = (py * sourceWidth + px) * 4;
+ const [r, g, b] = this._matteToWhite(
+ sourceData[index],
+ sourceData[index + 1],
+ sourceData[index + 2],
+ sourceData[index + 3],
+ );
+ reds.push(r);
+ greens.push(g);
+ blues.push(b);
+ }
+ }
+
+ return [
+ this._median(reds),
+ this._median(greens),
+ this._median(blues),
+ ];
+ }
+
+ static sampleToGrid(image, gridWidth) {
+ const { width: sourceWidth, height: sourceHeight } = this._getSourceSize(image);
+ if (!sourceWidth || !sourceHeight) {
+ throw new Error('原图尺寸无效,无法执行像素还原');
+ }
+
+ const targetWidth = this._normalizeGridWidth(image, gridWidth);
+ const targetHeight = Math.max(1, Math.round(targetWidth * sourceHeight / sourceWidth));
+ const sourceCanvas = document.createElement('canvas');
+ sourceCanvas.width = sourceWidth;
+ sourceCanvas.height = sourceHeight;
+ const sourceCtx = sourceCanvas.getContext('2d', { willReadFrequently: true });
+ sourceCtx.drawImage(image, 0, 0, sourceWidth, sourceHeight);
+ const sourceData = sourceCtx.getImageData(0, 0, sourceWidth, sourceHeight).data;
+
+ const canvas = document.createElement('canvas');
+ canvas.width = targetWidth;
+ canvas.height = targetHeight;
+ const ctx = canvas.getContext('2d');
+ const imageData = ctx.createImageData(targetWidth, targetHeight);
+
+ for (let gridY = 0; gridY < targetHeight; gridY++) {
+ const y0 = gridY * sourceHeight / targetHeight;
+ const y1 = (gridY + 1) * sourceHeight / targetHeight;
+ for (let gridX = 0; gridX < targetWidth; gridX++) {
+ const x0 = gridX * sourceWidth / targetWidth;
+ const x1 = (gridX + 1) * sourceWidth / targetWidth;
+ const [r, g, b] = this._sampleCellColor(sourceData, sourceWidth, sourceHeight, x0, y0, x1, y1);
+ const index = (gridY * targetWidth + gridX) * 4;
+ imageData.data[index] = r;
+ imageData.data[index + 1] = g;
+ imageData.data[index + 2] = b;
+ imageData.data[index + 3] = 255;
+ }
+ }
+
+ ctx.putImageData(imageData, 0, 0);
+ return canvas;
+ }
+
+ static renderSharp(sampleCanvas, scale) {
+ const normalizedScale = this._normalizeScale(scale);
+ const canvas = document.createElement('canvas');
+ canvas.width = sampleCanvas.width * normalizedScale;
+ canvas.height = sampleCanvas.height * normalizedScale;
+
+ const ctx = canvas.getContext('2d');
+ ctx.imageSmoothingEnabled = false;
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ ctx.drawImage(sampleCanvas, 0, 0, canvas.width, canvas.height);
+ return canvas;
+ }
+
+ static _scale2xImageData(sourceImageData) {
+ const srcWidth = sourceImageData.width;
+ const srcHeight = sourceImageData.height;
+ const src = sourceImageData.data;
+ const dest = new ImageData(srcWidth * 2, srcHeight * 2);
+ const out = dest.data;
+
+ const srcIndex = (x, y) => (y * srcWidth + x) * 4;
+ const outIndex = (x, y) => (y * dest.width + x) * 4;
+ const samePixel = (a, b) => (
+ src[a] === src[b] &&
+ src[a + 1] === src[b + 1] &&
+ src[a + 2] === src[b + 2] &&
+ src[a + 3] === src[b + 3]
+ );
+ const writePixel = (index, sourceIndex) => {
+ out[index] = src[sourceIndex];
+ out[index + 1] = src[sourceIndex + 1];
+ out[index + 2] = src[sourceIndex + 2];
+ out[index + 3] = src[sourceIndex + 3];
+ };
+
+ for (let y = 0; y < srcHeight; y++) {
+ for (let x = 0; x < srcWidth; x++) {
+ const p = srcIndex(x, y);
+ const a = y > 0 ? srcIndex(x, y - 1) : p;
+ const b = x < srcWidth - 1 ? srcIndex(x + 1, y) : p;
+ const c = x > 0 ? srcIndex(x - 1, y) : p;
+ const d = y < srcHeight - 1 ? srcIndex(x, y + 1) : p;
+
+ let p1 = p;
+ let p2 = p;
+ let p3 = p;
+ let p4 = p;
+
+ if (!samePixel(c, b) && !samePixel(a, d)) {
+ if (samePixel(a, c)) p1 = a;
+ if (samePixel(a, b)) p2 = b;
+ if (samePixel(d, c)) p3 = c;
+ if (samePixel(d, b)) p4 = b;
+ }
+
+ const dx = x * 2;
+ const dy = y * 2;
+ writePixel(outIndex(dx, dy), p1);
+ writePixel(outIndex(dx + 1, dy), p2);
+ writePixel(outIndex(dx, dy + 1), p3);
+ writePixel(outIndex(dx + 1, dy + 1), p4);
+ }
+ }
+
+ return dest;
+ }
+
+ static renderSmooth(sampleCanvas, scale) {
+ const normalizedScale = this._normalizeScale(scale);
+ let currentCanvas = sampleCanvas;
+ let currentScale = 1;
+ let stages = 0;
+
+ while (currentScale < normalizedScale) {
+ const nextScale = Math.min(normalizedScale, currentScale * 2);
+ const nextCanvas = document.createElement('canvas');
+ nextCanvas.width = sampleCanvas.width * nextScale;
+ nextCanvas.height = sampleCanvas.height * nextScale;
+ const nextCtx = nextCanvas.getContext('2d');
+ nextCtx.imageSmoothingEnabled = true;
+ if ('imageSmoothingQuality' in nextCtx) nextCtx.imageSmoothingQuality = 'high';
+ nextCtx.clearRect(0, 0, nextCanvas.width, nextCanvas.height);
+ nextCtx.drawImage(currentCanvas, 0, 0, nextCanvas.width, nextCanvas.height);
+ currentCanvas = nextCanvas;
+ currentScale = nextScale;
+ stages += 1;
+ }
+
+ const canvas = document.createElement('canvas');
+ canvas.width = currentCanvas.width;
+ canvas.height = currentCanvas.height;
+ const ctx = canvas.getContext('2d');
+ ctx.imageSmoothingEnabled = true;
+ if ('imageSmoothingQuality' in ctx) ctx.imageSmoothingQuality = 'high';
+ if ('filter' in ctx) ctx.filter = 'blur(0.35px) saturate(102%)';
+ ctx.drawImage(currentCanvas, 0, 0);
+ if ('filter' in ctx) ctx.filter = 'none';
+ return { canvas, passes: stages };
+ }
+
+ static restore(image, { gridWidth, mode = 'sharp', scale = 4 } = {}) {
+ const sampledCanvas = this.sampleToGrid(image, gridWidth);
+ const normalizedScale = this._normalizeScale(scale);
+
+ if (mode === 'smooth') {
+ const { canvas, passes } = this.renderSmooth(sampledCanvas, normalizedScale);
+ return {
+ mode,
+ scale: normalizedScale,
+ passes,
+ sampledWidth: sampledCanvas.width,
+ sampledHeight: sampledCanvas.height,
+ outputWidth: canvas.width,
+ outputHeight: canvas.height,
+ outputCanvas: canvas,
+ };
+ }
+
+ const canvas = this.renderSharp(sampledCanvas, normalizedScale);
+ return {
+ mode: 'sharp',
+ scale: normalizedScale,
+ passes: 0,
+ sampledWidth: sampledCanvas.width,
+ sampledHeight: sampledCanvas.height,
+ outputWidth: canvas.width,
+ outputHeight: canvas.height,
+ outputCanvas: canvas,
+ };
+ }
+}
+
+window.PixelRestoreEngine = PixelRestoreEngine;
\ No newline at end of file
diff --git a/public/bead-pattern-generator/js/tracker.js b/public/bead-pattern-generator/js/tracker.js
new file mode 100644
index 00000000000..4c94c48be55
--- /dev/null
+++ b/public/bead-pattern-generator/js/tracker.js
@@ -0,0 +1,76 @@
+/**
+ * 功能点击追踪脚本(pindou.top)
+ *
+ * 把用户关键操作上报到后端 /api/track/click:
+ * - 自动监听带 data-track 属性的元素点击
+ * - 绑定核心按钮:生成图案、导出 PNG/PDF、图库、对比、裁剪、像素还原、小红书导入、上传图片
+ * - 记录页面访问
+ * - 本地队列串行发送,失败静默;登录用户附带 Token
+ * - 暴露 window.pdTrack 供手动埋点
+ */
+/**
+ * 功能点击追踪 — pindou.top
+ * 自动追踪带 data-track 属性的元素 + 核心操作
+ */
+(function () {
+ const API = 'https://api.pindou.top';
+ const PAGE = location.pathname.replace(/\/$/, '') || '/';
+ const _q = []; // offline queue
+ let _sending = false;
+
+ function send(feature) {
+ if (!feature) return;
+ _q.push(feature);
+ _flush();
+ }
+
+ function _flush() {
+ if (_sending || !_q.length) return;
+ _sending = true;
+ const feature = _q.shift();
+ const body = JSON.stringify({ feature: feature, page: PAGE });
+ const hdrs = { 'Content-Type': 'application/json' };
+ const token = localStorage.getItem('pindou_token');
+ if (token) hdrs['Authorization'] = 'Bearer ' + token;
+
+ fetch(API + '/api/track/click', { method: 'POST', headers: hdrs, body: body })
+ .catch(function () { })
+ .finally(function () { _sending = false; _flush(); });
+ }
+
+ // 1) Auto-track elements with data-track="featureName"
+ document.addEventListener('click', function (e) {
+ var el = e.target.closest('[data-track]');
+ if (el) send(el.getAttribute('data-track'));
+ }, true);
+
+ // 2) Track core app operations by hooking known buttons
+ document.addEventListener('DOMContentLoaded', function () {
+ var hooks = {
+ 'convertBtn': '转换图案',
+ 'exportBtn': '导出PNG',
+ 'exportPdfBtn': '导出PDF',
+ 'galleryBtn': '打开模板库',
+ 'compareBtn': '对比模式',
+ 'cropToggle': '裁剪',
+ 'restoreBtn': '像素修复',
+ 'xhsImportBtn': '小红书导入'
+ };
+ Object.keys(hooks).forEach(function (id) {
+ var el = document.getElementById(id);
+ if (el) el.addEventListener('click', function () { send(hooks[id]); }, true);
+ });
+
+ // Track file upload
+ var dropZone = document.getElementById('dropZone');
+ if (dropZone) dropZone.addEventListener('click', function () { send('上传图片'); }, true);
+ var fi = document.getElementById('fileInput');
+ if (fi) fi.addEventListener('change', function () { if (fi.files.length) send('选择图片'); }, true);
+
+ // Track page visit
+ send('页面访问');
+ });
+
+ // Expose for manual tracking
+ window.pdTrack = send;
+})();
diff --git a/public/bg_image.jpg b/public/bg_image.jpg
index cb503374df5..b557b4b30fa 100644
Binary files a/public/bg_image.jpg and b/public/bg_image.jpg differ
diff --git a/public/cus.html b/public/cus.html
new file mode 100644
index 00000000000..c59cf586c5a
--- /dev/null
+++ b/public/cus.html
@@ -0,0 +1,80 @@
+
+
+
+
+
+ Test Page
+
+
+
+
+
Welcome to Barry's Test Page!
+
这是一个漂亮的小卡片示例,你可以在这里放任何内容。
+
回到首页
+
+
+
diff --git a/public/favicon.ico b/public/favicon.ico
index d0e0f7d4e3c..ba7f39e53ea 100644
Binary files a/public/favicon.ico and b/public/favicon.ico differ
diff --git a/public/favicon.png b/public/favicon.png
index 04a4875b665..d80954e9a60 100644
Binary files a/public/favicon.png and b/public/favicon.png differ
diff --git a/public/images/404/404 (1).png b/public/images/404/404 (1).png
new file mode 100644
index 00000000000..be7c2385323
Binary files /dev/null and b/public/images/404/404 (1).png differ
diff --git a/public/images/404/404 (2).png b/public/images/404/404 (2).png
new file mode 100644
index 00000000000..82550a7f5b5
Binary files /dev/null and b/public/images/404/404 (2).png differ
diff --git a/public/images/404/404 (3).png b/public/images/404/404 (3).png
new file mode 100644
index 00000000000..7a7d419b1c4
Binary files /dev/null and b/public/images/404/404 (3).png differ
diff --git a/public/images/404/404 (4).png b/public/images/404/404 (4).png
new file mode 100644
index 00000000000..02ee7228959
Binary files /dev/null and b/public/images/404/404 (4).png differ
diff --git a/public/images/404/404 (5).png b/public/images/404/404 (5).png
new file mode 100644
index 00000000000..9b8960dd6f3
Binary files /dev/null and b/public/images/404/404 (5).png differ
diff --git a/styles/notion.css b/styles/notion.css
index 8dff1f32bc9..0ca5c1027bc 100644
--- a/styles/notion.css
+++ b/styles/notion.css
@@ -693,7 +693,7 @@ svg.notion-page-icon {
}
.notion-inline-code {
- color: #eb5757;
+ color: #d97706;
padding: 0.2em 0.4em;
background: var(--bg-color-2);
border-radius: 3px;
@@ -987,12 +987,13 @@ code[class*='language-'] {
padding: 16px 16px 16px 12px;
display: inline-flex;
width: 100%;
- border-radius: 3px;
+ border-radius: 10px;
border-width: 1px;
align-items: center;
box-sizing: border-box;
margin: 4px 0;
- border: 1px solid var(--fg-color-0);
+ border: 1px solid rgba(217, 119, 6, 0.4);
+ background-color: rgba(217, 119, 6, 0.06);
}
.dark-mode .notion-callout {
@@ -2036,13 +2037,12 @@ svg + .notion-page-title-text {
.notion-quote {
display: block;
border-radius: 5px;
- border-color: var(--notion-blue);
- border-left-color: var(--notion-blue);
- background-color: var(--notion-blue_background_co);
+ border-color: #b45309;
+ border-left: 10px solid #b45309;
+ background-color: rgba(217, 119, 6, 0.08);
width: 100%;
white-space: pre-wrap;
word-break: break-word;
- border-left: 10px solid;
padding: 0.2em 0.9em;
margin: 6px 0;
font-size: 1em;
@@ -2051,30 +2051,30 @@ svg + .notion-page-title-text {
/* 深色模式下优化 quote / callout 对比度与层次 */
html.dark .notion-quote {
- border-left-color: #60a5fa !important;
- border-color: rgba(96, 165, 250, 0.45) !important;
+ border-left-color: #d97706 !important;
+ border-color: rgba(217, 119, 6, 0.45) !important;
background: linear-gradient(
135deg,
- rgba(37, 99, 235, 0.22),
- rgba(30, 64, 175, 0.14)
+ rgba(217, 119, 6, 0.22),
+ rgba(180, 83, 9, 0.14)
) !important;
- color: #dbeafe !important;
+ color: #fef3c7 !important;
}
html.dark .notion-callout {
- border: 1px solid rgba(129, 140, 248, 0.38) !important;
+ border: 1px solid rgba(217, 119, 6, 0.45) !important;
background: linear-gradient(
135deg,
- rgba(99, 102, 241, 0.18),
- rgba(30, 41, 59, 0.5)
+ rgba(217, 119, 6, 0.22),
+ rgba(180, 83, 9, 0.14)
) !important;
- color: #e2e8f0 !important;
+ color: #fef3c7 !important;
border-radius: 10px;
}
html.dark .notion-callout .notion-callout-text,
html.dark .notion-callout .notion-text {
- color: #e2e8f0 !important;
+ color: #fef3c7 !important;
}
/* .notion-asset-wrapper-pdf > div {
diff --git a/themes/heo/components/BlogPostArchive.js b/themes/heo/components/BlogPostArchive.js
index 3a9c469050f..99d7d761da8 100644
--- a/themes/heo/components/BlogPostArchive.js
+++ b/themes/heo/components/BlogPostArchive.js
@@ -1,5 +1,7 @@
import LazyImage from '@/components/LazyImage'
import { siteConfig } from '@/lib/config'
+import { useGlobal } from '@/lib/global'
+import { buildSlugMap, toSlug } from '@/lib/utils/slugMap'
import SmartLink from '@/components/SmartLink'
import CONFIG from '../config'
import TagItemMini from './TagItemMini'
@@ -12,6 +14,8 @@ import TagItemMini from './TagItemMini'
* @constructor
*/
const BlogPostArchive = ({ posts = [], archiveTitle, siteInfo }) => {
+ const { categoryOptions } = useGlobal()
+ const categorySlugMap = buildSlugMap(categoryOptions?.map(c => c.name) || [])
if (!posts || posts.length === 0) {
return <>>
} else {
@@ -62,7 +66,7 @@ const BlogPostArchive = ({ posts = [], archiveTitle, siteInfo }) => {
className={`flex items-center ${showPreview ? 'justify-center' : 'justify-start'} hidden md:block flex-wrap dark:text-gray-500 text-gray-600 `}>
{post.category}
diff --git a/themes/heo/components/BlogPostCard.js b/themes/heo/components/BlogPostCard.js
index 21518f6f7bc..d902650ccbd 100644
--- a/themes/heo/components/BlogPostCard.js
+++ b/themes/heo/components/BlogPostCard.js
@@ -1,11 +1,15 @@
import LazyImage from '@/components/LazyImage'
import NotionIcon from './NotionIcon'
import { siteConfig } from '@/lib/config'
+import { useGlobal } from '@/lib/global'
+import { buildSlugMap, toSlug } from '@/lib/utils/slugMap'
import SmartLink from '@/components/SmartLink'
import CONFIG from '../config'
import TagItemMini from './TagItemMini'
-const BlogPostCard = ({ index, post, showSummary, siteInfo }) => {
+const BlogPostCard = ({ index, post, showSummary, siteInfo, compact = false }) => {
+ const { categoryOptions } = useGlobal()
+ const categorySlugMap = buildSlugMap(categoryOptions?.map(c => c.name) || [])
const showPreview =
siteConfig('HEO_POST_LIST_PREVIEW', null, CONFIG) && post.blockMap
if (
@@ -33,8 +37,12 @@ const BlogPostCard = ({ index, post, showSummary, siteInfo }) => {
{/* 图片封面 */}
{showPageCover && (
@@ -58,7 +66,7 @@ const BlogPostCard = ({ index, post, showSummary, siteInfo }) => {
{/* 分类 */}
@@ -67,7 +75,7 @@ const BlogPostCard = ({ index, post, showSummary, siteInfo }) => {
className={`flex mb-1 items-center ${showPreview ? 'justify-center' : 'justify-start'} hidden md:block flex-wrap dark:text-gray-300 text-gray-600 hover:text-[var(--heo-color-primary)] dark:hover:text-[var(--heo-color-accent)]`}>
{post.category}
@@ -79,7 +87,9 @@ const BlogPostCard = ({ index, post, showSummary, siteInfo }) => {
href={post?.href}
passHref
className={
- ' group-hover:text-[var(--heo-color-primary)] dark:hover:text-[var(--heo-color-accent)] dark:group-hover:text-[var(--heo-color-accent)] text-black dark:text-gray-100 line-clamp-2 replace cursor-pointer text-xl font-extrabold leading-tight'
+ ` group-hover:text-[var(--heo-color-primary)] dark:hover:text-[var(--heo-color-accent)] dark:group-hover:text-[var(--heo-color-accent)] text-black dark:text-gray-100 line-clamp-2 replace cursor-pointer ${
+ compact ? 'text-lg' : 'text-xl'
+ } font-extrabold leading-tight`
}>
{siteConfig('POST_TITLE_ICON') && (
{
- return
+ return
<>{headerSlot}>
{children}
diff --git a/themes/heo/components/CategoryBar.js b/themes/heo/components/CategoryBar.js
index 2e7e38bb91a..a46067632d5 100644
--- a/themes/heo/components/CategoryBar.js
+++ b/themes/heo/components/CategoryBar.js
@@ -2,6 +2,7 @@ import { ChevronDoubleLeft, ChevronDoubleRight } from '@/components/HeroIcons'
import { useGlobal } from '@/lib/global'
import SmartLink from '@/components/SmartLink'
import { useRouter } from 'next/router'
+import { buildSlugMap, fromSlug, toSlug } from '@/lib/utils/slugMap'
import { useRef, useState } from 'react'
/**
@@ -12,6 +13,9 @@ import { useRef, useState } from 'react'
export default function CategoryBar(props) {
const { categoryOptions, border = true } = props
const { locale } = useGlobal()
+ const router = useRouter()
+ const categorySlugMap = buildSlugMap(categoryOptions?.map(c => c.name) || [])
+ const currentCategory = fromSlug(router.query.category, categorySlugMap)
const [scrollRight, setScrollRight] = useState(false)
// 创建一个ref引用
const categoryBarItemsRef = useRef(null)
@@ -38,9 +42,14 @@ export default function CategoryBar(props) {
id='category-bar-items'
ref={categoryBarItemsRef}
className='scroll-smooth max-w-4xl rounded-lg scroll-hidden flex justify-start flex-nowrap items-center overflow-x-scroll'>
-
+
{categoryOptions?.map((c, index) => (
-
+
))}
@@ -70,10 +79,7 @@ export default function CategoryBar(props) {
* @param {*} param0
* @returns
*/
-const MenuItem = ({ href, name }) => {
- const router = useRouter()
- const { category } = router.query
- const selected = category === name
+const MenuItem = ({ href, name, selected = false }) => {
return (
diff --git a/themes/heo/components/Hero.js b/themes/heo/components/Hero.js
index caf65b3452c..819e5b26344 100644
--- a/themes/heo/components/Hero.js
+++ b/themes/heo/components/Hero.js
@@ -1,11 +1,11 @@
// import Image from 'next/image'
-import { ArrowSmallRight, PlusSmall } from '@/components/HeroIcons'
+import { ArrowPath, ArrowSmallRight, PlusSmall } from '@/components/HeroIcons'
import LazyImage from '@/components/LazyImage'
import { siteConfig } from '@/lib/config'
import { useGlobal } from '@/lib/global'
import SmartLink from '@/components/SmartLink'
import { useRouter } from 'next/router'
-import { useImperativeHandle, useRef, useState } from 'react'
+import { useEffect, useImperativeHandle, useRef, useState } from 'react'
import CONFIG from '../config'
/**
@@ -48,7 +48,7 @@ function BannerGroup(props) {
// 左侧英雄区
+ className='hidden xl:flex flex-col justify-between flex-1 mr-2 max-w-[42rem]'>
{/* 动图 */}
{/* 导航分类 */}
@@ -80,16 +80,19 @@ function Banner(props) {
+ className='hidden xl:flex xl:flex-col group h-full bg-[var(--heo-color-card)] dark:bg-[var(--heo-color-card-dark)] rounded-xl hover:border hover:border-[var(--heo-color-border)] dark:hover:border-[var(--heo-color-border-dark)] mb-3 relative overflow-hidden'>
-
+
{siteConfig('HEO_HERO_TITLE_1', null, CONFIG)}
{siteConfig('HEO_HERO_TITLE_2', null, CONFIG)}
-
+
{siteConfig('HEO_HERO_TITLE_3', null, CONFIG)}
@@ -232,7 +235,7 @@ function TopGroup(props) {
+ className='flex-1 relative w-full h-64 xl:h-[342px]'>
{/* 置顶推荐文章 */}
{/* 一个大的跳转文章卡片 */}
-
+
)
}
@@ -274,7 +277,7 @@ function getTopPosts({ latestPosts, allNavPages }) {
!siteConfig('HEO_HERO_RECOMMEND_POST_TAG', null, CONFIG) ||
siteConfig('HEO_HERO_RECOMMEND_POST_TAG', null, CONFIG) === ''
) {
- return latestPosts
+ return latestPosts.sort((a, b) => new Date(b.date) - new Date(a.date))
}
// 显示包含‘推荐’标签的文章
@@ -316,15 +319,104 @@ function getTopPosts({ latestPosts, allNavPages }) {
* 英雄区右侧,今日卡牌
* @returns
*/
-function TodayCard({ cRef, siteInfo }) {
- const router = useRouter()
- const link = siteConfig('HEO_HERO_TITLE_LINK', null, CONFIG)
+function normalizeHeroQuotes(value) {
+ if (Array.isArray(value)) {
+ return value.map(item => String(item).trim()).filter(Boolean)
+ }
+
+ if (typeof value !== 'string') {
+ return []
+ }
+
+ const trimmed = value.trim()
+ if (!trimmed) {
+ return []
+ }
+
+ if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
+ try {
+ const parsed = JSON.parse(trimmed.replace(/'/g, '"'))
+ return normalizeHeroQuotes(parsed)
+ } catch {
+ return trimmed
+ .slice(1, -1)
+ .split(',')
+ .map(item => item.trim().replace(/^['"]|['"]$/g, ''))
+ .filter(Boolean)
+ }
+ }
+
+ return [trimmed]
+}
+
+/**
+ * 英雄区右侧,今日卡牌
+ * 每日一句 + Steam 状态,保留推荐文章遮罩入口
+ * @returns
+ */
+// 每日一句可随机切换的入场动画
+const QUOTE_ANIMS = ['flip', 'glitch', 'slide', 'zoom']
+
+function TodayCard({ cRef }) {
+ const steamProfileUrl = siteConfig('HEO_STEAM_PROFILE_URL', null, CONFIG)
const { locale } = useGlobal()
// 获取遮罩控制配置
const coverEnable = siteConfig('HEO_HERO_RECOMMEND_COVER_ENABLE', true, CONFIG)
// 卡牌是否盖住下层,如果配置为false则默认不盖住
const [isCoverUp, setIsCoverUp] = useState(coverEnable)
+ // 每日一句
+ const quoteList = normalizeHeroQuotes(
+ siteConfig('HEO_HERO_QUOTES', null, CONFIG)
+ )
+ const fallbackQuote = siteConfig('HEO_HERO_TITLE_5', '', CONFIG)
+ const sentences =
+ quoteList.length > 0 ? quoteList : fallbackQuote ? [fallbackQuote] : []
+ const [quoteIndex, setQuoteIndex] = useState(() =>
+ sentences.length > 0 ? Math.floor(Math.random() * sentences.length) : -1
+ )
+ // 每日一句切换:5 秒冷却 + 随机入场动画
+ const [cooldown, setCooldown] = useState(0)
+ const [quotePhase, setQuotePhase] = useState('idle')
+ const [quoteAnim, setQuoteAnim] = useState(() =>
+ QUOTE_ANIMS[Math.floor(Math.random() * QUOTE_ANIMS.length)]
+ )
+ const prevAnimRef = useRef(null)
+ const quoteTimeoutRef = useRef(null)
+
+ /**
+ * 随机挑选一种入场动画,避免连续两次相同
+ */
+ function pickRandomAnim() {
+ const candidates = QUOTE_ANIMS.filter(a => a !== prevAnimRef.current)
+ const anim = candidates[Math.floor(Math.random() * candidates.length)]
+ prevAnimRef.current = anim
+ return anim
+ }
+
+ /**
+ * 冷却倒计时:每秒减 1
+ */
+ useEffect(() => {
+ if (cooldown <= 0) {
+ return
+ }
+ const timer = setTimeout(() => setCooldown(c => Math.max(0, c - 1)), 1000)
+ return () => clearTimeout(timer)
+ }, [cooldown])
+
+ /**
+ * 组件卸载时清理切换动画定时器
+ */
+ useEffect(() => {
+ return () => clearTimeout(quoteTimeoutRef.current)
+ }, [])
+
+ // Steam 状态:是否显示加载占位,用公开的 SteamID 判断;API Key 只在服务端环境变量里
+ const steamConfigured = Boolean(siteConfig('HEO_STEAM_ID', null, CONFIG))
+ const [steam, setSteam] = useState(null)
+ const [steamError, setSteamError] = useState(false)
+
/**
* 外部可以调用此方法
*/
@@ -348,72 +440,413 @@ function TodayCard({ cRef, siteInfo }) {
}
/**
- * 点击卡片跳转的链接
+ * 随机切换下一句:带 5 秒冷却与随机入场动画
* @param {*} e
*/
- function handleCardClick(e) {
- router.push(link)
+ function handleNextQuote(e) {
+ e.stopPropagation()
+ if (sentences.length < 2 || cooldown > 0 || quotePhase === 'leave') {
+ return
+ }
+ setCooldown(5)
+ // 先快速淡出,再切换内容并按随机动画入场
+ setQuoteAnim(pickRandomAnim())
+ setQuotePhase('leave')
+ quoteTimeoutRef.current = setTimeout(() => {
+ let next = quoteIndex
+ while (next === quoteIndex) {
+ next = Math.floor(Math.random() * sentences.length)
+ }
+ setQuoteIndex(next)
+ setQuotePhase('enter')
+ }, 200)
}
+ /**
+ * 拉取 Steam 状态
+ */
+ useEffect(() => {
+ if (!steamConfigured) {
+ return
+ }
+ const controller = new AbortController()
+ fetch('/api/steam-status', { signal: controller.signal })
+ .then(res => (res.ok ? res.json() : Promise.reject(new Error(res.status))))
+ .then(data => {
+ if (!controller.signal.aborted) {
+ setSteam(data)
+ }
+ })
+ .catch(err => {
+ if (!controller.signal.aborted && err.name !== 'AbortError') {
+ setSteamError(true)
+ }
+ })
+ return () => controller.abort()
+ }, [steamConfigured])
+
// 如果配置为不显示遮罩,则不渲染TodayCard
if (!coverEnable) {
return null
}
+ const currentQuote = sentences[quoteIndex] || ''
+ // 根据切换阶段生成动画 class
+ const quoteAnimClass =
+ quotePhase === 'leave'
+ ? 'quote-switch-leave'
+ : quotePhase === 'enter'
+ ? `quote-switch-enter quote-switch-enter-${quoteAnim}`
+ : ''
+ const player = steam?.player
+ const showSteamLoading = steamConfigured && !steam && !steamError
+
+ // Steam 状态文案
+ let steamStatusText = ''
+ if (player?.inGame) {
+ const gameName = player.gameNameCn || player.gameextrainfo
+ steamStatusText =
+ player.numFriendsInGame > 0
+ ? `在和${player.numFriendsInGame}个朋友遨游「${gameName}」的世界`
+ : `在「${gameName}」的世界中`
+ } else if (player && player.personastate === 0) {
+ const lastGame =
+ player.lastPlayedGameNameCn ||
+ player.lastPlayedGameName ||
+ '某款游戏'
+ steamStatusText = player.lastlogoff
+ ? `${formatRelativeTime(player.lastlogoff)}玩了「${lastGame}」`
+ : '离线'
+ } else if (player) {
+ steamStatusText = '正沉浸在自己的世界中'
+ }
+
return (
+ } overflow-hidden absolute flex flex-1 flex-col h-full top-0 w-full`}>
- {/* 卡片文字信息 */}
-
-
-
- {siteConfig('HEO_HERO_TITLE_4', null, CONFIG)}
-
-
- {siteConfig('HEO_HERO_TITLE_5', null, CONFIG)}
-
-
- {/* 查看更多的按钮 */}
-
-
+ {/* 背景图 + 暗色遮罩,保证文字可读 */}
+
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+

-
- {locale.COMMON.RECOMMEND_POSTS}
+
+
+
+ {/* 上半部分:按钮 + 每日一句 */}
+
+
+ {sentences.length > 1 && (
+
+ )}
+
+
+
+
+
+ {siteConfig('HEO_HERO_TITLE_4', null, CONFIG)}
+
+
+ {currentQuote}
+
+
+
+
-
- {/* 封面图 */}
- {/* eslint-disable-next-line @next/next/no-img-element */}
-
+ {/* 下半部分:Steam 状态 */}
+
+
)
}
+/**
+ * 将时间戳格式化为相对时间(用于离线状态)
+ */
+function formatRelativeTime(timestamp) {
+ if (!timestamp) {
+ return '很久以'
+ }
+ const diff = Math.max(0, Math.floor(Date.now() / 1000 - timestamp))
+ const minute = 60
+ const hour = 60 * minute
+ const day = 24 * hour
+ if (diff < minute) {
+ return '刚刚'
+ }
+ if (diff < hour) {
+ return `${Math.floor(diff / minute)}分钟前`
+ }
+ if (diff < day) {
+ return `${Math.floor(diff / hour)}小时前`
+ }
+ if (diff < 30 * day) {
+ return `${Math.floor(diff / day)}天前`
+ }
+ return `${Math.floor(diff / (30 * day))}个月前`
+}
+
export default Hero
diff --git a/themes/heo/components/InfoCard.js b/themes/heo/components/InfoCard.js
index ff779bd1531..1e3733fdfc8 100644
--- a/themes/heo/components/InfoCard.js
+++ b/themes/heo/components/InfoCard.js
@@ -107,21 +107,21 @@ export function InfoCard(props) {
{/* 社交按钮 */}
{url1 && (
-
+
)}
{url2 && (
-
+
)}
{orcidUrl && (
-
+
@@ -163,7 +163,7 @@ function MoreButton() {
+ className=' select-none cursor-pointer py-1 px-2 bg-[var(--heo-color-primary-hover)] hover:bg-[var(--heo-color-card-muted)] hover:text-[var(--heo-color-text)] dark:bg-black/25 dark:hover:text-white dark:hover:bg-black text-sm rounded-lg duration-200 transition-colors'>
{greeting}
)
diff --git a/themes/heo/components/MenuItemCollapse.js b/themes/heo/components/MenuItemCollapse.js
index 46770f6ec78..47e45aaf277 100644
--- a/themes/heo/components/MenuItemCollapse.js
+++ b/themes/heo/components/MenuItemCollapse.js
@@ -63,7 +63,12 @@ export const MenuItemCollapse = ({ link }) => {
-
+
{link?.icon && }{' '}
{sLink.title}
diff --git a/themes/heo/components/MenuItemDrop.js b/themes/heo/components/MenuItemDrop.js
index ed8e741ab6c..dc949537c06 100644
--- a/themes/heo/components/MenuItemDrop.js
+++ b/themes/heo/components/MenuItemDrop.js
@@ -44,7 +44,12 @@ export const MenuItemDrop = ({ link }) => {
-
+
{link?.icon && }
{sLink.title}
diff --git a/themes/heo/components/NoticeBar.js b/themes/heo/components/NoticeBar.js
index 8abca16e40b..a16ec2b2b85 100644
--- a/themes/heo/components/NoticeBar.js
+++ b/themes/heo/components/NoticeBar.js
@@ -28,10 +28,13 @@ export function NoticeBar() {
return <>>
}
+ // 随机打乱 notices 数组
+ notices = shuffleArray(notices)
+
return (
-
{locale.COMMON.NOW}
+
(^_^)
@@ -42,3 +45,17 @@ export function NoticeBar() {
)
}
+
+/**
+ * 使用 Fisher-Yates 算法随机打乱数组
+ * @param {Array} array - 需要打乱的数组
+ * @returns {Array} - 打乱顺序后的新数组
+ */
+function shuffleArray(array) {
+ const shuffledArray = [...array] // 创建数组的副本,以避免修改原始数组
+ for (let i = shuffledArray.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1))
+ ;[shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]]
+ }
+ return shuffledArray
+}
diff --git a/themes/heo/components/PostAdjacent.js b/themes/heo/components/PostAdjacent.js
index 09f2204b371..a170ff3b6fe 100644
--- a/themes/heo/components/PostAdjacent.js
+++ b/themes/heo/components/PostAdjacent.js
@@ -66,7 +66,7 @@ export default function PostAdjacent({ prev, next }) {
+ className='cursor-pointer justify-between space-y-1 px-5 py-6 rounded-t-xl dark:bg-[var(--heo-color-card-dark)] hover:border hover:border-[var(--heo-color-border)] dark:hover:border-[var(--heo-color-border-dark)] border-b-0 items-center dark:text-white flex flex-col w-full h-18 duration-200'>
上一篇
{prev.title}
@@ -75,7 +75,7 @@ export default function PostAdjacent({ prev, next }) {
+ className='cursor-pointer justify-between space-y-1 px-5 py-6 rounded-b-xl dark:bg-[var(--heo-color-card-dark)] hover:border hover:border-[var(--heo-color-border)] dark:hover:border-[var(--heo-color-border-dark)] items-center dark:text-white flex flex-col w-full h-18 duration-200'>
下一篇
{next.title}
@@ -90,7 +90,7 @@ export default function PostAdjacent({ prev, next }) {
className={`${isShow ? 'mb-5 opacity-100' : '-mb-24 opacity-0'} hidden md:block fixed z-40 right-10 bottom-4 duration-200 transition-all`}>
+ className='text-sm block p-4 w-72 h-28 cursor-pointer drop-shadow-xl duration transition-all dark:bg-[var(--heo-color-card-dark)] hover:border hover:border-[var(--heo-color-border)] dark:hover:border-[var(--heo-color-border-dark)] bg-[var(--heo-color-card)] dark:text-gray-300 dark:hover:text-[var(--heo-color-accent)] hover:font-bold hover:text-[var(--heo-color-primary)] rounded-lg'>
{locale.COMMON.NEXT_POST}
{next?.title}
diff --git a/themes/heo/components/PostCopyright.js b/themes/heo/components/PostCopyright.js
index e92d775ad1b..a14edc6956c 100644
--- a/themes/heo/components/PostCopyright.js
+++ b/themes/heo/components/PostCopyright.js
@@ -13,10 +13,12 @@ import { resolveArticleCopyrightText } from '@/lib/utils/articleCopyright'
*/
export default function PostCopyright({ post }) {
const router = useRouter()
- const [path, setPath] = useState(siteConfig('LINK') + router.asPath)
+ const [path, setPath] = useState('') // 初始状态为空
+ const [copied, setCopied] = useState(false) // 复制成功提示
+
useEffect(() => {
- setPath(window.location.href)
- })
+ setPath(window.location.href) // 每次路由变化时更新 URL
+ }, [router.asPath]) // 监听 router.asPath
const { locale } = useGlobal()
const copyrightText = resolveArticleCopyrightText({
@@ -24,28 +26,46 @@ export default function PostCopyright({ post }) {
locale,
mode: siteConfig('HEO_ARTICLE_COPYRIGHT', null, CONFIG)
})
+ // 文章带「原创」标签时第一行显示作者,否则显示整理
+ const isOriginalPost =
+ post?.tags?.includes('原创') ||
+ post?.tagItems?.some(tag => tag.name === '原创')
if (!copyrightText) {
return <>>
}
+ // 复制链接的函数
+ const handleCopy = async () => {
+ try {
+ await navigator.clipboard.writeText(path)
+ setCopied(true) // 设置复制成功
+ setTimeout(() => setCopied(false), 2000) // 2秒后隐藏提示
+ } catch (error) {
+ console.error('复制失败:(')
+ }
+ }
+
return (
-
-
+
+
-
- {locale.COMMON.AUTHOR}:
-
+
+ {isOriginalPost ? locale.COMMON.AUTHOR : locale.COMMON.COMPILER || '整理'}:
+
+
{siteConfig('AUTHOR')}
-
{locale.COMMON.URL}:
-
- {path}
-
+ {path} (单击复制链接)
+
+ {copied && ✅ 链接复制成功!}
-
{locale.COMMON.COPYRIGHT}:
diff --git a/themes/heo/components/PostHeader.js b/themes/heo/components/PostHeader.js
index c65a4f29ef6..8765c78b97e 100644
--- a/themes/heo/components/PostHeader.js
+++ b/themes/heo/components/PostHeader.js
@@ -4,6 +4,8 @@ import NotionIcon from '@/components/NotionIcon'
import WordCount from '@/components/WordCount'
import { siteConfig } from '@/lib/config'
import { formatDateFmt } from '@/lib/utils/formatDate'
+import { useGlobal } from '@/lib/global'
+import { buildSlugMap, toSlug } from '@/lib/utils/slugMap'
import SmartLink from '@/components/SmartLink'
import WavesArea from './WavesArea'
@@ -13,6 +15,8 @@ import WavesArea from './WavesArea'
* @returns
*/
export default function PostHeader({ post, siteInfo, isDarkMode, lock }) {
+ const { tagOptions } = useGlobal()
+ const tagSlugMap = buildSlugMap(tagOptions?.map(t => t.name) || [])
if (!post) {
return <>>
}
@@ -48,9 +52,11 @@ export default function PostHeader({ post, siteInfo, isDarkMode, lock }) {
+ className='coverdiv lg:opacity-70 lg:translate-x-96 lg:rotate-12'>
(
@@ -52,7 +52,7 @@ export default function SideRight(props) {
{/* 最新文章列表 */}
@@ -65,7 +65,7 @@ export default function SideRight(props) {
{/* 标签和成绩 */}
diff --git a/themes/heo/components/TagGroups.js b/themes/heo/components/TagGroups.js
index 1bbd92f7136..96c1913e2f7 100644
--- a/themes/heo/components/TagGroups.js
+++ b/themes/heo/components/TagGroups.js
@@ -1,4 +1,6 @@
import SmartLink from '@/components/SmartLink'
+import { siteConfig } from '@/lib/config'
+import { buildSlugMap, fromSlug, toSlug } from '@/lib/utils/slugMap'
import { useRouter } from 'next/router'
/**
@@ -10,34 +12,41 @@ import { useRouter } from 'next/router'
*/
const TagGroups = ({ tags, className }) => {
const router = useRouter()
- const { tag: currentTag } = router.query
+ const slugMap = buildSlugMap(tags?.map(t => t.name) || [])
+ const currentTag = fromSlug(router.query.tag, slugMap)
if (!tags) return <>>
return (
-
+
)
}
diff --git a/themes/heo/components/TagItemMini.js b/themes/heo/components/TagItemMini.js
index 16b22921162..3dcec4a91f9 100644
--- a/themes/heo/components/TagItemMini.js
+++ b/themes/heo/components/TagItemMini.js
@@ -1,11 +1,15 @@
import { HashTag } from '@/components/HeroIcons'
import SmartLink from '@/components/SmartLink'
+import { useGlobal } from '@/lib/global'
+import { buildSlugMap, toSlug } from '@/lib/utils/slugMap'
const TagItemMini = ({ tag, selected = false }) => {
+ const { tagOptions } = useGlobal()
+ const slugMap = buildSlugMap(tagOptions?.map(t => t.name) || [])
return (
diff --git a/themes/heo/config.js b/themes/heo/config.js
index 9ebbeda3993..36563888a83 100644
--- a/themes/heo/config.js
+++ b/themes/heo/config.js
@@ -1,5 +1,5 @@
const CONFIG = {
- HEO_HOME_POST_TWO_COLS: true, // 首页博客两列显示,若为false则只显示一列
+ HEO_HOME_POST_TWO_COLS: false, // 首页博客两列显示,若为false则只显示一列
HEO_LOADING_COVER: true, // 页面加载的遮罩动画
HEO_HOME_BANNER_ENABLE: true,
@@ -20,64 +20,84 @@ const CONFIG = {
HEO_COLOR_TEXT: '#111827',
HEO_COLOR_TEXT_SECONDARY: '#4b5563',
- HEO_SITE_CREATE_TIME: '2021-09-21', // 建站日期,用于计算网站运行的第几天
+ HEO_SITE_CREATE_TIME: '2025-01-23', // 建站日期,用于计算网站运行的第几天
// 首页顶部通知条滚动内容,如不需要可以留空 []
HEO_NOTICE_BAR: [
- { title: '欢迎来到我的博客', url: 'https://blog.tangly1024.com' },
- { title: '访问文档中心获取更多帮助', url: 'https://docs.tangly1024.com' }
+ { title: '欢迎来到我的博客❤'},
+ { title: '我希望事情是本来的样子而不是我臆想的样子。'},
+ { title: '你和你喜欢的人一起坐过摩天轮吗?'},
+ { title: '放下助人情节,尊重他人命运。'},
+ { title: '童话也是生活的一部分。'},
+ { title: '墨小菊天下第一!'},
+ { title: '时间让你我越走越近,却越来越陌生。'},
+ { title: '𝑲𝒆𝒆𝒑 𝒐𝒏 𝒌𝒆𝒆𝒑𝒊𝒏𝒈 𝒐𝒏.'},
+ { title: '人活一辈子,谁不急个眼'},
+ { title: '欢迎来我的Bilibili主页逛逛 :)', url: 'https://space.bilibili.com/334597217' }
],
HEO_NOTICE_BAR_INTERVAL: 3000, // 多条通知的切换间隔,单位毫秒;非正数或无效值回退为 3000
// 英雄区左右侧组件颠倒位置
HEO_HERO_REVERSE: false,
// 博客主体区左右侧组件颠倒位置
- HEO_HERO_BODY_REVERSE: false,
+ HEO_HERO_BODY_REVERSE: true,
// 英雄区(首页顶部大卡)
- HEO_HERO_TITLE_1: '分享编程',
- HEO_HERO_TITLE_2: '与思维认知',
- HEO_HERO_TITLE_3: 'TANGLY1024.COM',
- HEO_HERO_TITLE_4: '新版上线',
- HEO_HERO_TITLE_5: 'NotionNext4.0 轻松定制主题',
- HEO_HERO_TITLE_LINK: 'https://tangly1024.com',
+ HEO_HERO_TITLE_1: '分享电子生活',
+ HEO_HERO_TITLE_2: '尽己所能记录问题与解决方案',
+ HEO_HERO_TITLE_3: 'from 2025',
+ HEO_HERO_TITLE_4: 'Fun Facts:', // 今日卡牌小标题
+ HEO_HERO_TITLE_5: '我的个人朋友圈上线啦!', // 保留,作为每日一句默认内容之一
+ HEO_HERO_TITLE_LINK: 'https://www.barryzed.top/article/memos_brief', // 点击今日卡牌跳转链接
// 英雄区遮罩文字
- HEO_HERO_COVER_TITLE: '随便逛逛',
+ HEO_HERO_COVER_TITLE: '随便逛逛?',
+
+ // 今日卡牌:Steam 状态追踪,API_KEY 或 ID 留空则不显示
+ // Steam Web API Key 请配置在环境变量 HEO_STEAM_API_KEY 中(Vercel 项目设置 -> Environment Variables,本地用 .env.local),不要写进代码仓库
+ HEO_STEAM_ID: '76561199012533932', // 你的 SteamID64,可在 https://steamid.io 查询
+ HEO_STEAM_PROFILE_URL: 'https://steamcommunity.com/id/barryzed', // 可选,自定义 Steam 主页跳转链接;留空则使用 Steam 返回的 profileurl
+ HEO_STEAM_CACHE_SECONDS: 120, // Steam 状态缓存秒数,避免频繁请求 Steam API
+ // Steam 游戏中文名映射(appid -> 中文名),未收录的游戏会自动请求 Steam 商店中文接口,失败则显示英文名
+ HEO_STEAM_GAME_NAMES: {
+ '250900': '以撒的结合:重生'
+ },
// 英雄区显示三个置顶分类
- HEO_HERO_CATEGORY_1: { title: '必看精选', url: '/tag/必看精选' },
- HEO_HERO_CATEGORY_2: { title: '热门文章', url: '/tag/热门文章' },
- HEO_HERO_CATEGORY_3: { title: '实用教程', url: '/tag/实用教程' },
+ HEO_HERO_CATEGORY_1: { title: '教程', url: '/category/tutorial' },
+ HEO_HERO_CATEGORY_2: { title: '游戏', url: '/category/game' },
+ HEO_HERO_CATEGORY_3: { title: '编程', url: '/category/program' },
// 英雄区右侧推荐文章标签, 例如 [推荐] , 最多六篇文章; 若留空白'',则推荐最近更新文章
HEO_HERO_RECOMMEND_POST_TAG: '推荐',
- HEO_HERO_RECOMMEND_POST_SORT_BY_UPDATE_TIME: false, // 推荐文章排序,为`true`时将强制按最后修改时间倒序
- // HERO_RECOMMEND_COVER: 'https://cdn.pixabay.com/photo/2015/10/30/20/13/sunrise-1014712_1280.jpg', // 英雄区右侧图片
+ HEO_HERO_RECOMMEND_POST_SORT_BY_UPDATE_TIME: true, // 推荐文章排序,为`true`时将强制按最后修改时间倒序
+ HERO_RECOMMEND_COVER: 'https://pic1.imgdb.cn/item/679a3cfbd0e0a243d4f879f9.webp', // 英雄区右侧图片
// 英雄区右侧推荐文章遮罩控制
- HEO_HERO_RECOMMEND_COVER_ENABLE: false, // 是否显示推荐文章遮罩图片,true显示遮罩需点击查看,false直接显示推荐文章
+ HEO_HERO_RECOMMEND_COVER_ENABLE: true, // 是否显示推荐文章遮罩图片,true显示遮罩需点击查看,false直接显示推荐文章
+
// 右侧个人资料卡牌欢迎语,点击可自动切换
HEO_INFOCARD_GREETINGS: [
- '你好!我是',
- '🔍 分享与热心帮助',
- '🤝 专修交互与设计',
- '🏃 脚踏实地行动派',
- '🏠 智能家居小能手',
- '🤖️ 数码科技爱好者',
- '🧱 团队小组发动机'
+ 'Hi!我是',
+ 'Apex Legends里爱玩探路者的',
+ '爱玩各种单机游戏的',
+ '爱打架子鼓的',
+ '会一点launchpad并在精进的',
+ '就爱自己瞎搞,还啥都想搞的',
+ '爱玩以撒的',
+ '单身的T_T',
+ '喜欢收集游戏设定集的',
+ '喜欢收集各种OST的',
+ '深爱着墨小菊的'
],
// 个人资料底部按钮
- HEO_INFO_CARD_URL1: '/about',
- HEO_INFO_CARD_ICON1: 'fas fa-user',
- HEO_INFO_CARD_URL2: 'https://github.com/tangly1024',
- HEO_INFO_CARD_ICON2: 'fab fa-github',
- HEO_INFO_CARD_ICON_ORCID: 'fab fa-orcid',
- HEO_INFO_CARD_ICON_CSDN: 'fab fa-csdn',
- HEO_INFO_CARD_ICON_JUEJIN: 'fab fa-juejin',
- HEO_INFO_CARD_URL3: 'https://www.tangly1024.com',
- HEO_INFO_CARD_TEXT3: '了解更多',
+ HEO_INFO_CARD_URL1: 'https://www.barryzed.top/article/record_info',
+ HEO_INFO_CARD_ICON1: 'fa-duotone fa-solid fa-chart-pie',
+ HEO_INFO_CARD_URL2: 'https://space.bilibili.com/334597217',
+ HEO_INFO_CARD_ICON2: 'fa-brands fa-bilibili',
+ HEO_INFO_CARD_URL3: 'https://www.barryzed.top/article/memos_brief',
+ HEO_INFO_CARD_TEXT3: '个人朋友圈',
// 用户技能图标
HEO_GROUP_ICONS: [
@@ -139,7 +159,7 @@ const CONFIG = {
}
],
- HEO_SOCIAL_CARD: true, // 是否显示右侧,点击加入社群按钮
+ HEO_SOCIAL_CARD: false, // 是否显示右侧,点击加入社群按钮
HEO_SOCIAL_CARD_TITLE_1: '交流频道',
HEO_SOCIAL_CARD_TITLE_2: '加入我们的社群讨论分享',
HEO_SOCIAL_CARD_TITLE_3: '点击加入社群',
diff --git a/themes/heo/index.js b/themes/heo/index.js
index 93863a7245a..17a377213c9 100644
--- a/themes/heo/index.js
+++ b/themes/heo/index.js
@@ -20,11 +20,12 @@ import { siteConfig } from '@/lib/config'
import { useGlobal } from '@/lib/global'
import { loadWowJS } from '@/lib/plugins/wow'
import { isBrowser } from '@/lib/utils'
+import { buildSlugMap, toSlug } from '@/lib/utils/slugMap'
import { Transition } from '@headlessui/react'
import SmartLink from '@/components/SmartLink'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
-import BlogPostArchive from './components/BlogPostArchive'
+import BlogPostCard from './components/BlogPostCard'
import BlogPostListPage from './components/BlogPostListPage'
import BlogPostListScroll from './components/BlogPostListScroll'
import CategoryBar from './components/CategoryBar'
@@ -222,22 +223,31 @@ const LayoutSearch = props => {
* @returns
*/
const LayoutArchive = props => {
- const { archivePosts } = props
+ const { archivePosts, siteInfo } = props
// 归档页顶部显示条,如果是默认归档则不显示。分类详情页显示分类列表,标签详情页显示当前标签
return (
-
+
{/* 文章分类条 */}
{Object.keys(archivePosts).map(archiveTitle => (
-
+
+
+ {archiveTitle}
+
+ {archivePosts[archiveTitle]?.map((post, index) => (
+
+ ))}
+
))}
@@ -288,7 +298,7 @@ const LayoutSlug = props => {
return (
<>
+ className={`article h-full w-full ${fullWidth ? '' : 'xl:max-w-5xl'} ${hasCode ? 'xl:w-[73.15vw]' : ''} bg-[var(--heo-color-card)] dark:bg-[var(--heo-color-bg-dark)] border border-[var(--heo-color-border)] dark:border-[var(--heo-color-border-dark)] lg:hover:shadow rounded-2xl lg:px-2 lg:py-4 `}>
{/* 文章锁 */}
{lock &&
}
@@ -354,9 +364,33 @@ const LayoutSlug = props => {
* @param {*} props
* @returns
*/
+const ERROR_IMAGES = [
+ { src: '/images/404/404 (1).png', weight: 1 },
+ { src: '/images/404/404 (2).png', weight: 1 },
+ { src: '/images/404/404 (3).png', weight: 1 },
+ { src: '/images/404/404 (4).png', weight: 1 },
+ { src: '/images/404/404 (5).png', weight: 0.1 }
+]
+
+const pickRandomErrorImage = () => {
+ const total = ERROR_IMAGES.reduce((sum, item) => sum + item.weight, 0)
+ let random = Math.random() * total
+ for (const item of ERROR_IMAGES) {
+ random -= item.weight
+ if (random < 0) {
+ return item.src
+ }
+ }
+ return ERROR_IMAGES[ERROR_IMAGES.length - 1].src
+}
+
const Layout404 = props => {
// const { meta, siteInfo } = props
const { onLoading, fullWidth } = useGlobal()
+ const [errorImage, setErrorImage] = useState(ERROR_IMAGES[0].src)
+ useEffect(() => {
+ setErrorImage(pickRandomErrorImage())
+ }, [])
return (
<>
{/* 主区块 */}
@@ -375,16 +409,17 @@ const Layout404 = props => {
leaveTo='opacity-0 -translate-y-16'
unmount={false}>
{/* 404卡牌 */}
-
+
{/* 左侧动图 */}
-
+
+
+
{/* 右侧文字 */}
+
没有找到这个页面哦(´。_。`)
404
@@ -413,33 +448,77 @@ const Layout404 = props => {
* @param {*} props
* @returns
*/
+// 分类卡片循环使用的渐变色
+const CATEGORY_GRADIENTS = [
+ 'from-orange-400 to-amber-300',
+ 'from-sky-400 to-cyan-300',
+ 'from-emerald-400 to-teal-300',
+ 'from-violet-400 to-purple-300',
+ 'from-rose-400 to-pink-300',
+ 'from-indigo-400 to-blue-300'
+]
+
const LayoutCategoryIndex = props => {
const { categoryOptions } = props
const { locale } = useGlobal()
+ const slugMap = buildSlugMap(categoryOptions?.map(c => c.name) || [])
+ // 按文章数量从多到少排序
+ const categories = [...(categoryOptions || [])].sort(
+ (a, b) => (b.count || 0) - (a.count || 0)
+ )
return (
-
- {locale.COMMON.CATEGORY}
+ {/* 标题 + 分类总数 */}
+
+
+
+ {locale.COMMON.CATEGORY}
+
+ {categories.length} 个分类
+
+
+
+ {/* 分类卡片网格 */}
- {categoryOptions?.map(category => {
+ className='duration-200 grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-4'>
+ {categories.length === 0 && (
+
+ 还没有分类
+
+ )}
+ {categories.map((category, index) => {
+ const gradient = CATEGORY_GRADIENTS[index % CATEGORY_GRADIENTS.length]
return (
-
- {category.name}
-
- {category.count}
+ className='group relative overflow-hidden cursor-pointer rounded-2xl border border-gray-200 dark:border-gray-700 bg-[var(--heo-color-card)] dark:bg-[var(--heo-color-card-dark)] p-5 transition-all duration-200 hover:-translate-y-1 hover:shadow-lg hover:border-[var(--heo-color-primary)] dark:hover:border-[var(--heo-color-accent)]'>
+ {/* 顶部渐变装饰条 */}
+
+
+
+
+
+
+
+ {category.name}
+
+
+ {category.count || 0} {locale.COMMON.POSTS}
+
+
+
+
+ 查看分类 →
@@ -458,31 +537,72 @@ const LayoutCategoryIndex = props => {
const LayoutTagIndex = props => {
const { tagOptions } = props
const { locale } = useGlobal()
+ const slugMap = buildSlugMap(tagOptions?.map(t => t.name) || [])
+ const [keyword, setKeyword] = useState('')
+
+ // 按文章数量从多到少排序,并支持关键词过滤
+ const tags = (tagOptions || [])
+ .filter(
+ tag =>
+ !keyword ||
+ tag.name.toLowerCase().includes(keyword.toLowerCase())
+ )
+ .sort((a, b) => (b.count || 0) - (a.count || 0))
return (
-
- {locale.COMMON.TAGS}
+ {/* 标题 + 标签总数 */}
+
+
+ {locale.COMMON.TAGS}
+
+ {tagOptions?.length || 0} 个标签
+
+
+
+ {/* 标签搜索 */}
+
+
+
+ setKeyword(e.target.value)}
+ placeholder='搜索标签…'
+ className='w-full rounded-xl border border-gray-200 dark:border-gray-700 bg-[var(--heo-color-card)] dark:bg-[var(--heo-color-card-dark)] py-2 pl-9 pr-3 text-sm text-gray-900 dark:text-gray-100 outline-none transition-colors focus:border-[var(--heo-color-primary)] dark:focus:border-[var(--heo-color-accent)]'
+ />
+
+
+
+ {/* 标签列表 */}
- {tagOptions.map(tag => {
+ className='duration-200 flex flex-wrap gap-3'>
+ {tags.length === 0 && (
+
+ 没有找到匹配的标签
+
+ )}
+ {tags.map((tag, index) => {
+ const hot = index < 3
return (
-
- {tag.name}
-
+ className={`group flex flex-nowrap items-center gap-1.5 rounded-full border bg-[var(--heo-color-card)] dark:bg-[var(--heo-color-card-dark)] px-4 py-1.5 cursor-pointer transition-all duration-150 hover:scale-105 border-gray-200 dark:border-gray-700 hover:border-[var(--heo-color-primary)] dark:hover:border-[var(--heo-color-accent)] hover:bg-[var(--heo-color-primary)] dark:hover:bg-[var(--heo-color-accent)] hover:text-[var(--heo-color-primary-text)] ${
+ hot
+ ? 'text-base font-bold'
+ : 'text-sm font-normal'
+ }`}>
+
+ {tag.name}
+
{tag.count}
-
+
)
diff --git a/themes/heo/style.js b/themes/heo/style.js
index 6f1e7cbff1f..d6cc0ed0ccd 100644
--- a/themes/heo/style.js
+++ b/themes/heo/style.js
@@ -163,11 +163,6 @@ const Style = () => {
white-space: nowrap;
}
- .today-card-cover {
- -webkit-mask-image: linear-gradient(to top, transparent 5%, black 70%);
- mask-image: linear-gradient(to top, transparent 5%, black 70%);
- }
-
.recent-top-post-group::-webkit-scrollbar {
display: none;
}
diff --git a/themes/hexo/components/SocialButton.js b/themes/hexo/components/SocialButton.js
index df517c0a546..a0da530f6ac 100644
--- a/themes/hexo/components/SocialButton.js
+++ b/themes/hexo/components/SocialButton.js
@@ -9,24 +9,9 @@ import { handleEmailClick } from '@/lib/plugins/mailEncrypt'
* @constructor
*/
const SocialButton = () => {
- const CONTACT_GITHUB = siteConfig('CONTACT_GITHUB')
- const CONTACT_TWITTER = siteConfig('CONTACT_TWITTER')
- const CONTACT_TELEGRAM = siteConfig('CONTACT_TELEGRAM')
-
- const CONTACT_LINKEDIN = siteConfig('CONTACT_LINKEDIN')
- const CONTACT_ORCID = siteConfig('CONTACT_ORCID')
- const CONTACT_CSDN = siteConfig('CONTACT_CSDN')
- const CONTACT_JUEJIN = siteConfig('CONTACT_JUEJIN')
- const CONTACT_WEIBO = siteConfig('CONTACT_WEIBO')
- const CONTACT_INSTAGRAM = siteConfig('CONTACT_INSTAGRAM')
const CONTACT_EMAIL = siteConfig('CONTACT_EMAIL')
- const ENABLE_RSS = siteConfig('ENABLE_RSS')
const CONTACT_BILIBILI = siteConfig('CONTACT_BILIBILI')
- const CONTACT_YOUTUBE = siteConfig('CONTACT_YOUTUBE')
- const CONTACT_XIAOHONGSHU = siteConfig('CONTACT_XIAOHONGSHU')
- const CONTACT_ZHISHIXINGQIU = siteConfig('CONTACT_ZHISHIXINGQIU')
- const CONTACT_WEHCHAT_PUBLIC = siteConfig('CONTACT_WEHCHAT_PUBLIC')
const [qrCodeShow, setQrCodeShow] = useState(false)
@@ -42,88 +27,7 @@ const SocialButton = () => {
return (
)
diff --git a/themes/hexo/config.js b/themes/hexo/config.js
index 5966bbff9cf..a0788df5d1f 100644
--- a/themes/hexo/config.js
+++ b/themes/hexo/config.js
@@ -2,10 +2,7 @@ const CONFIG = {
HEXO_HOME_BANNER_ENABLE: true,
// 3.14.1以后的版本中,欢迎语在blog.config.js中配置,用英文逗号','隔开多个。
HEXO_HOME_BANNER_GREETINGS: [
- 'Hi,我是一个程序员',
- 'Hi,我是一个打工人',
- 'Hi,我是一个干饭人',
- '欢迎来到我的博客🎉'
+ '这是主题文件夹中legacy的首页打字文字,你若看见这行字了请联系BarryZed:)'
], // 首页大图标语文字
HEXO_HOME_NAV_BUTTONS: true, // 首页是否显示分类大图标按钮
diff --git a/tsconfig.json b/tsconfig.json
index 2761fb88807..95dc7dde523 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -2,17 +2,39 @@
"compilerOptions": {
"baseUrl": ".",
"paths": {
- "@/*": ["./*"],
- "@/blog.config": ["./blog.config"],
- "@/components/*": ["components/*"],
- "@/hooks/*": ["hooks/*"],
- "@/themes/*": ["themes/*"],
- "@/pages/*": ["pages/*"],
- "@/data/*": ["data/*"],
- "@/lib/*": ["lib/*"],
- "@/styles/*": ["styles/*"]
+ "@/*": [
+ "./*"
+ ],
+ "@/blog.config": [
+ "./blog.config"
+ ],
+ "@/components/*": [
+ "components/*"
+ ],
+ "@/hooks/*": [
+ "hooks/*"
+ ],
+ "@/themes/*": [
+ "themes/*"
+ ],
+ "@/pages/*": [
+ "pages/*"
+ ],
+ "@/data/*": [
+ "data/*"
+ ],
+ "@/lib/*": [
+ "lib/*"
+ ],
+ "@/styles/*": [
+ "styles/*"
+ ]
},
- "lib": ["dom", "dom.iterable", "esnext"],
+ "lib": [
+ "dom",
+ "dom.iterable",
+ "esnext"
+ ],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
@@ -36,7 +58,8 @@
"allowSyntheticDefaultImports": true,
"declaration": false,
"declarationMap": false,
- "sourceMap": false
+ "sourceMap": false,
+ "target": "ES2017"
},
"include": [
"next-env.d.ts",