@linxin666/dsh-pet 0.4.7 → 0.4.8

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.
@@ -11,7 +11,8 @@ import { t } from './locales.ts'
11
11
  import type { PetStateView } from '../service.ts'
12
12
  import type { PetAnnouncement } from '../announce.ts'
13
13
  import type { PetDefinition, PetTrackDef } from '../registry.ts'
14
- import type { PetAnimation } from '../state.ts'
14
+ import type { GameplayBus } from './gameplay-hud.ts'
15
+ import { rowOf, type PetAnimation } from '../state.ts'
15
16
  import type { DecorationView } from '../contracts/status-decoration.ts'
16
17
 
17
18
  /** A minimal pet definition (geometry + tracks) as served by the host. */
@@ -71,8 +72,8 @@ const snapshot: PetStateView = {
71
72
  beforeAll(() => {
72
73
  // Deterministic zh copy for button labels.
73
74
  document.documentElement.lang = 'zh'
74
- // Prefer-reduced-motion matches: the sprite loop then never schedules
75
- // requestAnimationFrame, keeping the test free of animation timers.
75
+ // Prefer-reduced-motion matches: the sprite loop then never schedules a
76
+ // frame timer, keeping the test free of animation timers.
76
77
  Object.defineProperty(window, 'matchMedia', {
77
78
  configurable: true,
78
79
  value: (query: string) => ({
@@ -587,13 +588,15 @@ describe('PetSprite definition-driven render', () => {
587
588
  removeListener: () => {},
588
589
  dispatchEvent: () => false,
589
590
  })
590
- vi.spyOn(performance, 'now').mockReturnValue(0)
591
- let nextFrame: FrameRequestCallback | undefined
592
- vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
593
- nextFrame = callback
594
- return 1
595
- })
596
- vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {})
591
+ let now = 0
592
+ vi.spyOn(performance, 'now').mockImplementation(() => now)
593
+ const timers: { at: number; callback: () => void }[] = []
594
+ let timerId = 0
595
+ vi.spyOn(window, 'setTimeout').mockImplementation(((callback: () => void, delay = 0) => {
596
+ timers.push({ at: now + delay, callback })
597
+ return ++timerId
598
+ }) as typeof window.setTimeout)
599
+ vi.spyOn(window, 'clearTimeout').mockImplementation(() => {})
597
600
  const definition = petDefinition()
598
601
  definition.sequences = {
599
602
  thinking: ['running', 'waiting', 'running', 'waiting', 'running'],
@@ -604,7 +607,11 @@ describe('PetSprite definition-driven render', () => {
604
607
  })
605
608
  const sprite = screen.getByRole('button', { name: '鲸鱼娘' })
606
609
  expect(sprite.style.backgroundPosition).toBe('0px -1120px')
607
- act(() => { nextFrame?.(1_500) })
610
+ // The loop sleeps for the frame's remaining time; jump the clock past the
611
+ // first item of the sequence (running frames are 250ms each) and fire the
612
+ // one pending tick.
613
+ now = 1_500
614
+ act(() => { for (const timer of timers.splice(0)) timer.callback() })
608
615
  expect(sprite.style.backgroundPosition).toBe('0px -960px')
609
616
  })
610
617
 
@@ -619,23 +626,30 @@ describe('PetSprite definition-driven render', () => {
619
626
  removeListener: () => {},
620
627
  dispatchEvent: () => false,
621
628
  })
622
- vi.spyOn(performance, 'now').mockReturnValue(0)
623
- let nextFrame: FrameRequestCallback | undefined
624
- vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
625
- nextFrame = callback
626
- return 1
627
- })
628
- vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {})
629
+ let now = 0
630
+ vi.spyOn(performance, 'now').mockImplementation(() => now)
631
+ const timers: { at: number; callback: () => void }[] = []
632
+ let timerId = 0
633
+ vi.spyOn(window, 'setTimeout').mockImplementation(((callback: () => void, delay = 0) => {
634
+ timers.push({ at: now + delay, callback })
635
+ return ++timerId
636
+ }) as typeof window.setTimeout)
637
+ vi.spyOn(window, 'clearTimeout').mockImplementation(() => {})
629
638
  renderPet({
630
639
  snapshot: { ...snapshot, animation: 'idle', phase: 'idle' },
631
640
  })
632
641
  const sprite = screen.getByRole('button', { name: '鲸鱼娘' })
633
642
  const styleSetterSpy = vi.spyOn(sprite.style, 'backgroundPosition', 'set')
634
- // Idle frame 0 duration is 400ms. An intermediate tick at 16ms does not advance the frame.
635
- act(() => { nextFrame?.(16) })
643
+ // Idle frame 0 duration is 400ms. An intermediate tick at 16ms does not
644
+ // advance the frame, writes nothing, and the loop sleeps to the boundary
645
+ // (t=400) rather than polling every screen refresh.
646
+ now = 16
647
+ act(() => { for (const timer of timers.splice(0)) timer.callback() })
636
648
  expect(styleSetterSpy).not.toHaveBeenCalled()
649
+ expect(timers[0]?.at).toBe(400)
637
650
  // A tick past 400ms advances to frame 1 and should set backgroundPosition once.
638
- act(() => { nextFrame?.(410) })
651
+ now = 410
652
+ act(() => { for (const timer of timers.splice(0)) timer.callback() })
639
653
  expect(styleSetterSpy).toHaveBeenCalledTimes(1)
640
654
  })
641
655
  })
@@ -814,8 +828,8 @@ describe('PetSprite status decoration (pet-center M5, #567)', () => {
814
828
  })
815
829
  let now = 0
816
830
  vi.spyOn(performance, 'now').mockImplementation(() => now)
817
- // The ornament schedules by frame duration (setTimeout), the sprite
818
- // still uses rAF; capture both so stepping advances both loops.
831
+ // The ornament and the sprite both schedule by frame duration
832
+ // (setTimeout), so one capture and one stepping helper drive both loops.
819
833
  const timers: { at: number; callback: () => void }[] = []
820
834
  let timerId = 0
821
835
  vi.spyOn(window, 'setTimeout').mockImplementation(((callback: () => void, delay = 0) => {
@@ -948,7 +962,12 @@ describe('PetSprite status decoration (pet-center M5, #567)', () => {
948
962
  return frames.length
949
963
  })
950
964
  vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {})
951
- renderPet({ snapshot: { ...snapshot, bubble: '完成', phase: 'done', decoration: { ...decoration, loop: false } } })
965
+ // A custom visual keeps the sprite's own frame loop out of the timer
966
+ // capture, so a pending timer can only be the ornament's.
967
+ renderPet({
968
+ visual: <span data-testid="custom-visual" />,
969
+ snapshot: { ...snapshot, bubble: '完成', phase: 'done', decoration: { ...decoration, loop: false } },
970
+ })
952
971
  const el = ornament()!
953
972
  const step = (ms: number): void => {
954
973
  for (const callback of frames.splice(0)) callback(now)
@@ -967,7 +986,7 @@ describe('PetSprite status decoration (pet-center M5, #567)', () => {
967
986
  expect(el.style.backgroundPosition).toBe('-48px 0px')
968
987
  act(() => { step(161) })
969
988
  expect(el.style.backgroundPosition).toBe('-72px 0px')
970
- // The ornament stopped scheduling timers (only the sprite rAF remains).
989
+ // The ornament stopped scheduling timers.
971
990
  expect(timers).toHaveLength(0)
972
991
  act(() => { step(161) })
973
992
  // The last frame holds.
@@ -1000,7 +1019,9 @@ describe('PetSprite status decoration (pet-center M5, #567)', () => {
1000
1019
  })
1001
1020
  vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {})
1002
1021
  // failed binds the single frame 3 of a 24px-wide frame; loop stays true.
1022
+ // The custom visual keeps the sprite's own frame loop out of the capture.
1003
1023
  renderPet({
1024
+ visual: <span data-testid="custom-visual" />,
1004
1025
  snapshot: {
1005
1026
  ...snapshot,
1006
1027
  bubble: '失败',
@@ -1010,7 +1031,7 @@ describe('PetSprite status decoration (pet-center M5, #567)', () => {
1010
1031
  })
1011
1032
  const el = ornament()!
1012
1033
  // The ornament settles on its only frame, exactly like the reduced-motion
1013
- // hold — no timer may start (only the sprite's idle rAF is pending).
1034
+ // hold — no timer may start.
1014
1035
  expect(el.style.backgroundPosition).toBe('-72px 0px')
1015
1036
  expect(timers).toHaveLength(0)
1016
1037
  const step = (ts: number): void => { for (const callback of frames.splice(0)) callback(ts) }
@@ -1399,3 +1420,218 @@ describe('PetSprite announcement bubbles from several publishers (issue #1812)',
1399
1420
  })
1400
1421
  })
1401
1422
 
1423
+ /**
1424
+ * Capture every timer the pet schedules onto a virtual clock. The sprite frame
1425
+ * loop sleeps until the next frame boundary (issue #17), so a test steps it by
1426
+ * moving the clock and firing whatever became due.
1427
+ */
1428
+ function captureTimers(clock: () => number): { at: number; callback: () => void }[] {
1429
+ const timers: { at: number; callback: () => void }[] = []
1430
+ let timerId = 0
1431
+ vi.spyOn(window, 'setTimeout').mockImplementation(((callback: () => void, delay = 0) => {
1432
+ timers.push({ at: clock() + delay, callback })
1433
+ return ++timerId
1434
+ }) as typeof window.setTimeout)
1435
+ vi.spyOn(window, 'clearTimeout').mockImplementation(() => {})
1436
+ return timers
1437
+ }
1438
+
1439
+ /** Fire every captured timer once; each one may schedule the next wake. */
1440
+ function fireDue(timers: { at: number; callback: () => void }[]): void {
1441
+ for (const timer of timers.splice(0)) timer.callback()
1442
+ }
1443
+
1444
+ describe('PetSprite render cost (issue #17)', () => {
1445
+ it('snaps the atlas grid and the sprite box to whole pixels', () => {
1446
+ renderPet()
1447
+ const sprite = screen.getByRole('button', { name: '鲸鱼娘' })
1448
+ // 192x208 cells at display.size 160 are 147.69px and 160px unrounded. The
1449
+ // box, the atlas grid and every frame offset share the whole-pixel cell,
1450
+ // so a frame change is a whole-pixel translate of the scaled atlas instead
1451
+ // of a fresh resample of the 1536x1872 source.
1452
+ expect(sprite.style.width).toBe('148px')
1453
+ expect(sprite.style.height).toBe('160px')
1454
+ expect(sprite.style.backgroundSize).toBe('1184px 1440px')
1455
+ })
1456
+
1457
+ it('advances frames on a duration timer instead of the screen refresh', () => {
1458
+ vi.spyOn(window, 'matchMedia').mockReturnValue({
1459
+ matches: false,
1460
+ media: '(prefers-reduced-motion: reduce)',
1461
+ onchange: null,
1462
+ addEventListener: () => {},
1463
+ removeEventListener: () => {},
1464
+ addListener: () => {},
1465
+ removeListener: () => {},
1466
+ dispatchEvent: () => false,
1467
+ })
1468
+ let now = 0
1469
+ vi.spyOn(performance, 'now').mockImplementation(() => now)
1470
+ const timers = captureTimers(() => now)
1471
+ const raf = vi.spyOn(window, 'requestAnimationFrame')
1472
+ renderPet()
1473
+ const sprite = screen.getByRole('button', { name: '鲸鱼娘' })
1474
+ // Nothing drives the frame loop off the screen refresh any more.
1475
+ expect(raf).not.toHaveBeenCalled()
1476
+ // One pending wake: the loop's first tick, which then sleeps to the end of
1477
+ // the frame in play instead of re-arming for the next screen refresh.
1478
+ expect(timers).toHaveLength(1)
1479
+ act(() => { fireDue(timers) })
1480
+ expect(timers[0]?.at).toBe(400)
1481
+ now = 410
1482
+ act(() => { fireDue(timers) })
1483
+ expect(sprite.style.backgroundPosition).toBe('-148px 0px')
1484
+ // Idle frame 1 is already 10ms in, so the next wake is 390ms away.
1485
+ expect(timers[0]?.at).toBe(800)
1486
+ })
1487
+
1488
+ it('stops waking once a non-looping track holds its final frame', () => {
1489
+ vi.spyOn(window, 'matchMedia').mockReturnValue({
1490
+ matches: false,
1491
+ media: '(prefers-reduced-motion: reduce)',
1492
+ onchange: null,
1493
+ addEventListener: () => {},
1494
+ removeEventListener: () => {},
1495
+ addListener: () => {},
1496
+ removeListener: () => {},
1497
+ dispatchEvent: () => false,
1498
+ })
1499
+ let now = 0
1500
+ vi.spyOn(performance, 'now').mockImplementation(() => now)
1501
+ const timers = captureTimers(() => now)
1502
+ renderPet({ snapshot: { ...snapshot, animation: 'failed', phase: 'failed' } })
1503
+ const sprite = screen.getByRole('button', { name: '鲸鱼娘' })
1504
+ // 'failed' is a non-looping 8-frame track at 450ms per frame; the 8th frame
1505
+ // holds once the host owns the switch to its fallback.
1506
+ now = 8 * 450
1507
+ act(() => { fireDue(timers) })
1508
+ expect(sprite.style.backgroundPosition).toBe('-' + (7 * 148) + 'px -' + (rowOf('failed') * 160) + 'px')
1509
+ // The track is settled: no timer is pending, so the pet stops waking the
1510
+ // main thread for a frame that cannot change.
1511
+ expect(timers).toHaveLength(0)
1512
+ const styleSetterSpy = vi.spyOn(sprite.style, 'backgroundPosition', 'set')
1513
+ now = 60_000
1514
+ act(() => { fireDue(timers) })
1515
+ expect(styleSetterSpy).not.toHaveBeenCalled()
1516
+ expect(timers).toHaveLength(0)
1517
+ })
1518
+
1519
+ it('repaints a settled frame when the sprite scale changes', () => {
1520
+ vi.spyOn(window, 'matchMedia').mockReturnValue({
1521
+ matches: false,
1522
+ media: '(prefers-reduced-motion: reduce)',
1523
+ onchange: null,
1524
+ addEventListener: () => {},
1525
+ removeEventListener: () => {},
1526
+ addListener: () => {},
1527
+ removeListener: () => {},
1528
+ dispatchEvent: () => false,
1529
+ })
1530
+ let now = 0
1531
+ vi.spyOn(performance, 'now').mockImplementation(() => now)
1532
+ const timers = captureTimers(() => now)
1533
+ const definition = petDefinition()
1534
+ const display = snapshot.display
1535
+ const failed = { ...snapshot, animation: 'failed' as const, phase: 'failed' as const }
1536
+ const first = render(<PetSprite {...petProps({ definition, display, snapshot: failed })} />)
1537
+ const sprite = screen.getByRole('button', { name: '鲸鱼娘' })
1538
+ now = 8 * 450
1539
+ act(() => { fireDue(timers) })
1540
+ // A display.size change re-renders without restarting the track, and the
1541
+ // settled loop is woken by nothing: the held frame must be repainted at the
1542
+ // new scale or the box would show a neighbouring cell.
1543
+ first.rerender(<PetSprite {...petProps({ definition, display: { ...display, size: 120 }, snapshot: failed })} />)
1544
+ expect(sprite.style.width).toBe('111px')
1545
+ expect(sprite.style.height).toBe('120px')
1546
+ expect(sprite.style.backgroundPosition).toBe('-' + (7 * 111) + 'px -' + (rowOf('failed') * 120) + 'px')
1547
+ })
1548
+ })
1549
+
1550
+ describe('PetSprite roaming (issue #17)', () => {
1551
+ /** Drive the walk loop with a captured requestAnimationFrame. */
1552
+ function captureFrame(clock: () => number): { fire: () => void } {
1553
+ let pending: FrameRequestCallback | undefined
1554
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
1555
+ pending = callback
1556
+ return 1
1557
+ })
1558
+ vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {})
1559
+ return {
1560
+ fire: () => {
1561
+ const callback = pending
1562
+ pending = undefined
1563
+ callback?.(clock())
1564
+ },
1565
+ }
1566
+ }
1567
+
1568
+ it('writes the walk position to the element and renders only on landing', () => {
1569
+ let now = 0
1570
+ vi.spyOn(performance, 'now').mockImplementation(() => now)
1571
+ const frame = captureFrame(() => now)
1572
+ const onDragEnd = vi.fn()
1573
+ const tSpy = vi.fn(t)
1574
+ const bus: GameplayBus = {}
1575
+ renderPet({ onDragEnd, t: tSpy, bus })
1576
+ const sprite = screen.getByRole('button', { name: '鲸鱼娘' })
1577
+ const float = sprite.parentElement!.parentElement as HTMLDivElement
1578
+ // Open the hover panel: every render then resolves panel copy through t, so
1579
+ // the t call count is a render probe the walk must not disturb.
1580
+ fireEvent.pointerOver(sprite)
1581
+ const renders = tSpy.mock.calls.length
1582
+ // 24 + 120 right, 60 px/s, so 2s of motion toward right = 144.
1583
+ expect(bus.walk?.('left', 120, 60)).toBe(120)
1584
+ now = 1_000
1585
+ act(() => { frame.fire() })
1586
+ expect(float.style.right).toBe('84px')
1587
+ expect(float.style.bottom).toBe('20px')
1588
+ // Mid-walk movement is a DOM write, not a React state update.
1589
+ expect(tSpy.mock.calls.length).toBe(renders)
1590
+ now = 2_000
1591
+ act(() => { frame.fire() })
1592
+ expect(float.style.right).toBe('144px')
1593
+ expect(onDragEnd).toHaveBeenCalledTimes(1)
1594
+ expect(onDragEnd).toHaveBeenCalledWith(144, 20)
1595
+ // The landing frame hands the spot to React state, which keeps rendering it.
1596
+ expect(tSpy.mock.calls.length).toBeGreaterThan(renders)
1597
+ expect(float.style.right).toBe('144px')
1598
+ })
1599
+
1600
+ it('keeps the walked position when a render lands mid-walk', () => {
1601
+ let now = 0
1602
+ vi.spyOn(performance, 'now').mockImplementation(() => now)
1603
+ const frame = captureFrame(() => now)
1604
+ const definition = petDefinition()
1605
+ const display = snapshot.display
1606
+ const bus: GameplayBus = {}
1607
+ const first = render(<PetSprite {...petProps({ definition, display, bus })} />)
1608
+ const sprite = screen.getByRole('button', { name: '鲸鱼娘' })
1609
+ const float = sprite.parentElement!.parentElement as HTMLDivElement
1610
+ bus.walk?.('left', 120, 60)
1611
+ now = 1_000
1612
+ act(() => { frame.fire() })
1613
+ expect(float.style.right).toBe('84px')
1614
+ // A host poll re-renders the sprite mid-walk; the walked spot rides a ref,
1615
+ // so the sprite must not snap back to its saved position.
1616
+ first.rerender(<PetSprite {...petProps({ definition, display, bus })} />)
1617
+ expect(float.style.right).toBe('84px')
1618
+ })
1619
+
1620
+ it('starts a drag from the position the pet reached mid-walk', () => {
1621
+ let now = 0
1622
+ vi.spyOn(performance, 'now').mockImplementation(() => now)
1623
+ const frame = captureFrame(() => now)
1624
+ const onDragEnd = vi.fn()
1625
+ const bus: GameplayBus = {}
1626
+ renderPet({ onDragEnd, bus })
1627
+ const sprite = screen.getByRole('button', { name: '鲸鱼娘' })
1628
+ bus.walk?.('left', 120, 60)
1629
+ now = 1_000
1630
+ act(() => { frame.fire() })
1631
+ // Grab the pet where it actually is, not where the walk started.
1632
+ fireEvent.pointerDown(sprite, { clientX: 100, clientY: 100 })
1633
+ fireEvent.pointerUp(sprite)
1634
+ expect(onDragEnd).toHaveBeenCalledWith(84, 20)
1635
+ })
1636
+ })
1637
+
@@ -22,7 +22,7 @@ import type { GameplayBus } from './gameplay-hud.ts'
22
22
  import type { PetRoamDirection } from '../gameplay.ts'
23
23
  import type { DecorationView } from '../contracts/status-decoration.ts'
24
24
  import type { PetFeedback } from './pet-store.ts'
25
- import { framePosition, rowOfTrack, trimTrack } from './spritesheet.ts'
25
+ import { framePosition, rowOfTrack, scaledCellSize, trimTrack } from './spritesheet.ts'
26
26
  import { createSequenceTimeline } from './sequences.ts'
27
27
  import { animationForPhase, type ActivityPhase, type PetAnimation } from '../state.ts'
28
28
  import { NS } from './locales.ts'
@@ -250,10 +250,12 @@ function UsageAnnouncementBubble(props: { announcement: PetAnnouncement }): Reac
250
250
  }
251
251
 
252
252
  /**
253
- * The floating pet. The spritesheet frame advances on requestAnimationFrame
254
- * with per-frame durations from the definition's tracks; the atlas image is
255
- * loaded once and the background position is written straight to the sprite
256
- * element (no per-frame React state).
253
+ * The floating pet. The spritesheet frame advances on a timer scheduled for the
254
+ * current frame's remaining time (per-frame durations come from the
255
+ * definition's tracks), so the loop wakes once per frame change instead of once
256
+ * per screen refresh; the atlas image is loaded once and the background
257
+ * position is written straight to the sprite element (no per-frame React
258
+ * state). Roaming writes the sprite's position the same way (issue #17).
257
259
  */
258
260
  export function PetSprite(props: PetSpriteProps): ReactPortal {
259
261
  const { snapshot, definition, display, feedback } = props
@@ -376,6 +378,10 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
376
378
  const animation = snapshot?.animation ?? 'idle'
377
379
  const scaleRef = useRef(spriteScale)
378
380
  scaleRef.current = spriteScale
381
+ // The frame the loop painted last. A settled non-looping track leaves the
382
+ // loop stopped, so a later scale change repaints it from here instead of
383
+ // waking the loop.
384
+ const paintedRef = useRef<{ row: number; col: number } | null>(null)
379
385
  useEffect(() => {
380
386
  if (props.visual !== undefined) return
381
387
  const reduceMotion = typeof window !== 'undefined'
@@ -398,35 +404,46 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
398
404
  const leadAnimation = sequence?.[0] ?? animation
399
405
  const row = rowOfTrack(leadAnimation)
400
406
  const track = trimTrack(tracks[leadAnimation], rows[row] ?? tracks[leadAnimation].frames.length)
407
+ // Write one frame's offset to the sprite element, skipping the assignment
408
+ // when the coordinates did not change. lastPosStr is the cache the whole
409
+ // loop shares, so a tick that changes nothing costs no style write.
410
+ let lastPosStr = ''
411
+ const paint = (frameRow: number, col: number): void => {
412
+ paintedRef.current = { row: frameRow, col }
413
+ const pos = framePosition(cell, frameRow, col, scaleRef.current)
414
+ const posStr = pos.x + 'px ' + pos.y + 'px'
415
+ if (posStr === lastPosStr) return
416
+ lastPosStr = posStr
417
+ if (spriteRef.current !== null) {
418
+ spriteRef.current.style.backgroundPosition = posStr
419
+ }
420
+ }
401
421
  // Paint one static sprite frame up front either way, so the pet is never
402
422
  // blank while the loop heat-up runs.
403
- const leadCol = track.frames[0]!
404
- const lead = framePosition(cell, row, leadCol, scaleRef.current)
405
- let lastPosStr = lead.x + 'px ' + lead.y + 'px'
406
- if (spriteRef.current !== null) {
407
- spriteRef.current.style.backgroundPosition = lastPosStr
408
- }
423
+ paint(row, track.frames[0]!)
409
424
  if (reduceMotion) return
410
- let raf = 0
425
+ let timer = 0
411
426
  let last = performance.now()
412
427
  let sequenceElapsed = 0
413
- const tick = (ts: number): void => {
414
- const delta = ts - last
415
- last = ts
428
+ // Sleep to the next frame boundary instead of waking on every screen
429
+ // refresh: track durations are 300-700 ms, so a 60 Hz loop spent the vast
430
+ // majority of its ticks proving that nothing had changed -- the same rule
431
+ // StatusOrnament already follows. A late wake (throttled tab, jank) still
432
+ // catches up every due frame, so the track keeps its own clock.
433
+ const schedule = (delay: number): void => {
434
+ timer = window.setTimeout(tick, Math.max(1, delay))
435
+ }
436
+ const tick = (): void => {
437
+ timer = 0
438
+ const now = performance.now()
439
+ const delta = now - last
440
+ last = now
416
441
  if (timeline !== undefined && sequenceItems !== undefined) {
417
442
  sequenceElapsed += delta
418
443
  const current = timeline.frameAt(sequenceElapsed)
419
444
  const item = sequenceItems.get(current.animation)!
420
- const col = item.track.frames[current.frameIndex]!
421
- const pos = framePosition(cell, item.row, col, scaleRef.current)
422
- const posStr = pos.x + 'px ' + pos.y + 'px'
423
- if (posStr !== lastPosStr) {
424
- lastPosStr = posStr
425
- if (spriteRef.current !== null) {
426
- spriteRef.current.style.backgroundPosition = posStr
427
- }
428
- }
429
- raf = requestAnimationFrame(tick)
445
+ paint(item.row, item.track.frames[current.frameIndex]!)
446
+ schedule(timeline.remainingAt(sequenceElapsed))
430
447
  return
431
448
  }
432
449
  // row/track come from the effect scope: they were computed once above
@@ -445,28 +462,33 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
445
462
  st.index += 1
446
463
  }
447
464
  if (st.elapsed >= (track.durations[st.index] ?? 0)) {
448
- if (track.loop) {
449
- st.elapsed = 0
450
- st.index = 0
451
- } else {
452
- st.index = maxIndex // hold the final frame; the host switches tracks
453
- }
454
- }
455
- const col = track.frames[st.index]!
456
- const pos = framePosition(cell, row, col, scaleRef.current)
457
- const posStr = pos.x + 'px ' + pos.y + 'px'
458
- if (posStr !== lastPosStr) {
459
- lastPosStr = posStr
460
- if (spriteRef.current !== null) {
461
- spriteRef.current.style.backgroundPosition = posStr
465
+ if (!track.loop) {
466
+ // Hold the final frame; the host owns the switch to the fallback, so
467
+ // stop scheduling instead of re-painting the same frame forever.
468
+ st.index = maxIndex
469
+ paint(row, track.frames[st.index]!)
470
+ return
462
471
  }
472
+ st.elapsed = 0
473
+ st.index = 0
463
474
  }
464
- raf = requestAnimationFrame(tick)
475
+ paint(row, track.frames[st.index]!)
476
+ schedule((track.durations[st.index] ?? 0) - st.elapsed)
465
477
  }
466
- raf = requestAnimationFrame(tick)
467
- return () => cancelAnimationFrame(raf)
478
+ schedule(0)
479
+ return () => window.clearTimeout(timer)
468
480
  }, [animation, phase, cell, columns, rows, tracks, sequences, props.visual])
469
481
 
482
+ // A stopped loop is woken by nothing, so a sprite scale change repaints the
483
+ // frame it settled on: without this a resized pet would keep the old scale's
484
+ // cell offsets and show a neighbouring cell until the track changed.
485
+ useLayoutEffect(() => {
486
+ const painted = paintedRef.current
487
+ if (props.visual !== undefined || painted === null || spriteRef.current === null) return
488
+ const pos = framePosition(cell, painted.row, painted.col, spriteScale)
489
+ spriteRef.current.style.backgroundPosition = pos.x + 'px ' + pos.y + 'px'
490
+ }, [spriteScale, cell, props.visual])
491
+
470
492
  // Auto-clear the feedback bubble after its CSS animation. The callback
471
493
  // rides a ref so re-renders never reset the timer: the 2s poll rebuilds
472
494
  // `props` every tick, and depending on it would starve the timeout.
@@ -496,10 +518,13 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
496
518
 
497
519
  const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>): void => {
498
520
  if (props.dragDisabled === true) return
521
+ // Read the live position before ending a walk: the walk keeps it in a ref
522
+ // rather than React state, so a drag grabbed mid-walk starts where the pet
523
+ // actually is instead of snapping back to where the walk began.
524
+ const current = walkTargetRef.current ?? dragPosRef.current ?? { right: display.right, bottom: display.bottom }
499
525
  endWalk(false)
500
526
  e.preventDefault()
501
527
  ;(e.target as HTMLElement).setPointerCapture?.(e.pointerId)
502
- const current = dragPos ?? { right: display.right, bottom: display.bottom }
503
528
  dragRef.current = { startX: e.clientX, startY: e.clientY, ...current }
504
529
  draggedRef.current = false
505
530
  setHovered(false)
@@ -524,10 +549,6 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
524
549
  if (dragPos !== null) props.onDragEnd(dragPos.right, dragPos.bottom)
525
550
  }
526
551
 
527
- const pos = dragPos ?? { right: display.right, bottom: display.bottom }
528
- const spriteWidth = Math.round(cell.width * spriteScale)
529
- const spriteHeight = Math.round(cell.height * spriteScale)
530
-
531
552
  // --- roaming ---------------------------------------------------------
532
553
  // The gameplay HUD rolls when the pet may wander; this side owns the motion
533
554
  // (clamped to the viewport), the walk art's facing and the persisted resting
@@ -536,10 +557,24 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
536
557
  // the side view); every other track stays unmirrored.
537
558
  const [facingRight, setFacingRight] = useState(false)
538
559
  const walkRafRef = useRef(0)
560
+ // Live position while a walk is in flight. The walk writes the element's
561
+ // right/bottom directly and mirrors them here instead of calling setState:
562
+ // a walk is 1-3 s of 60 fps motion, and each frame used to re-render the
563
+ // whole sprite tree (bubble stack, dock panel) for a position the DOM already
564
+ // knew. Keeping it in a ref means a render that lands mid-walk (a poll, a
565
+ // hover) still sees where the sprite actually is (issue #17).
539
566
  const walkTargetRef = useRef<{ right: number; bottom: number } | null>(null)
540
567
  const dragPosRef = useRef(dragPos)
541
568
  dragPosRef.current = dragPos
542
569
 
570
+ const pos = walkTargetRef.current ?? dragPos ?? { right: display.right, bottom: display.bottom }
571
+ // One integral cell size for the sprite box, the atlas grid and every frame
572
+ // offset: background-size is this size times the column/row count, so the
573
+ // scaled atlas shares a pixel grid with the box that shows one cell (#17).
574
+ const scaled = scaledCellSize(cell, spriteScale)
575
+ const spriteWidth = scaled.width
576
+ const spriteHeight = scaled.height
577
+
543
578
  /** Stop an active walk; `persist` lands the pet on the spot it reached. */
544
579
  const endWalk = (persist: boolean): void => {
545
580
  if (walkRafRef.current === 0) return
@@ -548,7 +583,12 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
548
583
  setFacingRight(false)
549
584
  const settled = walkTargetRef.current
550
585
  walkTargetRef.current = null
551
- if (persist && settled !== null) props.onDragEnd(settled.right, settled.bottom)
586
+ if (settled === null) return
587
+ // Hand the reached spot back to React state: the walk's own frames never
588
+ // updated it, and a render (or a drag that starts here) would otherwise
589
+ // put the sprite back where the walk began.
590
+ setDragPos(settled)
591
+ if (persist) props.onDragEnd(settled.right, settled.bottom)
552
592
  }
553
593
 
554
594
  useEffect(() => {
@@ -589,7 +629,15 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
589
629
  bottom: current.bottom + (target.bottom - current.bottom) * t,
590
630
  }
591
631
  walkTargetRef.current = next
592
- setDragPos(next)
632
+ // The position goes straight to the element: a walk is the one motion
633
+ // that moved every frame, and a setState here re-rendered the bubble
634
+ // stack and the dock panel for a value the DOM already knew (issue
635
+ // #17). React state takes over once, on the landing frame.
636
+ const el = floatRef.current
637
+ if (el !== null) {
638
+ el.style.right = next.right + 'px'
639
+ el.style.bottom = next.bottom + 'px'
640
+ }
593
641
  if (t < 1) {
594
642
  walkRafRef.current = window.requestAnimationFrame(step)
595
643
  return
@@ -597,6 +645,7 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
597
645
  walkRafRef.current = 0
598
646
  walkTargetRef.current = null
599
647
  setFacingRight(false)
648
+ setDragPos(next)
600
649
  props.onDragEnd(next.right, next.bottom)
601
650
  }
602
651
  walkRafRef.current = window.requestAnimationFrame(step)
@@ -736,7 +785,7 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
736
785
  ...(props.visual === undefined
737
786
  ? {
738
787
  backgroundImage: imageReady ? 'url(' + definition.atlasUrl + ')' : undefined,
739
- backgroundSize: (cell.width * columns * spriteScale) + 'px ' + (cell.height * (definition.atlasRows ?? rows.length) * spriteScale) + 'px',
788
+ backgroundSize: (scaled.width * columns) + 'px ' + (scaled.height * (definition.atlasRows ?? rows.length)) + 'px',
740
789
  backgroundRepeat: 'no-repeat',
741
790
  backgroundPosition: '0 0',
742
791
  }
@@ -25,6 +25,18 @@ describe('pet bubble typography (#1549)', () => {
25
25
  })
26
26
  })
27
27
 
28
+ describe('pet floating surfaces (issue #17)', () => {
29
+ it('keeps backdrop-filter off every surface that rides the sprite', () => {
30
+ // A blurred fixed layer makes the region behind it re-composite whenever
31
+ // the sprite animates or roams, and the blur runs on the CPU path under
32
+ // software compositing and power saving. Both the status bubble and the
33
+ // hover panel are 90%+ opaque, so the filter was invisible work. Comments
34
+ // are stripped first: the rules explain WHY the filter is gone.
35
+ const declared = css.replace(/\/\*[\s\S]*?\*\//g, '')
36
+ expect(declared).not.toContain('backdrop-filter')
37
+ })
38
+ })
39
+
28
40
  describe('pet hover panel css', () => {
29
41
  it('anchors the panel below the pet', () => {
30
42
  const panel = css.match(/\.panel\s*\{([^}]*)\}/)?.[1] ?? ''