3D Technical Guide: Interactive Heart, Theme Tokens, and Shared 3D Primitives
This specification documents the 3D and pseudo-3D subsystem across the /heart React Three Fiber (@react-three/fiber + @react-three/rapier) scene, ThemeProvider read-only token derivation, shared DOM card tilt (Interactive3DCard), and unified pointer/keyboard accessibility hooks (useUnified3DInput and use3DInteraction). Portal builds stage this file to docs-portal/features/3d-technical-guide.md via ARCHITECTURAL_DOCS and scripts/generate-portal.ts.
1. Architecture Overview
The 3D subsystem is split into three layers so WebGL scenes and DOM tilt surfaces share input normalization, reduced-motion guards, and theme tokens without coupling runtime state:
- Read-Only Theme & Preset Tokens:
ComponentTokensandTHEME_PRESETSinsrc/lib/theme/presets.tsdefine CSS custom properties for 3D materials, Rapier physics parameters, extrusion geometry, lighting, glow filters, and card tilt springs across all five presets (classic,modern,romantic,minimal,editorial).ThemeProviderinsrc/components/ThemeProvider.tsxparses these tokens into memoized, read-only context values. /heartPhysics Scene & Fallbacks:HeartPageinsrc/app/heart/page.tsxgates/heartbehind guest session authentication and theinteractive3Dfeature module flag (FEATURE_MODULES.md:FEATURE_MODULES.md), then passes partner names intoHeartClientinsrc/app/heart/HeartClient.tsx.HeartClientorchestrates synchronous WebGL 2 detection viauseSyncExternalStore, a 2D SVG fallback (WebGLFallback), a plain DOM loading overlay outside<Canvas>, and dynamicssr: falseloading ofHeartSceneinsrc/app/heart/components/HeartScene.tsx, which hosts 3-tier FPS degradation (PerformanceTracker) andPhysicsHeart(src/app/heart/components/HeartScene.tsx).- Shared Input, Accessibility & DOM Tilt:
Interactive3DCardinsrc/components/ui/Interactive3DCard.tsxandPhysicsHeartboth consumeuseUnified3DInputinsrc/hooks/useUnified3DInput.ts, which pairs normalized pointer/touch tracking and auto-reconstruction timers withuse3DInteractioninsrc/hooks/use3DInteraction.tsxanduseReducedMotioninsrc/hooks/useReducedMotion.ts.
2. Theme Token Derivation & PHYSICS_CONSTANTS
Read-Only ThemeProvider Derivation (Zero Physics Setters)
ThemeProvider does not store mutable runtime physics state or expose setter functions for 3D parameters:
- Context Contract:
ThemeContextTypeinsrc/components/ThemeProvider.tsxexposes onlyThemeContextType.setThemeMode(for'light' | 'dark' | 'system'color mode switching) andThemeContextType.setPreviewConfig(for in-process whole-config draft preview overrides), with zero physics, extrusion, lighting, or card setters. - Static Fallback Defaults:
createContext<ThemeContextType>({ ... })insrc/components/ThemeProvider.tsxdefines static fallback values (initializingphysicsfromPHYSICS_CONSTANTS) used only whenuseTheme()is called outside a mounted<ThemeProvider>. - Memoized Token Computation: Inside
ThemeProvider(src/components/ThemeProvider.tsx),activePresetTokensis computed viauseMemoby merginggetPresetTokensfromsrc/lib/theme/presets.tswith persistedAppConfig.themeTokensoverrides. It then derives read-onlymetalness,roughness,envMapIntensity,cardPerspective,cardMaxRotation,cardSpringStiffness,cardSpringDamping, and memoizedphysics(ThemePhysics),extrusion(ThemeExtrusion),lighting(ThemeLighting), andglowFiltervalues viaparseTokenNum,parseTokenBool, andsanitizeTokenValue. - In-Process & Iframe Live Preview Overrides:
ThemeProviderinsrc/components/ThemeProvider.tsxupdatesdraftConfigOverridethrough two whole-config preview channels so derived 3D tokens recompute without mutating context imperatives: in-process calls toThemeContextType.setPreviewConfiginsrc/components/ThemeProvider.tsxfromActiveDemoProviderinsrc/components/demo/ActiveDemoProvider.tsx(mounted byDemoProviderinsrc/components/demo/DemoContext.tsxwhen switchingthemePreset, applying color overrides, or resetting demo state) andSetupWizardContent/SetupWizardinsrc/components/setup/SetupWizard.tsx(during onboarding stepsstep >= 2without an<iframe>), plus admin preview<iframe>(window !== window.parent)MessageEventpayloads matchingevent.data?.type === 'DRAFT_UPDATE'andevent.data.draftType === 'config'inThemeProvider(src/components/ThemeProvider.tsx), which sanitize incomingthemePresetandthemeTokensintodraftConfigOverride.
Preset CSS Custom Properties (presets.ts)
ComponentTokens in src/lib/theme/presets.ts defines 27 --3d-* tokens, --glow-filter, 4 --card-* tokens, and 3 --motion-* spring/tilt tokens:
| Category | Count | CSS Custom Properties | Consumed By |
|---|---|---|---|
| 3D Material | 3 | --3d-metalness, --3d-roughness, --3d-env-map-intensity | ThemeProvider (metalness, roughness, envMapIntensity) -> Heart3D MeshPhysicalMaterial |
| 3D Physics | 17 | --3d-physics-accessibility-impulse, --3d-physics-drag-velocity-multiplier, --3d-physics-bump-impulse-y, --3d-physics-bump-impulse-random-multiplier, --3d-physics-break-force-threshold, --3d-physics-explosion-impulse-left-x, --3d-physics-explosion-impulse-left-y, --3d-physics-explosion-impulse-left-z, --3d-physics-explosion-impulse-right-x, --3d-physics-explosion-impulse-right-y, --3d-physics-explosion-impulse-right-z, --3d-physics-explosion-torque-strength, --3d-physics-return-force-multiplier, --3d-physics-pulse-speed-dragging, --3d-physics-pulse-speed-idle, --3d-physics-pulse-scale-multiplier, --3d-physics-idle-rotation-speed | ThemeProvider (physics: ThemePhysics); note --3d-physics-bump-impulse-y and --3d-physics-bump-impulse-random-multiplier have no runtime readers |
| 3D Extrusion | 5 | --3d-extrusion-depth, --3d-extrusion-bevel-enabled, --3d-extrusion-bevel-thickness, --3d-extrusion-bevel-size, --3d-extrusion-bevel-segments | ThemeProvider (extrusion: ThemeExtrusion) -> Heart3D ExtrudeGeometry |
| 3D Lighting | 2 | --3d-light-ambient-intensity, --3d-light-directional-intensity | ThemeProvider (lighting: ThemeLighting) -> HeartScene <ambientLight> & <directionalLight> |
| 2D Fallback Glow | 1 | --glow-filter | ThemeProvider (glowFilter) -> WebGLFallback SVG style.filter |
| Card 3D Fallbacks | 4 | --card-perspective, --card-max-rotation, --card-spring-stiffness, --card-spring-damping | ThemeProvider -> Interactive3DCard perspective and fallback spring/tilt limits |
| Motion Spring & Tilt | 3 | --motion-spring-stiffness, --motion-spring-damping, --motion-tilt-max-deg | Interactive3DCard primary spring stiffness, damping, and max tilt degrees |
HEART_FONT_URL & Active vs. Unused PHYSICS_CONSTANTS (src/app/heart/constants.ts)
src/app/heart/constants.ts exports resolveHeartFontUrl and HEART_FONT_URL (/fonts/noto-sans-latin-400-normal.woff, prefixed with a normalized NEXT_PUBLIC_BASE_PATH when deployed under a static showcase subpath) so @react-three/drei <Text> meshes render offline without external CDN requests. PHYSICS_CONSTANTS in src/app/heart/constants.ts also exports 13 entries: 11 active fallback constants consumed by /heart and 2 unused legacy constants (BUMP_IMPULSE_Y and BUMP_IMPULSE_RANDOM_MULTIPLIER) in src/app/heart/constants.ts.
| Constant Key | Default Value | ThemePhysics Field | Status & Runtime Reader |
|---|---|---|---|
ACCESSIBILITY_IMPULSE | 20 | physics.accessibilityImpulse | Active — Kinematic arrow-key step scale (physics.accessibilityImpulse * KEYBOARD_STEP_SCALE) in PhysicsHeart (src/app/heart/components/HeartScene.tsx) |
DRAG_VELOCITY_MULTIPLIER | 20 | physics.dragVelocityMultiplier | Active — Release setLinvel throw velocity in PhysicsHeart (src/app/heart/components/HeartScene.tsx) |
BUMP_IMPULSE_Y | 10 | physics.bumpImpulseY | Unused — Populated in ThemeProvider, zero runtime consumers (PHYSICS_CONSTANTS.BUMP_IMPULSE_Y in src/app/heart/constants.ts) |
BUMP_IMPULSE_RANDOM_MULTIPLIER | 10 | physics.bumpImpulseRandomMultiplier | Unused — Populated in ThemeProvider, zero runtime consumers (PHYSICS_CONSTANTS.BUMP_IMPULSE_RANDOM_MULTIPLIER in src/app/heart/constants.ts) |
BREAK_FORCE_THRESHOLD | 200 | physics.breakForceThreshold | Active — handleContactForce threshold in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts) |
EXPLOSION_IMPULSE_LEFT | { x: 20, y: 15, z: 5 } | physics.explosionImpulseLeft | Active — Left shard applyImpulse in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts) |
EXPLOSION_IMPULSE_RIGHT | { x: -20, y: 15, z: -5 } | physics.explosionImpulseRight | Active — Right shard applyImpulse in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts) |
EXPLOSION_TORQUE_STRENGTH | 40 | physics.explosionTorqueStrength | Active — Random shard applyTorqueImpulse in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts) |
RETURN_FORCE_MULTIPLIER | 15 | physics.returnForceMultiplier | Active — Post-interaction origin return addForce in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts) |
PULSE_SPEED_DRAGGING | 5 | physics.pulseSpeedDragging | Active — Elevated pulse frequency during onDragStart in PhysicsHeart (src/app/heart/components/HeartScene.tsx) |
PULSE_SPEED_IDLE | 1 | physics.pulseSpeedIdle | Active — Initial and post-drag pulse frequency in PhysicsHeart (src/app/heart/components/HeartScene.tsx) |
PULSE_SCALE_MULTIPLIER | 0.05 | physics.pulseScaleMultiplier | Active — Sinusoidal scale amplitude in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts) |
IDLE_ROTATION_SPEED | 0.002 | physics.idleRotationSpeed | Active — Pre-interaction Y-axis Euler step in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts) |
3. /heart Scene Architecture, Lifecycle & Resilience
Route Gating (src/app/heart/page.tsx)
HeartPage in src/app/heart/page.tsx runs on the server:
- Enforces an authenticated guest session via
enforceActiveGuestPageSession(). - Loads
AppConfigviagetAppConfig()and checksisFeatureEnabled('interactive3D', config.modules), calling Next.jsnotFound()when disabled. - Renders
<HeartClient>withpartner1Name(config.partner1Name || config.brideName || '') andpartner2Name(config.partner2Name || config.groomName || '').
Scene Components & Dual-Clipped Geometry
HeartClient(src/app/heart/HeartClient.tsx): Manages viewport-responsivescale(0.4below768px,0.6at>= 768px),isPausedanimation pause state (handleTogglePause) with natural document focus order (preserving.skip-linkreachability), bottom keyboard hint pill clearance (useOptionalDemoinsrc/components/demo/DemoContext.tsx), synchronous WebGL 2 availability viauseSyncExternalStore, a plain DOMLoading…overlay outside<Canvas>untilmarkSceneReadyruns,performanceTier,resetKey, and dynamicnext/dynamic(ssr: false,loading: () => null) loading ofHeartScene(src/app/heart/components/HeartScene.tsx) with zero static 3D imports.HeartScene(src/app/heart/components/HeartScene.tsx): Renders the R3F<Canvas camera={{ position: [0, 0, 15], fov: 50 }} dpr={[1, 2]} gl={{ localClippingEnabled: true }}>(settingaria-hidden="true"ongl.domElementviaonCreatedso<Html>sibling controls remain exposed to assistive technology), scene lighting,PerformanceTracker,<Suspense fallback={null}>,<Physics key={resetKey} gravity={[0, 0, 0]}>, tier-gated<Sparkles />(respectingisPaused),<Environment>, and<EffectComposer><Bloom>, andSceneReadyNotifier(src/app/heart/components/HeartScene.tsx).PhysicsHeart(src/app/heart/components/HeartScene.tsx): Coordinates three Rapier<RigidBody>instances (mainwithCuboidCollider[1.5 * scale, 1.5 * scale, 0.8 * scale]andActiveCollisionTypes.CONTACT_FORCE_EVENTS, plusleftandrightshard bodies initialized astype="fixed"with half-width colliders at[-0.75 * scale, 0, 0]and[0.75 * scale, 0, 0]), threeuseUnified3DInputinstances,useHeartPhysics, and<Html>accessibility overlays.Heart3D(src/app/heart/components/Heart3D.tsx): Builds a centered BezierTHREE.ExtrudeGeometryusingextrusiontokens (depth,bevelEnabled,bevelSegments,bevelThickness,bevelSize). Insidesrc/app/heart/components/Heart3D.tsx, it creates two opposing X-axis clipping planes—planeLeft = new THREE.Plane(new THREE.Vector3(1, 0, 0), 0)andplaneRight = new THREE.Plane(new THREE.Vector3(-1, 0, 0), 0)—and attaches them to twoTHREE.MeshPhysicalMaterialinstances (goldusingprimaryColorandroughness,silverusingsecondaryColorandroughness + 0.05, both withclipShadows: true). Because WebGL local clipping is required to slice each mesh cleanly atx = 0,<Canvas>must passgl={{ localClippingEnabled: true }}inHeartScene(src/app/heart/components/HeartScene.tsx). WhenshardSideis omitted, both halves and both partner<Text font={HEART_FONT_URL}>labels ([-1, 0.1, 0.71]and[1, 0.1, 0.71]) render using the bundled local.wofffont; passingshardSide="left"orshardSide="right"renders only that clipped half and its corresponding partner name.ScreenBounds(src/app/heart/components/ScreenBounds.tsx): Surrounds the R3Fviewportwith four fixedCuboidColliderwalls (restitution={0.9}) so flung hearts and shards bounce inside the visible frame.Sparkles(src/app/heart/components/Sparkles.tsx): Renders 200 spherical<Points>(radius: 10) colored bythemeAccent, rotatingy += 0.001per frame when!reduceMotion && !isPaused.
Dragging, Keyboard Movement, Breaking & Shard Reconstruction
- Pointer Drag, Throw & Kinematic Keyboard Stepping:
onDragStartclearsisKeyboardControlled, switchesheartReftoRigidBodyType.KinematicPositionBased, and setspulseSpeedtophysics.pulseSpeedDragging.onDragMoveupdatessetNextKinematicTranslationacross the R3Fviewport.onDragEndrestoresRigidBodyType.Dynamicand, when!reduceMotionandMath.abs(vx) > 0.1 || Math.abs(vy) > 0.1, applies throw velocity(vx * physics.dragVelocityMultiplier, -vy * physics.dragVelocityMultiplier, 0)inPhysicsHeart(src/app/heart/components/HeartScene.tsx). PressingArrowUp,ArrowDown,ArrowLeft, orArrowRighton the whole-heart<Html><button>activatesisKeyboardControlled, switchesheartReftoRigidBodyType.KinematicPositionBased, and stepssetNextKinematicTranslationbyphysics.accessibilityImpulse * KEYBOARD_STEP_SCALEclamped insideScreenBounds, restoringRigidBodyType.Dynamicwhen starting a pointer drag, breaking/reconstructing the heart, or clickingReset. - Breaking & Explosion: A collision where
payload.totalForceMagnitude > physics.breakForceThresholdinhandleContactForceinsideuseHeartPhysics(src/app/heart/hooks/useHeartPhysics.ts)—or pressingSpace/Enteron the whole-heart button—callsbreakHeart(). InsideuseHeartPhysics(src/app/heart/hooks/useHeartPhysics.ts),mainRb.setEnabled(false)disables the whole heart,leftRbandrightRbenable asRigidBodyType.DynamicinheritingmainRbtranslation, rotation, linear velocity, and angular velocity, and (when!reduceMotion) receivephysics.explosionImpulseLeft,physics.explosionImpulseRight, and randomized torque impulses scaled byphysics.explosionTorqueStrength. - Automatic & Keyboard Reconstruction:
- Auto-Timer:
PhysicsHeartconfiguresreconstructTimeout: 3000insrc/app/heart/components/HeartScene.tsx, automatically invokingreconstruct()3 seconds afterisBrokenbecomestrue. - Manual Shard Action: Inside
PhysicsHeart(src/app/heart/components/HeartScene.tsx), both sharduseUnified3DInputhooks bindSpaceandEnter(onAction) toreconstructHeart()for immediate keyboard or click recovery. - Rigid-Body Reset: When
isBrokenreturns tofalse,useHeartPhysics(src/app/heart/hooks/useHeartPhysics.ts) zeroes linear and angular velocities onleftRbandrightRb, resets their translations to{ x: 0, y: 0, z: 0 }and rotations to{ x: 0, y: 0, z: 0, w: 1 }, switches both back toRigidBodyType.Fixed, callssetEnabled(false), and re-enablesmainRbasRigidBodyType.Dynamicat the origin with zero velocity.
- Auto-Timer:
Frame Forces, Pulsing & Secret Spot (useHeartPhysics)
On every animation frame in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts):
- Secret Spot (
"I love you!"): While!isBroken, ifmainRbenters the top-right corner (position.x > viewportWidth / 2 - 2 && position.y > viewportHeight / 2 - 2),setShowEasterEgg(true)reveals the 3D<Text font={HEART_FONT_URL}>"I love you!"mesh at[0, 0, 5], appends"Secret message revealed: I love you!"to the whole-heartaria-label, and updates the politesr-onlylive region inPhysicsHeart(src/app/heart/components/HeartScene.tsx). - Idle Y-Axis Rotation: Before first interaction (
!interacted) and when!reduceMotion && !isPaused,tempEuler.yincrements byphysics.idleRotationSpeedeach frame. - Central Return Force: Once
interactedistrueand!isKeyboardControlled, whenever radial XY distance from the origin exceeds0.1,useHeartPhysicsapplies a normalized inward force scaled byphysics.returnForceMultiplierwhen!reduceMotion && !isPaused(snappingmainRbdirectly to{ x: 0, y: 0, z: position.z }with zero linear velocity whenreduceMotionis active, or zeroing linear and angular velocity whenisPausedis active; within0.1units of origin it zeroes linear velocity). WhileisKeyboardControlledistrue, bothreturnForceMultiplierand thereduceMotionorigin snap are skipped so arrow keys can hold positions anywhere insideScreenBounds, including the top-right secret spot. - Sinusoidal Pulsing: Scales
groupRefuniformly to1 + Math.sin(t * pulseSpeed) * physics.pulseScaleMultiplier, locking scale to(1, 1, 1)whenreduceMotionorisPausedistrue.
<Html> Focus Handoff
PhysicsHeart renders visually transparent, focus-ring-enabled <button> controls inside @react-three/drei <Html> portals for the whole heart and each broken shard in src/app/heart/components/HeartScene.tsx:
focusedButtonReftracks'none' | 'whole' | 'left' | 'right'with a cleaned-up 50ms blur timeout inPhysicsHeart(src/app/heart/components/HeartScene.tsx) so unmounting a button during state transitions does not erase focus intent before theisBrokeneffect runs.- When
isBrokentransitions totruewhile'whole'was focused, arequestAnimationFrameloop transfers DOM focus toleftButtonRef(falling back to[aria-label^="Broken heart left segment"]) and cancels any pending frame callback on cleanup or unmount. - When
isBrokentransitions back tofalsewhile'left'or'right'was focused,requestAnimationFrametransfers DOM focus back towholeButtonRef(falling back to[aria-label^="Interactive 3D Heart"]) and cancels any pending frame callback on cleanup or unmount.
3-Tier FPS Degradation & Reset Recovery
PerformanceTracker(src/app/heart/components/HeartScene.tsx): Computes instantaneousfps = 1 / delta(honoringwindow.__mockFpsin tests). Wheneverfps < 30,lowFpsAccumulatorRefaccumulatesdelta; once sustained below 30 FPS for>= 3.0seconds, it stepsperformanceTierdown one level ('high'->'medium', or'medium'->'low') and resets the accumulator. Any frame withfps >= 30resets the accumulator to0, and tracking stops once'low'is reached.- Tier Feature Gating (
HeartSceneinsrc/app/heart/components/HeartScene.tsx):'high': Full<Physics>,<Sparkles />, procedural<Environment frames={1} resolution={256}>with warm<Lightformer>panels, and<EffectComposer><Bloom>post-processing.'medium': Drops<EffectComposer>/<Bloom>while keeping<Sparkles />and procedural<Environment><Lightformer>reflections.'low': Drops<Sparkles />,<Environment>, and<Bloom>, retaining core lighting and<Physics>simulation.
ResetButton Recovery: ClickingReset(handleResetinsideHeartClientinsrc/app/heart/HeartClient.tsx) setsinteractedtofalse, restoresperformanceTierto'high', and incrementsresetKeyto remount<Physics key={resetKey}>inHeartScene(src/app/heart/components/HeartScene.tsx) (or<WebGLFallback key={resetKey}>inHeartClient).
WebGLFallback (2D Interactive SVG)
Before mounting HeartScene (<Canvas>), HeartClient calls isWebGLAvailable() (src/app/heart/HeartClient.tsx) synchronously via useSyncExternalStore, probing WebGL2RenderingContext and webgl2 canvas contexts while respecting window.__mockWebGLSupport in tests. When WebGL 2 is unavailable, the dynamic HeartScene chunk and <Canvas> are never fetched or mounted and HeartClient renders WebGLFallback (src/app/heart/HeartClient.tsx):
- Renders a 200x200 pulsing (
animate-pulse motion-reduce:animate-none, switching toanimate-nonewhenisPausedistrue) SVG heart styled withprimaryColor,secondaryColor, partner name labels, andglowFilter || drop-shadow(0 0 10px ${accentColor}). - Supports pointer dragging via
setPointerCapture/releasePointerCaptureandtranslate(${position.x}px, ${position.y}px)transforms. - Supports keyboard movement in 20px steps (
ArrowUp,ArrowDown,ArrowLeft,ArrowRight) on the focusablerole="button"container (data-testid="webgl-fallback-heart"), announcing"Moved up","Moved down","Moved left", and"Moved right"through a politesr-onlylive region.
4. Shared DOM Tilt (Interactive3DCard) & Input Hooks
Polymorphic Interactive3DCard & Consumers
Interactive3DCard in src/components/ui/Interactive3DCard.tsx provides reusable Framer Motion 3D perspective tilt for DOM cards:
- Polymorphic Wrapper Cache:
MotionComponentWrapper(src/components/ui/Interactive3DCard.tsx) cachesmotion.create(Component)instances inmotionComponentCachebyElementType(as, defaulting to'div') and forwards DOM refs viasetRef, preventing unmount/remount cycles across re-renders. In non-production builds, renderingas="button"oras="a"with nested focusable descendants logs a console accessibility warning (src/components/ui/Interactive3DCard.tsx). - Runtime Callers:
- Home Travel Cards:
HomePageClientinsrc/components/home/HomePageClient.tsxrenders travel logistics entries inside<Interactive3DCard as="article">with[transform:translateZ(10px)]inner headings and descriptions. - Guest Registry Cards:
RegistryCardinsrc/features/registry/components/RegistryCard.tsxwraps non-admin registry items in<Interactive3DCard as="article">(passingtabIndex={isClickable ? -1 : undefined}so nested action buttons own keyboard tab stops without duplicating an outerrole="button"wrapper).
- Home Travel Cards:
Spring Resolution, Focus Tilt, Semantics & reduceMotion
- Spring & Tilt Token Precedence (
Interactive3DCardinsrc/components/ui/Interactive3DCard.tsx): ReadsgetPresetTokens(themePreset)so--motion-spring-stiffness,--motion-spring-damping, and--motion-tilt-max-degtake precedence, falling back toThemeProvidercardSpringStiffness(300),cardSpringDamping(20), andcardMaxRotation(10), whilecardPerspective(1000) drivestransformPerspective.useTransformmaps normalized[-0.5, 0.5]mouseYSpringto[tiltMaxDeg, -tiltMaxDeg](rotateX) andmouseXSpringto[-tiltMaxDeg, tiltMaxDeg](rotateY). - Focus Tilt: Focusing the card root directly (
!reduceMotion && e.target === e.currentTarget) setsx.set(0.15)andy.set(-0.15); blurring resets both springs to0inInteractive3DCard(src/components/ui/Interactive3DCard.tsx). - Conditional Button Semantics &
reduceMotionFallback (Interactive3DCardinsrc/components/ui/Interactive3DCard.tsx):shouldApplyButtonSemanticsistrueonly whenBoolean(onClick) && propTabIndex !== -1 && !isInteractive(neither'button'nor'a'). Only then does the card defaultrole="button"andtabIndex={0}, andhandleCardKeyDowntriggersonClickonEnterorSpacestrictly whene.target === e.currentTarget(ignoring bubbled key events from nested controls).- When
reduceMotionistrue,Interactive3DCardomitstransformPerspective,rotateX,rotateY,transformStyle: 'preserve-3d', andwillChange: 'transform'from inlinestyle.
useUnified3DInput (src/hooks/useUnified3DInput.ts)
useUnified3DInput in src/hooks/useUnified3DInput.ts unifies pointer, touch, lifecycle, and keyboard hooks across R3F meshes and DOM elements:
- Coordinate Normalization (
getNormalizedCoords):domRefMode: CachesdomRef.current.getBoundingClientRect()on pointer down (cachedRectRef) and clamps(clientX - left) / width - 0.5and(clientY - top) / height - 0.5to[-0.5, 0.5].r3fMode: Normalizes canvas coordinates via(clientX / r3f.size.width) - 0.5and(clientY / r3f.size.height) - 0.5.
- Velocity Tracking & 50ms Stale Cutoff: Computes
vx = dx / dtandvy = dy / dtinpx/msusingperformance.now(). On pointer release, ifperformance.now() - dragState.current.lastTime > 50,vxandvyreset to0so stationary holds before release do not fling objects. Pointer down and move handlers short-circuit whenisDestroyed || reduceMotion. - Lifecycle Timers: Manages
isDestroyed,destroy(), andreconstruct(), scheduling asetTimeoutforoptions.reconstructTimeoutms wheneverisDestroyedbecomestrueand cleaning up on unmount or early reconstruction. - Handler Split: Returns
handlers(pointer/touch only, used on R3F<group>),getInteractiveProps(keyboard +aria-describedby, used on<Html><button>), andmixedHandlers(combined pointer + accessibility props, used on DOM elements likeInteractive3DCard), settingAccessibleElementstonullwhenoptions.accessibilityis omitted.
use3DInteraction (src/hooks/use3DInteraction.tsx)
use3DInteraction in src/hooks/use3DInteraction.tsx provides screen-reader and keyboard parity for 3D controls:
- Generates React
useId()-scoped element IDs3d-instructions-${id}and3d-live-${id}. - Renders
AccessibleElements: a hiddensr-onlyinstructions node ({instructions}) and a polite atomic live region (aria-live="polite" aria-atomic="true") announcing directional or actionlabels(up,down,left,right,action) whenArrowUp,ArrowDown,ArrowLeft,ArrowRight,Space,Enter, oronClickhandlers fire. - Merges caller-supplied
aria-describedbytokens withinstructionsId(${existingDescribedBy} ${instructionsId}) ingetInteractiveProps(src/hooks/use3DInteraction.tsx) so external descriptions are preserved.
5. Extending 3D Features Safely
- Adding Preset 3D Tokens: Declare new custom properties on
ComponentTokensand all five presets insrc/lib/theme/presets.ts, then parse them viauseMemoinsideThemeProviderinsrc/components/ThemeProvider.tsx. KeepThemeProvidercontext values read-only rather than adding imperative physics setters. - Adding
/heartVisuals or Forces: Gate expensive shaders, particles, or post-processing effects byperformanceTierinHeartScene(src/app/heart/components/HeartScene.tsx), respectreduceMotionin everyuseFramecallback, and ensureWebGLFallbackremains operable via pointer drag and keyboard arrows. - Documentation & Portal Sync: Keep JSX identifiers wrapped in inline code backticks (for example,
`<Canvas>`and`<Html>`) and cite exported module symbols against file-level links rather than hardcoded#L<start>-L<end>line ranges soscripts/check-doc-links.ts,scripts/verify-spec-contracts.ts, andscripts/generate-portal.tspass cleanly.