{"version":3,"file":"VoiceVisualizationView.mjs","names":[],"sources":["../../../../../src/plugins/AIComponents/VoiceVisualization/VoiceVisualizationView.tsx"],"sourcesContent":["import { type PointerEvent, useEffect, useRef } from 'react';\nimport clsx from 'clsx';\n\nimport { useReducedMotionPreference } from '../../../components/MessageList/hooks/useReducedMotionPreference';\nimport { useStableCallback } from '../../../utils/useStableCallback';\nimport { type VoiceDriverInput, VoiceVisualizationDriver } from './driver';\nimport { audioLevelInput, expressivityInput } from './math';\nimport { toLocalPoint } from './hitArea';\nimport { FALLBACK_COLOR, readVoiceTheme, toHsvPalette } from './palette';\nimport type { VoiceRenderer } from './renderers/types';\nimport type { Hsv, VoiceVisualizationProps } from './types';\nimport { useVoiceStateLabel } from './useVoiceStateLabel';\nimport { ThemeScopeProvider, useAIThemeScopeClassName } from '../themeScope';\n\n/** How many frames pass between two reads of the theme, about once a second at 60 Hz. */\nconst THEME_FRAMES = 60;\n\ntype ViewProps = VoiceVisualizationProps & {\n  /** Whether a point, centred and normalized to the shorter side with y up, is on the shape. */\n  contains: (x: number, y: number) => boolean;\n  /** Makes the renderer for a freshly mounted canvas, or null when it cannot draw there. */\n  createRenderer: (canvas: HTMLCanvasElement) => VoiceRenderer | null;\n  /** Remounts the canvas and remakes the renderer when it changes. */\n  rendererKey: string;\n  /**\n   * The most device pixels per CSS pixel the canvas gets: a blurred shape looks the same at 1,\n   * at a quarter of the pixels of a 2x display, while a thin line needs the screen's own.\n   */\n  maxPixelRatio: number;\n};\n\n/**\n * What VoiceWave and VoiceGlow share: the motion advanced once a frame, the canvas kept at the\n * element's size, the theme's colors, reduced motion, the pointer and the accessible name.\n *\n * The loop runs only while the element is on screen, reads `audioLevel` once a frame and\n * redraws without re-rendering React.\n */\nexport const VoiceVisualizationView = ({\n  audioLevel,\n  className,\n  colors,\n  contains,\n  createRenderer,\n  expressivity,\n  maxPixelRatio,\n  onPointerLeave,\n  onPointerMove,\n  onPointerUp,\n  rendererKey,\n  state,\n  ...restProps\n}: ViewProps) => {\n  const themeScopeClassName = useAIThemeScopeClassName();\n  const label = useVoiceStateLabel(state);\n  const reduceMotion = useReducedMotionPreference();\n  const rootRef = useRef<HTMLDivElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const driverRef = useRef<VoiceVisualizationDriver | null>(null);\n  const audioLevelRef = useRef(audioLevel);\n  const themeRef = useRef<{ dark: number; palette: Hsv[] }>({ dark: 0, palette: [] });\n  const paletteRef = useRef<{ key: string; palette: Hsv[] }>({ key: '', palette: [] });\n  const propsRef = useRef({ colors, expressivity, reduceMotion, state });\n\n  /** The theme's accent color and whether it sits on a dark backdrop. */\n  const readTheme = useStableCallback(() => {\n    const root = rootRef.current;\n    if (!root || typeof getComputedStyle !== 'function') return;\n    themeRef.current = readVoiceTheme(root);\n  });\n\n  /** The driver's input from the latest props and the theme, keeping the audio level it has. */\n  const applyInput = useStableCallback(() => {\n    // The first input settles the driver, so read the theme before it starts on a fallback.\n    if (!driverRef.current) readTheme();\n    const { colors, expressivity, reduceMotion, state } = propsRef.current;\n    const key = (colors ?? []).join('|');\n    if (paletteRef.current.key !== key) {\n      paletteRef.current = { key, palette: toHsvPalette(colors ?? []) };\n    }\n    const own = paletteRef.current.palette;\n    const theme = themeRef.current.palette;\n    const input: VoiceDriverInput = {\n      audioLevel: driverRef.current?.input.audioLevel ?? null,\n      colors: own.length ? own : theme.length ? theme : toHsvPalette([FALLBACK_COLOR]),\n      expressivity: expressivityInput(expressivity),\n      reduceMotion,\n      state,\n    };\n    if (driverRef.current) driverRef.current.input = input;\n    else\n      driverRef.current = new VoiceVisualizationDriver({\n        ...input,\n        audioLevel: audioLevelInput(audioLevelRef.current?.()),\n      });\n  });\n\n  useEffect(() => {\n    audioLevelRef.current = audioLevel;\n    propsRef.current = { colors, expressivity, reduceMotion, state };\n    applyInput();\n  });\n\n  const makeRenderer = useStableCallback(createRenderer);\n\n  useEffect(() => {\n    const root = rootRef.current;\n    const canvas = canvasRef.current;\n    if (!root || !canvas || typeof requestAnimationFrame !== 'function') return;\n\n    const renderer = makeRenderer(canvas);\n    if (!renderer) return;\n\n    const resize = () => {\n      const pixelRatio = Math.min(window.devicePixelRatio || 1, maxPixelRatio);\n      const width = Math.round(root.clientWidth * pixelRatio);\n      const height = Math.round(root.clientHeight * pixelRatio);\n      if (canvas.width !== width) canvas.width = width;\n      if (canvas.height !== height) canvas.height = height;\n    };\n    resize();\n    const resizeObserver =\n      typeof ResizeObserver === 'function' ? new ResizeObserver(resize) : null;\n    resizeObserver?.observe(root);\n\n    // A new pixel ratio alone (another monitor, browser zoom) needs a new backing size too. The\n    // query matches only the ratio it was made for, so it is made again after each change.\n    let ratioQuery: MediaQueryList | null = null;\n    const onRatioChange = () => {\n      resize();\n      watchRatio();\n    };\n    const watchRatio = () => {\n      ratioQuery?.removeEventListener?.('change', onRatioChange);\n      ratioQuery =\n        typeof window.matchMedia === 'function'\n          ? window.matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`)\n          : null;\n      ratioQuery?.addEventListener?.('change', onRatioChange);\n    };\n    watchRatio();\n\n    let frameId = 0;\n    let last = 0;\n    let frames = 0;\n    let visible = true;\n\n    const tick = (now: number) => {\n      frameId = 0;\n      const driver = driverRef.current;\n      if (!driver) return;\n      const seconds = last === 0 ? 0 : (now - last) / 1000;\n      if (last !== 0) {\n        driver.input = {\n          ...driver.input,\n          audioLevel: audioLevelInput(audioLevelRef.current?.()),\n        };\n        driver.advance(seconds);\n      }\n      last = now;\n      if (++frames % THEME_FRAMES === 0) {\n        readTheme();\n        applyInput();\n      }\n      renderer.draw({\n        dark: themeRef.current.dark,\n        driver,\n        height: canvas.height,\n        seconds,\n        width: canvas.width,\n      });\n      // The canvas fades in once it has something to show, as on iOS, rather than flashing\n      // empty while a shader compiles or the first frame lands.\n      if (!canvas.dataset.ready) canvas.dataset.ready = 'true';\n      schedule();\n    };\n\n    const schedule = () => {\n      if (visible && !frameId) frameId = requestAnimationFrame(tick);\n    };\n\n    const stop = () => {\n      if (frameId) cancelAnimationFrame(frameId);\n      frameId = 0;\n      // The first frame back shows where it was rather than leaping over the pause.\n      last = 0;\n    };\n\n    // Off screen, nothing is drawn; hidden tabs already pause requestAnimationFrame.\n    const intersectionObserver =\n      typeof IntersectionObserver === 'function'\n        ? new IntersectionObserver((entries) => {\n            visible = entries.some((entry) => entry.isIntersecting);\n            if (visible) schedule();\n            else stop();\n          })\n        : null;\n    intersectionObserver?.observe(root);\n\n    const colorScheme =\n      typeof window.matchMedia === 'function'\n        ? window.matchMedia('(prefers-color-scheme: dark)')\n        : null;\n    const onSchemeChange = () => {\n      readTheme();\n      applyInput();\n    };\n    colorScheme?.addEventListener?.('change', onSchemeChange);\n\n    schedule();\n\n    return () => {\n      stop();\n      resizeObserver?.disconnect();\n      ratioQuery?.removeEventListener?.('change', onRatioChange);\n      intersectionObserver?.disconnect();\n      colorScheme?.removeEventListener?.('change', onSchemeChange);\n      renderer.dispose?.();\n    };\n  }, [applyInput, makeRenderer, maxPixelRatio, readTheme, rendererKey]);\n\n  // Pointer events are only watched, never prevented or stopped, so a click handler on the\n  // element or a parent still gets them. They come only from the shape's hit area: the rest of\n  // the box lets them through to whatever is behind it.\n  const handlePointerUp = (event: PointerEvent<HTMLDivElement>) => {\n    onPointerUp?.(event);\n    const { x, y } = toLocalPoint(event);\n    if (contains(x, y)) driverRef.current?.tap(x, y);\n  };\n\n  const handlePointerMove = (event: PointerEvent<HTMLDivElement>) => {\n    onPointerMove?.(event);\n    // Only a hovering mouse or pen ripples it; a finger has no hover.\n    if (event.pointerType === 'touch') return;\n    const { x, y } = toLocalPoint(event);\n    const hovering = event.buttons === 0 && contains(x, y);\n    driverRef.current?.hover(hovering ? x : null, hovering ? y : null);\n  };\n\n  const handlePointerLeave = (event: PointerEvent<HTMLDivElement>) => {\n    onPointerLeave?.(event);\n    driverRef.current?.hover(null, null);\n  };\n\n  return (\n    <ThemeScopeProvider>\n      <div\n        aria-label={label}\n        className={clsx(\n          themeScopeClassName,\n          'str-chat__ai-voice-visualization',\n          className,\n        )}\n        data-state={state}\n        role='img'\n        {...restProps}\n        onPointerLeave={handlePointerLeave}\n        onPointerMove={handlePointerMove}\n        onPointerUp={handlePointerUp}\n        ref={rootRef}\n      >\n        <canvas\n          aria-hidden='true'\n          className='str-chat__ai-voice-visualization__canvas'\n          key={rendererKey}\n          ref={canvasRef}\n        />\n        {/* Only the shape takes the pointer; around it, events reach what is behind. */}\n        <div aria-hidden='true' className='str-chat__ai-voice-visualization__hit' />\n      </div>\n    </ThemeScopeProvider>\n  );\n};\n"],"mappings":";;;;;;;;;;;;;;AAeA,IAAM,eAAe;;;;;;;;AAuBrB,IAAa,0BAA0B,EACrC,YACA,WACA,QACA,UACA,gBACA,cACA,eACA,gBACA,eACA,aACA,aACA,OACA,GAAG,gBACY;CACf,MAAM,sBAAsB,yBAAyB;CACrD,MAAM,QAAQ,mBAAmB,KAAK;CACtC,MAAM,eAAe,2BAA2B;CAChD,MAAM,UAAU,OAAuB,IAAI;CAC3C,MAAM,YAAY,OAA0B,IAAI;CAChD,MAAM,YAAY,OAAwC,IAAI;CAC9D,MAAM,gBAAgB,OAAO,UAAU;CACvC,MAAM,WAAW,OAAyC;EAAE,MAAM;EAAG,SAAS,CAAC;CAAE,CAAC;CAClF,MAAM,aAAa,OAAwC;EAAE,KAAK;EAAI,SAAS,CAAC;CAAE,CAAC;CACnF,MAAM,WAAW,OAAO;EAAE;EAAQ;EAAc;EAAc;CAAM,CAAC;;CAGrE,MAAM,YAAY,wBAAwB;EACxC,MAAM,OAAO,QAAQ;EACrB,IAAI,CAAC,QAAQ,OAAO,qBAAqB,YAAY;EACrD,SAAS,UAAU,eAAe,IAAI;CACxC,CAAC;;CAGD,MAAM,aAAa,wBAAwB;EAEzC,IAAI,CAAC,UAAU,SAAS,UAAU;EAClC,MAAM,EAAE,QAAQ,cAAc,cAAc,UAAU,SAAS;EAC/D,MAAM,OAAO,UAAU,CAAC,EAAA,CAAG,KAAK,GAAG;EACnC,IAA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