feat(v0.1.1): 周期表五大分区 / 分区与单格改色 / 全屏视线跟随 / 窗口图标 / 跨平台打包

This commit is contained in:
TianXiaRi
2026-12-02 10:27:25 +08:00
parent a9adcd0088
commit 1faee09484
37 changed files with 2477 additions and 127 deletions
+62
View File
@@ -0,0 +1,62 @@
const fs = require('fs')
const p = 'E:/SodiumPet/WorkPlace/v0.1.1/src/main/index.ts'
let c = fs.readFileSync(p, 'utf8')
function rep(from, to, label) {
if (!c.includes(from)) {
console.log('MISS:', label)
return
}
c = c.replace(from, to)
console.log('ok:', label)
}
// 编辑器:切到「等级」页 + 截图
rep(
` await editorWindow.webContents.executeJavaScript(
"[...document.querySelectorAll('.detail-tabs .set-tab')].find(b => b.textContent === '界面')?.click()"
)`,
` await editorWindow.webContents.executeJavaScript(
"[...document.querySelectorAll('.detail-tabs .set-tab')].find(b => b.textContent === '等级')?.click()"
)`,
'editor tab level'
)
rep(
` const stickerCount = await editorWindow.webContents.executeJavaScript(
"document.querySelectorAll('.sticker-cell').length"
)
fs.writeFileSync(path.join(HOME, 'data', 'stickers.txt'), String(stickerCount))`,
` const stickerCount = await editorWindow.webContents.executeJavaScript(
"document.querySelectorAll('.sticker-cell').length"
)
fs.writeFileSync(path.join(HOME, 'data', 'stickers.txt'), String(stickerCount))
const catCount = await editorWindow.webContents.executeJavaScript(
"JSON.stringify({ cells: document.querySelectorAll('.ped-cell').length, zones: document.querySelectorAll('.color-row').length, s: getComputedStyle(document.querySelector('.ped-cell')).backgroundColor })"
)
fs.writeFileSync(path.join(HOME, 'data', 'ped-stats.txt'), String(catCount))
const shot = await editorWindow.webContents.capturePage()
fs.writeFileSync(path.join(HOME, 'data', 'editor.png'), shot.toPNG())`,
'editor capture'
)
// 详情:等级预览截图(放在现有 dump 之后)
rep(
` await detailWindow.webContents.executeJavaScript(
"[...document.querySelectorAll('.level-mode .set-tab')].find(b => b.textContent.includes('化学'))?.click()"
)`,
` await detailWindow.webContents.executeJavaScript(
"[...document.querySelectorAll('.level-mode .set-tab')].find(b => b.textContent.includes('化学'))?.click()"
)
await new Promise((r) => setTimeout(r, 300))
{
const shot = await detailWindow.webContents.capturePage()
fs.writeFileSync(path.join(HOME, 'data', 'detail.png'), shot.toPNG())
const leg = await detailWindow.webContents.executeJavaScript(
"JSON.stringify([...document.querySelectorAll('.legend-item')].map(x => x.innerText.trim()))"
)
fs.writeFileSync(path.join(HOME, 'data', 'legend.txt'), String(leg))
}`,
'detail capture'
)
fs.writeFileSync(p, c, 'utf8')
+21
View File
@@ -0,0 +1,21 @@
const fs = require('fs')
const p = 'E:/SodiumPet/WorkPlace/v0.1.1/src/main/index.ts'
let c = fs.readFileSync(p, 'utf8')
const from = ` await editorWindow.webContents.executeJavaScript(
"[...document.querySelectorAll('.detail-tabs .set-tab')].find(b => b.textContent === '等级')?.click()"
)`
const to = ` const tabLabels = await editorWindow.webContents.executeJavaScript(
"JSON.stringify([...document.querySelectorAll('.detail-tabs .set-tab')].map(b => b.textContent.trim()))"
)
fs.writeFileSync(path.join(HOME, 'data', 'editor-tabs.txt'), String(tabLabels))
await editorWindow.webContents.executeJavaScript(
"(() => { const bs = [...document.querySelectorAll('.detail-tabs .set-tab')]; const t = bs.find(b => b.textContent.trim() === '等级') || bs[2]; t && t.click(); return !!t })()"
)`
if (!c.includes(from)) {
console.log('MISS editor click')
process.exit(1)
}
c = c.replace(from, to)
fs.writeFileSync(p, c, 'utf8')
console.log('patched editor tab click')
+36
View File
@@ -0,0 +1,36 @@
const fs = require('fs')
const p = 'E:/SodiumPet/WorkPlace/v0.1.1/src/renderer/src/detail/Detail.tsx'
let c = fs.readFileSync(p, 'utf8')
const startMark = ' <div className="periodic-legend">'
const start = c.indexOf(startMark)
if (start < 0) {
console.log('legend not found')
process.exit(1)
}
const end = c.indexOf(' </div>', start)
if (end < 0) {
console.log('legend end not found')
process.exit(1)
}
const oldBlock = c.slice(start, end + ' </div>'.length)
const newBlock = [
' <div className="periodic-legend">',
' {periodicZoneList(periodic).map((z) => (',
' <span key={z.id} className="legend-item">',
' <i style={{ background: z.color }} />',
' {z.label}',
' </span>',
' ))}',
' </div>'
].join('\n')
c = c.replace(oldBlock, newBlock)
if (!c.includes('periodicZoneList(periodic)')) {
console.log('replace failed')
process.exit(1)
}
c = c.replace(' periodicCellColor,', ' periodicCellColor,\n periodicZoneList,')
fs.writeFileSync(p, c, 'utf8')
console.log('detail legend patched')
+235
View File
@@ -0,0 +1,235 @@
const fs = require('fs')
const p = 'E:/SodiumPet/WorkPlace/v0.1.1/src/renderer/src/editor/Editor.tsx'
let c = fs.readFileSync(p, 'utf8')
// 1) imports
c = c.replace(
" periodicCellColor,\n PERIODIC_PRESETS,",
" periodicCellColor,\n periodicKeyOf,\n periodicZoneList,\n defaultZoneOf,\n ZONE_LABEL,\n ZONE_COLORS,\n PERIODIC_PRESETS,"
)
// 2) state
c = c.replace(
" const [customDirty, setCustomDirty] = useState(false)",
" const [customDirty, setCustomDirty] = useState(false)\n const [pedMode, setPedMode] = useState<'zone' | 'cell'>('zone')\n const [pedKey, setPedKey] = useState('s')"
)
// 3) helpers —— 插在 return 之前
const helperAnchor = " return (\n <div className=\"editor\""
const helpers = ` function newZone(): void {
const used = new Set(Object.keys(periodic.colors ?? {}))
for (const k of Object.keys(periodic.zoneNames ?? {})) used.add(k)
let n = 1
while (used.has('z' + n)) n++
const id = 'z' + n
const next: PeriodicStyle = {
...periodic,
colors: { ...(periodic.colors ?? {}), [id]: '#9aa7bd' },
zoneNames: { ...(periodic.zoneNames ?? {}), [id]: '自定义 ' + n }
}
setPeriodic(next)
setPedMode('zone')
setPedKey(id)
setCustomDirty(true)
}
const pedZoneRows = periodicZoneList(periodic)
const pedSelZ = pedMode === 'cell' ? Number(pedKey) : 0
const pedZoneNow =
periodic.zoneNames?.[pedKey] ??
(periodic.scheme === 'category'
? ELEMENT_CATEGORY_LABEL[pedKey as keyof typeof ELEMENT_CATEGORY_LABEL] ?? pedKey
: ZONE_LABEL[pedKey as keyof typeof ZONE_LABEL] ?? pedKey)
return (
<div className="editor"`
c = c.replace(helperAnchor, helpers)
// 4) 周期表编辑区整体替换
const startMark = ' <div className="periodic-editor" style={{ background: periodic.bg ?? \'#0e1420\' }}>'
const start = c.indexOf(startMark)
if (start < 0) {
console.log('periodic editor block not found')
process.exit(1)
}
const endMark = ' <div className="field">\n <span>底图背景</span>'
const end = c.indexOf(endMark, start)
if (end < 0) {
console.log('end marker not found')
process.exit(1)
}
const block = ` <div className="ped-mode">
<button
className={'chip' + (pedMode === 'zone' ? ' on' : '')}
onClick={() => setPedMode('zone')}
>
按分区改色
</button>
<button
className={'chip' + (pedMode === 'cell' ? ' on' : '')}
onClick={() => setPedMode('cell')}
>
单格改色
</button>
<span className="tips">按分区:整区同色;单格:只改一个格子。</span>
</div>
<div className="periodic-editor" style={{ background: periodic.bg ?? '#0e1420' }}>
{ELEMENTS.map((el) => {
const [row, col] = ELEMENT_GRID_POS[el.z - 1] ?? [1, 1]
const key = periodicKeyOf(el, periodic)
const colorFor = periodicCellColor(el, periodic)
const active = pedMode === 'zone' ? key === pedKey : String(el.z) === pedKey
return (
<label
key={el.z}
className={'ped-cell' + (active ? ' on' : '')}
style={{ gridRow: row, gridColumn: col, background: colorFor }}
title={el.z + ' ' + elementName(el.z) + ' · ' + key}
onClick={() => {
setPedKey(pedMode === 'zone' ? key : String(el.z))
setLvKind('chemistry')
setLvKey(el.z)
}}
>
<input
type="color"
className="ped-color"
value={colorFor}
onClick={(ev) => ev.stopPropagation()}
onChange={(ev) => {
setCustomDirty(true)
if (pedMode === 'zone') {
setPeriodic({
...periodic,
colors: { ...(periodic.colors ?? {}), [key]: ev.target.value }
})
} else {
setPeriodic({
...periodic,
cellColors: { ...(periodic.cellColors ?? {}), [el.z]: ev.target.value }
})
}
}}
/>
<span className="ped-z">{el.z}</span>
<span className="ped-sym">{el.symbol}</span>
</label>
)
})}
</div>
<div className="ped-current">
<span>
当前{pedMode === 'zone' ? '分区' : '格子'}:
<b>{pedMode === 'zone' ? pedZoneNow : pedKey + ' ' + elementName(Number(pedKey))}</b>
</span>
{pedMode === 'cell' && (
<>
<span className="muted">所属分区</span>
<select
className="text-input ped-small"
value={periodic.zoneOverrides?.[pedSelZ] ?? ''}
onChange={(ev) => {
const v = ev.target.value
const nextOverrides = { ...(periodic.zoneOverrides ?? {}) }
if (!v) delete nextOverrides[pedSelZ]
else nextOverrides[pedSelZ] = v
setPeriodic({ ...periodic, zoneOverrides: nextOverrides })
setCustomDirty(true)
}}
>
<option value="">
默认({ZONE_LABEL[defaultZoneOf(pedSelZ)] ?? defaultZoneOf(pedSelZ)})
</option>
{pedZoneRows.map((z) => (
<option key={z.id} value={z.id}>
{z.label}
</option>
))}
</select>
<button
className="mini"
onClick={() => {
const nextCells = { ...(periodic.cellColors ?? {}) }
delete nextCells[pedSelZ]
setPeriodic({ ...periodic, cellColors: nextCells })
setCustomDirty(true)
}}
>
清除本格颜色
</button>
</>
)}
<button className="mini" onClick={newZone}>
新建分区
</button>
<button
className="mini"
onClick={() => {
setPeriodic({ ...periodic, cellColors: {} })
setCustomDirty(true)
}}
>
清除全部单格
</button>
</div>
<div className="periodic-colors">
{pedZoneRows.map((row) => (
<label key={row.id} className="color-row">
<input
type="color"
value={row.color}
onChange={(e) => {
setPeriodic({
...periodic,
colors: { ...(periodic.colors ?? {}), [row.id]: e.target.value }
})
setCustomDirty(true)
}}
/>
<span>
{row.label}({row.count})
</span>
{!['s', 'p', 'd', 'ds', 'f'].includes(row.id) &&
!Object.keys(ELEMENT_CATEGORY_LABEL).includes(row.id) && (
<input
className="text-input ped-name"
value={periodic.zoneNames?.[row.id] ?? ''}
placeholder="分区名"
onChange={(e) => {
setPeriodic({
...periodic,
zoneNames: { ...(periodic.zoneNames ?? {}), [row.id]: e.target.value }
})
setCustomDirty(true)
}}
/>
)}
</label>
))}
</div>
`
c = c.slice(0, start) + block + c.slice(end)
// 5) 预设应用时清掉单格/归属覆盖;匹配时也比对覆盖是否为空
c = c.replace(
" setPeriodic({ ...periodic, scheme: preset.scheme, colors: { ...preset.colors } })",
" setPeriodic({\n scheme: preset.scheme,\n colors: { ...preset.colors },\n cellColors: {},\n zoneOverrides: {},\n zoneNames: {},\n bg: periodic.bg\n })"
)
c = c.replace(
" ps.scheme === periodic.scheme &&\n JSON.stringify(ps.colors) === JSON.stringify(periodic.colors ?? {})",
" ps.scheme === periodic.scheme &&\n JSON.stringify(ps.colors) === JSON.stringify(periodic.colors ?? {}) &&\n Object.keys(periodic.cellColors ?? {}).length === 0 &&\n Object.keys(periodic.zoneOverrides ?? {}).length === 0"
)
// 6) 提示文案
c = c.replace(
'<p className="tips">点下面的格子或图例就能改颜色;改完会变成「自定义」,另存命名后才会保留。</p>',
'<p className="tips">按分区改色会同时改掉整个区;单格改色只影响一个元素。改完会变成「自定义」,另存命名后才会保留。</p>'
)
fs.writeFileSync(p, c, 'utf8')
console.log('editor patched')
+15
View File
@@ -0,0 +1,15 @@
const fs = require('fs')
const p = 'E:/SodiumPet/WorkPlace/v0.1.1/src/main/index.ts'
let c = fs.readFileSync(p, 'utf8')
const from = ` const cfgNow = store.getConfig()
if (!cfgNow.eyeFollow || !mainWindow || mainWindow.isDestroyed()) return`
const to = ` const cfgNow = store.getConfig()
const forceLook = !!process.env.PET_FORCE_EYE_FOLLOW
if (!(cfgNow.eyeFollow || forceLook) || !mainWindow || mainWindow.isDestroyed()) return`
if (!c.includes(from)) {
console.log('MISS force look')
process.exit(1)
}
c = c.replace(from, to)
fs.writeFileSync(p, c, 'utf8')
console.log('force look debug added')
+73
View File
@@ -0,0 +1,73 @@
const fs = require('fs')
const base = 'E:/SodiumPet/WorkPlace/v0.1.1/src/'
function rep(file, from, to, label) {
const p = base + file
let c = fs.readFileSync(p, 'utf8')
if (!c.includes(from)) {
console.log('MISS:', label)
return
}
c = c.replace(from, to)
fs.writeFileSync(p, c, 'utf8')
console.log('ok:', label)
}
// 1) 适配器:全屏方向映射(远距离保持方向,近距离更灵敏)
rep(
'renderer/src/pet/adapters/live2d.ts',
` // 以脸的位置为中心,把目标限制在一个锥形范围内,鼠标很远时也不会锁死
const s = this.model.scale.x || 1
const cx = this.model.x + (this.baseSize.w / 2) * s
const cy = this.model.y + (this.baseSize.h * 0.45) * s
let dx = x - cx
let dy = y - cy
const dist = Math.hypot(dx, dy)
const R = 260
if (dist > R) {
dx = (dx / dist) * R
dy = (dy / dist) * R
}
this.model?.focus(cx + dx, cy + dy)`,
` // 以脸的位置为中心:方向永远跟随光标,距离只影响偏转幅度
// 这样光标跑到屏幕另一头也能转,不会在窗口边缘就"锁死"
const s = this.model.scale.x || 1
const cx = this.model.x + (this.baseSize.w / 2) * s
const cy = this.model.y + (this.baseSize.h * 0.45) * s
const dx = x - cx
const dy = y - cy
const dist = Math.hypot(dx, dy)
if (dist < 0.5) {
this.model?.focus(cx, cy)
return
}
// 620 约等于"一个窗口外两三屏"的距离;超出后只保留最大偏转
const eased = Math.min(1, Math.pow(dist / 620, 0.6))
const R = 80 + 340 * eased
this.model?.focus(cx + (dx / dist) * R, cy + (dy / dist) * R)`,
'adapter lookAt range'
)
// 2) 渲染层:去掉局部 pointermove 覆盖,统一交给主进程全局轮询
rep(
'renderer/src/App.tsx',
` if (cfg.eyeFollow) {
adapterRef.current?.lookAt?.(e.clientX + cfg.cropLeft, e.clientY + cfg.cropTop)
}
`,
'',
'remove local pointer eye-follow'
)
// 3) preload / api 类型补 inside
rep(
'preload/index.ts',
' onLook: (cb: (p: { x: number; y: number }) => void) => () => void',
' onLook: (cb: (p: { x: number; y: number; inside?: boolean }) => void) => () => void',
'preload onLook type'
)
rep(
'renderer/src/api.ts',
' onLook: (cb: (p: { x: number; y: number }) => void) => () => void',
' onLook: (cb: (p: { x: number; y: number; inside?: boolean }) => void) => () => void',
'api onLook type'
)
+93
View File
@@ -0,0 +1,93 @@
const fs = require('fs')
const p = 'E:/SodiumPet/WorkPlace/v0.1.1/src/main/index.ts'
let c = fs.readFileSync(p, 'utf8')
function rep(from, to, label) {
if (!c.includes(from)) {
console.log('MISS:', label)
return
}
c = c.replace(from, to)
console.log('ok:', label)
}
// 1) 数据目录:平台自适应
rep(
` const candidates = [
process.env.SODIUM_PET_HOME,
'E:\\\\SodiumPet',
path.dirname(app.getPath('exe')),
path.join(app.getPath('appData'), 'SodiumPet'),
path.join(app.getAppPath(), '.devdata')
].filter(Boolean) as string[]`,
` const isWin = process.platform === 'win32'
const candidates = [
process.env.SODIUM_PET_HOME,
// Windows 上沿用之前的固定目录;其他平台用系统标准数据目录
isWin ? 'E:\\\\SodiumPet' : '',
path.join(app.getPath('appData'), 'SodiumPet'),
isWin ? path.dirname(app.getPath('exe')) : '',
path.join(app.getAppPath(), '.devdata')
].filter(Boolean) as string[]`,
'resolveHome platform'
)
// 2) 点击穿透:forward 仅 Windows / macOS 支持
rep(
" mainWindow.setIgnoreMouseEvents(cfg.clickThrough, { forward: true })",
" mainWindow.setIgnoreMouseEvents(\n cfg.clickThrough,\n process.platform === 'linux' ? undefined : { forward: true }\n )",
'clickThrough forward'
)
// 3) 全屏视线跟随:33ms,窗口不可见也照常计算(多屏 / 其他窗口上方同样生效)
rep(
` // 全屏视线跟随:主进程按 50ms 轮询光标位置,发给宠物窗口
setInterval(() => {
const cfgNow = store.getConfig()
if (!cfgNow.eyeFollow || !mainWindow || !mainWindow.isVisible()) return
const p = screen.getCursorScreenPoint()
const b = mainWindow.getBounds()
mainWindow.webContents.send('pet:look', {
x: p.x - b.x + cfgNow.cropLeft,
y: p.y - b.y + cfgNow.cropTop
})
}, 50)`,
` // 全屏视线跟随:主进程按 33ms 轮询光标(屏幕坐标,跨窗口 / 跨显示器都有效)
setInterval(() => {
const cfgNow = store.getConfig()
if (!cfgNow.eyeFollow || !mainWindow || mainWindow.isDestroyed()) return
if (mainWindow.isMinimized()) return
const p = screen.getCursorScreenPoint()
const b = mainWindow.getBounds()
mainWindow.webContents.send('pet:look', {
x: p.x - b.x + cfgNow.cropLeft,
y: p.y - b.y + cfgNow.cropTop,
// 光标是否在窗口内(渲染层可用于复位/弱化)
inside: p.x >= b.x && p.x <= b.x + b.width && p.y >= b.y && p.y <= b.y + b.height
})
}, 33)`,
'global cursor polling'
)
// 4) 窗口截图探针(调试用,设置 PET_CAPTURE_PET 才生效)
rep(
` // 调试:把窗口内容截一张(不受窗口是否被遮挡影响)
if (process.env.PET_CAPTURE_ONCE) {`,
` if (process.env.PET_CAPTURE_PET) {
setTimeout(() => {
void mainWindow?.webContents.capturePage().then((img) => {
try {
fs.writeFileSync(process.env.PET_CAPTURE_PET as string, img.toPNG())
} catch {
/* 忽略 */
}
})
}, 7000)
}
// 调试:把窗口内容截一张(不受窗口是否被遮挡影响)
if (process.env.PET_CAPTURE_ONCE) {`,
'pet capture probe'
)
fs.writeFileSync(p, c, 'utf8')
+14
View File
@@ -0,0 +1,14 @@
const fs = require('fs')
const p = 'E:/SodiumPet/WorkPlace/v0.1.1/src/main/index.ts'
let c = fs.readFileSync(p, 'utf8')
const from =
"JSON.stringify({ cells: document.querySelectorAll('.ped-cell').length, zones: document.querySelectorAll('.color-row').length, s: getComputedStyle(document.querySelector('.ped-cell')).backgroundColor })"
const to =
"JSON.stringify({ cells: document.querySelectorAll('.ped-cell').length, zones: document.querySelectorAll('.color-row').length, colors: [0,4,25,28,56,117].map(i => getComputedStyle(document.querySelectorAll('.ped-cell')[i]).backgroundColor) })"
if (!c.includes(from)) {
console.log('MISS stats')
process.exit(1)
}
c = c.replace(from, to)
fs.writeFileSync(p, c, 'utf8')
console.log('stats patched')
+45
View File
@@ -0,0 +1,45 @@
const fs = require('fs')
const p = 'E:/SodiumPet/WorkPlace/v0.1.1/src/main/index.ts'
let c = fs.readFileSync(p, 'utf8')
// 1) helper:取表情包作为窗口图标
const anchor = 'function appIcon(): NativeImage | undefined {'
if (!c.includes(anchor)) {
console.log('MISS appIcon')
process.exit(1)
}
const helper = `function stickerIcon(name: string, size = 64): NativeImage | undefined {
try {
const p = path.join(bundledDir('stickers'), name)
if (fs.existsSync(p)) return nativeImage.createFromPath(p).resize({ width: size, height: size })
} catch {
/* 忽略 */
}
return undefined
}
function appIcon(): NativeImage | undefined {`
c = c.replace(anchor, helper)
// 2) 按出现顺序给每个窗口分配表情包图标
const mapping = [
'1.0.png', // 主窗口(桌宠)
'2.0.png', // 气泡
'3.0.png', // 右键底栏
'20.0.png', // 音乐
'9.0.png', // 歌词浮窗
'23.1.png', // 编辑器
'4.0.png', // 详细面板
'16.0.png', // 资料库
'8.0.png', // 对话条
'5.0.png' // 面板
]
let idx = 0
c = c.replace(/= new BrowserWindow\(\{/g, (m) => {
const file = mapping[idx] ?? '1.0.png'
idx++
return `${m} icon: stickerIcon('${file}'),`
})
console.log('windows iconified:', idx)
fs.writeFileSync(p, c, 'utf8')