Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

Address PET review summary follow-ups

JeffreyDeng-speca6e06c84492b
diff --git a/src/web/src/components/home-pet/cloud-code-monster-pet-drag.ts b/src/web/src/components/home-pet/cloud-code-monster-pet-drag.ts
new file mode 100644
index 000000000..028ee2c0c
--- /dev/null
+++ b/src/web/src/components/home-pet/cloud-code-monster-pet-drag.ts
@@ -0,0 +1,319 @@
+"use client";
+
+import {
+ type Dispatch,
+ type MutableRefObject,
+ type PointerEvent as ReactPointerEvent,
+ type RefObject,
+ type SetStateAction,
+ useCallback,
+ useRef,
+} from "react";
+
+import {
+ calculateMonsterWalkIntensity,
+ clampPetPosition,
+ getBounds,
+ getMonsterFootstepIntervalMs,
+ hasViolentMonsterDirectionChange,
+ isMonsterFaintShakeEvent,
+ isViolentMonsterDrag,
+ shouldFaintFromMonsterShake,
+} from "./cloud-code-monster-pet-activity";
+import {
+ CLOUD_CODE_MONSTER_FAINT_EVENT_WINDOW_MS,
+ CLOUD_CODE_MONSTER_SIZE,
+} from "./cloud-code-monster-pet-constants";
+import type {
+ PetPoint,
+ StoredCloudCodeMonsterActivity,
+} from "./cloud-code-monster-pet-types";
+
+type PetDragTimerKey = "faint" | "notification" | "walkSettle";
+
+type UsePetDragParams = {
+ boundaryRef: RefObject<HTMLElement | null>;
+ initialPosition?: PetPoint;
+ position: PetPoint | null;
+ isDragging: boolean;
+ fainted: boolean;
+ activityState: StoredCloudCodeMonsterActivity | null;
+ lastFootstepAtRef: MutableRefObject<number>;
+ violentDragEventsRef: MutableRefObject<number[]>;
+ setIsDragging: Dispatch<SetStateAction<boolean>>;
+ setNotificationActive: Dispatch<SetStateAction<boolean>>;
+ setFainted: Dispatch<SetStateAction<boolean>>;
+ setWalkDirection: Dispatch<SetStateAction<"left" | "right">>;
+ setWalkIntensity: Dispatch<SetStateAction<number>>;
+ setPosition: Dispatch<SetStateAction<PetPoint | null>>;
+ clearPetTimer: (key: PetDragTimerKey) => void;
+ setPetTimer: (
+ key: PetDragTimerKey,
+ callback: () => void,
+ delayMs: number
+ ) => void;
+ pushFootprint: (nextPosition: PetPoint, intensity: number) => void;
+ stopTemporaryMotion: () => void;
+ wakeMonsterToDefault: () => void;
+ startShockReaction: () => void;
+ startShakeReaction: () => void;
+ startFaintReaction: () => void;
+};
+
+function getPointerPoint(
+ event: ReactPointerEvent<HTMLButtonElement>,
+ boundary: HTMLElement | null
+): PetPoint {
+ const boundaryRect = boundary?.getBoundingClientRect();
+
+ return {
+ x: event.clientX - (boundaryRect?.left ?? 0),
+ y: event.clientY - (boundaryRect?.top ?? 0),
+ };
+}
+
+export function usePetDrag({
+ boundaryRef,
+ initialPosition,
+ position,
+ isDragging,
+ fainted,
+ activityState,
+ lastFootstepAtRef,
+ violentDragEventsRef,
+ setIsDragging,
+ setNotificationActive,
+ setFainted,
+ setWalkDirection,
+ setWalkIntensity,
+ setPosition,
+ clearPetTimer,
+ setPetTimer,
+ pushFootprint,
+ stopTemporaryMotion,
+ wakeMonsterToDefault,
+ startShockReaction,
+ startShakeReaction,
+ startFaintReaction,
+}: UsePetDragParams) {
+ const dragOffsetRef = useRef<PetPoint>({ x: 0, y: 0 });
+ const dragStartPointRef = useRef<PetPoint | null>(null);
+ const lastPointerRef = useRef<{ point: PetPoint; time: number } | null>(null);
+ const lastDragDeltaRef = useRef<PetPoint | null>(null);
+ const didDragRef = useRef(false);
+
+ const handlePetClick = useCallback(() => {
+ stopTemporaryMotion();
+ setNotificationActive(false);
+ clearPetTimer("notification");
+
+ if (didDragRef.current) {
+ didDragRef.current = false;
+ return;
+ }
+
+ if (isDragging) {
+ return;
+ }
+
+ if (activityState?.activityId) {
+ wakeMonsterToDefault();
+ }
+
+ if (fainted) {
+ setFainted(false);
+ clearPetTimer("faint");
+ }
+
+ startShockReaction();
+ }, [
+ activityState?.activityId,
+ clearPetTimer,
+ fainted,
+ isDragging,
+ setFainted,
+ setNotificationActive,
+ startShockReaction,
+ stopTemporaryMotion,
+ wakeMonsterToDefault,
+ ]);
+
+ const handlePointerDown = useCallback(
+ (event: ReactPointerEvent<HTMLButtonElement>) => {
+ if (event.button !== 0) {
+ return;
+ }
+
+ const bounds = getBounds(boundaryRef.current);
+ const currentPosition =
+ position ??
+ clampPetPosition(
+ initialPosition ?? {
+ x: bounds.width - CLOUD_CODE_MONSTER_SIZE.width - 112,
+ y: bounds.height * 0.48,
+ },
+ bounds,
+ CLOUD_CODE_MONSTER_SIZE
+ );
+ const pointerPoint = getPointerPoint(event, boundaryRef.current);
+ const now = performance.now();
+
+ dragOffsetRef.current = {
+ x: pointerPoint.x - currentPosition.x,
+ y: pointerPoint.y - currentPosition.y,
+ };
+ dragStartPointRef.current = pointerPoint;
+ lastPointerRef.current = { point: pointerPoint, time: now };
+ lastDragDeltaRef.current = null;
+ lastFootstepAtRef.current = now;
+ didDragRef.current = false;
+ stopTemporaryMotion();
+ setIsDragging(true);
+ setWalkIntensity(1.1);
+ event.currentTarget.setPointerCapture(event.pointerId);
+ },
+ [
+ boundaryRef,
+ initialPosition,
+ lastFootstepAtRef,
+ position,
+ setIsDragging,
+ setWalkIntensity,
+ stopTemporaryMotion,
+ ]
+ );
+
+ const handlePointerMove = useCallback(
+ (event: ReactPointerEvent<HTMLButtonElement>) => {
+ if (!isDragging) {
+ return;
+ }
+
+ const bounds = getBounds(boundaryRef.current);
+ const pointerPoint = getPointerPoint(event, boundaryRef.current);
+ const now = performance.now();
+ const lastPointer = lastPointerRef.current ?? {
+ point: pointerPoint,
+ time: now,
+ };
+ const deltaX = pointerPoint.x - lastPointer.point.x;
+ const deltaY = pointerPoint.y - lastPointer.point.y;
+ const nextDelta = { x: deltaX, y: deltaY };
+ const distance = Math.hypot(deltaX, deltaY);
+ const elapsed = Math.max(1, now - lastPointer.time);
+ const intensity = calculateMonsterWalkIntensity(distance, elapsed);
+ const nextPosition = clampPetPosition(
+ {
+ x: pointerPoint.x - dragOffsetRef.current.x,
+ y: pointerPoint.y - dragOffsetRef.current.y,
+ },
+ bounds,
+ CLOUD_CODE_MONSTER_SIZE
+ );
+ const dragStartPoint = dragStartPointRef.current ?? pointerPoint;
+ const movementX = Math.abs(pointerPoint.x - dragStartPoint.x);
+ const movementY = Math.abs(pointerPoint.y - dragStartPoint.y);
+
+ if (movementX > 3 || movementY > 3) {
+ didDragRef.current = true;
+ }
+ if (Math.abs(deltaX) > 0.5) {
+ setWalkDirection(deltaX >= 0 ? "right" : "left");
+ }
+ const hasSharpDirectionChange = hasViolentMonsterDirectionChange(
+ lastDragDeltaRef.current,
+ nextDelta
+ );
+
+ if (
+ !fainted &&
+ isViolentMonsterDrag(distance, elapsed, hasSharpDirectionChange)
+ ) {
+ startShakeReaction();
+ }
+
+ if (
+ !fainted &&
+ isMonsterFaintShakeEvent(distance, elapsed, hasSharpDirectionChange)
+ ) {
+ violentDragEventsRef.current = [
+ ...violentDragEventsRef.current.filter(
+ (eventTime) =>
+ now - eventTime <= CLOUD_CODE_MONSTER_FAINT_EVENT_WINDOW_MS
+ ),
+ now,
+ ];
+
+ if (shouldFaintFromMonsterShake(violentDragEventsRef.current, now)) {
+ startFaintReaction();
+ return;
+ }
+ }
+
+ setWalkIntensity(intensity);
+ setPosition(nextPosition);
+ lastPointerRef.current = { point: pointerPoint, time: now };
+ if (distance > 0.5) {
+ lastDragDeltaRef.current = nextDelta;
+ }
+
+ if (
+ distance > 1 &&
+ now - lastFootstepAtRef.current >=
+ getMonsterFootstepIntervalMs(intensity)
+ ) {
+ pushFootprint(nextPosition, intensity);
+ lastFootstepAtRef.current = now;
+ }
+ },
+ [
+ boundaryRef,
+ fainted,
+ isDragging,
+ lastFootstepAtRef,
+ pushFootprint,
+ setPosition,
+ setWalkDirection,
+ setWalkIntensity,
+ startFaintReaction,
+ startShakeReaction,
+ violentDragEventsRef,
+ ]
+ );
+
+ const stopDragging = useCallback(
+ (event: ReactPointerEvent<HTMLButtonElement>) => {
+ if (!isDragging) {
+ return;
+ }
+
+ setIsDragging(false);
+ violentDragEventsRef.current = [];
+ dragStartPointRef.current = null;
+ lastPointerRef.current = null;
+ lastDragDeltaRef.current = null;
+
+ setPetTimer("walkSettle", () => {
+ setWalkIntensity(1);
+ }, 180);
+
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ }
+ },
+ [
+ isDragging,
+ setIsDragging,
+ setPetTimer,
+ setWalkIntensity,
+ violentDragEventsRef,
+ ]
+ );
+
+ return {
+ handlePetClick,
+ handlePointerDown,
+ handlePointerMove,
+ stopDragging,
+ };
+}
diff --git a/src/web/src/components/home-pet/cloud-code-monster-pet.module.css b/src/web/src/components/home-pet/cloud-code-monster-pet.module.css
index 3e0613ce5..4beb791cd 100644
--- a/src/web/src/components/home-pet/cloud-code-monster-pet.module.css
+++ b/src/web/src/components/home-pet/cloud-code-monster-pet.module.css
@@ -2,7 +2,7 @@
display: contents;
}
-.petLayer :global(.cloud-code-monster-pet) {
+.pet {
position: absolute;
top: 0;
left: 0;
@@ -14,7 +14,7 @@
touch-action: none;
}
-.petLayer :global(.cloud-code-monster-pet-footsteps) {
+.footsteps {
position: absolute;
inset: 0;
z-index: 11;
@@ -22,7 +22,7 @@
pointer-events: none;
}
-.petLayer :global(.cloud-code-monster-pet-footprint) {
+.footprint {
position: absolute;
left: 0;
top: 0;
@@ -37,11 +37,11 @@
animation: cloud-code-monster-footprint 980ms ease-out both;
}
-.petLayer :global(.cloud-code-monster-pet-footprint[data-side="right"]) {
+.footprint[data-side="right"] {
--monster-footprint-rotate: 8deg;
}
-.petLayer :global(.cloud-code-monster-pet-button) {
+.button {
position: relative;
display: grid;
width: 82px;
@@ -56,16 +56,16 @@
transform-origin: 50% 88%;
}
-.petLayer :global(.cloud-code-monster-pet-button:active),
-.petLayer :global(.cloud-code-monster-pet-button[data-dragging="true"]) {
+.button:active,
+.button[data-dragging="true"] {
cursor: grabbing;
}
-.petLayer :global(.cloud-code-monster-pet-button[data-fainted="true"]) {
+.button[data-fainted="true"] {
cursor: pointer;
}
-.petLayer :global(.cloud-code-monster-pet-button:focus-visible) {
+.button:focus-visible {
outline: 2px solid color-mix(in oklch, var(--primary) 55%, transparent);
outline-offset: 5px;
border-radius: 8px;
@@ -80,7 +80,7 @@
transform-origin: 50% 50%;
}
-.petLayer :global(.cloud-code-monster-pet[data-direction="left"] .cloud-code-monster-pet-svg) {
+.pet[data-direction="left"] :global(.cloud-code-monster-pet-svg) {
transform: scaleX(-1);
}
@@ -100,47 +100,47 @@
transform-origin: 50% 80%;
}
-.petLayer :global(.cloud-code-monster-pet[data-walking="true"] .cloud-code-monster-pet-character) {
+.pet[data-walking="true"] :global(.cloud-code-monster-pet-character) {
animation: cloud-code-monster-walk var(--monster-walk-duration, 260ms) steps(2, end) infinite;
}
-.petLayer :global(.cloud-code-monster-pet[data-walking="true"] .cloud-code-monster-pet-left-foot) {
+.pet[data-walking="true"] :global(.cloud-code-monster-pet-left-foot) {
animation: cloud-code-monster-left-foot var(--monster-walk-duration, 260ms) steps(2, end) infinite;
transform-origin: 50% 50%;
}
-.petLayer :global(.cloud-code-monster-pet[data-walking="true"] .cloud-code-monster-pet-right-foot) {
+.pet[data-walking="true"] :global(.cloud-code-monster-pet-right-foot) {
animation: cloud-code-monster-right-foot var(--monster-walk-duration, 260ms) steps(2, end) infinite;
transform-origin: 50% 50%;
}
-.petLayer :global(.cloud-code-monster-pet[data-reacting="true"] .cloud-code-monster-pet-button) {
+.pet[data-reacting="true"] .button {
animation: cloud-code-monster-startled 900ms cubic-bezier(0.34, 1.56, 0.64, 1) both;
}
-.petLayer :global(.cloud-code-monster-pet[data-shaken="true"] .cloud-code-monster-pet-button) {
+.pet[data-shaken="true"] .button {
animation: cloud-code-monster-shaken 180ms steps(2, end) infinite;
}
-.petLayer :global(.cloud-code-monster-pet[data-fainted="true"] .cloud-code-monster-pet-button) {
+.pet[data-fainted="true"] .button {
animation: cloud-code-monster-faint 10s ease-in-out both;
filter: drop-shadow(0 6px 9px color-mix(in oklch, var(--foreground) 12%, transparent));
transform-origin: 50% 92%;
}
-.petLayer :global(.cloud-code-monster-pet[data-fainted="true"] .cloud-code-monster-pet-character) {
+.pet[data-fainted="true"] :global(.cloud-code-monster-pet-character) {
animation: none;
}
-.petLayer :global(.cloud-code-monster-pet[data-peeking="true"]) {
+.pet[data-peeking="true"] {
z-index: 2;
}
-.petLayer :global(.cloud-code-monster-pet[data-peeking="true"] .cloud-code-monster-pet-button) {
+.pet[data-peeking="true"] .button {
animation: cloud-code-monster-peek 4.2s ease-in-out both;
}
-.petLayer :global(.cloud-code-monster-pet-notification-bell) {
+.notificationBell {
position: absolute;
left: 50%;
top: -18px;
@@ -157,6 +157,10 @@
pointer-events: none;
}
+.notificationBellPixel {
+ display: block;
+}
+
.petLayer :global(.cloud-code-monster-pet-shock rect) {
animation: cloud-code-monster-shock-pixels 360ms steps(2, end) infinite;
transform-box: fill-box;
@@ -173,38 +177,38 @@
animation-delay: 140ms;
}
-.petLayer :global(.cloud-code-monster-pet[data-activity="sleeping"] .cloud-code-monster-pet-character) {
+.pet[data-activity="sleeping"] :global(.cloud-code-monster-pet-character) {
animation: cloud-code-monster-sleep 5.2s steps(2, end) infinite;
}
-.petLayer :global(.cloud-code-monster-pet[data-activity="sleeping"] .cloud-code-monster-pet-sleep rect) {
+.pet[data-activity="sleeping"] :global(.cloud-code-monster-pet-sleep rect) {
animation: cloud-code-monster-sleep-pixels 2.6s ease-in-out infinite;
transform-box: fill-box;
}
-.petLayer :global(.cloud-code-monster-pet[data-activity="sleeping"] .cloud-code-monster-pet-sleep-z) {
+.pet[data-activity="sleeping"] :global(.cloud-code-monster-pet-sleep-z) {
animation: cloud-code-monster-sleep-pixels 2.6s ease-in-out infinite;
transform-box: fill-box;
transform-origin: center;
}
-.petLayer :global(.cloud-code-monster-pet[data-activity="sleeping"] .cloud-code-monster-pet-sleep-z rect) {
+.pet[data-activity="sleeping"] :global(.cloud-code-monster-pet-sleep-z rect) {
animation: none;
}
-.petLayer :global(.cloud-code-monster-pet[data-activity="sleeping"] .cloud-code-monster-pet-sleep-z:nth-child(2)) {
+.pet[data-activity="sleeping"] :global(.cloud-code-monster-pet-sleep-z:nth-child(2)) {
animation-delay: 320ms;
}
-.petLayer :global(.cloud-code-monster-pet[data-activity="sleeping"] .cloud-code-monster-pet-sleep-z:nth-child(3)) {
+.pet[data-activity="sleeping"] :global(.cloud-code-monster-pet-sleep-z:nth-child(3)) {
animation-delay: 640ms;
}
-.petLayer :global(.cloud-code-monster-pet[data-activity="reading"] .cloud-code-monster-pet-book) {
+.pet[data-activity="reading"] :global(.cloud-code-monster-pet-book) {
animation: cloud-code-monster-read 3.2s steps(2, end) infinite;
}
-.petLayer :global(.cloud-code-monster-pet[data-activity="phone"] .cloud-code-monster-pet-phone) {
+.pet[data-activity="phone"] :global(.cloud-code-monster-pet-phone) {
animation: cloud-code-monster-phone 2.4s steps(2, end) infinite;
}
@@ -213,24 +217,24 @@
animation: cloud-code-monster-phone-glow 1.4s ease-in-out infinite;
}
-.petLayer :global(.cloud-code-monster-pet[data-activity="coding"] .cloud-code-monster-pet-laptop) {
+.pet[data-activity="coding"] :global(.cloud-code-monster-pet-laptop) {
animation: cloud-code-monster-keytap 1s steps(2, end) infinite;
}
-.petLayer :global(.cloud-code-monster-pet[data-activity="thinking"] .cloud-code-monster-pet-thought rect) {
+.pet[data-activity="thinking"] :global(.cloud-code-monster-pet-thought rect) {
animation: cloud-code-monster-thought 2.8s ease-in-out infinite;
transform-box: fill-box;
}
-.petLayer :global(.cloud-code-monster-pet[data-activity="thinking"] .cloud-code-monster-pet-thought rect:nth-child(2)) {
+.pet[data-activity="thinking"] :global(.cloud-code-monster-pet-thought rect:nth-child(2)) {
animation-delay: 240ms;
}
-.petLayer :global(.cloud-code-monster-pet[data-activity="thinking"] .cloud-code-monster-pet-thought rect:nth-child(3)) {
+.pet[data-activity="thinking"] :global(.cloud-code-monster-pet-thought rect:nth-child(3)) {
animation-delay: 480ms;
}
-.petLayer :global(.cloud-code-monster-pet[data-activity="snacking"] .cloud-code-monster-pet-snack) {
+.pet[data-activity="snacking"] :global(.cloud-code-monster-pet-snack) {
animation: cloud-code-monster-snack 2.2s steps(2, end) infinite;
}
@@ -340,7 +344,7 @@
}
@media (prefers-reduced-motion: reduce) {
- .petLayer :global(.cloud-code-monster-pet-button),
+ .button,
.petLayer :global(.cloud-code-monster-pet-character),
.petLayer :global(.cloud-code-monster-pet-left-foot),
.petLayer :global(.cloud-code-monster-pet-right-foot),
@@ -349,8 +353,8 @@
.petLayer :global(.cloud-code-monster-pet-accessory rect),
.petLayer :global(.cloud-code-monster-pet-shock rect),
.petLayer :global(.cloud-code-monster-pet-phone-glow),
- .petLayer :global(.cloud-code-monster-pet-notification-bell),
- .petLayer :global(.cloud-code-monster-pet-footprint) {
+ .notificationBell,
+ .footprint {
animation: none !important;
}
}
diff --git a/src/web/src/components/home-pet/cloud-code-monster-pet.test.ts b/src/web/src/components/home-pet/cloud-code-monster-pet.test.ts
index fd035e65c..40331e594 100644
--- a/src/web/src/components/home-pet/cloud-code-monster-pet.test.ts
+++ b/src/web/src/components/home-pet/cloud-code-monster-pet.test.ts
@@ -267,6 +267,10 @@ describe("production workspace PET mounting", () => {
path.join(root, "src/components/home-pet/cloud-code-monster-pet.tsx"),
"utf8"
);
+ const petDragHook = readFileSync(
+ path.join(root, "src/components/home-pet/cloud-code-monster-pet-drag.ts"),
+ "utf8"
+ );
const petPixelParts = readFileSync(
path.join(root, "src/components/home-pet/cloud-code-monster-pet-pixel-parts.tsx"),
"utf8"
@@ -345,6 +349,9 @@ describe("production workspace PET mounting", () => {
expect(petComponent).toContain("const hasPeekTargets = peekTargets.length > 0");
expect(petComponent).toContain("function usePetTimers()");
expect(petComponent).toContain("setPetTimer(\"peek\"");
+ expect(petComponent).toContain("usePetDrag({");
+ expect(petDragHook).toContain("export function usePetDrag");
+ expect(petDragHook).toContain("const handlePointerMove = useCallback");
expect(petComponent).not.toContain("peekTargets = []");
expect(petComponent).not.toContain("TimerRef = useRef");
for (const sensitiveShapeId of sensitiveShapeIds) {
@@ -355,7 +362,10 @@ describe("production workspace PET mounting", () => {
);
expect(agentNode).toContain("data-agent-node-id={agent.id}");
expect(agentNode).toContain('data-agent-working={activeTaskCount > 0 ? "true" : "false"}');
- expect(petCssModule).toContain(":global(.cloud-code-monster-pet)");
+ expect(petCssModule).toContain(".pet {");
+ expect(petCssModule).toContain(".button {");
+ expect(petCssModule).toContain(".footprint {");
+ expect(petCssModule).not.toContain(":global(.cloud-code-monster-pet)");
expect(globalCss).not.toContain(".cloud-code-monster-pet");
expect(globalCss).not.toContain(".home-pet");
expect(globalCss).not.toContain(".pet-preview-flow");
diff --git a/src/web/src/components/home-pet/cloud-code-monster-pet.tsx b/src/web/src/components/home-pet/cloud-code-monster-pet.tsx
index 29f7f3889..40069b536 100644
--- a/src/web/src/components/home-pet/cloud-code-monster-pet.tsx
+++ b/src/web/src/components/home-pet/cloud-code-monster-pet.tsx
@@ -2,7 +2,6 @@
import {
type CSSProperties,
- type PointerEvent as ReactPointerEvent,
type RefObject,
useCallback,
useEffect,
@@ -14,30 +13,23 @@ import {
import styles from "./cloud-code-monster-pet.module.css";
import {
- calculateMonsterWalkIntensity,
clampPetPosition,
createCloudCodeMonsterHiddenState,
createCloudCodeMonsterIdleState,
- createCloudCodeMonsterPreviewAwayState,
createCloudCodeMonsterWalkVelocity,
getBounds,
getMonsterFootstepIntervalMs,
- hasViolentMonsterDirectionChange,
- isMonsterFaintShakeEvent,
- isViolentMonsterDrag,
readStoredActivity,
reflectCloudCodeMonsterWalk,
resolveCloudCodeMonsterPeekPosition,
resolveCloudCodeMonsterPreviewComebackState,
resolveCloudCodeMonsterVisibleState,
shouldCloudCodeMonsterAutoWalk,
- shouldFaintFromMonsterShake,
writeStoredActivity,
} from "./cloud-code-monster-pet-activity";
import { CLOUD_CODE_MONSTER_ACTIVITIES } from "./cloud-code-monster-pet-activity-data";
import {
CLOUD_CODE_MONSTER_AUTO_WALK_STEP_MS,
- CLOUD_CODE_MONSTER_FAINT_EVENT_WINDOW_MS,
CLOUD_CODE_MONSTER_FAINT_MS,
CLOUD_CODE_MONSTER_PEEK_INTERVAL_MS,
CLOUD_CODE_MONSTER_PEEK_MS,
@@ -47,6 +39,7 @@ import {
CLOUD_CODE_MONSTER_SHAKE_REACTION_MS,
CLOUD_CODE_MONSTER_SIZE,
} from "./cloud-code-monster-pet-constants";
+import { usePetDrag } from "./cloud-code-monster-pet-drag";
import { MonsterSvg } from "./cloud-code-monster-pet-pixel-parts";
import {
CLOUD_CODE_MONSTER_PET_PRESETS,
@@ -112,18 +105,6 @@ export type {
StoredCloudCodeMonsterActivity,
} from "./cloud-code-monster-pet-types";
-function getPointerPoint(
- event: ReactPointerEvent<HTMLButtonElement>,
- boundary: HTMLElement | null
-): PetPoint {
- const boundaryRect = boundary?.getBoundingClientRect();
-
- return {
- x: event.clientX - (boundaryRect?.left ?? 0),
- y: event.clientY - (boundaryRect?.top ?? 0),
- };
-}
-
export type CloudCodeMonsterPetProps = {
boundaryRef: RefObject<HTMLElement | null>;
initialPosition?: PetPoint;
@@ -214,15 +195,10 @@ export function CloudCodeMonsterPet({
const [walkIntensity, setWalkIntensity] = useState(1);
const [walkDirection, setWalkDirection] = useState<"left" | "right">("right");
const [footprints, setFootprints] = useState<Footprint[]>([]);
- const dragOffsetRef = useRef<PetPoint>({ x: 0, y: 0 });
- const dragStartPointRef = useRef<PetPoint | null>(null);
- const lastPointerRef = useRef<{ point: PetPoint; time: number } | null>(null);
- const lastDragDeltaRef = useRef<PetPoint | null>(null);
const lastFootstepAtRef = useRef(0);
const autoWalkVelocityRef = useRef<PetPoint | null>(null);
const nextFootprintIdRef = useRef(1);
const nextFootSideRef = useRef<"left" | "right">("left");
- const didDragRef = useRef(false);
const resizeObserverRef = useRef<ResizeObserver | null>(null);
const violentDragEventsRef = useRef<number[]>([]);
const peekTargetsRef = useRef(peekTargets);
@@ -520,7 +496,7 @@ export function CloudCodeMonsterPet({
setPetTimer,
]);
- const wakeMonsterToDefault = () => {
+ const wakeMonsterToDefault = useCallback(() => {
setActivityState((current) => {
if (current && !current.activityId && current.hiddenAt === null) {
return current;
@@ -530,9 +506,9 @@ export function CloudCodeMonsterPet({
writeStoredActivity(nextState);
return nextState;
});
- };
+ }, []);
- const stopTemporaryMotion = () => {
+ const stopTemporaryMotion = useCallback(() => {
setIsAutoWalking(false);
setIsPeeking(false);
violentDragEventsRef.current = [];
@@ -541,14 +517,14 @@ export function CloudCodeMonsterPet({
clearPetTimer("autonomousWalk");
clearPetTimer("peek");
clearPetTimer("peekStop");
- };
+ }, [clearPetTimer]);
- const startShockReaction = () => {
+ const startShockReaction = useCallback(() => {
setReacting(true);
setPetTimer("reaction", () => {
setReacting(false);
}, CLOUD_CODE_MONSTER_REACTION_MS);
- };
+ }, [setPetTimer]);
useEffect(() => {
if (notificationToken <= 0) {
@@ -565,9 +541,16 @@ export function CloudCodeMonsterPet({
setPetTimer("notification", () => {
setNotificationActive(false);
}, CLOUD_CODE_MONSTER_REACTION_MS + 1_500);
- }, [notificationToken]);
+ }, [
+ activityState?.activityId,
+ notificationToken,
+ setPetTimer,
+ startShockReaction,
+ stopTemporaryMotion,
+ wakeMonsterToDefault,
+ ]);
- const startShakeReaction = () => {
+ const startShakeReaction = useCallback(() => {
if (fainted) {
return;
}
@@ -580,9 +563,14 @@ export function CloudCodeMonsterPet({
setPetTimer("shake", () => {
setShaken(false);
}, CLOUD_CODE_MONSTER_SHAKE_REACTION_MS);
- };
+ }, [
+ activityState?.activityId,
+ fainted,
+ setPetTimer,
+ wakeMonsterToDefault,
+ ]);
- const startFaintReaction = () => {
+ const startFaintReaction = useCallback(() => {
clearPetTimer("faint");
clearPetTimer("reaction");
clearPetTimer("shake");
@@ -597,169 +585,42 @@ export function CloudCodeMonsterPet({
setPetTimer("faint", () => {
setFainted(false);
}, CLOUD_CODE_MONSTER_FAINT_MS);
- };
-
- const handlePetClick = () => {
- stopTemporaryMotion();
- setNotificationActive(false);
- clearPetTimer("notification");
-
- if (didDragRef.current) {
- didDragRef.current = false;
- return;
- }
-
- if (isDragging) {
- return;
- }
-
- if (activityState?.activityId) {
- wakeMonsterToDefault();
- }
-
- if (fainted) {
- setFainted(false);
- clearPetTimer("faint");
- }
-
- startShockReaction();
- };
-
- const handlePointerDown = (event: ReactPointerEvent<HTMLButtonElement>) => {
- if (event.button !== 0) {
- return;
- }
-
- const bounds = getBounds(boundaryRef.current);
- const currentPosition =
- position ??
- clampPetPosition(
- initialPosition ?? {
- x: bounds.width - CLOUD_CODE_MONSTER_SIZE.width - 112,
- y: bounds.height * 0.48,
- },
- bounds,
- CLOUD_CODE_MONSTER_SIZE
- );
- const pointerPoint = getPointerPoint(event, boundaryRef.current);
- const now = performance.now();
-
- dragOffsetRef.current = {
- x: pointerPoint.x - currentPosition.x,
- y: pointerPoint.y - currentPosition.y,
- };
- dragStartPointRef.current = pointerPoint;
- lastPointerRef.current = { point: pointerPoint, time: now };
- lastDragDeltaRef.current = null;
- lastFootstepAtRef.current = now;
- didDragRef.current = false;
- stopTemporaryMotion();
- setIsDragging(true);
- setWalkIntensity(1.1);
- event.currentTarget.setPointerCapture(event.pointerId);
- };
-
- const handlePointerMove = (event: ReactPointerEvent<HTMLButtonElement>) => {
- if (!isDragging) {
- return;
- }
-
- const bounds = getBounds(boundaryRef.current);
- const pointerPoint = getPointerPoint(event, boundaryRef.current);
- const now = performance.now();
- const lastPointer = lastPointerRef.current ?? {
- point: pointerPoint,
- time: now,
- };
- const deltaX = pointerPoint.x - lastPointer.point.x;
- const deltaY = pointerPoint.y - lastPointer.point.y;
- const nextDelta = { x: deltaX, y: deltaY };
- const distance = Math.hypot(deltaX, deltaY);
- const elapsed = Math.max(1, now - lastPointer.time);
- const intensity = calculateMonsterWalkIntensity(distance, elapsed);
- const nextPosition = clampPetPosition(
- {
- x: pointerPoint.x - dragOffsetRef.current.x,
- y: pointerPoint.y - dragOffsetRef.current.y,
- },
- bounds,
- CLOUD_CODE_MONSTER_SIZE
- );
- const dragStartPoint = dragStartPointRef.current ?? pointerPoint;
- const movementX = Math.abs(pointerPoint.x - dragStartPoint.x);
- const movementY = Math.abs(pointerPoint.y - dragStartPoint.y);
-
- if (movementX > 3 || movementY > 3) {
- didDragRef.current = true;
- }
- if (Math.abs(deltaX) > 0.5) {
- setWalkDirection(deltaX >= 0 ? "right" : "left");
- }
- const hasSharpDirectionChange = hasViolentMonsterDirectionChange(
- lastDragDeltaRef.current,
- nextDelta
- );
-
- if (
- !fainted &&
- isViolentMonsterDrag(distance, elapsed, hasSharpDirectionChange)
- ) {
- startShakeReaction();
- }
-
- if (
- !fainted &&
- isMonsterFaintShakeEvent(distance, elapsed, hasSharpDirectionChange)
- ) {
- violentDragEventsRef.current = [
- ...violentDragEventsRef.current.filter(
- (eventTime) =>
- now - eventTime <= CLOUD_CODE_MONSTER_FAINT_EVENT_WINDOW_MS
- ),
- now,
- ];
-
- if (shouldFaintFromMonsterShake(violentDragEventsRef.current, now)) {
- startFaintReaction();
- return;
- }
- }
-
- setWalkIntensity(intensity);
- setPosition(nextPosition);
- lastPointerRef.current = { point: pointerPoint, time: now };
- if (distance > 0.5) {
- lastDragDeltaRef.current = nextDelta;
- }
-
- if (
- distance > 1 &&
- now - lastFootstepAtRef.current >= getMonsterFootstepIntervalMs(intensity)
- ) {
- pushFootprint(nextPosition, intensity);
- lastFootstepAtRef.current = now;
- }
- };
-
- const stopDragging = (event: ReactPointerEvent<HTMLButtonElement>) => {
- if (!isDragging) {
- return;
- }
-
- setIsDragging(false);
- violentDragEventsRef.current = [];
- dragStartPointRef.current = null;
- lastPointerRef.current = null;
- lastDragDeltaRef.current = null;
-
- setPetTimer("walkSettle", () => {
- setWalkIntensity(1);
- }, 180);
+ }, [
+ clearPetTimer,
+ setPetTimer,
+ stopTemporaryMotion,
+ wakeMonsterToDefault,
+ ]);
- if (event.currentTarget.hasPointerCapture(event.pointerId)) {
- event.currentTarget.releasePointerCapture(event.pointerId);
- }
- };
+ const {
+ handlePetClick,
+ handlePointerDown,
+ handlePointerMove,
+ stopDragging,
+ } = usePetDrag({
+ activityState,
+ boundaryRef,
+ fainted,
+ initialPosition,
+ isDragging,
+ lastFootstepAtRef,
+ position,
+ pushFootprint,
+ setFainted,
+ setIsDragging,
+ setNotificationActive,
+ setPetTimer,
+ setPosition,
+ setWalkDirection,
+ setWalkIntensity,
+ clearPetTimer,
+ startFaintReaction,
+ startShakeReaction,
+ startShockReaction,
+ stopTemporaryMotion,
+ violentDragEventsRef,
+ wakeMonsterToDefault,
+ });
if (!position || !activityState) {
return null;
@@ -769,11 +630,11 @@ export function CloudCodeMonsterPet({
return (
<div className={styles.petLayer}>
- <div className="cloud-code-monster-pet-footsteps" aria-hidden="true">
+ <div className={styles.footsteps} aria-hidden="true">
{footprints.map((footprint) => (
<span
key={footprint.id}
- className="cloud-code-monster-pet-footprint"
+ className={styles.footprint}
data-side={footprint.side}
onAnimationEnd={() => {
setFootprints((currentFootprints) =>
@@ -800,7 +661,7 @@ export function CloudCodeMonsterPet({
? "peeking at work"
: displayedActivity?.label ?? "idle"
}`}
- className="cloud-code-monster-pet"
+ className={styles.pet}
data-activity={displayedActivity?.id ?? "idle"}
data-dragging={isDragging}
data-walking={isWalking}
@@ -826,10 +687,10 @@ export function CloudCodeMonsterPet({
}
>
{notificationActive ? (
- <span className="cloud-code-monster-pet-notification-bell" aria-hidden="true">
+ <span className={styles.notificationBell} aria-hidden="true">
<svg
viewBox="0 0 24 24"
- className="cloud-code-monster-pet-notification-bell-pixel size-6"
+ className={`${styles.notificationBellPixel} size-6`}
role="img"
shapeRendering="crispEdges"
>
@@ -848,7 +709,7 @@ export function CloudCodeMonsterPet({
) : null}
<button
type="button"
- className="cloud-code-monster-pet-button"
+ className={styles.button}
data-dragging={isDragging}
data-fainted={fainted}
onClick={handlePetClick}