@linxin666/dsh-pet 0.4.7 → 0.4.9

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.
Files changed (60) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +8 -2
  3. package/README.zh.md +8 -2
  4. package/contracts/voice-pack-v1.schema.json +27 -0
  5. package/lib/client.js +144 -68
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +160 -28
  8. package/lib/types/affinity.d.ts +26 -3
  9. package/lib/types/affinity.d.ts.map +1 -1
  10. package/lib/types/affinity.js +27 -4
  11. package/lib/types/client/PetDockEntry.d.ts +5 -0
  12. package/lib/types/client/PetDockEntry.d.ts.map +1 -1
  13. package/lib/types/client/PetDockEntry.js +1 -1
  14. package/lib/types/client/PetSprite.d.ts +11 -4
  15. package/lib/types/client/PetSprite.d.ts.map +1 -1
  16. package/lib/types/client/PetSprite.js +120 -58
  17. package/lib/types/client/index.d.ts.map +1 -1
  18. package/lib/types/client/index.js +15 -1
  19. package/lib/types/client/sequences.d.ts +9 -2
  20. package/lib/types/client/sequences.d.ts.map +1 -1
  21. package/lib/types/client/sequences.js +25 -14
  22. package/lib/types/client/spritesheet.d.ts +22 -1
  23. package/lib/types/client/spritesheet.d.ts.map +1 -1
  24. package/lib/types/client/spritesheet.js +26 -2
  25. package/lib/types/index.d.ts +1 -1
  26. package/lib/types/index.d.ts.map +1 -1
  27. package/lib/types/ledger.d.ts +10 -1
  28. package/lib/types/ledger.d.ts.map +1 -1
  29. package/lib/types/ledger.js +11 -1
  30. package/lib/types/pair-access.d.ts.map +1 -1
  31. package/lib/types/pair-access.js +26 -3
  32. package/lib/types/service.d.ts +14 -12
  33. package/lib/types/service.d.ts.map +1 -1
  34. package/lib/types/service.js +22 -17
  35. package/lib/types/voice-pack.d.ts +20 -1
  36. package/lib/types/voice-pack.d.ts.map +1 -1
  37. package/lib/types/voice-pack.js +86 -3
  38. package/package.json +24 -24
  39. package/src/affinity.test.ts +42 -0
  40. package/src/affinity.ts +46 -3
  41. package/src/client/PetDockEntry.tsx +6 -0
  42. package/src/client/PetSprite.test.tsx +304 -26
  43. package/src/client/PetSprite.tsx +123 -58
  44. package/src/client/index.test.tsx +4 -0
  45. package/src/client/index.ts +15 -1
  46. package/src/client/pet-css.test.ts +12 -0
  47. package/src/client/pet.module.css +9 -3
  48. package/src/client/sequences.test.ts +37 -1
  49. package/src/client/sequences.ts +42 -16
  50. package/src/client/spritesheet.test.ts +81 -0
  51. package/src/client/spritesheet.ts +27 -2
  52. package/src/index.ts +2 -0
  53. package/src/ledger.test.ts +19 -0
  54. package/src/ledger.ts +15 -1
  55. package/src/pair-access.ts +26 -3
  56. package/src/registry.test.ts +2 -1
  57. package/src/service.test.ts +61 -0
  58. package/src/service.ts +27 -18
  59. package/src/voice-pack.test.ts +112 -0
  60. package/src/voice-pack.ts +101 -3
@@ -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'
@@ -103,6 +103,11 @@ export interface PetSpriteProps {
103
103
  portalTarget?: Element
104
104
  /** Locale translate seat (namespace-bound). */
105
105
  t: TranslateNS<typeof NS>
106
+ /**
107
+ * Active UI locale id, used to pick a pet-declared English rank name
108
+ * (`rankEn`). Defaults to the document language for direct mounts/tests.
109
+ */
110
+ lang?: string
106
111
  }
107
112
 
108
113
  /** Clamp a drag offset inside the viewport with a margin. */
@@ -250,10 +255,12 @@ function UsageAnnouncementBubble(props: { announcement: PetAnnouncement }): Reac
250
255
  }
251
256
 
252
257
  /**
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).
258
+ * The floating pet. The spritesheet frame advances on a timer scheduled for the
259
+ * current frame's remaining time (per-frame durations come from the
260
+ * definition's tracks), so the loop wakes once per frame change instead of once
261
+ * per screen refresh; the atlas image is loaded once and the background
262
+ * position is written straight to the sprite element (no per-frame React
263
+ * state). Roaming writes the sprite's position the same way (issue #17).
257
264
  */
258
265
  export function PetSprite(props: PetSpriteProps): ReactPortal {
259
266
  const { snapshot, definition, display, feedback } = props
@@ -302,6 +309,21 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
302
309
  const panel = definition.panel
303
310
  const panelLabel = (slot: 'feed' | 'rename' | 'hide' | 'confirm', i18n: string): string =>
304
311
  panel?.labels?.[slot] ?? i18n
312
+ // The active rank name is display-only: a pet-declared ladder may carry an
313
+ // English variant, while built-in names still resolve through the i18n
314
+ // dictionary. `lang` is handed down by the mount; the document language is
315
+ // the direct-mount/test fallback.
316
+ const englishUi = (props.lang ?? (typeof document === 'undefined' ? 'zh' : document.documentElement.lang))
317
+ .toLowerCase()
318
+ .startsWith('en')
319
+ const rankNameOf = (): string => {
320
+ const rawRank = snapshot?.affinity.rank ?? '?'
321
+ const rankEn = snapshot?.affinity.rankEn
322
+ if (englishUi && rankEn !== undefined) return rankEn
323
+ const rankKey = `pet.rank.name.${rawRank}`
324
+ const localized = props.t(rankKey as never)
325
+ return localized !== rankKey ? localized : rawRank
326
+ }
305
327
  const panelStat = (
306
328
  slot: 'rank' | 'treats' | 'points',
307
329
  i18nKey: 'pet.rank' | 'pet.treats' | 'pet.points',
@@ -312,8 +334,10 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
312
334
  // The host whitelists {rank}/{n}/{points} in every stat slot, so a pack
313
335
  // format may reference any of them; substitute all three live values
314
336
  // (the slot's own value plus the siblings) instead of only the slot's.
337
+ // {rank} carries the effective name, so a pet ladder's English variant
338
+ // also reaches a custom stat format.
315
339
  const all: Record<string, string | number> = {
316
- rank: snapshot?.affinity.rank ?? '?',
340
+ rank: values.rank !== undefined ? values.rank : rankNameOf(),
317
341
  n: snapshot?.treats.stocked ?? 0,
318
342
  points: snapshot?.affinity.points ?? 0,
319
343
  }
@@ -376,6 +400,10 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
376
400
  const animation = snapshot?.animation ?? 'idle'
377
401
  const scaleRef = useRef(spriteScale)
378
402
  scaleRef.current = spriteScale
403
+ // The frame the loop painted last. A settled non-looping track leaves the
404
+ // loop stopped, so a later scale change repaints it from here instead of
405
+ // waking the loop.
406
+ const paintedRef = useRef<{ row: number; col: number } | null>(null)
379
407
  useEffect(() => {
380
408
  if (props.visual !== undefined) return
381
409
  const reduceMotion = typeof window !== 'undefined'
@@ -398,35 +426,46 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
398
426
  const leadAnimation = sequence?.[0] ?? animation
399
427
  const row = rowOfTrack(leadAnimation)
400
428
  const track = trimTrack(tracks[leadAnimation], rows[row] ?? tracks[leadAnimation].frames.length)
429
+ // Write one frame's offset to the sprite element, skipping the assignment
430
+ // when the coordinates did not change. lastPosStr is the cache the whole
431
+ // loop shares, so a tick that changes nothing costs no style write.
432
+ let lastPosStr = ''
433
+ const paint = (frameRow: number, col: number): void => {
434
+ paintedRef.current = { row: frameRow, col }
435
+ const pos = framePosition(cell, frameRow, col, scaleRef.current)
436
+ const posStr = pos.x + 'px ' + pos.y + 'px'
437
+ if (posStr === lastPosStr) return
438
+ lastPosStr = posStr
439
+ if (spriteRef.current !== null) {
440
+ spriteRef.current.style.backgroundPosition = posStr
441
+ }
442
+ }
401
443
  // Paint one static sprite frame up front either way, so the pet is never
402
444
  // 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
- }
445
+ paint(row, track.frames[0]!)
409
446
  if (reduceMotion) return
410
- let raf = 0
447
+ let timer = 0
411
448
  let last = performance.now()
412
449
  let sequenceElapsed = 0
413
- const tick = (ts: number): void => {
414
- const delta = ts - last
415
- last = ts
450
+ // Sleep to the next frame boundary instead of waking on every screen
451
+ // refresh: track durations are 300-700 ms, so a 60 Hz loop spent the vast
452
+ // majority of its ticks proving that nothing had changed -- the same rule
453
+ // StatusOrnament already follows. A late wake (throttled tab, jank) still
454
+ // catches up every due frame, so the track keeps its own clock.
455
+ const schedule = (delay: number): void => {
456
+ timer = window.setTimeout(tick, Math.max(1, delay))
457
+ }
458
+ const tick = (): void => {
459
+ timer = 0
460
+ const now = performance.now()
461
+ const delta = now - last
462
+ last = now
416
463
  if (timeline !== undefined && sequenceItems !== undefined) {
417
464
  sequenceElapsed += delta
418
465
  const current = timeline.frameAt(sequenceElapsed)
419
466
  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)
467
+ paint(item.row, item.track.frames[current.frameIndex]!)
468
+ schedule(timeline.remainingAt(sequenceElapsed))
430
469
  return
431
470
  }
432
471
  // row/track come from the effect scope: they were computed once above
@@ -445,28 +484,33 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
445
484
  st.index += 1
446
485
  }
447
486
  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
487
+ if (!track.loop) {
488
+ // Hold the final frame; the host owns the switch to the fallback, so
489
+ // stop scheduling instead of re-painting the same frame forever.
490
+ st.index = maxIndex
491
+ paint(row, track.frames[st.index]!)
492
+ return
462
493
  }
494
+ st.elapsed = 0
495
+ st.index = 0
463
496
  }
464
- raf = requestAnimationFrame(tick)
497
+ paint(row, track.frames[st.index]!)
498
+ schedule((track.durations[st.index] ?? 0) - st.elapsed)
465
499
  }
466
- raf = requestAnimationFrame(tick)
467
- return () => cancelAnimationFrame(raf)
500
+ schedule(0)
501
+ return () => window.clearTimeout(timer)
468
502
  }, [animation, phase, cell, columns, rows, tracks, sequences, props.visual])
469
503
 
504
+ // A stopped loop is woken by nothing, so a sprite scale change repaints the
505
+ // frame it settled on: without this a resized pet would keep the old scale's
506
+ // cell offsets and show a neighbouring cell until the track changed.
507
+ useLayoutEffect(() => {
508
+ const painted = paintedRef.current
509
+ if (props.visual !== undefined || painted === null || spriteRef.current === null) return
510
+ const pos = framePosition(cell, painted.row, painted.col, spriteScale)
511
+ spriteRef.current.style.backgroundPosition = pos.x + 'px ' + pos.y + 'px'
512
+ }, [spriteScale, cell, props.visual])
513
+
470
514
  // Auto-clear the feedback bubble after its CSS animation. The callback
471
515
  // rides a ref so re-renders never reset the timer: the 2s poll rebuilds
472
516
  // `props` every tick, and depending on it would starve the timeout.
@@ -496,10 +540,13 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
496
540
 
497
541
  const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>): void => {
498
542
  if (props.dragDisabled === true) return
543
+ // Read the live position before ending a walk: the walk keeps it in a ref
544
+ // rather than React state, so a drag grabbed mid-walk starts where the pet
545
+ // actually is instead of snapping back to where the walk began.
546
+ const current = walkTargetRef.current ?? dragPosRef.current ?? { right: display.right, bottom: display.bottom }
499
547
  endWalk(false)
500
548
  e.preventDefault()
501
549
  ;(e.target as HTMLElement).setPointerCapture?.(e.pointerId)
502
- const current = dragPos ?? { right: display.right, bottom: display.bottom }
503
550
  dragRef.current = { startX: e.clientX, startY: e.clientY, ...current }
504
551
  draggedRef.current = false
505
552
  setHovered(false)
@@ -524,10 +571,6 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
524
571
  if (dragPos !== null) props.onDragEnd(dragPos.right, dragPos.bottom)
525
572
  }
526
573
 
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
574
  // --- roaming ---------------------------------------------------------
532
575
  // The gameplay HUD rolls when the pet may wander; this side owns the motion
533
576
  // (clamped to the viewport), the walk art's facing and the persisted resting
@@ -536,10 +579,24 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
536
579
  // the side view); every other track stays unmirrored.
537
580
  const [facingRight, setFacingRight] = useState(false)
538
581
  const walkRafRef = useRef(0)
582
+ // Live position while a walk is in flight. The walk writes the element's
583
+ // right/bottom directly and mirrors them here instead of calling setState:
584
+ // a walk is 1-3 s of 60 fps motion, and each frame used to re-render the
585
+ // whole sprite tree (bubble stack, dock panel) for a position the DOM already
586
+ // knew. Keeping it in a ref means a render that lands mid-walk (a poll, a
587
+ // hover) still sees where the sprite actually is (issue #17).
539
588
  const walkTargetRef = useRef<{ right: number; bottom: number } | null>(null)
540
589
  const dragPosRef = useRef(dragPos)
541
590
  dragPosRef.current = dragPos
542
591
 
592
+ const pos = walkTargetRef.current ?? dragPos ?? { right: display.right, bottom: display.bottom }
593
+ // One integral cell size for the sprite box, the atlas grid and every frame
594
+ // offset: background-size is this size times the column/row count, so the
595
+ // scaled atlas shares a pixel grid with the box that shows one cell (#17).
596
+ const scaled = scaledCellSize(cell, spriteScale)
597
+ const spriteWidth = scaled.width
598
+ const spriteHeight = scaled.height
599
+
543
600
  /** Stop an active walk; `persist` lands the pet on the spot it reached. */
544
601
  const endWalk = (persist: boolean): void => {
545
602
  if (walkRafRef.current === 0) return
@@ -548,7 +605,12 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
548
605
  setFacingRight(false)
549
606
  const settled = walkTargetRef.current
550
607
  walkTargetRef.current = null
551
- if (persist && settled !== null) props.onDragEnd(settled.right, settled.bottom)
608
+ if (settled === null) return
609
+ // Hand the reached spot back to React state: the walk's own frames never
610
+ // updated it, and a render (or a drag that starts here) would otherwise
611
+ // put the sprite back where the walk began.
612
+ setDragPos(settled)
613
+ if (persist) props.onDragEnd(settled.right, settled.bottom)
552
614
  }
553
615
 
554
616
  useEffect(() => {
@@ -589,7 +651,15 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
589
651
  bottom: current.bottom + (target.bottom - current.bottom) * t,
590
652
  }
591
653
  walkTargetRef.current = next
592
- setDragPos(next)
654
+ // The position goes straight to the element: a walk is the one motion
655
+ // that moved every frame, and a setState here re-rendered the bubble
656
+ // stack and the dock panel for a value the DOM already knew (issue
657
+ // #17). React state takes over once, on the landing frame.
658
+ const el = floatRef.current
659
+ if (el !== null) {
660
+ el.style.right = next.right + 'px'
661
+ el.style.bottom = next.bottom + 'px'
662
+ }
593
663
  if (t < 1) {
594
664
  walkRafRef.current = window.requestAnimationFrame(step)
595
665
  return
@@ -597,6 +667,7 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
597
667
  walkRafRef.current = 0
598
668
  walkTargetRef.current = null
599
669
  setFacingRight(false)
670
+ setDragPos(next)
600
671
  props.onDragEnd(next.right, next.bottom)
601
672
  }
602
673
  walkRafRef.current = window.requestAnimationFrame(step)
@@ -736,7 +807,7 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
736
807
  ...(props.visual === undefined
737
808
  ? {
738
809
  backgroundImage: imageReady ? 'url(' + definition.atlasUrl + ')' : undefined,
739
- backgroundSize: (cell.width * columns * spriteScale) + 'px ' + (cell.height * (definition.atlasRows ?? rows.length) * spriteScale) + 'px',
810
+ backgroundSize: (scaled.width * columns) + 'px ' + (scaled.height * (definition.atlasRows ?? rows.length)) + 'px',
740
811
  backgroundRepeat: 'no-repeat',
741
812
  backgroundPosition: '0 0',
742
813
  }
@@ -918,13 +989,7 @@ export function PetSprite(props: PetSpriteProps): ReactPortal {
918
989
  <div className={styles.rankRow}>
919
990
  <span className={styles.nameCell}>{displayName}</span>
920
991
  <span className={styles.statRank}>
921
- {(() => {
922
- const rawRank = snapshot?.affinity.rank ?? '?'
923
- const rankKey = `pet.rank.name.${rawRank}`
924
- const localized = props.t(rankKey as any)
925
- const rankName = localized !== rankKey ? localized : rawRank
926
- return panelStat('rank', 'pet.rank', { rank: rankName })
927
- })()}
992
+ {panelStat('rank', 'pet.rank', { rank: rankNameOf() })}
928
993
  </span>
929
994
  </div>
930
995
  <div className={styles.rankRow}>
@@ -180,6 +180,10 @@ function fakeContext(options: FakeContextOptions = {}): FakeClientLifecycle {
180
180
  localeSeats.push(namespace)
181
181
  return (key: string) => 'seat:' + key
182
182
  },
183
+ // The mount reads the active locale for a pet-declared English rank
184
+ // name and re-renders on a switch; this stub pins the zh default.
185
+ getLocale: () => ({ active: 'zh', locales: [], revision: 0 }),
186
+ subscribe: () => () => {},
183
187
  },
184
188
  // The family binder is optional (dsh-web-settings may be absent); both
185
189
  // answers are the shared per-entry form of this plugin's own profile entry.
@@ -662,7 +662,20 @@ export function apply(ctx: ClientContext): void {
662
662
  // the 'pet' namespace instead follows the active language, the English
663
663
  // fallback, and every language pack that registers a dictionary for it
664
664
  // (the settings section label already resolves through the same seat).
665
- petRoot.render(createElement(PetDockEntry, { ...injected(), t: ctx.locale.bind(NS), portalTarget: container }))
665
+ const renderPet = (): void => {
666
+ petRoot.render(createElement(PetDockEntry, {
667
+ ...injected(),
668
+ t: ctx.locale.bind(NS),
669
+ // The active locale rides the same mount as the translate seat so a
670
+ // pet-declared English rank name follows the UI language.
671
+ lang: ctx.locale.getLocale().active,
672
+ portalTarget: container,
673
+ }))
674
+ }
675
+ renderPet()
676
+ // Re-render on a language switch instead of waiting for the next poll
677
+ // tick: the declared rank ladder's nameEn applies immediately.
678
+ const unsubscribeLocale = ctx.locale.subscribe(renderPet)
666
679
 
667
680
  let uiGone = false
668
681
  disposeUi = () => {
@@ -670,6 +683,7 @@ export function apply(ctx: ClientContext): void {
670
683
  uiGone = true
671
684
  clearUiTeardown?.()
672
685
  clearUiTeardown = undefined
686
+ unsubscribeLocale()
673
687
  petRoot.unmount()
674
688
  container.remove()
675
689
  disposePoll()
@@ -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] ?? ''
@@ -63,7 +63,10 @@
63
63
  0 4px 12px rgba(2, 6, 23, 0.35),
64
64
  inset 0 1px 0 rgba(226, 232, 255, 0.1),
65
65
  0 0 12px rgba(77, 107, 254, 0.18);
66
- backdrop-filter: blur(8px);
66
+ /* No backdrop-filter (issue #17): the glass is 90-94% opaque, so the blur was
67
+ invisible while forcing this permanently-mounted layer to re-composite the
68
+ page behind it on every sprite frame change; a blurred fixed layer costs
69
+ CPU on software-compositing and power-saving paths. */
67
70
  letter-spacing: 0.02em;
68
71
  animation: pet-bubble-in 240ms ease-out;
69
72
  }
@@ -242,7 +245,8 @@
242
245
  0 8px 24px rgba(2, 6, 23, 0.45),
243
246
  0 0 0 1px rgba(77, 107, 254, 0.1),
244
247
  inset 0 1px 0 rgba(226, 232, 255, 0.08);
245
- backdrop-filter: blur(10px);
248
+ /* No backdrop-filter (issue #17): at 95-97% opacity the blur never showed,
249
+ and the panel overlaid the sprite's own animation while it was open. */
246
250
  display: flex;
247
251
  flex-direction: column;
248
252
  gap: 7px;
@@ -657,7 +661,9 @@
657
661
  0 4px 12px rgba(2, 6, 23, 0.35),
658
662
  inset 0 1px 0 rgba(226, 232, 255, 0.1),
659
663
  0 0 12px rgba(77, 107, 254, 0.18);
660
- backdrop-filter: blur(8px);
664
+ /* No backdrop-filter (issue #17), same reason as .bubbleStatus: a 92-95%
665
+ opaque pill gains nothing visible from the blur but pays for the filter on
666
+ every frame the pet animates. */
661
667
  letter-spacing: 0.02em;
662
668
  animation: pet-usage-in 280ms cubic-bezier(0.22, 1, 0.36, 1);
663
669
  }
@@ -36,7 +36,7 @@ describe('createSequenceTimeline', () => {
36
36
  const sequence: PetAnimation[] = ['running', 'waiting']
37
37
 
38
38
  it('resolves identically to the per-call helper at animation-sample elapsed values', () => {
39
- // The sprite frame loop asks once per rAF tick with accumulated
39
+ // The sprite frame loop asks once per frame tick with accumulated
40
40
  // millisecond offsets; the precomputed table must agree everywhere.
41
41
  const timeline = createSequenceTimeline(sequence, tracks)
42
42
  for (let elapsed = 0; elapsed <= 1_500; elapsed += 7) {
@@ -51,3 +51,39 @@ describe('createSequenceTimeline', () => {
51
51
  expect(timeline.frameAt(1_420)).toEqual({ animation: 'running', frameIndex: 0 })
52
52
  })
53
53
  })
54
+
55
+ describe('SequenceTimeline.remainingAt (issue #17)', () => {
56
+ const sequence: PetAnimation[] = ['running', 'waiting']
57
+
58
+ it('reports the time left in the frame the query lands on', () => {
59
+ const timeline = createSequenceTimeline(sequence, tracks)
60
+ // running frames are 100ms then 200ms, waiting 300ms then 100ms.
61
+ expect(timeline.remainingAt(0)).toBe(100)
62
+ expect(timeline.remainingAt(40)).toBe(60)
63
+ expect(timeline.remainingAt(100)).toBe(200)
64
+ expect(timeline.remainingAt(299)).toBe(1)
65
+ // The second item's first frame, measured from the item boundary.
66
+ expect(timeline.remainingAt(300)).toBe(300)
67
+ expect(timeline.remainingAt(600)).toBe(100)
68
+ })
69
+
70
+ it('accounts for a loop wrap without overshooting', () => {
71
+ const timeline = createSequenceTimeline(sequence, tracks)
72
+ // 700ms is one full sequence: the wrap lands on running frame 0 again.
73
+ expect(timeline.frameAt(700)).toEqual({ animation: 'running', frameIndex: 0 })
74
+ expect(timeline.remainingAt(700)).toBe(100)
75
+ expect(timeline.remainingAt(750)).toBe(50)
76
+ })
77
+
78
+ it('steps over a zero-length frame instead of reporting a zero delay', () => {
79
+ const zeroTracks = {
80
+ running: track([0, 200]),
81
+ waiting: track([100]),
82
+ } as Record<PetAnimation, PetTrackDef>
83
+ const timeline = createSequenceTimeline(sequence, zeroTracks)
84
+ // The loop schedules its next wake from this value, so a zero-duration
85
+ // frame must resolve to the next real frame rather than to a 0ms timer.
86
+ expect(timeline.remainingAt(0)).toBe(200)
87
+ expect(timeline.remainingAt(200)).toBe(100)
88
+ })
89
+ })
@@ -10,11 +10,26 @@ export interface SequenceFrame {
10
10
 
11
11
  /**
12
12
  * Precomputed timeline for one looping sequence: the per-item duration table
13
- * is built once instead of per query. The sprite frame loop asks at
14
- * animation rate (~60 Hz), where the per-call map/reduce is pure waste.
13
+ * is built once instead of per query. The sprite frame loop asks once per
14
+ * frame change, where the per-call map/reduce is pure waste.
15
15
  */
16
16
  export interface SequenceTimeline {
17
17
  frameAt(elapsedMs: number): SequenceFrame
18
+ /**
19
+ * Milliseconds from `elapsedMs` until the frame it lands on ends. The sprite
20
+ * loop sleeps for exactly this long instead of polling at the screen refresh
21
+ * rate (issue #17); the floor of 1 ms keeps a zero-length frame from turning
22
+ * into a busy timer.
23
+ */
24
+ remainingAt(elapsedMs: number): number
25
+ }
26
+
27
+ /** One sequence position, with the residual offset inside its own frame. */
28
+ interface SequencePoint {
29
+ animation: PetAnimation
30
+ track: PetTrackDef
31
+ frameIndex: number
32
+ offsetInFrame: number
18
33
  }
19
34
 
20
35
  /** Build a {@link SequenceTimeline} over one manifest sequence. */
@@ -24,22 +39,33 @@ export function createSequenceTimeline(
24
39
  ): SequenceTimeline {
25
40
  const itemDurations = sequence.map(animation => tracks[animation].durations.reduce((sum, value) => sum + value, 0))
26
41
  const sequenceDuration = itemDurations.reduce((sum, value) => sum + value, 0)
42
+ // One traversal serves both queries: frameAt needs the index it lands on and
43
+ // remainingAt needs how far into that frame it is, so resolving them
44
+ // separately would walk the same tables twice for one loop tick.
45
+ const locate = (elapsedMs: number): SequencePoint => {
46
+ let offset = sequenceDuration > 0 ? Math.max(0, elapsedMs) % sequenceDuration : 0
47
+ let itemIndex = 0
48
+ while (itemIndex < sequence.length - 1 && offset >= itemDurations[itemIndex]!) {
49
+ offset -= itemDurations[itemIndex]!
50
+ itemIndex += 1
51
+ }
52
+ const animation = sequence[itemIndex]!
53
+ const track = tracks[animation]
54
+ let frameIndex = 0
55
+ while (frameIndex < track.frames.length - 1 && offset >= track.durations[frameIndex]!) {
56
+ offset -= track.durations[frameIndex]!
57
+ frameIndex += 1
58
+ }
59
+ return { animation, track, frameIndex, offsetInFrame: offset }
60
+ }
27
61
  return {
28
62
  frameAt(elapsedMs: number): SequenceFrame {
29
- let offset = Math.max(0, elapsedMs) % sequenceDuration
30
- let itemIndex = 0
31
- while (itemIndex < sequence.length - 1 && offset >= itemDurations[itemIndex]!) {
32
- offset -= itemDurations[itemIndex]!
33
- itemIndex += 1
34
- }
35
- const animation = sequence[itemIndex]!
36
- const track = tracks[animation]
37
- let frameIndex = 0
38
- while (frameIndex < track.frames.length - 1 && offset >= track.durations[frameIndex]!) {
39
- offset -= track.durations[frameIndex]!
40
- frameIndex += 1
41
- }
42
- return { animation, frameIndex }
63
+ const point = locate(elapsedMs)
64
+ return { animation: point.animation, frameIndex: point.frameIndex }
65
+ },
66
+ remainingAt(elapsedMs: number): number {
67
+ const point = locate(elapsedMs)
68
+ return Math.max(1, (point.track.durations[point.frameIndex] ?? 0) - point.offsetInFrame)
43
69
  },
44
70
  }
45
71
  }
@@ -0,0 +1,81 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import type { PetCell } from '../registry.ts'
3
+ import { framePosition, scaledCellSize, trimTrack } from './spritesheet.ts'
4
+
5
+ /** The built-in hatch-pet cell (192 x 208). */
6
+ const CELL: PetCell = { width: 192, height: 208 }
7
+
8
+ /** The whale-girl display: `display.size` 160 over a 208px-tall cell. */
9
+ const SCALE = 160 / CELL.height
10
+
11
+ describe('scaledCellSize (issue #17)', () => {
12
+ it('rounds the scaled cell so a fractional sprite scale stays on whole pixels', () => {
13
+ // 192 * 160/208 = 147.69px and 208 * 160/208 = 160px before rounding.
14
+ expect(scaledCellSize(CELL, SCALE)).toEqual({ width: 148, height: 160 })
15
+ })
16
+
17
+ it('agrees with the sprite box the component renders for the same scale', () => {
18
+ // The element is sized from the same helper, so a cell of the scaled atlas
19
+ // and the box that shows it are the same rectangle instead of drifting by
20
+ // a fraction of a pixel per frame.
21
+ const scaled = scaledCellSize(CELL, SCALE)
22
+ expect(Math.round(CELL.width * SCALE)).toBe(scaled.width)
23
+ expect(Math.round(CELL.height * SCALE)).toBe(scaled.height)
24
+ })
25
+
26
+ it('floors a collapsed cell at one pixel instead of rendering nothing', () => {
27
+ expect(scaledCellSize(CELL, 0.001)).toEqual({ width: 1, height: 1 })
28
+ })
29
+ })
30
+
31
+ describe('framePosition (issue #17)', () => {
32
+ it('places every column on an exact multiple of the scaled cell width', () => {
33
+ const scaled = scaledCellSize(CELL, SCALE)
34
+ for (let col = 0; col < 8; col += 1) {
35
+ const pos = framePosition(CELL, 0, col, SCALE)
36
+ expect(pos.x).toBe(-col * scaled.width)
37
+ expect(Number.isInteger(pos.x)).toBe(true)
38
+ // Row 0 is the top of the atlas; the offset is -0, which is still whole.
39
+ expect(Math.abs(pos.y)).toBe(0)
40
+ }
41
+ })
42
+
43
+ it('places every row on an exact multiple of the scaled cell height', () => {
44
+ const scaled = scaledCellSize(CELL, SCALE)
45
+ for (let row = 0; row < 9; row += 1) {
46
+ const pos = framePosition(CELL, row, 0, SCALE)
47
+ expect(pos.y).toBe(-row * scaled.height)
48
+ expect(Number.isInteger(pos.y)).toBe(true)
49
+ expect(Math.abs(pos.x)).toBe(0)
50
+ }
51
+ })
52
+
53
+ it('never returns a fractional offset at a scale that does not divide the cell', () => {
54
+ // 120/208 leaves 110.77px cells: the old formula returned -110.77px per
55
+ // column, which is what forced the compositor to resample the atlas.
56
+ const scale = 120 / CELL.height
57
+ const scaled = scaledCellSize(CELL, scale)
58
+ expect(scaled).toEqual({ width: 111, height: 120 })
59
+ expect(framePosition(CELL, 5, 7, scale)).toEqual({ x: -7 * 111, y: -5 * 120 })
60
+ })
61
+
62
+ it('keeps the raw atlas grid when no scale is applied', () => {
63
+ expect(framePosition(CELL, 3, 5)).toEqual({ x: -5 * CELL.width, y: -3 * CELL.height })
64
+ })
65
+ })
66
+
67
+ describe('trimTrack', () => {
68
+ it('trims to the smaller of the track table and the row frame count', () => {
69
+ const track = { frames: [0, 1, 2, 3, 4, 5], durations: [1, 2, 3, 4, 5, 6], loop: true }
70
+ expect(trimTrack(track, 4)).toEqual({
71
+ frames: [0, 1, 2, 3],
72
+ durations: [1, 2, 3, 4],
73
+ loop: true,
74
+ })
75
+ })
76
+
77
+ it('degrades a row with no detected frames to the first frame', () => {
78
+ const track = { frames: [0, 1], durations: [10, 20], loop: false, fallback: 'idle' as const }
79
+ expect(trimTrack(track, 0)).toEqual({ frames: [0], durations: [10], loop: false, fallback: 'idle' })
80
+ })
81
+ })
@@ -19,15 +19,40 @@ export function rowOfTrack(animation: PetAnimation): number {
19
19
  return rowOf(animation)
20
20
  }
21
21
 
22
+ /**
23
+ * Integer size of one cell after `scale`, in device-independent px.
24
+ *
25
+ * Rounding happens here, once, so the rendered atlas grid is integral end to
26
+ * end (issue #17): `background-size` is this size times the column/row count
27
+ * and every frame offset is an exact multiple of it. A fractional cell size
28
+ * leaves each frame on a sub-pixel boundary — 192px cells at `display.size`
29
+ * 160 scale to 147.69px — and the compositor then has to resample the whole
30
+ * scaled atlas on every frame change instead of translating an already-scaled
31
+ * bitmap by whole pixels. The pet advances a frame every 300-700 ms, so that
32
+ * resample was running continuously for a background surface the size of the
33
+ * sprite. A floor of 1px keeps a legally tiny display.size from collapsing the
34
+ * cell to zero and rendering nothing.
35
+ */
36
+ export function scaledCellSize(cell: PetCell, scale: number): { width: number; height: number } {
37
+ return {
38
+ width: Math.max(1, Math.round(cell.width * scale)),
39
+ height: Math.max(1, Math.round(cell.height * scale)),
40
+ }
41
+ }
42
+
22
43
  /**
23
44
  * Background-position (px) of one frame cell within the scaled atlas.
24
45
  * The background image is scaled by `scale` (element size ÷ cell size), and
25
46
  * background-position offsets are applied in SCALED coordinates — using raw
26
47
  * atlas coordinates here would drift each frame by the scale factor and
27
- * render torn/overlapping frames.
48
+ * render torn/overlapping frames. The scaled cell is quantized by
49
+ * {@link scaledCellSize}, so the offset of frame N is exactly N whole cells:
50
+ * the atlas is snapped to the pixel grid and a frame change is a plain
51
+ * translate of the scaled bitmap.
28
52
  */
29
53
  export function framePosition(cell: PetCell, row: number, col: number, scale = 1): { x: number; y: number } {
30
- return { x: -col * cell.width * scale, y: -row * cell.height * scale }
54
+ const scaled = scaledCellSize(cell, scale)
55
+ return { x: -col * scaled.width, y: -row * scaled.height }
31
56
  }
32
57
 
33
58
  /**