@istmx/ui 0.1.2 → 0.1.6

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.
@@ -0,0 +1,1020 @@
1
+ 'use client'
2
+
3
+ import {
4
+ AnimatePresence,
5
+ animate,
6
+ motion,
7
+ useMotionValue,
8
+ useReducedMotion,
9
+ } from 'motion/react'
10
+ import {
11
+ useCallback,
12
+ useEffect,
13
+ useId,
14
+ useRef,
15
+ useState,
16
+ type CSSProperties,
17
+ } from 'react'
18
+ import { cn } from '@/lib/utils'
19
+
20
+ // -----------------------------------------------------------------------------
21
+ // Pixel Art Engine (Parametric 32x32 Cat Model)
22
+ // -----------------------------------------------------------------------------
23
+
24
+ export const CAT_SIZE = 32
25
+ export const CAT_FEET_Y = 27
26
+
27
+ export type PixelCatBreed =
28
+ 'white' | 'orange' | 'black' | 'calico' | 'gray' | 'theme'
29
+
30
+ export type PixelCatPose =
31
+ 'idle' | 'walk' | 'sit' | 'sleep' | 'alert' | 'happy' | 'stretch' | 'groom'
32
+
33
+ type Eyes = 'open' | 'blink' | 'happy' | 'closed' | 'wide'
34
+ type Mouth = 'smile' | 'open'
35
+ type TailKind = 'low' | 'mid' | 'up'
36
+ type Body = 'stand' | 'sit' | 'loaf' | 'stretch' | 'scratch'
37
+
38
+ interface CatFrame {
39
+ body?: Body
40
+ bob?: number
41
+ headDX?: number
42
+ headDY?: number
43
+ eyes?: Eyes
44
+ mouth?: Mouth
45
+ tallEars?: boolean
46
+ tail?: TailKind
47
+ sway?: number
48
+ legs?: 0 | 1 | 2 | 3 | 'jump'
49
+ breath?: number
50
+ pawLick?: boolean
51
+ }
52
+
53
+ export const CAT_PALETTES: Record<
54
+ PixelCatBreed,
55
+ Record<1 | 2 | 3 | 4, string>
56
+ > = {
57
+ white: {
58
+ 1: '#f5f5f5',
59
+ 2: '#cccccc',
60
+ 3: '#18181b',
61
+ 4: '#27272a',
62
+ },
63
+ orange: {
64
+ 1: '#f59e0b',
65
+ 2: '#d97706',
66
+ 3: '#451a03',
67
+ 4: '#78350f',
68
+ },
69
+ black: {
70
+ 1: '#262626',
71
+ 2: '#3f3f46',
72
+ 3: '#facc15', // Golden glowing eyes
73
+ 4: '#09090b',
74
+ },
75
+ calico: {
76
+ 1: '#fef3c7',
77
+ 2: '#ea580c',
78
+ 3: '#18181b',
79
+ 4: '#27272a',
80
+ },
81
+ gray: {
82
+ 1: '#94a3b8',
83
+ 2: '#64748b',
84
+ 3: '#0f172a',
85
+ 4: '#1e293b',
86
+ },
87
+ theme: {
88
+ 1: '#e4e4e7',
89
+ 2: '#a1a1aa',
90
+ 3: '#18181b',
91
+ 4: '#27272a',
92
+ },
93
+ }
94
+
95
+ class Grid {
96
+ data = new Uint8Array(CAT_SIZE * CAT_SIZE)
97
+ px(x: number, y: number, v: number) {
98
+ if (x < 0 || y < 0 || x >= CAT_SIZE || y >= CAT_SIZE) return
99
+ this.data[y * CAT_SIZE + x] = v
100
+ }
101
+ rect(x: number, y: number, w: number, h: number, v: number) {
102
+ for (let j = 0; j < h; j++) {
103
+ for (let i = 0; i < w; i++) this.px(x + i, y + j, v)
104
+ }
105
+ }
106
+ round(x: number, y: number, w: number, h: number, v: number, r = 1) {
107
+ for (let j = 0; j < h; j++) {
108
+ for (let i = 0; i < w; i++) {
109
+ const cx = Math.min(i, w - 1 - i)
110
+ const cy = Math.min(j, h - 1 - j)
111
+ if (cx + cy < r) continue
112
+ this.px(x + i, y + j, v)
113
+ }
114
+ }
115
+ }
116
+ outline() {
117
+ const src = this.data.slice()
118
+ for (let y = 0; y < CAT_SIZE; y++) {
119
+ for (let x = 0; x < CAT_SIZE; x++) {
120
+ if (src[y * CAT_SIZE + x]) continue
121
+ const n =
122
+ (x > 0 && src[y * CAT_SIZE + x - 1]) ||
123
+ (x < CAT_SIZE - 1 && src[y * CAT_SIZE + x + 1]) ||
124
+ (y > 0 && src[(y - 1) * CAT_SIZE + x]) ||
125
+ (y < CAT_SIZE - 1 && src[(y + 1) * CAT_SIZE + x])
126
+ if (n) this.data[y * CAT_SIZE + x] = 4
127
+ }
128
+ }
129
+ }
130
+ }
131
+
132
+ const TAILS: Record<TailKind, [number, number][]> = {
133
+ low: [
134
+ [4, 15],
135
+ [3, 16],
136
+ [2, 17],
137
+ [1, 18],
138
+ [1, 20],
139
+ ],
140
+ mid: [
141
+ [4, 14],
142
+ [3, 13],
143
+ [2, 12],
144
+ [1, 11],
145
+ [1, 9],
146
+ ],
147
+ up: [
148
+ [4, 14],
149
+ [3, 12],
150
+ [3, 10],
151
+ [2, 8],
152
+ [3, 6],
153
+ ],
154
+ }
155
+
156
+ function drawTail(g: Grid, kind: TailKind, sway: number, dy: number) {
157
+ TAILS[kind].forEach(([x, y], i) => {
158
+ const dx = i >= 4 ? sway * 2 : i >= 2 ? sway : 0
159
+ g.rect(x + dx, y + dy, 2, 2, 1)
160
+ })
161
+ }
162
+
163
+ function drawHead(g: Grid, hx: number, hy: number, f: CatFrame) {
164
+ const tall = f.tallEars ? 1 : 0
165
+ for (let row = 0; row < 4 + tall; row++) {
166
+ const y = hy - 4 - tall + row
167
+ const w = row - tall + 1 > 0 ? row - tall + 1 : 1
168
+ g.rect(hx + 1, y, w, 1, 1)
169
+ g.rect(hx + 12 - w, y, w, 1, 1)
170
+ }
171
+ g.px(hx + 2, hy - 2, 2)
172
+ g.px(hx + 10, hy - 2, 2)
173
+
174
+ g.round(hx, hy, 13, 10, 1, 2)
175
+ g.px(hx - 1, hy + 5, 1)
176
+ g.px(hx + 13, hy + 5, 1)
177
+
178
+ const eye = (cx: number, mirror: boolean) => {
179
+ const e = f.eyes ?? 'open'
180
+ if (e === 'open') {
181
+ const glintX = mirror ? cx : cx - 1
182
+ g.rect(glintX, hy + 3, 2, 2, 3)
183
+ g.px(glintX, hy + 3, 1)
184
+ } else if (e === 'blink' || e === 'closed') {
185
+ g.rect(mirror ? cx - 1 : cx - 1, hy + 4, 3, 1, 3)
186
+ } else if (e === 'wide') {
187
+ const glintX = mirror ? cx - 1 : cx - 1
188
+ g.rect(glintX, hy + 2, 3, 3, 3)
189
+ g.px(glintX, hy + 2, 1)
190
+ } else if (e === 'happy') {
191
+ g.px(cx - 1, hy + 4, 3)
192
+ g.px(cx, hy + 3, 3)
193
+ g.px(cx + 1, hy + 4, 3)
194
+ }
195
+ }
196
+ eye(hx + 3, false)
197
+ eye(hx + 9, true)
198
+
199
+ g.rect(hx + 5, hy + 5, 2, 1, 3)
200
+
201
+ if (f.mouth === 'open') {
202
+ g.rect(hx + 5, hy + 6, 2, 2, 3)
203
+ g.px(hx + 5, hy + 7, 2)
204
+ } else {
205
+ g.px(hx + 5, hy + 6, 3)
206
+ g.px(hx + 6, hy + 6, 3)
207
+ g.px(hx + 4, hy + 5, 3)
208
+ g.px(hx + 7, hy + 5, 3)
209
+ }
210
+
211
+ g.px(hx - 2, hy + 5, 2)
212
+ g.px(hx - 2, hy + 7, 2)
213
+ g.px(hx + 14, hy + 5, 2)
214
+ g.px(hx + 14, hy + 7, 2)
215
+ }
216
+
217
+ function drawLeg(g: Grid, x: number, y0: number, len: number, v: number) {
218
+ g.rect(x, y0, 2, len, v)
219
+ }
220
+
221
+ function buildCatGrid(f: CatFrame): Uint8Array {
222
+ const g = new Grid()
223
+ const body = f.body ?? 'stand'
224
+ const bob = f.bob ?? 0
225
+
226
+ if (body === 'stand') {
227
+ const legs = f.legs
228
+ const spec: [number, number, 'A' | 'B'][] = [
229
+ [5, 1, 'A'],
230
+ [8, 2, 'B'],
231
+ [14, 2, 'A'],
232
+ [17, 1, 'B'],
233
+ ]
234
+ drawTail(g, f.tail ?? 'low', f.sway ?? 0, bob)
235
+ spec.forEach(([x, v, pair]) => {
236
+ let dx = 0
237
+ let lift = 0
238
+ if (legs === 'jump') {
239
+ dx = x < 12 ? -2 : 2
240
+ lift = 0
241
+ } else if (legs !== undefined) {
242
+ const A = pair === 'A'
243
+ if (legs === 0) dx = A ? 1 : -1
244
+ if (legs === 1) lift = A ? 1 : 0
245
+ if (legs === 2) dx = A ? -1 : 1
246
+ if (legs === 3) lift = A ? 0 : 1
247
+ }
248
+ const top = 22 + bob
249
+ const len = 5 - lift - (legs === 'jump' ? 1 : 0)
250
+ drawLeg(g, x + dx, top, Math.max(1, len), v)
251
+ })
252
+
253
+ g.round(4, 12 + bob, 17, 10, 1, 2)
254
+ g.rect(6, 22 + bob, 13, 1, 1)
255
+ g.rect(8, 23 + bob, 9, 1, 2)
256
+ g.rect(7, 14 + bob, 3, 1, 2)
257
+ g.rect(11, 14 + bob, 2, 1, 2)
258
+
259
+ drawHead(g, 17 + (f.headDX ?? 0), 8 + (f.headDY ?? 0) + bob, f)
260
+ } else if (body === 'sit') {
261
+ for (let x = 2; x <= 22; x++) g.rect(x, 26, 1, 2, 1)
262
+ g.rect(1, 24, 2, 3, 1)
263
+ g.rect(23, 25, 2, 2, 1)
264
+ g.rect(24, 23, 2, 3, 1)
265
+ const sway = f.sway ?? 0
266
+ if (sway) g.px(25, 22, 1)
267
+
268
+ g.round(4, 14, 13, 12, 1, 3)
269
+ g.round(13, 10, 10, 16, 1, 2)
270
+ g.rect(18, 22, 3, 4, 2)
271
+ g.rect(13, 24, 3, 2, 2)
272
+
273
+ if (f.pawLick) {
274
+ g.rect(18, 15, 3, 3, 1)
275
+ g.px(19, 14, 3)
276
+ }
277
+
278
+ drawHead(g, 15 + (f.headDX ?? 0), 4 + (f.headDY ?? 0), f)
279
+ } else if (body === 'loaf') {
280
+ const b = f.breath ?? 0
281
+ g.rect(2, 22, 2, 4, 1)
282
+ g.round(3, 15 - b, 24, 12 + b, 1, 4)
283
+ g.rect(5, 25, 18, 1, 2)
284
+ g.rect(24, 23, 2, 3, 1)
285
+ drawHead(g, 17, 14 - b, { ...f, eyes: 'closed' })
286
+ } else if (body === 'stretch') {
287
+ drawTail(g, 'up', 1, -2)
288
+ drawLeg(g, 5, 18, 9, 1)
289
+ drawLeg(g, 8, 18, 9, 2)
290
+ g.round(5, 10, 15, 8, 1, 2)
291
+ g.round(13, 15, 10, 8, 1, 2)
292
+ g.rect(18, 24, 8, 2, 1)
293
+ g.rect(20, 25, 6, 2, 2)
294
+ drawHead(g, 19, 13, { ...f, eyes: 'closed' })
295
+ }
296
+
297
+ g.outline()
298
+ return g.data
299
+ }
300
+
301
+ const IDLE_TAIL = [0, 1, 0, -1]
302
+ const idleFrames: CatFrame[] = Array.from({ length: 12 }, (_, i) => ({
303
+ tail: 'up',
304
+ sway: IDLE_TAIL[i % 4],
305
+ eyes: i === 9 ? 'blink' : 'open',
306
+ }))
307
+
308
+ const ANIMATIONS: Record<PixelCatPose, { fps: number; frames: CatFrame[] }> = {
309
+ idle: { fps: 4, frames: idleFrames },
310
+ walk: {
311
+ fps: 8,
312
+ frames: [0, 1, 2, 3].map((p) => ({
313
+ legs: p as 0 | 1 | 2 | 3,
314
+ tail: 'up',
315
+ sway: p % 2 === 0 ? 1 : -1,
316
+ bob: p % 2 === 1 ? -1 : 0,
317
+ })),
318
+ },
319
+ sit: {
320
+ fps: 2,
321
+ frames: [
322
+ { body: 'sit' },
323
+ { body: 'sit', sway: 1 },
324
+ { body: 'sit' },
325
+ { body: 'sit', eyes: 'blink' },
326
+ ],
327
+ },
328
+ sleep: {
329
+ fps: 1,
330
+ frames: [
331
+ { body: 'loaf', breath: 0 },
332
+ { body: 'loaf', breath: 1 },
333
+ ],
334
+ },
335
+ alert: {
336
+ fps: 3,
337
+ frames: [
338
+ { eyes: 'wide', tallEars: true, tail: 'up', sway: 0 },
339
+ { eyes: 'wide', tallEars: true, tail: 'up', sway: 1 },
340
+ ],
341
+ },
342
+ happy: {
343
+ fps: 8,
344
+ frames: [0, -3, 0, -3].map((b, i) => ({
345
+ bob: b,
346
+ eyes: 'happy' as const,
347
+ tail: 'up' as const,
348
+ sway: i % 2 ? 1 : -1,
349
+ legs: b < 0 ? ('jump' as const) : undefined,
350
+ })),
351
+ },
352
+ stretch: {
353
+ fps: 2,
354
+ frames: [{ body: 'stretch' }, { body: 'stretch' }],
355
+ },
356
+ groom: {
357
+ fps: 3,
358
+ frames: [
359
+ { body: 'sit', pawLick: true, headDX: 1, headDY: 2, eyes: 'closed' },
360
+ { body: 'sit', pawLick: true, headDX: 1, headDY: 3, eyes: 'closed' },
361
+ { body: 'sit', pawLick: false, headDX: 0, headDY: 1, eyes: 'happy' },
362
+ ],
363
+ },
364
+ }
365
+
366
+ const canvasCache = new Map<string, HTMLCanvasElement>()
367
+
368
+ function hexToRgb(hex: string): [number, number, number] {
369
+ if (hex.startsWith('#')) {
370
+ const raw = hex.slice(1)
371
+ const n = parseInt(
372
+ raw.length === 3
373
+ ? raw
374
+ .split('')
375
+ .map((c) => c + c)
376
+ .join('')
377
+ : raw,
378
+ 16,
379
+ )
380
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
381
+ }
382
+ return [240, 240, 240]
383
+ }
384
+
385
+ function getCatFrameCanvas(
386
+ pose: PixelCatPose,
387
+ index: number,
388
+ palette: Record<1 | 2 | 3 | 4, string>,
389
+ ): HTMLCanvasElement | null {
390
+ if (typeof document === 'undefined') return null
391
+ const frames = ANIMATIONS[pose].frames
392
+ const i = ((index % frames.length) + frames.length) % frames.length
393
+ const palKey = `${palette[1]}_${palette[2]}_${palette[3]}_${palette[4]}`
394
+ const key = `${pose}:${i}:${palKey}`
395
+ const hit = canvasCache.get(key)
396
+ if (hit) return hit
397
+
398
+ const canvas = document.createElement('canvas')
399
+ canvas.width = CAT_SIZE
400
+ canvas.height = CAT_SIZE
401
+ const ctx = canvas.getContext('2d')
402
+ if (!ctx) return null
403
+
404
+ const img = ctx.createImageData(CAT_SIZE, CAT_SIZE)
405
+ const data = buildCatGrid(frames[i])
406
+ for (let p = 0; p < data.length; p++) {
407
+ const v = data[p]
408
+ if (!v) continue
409
+ const hex = palette[v as 1 | 2 | 3 | 4] || '#ffffff'
410
+ const [r, g, b] = hexToRgb(hex)
411
+ img.data[p * 4] = r
412
+ img.data[p * 4 + 1] = g
413
+ img.data[p * 4 + 2] = b
414
+ img.data[p * 4 + 3] = 255
415
+ }
416
+ ctx.putImageData(img, 0, 0)
417
+ canvasCache.set(key, canvas)
418
+ return canvas
419
+ }
420
+
421
+ function CatSpriteCanvas({
422
+ pose,
423
+ palette,
424
+ animated,
425
+ }: {
426
+ pose: PixelCatPose
427
+ palette: Record<1 | 2 | 3 | 4, string>
428
+ animated: boolean
429
+ }) {
430
+ const canvasRef = useRef<HTMLCanvasElement>(null)
431
+
432
+ useEffect(() => {
433
+ const canvas = canvasRef.current
434
+ if (!canvas) return
435
+ const ctx = canvas.getContext('2d')
436
+ if (!ctx) return
437
+
438
+ ctx.imageSmoothingEnabled = false
439
+ const animDef = ANIMATIONS[pose]
440
+ const { fps, frames } = animDef
441
+ let index = 0
442
+
443
+ const draw = () => {
444
+ ctx.clearRect(0, 0, CAT_SIZE, CAT_SIZE)
445
+ const frameCanvas = getCatFrameCanvas(pose, index, palette)
446
+ if (frameCanvas) {
447
+ ctx.drawImage(frameCanvas, 0, 0)
448
+ }
449
+ }
450
+
451
+ draw()
452
+ if (!animated) return
453
+
454
+ const interval = window.setInterval(() => {
455
+ index = (index + 1) % frames.length
456
+ draw()
457
+ }, 1000 / fps)
458
+
459
+ return () => window.clearInterval(interval)
460
+ }, [pose, palette, animated])
461
+
462
+ return (
463
+ <canvas
464
+ ref={canvasRef}
465
+ width={CAT_SIZE}
466
+ height={CAT_SIZE}
467
+ aria-hidden="true"
468
+ className="block h-full w-full select-none"
469
+ style={{
470
+ imageRendering: 'pixelated',
471
+ }}
472
+ />
473
+ )
474
+ }
475
+
476
+ // -----------------------------------------------------------------------------
477
+ // Component Props and Configuration
478
+ // -----------------------------------------------------------------------------
479
+
480
+ export type PixelCatPosition =
481
+ | 'random'
482
+ | 'center'
483
+ | 'top-left'
484
+ | 'top-right'
485
+ | 'bottom-left'
486
+ | 'bottom-right'
487
+ | { x: number; y: number }
488
+
489
+ export type PixelCatProps = {
490
+ /** Size in pixels (width and height). Default: 36 */
491
+ size?: number
492
+ /** Cat fur color pattern / breed. Default: 'white' */
493
+ breed?: PixelCatBreed
494
+ /** Custom 4-color palette overriding the breed colors. */
495
+ palette?: Record<1 | 2 | 3 | 4, string>
496
+ /** Whether the cat wanders within its parent container. Default: true */
497
+ wandering?: boolean
498
+ /** Movement speed multiplier. Default: 1 */
499
+ speed?: number
500
+ /** Movement boundary: 'parent' container (default) or full 'viewport' */
501
+ boundary?: 'parent' | 'viewport'
502
+ /** Initial placement inside the container. Default: 'random' */
503
+ position?: PixelCatPosition
504
+ /** Initial pose when rendered. Default: 'sit' */
505
+ initialPose?: PixelCatPose
506
+ /** Fixed pose to lock the cat into (disables pose cycling). */
507
+ pose?: PixelCatPose
508
+ /** Whether clicking / hovering pets the cat. Default: true */
509
+ interactive?: boolean
510
+ /** Whether the cat observes and responds to cursor proximity. Default: true */
511
+ cursorInteraction?: boolean
512
+ /** List of speech messages. */
513
+ messages?: string[]
514
+ /** Whether speech bubbles are shown. Default: true */
515
+ showBubble?: boolean
516
+ /** Callback fired when user pets (clicks) the cat. */
517
+ onPet?: (state: { count: number; pose: PixelCatPose }) => void
518
+ /** Callback fired when pose changes. */
519
+ onPoseChange?: (pose: PixelCatPose) => void
520
+ /** Inner padding in pixels from container edges. Default: 8 */
521
+ padding?: number
522
+ /** Optional class name for the wrapper. */
523
+ className?: string
524
+ /** Optional inline styles for the wrapper. */
525
+ style?: CSSProperties
526
+ }
527
+
528
+ const DEFAULT_MESSAGES = ['meow', 'meow!', 'purrr...', 'mrrp', ':3', 'nya~']
529
+
530
+ const rand = (min: number, max: number) => min + Math.random() * (max - min)
531
+ const clamp = (v: number, min: number, max: number) =>
532
+ Math.min(max, Math.max(min, v))
533
+
534
+ export function PixelCat({
535
+ size = 36,
536
+ breed = 'white',
537
+ palette,
538
+ wandering = true,
539
+ speed = 1,
540
+ boundary = 'parent',
541
+ position = 'random',
542
+ initialPose = 'sit',
543
+ pose: fixedPose,
544
+ interactive = true,
545
+ cursorInteraction = true,
546
+ messages = DEFAULT_MESSAGES,
547
+ showBubble = true,
548
+ onPet,
549
+ onPoseChange,
550
+ padding = 8,
551
+ className,
552
+ style,
553
+ }: PixelCatProps) {
554
+ const reduceMotion = useReducedMotion()
555
+ const instanceId = useId()
556
+
557
+ const x = useMotionValue(-999)
558
+ const y = useMotionValue(-999)
559
+ const [currentPose, setCurrentPose] = useState<PixelCatPose>(
560
+ fixedPose ?? initialPose,
561
+ )
562
+ const [facing, setFacing] = useState<1 | -1>(1)
563
+ const [bubbleText, setBubbleText] = useState<string | null>(null)
564
+ const [petCount, setPetCount] = useState(0)
565
+ const [hearts, setHearts] = useState<{ id: number; x: number; y: number }[]>(
566
+ [],
567
+ )
568
+
569
+ const rootRef = useRef<HTMLDivElement>(null)
570
+ const cursorRef = useRef<{ x: number; y: number } | null>(null)
571
+ const activeAnimations = useRef<Set<{ stop: () => void }>>(new Set())
572
+ const isInteracting = useRef(false)
573
+ const containerDimensions = useRef({ width: 0, height: 0 })
574
+
575
+ const activePalette = palette ?? CAT_PALETTES[breed] ?? CAT_PALETTES.white
576
+
577
+ // Update pose helper
578
+ const setCatPose = useCallback(
579
+ (p: PixelCatPose) => {
580
+ if (fixedPose) return
581
+ setCurrentPose(p)
582
+ onPoseChange?.(p)
583
+ },
584
+ [fixedPose, onPoseChange],
585
+ )
586
+
587
+ // Calculate container boundaries
588
+ const getBounds = useCallback(() => {
589
+ let w = containerDimensions.current.width
590
+ let h = containerDimensions.current.height
591
+
592
+ if (
593
+ boundary === 'viewport' ||
594
+ (typeof window !== 'undefined' && (!w || !h))
595
+ ) {
596
+ if (boundary === 'viewport') {
597
+ w = window.innerWidth
598
+ h = window.innerHeight
599
+ } else {
600
+ const parent = rootRef.current?.parentElement
601
+ if (parent) {
602
+ w = parent.clientWidth
603
+ h = parent.clientHeight
604
+ }
605
+ }
606
+ }
607
+
608
+ const minX = padding
609
+ const maxX = Math.max(padding, (w || 300) - size - padding)
610
+ const minY = padding
611
+ const maxY = Math.max(padding, (h || 200) - size - padding)
612
+
613
+ return { minX, maxX, minY, maxY, width: w, height: h }
614
+ }, [boundary, padding, size])
615
+
616
+ // Resolve initial coordinates based on position prop
617
+ const resolveInitialPos = useCallback(() => {
618
+ const { minX, maxX, minY, maxY, width, height } = getBounds()
619
+
620
+ if (typeof position === 'object') {
621
+ const px = (position.x / 100) * (width - size)
622
+ const py = (position.y / 100) * (height - size)
623
+ return {
624
+ x: clamp(px, minX, maxX),
625
+ y: clamp(py, minY, maxY),
626
+ }
627
+ }
628
+
629
+ switch (position) {
630
+ case 'center':
631
+ return { x: (minX + maxX) / 2, y: (minY + maxY) / 2 }
632
+ case 'top-left':
633
+ return { x: minX, y: minY }
634
+ case 'top-right':
635
+ return { x: maxX, y: minY }
636
+ case 'bottom-left':
637
+ return { x: minX, y: maxY }
638
+ case 'bottom-right':
639
+ return { x: maxX, y: maxY }
640
+ case 'random':
641
+ default:
642
+ return { x: rand(minX, maxX), y: rand(minY, maxY) }
643
+ }
644
+ }, [getBounds, position, size])
645
+
646
+ // ResizeObserver for parent container bounds
647
+ useEffect(() => {
648
+ if (typeof window === 'undefined') return
649
+
650
+ const updateDimensions = () => {
651
+ if (boundary === 'viewport') {
652
+ containerDimensions.current = {
653
+ width: window.innerWidth,
654
+ height: window.innerHeight,
655
+ }
656
+ } else {
657
+ const parent = rootRef.current?.parentElement
658
+ if (parent) {
659
+ containerDimensions.current = {
660
+ width: parent.clientWidth,
661
+ height: parent.clientHeight,
662
+ }
663
+ }
664
+ }
665
+ }
666
+
667
+ updateDimensions()
668
+
669
+ // Place cat initially
670
+ const initial = resolveInitialPos()
671
+ x.set(initial.x)
672
+ y.set(initial.y)
673
+
674
+ if (boundary === 'viewport') {
675
+ window.addEventListener('resize', updateDimensions)
676
+ return () => window.removeEventListener('resize', updateDimensions)
677
+ }
678
+
679
+ const parent = rootRef.current?.parentElement
680
+ if (!parent) return
681
+
682
+ const ro = new ResizeObserver((entries) => {
683
+ for (const entry of entries) {
684
+ containerDimensions.current = {
685
+ width: entry.contentRect.width,
686
+ height: entry.contentRect.height,
687
+ }
688
+ // Clamp current position if parent shrunk
689
+ const b = getBounds()
690
+ if (x.get() > b.maxX) x.set(b.maxX)
691
+ if (y.get() > b.maxY) y.set(b.maxY)
692
+ }
693
+ })
694
+ ro.observe(parent)
695
+
696
+ return () => ro.disconnect()
697
+ }, [boundary, getBounds, resolveInitialPos, x, y])
698
+
699
+ // Track cursor within parent container or window
700
+ useEffect(() => {
701
+ if (!cursorInteraction || typeof window === 'undefined') return
702
+
703
+ const handlePointerMove = (e: PointerEvent) => {
704
+ if (e.pointerType === 'touch') return
705
+ if (boundary === 'viewport') {
706
+ cursorRef.current = { x: e.clientX, y: e.clientY }
707
+ } else {
708
+ const parent = rootRef.current?.parentElement
709
+ if (!parent) return
710
+ const rect = parent.getBoundingClientRect()
711
+ // Relative to parent container
712
+ cursorRef.current = {
713
+ x: e.clientX - rect.left,
714
+ y: e.clientY - rect.top,
715
+ }
716
+ }
717
+ }
718
+
719
+ const handlePointerLeave = () => {
720
+ cursorRef.current = null
721
+ }
722
+
723
+ const target =
724
+ boundary === 'viewport'
725
+ ? window
726
+ : (rootRef.current?.parentElement ?? window)
727
+
728
+ target.addEventListener('pointermove', handlePointerMove as EventListener, {
729
+ passive: true,
730
+ })
731
+ target.addEventListener('pointerleave', handlePointerLeave as EventListener)
732
+
733
+ return () => {
734
+ target.removeEventListener(
735
+ 'pointermove',
736
+ handlePointerMove as EventListener,
737
+ )
738
+ target.removeEventListener(
739
+ 'pointerleave',
740
+ handlePointerLeave as EventListener,
741
+ )
742
+ }
743
+ }, [boundary, cursorInteraction])
744
+
745
+ // Handle petting / interaction
746
+ const handlePet = useCallback(() => {
747
+ if (!interactive) return
748
+ isInteracting.current = true
749
+ const nextCount = petCount + 1
750
+ setPetCount(nextCount)
751
+
752
+ // Pose reaction
753
+ setCatPose('happy')
754
+ onPet?.({ count: nextCount, pose: 'happy' })
755
+
756
+ // Speech bubble
757
+ if (showBubble && messages.length > 0) {
758
+ const msg = messages[Math.floor(Math.random() * messages.length)]
759
+ setBubbleText(msg)
760
+ }
761
+
762
+ // Floating heart effect
763
+ const heartId = Date.now() + Math.random()
764
+ setHearts((prev) => [
765
+ ...prev.slice(-3),
766
+ { id: heartId, x: rand(-8, 8), y: rand(-4, 4) },
767
+ ])
768
+
769
+ window.setTimeout(() => {
770
+ setHearts((prev) => prev.filter((h) => h.id !== heartId))
771
+ }, 1200)
772
+
773
+ window.setTimeout(() => {
774
+ setBubbleText(null)
775
+ isInteracting.current = false
776
+ if (!fixedPose) setCatPose('sit')
777
+ }, 2000)
778
+ }, [
779
+ fixedPose,
780
+ interactive,
781
+ messages,
782
+ onPet,
783
+ petCount,
784
+ setCatPose,
785
+ showBubble,
786
+ ])
787
+
788
+ // Wandering & Behavior Loop
789
+ useEffect(() => {
790
+ if (!wandering || reduceMotion || fixedPose) return
791
+
792
+ let cancelled = false
793
+ const timers = new Set<number>()
794
+
795
+ const wait = (ms: number) =>
796
+ new Promise<void>((resolve) => {
797
+ const t = window.setTimeout(() => {
798
+ timers.delete(t)
799
+ resolve()
800
+ }, ms)
801
+ timers.add(t)
802
+ })
803
+
804
+ const walkTo = async (tx: number, ty: number) => {
805
+ if (cancelled) return
806
+ const dx = tx - x.get()
807
+ const dy = ty - y.get()
808
+ const dist = Math.hypot(dx, dy)
809
+ if (dist < 4) return
810
+
811
+ setFacing(dx >= 0 ? 1 : -1)
812
+ setCatPose('walk')
813
+
814
+ const travelSpeed = Math.max(16, rand(28, 44) * speed)
815
+ const duration = dist / travelSpeed
816
+
817
+ const ax = animate(x, tx, { duration, ease: 'linear' })
818
+ const ay = animate(y, ty, { duration, ease: 'linear' })
819
+
820
+ activeAnimations.current.add(ax)
821
+ activeAnimations.current.add(ay)
822
+
823
+ await Promise.all([ax, ay]).catch(() => {})
824
+ activeAnimations.current.delete(ax)
825
+ activeAnimations.current.delete(ay)
826
+ }
827
+
828
+ const runLoop = async () => {
829
+ // Small initial delay before wandering begins
830
+ await wait(rand(1000, 2500))
831
+
832
+ while (!cancelled) {
833
+ if (isInteracting.current) {
834
+ await wait(500)
835
+ continue
836
+ }
837
+
838
+ const b = getBounds()
839
+ const c = cursorRef.current
840
+
841
+ // Cursor awareness
842
+ if (cursorInteraction && c) {
843
+ const cx = x.get() + size / 2
844
+ const cy = y.get() + size / 2
845
+ const distToCursor = Math.hypot(c.x - cx, c.y - cy)
846
+
847
+ if (distToCursor < 36) {
848
+ // Playfully scamper away
849
+ const ang = Math.atan2(cy - c.y, cx - c.x) + rand(-0.4, 0.4)
850
+ const escapeDist = rand(60, 110)
851
+ await walkTo(
852
+ clamp(x.get() + Math.cos(ang) * escapeDist, b.minX, b.maxX),
853
+ clamp(y.get() + Math.sin(ang) * escapeDist, b.minY, b.maxY),
854
+ )
855
+ continue
856
+ } else if (distToCursor < 120) {
857
+ // Face cursor alertly
858
+ setFacing(c.x >= cx ? 1 : -1)
859
+ setCatPose('alert')
860
+ await wait(rand(800, 1600))
861
+ if (Math.random() < 0.35 && cursorRef.current) {
862
+ // Curious step closer
863
+ const target = cursorRef.current
864
+ const ang = Math.atan2(target.y - cy, target.x - cx)
865
+ await walkTo(
866
+ clamp(target.x - Math.cos(ang) * 44 - size / 2, b.minX, b.maxX),
867
+ clamp(target.y - Math.sin(ang) * 44 - size / 2, b.minY, b.maxY),
868
+ )
869
+ }
870
+ continue
871
+ }
872
+ }
873
+
874
+ // Autonomous wandering behaviors
875
+ const roll = Math.random()
876
+
877
+ if (roll < 0.45) {
878
+ // Walk to a new position
879
+ const targetX = rand(b.minX, b.maxX)
880
+ const targetY = rand(b.minY, b.maxY)
881
+ await walkTo(targetX, targetY)
882
+ } else if (roll < 0.65) {
883
+ // Sit and observe
884
+ setCatPose('sit')
885
+ if (showBubble && Math.random() < 0.15 && messages.length > 0) {
886
+ setBubbleText(messages[Math.floor(Math.random() * messages.length)])
887
+ await wait(1800)
888
+ setBubbleText(null)
889
+ } else {
890
+ await wait(rand(2500, 5000))
891
+ }
892
+ } else if (roll < 0.78) {
893
+ // Take a nap / loaf
894
+ setCatPose('sleep')
895
+ await wait(rand(4000, 8000))
896
+ } else if (roll < 0.88) {
897
+ // Groom paw
898
+ setCatPose('groom')
899
+ await wait(rand(2000, 4000))
900
+ } else if (roll < 0.94) {
901
+ // Morning stretch
902
+ setCatPose('stretch')
903
+ await wait(rand(1800, 3200))
904
+ } else {
905
+ // Idle sway
906
+ setCatPose('idle')
907
+ if (Math.random() < 0.4) setFacing((f) => (f === 1 ? -1 : 1))
908
+ await wait(rand(1500, 3000))
909
+ }
910
+
911
+ if (cancelled) break
912
+ setCatPose('idle')
913
+ await wait(rand(600, 1800))
914
+ }
915
+ }
916
+
917
+ runLoop()
918
+
919
+ const anims = activeAnimations.current
920
+ return () => {
921
+ cancelled = true
922
+ anims.forEach((a) => a.stop())
923
+ anims.clear()
924
+ timers.forEach((t) => window.clearTimeout(t))
925
+ }
926
+ }, [
927
+ cursorInteraction,
928
+ fixedPose,
929
+ getBounds,
930
+ messages,
931
+ reduceMotion,
932
+ setCatPose,
933
+ showBubble,
934
+ size,
935
+ speed,
936
+ wandering,
937
+ x,
938
+ y,
939
+ ])
940
+
941
+ const activePose = fixedPose ?? currentPose
942
+
943
+ return (
944
+ <motion.div
945
+ ref={rootRef}
946
+ id={`pixel-cat-${instanceId}`}
947
+ className={cn(
948
+ boundary === 'viewport' ? 'fixed' : 'absolute',
949
+ 'pointer-events-none top-0 left-0 z-20 select-none',
950
+ className,
951
+ )}
952
+ style={{
953
+ width: size,
954
+ height: size,
955
+ x,
956
+ y,
957
+ ...style,
958
+ }}
959
+ >
960
+ {/* Facing transform container */}
961
+ <div
962
+ className="pointer-events-none h-full w-full transition-transform duration-100"
963
+ style={{ transform: `scaleX(${facing})` }}
964
+ >
965
+ <CatSpriteCanvas
966
+ pose={activePose}
967
+ palette={activePalette}
968
+ animated={!reduceMotion}
969
+ />
970
+ </div>
971
+
972
+ {/* Hitbox for petting */}
973
+ {interactive && (
974
+ <button
975
+ type="button"
976
+ tabIndex={0}
977
+ aria-label={`Pet the ${breed} cat`}
978
+ onClick={handlePet}
979
+ className="focus-visible:ring-ring pointer-events-auto absolute -inset-2 cursor-pointer rounded-full outline-none focus-visible:ring-1"
980
+ />
981
+ )}
982
+
983
+ {/* Speech Bubble */}
984
+ <AnimatePresence>
985
+ {bubbleText && (
986
+ <motion.div
987
+ key={bubbleText}
988
+ initial={{ opacity: 0, y: 4, scale: 0.9 }}
989
+ animate={{ opacity: 1, y: 0, scale: 1 }}
990
+ exit={{ opacity: 0, y: -2, scale: 0.9 }}
991
+ transition={{ duration: 0.18 }}
992
+ className="border-border bg-popover text-popover-foreground pointer-events-none absolute bottom-full left-1/2 mb-1.5 -translate-x-1/2 rounded-md border px-2 py-0.5 font-mono text-[11px] font-medium whitespace-nowrap shadow-sm"
993
+ >
994
+ {bubbleText}
995
+ {/* Tiny speech pointer notch */}
996
+ <div className="border-border bg-popover absolute -bottom-1 left-1/2 h-1.5 w-1.5 -translate-x-1/2 rotate-45 border-r border-b" />
997
+ </motion.div>
998
+ )}
999
+ </AnimatePresence>
1000
+
1001
+ {/* Floating Hearts Reaction */}
1002
+ <AnimatePresence>
1003
+ {hearts.map((h) => (
1004
+ <motion.span
1005
+ key={h.id}
1006
+ initial={{ opacity: 1, y: 0, x: h.x, scale: 0.8 }}
1007
+ animate={{ opacity: 0, y: -24, scale: 1.2 }}
1008
+ exit={{ opacity: 0 }}
1009
+ transition={{ duration: 1, ease: 'easeOut' }}
1010
+ className="pointer-events-none absolute -top-1 left-1/2 -translate-x-1/2 text-xs leading-none select-none"
1011
+ >
1012
+ ❤️
1013
+ </motion.span>
1014
+ ))}
1015
+ </AnimatePresence>
1016
+ </motion.div>
1017
+ )
1018
+ }
1019
+
1020
+ export default PixelCat