Skip to content

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:

  1. Read-Only Theme & Preset Tokens: ComponentTokens and THEME_PRESETS in src/lib/theme/presets.ts define 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). ThemeProvider in src/components/ThemeProvider.tsx parses these tokens into memoized, read-only context values.
  2. /heart Physics Scene & Fallbacks: HeartPage in src/app/heart/page.tsx gates /heart behind guest session authentication and the interactive3D feature module flag (FEATURE_MODULES.md: FEATURE_MODULES.md), then passes partner names into HeartClient in src/app/heart/HeartClient.tsx. HeartClient orchestrates synchronous WebGL 2 detection via useSyncExternalStore, a 2D SVG fallback (WebGLFallback), a plain DOM loading overlay outside <Canvas>, and dynamic ssr: false loading of HeartScene in src/app/heart/components/HeartScene.tsx, which hosts 3-tier FPS degradation (PerformanceTracker) and PhysicsHeart (src/app/heart/components/HeartScene.tsx).
  3. Shared Input, Accessibility & DOM Tilt: Interactive3DCard in src/components/ui/Interactive3DCard.tsx and PhysicsHeart both consume useUnified3DInput in src/hooks/useUnified3DInput.ts, which pairs normalized pointer/touch tracking and auto-reconstruction timers with use3DInteraction in src/hooks/use3DInteraction.tsx and useReducedMotion in src/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: ThemeContextType in src/components/ThemeProvider.tsx exposes only ThemeContextType.setThemeMode (for 'light' | 'dark' | 'system' color mode switching) and ThemeContextType.setPreviewConfig (for in-process whole-config draft preview overrides), with zero physics, extrusion, lighting, or card setters.
  • Static Fallback Defaults: createContext<ThemeContextType>({ ... }) in src/components/ThemeProvider.tsx defines static fallback values (initializing physics from PHYSICS_CONSTANTS) used only when useTheme() is called outside a mounted <ThemeProvider>.
  • Memoized Token Computation: Inside ThemeProvider (src/components/ThemeProvider.tsx), activePresetTokens is computed via useMemo by merging getPresetTokens from src/lib/theme/presets.ts with persisted AppConfig.themeTokens overrides. It then derives read-only metalness, roughness, envMapIntensity, cardPerspective, cardMaxRotation, cardSpringStiffness, cardSpringDamping, and memoized physics (ThemePhysics), extrusion (ThemeExtrusion), lighting (ThemeLighting), and glowFilter values via parseTokenNum, parseTokenBool, and sanitizeTokenValue.
  • In-Process & Iframe Live Preview Overrides: ThemeProvider in src/components/ThemeProvider.tsx updates draftConfigOverride through two whole-config preview channels so derived 3D tokens recompute without mutating context imperatives: in-process calls to ThemeContextType.setPreviewConfig in src/components/ThemeProvider.tsx from ActiveDemoProvider in src/components/demo/ActiveDemoProvider.tsx (mounted by DemoProvider in src/components/demo/DemoContext.tsx when switching themePreset, applying color overrides, or resetting demo state) and SetupWizardContent / SetupWizard in src/components/setup/SetupWizard.tsx (during onboarding steps step >= 2 without an <iframe>), plus admin preview <iframe> (window !== window.parent) MessageEvent payloads matching event.data?.type === 'DRAFT_UPDATE' and event.data.draftType === 'config' in ThemeProvider (src/components/ThemeProvider.tsx), which sanitize incoming themePreset and themeTokens into draftConfigOverride.

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:

CategoryCountCSS Custom PropertiesConsumed By
3D Material3--3d-metalness, --3d-roughness, --3d-env-map-intensityThemeProvider (metalness, roughness, envMapIntensity) -> Heart3D MeshPhysicalMaterial
3D Physics17--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-speedThemeProvider (physics: ThemePhysics); note --3d-physics-bump-impulse-y and --3d-physics-bump-impulse-random-multiplier have no runtime readers
3D Extrusion5--3d-extrusion-depth, --3d-extrusion-bevel-enabled, --3d-extrusion-bevel-thickness, --3d-extrusion-bevel-size, --3d-extrusion-bevel-segmentsThemeProvider (extrusion: ThemeExtrusion) -> Heart3D ExtrudeGeometry
3D Lighting2--3d-light-ambient-intensity, --3d-light-directional-intensityThemeProvider (lighting: ThemeLighting) -> HeartScene <ambientLight> & <directionalLight>
2D Fallback Glow1--glow-filterThemeProvider (glowFilter) -> WebGLFallback SVG style.filter
Card 3D Fallbacks4--card-perspective, --card-max-rotation, --card-spring-stiffness, --card-spring-dampingThemeProvider -> Interactive3DCard perspective and fallback spring/tilt limits
Motion Spring & Tilt3--motion-spring-stiffness, --motion-spring-damping, --motion-tilt-max-degInteractive3DCard 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 KeyDefault ValueThemePhysics FieldStatus & Runtime Reader
ACCESSIBILITY_IMPULSE20physics.accessibilityImpulseActive — Kinematic arrow-key step scale (physics.accessibilityImpulse * KEYBOARD_STEP_SCALE) in PhysicsHeart (src/app/heart/components/HeartScene.tsx)
DRAG_VELOCITY_MULTIPLIER20physics.dragVelocityMultiplierActive — Release setLinvel throw velocity in PhysicsHeart (src/app/heart/components/HeartScene.tsx)
BUMP_IMPULSE_Y10physics.bumpImpulseYUnused — Populated in ThemeProvider, zero runtime consumers (PHYSICS_CONSTANTS.BUMP_IMPULSE_Y in src/app/heart/constants.ts)
BUMP_IMPULSE_RANDOM_MULTIPLIER10physics.bumpImpulseRandomMultiplierUnused — Populated in ThemeProvider, zero runtime consumers (PHYSICS_CONSTANTS.BUMP_IMPULSE_RANDOM_MULTIPLIER in src/app/heart/constants.ts)
BREAK_FORCE_THRESHOLD200physics.breakForceThresholdActive — handleContactForce threshold in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts)
EXPLOSION_IMPULSE_LEFT{ x: 20, y: 15, z: 5 }physics.explosionImpulseLeftActive — Left shard applyImpulse in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts)
EXPLOSION_IMPULSE_RIGHT{ x: -20, y: 15, z: -5 }physics.explosionImpulseRightActive — Right shard applyImpulse in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts)
EXPLOSION_TORQUE_STRENGTH40physics.explosionTorqueStrengthActive — Random shard applyTorqueImpulse in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts)
RETURN_FORCE_MULTIPLIER15physics.returnForceMultiplierActive — Post-interaction origin return addForce in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts)
PULSE_SPEED_DRAGGING5physics.pulseSpeedDraggingActive — Elevated pulse frequency during onDragStart in PhysicsHeart (src/app/heart/components/HeartScene.tsx)
PULSE_SPEED_IDLE1physics.pulseSpeedIdleActive — Initial and post-drag pulse frequency in PhysicsHeart (src/app/heart/components/HeartScene.tsx)
PULSE_SCALE_MULTIPLIER0.05physics.pulseScaleMultiplierActive — Sinusoidal scale amplitude in useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts)
IDLE_ROTATION_SPEED0.002physics.idleRotationSpeedActive — 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:

  1. Enforces an authenticated guest session via enforceActiveGuestPageSession().
  2. Loads AppConfig via getAppConfig() and checks isFeatureEnabled('interactive3D', config.modules), calling Next.js notFound() when disabled.
  3. Renders <HeartClient> with partner1Name (config.partner1Name || config.brideName || '') and partner2Name (config.partner2Name || config.groomName || '').

Scene Components & Dual-Clipped Geometry ​

  • HeartClient (src/app/heart/HeartClient.tsx): Manages viewport-responsive scale (0.4 below 768px, 0.6 at >= 768px), isPaused animation pause state (handleTogglePause) with natural document focus order (preserving .skip-link reachability), bottom keyboard hint pill clearance (useOptionalDemo in src/components/demo/DemoContext.tsx), synchronous WebGL 2 availability via useSyncExternalStore, a plain DOM Loading… overlay outside <Canvas> until markSceneReady runs, performanceTier, resetKey, and dynamic next/dynamic (ssr: false, loading: () => null) loading of HeartScene (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 }}> (setting aria-hidden="true" on gl.domElement via onCreated so <Html> sibling controls remain exposed to assistive technology), scene lighting, PerformanceTracker, <Suspense fallback={null}>, <Physics key={resetKey} gravity={[0, 0, 0]}>, tier-gated <Sparkles /> (respecting isPaused), <Environment>, and <EffectComposer> <Bloom>, and SceneReadyNotifier (src/app/heart/components/HeartScene.tsx).
  • PhysicsHeart (src/app/heart/components/HeartScene.tsx): Coordinates three Rapier <RigidBody> instances (main with CuboidCollider [1.5 * scale, 1.5 * scale, 0.8 * scale] and ActiveCollisionTypes.CONTACT_FORCE_EVENTS, plus left and right shard bodies initialized as type="fixed" with half-width colliders at [-0.75 * scale, 0, 0] and [0.75 * scale, 0, 0]), three useUnified3DInput instances, useHeartPhysics, and <Html> accessibility overlays.
  • Heart3D (src/app/heart/components/Heart3D.tsx): Builds a centered Bezier THREE.ExtrudeGeometry using extrusion tokens (depth, bevelEnabled, bevelSegments, bevelThickness, bevelSize). Inside src/app/heart/components/Heart3D.tsx, it creates two opposing X-axis clipping planes—planeLeft = new THREE.Plane(new THREE.Vector3(1, 0, 0), 0) and planeRight = new THREE.Plane(new THREE.Vector3(-1, 0, 0), 0)—and attaches them to two THREE.MeshPhysicalMaterial instances (gold using primaryColor and roughness, silver using secondaryColor and roughness + 0.05, both with clipShadows: true). Because WebGL local clipping is required to slice each mesh cleanly at x = 0, <Canvas> must pass gl={{ localClippingEnabled: true }} in HeartScene (src/app/heart/components/HeartScene.tsx). When shardSide is 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 .woff font; passing shardSide="left" or shardSide="right" renders only that clipped half and its corresponding partner name.
  • ScreenBounds (src/app/heart/components/ScreenBounds.tsx): Surrounds the R3F viewport with four fixed CuboidCollider walls (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 by themeAccent, rotating y += 0.001 per frame when !reduceMotion && !isPaused.

Dragging, Keyboard Movement, Breaking & Shard Reconstruction ​

  1. Pointer Drag, Throw & Kinematic Keyboard Stepping: onDragStart clears isKeyboardControlled, switches heartRef to RigidBodyType.KinematicPositionBased, and sets pulseSpeed to physics.pulseSpeedDragging. onDragMove updates setNextKinematicTranslation across the R3F viewport. onDragEnd restores RigidBodyType.Dynamic and, when !reduceMotion and Math.abs(vx) > 0.1 || Math.abs(vy) > 0.1, applies throw velocity (vx * physics.dragVelocityMultiplier, -vy * physics.dragVelocityMultiplier, 0) in PhysicsHeart (src/app/heart/components/HeartScene.tsx). Pressing ArrowUp, ArrowDown, ArrowLeft, or ArrowRight on the whole-heart <Html> <button> activates isKeyboardControlled, switches heartRef to RigidBodyType.KinematicPositionBased, and steps setNextKinematicTranslation by physics.accessibilityImpulse * KEYBOARD_STEP_SCALE clamped inside ScreenBounds, restoring RigidBodyType.Dynamic when starting a pointer drag, breaking/reconstructing the heart, or clicking Reset.
  2. Breaking & Explosion: A collision where payload.totalForceMagnitude > physics.breakForceThreshold in handleContactForce inside useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts)—or pressing Space/Enter on the whole-heart button—calls breakHeart(). Inside useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts), mainRb.setEnabled(false) disables the whole heart, leftRb and rightRb enable as RigidBodyType.Dynamic inheriting mainRb translation, rotation, linear velocity, and angular velocity, and (when !reduceMotion) receive physics.explosionImpulseLeft, physics.explosionImpulseRight, and randomized torque impulses scaled by physics.explosionTorqueStrength.
  3. Automatic & Keyboard Reconstruction:
    • Auto-Timer: PhysicsHeart configures reconstructTimeout: 3000 in src/app/heart/components/HeartScene.tsx, automatically invoking reconstruct() 3 seconds after isBroken becomes true.
    • Manual Shard Action: Inside PhysicsHeart (src/app/heart/components/HeartScene.tsx), both shard useUnified3DInput hooks bind Space and Enter (onAction) to reconstructHeart() for immediate keyboard or click recovery.
    • Rigid-Body Reset: When isBroken returns to false, useHeartPhysics (src/app/heart/hooks/useHeartPhysics.ts) zeroes linear and angular velocities on leftRb and rightRb, resets their translations to { x: 0, y: 0, z: 0 } and rotations to { x: 0, y: 0, z: 0, w: 1 }, switches both back to RigidBodyType.Fixed, calls setEnabled(false), and re-enables mainRb as RigidBodyType.Dynamic at the origin with zero velocity.

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, if mainRb enters 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-heart aria-label, and updates the polite sr-only live region in PhysicsHeart (src/app/heart/components/HeartScene.tsx).
  • Idle Y-Axis Rotation: Before first interaction (!interacted) and when !reduceMotion && !isPaused, tempEuler.y increments by physics.idleRotationSpeed each frame.
  • Central Return Force: Once interacted is true and !isKeyboardControlled, whenever radial XY distance from the origin exceeds 0.1, useHeartPhysics applies a normalized inward force scaled by physics.returnForceMultiplier when !reduceMotion && !isPaused (snapping mainRb directly to { x: 0, y: 0, z: position.z } with zero linear velocity when reduceMotion is active, or zeroing linear and angular velocity when isPaused is active; within 0.1 units of origin it zeroes linear velocity). While isKeyboardControlled is true, both returnForceMultiplier and the reduceMotion origin snap are skipped so arrow keys can hold positions anywhere inside ScreenBounds, including the top-right secret spot.
  • Sinusoidal Pulsing: Scales groupRef uniformly to 1 + Math.sin(t * pulseSpeed) * physics.pulseScaleMultiplier, locking scale to (1, 1, 1) when reduceMotion or isPaused is true.

<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:

  • focusedButtonRef tracks 'none' | 'whole' | 'left' | 'right' with a cleaned-up 50ms blur timeout in PhysicsHeart (src/app/heart/components/HeartScene.tsx) so unmounting a button during state transitions does not erase focus intent before the isBroken effect runs.
  • When isBroken transitions to true while 'whole' was focused, a requestAnimationFrame loop transfers DOM focus to leftButtonRef (falling back to [aria-label^="Broken heart left segment"]) and cancels any pending frame callback on cleanup or unmount.
  • When isBroken transitions back to false while 'left' or 'right' was focused, requestAnimationFrame transfers DOM focus back to wholeButtonRef (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 instantaneous fps = 1 / delta (honoring window.__mockFps in tests). Whenever fps < 30, lowFpsAccumulatorRef accumulates delta; once sustained below 30 FPS for >= 3.0 seconds, it steps performanceTier down one level ('high' -> 'medium', or 'medium' -> 'low') and resets the accumulator. Any frame with fps >= 30 resets the accumulator to 0, and tracking stops once 'low' is reached.
  • Tier Feature Gating (HeartScene in src/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.
  • Reset Button Recovery: Clicking Reset (handleReset inside HeartClient in src/app/heart/HeartClient.tsx) sets interacted to false, restores performanceTier to 'high', and increments resetKey to remount <Physics key={resetKey}> in HeartScene (src/app/heart/components/HeartScene.tsx) (or <WebGLFallback key={resetKey}> in HeartClient).

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 to animate-none when isPaused is true) SVG heart styled with primaryColor, secondaryColor, partner name labels, and glowFilter || drop-shadow(0 0 10px ${accentColor}).
  • Supports pointer dragging via setPointerCapture / releasePointerCapture and translate(${position.x}px, ${position.y}px) transforms.
  • Supports keyboard movement in 20px steps (ArrowUp, ArrowDown, ArrowLeft, ArrowRight) on the focusable role="button" container (data-testid="webgl-fallback-heart"), announcing "Moved up", "Moved down", "Moved left", and "Moved right" through a polite sr-only live 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) caches motion.create(Component) instances in motionComponentCache by ElementType (as, defaulting to 'div') and forwards DOM refs via setRef, preventing unmount/remount cycles across re-renders. In non-production builds, rendering as="button" or as="a" with nested focusable descendants logs a console accessibility warning (src/components/ui/Interactive3DCard.tsx).
  • Runtime Callers:
    • Home Travel Cards: HomePageClient in src/components/home/HomePageClient.tsx renders travel logistics entries inside <Interactive3DCard as="article"> with [transform:translateZ(10px)] inner headings and descriptions.
    • Guest Registry Cards: RegistryCard in src/features/registry/components/RegistryCard.tsx wraps non-admin registry items in <Interactive3DCard as="article"> (passing tabIndex={isClickable ? -1 : undefined} so nested action buttons own keyboard tab stops without duplicating an outer role="button" wrapper).

Spring Resolution, Focus Tilt, Semantics & reduceMotion ​

  • Spring & Tilt Token Precedence (Interactive3DCard in src/components/ui/Interactive3DCard.tsx): Reads getPresetTokens(themePreset) so --motion-spring-stiffness, --motion-spring-damping, and --motion-tilt-max-deg take precedence, falling back to ThemeProvider cardSpringStiffness (300), cardSpringDamping (20), and cardMaxRotation (10), while cardPerspective (1000) drives transformPerspective. useTransform maps normalized [-0.5, 0.5] mouseYSpring to [tiltMaxDeg, -tiltMaxDeg] (rotateX) and mouseXSpring to [-tiltMaxDeg, tiltMaxDeg] (rotateY).
  • Focus Tilt: Focusing the card root directly (!reduceMotion && e.target === e.currentTarget) sets x.set(0.15) and y.set(-0.15); blurring resets both springs to 0 in Interactive3DCard (src/components/ui/Interactive3DCard.tsx).
  • Conditional Button Semantics & reduceMotion Fallback (Interactive3DCard in src/components/ui/Interactive3DCard.tsx):
    • shouldApplyButtonSemantics is true only when Boolean(onClick) && propTabIndex !== -1 && !isInteractive (neither 'button' nor 'a'). Only then does the card default role="button" and tabIndex={0}, and handleCardKeyDown triggers onClick on Enter or Space strictly when e.target === e.currentTarget (ignoring bubbled key events from nested controls).
    • When reduceMotion is true, Interactive3DCard omits transformPerspective, rotateX, rotateY, transformStyle: 'preserve-3d', and willChange: 'transform' from inline style.

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):
    • domRef Mode: Caches domRef.current.getBoundingClientRect() on pointer down (cachedRectRef) and clamps (clientX - left) / width - 0.5 and (clientY - top) / height - 0.5 to [-0.5, 0.5].
    • r3f Mode: Normalizes canvas coordinates via (clientX / r3f.size.width) - 0.5 and (clientY / r3f.size.height) - 0.5.
  • Velocity Tracking & 50ms Stale Cutoff: Computes vx = dx / dt and vy = dy / dt in px/ms using performance.now(). On pointer release, if performance.now() - dragState.current.lastTime > 50, vx and vy reset to 0 so stationary holds before release do not fling objects. Pointer down and move handlers short-circuit when isDestroyed || reduceMotion.
  • Lifecycle Timers: Manages isDestroyed, destroy(), and reconstruct(), scheduling a setTimeout for options.reconstructTimeout ms whenever isDestroyed becomes true and 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>), and mixedHandlers (combined pointer + accessibility props, used on DOM elements like Interactive3DCard), setting AccessibleElements to null when options.accessibility is 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 IDs 3d-instructions-${id} and 3d-live-${id}.
  • Renders AccessibleElements: a hidden sr-only instructions node ({instructions}) and a polite atomic live region (aria-live="polite" aria-atomic="true") announcing directional or action labels (up, down, left, right, action) when ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Space, Enter, or onClick handlers fire.
  • Merges caller-supplied aria-describedby tokens with instructionsId (${existingDescribedBy} ${instructionsId}) in getInteractiveProps (src/hooks/use3DInteraction.tsx) so external descriptions are preserved.

5. Extending 3D Features Safely ​

  • Adding Preset 3D Tokens: Declare new custom properties on ComponentTokens and all five presets in src/lib/theme/presets.ts, then parse them via useMemo inside ThemeProvider in src/components/ThemeProvider.tsx. Keep ThemeProvider context values read-only rather than adding imperative physics setters.
  • Adding /heart Visuals or Forces: Gate expensive shaders, particles, or post-processing effects by performanceTier in HeartScene (src/app/heart/components/HeartScene.tsx), respect reduceMotion in every useFrame callback, and ensure WebGLFallback remains 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 so scripts/check-doc-links.ts, scripts/verify-spec-contracts.ts, and scripts/generate-portal.ts pass cleanly.

Released under the AGPL-3.0 License.