@harmonia-core/ui 1.0.0

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 (77) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +267 -0
  3. package/dist/capacity/animation.d.ts +77 -0
  4. package/dist/capacity/animation.d.ts.map +1 -0
  5. package/dist/capacity/constants.d.ts +119 -0
  6. package/dist/capacity/constants.d.ts.map +1 -0
  7. package/dist/capacity/feedback.d.ts +55 -0
  8. package/dist/capacity/feedback.d.ts.map +1 -0
  9. package/dist/capacity/fields/field-manager.d.ts +45 -0
  10. package/dist/capacity/fields/field-manager.d.ts.map +1 -0
  11. package/dist/capacity/index.d.ts +15 -0
  12. package/dist/capacity/index.d.ts.map +1 -0
  13. package/dist/capacity/index.js +1313 -0
  14. package/dist/capacity/index.js.map +1 -0
  15. package/dist/capacity/index.mjs +1267 -0
  16. package/dist/capacity/index.mjs.map +1 -0
  17. package/dist/capacity/mode.d.ts +50 -0
  18. package/dist/capacity/mode.d.ts.map +1 -0
  19. package/dist/capacity/prediction/hooks.d.ts +11 -0
  20. package/dist/capacity/prediction/hooks.d.ts.map +1 -0
  21. package/dist/capacity/prediction/pattern-extractor.d.ts +26 -0
  22. package/dist/capacity/prediction/pattern-extractor.d.ts.map +1 -0
  23. package/dist/capacity/prediction/pattern-store.d.ts +35 -0
  24. package/dist/capacity/prediction/pattern-store.d.ts.map +1 -0
  25. package/dist/capacity/prediction/prediction-engine.d.ts +39 -0
  26. package/dist/capacity/prediction/prediction-engine.d.ts.map +1 -0
  27. package/dist/capacity/prediction/types.d.ts +24 -0
  28. package/dist/capacity/prediction/types.d.ts.map +1 -0
  29. package/dist/capacity/provider.d.ts +119 -0
  30. package/dist/capacity/provider.d.ts.map +1 -0
  31. package/dist/capacity/signals/aggregator.d.ts +38 -0
  32. package/dist/capacity/signals/aggregator.d.ts.map +1 -0
  33. package/dist/capacity/signals/detectors/environment-detector.d.ts +31 -0
  34. package/dist/capacity/signals/detectors/environment-detector.d.ts.map +1 -0
  35. package/dist/capacity/signals/detectors/input-detector.d.ts +23 -0
  36. package/dist/capacity/signals/detectors/input-detector.d.ts.map +1 -0
  37. package/dist/capacity/signals/detectors/interaction-detector.d.ts +27 -0
  38. package/dist/capacity/signals/detectors/interaction-detector.d.ts.map +1 -0
  39. package/dist/capacity/signals/detectors/scroll-detector.d.ts +35 -0
  40. package/dist/capacity/signals/detectors/scroll-detector.d.ts.map +1 -0
  41. package/dist/capacity/signals/detectors/session-detector.d.ts +23 -0
  42. package/dist/capacity/signals/detectors/session-detector.d.ts.map +1 -0
  43. package/dist/capacity/signals/detectors/time-detector.d.ts +20 -0
  44. package/dist/capacity/signals/detectors/time-detector.d.ts.map +1 -0
  45. package/dist/capacity/signals/detectors/types.d.ts +25 -0
  46. package/dist/capacity/signals/detectors/types.d.ts.map +1 -0
  47. package/dist/capacity/signals/signal-bus.d.ts +50 -0
  48. package/dist/capacity/signals/signal-bus.d.ts.map +1 -0
  49. package/dist/capacity/types.d.ts +239 -0
  50. package/dist/capacity/types.d.ts.map +1 -0
  51. package/dist/capacity/utils/index.d.ts +7 -0
  52. package/dist/capacity/utils/index.d.ts.map +1 -0
  53. package/dist/capacity/utils/typography.d.ts +176 -0
  54. package/dist/capacity/utils/typography.d.ts.map +1 -0
  55. package/dist/components/ambient-field-monitor.d.ts +10 -0
  56. package/dist/components/ambient-field-monitor.d.ts.map +1 -0
  57. package/dist/components/capacity-controls.d.ts +15 -0
  58. package/dist/components/capacity-controls.d.ts.map +1 -0
  59. package/dist/components/capacity-demo-card.d.ts +13 -0
  60. package/dist/components/capacity-demo-card.d.ts.map +1 -0
  61. package/dist/components/index.d.ts +18 -0
  62. package/dist/components/index.d.ts.map +1 -0
  63. package/dist/components/index.js +1703 -0
  64. package/dist/components/index.js.map +1 -0
  65. package/dist/components/index.mjs +1688 -0
  66. package/dist/components/index.mjs.map +1 -0
  67. package/dist/components/ui/badge.d.ts +8 -0
  68. package/dist/components/ui/badge.d.ts.map +1 -0
  69. package/dist/components/ui/button.d.ts +10 -0
  70. package/dist/components/ui/button.d.ts.map +1 -0
  71. package/dist/components/ui/card.d.ts +10 -0
  72. package/dist/components/ui/card.d.ts.map +1 -0
  73. package/dist/components/ui/select.d.ts +6 -0
  74. package/dist/components/ui/select.d.ts.map +1 -0
  75. package/dist/components/ui/slider.d.ts +14 -0
  76. package/dist/components/ui/slider.d.ts.map +1 -0
  77. package/package.json +98 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../lib/capacity/constants.ts","../../lib/capacity/feedback.ts","../../lib/capacity/fields/field-manager.ts","../../lib/capacity/mode.ts","../../lib/capacity/signals/detectors/time-detector.ts","../../lib/capacity/signals/detectors/session-detector.ts","../../lib/capacity/signals/detectors/scroll-detector.ts","../../lib/capacity/signals/detectors/interaction-detector.ts","../../lib/capacity/signals/detectors/input-detector.ts","../../lib/capacity/signals/detectors/environment-detector.ts","../../lib/capacity/signals/aggregator.ts","../../lib/capacity/provider.tsx","../../lib/capacity/animation.ts","../../lib/capacity/utils/typography.ts","../../lib/capacity/signals/signal-bus.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWO,IAAM,GAAA,GAAM;AAGZ,IAAM,WAAA,GAAc;AAGpB,IAAM,SAAA,GAAY,CAAC,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,EAAA,EAAI,EAAA,EAAI,EAAA,EAAI,EAAA,EAAI,IAAI,GAAG;AAW5D,IAAM,oBAAA,GAAuB;AAAA,EAClC,GAAA,EAAK,GAAA;AAAA;AAAA,EACL,GAAA,EAAK,GAAA;AAAA;AAAA,EACL,IAAA,EAAM;AAAA;AACR;AAOO,IAAM,oBAAA,GAAuB;AAAA,EAClC,SAAA,EAAW,IAAA;AAAA;AAAA,EACX,iBAAA,EAAmB,IAAA;AAAA;AAAA,EACnB,UAAA,EAAY;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ACf,eAAA,EAAiB;AACnB","file":"index.mjs","sourcesContent":["/**\n * Capacity-Adaptive UI Constants\n *\n * Structural Principles Layer - Mathematical foundations for proportional design\n */\n\n// ============================================================================\n// Proportional Systems (Golden Ratio, Fibonacci)\n// ============================================================================\n\n/** Golden ratio φ */\nexport const PHI = 1.618033988749895\n\n/** Inverse golden ratio (1/φ) */\nexport const PHI_INVERSE = 0.618033988749895\n\n/** Fibonacci sequence for natural scaling steps */\nexport const FIBONACCI = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] as const\n\n// ============================================================================\n// Auditory Feedback Frequencies (Hz) - Phase 3\n// ============================================================================\n\n/**\n * Frequency ranges for optional auditory feedback\n * Used for interaction confirmation and depth signaling\n * Note: These are constrained ranges, not healing claims\n */\nexport const FEEDBACK_FREQUENCIES = {\n low: 396, // Foundation/root elements\n mid: 528, // Primary interactive content\n high: 741, // Dynamic/feedback elements\n} as const\n\n// ============================================================================\n// Field Defaults\n// ============================================================================\n\n/** Default field configuration */\nexport const DEFAULT_FIELD_CONFIG = {\n smoothing: 0.15, // Exponential smoothing factor\n velocityThreshold: 0.05, // Min velocity to register as trend\n debounceMs: 100, // Debounce rapid changes\n} as const\n\n/** Default user capacity (neutral state) */\nexport const DEFAULT_USER_CAPACITY = {\n cognitive: 0.7,\n temporal: 0.7,\n emotional: 0.7,\n} as const\n\n/** Default emotional state (positive to show expressive animations) */\nexport const DEFAULT_EMOTIONAL_STATE = {\n valence: 0.3, // > 0.15 (with emotional > 0.6) triggers expressive motion mode\n arousal: 0.5,\n} as const\n\n/** Default capacity field (neutral state) */\nexport const DEFAULT_CAPACITY_FIELD = {\n cognitive: 0.5,\n temporal: 0.5,\n emotional: 0.5,\n valence: 0.0,\n} as const\n\n// ============================================================================\n// Component Response Presets\n// ============================================================================\n\n/**\n * Intelligent defaults for component responses\n * 90% of components can use these without override\n */\ninterface ComponentResponse {\n visual: {\n opacityRange: [number, number]\n scaleRange: [number, number]\n }\n spatial: {\n densityRange: [number, number]\n spacingMultiplier: [number, number]\n }\n sonic: {\n enabled: boolean\n }\n semantic: {\n verbosityLevel: string\n urgencyFraming: string\n }\n}\n\nexport const DEFAULT_COMPONENT_RESPONSE: ComponentResponse = {\n visual: {\n opacityRange: [0.4, 1.0],\n scaleRange: [0.95, 1.0],\n },\n spatial: {\n densityRange: [0.6, 1.0],\n spacingMultiplier: [1.0, PHI],\n },\n sonic: {\n enabled: false, // Opt-in\n },\n semantic: {\n verbosityLevel: \"concise\",\n urgencyFraming: \"neutral\",\n },\n} as const\n\n// ============================================================================\n// Accessibility Constants\n// ============================================================================\n\n/** Minimum contrast ratio (WCAG AA) - invariant across all states */\nexport const MIN_CONTRAST_RATIO = 4.5\n\n/** Reduced motion media query key */\nexport const PREFERS_REDUCED_MOTION = \"(prefers-reduced-motion: reduce)\"\n\n/** Maximum animation duration (ms) for time-sensitive users */\nexport const MAX_ANIMATION_DURATION_MS = 300\n\n// ============================================================================\n// Motion Tokens\n// ============================================================================\n\n/**\n * Motion tokens by mode\n * \n * \"off\" means no decorative motion, NOT no transitions at all.\n * You still keep: opacity fades, height/visibility transitions, focus transitions.\n * This preserves usability and avoids \"broken UI\" feelings.\n * \n * \"subtle\" = grounded, low-amplitude, slow easing\n * \"expressive\" = playful, elastic, higher amplitude\n */\nexport const MOTION_TOKENS = {\n off: {\n durationFast: 0,\n durationBase: 0,\n durationSlow: 0,\n easing: \"linear\",\n // Essential transitions still allowed (opacity, focus rings)\n essentialDuration: 100,\n essentialEasing: \"ease-out\",\n },\n soothing: {\n durationFast: 0, // No fast motion -- everything is slow and rhythmic\n durationBase: 800,\n durationSlow: 1200,\n easing: \"ease-in-out\", // Smooth, no sharp edges\n essentialDuration: 200,\n essentialEasing: \"ease-in-out\",\n },\n subtle: {\n durationFast: 100,\n durationBase: 200,\n durationSlow: 350,\n easing: \"ease-out\",\n essentialDuration: 150,\n essentialEasing: \"ease-out\",\n },\n expressive: {\n durationFast: 200,\n durationBase: 400,\n durationSlow: 700,\n easing: \"cubic-bezier(0.34, 1.56, 0.64, 1)\", // Spring-like overshoot\n essentialDuration: 150,\n essentialEasing: \"ease-out\",\n },\n} as const\n","/**\n * Multimodal Feedback - Phase 3\n *\n * Opt-in haptic and sonic feedback tied to capacity state.\n * Both channels are disabled by default (see DEFAULT_COMPONENT_RESPONSE.sonic.enabled).\n *\n * Haptic: Web Vibration API — short patterns on interaction\n * Sonic: Web Audio API — sub-audible tones from FEEDBACK_FREQUENCIES\n *\n * Design constraints:\n * - Opt-in only: never fires without explicit user enablement\n * - Degrades silently on unsupported browsers\n * - Volume capped at 0.08 to keep tones sub-audible (felt, not heard prominently)\n * - Arousal-aware: higher arousal → higher frequency feedback\n */\n\nimport type { ArousalMode } from \"./types\"\nimport { FEEDBACK_FREQUENCIES } from \"./constants\"\n\n// ============================================================================\n// Haptic Feedback (Web Vibration API)\n// ============================================================================\n\n/** Haptic patterns (ms on/off durations) for different interaction types */\nexport const HAPTIC_PATTERNS = {\n /** Short tap — confirm/select */\n tap: [8],\n /** Two pulses — toggle/switch */\n toggle: [8, 50, 8],\n /** Gentle pulse — ambient/ambient confirmation */\n pulse: [15, 30, 15],\n /** Error/warning — three quick */\n error: [50, 30, 50, 30, 50],\n} as const\n\nexport type HapticPatternName = keyof typeof HAPTIC_PATTERNS\n\n/**\n * Trigger a haptic vibration pattern.\n * Silently no-ops on unsupported browsers (desktop, iOS Safari).\n */\nexport function triggerHaptic(pattern: HapticPatternName = \"tap\"): void {\n if (typeof navigator !== \"undefined\" && \"vibrate\" in navigator) {\n navigator.vibrate(HAPTIC_PATTERNS[pattern])\n }\n}\n\n// ============================================================================\n// Sonic Feedback (Web Audio API)\n// ============================================================================\n\nlet _audioCtx: AudioContext | null = null\n\nfunction getAudioContext(): AudioContext | null {\n if (typeof window === \"undefined\") return null\n try {\n if (!_audioCtx || _audioCtx.state === \"closed\") {\n _audioCtx = new AudioContext()\n }\n // Resume if suspended (browser autoplay policy)\n if (_audioCtx.state === \"suspended\") {\n _audioCtx.resume()\n }\n return _audioCtx\n } catch {\n return null\n }\n}\n\n/**\n * Play a short sine-wave tone for interaction confirmation.\n *\n * @param frequency - Hz from FEEDBACK_FREQUENCIES (396/528/741)\n * @param duration - Tone length in ms (default 120)\n * @param volume - Peak gain, 0–1 (default 0.06 — sub-audible)\n */\nexport function playSonicFeedback(\n frequency: number,\n duration: number = 120,\n volume: number = 0.06,\n): void {\n const ctx = getAudioContext()\n if (!ctx) return\n\n const oscillator = ctx.createOscillator()\n const gainNode = ctx.createGain()\n\n oscillator.connect(gainNode)\n gainNode.connect(ctx.destination)\n\n oscillator.type = \"sine\"\n oscillator.frequency.setValueAtTime(frequency, ctx.currentTime)\n\n // Fade in/out envelope to prevent click artifacts\n gainNode.gain.setValueAtTime(0, ctx.currentTime)\n gainNode.gain.linearRampToValueAtTime(volume, ctx.currentTime + 0.015)\n gainNode.gain.linearRampToValueAtTime(0, ctx.currentTime + duration / 1000)\n\n oscillator.start(ctx.currentTime)\n oscillator.stop(ctx.currentTime + duration / 1000 + 0.02)\n}\n\n/**\n * Select the appropriate frequency for the current arousal level.\n *\n * calm → 396 Hz (low/root — grounding)\n * neutral → 528 Hz (mid — balanced)\n * activated → 741 Hz (high — energetic)\n */\nexport function getFrequencyForPace(pace: ArousalMode): number {\n if (pace === \"activated\") return FEEDBACK_FREQUENCIES.high\n if (pace === \"calm\") return FEEDBACK_FREQUENCIES.low\n return FEEDBACK_FREQUENCIES.mid\n}\n\n/**\n * Play sonic feedback tuned to the current arousal/pace level.\n * Convenience wrapper over playSonicFeedback + getFrequencyForPace.\n */\nexport function playPacedSonic(pace: ArousalMode, duration?: number): void {\n playSonicFeedback(getFrequencyForPace(pace), duration)\n}\n","/**\n * Field Manager - Singleton that maintains ambient field state\n *\n * Components subscribe to fields, never write to them\n * Only Phase 1 slider system writes field values\n */\n\nimport type { AmbientContext, UserCapacity, EmotionalState, FieldValue, FieldConfig } from \"../types\"\nimport { DEFAULT_USER_CAPACITY, DEFAULT_EMOTIONAL_STATE, DEFAULT_FIELD_CONFIG } from \"../constants\"\n\n// ============================================================================\n// Field Derivation Functions\n// ============================================================================\n\n/**\n * Derives energy field from user capacity\n * Energy = geometric mean of all capacity dimensions\n */\nfunction deriveEnergyField(capacity: UserCapacity): number {\n const { cognitive, temporal, emotional } = capacity\n return Math.pow(cognitive * temporal * emotional, 1 / 3)\n}\n\n/**\n * Derives attention field from temporal pressure\n * Attention inversely related to time availability\n */\nfunction deriveAttentionField(capacity: UserCapacity): number {\n // When temporal capacity is low (time pressure high), attention demand increases\n return 1 - capacity.temporal * 0.5 // Range: 0.5 to 1.0\n}\n\n/**\n * Derives emotional valence field from emotional state\n * Direct mapping of valence dimension\n */\nfunction deriveEmotionalValenceField(state: EmotionalState): number {\n return state.valence\n}\n\n// ============================================================================\n// Field Value Factory\n// ============================================================================\n\n/**\n * Creates a field value with temporal tracking\n */\nfunction createFieldValue<T>(value: T, previousValue?: FieldValue<T>): FieldValue<T> {\n const now = Date.now()\n const lastChange = previousValue?.lastChange ?? now\n const timeDelta = (now - lastChange) / 1000 // seconds\n\n let trend: \"rising\" | \"falling\" | \"stable\" = \"stable\"\n let velocity: number | undefined\n\n if (typeof value === \"number\" && previousValue && typeof previousValue.value === \"number\") {\n const valueDelta = value - previousValue.value\n velocity = timeDelta > 0 ? valueDelta / timeDelta : 0\n\n if (Math.abs(velocity) > DEFAULT_FIELD_CONFIG.velocityThreshold) {\n trend = velocity > 0 ? \"rising\" : \"falling\"\n }\n }\n\n return {\n value,\n lastChange: now,\n trend,\n velocity,\n }\n}\n\n// ============================================================================\n// Field Manager Class\n// ============================================================================\n\ntype FieldChangeListener = (context: AmbientContext) => void\n\nclass FieldManagerClass {\n private context: AmbientContext\n private listeners: Set<FieldChangeListener> = new Set()\n private config: FieldConfig = DEFAULT_FIELD_CONFIG\n\n constructor() {\n const initialCapacity = DEFAULT_USER_CAPACITY\n const initialState = DEFAULT_EMOTIONAL_STATE\n\n this.context = {\n energy: createFieldValue(deriveEnergyField(initialCapacity)),\n attention: createFieldValue(deriveAttentionField(initialCapacity)),\n emotionalValence: createFieldValue(deriveEmotionalValenceField(initialState)),\n userCapacity: initialCapacity,\n emotionalState: initialState,\n }\n }\n\n /**\n * Get current ambient context (read-only)\n */\n getContext(): Readonly<AmbientContext> {\n return this.context\n }\n\n /**\n * Update user capacity (Phase 1 slider system writes here)\n */\n updateCapacity(capacity: Partial<UserCapacity>): void {\n const newCapacity = { ...this.context.userCapacity, ...capacity }\n\n this.context = {\n ...this.context,\n userCapacity: newCapacity,\n energy: createFieldValue(deriveEnergyField(newCapacity), this.context.energy),\n attention: createFieldValue(deriveAttentionField(newCapacity), this.context.attention),\n }\n\n this.notifyListeners()\n }\n\n /**\n * Update emotional state (Phase 1 slider system writes here)\n */\n updateEmotionalState(state: Partial<EmotionalState>): void {\n const newState = { ...this.context.emotionalState, ...state }\n\n this.context = {\n ...this.context,\n emotionalState: newState,\n emotionalValence: createFieldValue(deriveEmotionalValenceField(newState), this.context.emotionalValence),\n }\n\n this.notifyListeners()\n }\n\n /**\n * Subscribe to field changes\n */\n subscribe(listener: FieldChangeListener): () => void {\n this.listeners.add(listener)\n\n // Return unsubscribe function\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n /**\n * Notify all listeners of field changes\n */\n private notifyListeners(): void {\n this.listeners.forEach((listener) => {\n try {\n listener(this.context)\n } catch (error) {\n console.error(\"[v0] Field listener error:\", error)\n }\n })\n }\n\n /**\n * Update field configuration\n */\n updateConfig(config: Partial<FieldConfig>): void {\n this.config = { ...this.config, ...config }\n }\n\n /**\n * Get current field configuration\n */\n getConfig(): Readonly<FieldConfig> {\n return this.config\n }\n}\n\n// Singleton instance\nexport const FieldManager = new FieldManagerClass()\n","/**\n * Mode Derivation - Field → Mode transformation\n *\n * This is the key insight: don't map sliders directly to 50 UI changes.\n * Instead, derive 2-4 coherent modes and let modes drive everything.\n *\n * STRICT SEPARATION OF CONCERNS:\n * ┌─────────────┬────────────────────────────────────┬─────────────────────────────┐\n * │ Slider │ Controls │ Must NOT Control │\n * ├─────────────┼────────────────────────────────────┼─────────────────────────────┤\n * │ Cognitive │ density, hierarchy, concurrency │ tone, animation speed │\n * │ Temporal │ content length, shortcuts, defaults│ color, layout structure │\n * │ Emotional │ motion restraint, friction │ content importance │\n * │ Valence │ tone, expressiveness │ information volume │\n * └─────────────┴────────────────────────────────────┴─────────────────────────────┘\n */\n\nimport type { CapacityField, InterfaceMode, InterfaceModeLabel, ArousalMode } from \"./types\"\n\n// ============================================================================\n// Mode Derivation Rules\n// ============================================================================\n\n/**\n * Derives InterfaceMode from CapacityField\n *\n * Rules:\n * - Cognitive → density (how many things compete for attention at once)\n * - Temporal → content length, shortcuts (how much time the UI asks from user)\n * - Emotional → motion restraint (nervous-system-safe UI, no surprises)\n * - Valence → tone/expressiveness (emotional color, not information volume)\n */\nexport function deriveMode(field: CapacityField): InterfaceMode {\n const lowCognitive = field.cognitive < 0.4\n const highCognitive = field.cognitive > 0.7\n const lowEmotional = field.emotional < 0.4\n const highEmotional = field.emotional > 0.6\n const lowTemporal = field.temporal < 0.4\n const highValence = field.valence > 0.15\n const negValence = field.valence < -0.15\n\n // ═══════════════════════════════════════════════════════════════════════════\n // COGNITIVE → Density, Hierarchy, Concurrency\n // Controls how many things compete for attention at once\n // Wider thresholds → clearer visual jumps between modes\n // ═══════════════════════════════════════════════════════════════════════════\n const density: InterfaceMode[\"density\"] = lowCognitive\n ? \"low\"\n : highCognitive\n ? \"high\"\n : \"medium\"\n\n // ═══════════════════════════════════════════════════════════════════════════\n // TEMPORAL → Content Length, Shortcuts, Defaults\n // Controls how much time the UI asks from the user\n // ═══════════════════════════════════════════════════════════════════════════\n const choiceLoad: InterfaceMode[\"choiceLoad\"] = lowTemporal ? \"minimal\" : \"normal\"\n\n // Guidance increases when temporal is low (provide shortcuts/defaults)\n // Also increases when cognitive is low (need more explanation)\n const guidance: InterfaceMode[\"guidance\"] = lowCognitive\n ? \"high\"\n : lowTemporal\n ? \"medium\"\n : \"low\"\n\n // ═══════════════════════════════════════════════════════════════════════════\n // EMOTIONAL → Motion Restraint, Friction\n // Controls nervous-system-safe UI (no surprises when capacity is low)\n // Four distinct tiers:\n // off: emotional < 0.15 → fully protective, static UI\n // soothing: emotional 0.15-0.4 → slow rhythmic motion only (breathe, float)\n // subtle: emotional 0.4-0.6 or low valence → grounded, minimal motion\n // expressive: emotional > 0.6 AND positive valence → full animation suite\n // ═══════════════════════════════════════════════════════════════════════════\n const veryLowEmotional = field.emotional < 0.15\n const motion: InterfaceMode[\"motion\"] = veryLowEmotional\n ? \"off\"\n : lowEmotional\n ? \"soothing\"\n : highEmotional && highValence\n ? \"expressive\"\n : \"subtle\"\n\n // ═══════════════════════════════════════════════════════════════════════════\n // VALENCE → Tone, Expressiveness (NOT information volume)\n // Controls emotional color: warmth, playfulness, accent frequency\n // ═══════════════════════════════════════════════════════════════════════════\n // Boosted contrast when mood is low helps with visual accessibility\n // This is a subtle visual adjustment, not information density\n const contrast: InterfaceMode[\"contrast\"] = negValence ? \"boosted\" : \"standard\"\n\n // ═══════════════════════════════════════════════════════════════════════════\n // COGNITIVE → Focus Guidance\n // Draws attention to important elements proportional to cognitive load.\n // Three tiers:\n // guided: cognitive < 0.4 → strong beacon glow + border (distracted)\n // gentle: cognitive < 0.7 → soft highlight + muted glow (calm/moderate)\n // default: cognitive >= 0.7 → no special treatment (focused/sharp)\n // Only activates when there IS some motion available (not \"off\"),\n // so the beacons don't appear on an already-static UI.\n // ═══════════════════════════════════════════════════════════════════════════\n const focus: InterfaceMode[\"focus\"] = motion === \"off\"\n ? \"default\"\n : lowCognitive\n ? \"guided\"\n : !highCognitive\n ? \"gentle\"\n : \"default\"\n\n // ═══════════════════════════════════════════════════════════════════════════\n // AROUSAL → Animation Pacing (Phase 3)\n // Controls HOW FAST animations play, independent of motion intensity.\n // calm: arousal < 0.35 → slow, deliberate pacing (+50% duration)\n // neutral: arousal 0.35–0.65 → standard pacing\n // activated: arousal > 0.65 → fast, energetic pacing (-35% duration)\n // ═══════════════════════════════════════════════════════════════════════════\n const arousal = field.arousal ?? 0.5\n const pace: ArousalMode = arousal < 0.35 ? \"calm\"\n : arousal > 0.65 ? \"activated\"\n : \"neutral\"\n\n return { density, guidance, motion, contrast, choiceLoad, focus, pace }\n}\n\n// ============================================================================\n// Mode Label Derivation\n// ============================================================================\n\n/**\n * Derives a human-readable mode label from raw capacity inputs\n *\n * We use RAW VALUES, not derived mode, because:\n * - Neutral (0.5, 0.5, 0.5) and Focused (0.7, 0.7, 0.6) produce the same InterfaceMode\n * - But they should have different labels (Calm vs Focused)\n * - The distinction is the RAW capacity level, not the derived mode\n *\n * Preset → Label / Motion / Focus mapping:\n * - Exhausted (0.1, 0.1, 0.1) → Minimal motion: off focus: default (static)\n * - Overwhelmed (0.2, 0.15, 0.2) → Minimal motion: soothing focus: guided (warm beacon)\n * - Distracted (0.35, 0.25, 0.5) → Minimal motion: subtle focus: guided (warm beacon)\n * - Neutral (0.5, 0.5, 0.5) → Calm motion: subtle focus: gentle (cool glow)\n * - Focused (0.75, 0.75, 0.55) → Focused motion: subtle focus: default\n * - Energized (0.9, 0.85, 0.85) → Exploratory motion: expressive focus: default\n * - Exploring (1.0, 1.0, 1.0) → Exploratory motion: expressive focus: default\n */\nexport function deriveModeLabel(inputs: CapacityField): InterfaceModeLabel {\n const { cognitive, temporal, emotional } = inputs\n\n // Exploratory: High cognitive AND high emotional capacity (energetic, engaged)\n // Threshold: both > 0.6 (lowered to capture Energized preset)\n if (cognitive > 0.6 && emotional > 0.6) {\n return \"Exploratory\"\n }\n\n // Minimal: Low capacity (cognitive AND temporal both below midpoint)\n // Threshold: both < 0.4 (raised to capture Overwhelmed + Exhausted distinctly)\n if (cognitive < 0.4 && temporal < 0.4) {\n return \"Minimal\"\n }\n\n // Focused: Good cognitive AND good temporal capacity (ready to work)\n // Threshold: both >= 0.55 (lowered slightly to capture Focused preset cleanly)\n if (cognitive >= 0.55 && temporal >= 0.55) {\n return \"Focused\"\n }\n\n // Calm: Everything else\n // Includes: Neutral (0.5s), Distracted (ok cognitive but low temporal), moderate states\n return \"Calm\"\n}\n\n// ============================================================================\n// Mode Utilities\n// ============================================================================\n\n/**\n * Get mode badge color based on label\n */\nexport function getModeBadgeColor(label: InterfaceModeLabel): string {\n switch (label) {\n case \"Calm\":\n return \"oklch(0.65 0.15 220)\" // Soft blue\n case \"Focused\":\n return \"oklch(0.68 0.16 45)\" // Primary rust\n case \"Exploratory\":\n return \"oklch(0.65 0.2 135)\" // Toxic green\n case \"Minimal\":\n return \"oklch(0.55 0.1 280)\" // Muted purple\n default:\n return \"oklch(0.5 0 0)\" // Gray\n }\n}\n","/**\n * @file Implements a signal detector for time-based capacity.\n * Emits two readings per detect() call: cognitive (hour-of-day diurnal pattern)\n * and temporal (weekday vs. weekend).\n */\n\nimport { SignalDetector, SignalReading } from './types';\n\n/**\n * The TimeDetector class implements the SignalDetector interface\n * to provide signal readings based on the current time and day.\n */\nexport class TimeDetector implements SignalDetector {\n readonly name = 'TimeDetector';\n readonly weight = 0.6; // Medium weight — time is significant but a broad generalisation\n\n /**\n * Detects and returns SignalReadings based on the current time and day.\n * Returns two readings: cognitive (hour-of-day) and temporal (weekday/weekend).\n */\n detect(): SignalReading[] {\n const now = new Date();\n const hour = now.getHours();\n const dayOfWeek = now.getDay(); // 0 = Sunday, 6 = Saturday\n const ts = now.getTime();\n\n // ── Cognitive capacity: typical diurnal patterns ────────────────────────\n let cognitiveValue: number;\n if (hour >= 9 && hour < 12) {\n cognitiveValue = 0.8; // Morning peak\n } else if (hour >= 14 && hour < 17) {\n cognitiveValue = 0.6; // Afternoon dip\n } else if (hour >= 17 && hour < 20) {\n cognitiveValue = 0.5; // Evening, winding down\n } else if (hour >= 20 || hour < 6) {\n cognitiveValue = 0.3; // Late night / early morning\n } else {\n cognitiveValue = 0.7; // Early morning ramp-up (6–9am)\n }\n\n // ── Temporal capacity: weekday vs. weekend ──────────────────────────────\n const temporalValue = (dayOfWeek >= 1 && dayOfWeek <= 5) ? 0.7 : 0.9;\n // Weekends tend to feel less time-pressured → higher temporal capacity\n\n return [\n {\n dimension: 'cognitive',\n value: cognitiveValue,\n confidence: 0.7, // Medium — population average, not personalised\n timestamp: ts,\n detectorName: this.name,\n },\n {\n dimension: 'temporal',\n value: temporalValue,\n confidence: 0.6, // Slightly lower — weekday/weekend is a coarser signal\n timestamp: ts,\n detectorName: this.name,\n },\n ];\n }\n}\n","/**\n * @file Implements a signal detector for session duration.\n * This detector assesses temporal capacity based on how long the user has been active in the current session.\n */\n\nimport { SignalDetector, SignalReading } from './types';\n\n/**\n * The SessionDetector class implements the SignalDetector interface\n * to provide signal readings based on the current session duration.\n */\nexport class SessionDetector implements SignalDetector {\n readonly name = 'SessionDetector';\n readonly weight = 0.7; // Medium-high weight, as session duration can significantly impact capacity\n private sessionStartTime: number;\n\n constructor() {\n this.sessionStartTime = Date.now();\n }\n\n /**\n * Detects and returns a SignalReading based on the current session duration.\n * It provides insights into the temporal dimension.\n *\n * @returns {SignalReading} A reading indicating the inferred capacity.\n */\n detect(): SignalReading[] {\n const now = Date.now();\n const sessionDurationMinutes = (now - this.sessionStartTime) / (1000 * 60);\n\n let temporalValue: number;\n let confidence: number;\n\n // Temporal capacity inference based on session duration\n if (sessionDurationMinutes < 15) {\n temporalValue = 0.9; // High capacity, just started\n confidence = 0.8;\n } else if (sessionDurationMinutes < 60) {\n temporalValue = 0.7; // Moderate capacity, sustained engagement\n confidence = 0.7;\n } else if (sessionDurationMinutes < 180) {\n temporalValue = 0.5; // Lower capacity, potential fatigue\n confidence = 0.6;\n } else {\n temporalValue = 0.3; // Significantly lower capacity, extended use\n confidence = 0.7;\n }\n\n return [{\n dimension: 'temporal',\n value: temporalValue,\n confidence: confidence,\n timestamp: now,\n detectorName: this.name,\n }];\n }\n}\n","/**\n * @file Implements a signal detector for scroll velocity.\n * This detector assesses cognitive capacity based on the user's scrolling behavior.\n */\n\nimport { SignalDetector, SignalReading } from './types';\n\nconst DEBOUNCE_TIME_MS = 100; // Milliseconds to debounce scroll events\n\n/**\n * The ScrollDetector class implements the SignalDetector interface\n * to provide signal readings based on scroll velocity.\n */\nexport class ScrollDetector implements SignalDetector {\n readonly name = 'ScrollDetector';\n readonly weight = 0.5; // Moderate weight, as scroll velocity can indicate engagement or frustration\n\n private lastScrollY = 0;\n private lastScrollTime = 0;\n private scrollVelocity = 0;\n private timeoutId: NodeJS.Timeout | null = null;\n\n constructor() {\n if (typeof window !== 'undefined') {\n window.addEventListener('scroll', this.handleScroll, { passive: true });\n }\n }\n\n /**\n * Handles the scroll event, debouncing it and calculating scroll velocity.\n * @private\n */\n private handleScroll = () => {\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n }\n\n this.timeoutId = setTimeout(() => {\n const now = Date.now();\n const scrollY = window.scrollY;\n\n const distance = Math.abs(scrollY - this.lastScrollY);\n const timeElapsed = now - this.lastScrollTime;\n\n if (timeElapsed > 0) {\n // Pixels per second\n this.scrollVelocity = (distance / timeElapsed) * 1000;\n } else {\n this.scrollVelocity = 0;\n }\n\n this.lastScrollY = scrollY;\n this.lastScrollTime = now;\n }, DEBOUNCE_TIME_MS);\n };\n\n /**\n * Detects and returns a SignalReading based on the current scroll velocity.\n * It provides insights into the cognitive dimension.\n *\n * @returns {SignalReading} A reading indicating the inferred capacity.\n */\n detect(): SignalReading[] {\n const now = Date.now();\n let cognitiveValue: number;\n let confidence: number;\n\n // Interpret scroll velocity: very fast/slow could indicate issues, moderate is normal\n if (this.scrollVelocity > 1500) {\n cognitiveValue = 0.4; // Very fast scroll, possibly disengaged or frantically searching\n confidence = 0.6;\n } else if (this.scrollVelocity > 500) {\n cognitiveValue = 0.7; // Moderate scroll, engaged browsing\n confidence = 0.8;\n } else if (this.scrollVelocity > 50) {\n cognitiveValue = 0.6; // Slow scroll, careful reading or struggling\n confidence = 0.7;\n } else {\n cognitiveValue = 0.5; // Very slow or no scroll, idle or deeply focused\n confidence = 0.5;\n }\n\n return [{\n dimension: 'cognitive',\n value: cognitiveValue,\n confidence: confidence,\n timestamp: now,\n detectorName: this.name,\n }];\n }\n\n /**\n * Cleans up the scroll event listener when the detector is no longer needed.\n */\n destroy() {\n if (typeof window !== 'undefined') {\n window.removeEventListener('scroll', this.handleScroll);\n if (this.timeoutId) {\n clearTimeout(this.timeoutId);\n }\n }\n }\n}\n","/**\n * @file Implements a signal detector for user interaction patterns.\n * Assesses cognitive capacity from click rate and precision using a rolling window.\n *\n * Bug fixes vs. original:\n * - clickCount / totalClickDistance accumulated forever → replaced with a 60-second\n * rolling window so recent behaviour dominates over historical averages.\n * - IDLE_THRESHOLD_MS was 3 s (too aggressive for focused reading) → raised to 15 s.\n */\n\nimport { SignalDetector, SignalReading } from './types';\n\nconst DEBOUNCE_MOVE_TIME_MS = 50;\nconst IDLE_THRESHOLD_MS = 15_000; // 15 s — focused readers pause longer than 3 s\nconst CLICK_WINDOW_MS = 60_000; // 60 s rolling window for click history\n\ninterface ClickEntry {\n time: number;\n distance: number; // px distance from previous click position\n}\n\nexport class InteractionDetector implements SignalDetector {\n readonly name = 'InteractionDetector';\n readonly weight = 0.7;\n\n private lastMouseMoveTime = 0;\n private lastClickTime = 0;\n private lastClickPosition: { x: number; y: number } | null = null;\n private clickHistory: ClickEntry[] = []; // rolling 60-second window\n private idleTimer: ReturnType<typeof setTimeout> | null = null;\n private isIdle = false;\n\n constructor() {\n if (typeof window !== 'undefined') {\n window.addEventListener('mousemove', this.handleMouseMove, { passive: true });\n window.addEventListener('click', this.handleClick, { passive: true });\n }\n this.resetIdleTimer();\n }\n\n private resetIdleTimer = () => {\n if (this.idleTimer) clearTimeout(this.idleTimer);\n this.isIdle = false;\n this.idleTimer = setTimeout(() => { this.isIdle = true; }, IDLE_THRESHOLD_MS);\n };\n\n private handleMouseMove = () => {\n this.lastMouseMoveTime = Date.now();\n this.resetIdleTimer();\n };\n\n private handleClick = (event: MouseEvent) => {\n this.resetIdleTimer();\n const now = Date.now();\n this.lastClickTime = now;\n\n let distance = 0;\n if (this.lastClickPosition) {\n const dx = event.clientX - this.lastClickPosition.x;\n const dy = event.clientY - this.lastClickPosition.y;\n distance = Math.sqrt(dx * dx + dy * dy);\n }\n this.lastClickPosition = { x: event.clientX, y: event.clientY };\n this.clickHistory.push({ time: now, distance });\n };\n\n detect(): SignalReading[] {\n const now = Date.now();\n\n // Prune entries outside the rolling window\n const cutoff = now - CLICK_WINDOW_MS;\n this.clickHistory = this.clickHistory.filter(c => c.time >= cutoff);\n\n const clickCount = this.clickHistory.length;\n const avgClickDistance =\n clickCount > 0\n ? this.clickHistory.reduce((sum, c) => sum + c.distance, 0) / clickCount\n : 0;\n\n const timeSinceLastClick = now - this.lastClickTime;\n\n let cognitiveValue: number;\n let confidence: number;\n\n if (this.isIdle) {\n cognitiveValue = 0.4; // Idle: disengaged or deeply thinking\n confidence = 0.6;\n } else if (timeSinceLastClick < 500 && clickCount > 5 && avgClickDistance < 20) {\n cognitiveValue = 0.9; // Highly engaged: frequent, precise clicks\n confidence = 0.9;\n } else if (timeSinceLastClick < 1500 && clickCount > 1 && avgClickDistance < 50) {\n cognitiveValue = 0.7; // Moderately engaged\n confidence = 0.7;\n } else if (avgClickDistance > 100) {\n cognitiveValue = 0.3; // Low precision: possibly frustrated or impaired\n confidence = 0.6;\n } else {\n cognitiveValue = 0.5; // Ambiguous / default\n confidence = 0.5;\n }\n\n return [{\n dimension: 'cognitive',\n value: cognitiveValue,\n confidence,\n timestamp: now,\n detectorName: this.name,\n }];\n }\n\n destroy() {\n if (typeof window !== 'undefined') {\n window.removeEventListener('mousemove', this.handleMouseMove);\n window.removeEventListener('click', this.handleClick);\n }\n if (this.idleTimer) clearTimeout(this.idleTimer);\n }\n}\n","/**\n * @file Implements a signal detector for user input patterns (typing speed + error rate).\n * Assesses cognitive capacity based on typing behaviour.\n *\n * Bug fix vs. original:\n * - errorCount / lastErrorTime tracked errors since an arbitrary past reset; old\n * errors counted the same as current ones → replaced with an errorTimes[] sliding\n * window so only errors within ERROR_CHECK_WINDOW (5 s) are counted.\n * - Inference now uses recentErrorCount (integer) instead of a boolean, letting the\n * code distinguish a single correction from repeated fumbling.\n */\n\nimport { SignalDetector, SignalReading } from './types';\n\nconst TYPING_SPEED_SAMPLE_SIZE = 10; // Key presses to average for CPM calculation\nconst ERROR_CHECK_WINDOW = 5_000; // ms: only count errors in this sliding window\n\nexport class InputDetector implements SignalDetector {\n readonly name = 'InputDetector';\n readonly weight = 0.6;\n\n private keyPressTimes: number[] = [];\n private errorTimes: number[] = []; // timestamps of recent Backspace/Delete presses\n\n constructor() {\n if (typeof window !== 'undefined') {\n window.addEventListener('keydown', this.handleKeyDown, { passive: true });\n }\n }\n\n private handleKeyDown = (event: KeyboardEvent) => {\n const now = Date.now();\n\n this.keyPressTimes.push(now);\n if (this.keyPressTimes.length > TYPING_SPEED_SAMPLE_SIZE) {\n this.keyPressTimes.shift();\n }\n\n if (event.key === 'Backspace' || event.key === 'Delete') {\n this.errorTimes.push(now);\n }\n };\n\n detect(): SignalReading[] {\n const now = Date.now();\n\n // ── Typing speed (characters per minute) ───────────────────────────────\n let typingSpeedCPM = 0;\n if (this.keyPressTimes.length > 1) {\n const elapsed = this.keyPressTimes[this.keyPressTimes.length - 1] - this.keyPressTimes[0];\n if (elapsed > 0) {\n typingSpeedCPM = (this.keyPressTimes.length / elapsed) * 60_000;\n }\n }\n\n // ── Recent error count (sliding window) ────────────────────────────────\n const cutoff = now - ERROR_CHECK_WINDOW;\n this.errorTimes = this.errorTimes.filter(t => t >= cutoff);\n const recentErrorCount = this.errorTimes.length;\n\n // ── Cognitive inference ─────────────────────────────────────────────────\n let cognitiveValue: number;\n let confidence: number;\n\n if (typingSpeedCPM > 100 && recentErrorCount === 0) {\n cognitiveValue = 0.9; // Fast + accurate → high cognitive capacity\n confidence = 0.8;\n } else if (typingSpeedCPM > 40 && recentErrorCount <= 1) {\n cognitiveValue = 0.7; // Moderate speed, minimal errors\n confidence = 0.7;\n } else if (recentErrorCount > 2 || typingSpeedCPM < 20) {\n cognitiveValue = 0.4; // Repeated errors or very slow → lower capacity\n confidence = 0.6;\n } else {\n cognitiveValue = 0.6; // Ambiguous / default\n confidence = 0.5;\n }\n\n return [{\n dimension: 'cognitive',\n value: cognitiveValue,\n confidence,\n timestamp: now,\n detectorName: this.name,\n }];\n }\n\n destroy() {\n if (typeof window !== 'undefined') {\n window.removeEventListener('keydown', this.handleKeyDown);\n }\n }\n}\n","/**\n * @file Implements signal detectors for environmental preferences.\n * Reads prefers-reduced-motion (→ temporal) and prefers-color-scheme (→ emotional).\n *\n * Bug fixes vs. original:\n * - Memory leak: stored MediaQueryList refs so removeEventListener unregisters the\n * exact same handler that was registered (arrow-function class properties create a\n * new reference on each access, so calling this.detect would never unregister).\n * - Discarded temporal dimension: now returns both temporal and emotional readings.\n */\n\nimport { SignalDetector, SignalReading } from './types';\n\nexport class EnvironmentDetector implements SignalDetector {\n readonly name = 'EnvironmentDetector';\n readonly weight = 0.8; // High weight — these are explicit user preferences\n\n private mqlReducedMotion: MediaQueryList | null = null;\n private mqlDarkMode: MediaQueryList | null = null;\n // A single stable handler reference that both addEventListener and\n // removeEventListener receive. detect() is stateless so the handler is a\n // no-op: the aggregator polls detect() on its own 2-second schedule.\n private readonly handleChange: () => void;\n\n constructor() {\n this.handleChange = () => {};\n if (typeof window !== 'undefined') {\n this.mqlReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');\n this.mqlDarkMode = window.matchMedia('(prefers-color-scheme: dark)');\n this.mqlReducedMotion.addEventListener('change', this.handleChange);\n this.mqlDarkMode.addEventListener('change', this.handleChange);\n }\n }\n\n /**\n * Returns two readings:\n * - temporal: based on prefers-reduced-motion (low → less time pressure on animations)\n * - emotional: based on prefers-color-scheme (dark → slightly lower emotional load)\n */\n detect(): SignalReading[] {\n const now = Date.now();\n\n // Use stored refs for efficiency; fall back to fresh queries on SSR or if\n // the constructor ran without a window (e.g. jest with no matchMedia stub).\n const prefersReducedMotion =\n this.mqlReducedMotion != null\n ? this.mqlReducedMotion.matches\n : typeof window !== 'undefined' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\n const prefersDarkMode =\n this.mqlDarkMode != null\n ? this.mqlDarkMode.matches\n : typeof window !== 'undefined' &&\n window.matchMedia('(prefers-color-scheme: dark)').matches;\n\n return [\n {\n dimension: 'temporal',\n // prefers-reduced-motion → user may have lower tolerance for demanding UIs\n value: prefersReducedMotion ? 0.3 : 0.8,\n confidence: 0.9,\n timestamp: now,\n detectorName: this.name,\n },\n {\n dimension: 'emotional',\n // Dark mode preference → slightly lower emotional capacity or reduced-stimulation preference\n value: prefersDarkMode ? 0.6 : 0.7,\n confidence: 0.9,\n timestamp: now,\n detectorName: this.name,\n },\n ];\n }\n\n /**\n * Removes the event listeners registered in the constructor.\n * Uses the stored refs so the same function reference is unregistered.\n */\n destroy() {\n this.mqlReducedMotion?.removeEventListener('change', this.handleChange);\n this.mqlDarkMode?.removeEventListener('change', this.handleChange);\n this.mqlReducedMotion = null;\n this.mqlDarkMode = null;\n }\n}\n","/**\n * @file Aggregates signals from all detectors into a suggested CapacityField.\n *\n * Bug fixes vs. original:\n * - detect() now returns SignalReading[] so readings.push(...) spreads the array.\n * - getDetectorWeight() now uses a per-detector/dimension lookup table instead of\n * ignoring the dimension parameter.\n * - destroy() uses the optional-chaining destroy?() instead of (detector as any).destroy().\n */\n\nimport { SignalDetector, SignalReading } from './detectors/types';\nimport { CapacityField } from '../types';\nimport { TimeDetector } from './detectors/time-detector';\nimport { SessionDetector } from './detectors/session-detector';\nimport { ScrollDetector } from './detectors/scroll-detector';\nimport { InteractionDetector } from './detectors/interaction-detector';\nimport { InputDetector } from './detectors/input-detector';\nimport { EnvironmentDetector } from './detectors/environment-detector';\n\nexport class SignalAggregator {\n private detectors: SignalDetector[];\n\n /**\n * Per-detector, per-dimension weight overrides.\n * Falls back to detector.weight for any unlisted combination.\n *\n * Rationale for asymmetries:\n * - TimeDetector: cognitive signal is stronger (diurnal pattern) than temporal\n * (weekday/weekend is coarser)\n * - EnvironmentDetector: emotional signal (color scheme) is a stronger explicit\n * preference than temporal (reduced-motion)\n */\n private static readonly DIMENSION_WEIGHTS: Partial<\n Record<string, Partial<Record<SignalReading['dimension'], number>>>\n > = {\n TimeDetector: { cognitive: 0.6, temporal: 0.5 },\n EnvironmentDetector: { emotional: 0.8, temporal: 0.7 },\n InteractionDetector: { cognitive: 0.7 },\n InputDetector: { cognitive: 0.6 },\n SessionDetector: { temporal: 0.7 },\n ScrollDetector: { cognitive: 0.5 },\n };\n\n constructor() {\n this.detectors = [\n new TimeDetector(),\n new SessionDetector(),\n new ScrollDetector(),\n new InteractionDetector(),\n new InputDetector(),\n new EnvironmentDetector(),\n ];\n }\n\n /**\n * Collects signal readings from all detectors and aggregates them into a\n * confidence-weighted CapacityField.\n */\n async aggregateSignals(): Promise<CapacityField> {\n const readings: SignalReading[] = [];\n\n for (const detector of this.detectors) {\n const detectorReadings = await detector.detect();\n readings.push(...detectorReadings);\n }\n\n const weightedSums: Record<SignalReading['dimension'], number> = {\n cognitive: 0, temporal: 0, emotional: 0, valence: 0,\n };\n const totalWeights: Record<SignalReading['dimension'], number> = {\n cognitive: 0, temporal: 0, emotional: 0, valence: 0,\n };\n\n for (const reading of readings) {\n const effectiveWeight =\n reading.confidence * this.getDetectorWeight(reading.dimension, reading.detectorName);\n weightedSums[reading.dimension] += reading.value * effectiveWeight;\n totalWeights[reading.dimension] += effectiveWeight;\n }\n\n return {\n cognitive: totalWeights.cognitive > 0 ? weightedSums.cognitive / totalWeights.cognitive : 0.5,\n temporal: totalWeights.temporal > 0 ? weightedSums.temporal / totalWeights.temporal : 0.5,\n emotional: totalWeights.emotional > 0 ? weightedSums.emotional / totalWeights.emotional : 0.5,\n valence: totalWeights.valence > 0 ? weightedSums.valence / totalWeights.valence : 0,\n };\n }\n\n /**\n * Returns the effective weight for a detector/dimension pair.\n * Checks DIMENSION_WEIGHTS first; falls back to detector.weight.\n */\n private getDetectorWeight(\n dimension: SignalReading['dimension'],\n detectorName: string,\n ): number {\n const override = SignalAggregator.DIMENSION_WEIGHTS[detectorName]?.[dimension];\n if (override !== undefined) return override;\n return this.detectors.find(d => d.name === detectorName)?.weight ?? 0;\n }\n\n /** Cleans up all detector resources (event listeners, timers). */\n destroy() {\n for (const detector of this.detectors) {\n detector.destroy?.();\n }\n }\n}\n","/**\n * Capacity Provider - React Context wrapper for ambient fields\n *\n * Wraps application root and exposes field hooks\n */\n\n\"use client\"\n\nimport type React from \"react\"\n\nimport { createContext, useContext, useEffect, useState, useCallback, useRef, type Dispatch, type SetStateAction } from \"react\"\nimport type { AmbientContext, UserCapacity, EmotionalState, MotionMode, CapacityField, InterfaceMode } from \"./types\"\nimport { triggerHaptic, playPacedSonic, type HapticPatternName } from \"./feedback\"\nimport { FieldManager } from \"./fields/field-manager\"\nimport { deriveMode } from \"./mode\"\nimport { MOTION_TOKENS, DEFAULT_CAPACITY_FIELD } from \"./constants\"\nimport { SignalAggregator } from \"./signals/aggregator\"\n\n// ============================================================================\n// Context Definition\n// ============================================================================\n\ninterface CapacityContextValue {\n context: AmbientContext\n updateCapacity: (capacity: Partial<UserCapacity>) => void\n updateEmotionalState: (state: Partial<EmotionalState>) => void\n isAutoMode: boolean;\n toggleAutoMode: () => void;\n updateCapacityField: (field: CapacityField) => void;\n hapticEnabled: boolean;\n sonicEnabled: boolean;\n setHapticEnabled: Dispatch<SetStateAction<boolean>>;\n setSonicEnabled: Dispatch<SetStateAction<boolean>>;\n}\n\nconst CapacityContext = createContext<CapacityContextValue | null>(null)\n\n// ============================================================================\n// Provider Component\n// ============================================================================\n\n/**\n * Exponential moving average weight for auto-mode signal smoothing.\n *\n * Each new reading contributes this fraction; the previous smoothed value\n * keeps (1 − α). A lower value means more smoothing and a longer \"warm-up\"\n * before a mode label actually flips — roughly α=0.2 means 4–5 consecutive\n * 2-second polls (~8–10 s) before a step-change lands at ≈ 67 % of its\n * final value, preventing single noisy readings from triggering a switch.\n */\nconst AUTO_EMA_ALPHA = 0.2;\n\nfunction applyEMA(prev: CapacityField, next: CapacityField, alpha: number): CapacityField {\n return {\n cognitive: prev.cognitive * (1 - alpha) + next.cognitive * alpha,\n temporal: prev.temporal * (1 - alpha) + next.temporal * alpha,\n emotional: prev.emotional * (1 - alpha) + next.emotional * alpha,\n valence: prev.valence * (1 - alpha) + next.valence * alpha,\n };\n}\n\nexport function CapacityProvider({ children }: { children: React.ReactNode }) {\n const [context, setContext] = useState<AmbientContext>(() => FieldManager.getContext());\n const [isAutoMode, setIsAutoMode] = useState<boolean>(true); // Start in auto mode\n const [hapticEnabled, setHapticEnabled] = useState<boolean>(false);\n const [sonicEnabled, setSonicEnabled] = useState<boolean>(false);\n const isFirstAggregationComplete = useRef<boolean>(false); // New ref to control initial aggregator application\n const smoothedFieldRef = useRef<CapacityField | null>(null); // EMA-smoothed field for auto mode\n const aggregatorRef = useRef<SignalAggregator | null>(null);\n\n useEffect(() => {\n // Initialize aggregator on mount\n aggregatorRef.current = new SignalAggregator();\n\n const unsubscribe = FieldManager.subscribe((newContext) => {\n setContext(newContext);\n });\n\n return () => {\n unsubscribe();\n // Clean up aggregator on unmount\n if (aggregatorRef.current) {\n aggregatorRef.current.destroy();\n }\n };\n }, []);\n\n // Effect to run aggregator in auto mode\n useEffect(() => {\n let intervalId: NodeJS.Timeout;\n\n if (isAutoMode && aggregatorRef.current) {\n // Reset smoothing state when (re-)entering auto mode so stale manual\n // slider positions don't bias the EMA baseline.\n isFirstAggregationComplete.current = false;\n smoothedFieldRef.current = null;\n intervalId = setInterval(async () => {\n try {\n const suggestedField = await aggregatorRef.current!.aggregateSignals();\n\n if (!isFirstAggregationComplete.current) {\n // Skip the very first aggregation — detectors need one cycle to stabilise.\n // Seed the EMA with this reading so the next poll has a sensible baseline.\n isFirstAggregationComplete.current = true;\n smoothedFieldRef.current = suggestedField;\n } else {\n // Apply EMA smoothing: new readings blend in gradually so a single\n // noisy poll can't instantly flip the mode label.\n smoothedFieldRef.current = applyEMA(\n smoothedFieldRef.current ?? suggestedField,\n suggestedField,\n AUTO_EMA_ALPHA,\n );\n const smoothed = smoothedFieldRef.current;\n FieldManager.updateCapacity({\n cognitive: smoothed.cognitive,\n temporal: smoothed.temporal,\n emotional: smoothed.emotional,\n });\n FieldManager.updateEmotionalState({\n valence: smoothed.valence,\n });\n }\n } catch (error) {\n // Log but do not crash — auto mode silently degrades on transient failures\n console.warn('[CapacityProvider] Signal aggregation failed:', error);\n }\n }, 2000); // Aggregate every 2 seconds\n }\n\n return () => {\n if (intervalId) {\n clearInterval(intervalId);\n }\n };\n }, [isAutoMode]);\n\n // Memoized update functions\n const updateCapacity = useCallback((capacity: Partial<UserCapacity>) => {\n if (isAutoMode) {\n setIsAutoMode(false); // Switch to manual mode if user manually updates capacity\n }\n FieldManager.updateCapacity(capacity);\n }, [isAutoMode]);\n\n const updateEmotionalState = useCallback((state: Partial<EmotionalState>) => {\n if (isAutoMode) {\n setIsAutoMode(false); // Switch to manual mode if user manually updates emotional state\n }\n FieldManager.updateEmotionalState(state);\n }, [isAutoMode]);\n\n const updateCapacityField = useCallback((field: CapacityField) => {\n // This function can be used to set the full capacity field directly, regardless of auto mode.\n // Useful for initial setup or explicit overrides.\n FieldManager.updateCapacity({\n cognitive: field.cognitive,\n temporal: field.temporal,\n emotional: field.emotional,\n });\n FieldManager.updateEmotionalState({\n valence: field.valence,\n });\n }, []);\n\n const toggleAutoMode = useCallback(() => {\n setIsAutoMode((prev) => !prev);\n }, []);\n\n return (\n <CapacityContext.Provider value={{\n context, updateCapacity, updateEmotionalState, isAutoMode, toggleAutoMode, updateCapacityField,\n hapticEnabled, sonicEnabled, setHapticEnabled, setSonicEnabled,\n }}>\n {children}\n </CapacityContext.Provider>\n );\n}\n\n// ============================================================================\n// Hooks\n// ============================================================================\n\n/**\n * Access full ambient context\n * Most components should use specific field hooks instead\n */\nexport function useCapacityContext(): CapacityContextValue {\n const context = useContext(CapacityContext)\n if (!context) {\n throw new Error(\"useCapacityContext must be used within CapacityProvider\")\n }\n return context\n}\n\n/**\n * Subscribe to energy field only\n */\nexport function useEnergyField() {\n const { context } = useCapacityContext()\n return context.energy\n}\n\n/**\n * Subscribe to attention field only\n */\nexport function useAttentionField() {\n const { context } = useCapacityContext()\n return context.attention\n}\n\n/**\n * Subscribe to emotional valence field only\n */\nexport function useEmotionalValenceField() {\n const { context } = useCapacityContext()\n return context.emotionalValence\n}\n\n/**\n * Get field update functions (for Phase 1 slider system)\n */\nexport function useFieldControls() {\n const { updateCapacity, updateEmotionalState, isAutoMode, toggleAutoMode, updateCapacityField } = useCapacityContext()\n return { updateCapacity, updateEmotionalState, isAutoMode, toggleAutoMode, updateCapacityField }\n}\n\n/**\n * Detect system prefers-reduced-motion preference\n * Returns true if user has requested reduced motion\n */\nexport function usePrefersReducedMotion(): boolean {\n const [prefersReducedMotion, setPrefersReducedMotion] = useState(false)\n\n useEffect(() => {\n // Check initial value\n const mediaQuery = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n setPrefersReducedMotion(mediaQuery.matches)\n\n // Listen for changes\n const handleChange = (event: MediaQueryListEvent) => {\n setPrefersReducedMotion(event.matches)\n }\n\n mediaQuery.addEventListener(\"change\", handleChange)\n return () => mediaQuery.removeEventListener(\"change\", handleChange)\n }, [])\n\n return prefersReducedMotion\n}\n\n/**\n * Derive the full mode from current capacity context.\n * This is the primary hook for section-level components that need\n * the field values AND the derived mode together.\n * \n * Eliminates the repeated { cognitive: context.userCapacity.cognitive, ... }\n * construction that was duplicated across every section component.\n */\nexport function useDerivedMode(): {\n field: CapacityField\n mode: InterfaceMode\n} {\n const { context } = useCapacityContext()\n\n const field: CapacityField = {\n cognitive: context.userCapacity.cognitive,\n temporal: context.userCapacity.temporal,\n emotional: context.userCapacity.emotional,\n valence: context.emotionalState.valence,\n arousal: context.emotionalState.arousal,\n }\n\n const mode = deriveMode(field)\n\n return { field, mode }\n}\n\n/**\n * Get effective motion mode with system preference override\n *\n * System prefers-reduced-motion is a HARD OVERRIDE - non-negotiable on safety.\n * This ensures accessibility compliance regardless of derived mode.\n */\nexport function useEffectiveMotion(): {\n mode: MotionMode\n tokens: typeof MOTION_TOKENS[keyof typeof MOTION_TOKENS]\n prefersReducedMotion: boolean\n} {\n const { field } = useDerivedMode()\n const prefersReducedMotion = usePrefersReducedMotion()\n\n const derivedMode = deriveMode(field)\n const effectiveMode: MotionMode = prefersReducedMotion ? \"off\" : derivedMode.motion\n\n return {\n mode: effectiveMode,\n tokens: MOTION_TOKENS[effectiveMode],\n prefersReducedMotion,\n }\n}\n\n/**\n * Access multimodal feedback preferences and fire helper.\n *\n * Reads opt-in flags from context — feedback only fires when the user\n * has explicitly enabled it in the CapacityControls panel.\n * Pace-aware: sonic frequency adapts to current arousal level.\n */\nexport function useFeedback(): {\n hapticEnabled: boolean\n sonicEnabled: boolean\n setHapticEnabled: Dispatch<SetStateAction<boolean>>\n setSonicEnabled: Dispatch<SetStateAction<boolean>>\n fire: (pattern?: HapticPatternName) => void\n} {\n const { hapticEnabled, sonicEnabled, setHapticEnabled, setSonicEnabled } = useCapacityContext()\n const { mode } = useDerivedMode()\n\n const fire = useCallback((pattern: HapticPatternName = \"tap\") => {\n if (hapticEnabled) triggerHaptic(pattern)\n if (sonicEnabled) playPacedSonic(mode.pace)\n }, [hapticEnabled, sonicEnabled, mode.pace])\n\n return { hapticEnabled, sonicEnabled, setHapticEnabled, setSonicEnabled, fire }\n}\n\n/**\n * Get motion tokens with arousal-based pacing applied (Phase 3)\n *\n * Arousal independently controls animation speed:\n * - calm (< 0.35): +50% duration — slow, deliberate\n * - neutral (0.35–0.65): standard duration\n * - activated (> 0.65): -35% duration — fast, energetic\n *\n * System prefers-reduced-motion overrides pace to \"calm\" for safety.\n */\nexport function usePacedMotionTokens(): {\n mode: MotionMode\n pace: ReturnType<typeof deriveMode>[\"pace\"]\n tokens: {\n durationFast: number\n durationBase: number\n durationSlow: number\n easing: string\n essentialDuration: number\n essentialEasing: string\n }\n} {\n const { mode } = useDerivedMode()\n const { mode: effectiveMotion, tokens: baseTokens, prefersReducedMotion } = useEffectiveMotion()\n\n const effectivePace = prefersReducedMotion ? \"calm\" : mode.pace\n const multiplier = effectivePace === \"calm\" ? 1.5 : effectivePace === \"activated\" ? 0.65 : 1.0\n\n return {\n mode: effectiveMotion,\n pace: effectivePace,\n tokens: {\n ...baseTokens,\n durationFast: Math.round(baseTokens.durationFast * multiplier),\n durationBase: Math.round(baseTokens.durationBase * multiplier),\n durationSlow: Math.round(baseTokens.durationSlow * multiplier),\n },\n }\n}\n","/**\n * Capacity-aware animation class utilities.\n *\n * Centralizes the repeated pattern of selecting CSS animation classes\n * based on the current motion mode (off / subtle / expressive).\n * Each section was independently deriving the same entranceClass / hoverClass /\n * ambientClass -- this module makes it a single source of truth.\n */\n\nimport type { MotionMode, FocusMode } from \"./types\"\n\n// ============================================================================\n// Entrance animations (one-shot, runs once when section scrolls into view)\n// ============================================================================\n\n/**\n * Map of named entrance animation presets.\n * Each preset maps a MotionMode to a CSS class name from globals.css.\n * \"off\" always maps to \"\" (no animation).\n */\nconst ENTRANCE_PRESETS = {\n /** Liquid organic morph -> gentle scale fade -> soft bloom -> none */\n morph: { expressive: \"morph-fade-in\", subtle: \"sacred-fade\", soothing: \"bloom\", off: \"\" },\n /** Spinning vortex -> gentle scale fade -> soft bloom -> none */\n vortex: { expressive: \"vortex-reveal\", subtle: \"sacred-fade\", soothing: \"bloom\", off: \"\" },\n /** Spiral in from corner -> soft bloom -> soft bloom -> none */\n spiral: { expressive: \"spiral-in\", subtle: \"bloom\", soothing: \"bloom\", off: \"\" },\n} as const\n\ntype EntrancePreset = keyof typeof ENTRANCE_PRESETS\n\n/**\n * Returns the appropriate entrance animation class for the given motion mode.\n * Returns \"\" when hasPlayed is true, preventing re-render flicker.\n */\nexport function entranceClass(\n motion: MotionMode,\n preset: EntrancePreset,\n hasPlayed: boolean,\n): string {\n if (hasPlayed) return \"\"\n return ENTRANCE_PRESETS[preset][motion]\n}\n\n// ============================================================================\n// Hover animations (applied as a persistent class, triggered by :hover in CSS)\n// ============================================================================\n\n/**\n * Returns the appropriate hover animation class.\n * \"off\" mode disables hover animations entirely.\n */\nexport function hoverClass(motion: MotionMode): string {\n if (motion === \"expressive\") return \"hover-expand\"\n if (motion === \"subtle\" || motion === \"soothing\") return \"hover-lift\"\n return \"\"\n}\n\n// ============================================================================\n// Ambient animations (looping, always active while mode is expressive)\n// ============================================================================\n\n/**\n * Returns a class for continuous ambient animation (breathing, floating, etc.)\n *\n * - expressive: all ambient types active\n * - soothing: only slow, rhythmic types (breathe, float) -- calms the nervous system\n * - subtle / off: no ambient animation\n */\nexport function ambientClass(motion: MotionMode, type: \"breathe\" | \"float\" | \"pulse\" | \"vibrate\"): string {\n if (motion === \"expressive\") return type\n if (motion === \"soothing\" && (type === \"breathe\" || type === \"float\")) return type\n return \"\"\n}\n\n/**\n * Returns the appropriate animation class for list items (staggered entrance).\n * Expressive: helix-rise, Subtle: sacred-fade, Off: none.\n */\nexport function listItemClass(motion: MotionMode): string {\n if (motion === \"expressive\") return \"helix-rise\"\n if (motion === \"subtle\" || motion === \"soothing\") return \"sacred-fade\"\n return \"\"\n}\n\n// ============================================================================\n// Focus / attention-drawing classes (activated by FocusMode \"guided\" or \"gentle\")\n// ============================================================================\n\n/**\n * Returns attention-beacon class for important container elements (cards, CTAs).\n * - guided: strong warm glow (3s cycle) + border accent\n * - gentle: muted cool glow (5s cycle) + softer border\n * - default: no treatment\n */\nexport function focusBeaconClass(focus: FocusMode): string {\n if (focus === \"guided\") return \"attention-beacon focus-highlight\"\n if (focus === \"gentle\") return \"gentle-beacon gentle-highlight\"\n return \"\"\n}\n\n/**\n * Returns attention-text class for important headings / labels.\n * - guided: warm text-shadow pulse (3s)\n * - gentle: cool text-shadow pulse (5s)\n * - default: no treatment\n */\nexport function focusTextClass(focus: FocusMode): string {\n if (focus === \"guided\") return \"attention-text\"\n if (focus === \"gentle\") return \"gentle-text\"\n return \"\"\n}\n","/**\n * Typography Utilities - Renge (Proportional Form)\n *\n * Font scaling based on golden ratio with subtle randomness\n * and energy-based adjustments for cognitive load adaptation.\n *\n * Philosophy:\n * - Legibility first: minimum sizes and contrast are non-negotiable\n * - φ-based modular scale prevents arbitrary sizing\n * - Small random jitter (±5%) prevents mechanical rigidity\n * - Energy-based bias: low energy = larger (readability), high = smaller (density)\n */\n\nimport { PHI, FIBONACCI } from \"../constants\"\nimport type { DensityMode } from \"../types\"\n\n// ============================================================================\n// Type Definitions\n// ============================================================================\n\n/**\n * Typography roles in the UI hierarchy\n * Maps to semantic HTML elements\n */\nexport type TypographyRole = \"h1\" | \"h2\" | \"h3\" | \"h4\" | \"body\" | \"caption\" | \"label\"\n\n/**\n * Energy levels derived from EnergyField\n * Influences sizing bias for cognitive adaptation\n */\nexport type EnergyLevel = \"low\" | \"medium\" | \"high\"\n\n/**\n * Attention levels derived from AttentionField\n * Influences weight and spacing for focus\n */\nexport type AttentionLevel = \"low\" | \"medium\" | \"high\"\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** Base font size in pixels (browser default) */\nconst BASE_FONT_SIZE = 16\n\n/** Minimum font size for accessibility (WCAG) */\nconst MIN_FONT_SIZE = 14\n\n/** Maximum random jitter factor (±5%) */\nconst JITTER_FACTOR = 0.05\n\n/**\n * Scale steps for each typography role\n * Uses powers of φ for natural growth\n */\nconst SCALE_STEPS: Record<TypographyRole, number> = {\n h1: 4, // φ^4 ≈ 6.85x base\n h2: 3, // φ^3 ≈ 4.24x base\n h3: 2, // φ^2 ≈ 2.62x base\n h4: 1, // φ^1 ≈ 1.62x base\n body: 0, // φ^0 = 1x base\n label: -0.5, // φ^-0.5 ≈ 0.79x base\n caption: -1, // φ^-1 ≈ 0.62x base\n}\n\n/**\n * Energy-based size multipliers\n * Low energy: slightly larger for readability under cognitive load\n * High energy: slightly smaller for information density\n */\nconst ENERGY_BIAS: Record<EnergyLevel, number> = {\n low: 1.05, // +5% for better readability when tired\n medium: 1.0, // Neutral\n high: 0.95, // -5% for higher density when alert\n}\n\n/**\n * Attention-based font weight adjustments\n * Higher attention = bolder to aid focus\n */\nconst ATTENTION_WEIGHT: Record<AttentionLevel, number> = {\n low: 400, // Regular\n medium: 450, // Medium\n high: 500, // Medium-bold for focus\n}\n\n/**\n * Attention-based letter spacing (em units)\n * Tighter when focused, looser when relaxed\n */\nconst ATTENTION_TRACKING: Record<AttentionLevel, number> = {\n low: 0.02, // Loose tracking for comfortable reading\n medium: 0, // Normal\n high: -0.01, // Tight tracking for focus\n}\n\n// ============================================================================\n// Core Functions\n// ============================================================================\n\n/**\n * Modular scale function using golden ratio\n *\n * @param step - Power of φ to scale by (can be negative for smaller sizes)\n * @param base - Base size in pixels (default: 16)\n * @returns Scaled size in pixels\n *\n * Example:\n * modularScale(2) → 16 * φ^2 ≈ 41.89px\n * modularScale(-1) → 16 * φ^-1 ≈ 9.89px\n */\nexport function modularScale(step: number, base: number = BASE_FONT_SIZE): number {\n return base * Math.pow(PHI, step)\n}\n\n/**\n * Get font size with φ-based scaling, random jitter, and energy bias\n *\n * @param role - Typography role (h1, h2, body, etc.)\n * @param energy - Energy level from EnergyField (default: medium)\n * @param options - Optional overrides\n * @returns Font size in pixels (clamped to minimum)\n *\n * Design decisions:\n * 1. Uses φ-based modular scale for natural proportions\n * 2. Adds ±5% random jitter to prevent mechanical feel\n * 3. Biases size based on energy: low = larger, high = smaller\n * 4. Always respects minimum font size for accessibility\n */\nexport function getFontSize(\n role: TypographyRole,\n energy: EnergyLevel = \"medium\",\n options?: {\n base?: number\n jitter?: boolean\n minSize?: number\n },\n): number {\n const { base = BASE_FONT_SIZE, jitter = true, minSize = MIN_FONT_SIZE } = options || {}\n\n // Calculate base scale from φ ratio\n const step = SCALE_STEPS[role]\n const baseSize = modularScale(step, base)\n\n // Apply random jitter (±5%) if enabled\n // This prevents the UI from feeling too rigid/mechanical\n const jitterAmount = jitter ? (Math.random() - 0.5) * 2 * JITTER_FACTOR : 0\n const jitteredSize = baseSize * (1 + jitterAmount)\n\n // Apply energy-based bias for cognitive adaptation\n const energyAdjustedSize = jitteredSize * ENERGY_BIAS[energy]\n\n // Clamp to minimum for accessibility\n return Math.max(energyAdjustedSize, minSize)\n}\n\n/**\n * Get font weight based on attention level\n *\n * @param attention - Attention level from AttentionField\n * @returns Font weight value (400-500)\n *\n * Higher attention = bolder text to help maintain focus\n */\nexport function getFontWeight(attention: AttentionLevel = \"medium\"): number {\n return ATTENTION_WEIGHT[attention]\n}\n\n/**\n * Get letter spacing based on attention level\n *\n * @param attention - Attention level from AttentionField\n * @returns Letter spacing in em units\n *\n * Tighter tracking when focused, looser when relaxed\n */\nexport function getLetterSpacing(attention: AttentionLevel = \"medium\"): number {\n return ATTENTION_TRACKING[attention]\n}\n\n/**\n * Get line height based on typography role\n *\n * @param role - Typography role\n * @returns Line height as unitless multiplier\n *\n * Design decisions:\n * - Headings: tighter (1.2-1.3) for visual impact\n * - Body: comfortable reading (1.5-1.6)\n * - Always maintains readability standards\n */\nexport function getLineHeight(role: TypographyRole): number {\n const lineHeights: Record<TypographyRole, number> = {\n h1: 1.2,\n h2: 1.25,\n h3: 1.3,\n h4: 1.35,\n body: 1.5,\n label: 1.4,\n caption: 1.45,\n }\n\n return lineHeights[role]\n}\n\n// ============================================================================\n// Composite Helpers\n// ============================================================================\n\n/**\n * Get complete typography styles for a role\n *\n * @param role - Typography role\n * @param energy - Energy level from EnergyField\n * @param attention - Attention level from AttentionField\n * @returns Complete CSS-in-JS typography object\n *\n * Returns all typography properties in one call for convenience\n */\nexport function getTypographyStyles(\n role: TypographyRole,\n energy: EnergyLevel = \"medium\",\n attention: AttentionLevel = \"medium\",\n) {\n return {\n fontSize: `${getFontSize(role, energy)}px`,\n fontWeight: getFontWeight(attention),\n lineHeight: getLineHeight(role),\n letterSpacing: `${getLetterSpacing(attention)}em`,\n }\n}\n\n/**\n * Get responsive font size with clamp()\n *\n * @param role - Typography role\n * @param energy - Energy level\n * @returns CSS clamp() expression for fluid typography\n *\n * Creates fluid typography that scales between viewport sizes\n * while respecting φ-based proportions\n */\nexport function getFluidFontSize(role: TypographyRole, energy: EnergyLevel = \"medium\"): string {\n const minSize = getFontSize(role, energy, { jitter: false })\n const maxSize = minSize * 1.2 // 20% range for fluidity\n\n // Fluid scaling between 320px and 1920px viewports\n return `clamp(${minSize}px, ${minSize}px + (${maxSize - minSize}) * ((100vw - 320px) / 1600), ${maxSize}px)`\n}\n\n// ============================================================================\n// Proportional Spacing System (Fibonacci / Golden Ratio) — Phase 3\n// ============================================================================\n\n/** Base spacing unit in pixels (4px = 0.25rem grid) */\nconst SPACING_BASE = 4\n\n/**\n * Fibonacci-based spacing scale.\n * Each step is a Fibonacci number × SPACING_BASE (4px):\n *\n * Step | Fibonacci | px | rem\n * -----|-----------|-----|-----\n * 0 | 1 | 4 | 0.25\n * 1 | 1 | 4 | 0.25\n * 2 | 2 | 8 | 0.5\n * 3 | 3 | 12 | 0.75\n * 4 | 5 | 20 | 1.25\n * 5 | 8 | 32 | 2\n * 6 | 13 | 52 | 3.25\n * 7 | 21 | 84 | 5.25\n * 8 | 34 | 136 | 8.5\n * 9 | 55 | 220 | 13.75\n */\nexport const SPACING_SCALE = FIBONACCI.map((f) => f * SPACING_BASE)\n\n/**\n * Get spacing value from Fibonacci scale.\n *\n * @param step - Scale step (0–11, maps to FIBONACCI sequence)\n * @param unit - Return \"px\" string, \"rem\" string, or raw number (default: \"px\")\n * @returns Spacing value\n *\n * @example\n * getSpacing(4) // \"20px\" (Fibonacci[4]=5 × 4)\n * getSpacing(5, \"rem\") // \"2rem\" (Fibonacci[5]=8 × 4 / 16)\n * getSpacing(3, \"raw\") // 12\n */\nexport function getSpacing(\n step: number,\n unit: \"px\" | \"rem\" | \"raw\" = \"px\",\n): string | number {\n const clampedStep = Math.max(0, Math.min(step, SPACING_SCALE.length - 1))\n const raw = SPACING_SCALE[clampedStep]\n\n if (unit === \"raw\") return raw\n if (unit === \"rem\") return `${(raw / 16).toFixed(4).replace(/\\.?0+$/, \"\")}rem`\n return `${raw}px`\n}\n\n/**\n * Get proportional padding/gap values based on current density mode.\n *\n * Returns CSS-ready spacing strings using the Fibonacci scale,\n * scaled back at low density (less space) and up at high density (more breathing room).\n *\n * @param density - Current density mode from InterfaceMode\n * @returns Object of CSS spacing values for padding, gap, etc.\n */\nexport function getProportionalSpacing(density: DensityMode): {\n xs: string // Inline/tight spacing\n sm: string // Component internal padding\n md: string // Section/card padding\n lg: string // Between-section gap\n gap: string // Grid/flex gap\n} {\n // Fibonacci steps shift by density\n const shift = density === \"low\" ? -1 : density === \"high\" ? 1 : 0\n\n return {\n xs: getSpacing(2 + shift) as string,\n sm: getSpacing(3 + shift) as string,\n md: getSpacing(5 + shift) as string,\n lg: getSpacing(7 + shift) as string,\n gap: getSpacing(4 + shift) as string,\n }\n}\n\n/**\n * Get a φ-based size ratio for proportional component scaling.\n *\n * @param steps - Number of φ steps (positive = larger, negative = smaller)\n * @returns Unitless multiplier based on powers of φ\n *\n * @example\n * phiRatio(1) // 1.618 — golden ratio\n * phiRatio(-1) // 0.618 — inverse golden ratio\n * phiRatio(2) // 2.618 — φ²\n */\nexport function phiRatio(steps: number): number {\n return Math.pow(PHI, steps)\n}\n","/**\n * Signal Bus - Type-safe pub/sub for inter-component communication\n *\n * Components emit signals, never directly call each other\n */\n\nimport type { Signal, SignalHandler, Unsubscribe, SignalPriority } from \"../types\"\n\n// ============================================================================\n// Signal Bus Class\n// ============================================================================\n\nclass SignalBusClass {\n private handlers: Map<string, Set<SignalHandler>> = new Map()\n private signalQueue: Signal[] = []\n private processing = false\n\n /**\n * Emit a signal to all subscribed handlers\n */\n emit<T = unknown>(type: string, payload: T, priority: SignalPriority = \"normal\", source?: string): void {\n const signal: Signal<T> = {\n type,\n payload,\n timestamp: Date.now(),\n priority,\n source,\n }\n\n // Add to queue based on priority\n if (priority === \"critical\") {\n this.signalQueue.unshift(signal)\n } else {\n this.signalQueue.push(signal)\n }\n\n // Process queue\n this.processQueue()\n }\n\n /**\n * Subscribe to a specific signal type\n */\n subscribe<T = unknown>(type: string, handler: SignalHandler<T>): Unsubscribe {\n if (!this.handlers.has(type)) {\n this.handlers.set(type, new Set())\n }\n\n const handlers = this.handlers.get(type)!\n handlers.add(handler as SignalHandler)\n\n // Return unsubscribe function\n return () => {\n handlers.delete(handler as SignalHandler)\n if (handlers.size === 0) {\n this.handlers.delete(type)\n }\n }\n }\n\n /**\n * Subscribe to multiple signal types with same handler\n */\n subscribeMultiple<T = unknown>(types: string[], handler: SignalHandler<T>): Unsubscribe {\n const unsubscribers = types.map((type) => this.subscribe(type, handler))\n\n return () => {\n unsubscribers.forEach((unsub) => unsub())\n }\n }\n\n /**\n * Process signal queue\n */\n private async processQueue(): Promise<void> {\n if (this.processing || this.signalQueue.length === 0) {\n return\n }\n\n this.processing = true\n\n while (this.signalQueue.length > 0) {\n const signal = this.signalQueue.shift()!\n const handlers = this.handlers.get(signal.type)\n\n if (handlers) {\n handlers.forEach((handler) => {\n try {\n handler(signal)\n } catch (error) {\n console.error(`[v0] Signal handler error for \"${signal.type}\":`, error)\n }\n })\n }\n }\n\n this.processing = false\n }\n\n /**\n * Get count of handlers for a signal type\n */\n getHandlerCount(type: string): number {\n return this.handlers.get(type)?.size ?? 0\n }\n\n /**\n * Clear all handlers (useful for testing)\n */\n clear(): void {\n this.handlers.clear()\n this.signalQueue = []\n }\n}\n\n// Singleton instance\nexport const SignalBus = new SignalBusClass()\n\n// ============================================================================\n// Common Signal Types (String Constants)\n// ============================================================================\n\nexport const SIGNAL_TYPES = {\n // Field changes\n FIELD_ENERGY_CHANGED: \"field:energy:changed\",\n FIELD_ATTENTION_CHANGED: \"field:attention:changed\",\n FIELD_VALENCE_CHANGED: \"field:valence:changed\",\n\n // User interactions\n USER_INTERACTION_START: \"user:interaction:start\",\n USER_INTERACTION_END: \"user:interaction:end\",\n USER_FOCUS_CHANGED: \"user:focus:changed\",\n\n // Component lifecycle\n COMPONENT_MOUNTED: \"component:mounted\",\n COMPONENT_UNMOUNTED: \"component:unmounted\",\n\n // Accessibility\n A11Y_ANNOUNCE: \"a11y:announce\",\n A11Y_FOCUS_TRAP: \"a11y:focus:trap\",\n} as const\n"]}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Mode Derivation - Field → Mode transformation
3
+ *
4
+ * This is the key insight: don't map sliders directly to 50 UI changes.
5
+ * Instead, derive 2-4 coherent modes and let modes drive everything.
6
+ *
7
+ * STRICT SEPARATION OF CONCERNS:
8
+ * ┌─────────────┬────────────────────────────────────┬─────────────────────────────┐
9
+ * │ Slider │ Controls │ Must NOT Control │
10
+ * ├─────────────┼────────────────────────────────────┼─────────────────────────────┤
11
+ * │ Cognitive │ density, hierarchy, concurrency │ tone, animation speed │
12
+ * │ Temporal │ content length, shortcuts, defaults│ color, layout structure │
13
+ * │ Emotional │ motion restraint, friction │ content importance │
14
+ * │ Valence │ tone, expressiveness │ information volume │
15
+ * └─────────────┴────────────────────────────────────┴─────────────────────────────┘
16
+ */
17
+ import type { CapacityField, InterfaceMode, InterfaceModeLabel } from "./types";
18
+ /**
19
+ * Derives InterfaceMode from CapacityField
20
+ *
21
+ * Rules:
22
+ * - Cognitive → density (how many things compete for attention at once)
23
+ * - Temporal → content length, shortcuts (how much time the UI asks from user)
24
+ * - Emotional → motion restraint (nervous-system-safe UI, no surprises)
25
+ * - Valence → tone/expressiveness (emotional color, not information volume)
26
+ */
27
+ export declare function deriveMode(field: CapacityField): InterfaceMode;
28
+ /**
29
+ * Derives a human-readable mode label from raw capacity inputs
30
+ *
31
+ * We use RAW VALUES, not derived mode, because:
32
+ * - Neutral (0.5, 0.5, 0.5) and Focused (0.7, 0.7, 0.6) produce the same InterfaceMode
33
+ * - But they should have different labels (Calm vs Focused)
34
+ * - The distinction is the RAW capacity level, not the derived mode
35
+ *
36
+ * Preset → Label / Motion / Focus mapping:
37
+ * - Exhausted (0.1, 0.1, 0.1) → Minimal motion: off focus: default (static)
38
+ * - Overwhelmed (0.2, 0.15, 0.2) → Minimal motion: soothing focus: guided (warm beacon)
39
+ * - Distracted (0.35, 0.25, 0.5) → Minimal motion: subtle focus: guided (warm beacon)
40
+ * - Neutral (0.5, 0.5, 0.5) → Calm motion: subtle focus: gentle (cool glow)
41
+ * - Focused (0.75, 0.75, 0.55) → Focused motion: subtle focus: default
42
+ * - Energized (0.9, 0.85, 0.85) → Exploratory motion: expressive focus: default
43
+ * - Exploring (1.0, 1.0, 1.0) → Exploratory motion: expressive focus: default
44
+ */
45
+ export declare function deriveModeLabel(inputs: CapacityField): InterfaceModeLabel;
46
+ /**
47
+ * Get mode badge color based on label
48
+ */
49
+ export declare function getModeBadgeColor(label: InterfaceModeLabel): string;
50
+ //# sourceMappingURL=mode.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mode.d.ts","sourceRoot":"","sources":["../../lib/capacity/mode.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,kBAAkB,EAAe,MAAM,SAAS,CAAA;AAM5F;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,aAAa,GAAG,aAAa,CA2F9D;AAMD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,aAAa,GAAG,kBAAkB,CAwBzE;AAMD;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,kBAAkB,GAAG,MAAM,CAanE"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @file React hook for exposing predicted capacity states.
3
+ */
4
+ import { CapacityField } from '../types';
5
+ /**
6
+ * A React hook that provides the anticipated future capacity state.
7
+ * It initializes and uses the PatternStore, PatternExtractor, and PredictionEngine.
8
+ * @returns {CapacityField | null} The predicted CapacityField or null if no confident prediction is available.
9
+ */
10
+ export declare function usePredictedCapacity(): CapacityField | null;
11
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../../../lib/capacity/prediction/hooks.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAQzC;;;;GAIG;AACH,wBAAgB,oBAAoB,IAAI,aAAa,GAAG,IAAI,CAyC3D"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @file Analyzes session history from PatternStore to identify recurring capacity patterns.
3
+ */
4
+ import { CapacityPattern } from './types';
5
+ import { PatternStore } from './pattern-store';
6
+ /**
7
+ * Extracts recurring capacity patterns from historical data.
8
+ */
9
+ export declare class PatternExtractor {
10
+ private store;
11
+ constructor(store: PatternStore);
12
+ /**
13
+ * Analyzes the historical capacity data to find recurring patterns.
14
+ * @returns {CapacityPattern[]} An array of identified CapacityPattern objects.
15
+ */
16
+ extractPatterns(): CapacityPattern[];
17
+ /**
18
+ * Averages two CapacityField objects. Used for incremental averaging of predictions.
19
+ * @param {Partial<CapacityField>} currentAvg - The current averaged capacity field.
20
+ * @param {CapacityField} newItem - The new capacity field to include in the average.
21
+ * @param {number} currentSampleSize - The current number of samples in the average.
22
+ * @returns {Partial<CapacityField>} The new averaged capacity field.
23
+ */
24
+ private averageCapacityFields;
25
+ }
26
+ //# sourceMappingURL=pattern-extractor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pattern-extractor.d.ts","sourceRoot":"","sources":["../../../lib/capacity/prediction/pattern-extractor.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAE,eAAe,EAAkB,MAAM,SAAS,CAAC;AAC1D,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAO/C;;GAEG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,KAAK,CAAe;gBAEhB,KAAK,EAAE,YAAY;IAI/B;;;OAGG;IACH,eAAe,IAAI,eAAe,EAAE;IAkDpC;;;;;;OAMG;IACH,OAAO,CAAC,qBAAqB;CAqB9B"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @file Manages the storage and retrieval of CapacityField patterns in localStorage.
3
+ * Provides CRUD operations for persisting user capacity history.
4
+ *
5
+ * Bug fix vs. original: all localStorage calls are now wrapped in try/catch.
6
+ * localStorage.setItem() throws DOMException when the storage quota is exceeded and
7
+ * JSON.parse throws SyntaxError on corrupt data. Both are now handled gracefully —
8
+ * reads degrade to [] and writes are silently skipped.
9
+ */
10
+ import { CapacityField } from '../types';
11
+ interface CapacityHistoryItem {
12
+ timestamp: number;
13
+ capacity: CapacityField;
14
+ }
15
+ export declare class PatternStore {
16
+ constructor();
17
+ /**
18
+ * Records a new CapacityField state with a timestamp.
19
+ * Silently skips the write if localStorage is full or unavailable.
20
+ */
21
+ recordCapacity(capacity: CapacityField): void;
22
+ /**
23
+ * Retrieves the entire capacity history.
24
+ * Returns [] on any storage or parse error.
25
+ */
26
+ getHistory(): CapacityHistoryItem[];
27
+ /** Clears the entire capacity history. */
28
+ clearHistory(): void;
29
+ /** Deletes a specific historical item by its timestamp. */
30
+ deleteItem(timestamp: number): void;
31
+ /** Updates the capacity fields of a specific historical item. */
32
+ updateItem(timestamp: number, updates: Partial<CapacityField>): void;
33
+ }
34
+ export {};
35
+ //# sourceMappingURL=pattern-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pattern-store.d.ts","sourceRoot":"","sources":["../../../lib/capacity/prediction/pattern-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAKzC,UAAU,mBAAmB;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,aAAa,CAAC;CACzB;AAED,qBAAa,YAAY;;IAavB;;;OAGG;IACH,cAAc,CAAC,QAAQ,EAAE,aAAa,GAAG,IAAI;IAY7C;;;OAGG;IACH,UAAU,IAAI,mBAAmB,EAAE;IAUnC,0CAA0C;IAC1C,YAAY,IAAI,IAAI;IASpB,2DAA2D;IAC3D,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI;IAUnC,iEAAiE;IACjE,UAAU,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,aAAa,CAAC,GAAG,IAAI;CAarE"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @file Matches the current context against stored patterns to generate predictive capacity suggestions.
3
+ */
4
+ import { CapacityField } from '../types';
5
+ import { PatternTrigger } from './types';
6
+ import { PatternExtractor } from './pattern-extractor';
7
+ /**
8
+ * The PredictionEngine uses extracted patterns to predict future capacity states
9
+ * based on the current context.
10
+ */
11
+ export declare class PredictionEngine {
12
+ private patternExtractor;
13
+ private patterns;
14
+ constructor(patternExtractor: PatternExtractor);
15
+ /**
16
+ * Loads or reloads patterns from the extractor.
17
+ */
18
+ loadPatterns(): void;
19
+ /**
20
+ * Generates a predicted CapacityField based on the current context.
21
+ * @param {PatternTrigger} currentContext - The current environmental and behavioral context.
22
+ * @returns {CapacityField | null} A predicted CapacityField or null if no confident prediction can be made.
23
+ */
24
+ predictCapacity(currentContext: PatternTrigger): CapacityField | null;
25
+ /**
26
+ * Determines if a pattern's trigger matches the current context.
27
+ * This can be made more sophisticated (e.g., fuzzy matching, weighting different trigger types).
28
+ * @param {PatternTrigger} patternTrigger - The trigger defined in the pattern.
29
+ * @param {PatternTrigger} currentContext - The current environmental and behavioral context.
30
+ * @returns {boolean} True if the pattern trigger matches the current context.
31
+ */
32
+ private matchesContext;
33
+ /**
34
+ * Implements confidence decay for patterns. Confidence should decay over time if a pattern is not re-observed.
35
+ * This method would typically be called periodically (e.g., daily) or when patterns are reloaded.
36
+ */
37
+ decayConfidence(): void;
38
+ }
39
+ //# sourceMappingURL=prediction-engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prediction-engine.d.ts","sourceRoot":"","sources":["../../../lib/capacity/prediction/prediction-engine.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAmB,cAAc,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAIvD;;;GAGG;AACH,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,gBAAgB,CAAmB;IAC3C,OAAO,CAAC,QAAQ,CAAyB;gBAE7B,gBAAgB,EAAE,gBAAgB;IAK9C;;OAEG;IACH,YAAY,IAAI,IAAI;IAIpB;;;;OAIG;IACH,eAAe,CAAC,cAAc,EAAE,cAAc,GAAG,aAAa,GAAG,IAAI;IA6BrE;;;;;;OAMG;IACH,OAAO,CAAC,cAAc;IActB;;;OAGG;IACH,eAAe,IAAI,IAAI;CAUxB"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @file Defines the interfaces for predictive adaptation patterns.
3
+ */
4
+ import { CapacityField } from '../types';
5
+ /**
6
+ * Represents a detected capacity pattern, linking a trigger to a predicted CapacityField.
7
+ */
8
+ export interface CapacityPattern {
9
+ trigger: PatternTrigger;
10
+ prediction: Partial<CapacityField>;
11
+ confidence: number;
12
+ sampleSize: number;
13
+ timestamp: number;
14
+ }
15
+ /**
16
+ * Defines the conditions that trigger a capacity pattern.
17
+ * This can be extended with more specific properties as needed.
18
+ */
19
+ export interface PatternTrigger {
20
+ timeOfDay?: number;
21
+ dayOfWeek?: number;
22
+ sessionDuration?: number;
23
+ }
24
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../lib/capacity/prediction/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,cAAc,CAAC;IACxB,UAAU,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;IACnC,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,eAAe,CAAC,EAAE,MAAM,CAAC;CAE1B"}
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Capacity Provider - React Context wrapper for ambient fields
3
+ *
4
+ * Wraps application root and exposes field hooks
5
+ */
6
+ import type React from "react";
7
+ import { type Dispatch, type SetStateAction } from "react";
8
+ import type { AmbientContext, UserCapacity, EmotionalState, MotionMode, CapacityField, InterfaceMode } from "./types";
9
+ import { type HapticPatternName } from "./feedback";
10
+ import { deriveMode } from "./mode";
11
+ import { MOTION_TOKENS } from "./constants";
12
+ interface CapacityContextValue {
13
+ context: AmbientContext;
14
+ updateCapacity: (capacity: Partial<UserCapacity>) => void;
15
+ updateEmotionalState: (state: Partial<EmotionalState>) => void;
16
+ isAutoMode: boolean;
17
+ toggleAutoMode: () => void;
18
+ updateCapacityField: (field: CapacityField) => void;
19
+ hapticEnabled: boolean;
20
+ sonicEnabled: boolean;
21
+ setHapticEnabled: Dispatch<SetStateAction<boolean>>;
22
+ setSonicEnabled: Dispatch<SetStateAction<boolean>>;
23
+ }
24
+ export declare function CapacityProvider({ children }: {
25
+ children: React.ReactNode;
26
+ }): import("react/jsx-runtime").JSX.Element;
27
+ /**
28
+ * Access full ambient context
29
+ * Most components should use specific field hooks instead
30
+ */
31
+ export declare function useCapacityContext(): CapacityContextValue;
32
+ /**
33
+ * Subscribe to energy field only
34
+ */
35
+ export declare function useEnergyField(): import("./types").EnergyFieldValue;
36
+ /**
37
+ * Subscribe to attention field only
38
+ */
39
+ export declare function useAttentionField(): import("./types").AttentionFieldValue;
40
+ /**
41
+ * Subscribe to emotional valence field only
42
+ */
43
+ export declare function useEmotionalValenceField(): import("./types").EmotionalValenceFieldValue;
44
+ /**
45
+ * Get field update functions (for Phase 1 slider system)
46
+ */
47
+ export declare function useFieldControls(): {
48
+ updateCapacity: (capacity: Partial<UserCapacity>) => void;
49
+ updateEmotionalState: (state: Partial<EmotionalState>) => void;
50
+ isAutoMode: boolean;
51
+ toggleAutoMode: () => void;
52
+ updateCapacityField: (field: CapacityField) => void;
53
+ };
54
+ /**
55
+ * Detect system prefers-reduced-motion preference
56
+ * Returns true if user has requested reduced motion
57
+ */
58
+ export declare function usePrefersReducedMotion(): boolean;
59
+ /**
60
+ * Derive the full mode from current capacity context.
61
+ * This is the primary hook for section-level components that need
62
+ * the field values AND the derived mode together.
63
+ *
64
+ * Eliminates the repeated { cognitive: context.userCapacity.cognitive, ... }
65
+ * construction that was duplicated across every section component.
66
+ */
67
+ export declare function useDerivedMode(): {
68
+ field: CapacityField;
69
+ mode: InterfaceMode;
70
+ };
71
+ /**
72
+ * Get effective motion mode with system preference override
73
+ *
74
+ * System prefers-reduced-motion is a HARD OVERRIDE - non-negotiable on safety.
75
+ * This ensures accessibility compliance regardless of derived mode.
76
+ */
77
+ export declare function useEffectiveMotion(): {
78
+ mode: MotionMode;
79
+ tokens: typeof MOTION_TOKENS[keyof typeof MOTION_TOKENS];
80
+ prefersReducedMotion: boolean;
81
+ };
82
+ /**
83
+ * Access multimodal feedback preferences and fire helper.
84
+ *
85
+ * Reads opt-in flags from context — feedback only fires when the user
86
+ * has explicitly enabled it in the CapacityControls panel.
87
+ * Pace-aware: sonic frequency adapts to current arousal level.
88
+ */
89
+ export declare function useFeedback(): {
90
+ hapticEnabled: boolean;
91
+ sonicEnabled: boolean;
92
+ setHapticEnabled: Dispatch<SetStateAction<boolean>>;
93
+ setSonicEnabled: Dispatch<SetStateAction<boolean>>;
94
+ fire: (pattern?: HapticPatternName) => void;
95
+ };
96
+ /**
97
+ * Get motion tokens with arousal-based pacing applied (Phase 3)
98
+ *
99
+ * Arousal independently controls animation speed:
100
+ * - calm (< 0.35): +50% duration — slow, deliberate
101
+ * - neutral (0.35–0.65): standard duration
102
+ * - activated (> 0.65): -35% duration — fast, energetic
103
+ *
104
+ * System prefers-reduced-motion overrides pace to "calm" for safety.
105
+ */
106
+ export declare function usePacedMotionTokens(): {
107
+ mode: MotionMode;
108
+ pace: ReturnType<typeof deriveMode>["pace"];
109
+ tokens: {
110
+ durationFast: number;
111
+ durationBase: number;
112
+ durationSlow: number;
113
+ easing: string;
114
+ essentialDuration: number;
115
+ essentialEasing: string;
116
+ };
117
+ };
118
+ export {};
119
+ //# sourceMappingURL=provider.d.ts.map