dsh-pighub 0.0.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js ADDED
@@ -0,0 +1,1052 @@
1
+ /**
2
+ * dsh-pighub —— 浏览器半(Client half)。
3
+ *
4
+ * 契约:这个文件必须是一个 **CJS closure-factory bundle**——脚本执行时只调用
5
+ * window.__ModuleLoader__.load({ id, factory }),所有副作用(含样式注入)都发生在
6
+ * factory 真正被物化时。它不是 ESM,也不能 import:宿主会把页面里冻结的模块表
7
+ * 通过 require 传进来(react / react-dom / @deepseek-ai/cordis …)。
8
+ *
9
+ * 这一半负责三块界面,全部注册在官方增量槽位上(不碰 root / sidebar 这类 single 槽位,
10
+ * 那会把官方声明的子槽位一起带走):
11
+ *
12
+ * sidebar.panellist ← 左栏入口(一只朝右看的猪)
13
+ * main ← 面板:左边猪圈,右边像素标题 + 今日猪猪 + 清单
14
+ * shell.overlay ← 页面级桌宠层(面板关掉也要在,所以不能挂在面板里)
15
+ *
16
+ * 与生态里其他桌宠插件并存的四条纪律(照 dsh-pet@0.4.8 的实测约定来):
17
+ * 1. 桌宠层容器 pointer-events: none,只有猪本体接收指针;
18
+ * 2. z-index 取 41(dsh-pet 的根是 40),谁都不遮谁,也不抢模态框的层级;
19
+ * 3. 样式标签带 data-plugin="dsh-pighub"、类名全部 .pighub- 前缀,不写全局选择器;
20
+ * 4. 尊重 prefers-reduced-motion:关掉弹跳与漂移,只保留位置变化。
21
+ */
22
+ window.__ModuleLoader__.load({
23
+ id: 'dsh-pighub',
24
+ factory(require) {
25
+ const React = require('react');
26
+ const h = React.createElement;
27
+ const useRef = React.useRef;
28
+ const useState = React.useState;
29
+ const useEffect = React.useEffect;
30
+ const useCallback = React.useCallback;
31
+
32
+ /* ------------------------------------------------------------------ 样式 */
33
+ const CSS_TAG = 'dsh-pighub/panel';
34
+ /*
35
+ * 样式全部走 DSH 主题令牌(~--dsw-alias-*~),**不判断亮暗**:
36
+ * 深色模式在 shell 里是 ~body[data-ds-dark-theme]~,令牌值由 shell 重定义(见
37
+ * ~@deepseek-ai/dsh-client-ui-theme/lib/styles/design-platform.css~)。
38
+ * 所以只要不写死颜色,主题切换就自动跟随,也不需要维护第二套配色。
39
+ * 猪圈草地与围栏不属于令牌体系,用 ~color-mix~ 与背景令牌混色,同样自动跟随。
40
+ */
41
+ const CSS = [
42
+ '.pighub-panel{position:relative;display:flex;gap:18px;padding:18px;box-sizing:border-box;height:100%;min-height:0;',
43
+ 'color:var(--dsw-alias-label-primary,#1f2328);font-family:\'Microsoft YaHei UI\',\'Segoe UI\',\'PingFang SC\',system-ui,sans-serif}',
44
+ '.pighub-panel *{box-sizing:border-box}',
45
+ '.pighub-left{flex:0 0 auto;display:flex;align-items:flex-start}',
46
+ '.pighub-pen{position:relative;width:min(46vmin,400px);aspect-ratio:1/1;border-radius:14px;overflow:hidden;',
47
+ 'background:radial-gradient(circle at 30% 25%,',
48
+ 'color-mix(in oklab,#cfeaa8 78%,var(--dsw-alias-bg-base,#fff)),',
49
+ 'color-mix(in oklab,#9ccc6a 62%,var(--dsw-alias-bg-layer-2,#eef1ea)) 62%,',
50
+ 'color-mix(in oklab,#7fbf4e 55%,var(--dsw-alias-bg-layer-2,#eef1ea)));',
51
+ 'box-shadow:inset 0 0 0 2px color-mix(in oklab,#6b5433 30%,transparent)}',
52
+ '.pighub-pen:after{content:"";position:absolute;inset:0;pointer-events:none;',
53
+ 'background-image:repeating-linear-gradient(45deg,rgba(255,255,255,.05) 0 6px,transparent 6px 12px)}',
54
+ '.pighub-house{position:absolute;left:5%;bottom:6%;width:16%;aspect-ratio:40/34;z-index:2;',
55
+ 'cursor:pointer;filter:drop-shadow(0 3px 4px rgba(0,0,0,.28))}',
56
+ '.pighub-house svg{width:100%;height:100%;display:block}',
57
+ '.pighub-house-wall{fill:color-mix(in oklab,#e8c9a0 72%,var(--dsw-alias-bg-elevated,#fff));',
58
+ 'stroke:color-mix(in oklab,#6b4320 60%,transparent);stroke-width:1.4}',
59
+ '.pighub-house-roof{fill:color-mix(in oklab,#c85a3c 70%,var(--dsw-alias-bg-elevated,#fff));',
60
+ 'stroke:color-mix(in oklab,#6b2f18 62%,transparent);stroke-width:1.4;stroke-linejoin:round}',
61
+ '.pighub-house-door{fill:color-mix(in oklab,#8a5a30 78%,var(--dsw-alias-bg-base,#fff));',
62
+ 'stroke:color-mix(in oklab,#4a2a12 60%,transparent);stroke-width:1.1}',
63
+ '.pighub-house-window{fill:color-mix(in oklab,#ffe9a8 80%,var(--dsw-alias-bg-elevated,#fff));',
64
+ 'stroke:color-mix(in oklab,#4a2a12 55%,transparent);stroke-width:1}',
65
+ '.pighub-fence-band{position:absolute;left:0;right:0;height:9%;pointer-events:none;z-index:1}',
66
+ '.pighub-fence-band.is-back{top:0;height:10%}',
67
+ '.pighub-fence-band.is-front{bottom:0;height:12%;z-index:3}',
68
+ '.pighub-fence-post{fill:color-mix(in oklab,#c98a4b 70%,var(--dsw-alias-bg-elevated,#fff));',
69
+ 'stroke:color-mix(in oklab,#5a3714 58%,transparent);stroke-width:.7}',
70
+ '.pighub-fence-rail{fill:color-mix(in oklab,#dda264 68%,var(--dsw-alias-bg-elevated,#fff));',
71
+ 'stroke:color-mix(in oklab,#5a3714 58%,transparent);stroke-width:.7}',
72
+ '.pighub-fence-side{position:absolute;top:0;bottom:0;width:3.2%;pointer-events:none;z-index:1;',
73
+ 'background:repeating-linear-gradient(0deg,',
74
+ 'color-mix(in oklab,#7e5024 46%,transparent) 0 5px,transparent 5px 15px),',
75
+ 'linear-gradient(90deg,rgba(255,255,255,.28),rgba(60,38,14,.20))}',
76
+ '.pighub-fence-side.is-left{left:0}',
77
+ '.pighub-fence-side.is-right{right:0;transform:scaleX(-1)}',
78
+ '.pighub-fence i{position:absolute;display:block;',
79
+ 'background:color-mix(in oklab,#c98a4b 72%,var(--dsw-alias-bg-elevated,#fff));',
80
+ 'background-image:repeating-linear-gradient(90deg,',
81
+ 'color-mix(in oklab,#7e5024 46%,transparent) 0 5px,transparent 5px 15px),',
82
+ 'linear-gradient(180deg,rgba(255,255,255,.30),rgba(60,38,14,.22))}',
83
+ '.pighub-fence .t,.pighub-fence .b{left:0;right:0;height:12px}',
84
+ '.pighub-fence .t{top:0;border-bottom:2px solid color-mix(in oklab,#5a3714 40%,transparent)}',
85
+ '.pighub-fence .b{bottom:0;border-top:2px solid color-mix(in oklab,#5a3714 40%,transparent)}',
86
+ '.pighub-fence .l,.pighub-fence .r{top:0;bottom:0;width:12px;',
87
+ 'background-image:repeating-linear-gradient(0deg,',
88
+ 'color-mix(in oklab,#7e5024 46%,transparent) 0 5px,transparent 5px 15px),',
89
+ 'linear-gradient(90deg,rgba(255,255,255,.30),rgba(60,38,14,.22))}',
90
+ '.pighub-fence .l{left:0;border-right:2px solid color-mix(in oklab,#5a3714 40%,transparent)}',
91
+ '.pighub-fence .r{right:0;border-left:2px solid color-mix(in oklab,#5a3714 40%,transparent)}',
92
+ '.pighub-ground{position:absolute;left:4%;right:4%;bottom:6%;height:34%;border-radius:50%;',
93
+ 'background:radial-gradient(ellipse at 50% 50%,rgba(96,68,32,.26),rgba(96,68,32,0) 70%)}',
94
+ '.pighub-actor{position:absolute;transform:translate(-50%,-50%);width:15%;',
95
+ 'transition:left 1.1s ease-in-out,top 1.1s ease-in-out;will-change:left,top}',
96
+ '.pighub-actor img{display:block;width:100%;height:auto;user-select:none;-webkit-user-drag:none;',
97
+ 'touch-action:none;cursor:grab;filter:drop-shadow(0 2px 2px rgba(0,0,0,.32))}',
98
+ '.pighub-actor.is-walk img{animation:pighub-hop .62s ease-in-out infinite}',
99
+ '.pighub-actor.is-idle img{animation:pighub-breathe 2.4s ease-in-out infinite}',
100
+ '.pighub-actor.is-static img{animation:none}',
101
+ '.pighub-actor.is-squish img{animation:pighub-squish .58s cubic-bezier(.34,1.56,.64,1) !important}',
102
+ '@keyframes pighub-squish{0%{transform:scale(1,1)}22%{transform:scale(1.18,.8) translateY(6%)}58%{transform:scale(.93,1.09) translateY(-4%)}100%{transform:scale(1,1)}}',
103
+ '.pighub-starbadge{position:absolute;left:50%;bottom:calc(100% - 2px);transform:translate(-50%,-2px);',
104
+ 'background:var(--dsw-alias-bg-layer-3,#f7f7f7);color:var(--dsw-alias-label-primary,#1f2328);',
105
+ 'border:1px solid var(--dsw-alias-border-l2,rgba(0,0,0,.12));',
106
+ 'font-size:10px;line-height:1;padding:3px 7px;border-radius:999px;',
107
+ 'white-space:nowrap;pointer-events:none;opacity:0;transition:opacity .16s ease;letter-spacing:1px;z-index:3}',
108
+ '.pighub-starbadge.on{opacity:1}',
109
+ '.pighub-settings{position:absolute;right:14px;top:14px;z-index:5;display:flex;gap:6px;align-items:center}',
110
+ '.pighub-iconbtn{width:30px;height:30px;display:inline-flex;align-items:center;justify-content:center;border-radius:9px;',
111
+ 'border:1px solid var(--dsw-alias-border-l2,rgba(120,120,120,.28));',
112
+ 'background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.08));color:inherit;cursor:pointer}',
113
+ '.pighub-iconbtn:hover{background:var(--dsw-alias-interactive-bg-active,rgba(127,127,127,.16))}',
114
+ '.pighub-pop{position:absolute;right:0;top:38px;width:264px;padding:12px;border-radius:12px;z-index:6;',
115
+ 'background:var(--dsw-alias-bg-layer-3,#fff);border:1px solid var(--dsw-alias-border-l2,rgba(120,120,120,.24));',
116
+ 'box-shadow:0 10px 30px rgba(0,0,0,.18);display:flex;flex-direction:column;gap:10px}',
117
+ '.pighub-pop h4{margin:0;font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary,#5a5a5a)}',
118
+ '.pighub-seg{display:flex;gap:4px;flex-wrap:wrap}',
119
+ '.pighub-seg button{flex:1 1 auto;border:1px solid var(--dsw-alias-border-l2,rgba(120,120,120,.3));background:transparent;',
120
+ 'color:inherit;border-radius:8px;padding:6px 4px;font-size:12px;cursor:pointer}',
121
+ '.pighub-seg button[aria-pressed="true"]{background:var(--dsw-alias-interactive-bg-hover,rgba(226,84,58,.14));',
122
+ 'border-color:var(--dsw-alias-brand-primary,#e2543a);color:var(--dsw-alias-brand-primary,#c8402a);font-weight:600}',
123
+ '.pighub-pop .row{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:11px;',
124
+ 'color:var(--dsw-alias-label-secondary,#5a5a5a)}',
125
+ '.pighub-link{border:0;background:transparent;color:var(--dsw-alias-brand-primary,#c8402a);font-size:12px;',
126
+ 'cursor:pointer;padding:0;text-decoration:underline}',
127
+ '.pighub-path{font-family:ui-monospace,Consolas,monospace;font-size:10px;word-break:break-all;',
128
+ 'color:var(--dsw-alias-label-tertiary,#8a8a8a)}',
129
+ '.pighub-empty{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;',
130
+ 'color:var(--dsw-alias-label-secondary,#4b5a3c);font-size:13px;pointer-events:none;text-align:center;padding:24px}',
131
+ '.pighub-right{flex:1 1 auto;min-width:0;display:flex;flex-direction:column;gap:14px}',
132
+ '.pighub-head{display:flex;flex-direction:column;gap:10px;align-items:flex-start}',
133
+ '.pighub-title{display:block;height:46px;color:var(--dsw-alias-brand-primary,#e2543a)}',
134
+ '.pighub-title svg{height:46px;width:auto;display:block;shape-rendering:crispEdges}',
135
+ '.pighub-draw{border:0;border-radius:10px;padding:9px 16px;font-size:14px;font-weight:600;cursor:pointer;',
136
+ 'background:var(--dsw-alias-button-primary-fill,#e2543a);color:var(--dsw-alias-label-primary-inverted,#fff);',
137
+ 'box-shadow:0 2px 0 color-mix(in oklab,var(--dsw-alias-button-primary-fill,#e2543a) 70%,#000);',
138
+ 'transition:transform .12s ease,box-shadow .12s ease}',
139
+ '.pighub-draw:active{transform:translateY(1px);box-shadow:0 1px 0 color-mix(in oklab,var(--dsw-alias-button-primary-fill,#e2543a) 70%,#000)}',
140
+ '.pighub-draw:disabled{background:var(--dsw-alias-bg-mask-2,#d9dcd4);color:var(--dsw-alias-label-tertiary,#6b7466);',
141
+ 'box-shadow:none;cursor:default}',
142
+ '.pighub-meta{font-size:12px;color:var(--dsw-alias-label-secondary,#5a5a5a);line-height:1.5}',
143
+ '.pighub-sorts{display:flex;gap:6px;flex-wrap:wrap}',
144
+ '.pighub-sort{border:1px solid var(--dsw-alias-border-l2,rgba(120,120,120,.32));background:transparent;color:inherit;',
145
+ 'border-radius:999px;padding:4px 11px;font-size:12px;cursor:pointer}',
146
+ '.pighub-sort[aria-pressed="true"]{background:var(--dsw-alias-interactive-bg-hover,rgba(226,84,58,.12));',
147
+ 'border-color:var(--dsw-alias-brand-primary,#e2543a);color:var(--dsw-alias-brand-primary,#c8402a)}',
148
+ '.pighub-list{flex:1 1 auto;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:8px;padding-right:4px}',
149
+ '.pighub-row{display:flex;gap:10px;align-items:center;padding:8px;border-radius:10px;',
150
+ 'background:var(--dsw-alias-bg-layer-1,rgba(127,127,127,.06));',
151
+ // 亮色主题里 layer-1 与底色同为白,只靠背景分不出卡片;补一圈极淡描边,两种主题都成立。
152
+ 'border:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.06))}',
153
+ '.pighub-row:hover{border-color:var(--dsw-alias-border-l2,rgba(226,84,58,.35))}',
154
+ '.pighub-row img{width:44px;height:44px;object-fit:cover;border-radius:8px;flex:0 0 auto;',
155
+ 'background:var(--dsw-alias-bg-mask-2,rgba(127,127,127,.12))}',
156
+ '.pighub-row-main{min-width:0;flex:1 1 auto}',
157
+ '.pighub-row-title{font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary,#1f2328);',
158
+ 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
159
+ '.pighub-row-sub{font-size:11px;color:var(--dsw-alias-label-secondary,#5a5a5a);margin-top:2px;line-height:1.45;',
160
+ 'white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
161
+ '.pighub-stars{flex:0 0 auto;color:var(--dsw-static-amber-500,#f0a92c);font-size:12px;letter-spacing:1px}',
162
+ '.pighub-tag{flex:0 0 auto;font-size:11px;padding:2px 7px;border-radius:999px;',
163
+ 'background:var(--dsw-alias-bg-mask-2,rgba(127,127,127,.14));color:var(--dsw-alias-label-secondary,#5a5a5a)}',
164
+ '.pighub-pets{position:fixed;inset:0;z-index:41;pointer-events:none;overflow:hidden}',
165
+ '.pighub-reveal{position:fixed;left:0;top:0;z-index:60;pointer-events:none;will-change:transform,opacity}',
166
+ '.pighub-reveal img{display:block;width:100%;height:100%;filter:drop-shadow(0 8px 14px rgba(0,0,0,.32))}',
167
+ '.pighub-reveal.is-pop img{animation:pighub-pop .5s cubic-bezier(.2,1.7,.42,1) both}',
168
+ '@keyframes pighub-pop{0%{transform:scale(.15) rotate(-25deg);opacity:0}55%{transform:scale(1.22) rotate(8deg);opacity:1}100%{transform:scale(1) rotate(0)}}',
169
+ '.pighub-reveal.is-fly{transition:transform .64s cubic-bezier(.5,.05,.3,1),opacity .2s .5s}',
170
+ '.pighub-spark{position:fixed;left:0;top:0;width:9px;height:9px;border-radius:50%;z-index:59;pointer-events:none;',
171
+ 'background:radial-gradient(circle,var(--dsw-static-amber-100,#fff3c4) 0%,var(--dsw-static-amber-400,#ffd479) 60%,transparent 70%);',
172
+ 'animation:pighub-spark .72s ease-out both}',
173
+ '@keyframes pighub-spark{0%{transform:translate3d(var(--sx),var(--sy),0) scale(.4);opacity:0}25%{opacity:1}100%{transform:translate3d(var(--ex),var(--ey),0) scale(.15);opacity:0}}',
174
+ '.pighub-pet{position:absolute;width:72px;height:72px;pointer-events:auto;cursor:grab;',
175
+ 'transition:left 1.05s linear,top 1.05s linear;touch-action:none}',
176
+ '.pighub-pet img{display:block;width:100%;height:100%;object-fit:contain;user-select:none;',
177
+ '-webkit-user-drag:none;pointer-events:auto;filter:drop-shadow(0 3px 3px rgba(0,0,0,.3))}',
178
+ '.pighub-pet.is-idle img{animation:pighub-pet-breathe 2.6s ease-in-out infinite}',
179
+ '@keyframes pighub-pet-breathe{0%,100%{transform:scale(1)}50%{transform:scale(1.05)}}',
180
+ '.pighub-pet.is-drag{transition:none;cursor:grabbing}',
181
+ '.pighub-toast{position:fixed;left:50%;bottom:26px;transform:translateX(-50%);z-index:62;pointer-events:none;',
182
+ 'background:var(--dsw-alias-toast-bg,#202020);color:var(--dsw-alias-label-primary-foreground,#fff);',
183
+ 'border:1px solid var(--dsw-alias-border-l2,rgba(255,255,255,.16));',
184
+ 'padding:8px 14px;border-radius:999px;font-size:13px;box-shadow:0 6px 20px rgba(0,0,0,.24)}',
185
+ '@media (prefers-reduced-motion: reduce){.pighub-actor,.pighub-pet,.pighub-zz,.pighub-reveal img{animation:none !important;transition:none !important}}',
186
+ ].join('');
187
+
188
+ function injectCss() {
189
+ if (typeof document === 'undefined') return;
190
+ if (document.querySelector('style[data-plugin-css="' + CSS_TAG + '"]') !== null) return;
191
+ const tag = document.createElement('style');
192
+ tag.dataset.plugin = 'dsh-pighub';
193
+ tag.dataset.pluginCss = CSS_TAG;
194
+ tag.textContent = CSS;
195
+ document.head.appendChild(tag);
196
+ }
197
+
198
+ const REDUCED = typeof window !== 'undefined' && typeof window.matchMedia === 'function'
199
+ ? window.matchMedia('(prefers-reduced-motion: reduce)').matches
200
+ : false;
201
+
202
+ /* -------------------------------------------------- 侧边栏 icon:朝右的猪 */
203
+ /**
204
+ * 24x24 描边图标:椭圆身 + 右侧猪鼻 + 上耳 + 一只眼 + 两条腿 + 左侧卷尾。
205
+ * 用 currentColor 描边,因此跟随侧栏的选中/悬停配色,与其他入口同样粗细、同样尺寸
206
+ * (Memory Lab 的图标也是 props.size 默认 16,本图标对齐同一约定)。
207
+ */
208
+ function PigHubIcon(props) {
209
+ const size = typeof props?.size === 'number' ? props.size : 16;
210
+ return h('svg', {
211
+ width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor',
212
+ strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round',
213
+ 'aria-hidden': true, focusable: false, style: { display: 'block' },
214
+ },
215
+ h('ellipse', { cx: 11.5, cy: 12.6, rx: 7.6, ry: 5.2 }),
216
+ h('path', { d: 'M18.4 10.4 h1.9 a2 2 0 0 1 0 4 h-1.9' }),
217
+ h('path', { d: 'M8.6 8.1 L10.1 5.3 L12.2 8' }),
218
+ h('path', { d: 'M7.6 17.6 v2.2' }),
219
+ h('path', { d: 'M14.2 17.6 v2.2' }),
220
+ h('path', { d: 'M4.1 11.2 c-1.5 -.3 -1.9 -1.7 -.8 -2.3 c.8 -.4 1.4 .2 1.1 .9' }),
221
+ h('circle', { cx: 14.6, cy: 11.2, r: 0.75, fill: 'currentColor', stroke: 'none' }),
222
+ h('circle', { cx: 19.5, cy: 11.7, r: 0.42, fill: 'currentColor', stroke: 'none' }),
223
+ h('circle', { cx: 19.5, cy: 13.5, r: 0.42, fill: 'currentColor', stroke: 'none' }),
224
+ );
225
+ }
226
+
227
+ /* ------------------------------------------------ 像素标题:PigHub 字形表 */
228
+ /**
229
+ * 5x7 位图字模。每一行 5 个字符,'#' 点亮。
230
+ * 手写而非用字体:字体在任何机器上都渲染成矢量,「像素风」就没了;位图在任何
231
+ * DPI 下都是同一块方格,而且不需要下载字体文件(也就不会因此多一个网络依赖)。
232
+ */
233
+ const GLYPHS = {
234
+ P: ['####.', '#...#', '#...#', '####.', '#....', '#....', '#....'],
235
+ i: ['..#..', '.....', '.##..', '..#..', '..#..', '..#..', '.###.'],
236
+ g: ['.....', '.....', '.####', '#...#', '.####', '....#', '.###.'],
237
+ H: ['#...#', '#...#', '#...#', '#####', '#...#', '#...#', '#...#'],
238
+ u: ['.....', '.....', '#...#', '#...#', '#...#', '#...#', '.###.'],
239
+ b: ['#....', '#....', '####.', '#...#', '#...#', '#...#', '####.'],
240
+ };
241
+
242
+ /**
243
+ * 把 'PigHub' 画成 SVG 方块。字距 1 格,总共 6*5 + 5 = 35 格宽、7 格高。
244
+ * 阴影是一份偏移 0.55 格的同样方块,颜色更深——用图形叠出「硬阴影」,
245
+ * 而不是 text-shadow(那是给文字用的,对 SVG 方块无效)。
246
+ */
247
+ function PixelTitle() {
248
+ const word = 'PigHub';
249
+ const cells = [];
250
+ word.split('').forEach((ch, gi) => {
251
+ const glyph = GLYPHS[ch] || GLYPHS.unknown;
252
+ for (let r = 0; r < glyph.length; r += 1) {
253
+ for (let c = 0; c < glyph[r].length; c += 1) {
254
+ if (glyph[r][c] !== '#') continue;
255
+ cells.push([gi * 6 + c, r]);
256
+ }
257
+ }
258
+ });
259
+ const width = word.length * 6 - 1;
260
+ const rects = cells.map(([x, y], i) => h('rect', { key: 'c' + i, x, y, width: 1, height: 1 }));
261
+ const shadow = cells.map(([x, y], i) => h('rect', { key: 's' + i, x: x + 0.55, y: y + 0.55, width: 1, height: 1 }));
262
+ return h('span', { className: 'pighub-title', role: 'img', 'aria-label': 'PigHub' },
263
+ h('svg', { viewBox: '0 0 ' + width + ' 7', preserveAspectRatio: 'xMinYMin meet' },
264
+ h('g', { fill: 'rgba(120,40,20,.35)' }, shadow),
265
+ h('g', { fill: 'currentColor' }, rects),
266
+ ),
267
+ );
268
+ }
269
+
270
+ /* ---------------------------------------------------------------- 数据层 */
271
+ /*
272
+ * 一个 factory 级的单例 store:面板与桌宠层是两个槽位里的两个组件,但它们必须看到
273
+ * 同一份「我有哪些猪」,所以状态不放在任何一个组件里。订阅式而非 Context,是因为
274
+ * 桌宠层挂在 shell.overlay 上,与 main 里的面板不是同一棵子树,套 Provider 够不着。
275
+ */
276
+ const ROUTE = '/pighub';
277
+
278
+ function createStore() {
279
+ let state = { phase: 'idle', data: null, error: '', drag: null, penRect: null, toast: '' };
280
+ const listeners = new Set();
281
+ let toastTimer = null;
282
+ const get = () => state;
283
+ const emit = () => { for (const fn of listeners) { try { fn(); } catch { /* 单个订阅者出错不拖垮其他 */ } } };
284
+ const set = (patch) => {
285
+ state = Object.assign({}, state, typeof patch === 'function' ? patch(state) : patch);
286
+ emit();
287
+ };
288
+ const subscribe = (fn) => { listeners.add(fn); return () => listeners.delete(fn); };
289
+ const toast = (text) => {
290
+ set({ toast: text });
291
+ if (toastTimer) clearTimeout(toastTimer);
292
+ toastTimer = setTimeout(() => set({ toast: '' }), 2600);
293
+ };
294
+
295
+ async function request(body) {
296
+ const response = await fetch(ROUTE, {
297
+ method: 'POST',
298
+ headers: { 'content-type': 'application/json' },
299
+ body: JSON.stringify(body),
300
+ });
301
+ const text = await response.text();
302
+ let json;
303
+ try { json = JSON.parse(text); } catch { json = { ok: false, error: 'bad_response' }; }
304
+ if (!response.ok && !json.error) json.error = 'http_' + response.status;
305
+ return json;
306
+ }
307
+
308
+ function apply(payload) {
309
+ const ok = payload && payload.ok !== false;
310
+ set({
311
+ phase: ok ? 'ready' : 'error',
312
+ data: payload && payload.pigs ? payload : state.data,
313
+ error: ok ? '' : String((payload && (payload.error || (payload.catalog && payload.catalog.error))) || 'error'),
314
+ });
315
+ }
316
+
317
+ async function load() {
318
+ set({ phase: state.data ? state.phase : 'loading' });
319
+ try { apply(await request({ action: 'state' })); }
320
+ catch (error) { set({ phase: 'error', error: String((error && error.message) || error) }); }
321
+ }
322
+
323
+ async function draw() {
324
+ try {
325
+ const payload = await request({ action: 'draw' });
326
+ apply(payload);
327
+ if (payload.draw && payload.draw.ok) {
328
+ const pig = (payload.pigs || []).find((p) => p.id === payload.draw.pigId);
329
+ toast(payload.draw.upgraded
330
+ ? '重复的猪猪!' + (pig ? '「' + pig.title + '」' : '') + ' 升到 ' + payload.draw.stars + ' 星'
331
+ : '抽到新猪猪:' + (pig ? '「' + pig.title + '」' : ''));
332
+ } else if (payload.draw) {
333
+ toast(payload.draw.error === 'already_drawn' ? '今天已经抽过了,明天再来' : '抽不到:' + payload.draw.error);
334
+ }
335
+ return payload;
336
+ } catch (error) { set({ error: String((error && error.message) || error) }); return null; }
337
+ }
338
+
339
+ async function sort(next) {
340
+ try { apply(await request({ action: 'sort', sort: next })); }
341
+ catch (error) { set({ error: String((error && error.message) || error) }); }
342
+ }
343
+
344
+ async function setPet(pigId, pet) {
345
+ return place(pigId, pet ? 'pet' : 'pen');
346
+ }
347
+
348
+ /** 三态放置:猪圈 / 桌宠 / 库存(仓库)。库存的猪不再渲染,也就不再加载贴图。 */
349
+ async function place(pigId, to) {
350
+ try { apply(await request({ action: 'place', pigId, to })); }
351
+ catch (error) { set({ error: String((error && error.message) || error) }); }
352
+ }
353
+
354
+ async function updatePrefs(patch) {
355
+ try { apply(await request(Object.assign({ action: 'prefs' }, patch))); }
356
+ catch (error) { set({ error: String((error && error.message) || error) }); }
357
+ }
358
+
359
+ async function refreshCatalog() {
360
+ try {
361
+ set({ phase: state.data ? state.phase : 'loading' });
362
+ apply(await request({ action: 'refresh' }));
363
+ toast('素材已重新同步');
364
+ } catch (error) {
365
+ set({ error: String((error && error.message) || error) });
366
+ toast('同步失败:' + ((error && error.message) || error));
367
+ }
368
+ }
369
+
370
+ return {
371
+ get, set, subscribe, toast, load, draw, sort, setPet, place, updatePrefs, refreshCatalog,
372
+ beginDrag: (drag) => set({ drag }),
373
+ moveDrag: (x, y, drag) => set({ drag: Object.assign({}, drag, { x, y }) }),
374
+ endDrag: () => set({ drag: null }),
375
+ setPenRect: (rect) => set({ penRect: rect }),
376
+ };
377
+ }
378
+
379
+ const STORE = createStore();
380
+
381
+ /* ------------------------------------------------------- 素材:去白底透明 */
382
+ /*
383
+ * PigHub 的图多是**白底 JPG 梗图**。直接把白底贴在猪圈里,猪就像一张张卡片;
384
+ * 所以这里把「与边框连通的白」抠成透明,只留主体。
385
+ *
386
+ * 为什么必须在浏览器里做:Node 侧没有解码器(本项目零依赖),而浏览器本来就要解码;
387
+ * 为什么必须走自己的 /pighub/image 代理:上游图片**不带 CORS 头**,直接读像素会把
388
+ * canvas 标成 tainted,getImageData 直接抛错。同源代理后 canvas 是干净的。
389
+ *
390
+ * 抠图规则刻意选「从四边向内漫水填充」,而不是「全图去白」:梗图内部常有白色对话框,
391
+ * 全图去白会把它们也打穿。四边连通的白才是背景。
392
+ */
393
+ /**
394
+ * 素材是**包内文件**:这里只按猪 id 建索引,不做任何处理。
395
+ * 去白底、裁到猪身、描摹成 SVG 都在构建期完成(scripts/build-assets.mjs),
396
+ * 运行时不联网、不占用户算力。
397
+ */
398
+ function usePigImages(pigs) {
399
+ const map = {};
400
+ for (const pig of pigs) if (pig && pig.id) map[pig.id] = pig.assetUrl || pig.imageUrl || '';
401
+ return map;
402
+ }
403
+ /* --------------------------------------------------------------- 围栏 */
404
+ /*
405
+ * 卡通围栏:**有高度、有遮挡**。做法是 2.5D 那套最省事也最稳的办法——
406
+ * 把围栏拆成前后两层:远侧(上/左右)画在猪**后面**,近侧(下)画在猪**前面**,
407
+ * 于是走到底边附近的猪会被近侧栏杆挡住一截,「猪在圈里」这件事立刻有了纵深。
408
+ *
409
+ * 造型参考了常见的手绘卡通栅栏素材(粗圆头立柱 + 两道横杆 + 深色描边 + 地面投影),
410
+ * 但这里是自己用 SVG 画的:不引入第三方素材、不涉及授权,还能跟随主题色。
411
+ */
412
+ const FENCE_POSTS = 7;
413
+
414
+ function FenceBand({ side }) {
415
+ const tall = side === 'front' ? 15 : 11; // 近侧更高,强化纵深
416
+ const width = 100;
417
+ const height = tall + 6;
418
+ const postWidth = 4.6;
419
+ const gap = width / FENCE_POSTS;
420
+ const parts = [];
421
+ // 地面投影:柱子底下的一圈暗影
422
+ for (let index = 0; index < FENCE_POSTS; index += 1) {
423
+ const x = gap * index + (gap - postWidth) / 2;
424
+ parts.push(h('ellipse', { key: 'shadow' + index, cx: x + postWidth / 2, cy: height - 1.4, rx: postWidth * 0.95, ry: 1.6, fill: 'rgba(0,0,0,.22)' }));
425
+ }
426
+ // 横杆(两道):先画下面那道,再画上面那道,靠近观者的压在上面
427
+ const railY = side === 'front' ? [height - 11.5, height - 6.5] : [height - 10, height - 5];
428
+ parts.push(h('rect', { key: 'rail0', x: 0, y: railY[0], width, height: 3.2, rx: 1.6, className: 'pighub-fence-rail' }));
429
+ parts.push(h('rect', { key: 'rail1', x: 0, y: railY[1], width, height: 3.2, rx: 1.6, className: 'pighub-fence-rail' }));
430
+ // 立柱:圆头,底端落在投影上
431
+ for (let index = 0; index < FENCE_POSTS; index += 1) {
432
+ const x = gap * index + (gap - postWidth) / 2;
433
+ parts.push(h('rect', {
434
+ key: 'post' + index,
435
+ x,
436
+ y: height - tall,
437
+ width: postWidth,
438
+ height: tall,
439
+ rx: postWidth / 2.2,
440
+ className: 'pighub-fence-post',
441
+ }));
442
+ }
443
+ return h('svg', {
444
+ className: 'pighub-fence-band is-' + side,
445
+ viewBox: '0 0 ' + width + ' ' + height,
446
+ preserveAspectRatio: 'none',
447
+ 'aria-hidden': true,
448
+ style: side === 'front' ? { bottom: 0 } : undefined,
449
+ }, parts);
450
+ }
451
+
452
+ /* --------------------------------------------------------- 星级小胶囊 */
453
+ /**
454
+ * 星级显示三档(设置项,存在 prefs.starDisplay):
455
+ * off —— 完全不渲染;
456
+ * hover —— 鼠标划过那只猪显示,5 秒后自动消失;
457
+ * always —— 常驻在猪的上方。
458
+ * 组件只负责「这一帧亮不亮」,计时留给调用方(它知道谁被划过)。
459
+ */
460
+ function StarBadge(props) {
461
+ if (props.mode === 'off') return null;
462
+ const visible = props.mode === 'always' || props.visible === true;
463
+ return h('span', { className: 'pighub-starbadge' + (visible ? ' on' : ''), 'aria-hidden': visible ? 'false' : 'true' },
464
+ starText(props.stars));
465
+ }
466
+ /* --------------------------------------------------------------- 小工具 */
467
+ const STAR_MAX = 8;
468
+ function starText(stars) {
469
+ const n = Math.max(1, Math.floor(Number(stars) || 1));
470
+ if (n <= STAR_MAX) return new Array(n + 1).join('\u2605');
471
+ return new Array(STAR_MAX + 1).join('\u2605') + ' x' + n;
472
+ }
473
+ function shortTime(iso) {
474
+ if (!iso) return '—';
475
+ const at = new Date(iso);
476
+ if (Number.isNaN(at.getTime())) return '—';
477
+ const pad = (n) => String(n).padStart(2, '0');
478
+ return at.getFullYear() + '-' + pad(at.getMonth() + 1) + '-' + pad(at.getDate()) + ' ' + pad(at.getHours()) + ':' + pad(at.getMinutes());
479
+ }
480
+ function pigImage(pig, src) {
481
+ return h('img', {
482
+ src: src || pig.imageUrl,
483
+ alt: pig.title || ('猪猪 ' + pig.id),
484
+ draggable: false,
485
+ referrerPolicy: 'no-referrer',
486
+ loading: 'lazy',
487
+ decoding: 'async',
488
+ });
489
+ }
490
+
491
+ /* -------------------------------------------------- 猪圈内的行为(游走/发呆) */
492
+ /*
493
+ * 每 1.7 秒给每只猪掷一次骰子:约 28% 发呆,其余挑一个新落脚点。移动本身交给 CSS
494
+ * transition(1.1s),所以位移是平滑的、也不需要 rAF 逐帧改样式——面板开着的时候这是
495
+ * 一整页最省的东西。位置用百分比,猪圈缩放时不需要重算。
496
+ */
497
+ function usePenActors(pigs, disabled) {
498
+ const [actors, setActors] = useState({});
499
+ const signature = pigs.map((p) => p.id).join('|');
500
+ useEffect(() => {
501
+ let alive = true;
502
+ setActors((prev) => {
503
+ const next = {};
504
+ pigs.forEach((pig, index) => {
505
+ const old = prev[pig.id];
506
+ // 死猪:位置一旦定下就不再变,mode 固定为 static,CSS 也不给它任何动画。
507
+ if (pig.kind === 'dead') {
508
+ next[pig.id] = old || {
509
+ x: 20 + (index % 3) * 30,
510
+ y: 32 + Math.floor(index / 3) * 22,
511
+ mode: 'static',
512
+ };
513
+ if (old) next[pig.id] = Object.assign({}, old, { mode: 'static' });
514
+ return;
515
+ }
516
+ // 初始站位按 3 列网格铺开(而不是随机撒点):随机撒点会让头几只叠在一起,
517
+ // 看上去像一张图而不是一群猪。抖动只加在网格内,保证不越过围栏。
518
+ next[pig.id] = old || {
519
+ x: 20 + (index % 3) * 30 + (Math.random() * 8 - 4),
520
+ y: 32 + Math.floor(index / 3) * 22 + (Math.random() * 6 - 3),
521
+ mode: 'idle',
522
+ };
523
+ });
524
+ return next;
525
+ });
526
+ const timer = setInterval(() => {
527
+ if (!alive) return;
528
+ setActors((prev) => {
529
+ const next = Object.assign({}, prev);
530
+ for (const pig of pigs) {
531
+ const current = next[pig.id] || { x: 50, y: 46, mode: 'idle' };
532
+ if (pig.kind === 'dead' || disabled) { next[pig.id] = Object.assign({}, current, { mode: 'static' }); continue; }
533
+ if (Math.random() < 0.28) { next[pig.id] = Object.assign({}, current, { mode: 'idle' }); continue; }
534
+ next[pig.id] = { x: 14 + Math.random() * 70, y: 24 + Math.random() * 54, mode: 'walk' };
535
+ }
536
+ return next;
537
+ });
538
+ }, 1700);
539
+ return () => { alive = false; clearInterval(timer); };
540
+ }, [signature, disabled]);
541
+ return actors;
542
+ }
543
+
544
+ /* --------------------------------------------------------------- 猪圈面板 */
545
+ function PigHubPanel() {
546
+ const [state, setState] = useState(STORE.get());
547
+ useEffect(() => STORE.subscribe(() => setState(STORE.get())), []);
548
+ useEffect(() => { STORE.load(); }, []);
549
+
550
+ const penRef = useRef(null);
551
+ const houseRef = useRef(null);
552
+ /* 猪圈矩形要实时报给 store:桌宠有 30% 的落脚点在猪圈里,而它挂在另一个槽位,
553
+ * 自己量不到这个 DOM。窗口尺寸变化与面板滚动都会让矩形变,所以定时也在量。 */
554
+ useEffect(() => {
555
+ const measure = () => {
556
+ const el = penRef.current;
557
+ if (!el || typeof el.getBoundingClientRect !== 'function') return;
558
+ const rect = el.getBoundingClientRect();
559
+ STORE.setPenRect({ left: rect.left, top: rect.top, width: rect.width, height: rect.height });
560
+ };
561
+ measure();
562
+ window.addEventListener('resize', measure);
563
+ const timer = setInterval(measure, 2000);
564
+ return () => { window.removeEventListener('resize', measure); clearInterval(timer); };
565
+ }, []);
566
+
567
+ const data = state.data;
568
+ const pigs = (data && data.pigs) || [];
569
+ const pets = (data && data.pets) || [];
570
+ // 三态:pen 进场、pet 去桌面、store 进仓库(进仓库的不渲染,也就不加载贴图)
571
+ const penPigs = pigs.filter((pig) => (pig.place || (pets.indexOf(pig.id) >= 0 ? 'pet' : 'pen')) === 'pen');
572
+ const today = (data && data.today) || { drawn: false, date: '' };
573
+ const catalog = (data && data.catalog) || { count: 0, fetchedAt: '', error: '' };
574
+ const actors = usePenActors(penPigs, REDUCED);
575
+
576
+ // 素材:列表与人物的图都换成本地抠完白底的版本(同一份缓存,不重复处理)
577
+ const imageMap = usePigImages(pigs);
578
+
579
+ /*
580
+ * 抽取动画:**弹出 → 旋转 → 收进猪圈**。三条设计约束:
581
+ * 1. 起点是**按钮**(你按下的那个),不是屏幕中央 —— 动画要有因果感;
582
+ * 2. 落点取这只猪此刻**真实的 DOM 中心**(不是百分比推算,实测差 18px);
583
+ * 3. 动画期间真正的猪先隐藏,落定后再出现 —— 「看到它落在哪」与「它就在哪」是同一件事。
584
+ */
585
+ const [reveal, setReveal] = useState(null);
586
+ const drawButtonRef = useRef(null);
587
+ const REVEAL_SIZE = 132;
588
+ const REVEAL_LAND_SCALE = 0.56;
589
+ const POP_MS = 520;
590
+ const FLY_MS = 640;
591
+
592
+ const startReveal = (pigId) => {
593
+ const button = drawButtonRef.current;
594
+ const rect = button && typeof button.getBoundingClientRect === 'function' ? button.getBoundingClientRect() : null;
595
+ const from = rect && rect.width > 0
596
+ ? { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }
597
+ : { x: (typeof window !== 'undefined' ? window.innerWidth : 800) / 2, y: 120 };
598
+ const sparks = new Array(9).fill(0).map((_, index) => {
599
+ const angle = (Math.PI * 2 * index) / 9 + Math.random() * 0.4;
600
+ const distance = 70 + Math.random() * 60;
601
+ return {
602
+ id: index,
603
+ sx: from.x - 4, sy: from.y - 4,
604
+ ex: from.x - 4 + Math.cos(angle) * distance,
605
+ ey: from.y - 4 + Math.sin(angle) * distance,
606
+ };
607
+ });
608
+ // 先给原图(抠底结果可能还在路上),避免弹出瞬间是空框。
609
+ const store = STORE.get();
610
+ const drawn = store && store.data && Array.isArray(store.data.pigs)
611
+ ? store.data.pigs.filter((pig) => pig.id === pigId)[0]
612
+ : null;
613
+ setReveal({ id: pigId, from, phase: 'pop', target: null, sparks, imageUrl: drawn ? drawn.imageUrl : '' });
614
+
615
+ // 起飞前再算落点:这时新猪的落脚点已经分配好了。
616
+ setTimeout(() => {
617
+ const pen = STORE.get().penRect;
618
+ const safeId = String(pigId).replace(/[^a-zA-Z0-9_-]/g, '');
619
+ let target = null;
620
+ try {
621
+ const node = typeof document !== 'undefined'
622
+ ? document.querySelector('.pighub-actor[data-pig="' + safeId + '"]')
623
+ : null;
624
+ const box = node ? node.getBoundingClientRect() : null;
625
+ if (box && box.width > 0) target = { x: box.left + box.width / 2, y: box.top + box.height / 2 };
626
+ } catch { /* 量不到就用猪圈中心兜底 */ }
627
+ if (!target && pen && pen.width > 0) target = { x: pen.left + pen.width / 2, y: pen.top + pen.height / 2 };
628
+ setReveal((current) => (current && current.id === pigId ? Object.assign({}, current, { phase: 'fly', target }) : current));
629
+ }, POP_MS);
630
+
631
+ setTimeout(() => setReveal((current) => (current && current.id === pigId ? null : current)), POP_MS + FLY_MS + 140);
632
+ };
633
+ /* 活猪被点一下会「弹」一下:加一个 600ms 的 class,CSS 用 squash & stretch 播放。
634
+ * 用 class + 定时器而不是 Web Animations:动画结束撤掉 class 就完全复原,
635
+ * 元素上不会留下一段隐式动画状态。死猪不响应点击(它不动)。 */
636
+ const [squished, setSquished] = useState([]);
637
+ const squish = (id) => {
638
+ setSquished((list) => (list.indexOf(id) >= 0 ? list : list.concat(id)));
639
+ setTimeout(() => setSquished((list) => list.filter((item) => item !== id)), 600);
640
+ };
641
+ const starMode = (data && data.prefs && data.prefs.starDisplay) || 'hover';
642
+
643
+ /* 设置浮层。星级显示三档改的是 prefs,落盘在 Host 半,所以刷新/换机器后仍然生效。 */
644
+ const [settingsOpen, setSettingsOpen] = useState(false);
645
+ /*
646
+ * hover 档:划过就记一个「到期时间」,面板每 400ms 重渲染一次来让胶囊自己消失。
647
+ * 用「到期时间 + 轮询」而不是「每只猪一个 setTimeout」:猪的数量是运行期才知道的,
648
+ * 定时器数量不该随之增长;一次 400ms 的重渲染也就几毫秒。
649
+ */
650
+ const hoverRef = useRef({});
651
+ const [, setHoverTick] = useState(0);
652
+ useEffect(() => {
653
+ const timer = setInterval(() => setHoverTick((value) => value + 1), 400);
654
+ return () => clearInterval(timer);
655
+ }, []);
656
+ const markHover = (id) => { hoverRef.current[id] = Date.now() + 5000; setHoverTick((value) => value + 1); };
657
+ const isHoverLive = (id) => (hoverRef.current[id] || 0) > Date.now();
658
+
659
+ const onPenPointerDown = useCallback((event, pig) => {
660
+ if (event.button !== undefined && event.button !== 0) return;
661
+ if (typeof event.currentTarget.setPointerCapture === 'function') {
662
+ try { event.currentTarget.setPointerCapture(event.pointerId); } catch { /* 指针捕获不可用就退化为普通拖拽 */ }
663
+ }
664
+ STORE.beginDrag({ id: pig.id, imageUrl: pig.imageUrl, title: pig.title, startX: event.clientX, startY: event.clientY, x: event.clientX, y: event.clientY, active: false });
665
+ }, []);
666
+
667
+ const onPenPointerMove = useCallback((event, pig) => {
668
+ const drag = STORE.get().drag;
669
+ if (!drag || drag.id !== pig.id) return;
670
+ const dx = event.clientX - drag.startX;
671
+ const dy = event.clientY - drag.startY;
672
+ const active = drag.active || (dx * dx + dy * dy) > 25;
673
+ STORE.moveDrag(event.clientX, event.clientY, Object.assign({}, drag, { active }));
674
+ }, []);
675
+
676
+ const onPenPointerUp = useCallback((event, pig) => {
677
+ const drag = STORE.get().drag;
678
+ STORE.endDrag();
679
+ if (!drag || drag.id !== pig.id || !drag.active) return;
680
+ const rect = STORE.get().penRect;
681
+ // 落点优先级:仓库小屋 > 猪圈内(取消)> 圈外(变桌宠)
682
+ const house = houseRef.current && typeof houseRef.current.getBoundingClientRect === 'function'
683
+ ? houseRef.current.getBoundingClientRect()
684
+ : null;
685
+ const overHouse = house && house.width > 0
686
+ && event.clientX >= house.left && event.clientX <= house.right
687
+ && event.clientY >= house.top && event.clientY <= house.bottom;
688
+ if (overHouse) {
689
+ STORE.place(pig.id, 'store');
690
+ STORE.toast('「' + (pig.title || '猪猪') + '」收进仓库了');
691
+ return;
692
+ }
693
+ const inside = rect
694
+ && event.clientX >= rect.left && event.clientX <= rect.left + rect.width
695
+ && event.clientY >= rect.top && event.clientY <= rect.top + rect.height;
696
+ if (inside) return; // 拖回猪圈内 = 取消,不改变归属
697
+ STORE.place(pig.id, 'pet'); // 拖出来 = 原地变成桌宠
698
+ STORE.toast('「' + (pig.title || '猪猪') + '」出门遛弯了,双击可叫回猪圈');
699
+ }, []);
700
+
701
+ /* 设置按钮固定在**整个面板的右上角**(不是右栏的右上角):它是这个页面的设置,
702
+ * 与右栏内容滚动无关,所以用绝对定位挂在面板容器上。 */
703
+ const settings = h('div', { className: 'pighub-settings' },
704
+ h('button', {
705
+ type: 'button',
706
+ className: 'pighub-iconbtn',
707
+ title: 'PigHub 设置',
708
+ 'aria-label': 'PigHub 设置',
709
+ 'aria-expanded': settingsOpen ? 'true' : 'false',
710
+ onClick: () => setSettingsOpen((open) => !open),
711
+ },
712
+ h('svg', { width: 16, height: 16, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
713
+ h('circle', { cx: 12, cy: 12, r: 3 }),
714
+ h('path', { d: 'M19.4 15a1.7 1.7 0 0 0 .34 1.87l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.7 1.7 0 0 0-1.87-.34 1.7 1.7 0 0 0-1 1.56V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.56 1.7 1.7 0 0 0-1.87.34l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.7 1.7 0 0 0 4.6 15a1.7 1.7 0 0 0-1.56-1H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 8.9a1.7 1.7 0 0 0-.34-1.87l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.7 1.7 0 0 0 8.96 4.6H9a1.7 1.7 0 0 0 1-1.56V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.56 1.7 1.7 0 0 0 1.87-.34l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.7 1.7 0 0 0-.34 1.87V9a1.7 1.7 0 0 0 1.56 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z' }),
715
+ ),
716
+ ),
717
+ settingsOpen
718
+ ? h('div', { className: 'pighub-pop' },
719
+ h('h4', null, '星级显示'),
720
+ h('div', { className: 'pighub-seg' },
721
+ [['off', '关闭'], ['hover', '默认'], ['always', '常驻']].map(([mode, label]) =>
722
+ h('button', {
723
+ key: mode,
724
+ type: 'button',
725
+ 'aria-pressed': starMode === mode ? 'true' : 'false',
726
+ onClick: () => STORE.updatePrefs({ starDisplay: mode }),
727
+ }, label),
728
+ ),
729
+ ),
730
+ h('div', { className: 'row' }, h('span', null, '默认:划过猪猪显示 5 秒;常驻:一直显示在它上方')),
731
+ h('h4', null, '素材库(本版本冻结)'),
732
+ h('div', { className: 'row' },
733
+ h('span', null, (data && data.assets && data.assets.version ? data.assets.version : '—')
734
+ + ' · 共 ' + ((data && data.assets && data.assets.total) || 0) + ' 只'
735
+ + '(活 ' + ((data && data.assets && data.assets.live) || 0) + ' · 死 ' + ((data && data.assets && data.assets.dead) || 0) + ')'),
736
+ ),
737
+ h('h4', null, '数据目录'),
738
+ h('div', { className: 'pighub-path' }, (data && data.root) || ''),
739
+ )
740
+ : null,
741
+ );
742
+
743
+ /* 抽取动画层:固定定位,坐标即视口坐标(面板没有 transform 祖先)。 */
744
+ const landOffset = REVEAL_SIZE / 2; // scale/rotate 都绕中心,因此中心 = translate + 半个元素尺寸
745
+ const revealLayer = reveal
746
+ ? h('div', null,
747
+ reveal.phase === 'pop'
748
+ ? reveal.sparks.map((spark) => h('span', {
749
+ key: 'spark-' + spark.id,
750
+ className: 'pighub-spark',
751
+ style: {
752
+ '--sx': spark.sx + 'px', '--sy': spark.sy + 'px',
753
+ '--ex': spark.ex + 'px', '--ey': spark.ey + 'px',
754
+ },
755
+ }))
756
+ : null,
757
+ h('div', {
758
+ className: 'pighub-reveal ' + (reveal.phase === 'pop' ? 'is-pop' : 'is-fly'),
759
+ style: {
760
+ width: REVEAL_SIZE + 'px',
761
+ height: REVEAL_SIZE + 'px',
762
+ transform: reveal.phase === 'pop' || !reveal.target
763
+ ? 'translate3d(' + (reveal.from.x - landOffset) + 'px,' + (reveal.from.y - landOffset) + 'px,0)'
764
+ : 'translate3d(' + (reveal.target.x - landOffset) + 'px,' + (reveal.target.y - landOffset) + 'px,0) rotate(720deg) scale(' + REVEAL_LAND_SCALE + ')',
765
+ },
766
+ },
767
+ h('img', {
768
+ src: imageMap[reveal.id] || reveal.imageUrl || '',
769
+ alt: '',
770
+ draggable: false,
771
+ referrerPolicy: 'no-referrer',
772
+ }),
773
+ ),
774
+ )
775
+ : null;
776
+
777
+ return h('div', { className: 'pighub-panel' },
778
+ settings,
779
+ revealLayer,
780
+ h('div', { className: 'pighub-left' },
781
+ h('div', { className: 'pighub-pen', ref: penRef },
782
+ h('div', { className: 'pighub-ground' }),
783
+ // 远侧围栏 + 左右侧栏:画在猪的后面(z1)
784
+ h('div', { className: 'pighub-house', ref: houseRef, title: '把小猪拖进来收进仓库(不再加载)' },
785
+ h('svg', { viewBox: '0 0 40 34', 'aria-hidden': true },
786
+ h('rect', { x: 6, y: 14, width: 28, height: 18, rx: 2, className: 'pighub-house-wall' }),
787
+ h('path', { d: 'M3 15 L20 3 L37 15 Z', className: 'pighub-house-roof' }),
788
+ h('rect', { x: 17, y: 22, width: 7, height: 10, rx: 1, className: 'pighub-house-door' }),
789
+ h('rect', { x: 10, y: 18, width: 4, height: 4, rx: 1, className: 'pighub-house-window' }),
790
+ h('rect', { x: 26, y: 18, width: 4, height: 4, rx: 1, className: 'pighub-house-window' }),
791
+ ),
792
+ ),
793
+ h(FenceBand, { side: 'back' }),
794
+ h('div', { className: 'pighub-fence-side is-left', 'aria-hidden': true }),
795
+ h('div', { className: 'pighub-fence-side is-right', 'aria-hidden': true }),
796
+ penPigs.length === 0
797
+ ? h('div', { className: 'pighub-empty' }, state.phase === 'loading' ? '正在打开猪圈…' : '猪圈还是空的\n点右边的「今日猪猪」领一只')
798
+ : penPigs.map((pig) => {
799
+ const actor = actors[pig.id] || { x: 50, y: 46, mode: 'idle' };
800
+ const motionClass = actor.mode === 'static' ? 'is-static' : (actor.mode === 'walk' ? 'is-walk' : 'is-idle');
801
+ // 死猪不挂点击:它「只能由用户拖动」,点击这件事对它不存在。
802
+ const clickProps = pig.kind === 'dead' ? {} : { onClick: () => squish(pig.id) };
803
+ return h('div', {
804
+ key: pig.id,
805
+ 'data-pig': pig.id,
806
+ className: 'pighub-actor ' + motionClass
807
+ + (squished.indexOf(pig.id) >= 0 ? ' is-squish' : '')
808
+ + (reveal && reveal.id === pig.id ? ' is-hidden' : ''),
809
+ style: { left: actor.x + '%', top: actor.y + '%' },
810
+ onPointerEnter: () => markHover(pig.id),
811
+ },
812
+ h(StarBadge, { mode: starMode, stars: pig.stars, visible: isHoverLive(pig.id) }),
813
+ h('img', {
814
+ src: imageMap[pig.id] || pig.imageUrl,
815
+ alt: pig.title || ('猪猪 ' + pig.id),
816
+ draggable: false,
817
+ referrerPolicy: 'no-referrer',
818
+ onPointerDown: (event) => onPenPointerDown(event, pig),
819
+ onPointerMove: (event) => onPenPointerMove(event, pig),
820
+ onPointerUp: (event) => onPenPointerUp(event, pig),
821
+ onPointerCancel: () => STORE.endDrag(),
822
+ ...clickProps,
823
+ title: (pig.title || '猪猪') + ' · ' + (pig.kind === 'dead' ? '死猪(静止)' : '活猪(会动)')
824
+ + ' · ' + starText(pig.stars) + ' · 按住拖出猪圈可当桌宠',
825
+ }),
826
+ );
827
+ }),
828
+ // 近侧围栏:最后画 → 压在猪身上,走到底边的猪被挡住一截,这就是「高度」。
829
+ h(FenceBand, { side: 'front' }),
830
+ ),
831
+ ),
832
+ h('div', { className: 'pighub-right' },
833
+ h('div', { className: 'pighub-head' },
834
+ h(PixelTitle, null),
835
+ h('button', {
836
+ type: 'button',
837
+ className: 'pighub-draw',
838
+ ref: drawButtonRef,
839
+ disabled: today.drawn || state.phase === 'loading',
840
+ onClick: async () => {
841
+ const payload = await STORE.draw();
842
+ if (payload && payload.draw && payload.draw.ok) startReveal(payload.draw.pigId);
843
+ },
844
+ title: today.drawn ? '每天只能抽一次,明天再来' : '从 PigHub 的猪猪里随机抽一只',
845
+ }, today.drawn ? '今日已获取' : '今日猪猪'),
846
+ h('div', { className: 'pighub-meta' },
847
+ (catalog.count || 0) + ' 只猪猪可选 · 已收集 ' + pigs.length + ' 只 · 抽过 ' + ((data && data.draws) || 0) + ' 次'
848
+ + ' · 猪圈 ' + penPigs.length + ' 只 · 桌宠 ' + pets.length + ' 只'
849
+ + (catalog.error ? ' · 目录暂用缓存(' + catalog.error + ')' : ''),
850
+ ),
851
+ ),
852
+ h('div', { className: 'pighub-sorts' },
853
+ [['time', '按获取时间'], ['stars', '按星级'], ['rarity', '按稀有度']].map(([key, label]) =>
854
+ h('button', {
855
+ key,
856
+ type: 'button',
857
+ className: 'pighub-sort',
858
+ 'aria-pressed': ((data && data.sort) || 'time') === key ? 'true' : 'false',
859
+ onClick: () => STORE.sort(key),
860
+ }, label),
861
+ ),
862
+ ),
863
+ h('div', { className: 'pighub-list' },
864
+ pigs.length === 0
865
+ ? h('div', { className: 'pighub-meta' }, '还没有猪猪。今日猪猪每天一次,慢慢喂。')
866
+ : pigs.map((pig) => h('div', { className: 'pighub-row', key: pig.id },
867
+ pigImage(pig, imageMap[pig.id]),
868
+ h('div', { className: 'pighub-row-main' },
869
+ h('div', { className: 'pighub-row-title' }, pig.title || ('猪猪 ' + pig.id)),
870
+ h('div', { className: 'pighub-row-sub' },
871
+ '首次获得 ' + shortTime(pig.firstObtainedAt) + ' · 最近升星 ' + shortTime(pig.lastUpgradedAt),
872
+ ),
873
+ ),
874
+ h('span', { className: 'pighub-tag', title: pig.kind === 'dead' ? '死猪:完全静止,只能拖动' : '活猪:会游走,点击会弹一下' }, pig.kind === 'dead' ? '死猪' : '活猪'),
875
+ pets.indexOf(pig.id) >= 0 ? h('span', { className: 'pighub-tag', title: '这只猪在猪圈外,正作为桌宠待着' }, '桌宠') : null,
876
+ h('span', { className: 'pighub-tag' }, pig.rarityLabel || pig.rarity),
877
+ h('span', { className: 'pighub-stars', title: pig.stars + ' 星' }, starText(pig.stars)),
878
+ )),
879
+ ),
880
+ ),
881
+ );
882
+ }
883
+
884
+ /* --------------------------------------------------------------- 桌宠层 */
885
+ /*
886
+ * 挂在 shell.overlay 上而不是面板里:面板关掉、切到别的入口,桌宠也该还在桌面上。
887
+ * 容器 pointer-events: none,只有猪本体接收指针——这样它既能在整页游走,又不会挡住
888
+ * 下面任何按钮;与生态里其他桌宠插件(如 dsh-pet,根 z-index 40)各自成层,互不遮挡。
889
+ */
890
+ function PigHubPetLayer() {
891
+ const [state, setState] = useState(STORE.get());
892
+ useEffect(() => STORE.subscribe(() => setState(STORE.get())), []);
893
+ useEffect(() => { if (!STORE.get().data) STORE.load(); }, []);
894
+ const [positions, setPositions] = useState({});
895
+ const [dragId, setDragId] = useState('');
896
+ const offsetRef = useRef({ x: 0, y: 0 });
897
+
898
+ const data = state.data;
899
+ const pigs = (data && data.pigs) || [];
900
+ const petIds = (data && data.pets) || [];
901
+ const byId = {};
902
+ for (const pig of pigs) byId[pig.id] = pig;
903
+ const signature = petIds.join('|');
904
+ // 死猪作为桌宠也不动:把 kind 也纳入重算条件,否则换版本后旧签名不会触发重新计时。
905
+ const kindsSignature = petIds.map((id) => (byId[id] ? byId[id].kind : '') || '').join('|');
906
+
907
+ /* 每 2.2 秒重新挑落脚点:74% 移动、26% 发呆。约三成的落脚点在猪圈矩形内,
908
+ * 于是「在桌面游走」与「回猪圈里转」是同一套行为,不是两套代码。 */
909
+ useEffect(() => {
910
+ const timer = setInterval(() => {
911
+ const vw = (typeof window !== 'undefined' && window.innerWidth) || 1200;
912
+ const vh = (typeof window !== 'undefined' && window.innerHeight) || 800;
913
+ const pen = STORE.get().penRect;
914
+ setPositions((prev) => {
915
+ const next = Object.assign({}, prev);
916
+ petIds.forEach((id, index) => {
917
+ const current = next[id] || { x: vw * 0.68 + index * 22, y: vh * 0.66 - index * 26 };
918
+ const petPig = byId[id];
919
+ // 死猪:作为桌宠也只待在原地,只有用户拖动才会移动。
920
+ if (petPig && petPig.kind === 'dead') { next[id] = current; return; }
921
+ if (dragId === id || REDUCED || Math.random() < 0.26) { next[id] = current; return; }
922
+ if (pen && pen.width > 0 && Math.random() < 0.3) {
923
+ next[id] = {
924
+ x: pen.left + pen.width * (0.18 + Math.random() * 0.64),
925
+ y: pen.top + pen.height * (0.22 + Math.random() * 0.56),
926
+ };
927
+ return;
928
+ }
929
+ next[id] = {
930
+ x: 50 + Math.random() * Math.max(60, vw - 130),
931
+ y: 70 + Math.random() * Math.max(60, vh - 170),
932
+ };
933
+ });
934
+ for (const id of Object.keys(next)) if (petIds.indexOf(id) === -1) delete next[id];
935
+ return next;
936
+ });
937
+ }, 2200);
938
+ return () => clearInterval(timer);
939
+ }, [signature, kindsSignature, dragId]);
940
+
941
+ const dragging = state.drag && state.drag.active ? state.drag : null;
942
+
943
+ // 桌宠的图也走同一套去白底缓存;星级胶囊与面板里共用同一套三档设置。
944
+ const petPigs = pigs.filter((pig) => petIds.indexOf(pig.id) >= 0);
945
+ const imageMap = usePigImages(petPigs);
946
+ const starMode = (data && data.prefs && data.prefs.starDisplay) || 'hover';
947
+ const hoverRef = useRef({});
948
+ const [, setHoverTick] = useState(0);
949
+ useEffect(() => {
950
+ const timer = setInterval(() => setHoverTick((value) => value + 1), 400);
951
+ return () => clearInterval(timer);
952
+ }, []);
953
+ const markHover = (id) => { hoverRef.current[id] = Date.now() + 5000; setHoverTick((value) => value + 1); };
954
+ const isHoverLive = (id) => (hoverRef.current[id] || 0) > Date.now();
955
+
956
+ // 空态要放在**所有 hook 之后**才返回:在 hook 之前分叉会让两次渲染的 hook 数量不同,
957
+ // 真实 React 会直接抛「Rendered fewer hooks than expected」。这条是测试把它抓出来的。
958
+ if (petIds.length === 0 && !dragging && !state.toast) return null;
959
+
960
+ return h('div', { className: 'pighub-pets' },
961
+ petIds.map((id) => {
962
+ const pig = byId[id];
963
+ if (!pig) return null;
964
+ // 首帧还没有摆过位置:落在右下角附近,而不是页面原点(否则会贴到左上角)。
965
+ const viewportWidth = (typeof window !== 'undefined' && window.innerWidth) || 1280;
966
+ const viewportHeight = (typeof window !== 'undefined' && window.innerHeight) || 800;
967
+ const pos = positions[id] || { x: viewportWidth * 0.74, y: viewportHeight * 0.72 };
968
+ const isDragging = dragId === id;
969
+ return h('div', {
970
+ key: id,
971
+ className: 'pighub-pet' + (isDragging ? ' is-drag' : '') + (REDUCED || isDragging || pig.kind === 'dead' ? '' : ' is-idle'),
972
+ style: { left: pos.x + 'px', top: pos.y + 'px', transform: 'translate(-50%,-50%)' },
973
+ title: (pig.title || '猪猪') + ' · 拖动可移动,双击回猪圈',
974
+ onPointerEnter: () => markHover(id),
975
+ onPointerDown: (event) => {
976
+ if (event.button !== undefined && event.button !== 0) return;
977
+ if (typeof event.currentTarget.setPointerCapture === 'function') {
978
+ try { event.currentTarget.setPointerCapture(event.pointerId); } catch { /* 退化为普通拖拽 */ }
979
+ }
980
+ offsetRef.current = { x: event.clientX - pos.x, y: event.clientY - pos.y };
981
+ setDragId(id);
982
+ },
983
+ onPointerMove: (event) => {
984
+ if (dragId !== id) return;
985
+ const next = { x: event.clientX - offsetRef.current.x, y: event.clientY - offsetRef.current.y };
986
+ setPositions((prev) => Object.assign({}, prev, { [id]: next }));
987
+ },
988
+ onPointerUp: () => setDragId(''),
989
+ onPointerCancel: () => setDragId(''),
990
+ onDoubleClick: () => { STORE.setPet(id, false); STORE.toast('「' + (pig.title || '猪猪') + '」回到猪圈'); },
991
+ },
992
+ h(StarBadge, { mode: starMode, stars: pig.stars, visible: isHoverLive(id) }),
993
+ h('img', {
994
+ src: imageMap[id] || pig.imageUrl,
995
+ alt: pig.title || ('猪猪 ' + id),
996
+ draggable: false,
997
+ referrerPolicy: 'no-referrer',
998
+ }),
999
+ );
1000
+ }),
1001
+ dragging
1002
+ ? h('div', {
1003
+ className: 'pighub-pet is-drag',
1004
+ style: { left: dragging.x + 'px', top: dragging.y + 'px', transform: 'translate(-50%,-50%)', pointerEvents: 'none' },
1005
+ },
1006
+ h('img', { src: dragging.imageUrl, alt: dragging.title || '猪猪', draggable: false, referrerPolicy: 'no-referrer' }),
1007
+ )
1008
+ : null,
1009
+ state.toast ? h('div', { className: 'pighub-toast' }, state.toast) : null,
1010
+ );
1011
+ }
1012
+ /* ---------------------------------------------------------------- 注册 */
1013
+ /*
1014
+ * 三个槽位三种用途,都是**增量贡献**:
1015
+ * sidebar.panellist —— list,必须给 id;order 22 排在 Memory Lab(20)/NewMate(21) 之后
1016
+ * main —— keyed,key 与 sidebar 的 id 相同,布局据此派发面板
1017
+ * shell.overlay —— list,页面级浮层,桌宠的家
1018
+ * 每个注册都包在 ctx.effect 里,卸载/热重载时自动撤销(否则槽位会留下悬挂贡献)。
1019
+ */
1020
+ return {
1021
+ name: 'dsh-pighub',
1022
+ inject: ['slots'],
1023
+ apply(ctx) {
1024
+ injectCss();
1025
+
1026
+ ctx.effect(
1027
+ () => ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
1028
+ name: 'sidebar.panellist',
1029
+ id: 'pighub',
1030
+ order: 22,
1031
+ label: () => 'PigHub',
1032
+ }, PigHubIcon)),
1033
+ 'pighub-sidebar-entry',
1034
+ );
1035
+
1036
+ ctx.effect(
1037
+ () => ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: 'pighub' }, PigHubPanel)),
1038
+ 'pighub-main-panel',
1039
+ );
1040
+
1041
+ ctx.effect(
1042
+ () => ctx.slots.inject('shell.overlay', () => ctx.slots.register({
1043
+ name: 'shell.overlay',
1044
+ id: 'pighub-pets',
1045
+ order: 30,
1046
+ }, PigHubPetLayer)),
1047
+ 'pighub-pet-layer',
1048
+ );
1049
+ },
1050
+ };
1051
+ },
1052
+ });