{"version":3,"file":"useHeardText.mjs","names":[],"sources":["../../../../../src/plugins/AIComponents/hooks/useHeardText.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\n\n/** How much of a text the user has heard so far. */\nexport type HeardTextProgress = {\n  /**\n   * Number of characters of the text the user has heard, counted in Unicode code points\n   * (as `Array.from(text).length` counts them, not UTF-16 code units like `text.length`).\n   * May be fractional; it is floored before rendering. A value at or above the text's\n   * code point length reveals the whole text.\n   */\n  chars: number;\n  /** `true` once the speech for the text has finished (played out, interrupted or skipped). */\n  done: boolean;\n};\n\n/**\n * Returns how much of the text the user has heard by `now` (a `performance.now()`\n * timestamp).\n *\n * Return `undefined` only for a text that is not spoken at all: the full text is then\n * shown, and the reveal never moves back past what has been shown. A text that will be\n * spoken but whose audio has not started, or that the voice source does not know yet,\n * must return `{ chars: 0, done: false }`, or it is shown in full before it is heard.\n *\n * Also called during render, so keep it free of side effects.\n */\nexport type HeardTextFunction = (now: number) => HeardTextProgress | undefined;\n\n/**\n * Registers a listener that is called whenever the speech progress source changes\n * (playback started, paused, finished...). Returns an unsubscribe function.\n */\nexport type HeardTextSubscribe = (listener: () => void) => () => void;\n\nexport type UseHeardTextParams = {\n  /** The speech progress of `text`, see `HeardTextFunction`. */\n  heard: HeardTextFunction;\n  /** The full text to reveal. */\n  text: string;\n  /**\n   * `true` while the text is still being written. The full text is only revealed\n   * automatically once `heard` reports `done` and `generating` is falsy.\n   */\n  generating?: boolean;\n  /**\n   * Defaults to `true`. `false` reveals the full text at once, for example for a message\n   * loaded from history. Read when the hook mounts and when `text` is replaced by a\n   * different text, not on every change.\n   */\n  live?: boolean;\n  /**\n   * Optional change notifications from the speech progress source. Without it, `heard`\n   * is only checked again while the text is paced and its speech is not done, and when\n   * `text` or `generating` change. Subscribed once; to switch to another source, remount\n   * the component (for example with a `key`).\n   */\n  subscribe?: HeardTextSubscribe;\n};\n\nexport type UseHeardTextResult = {\n  /** The part of the text the user has heard (the full text when not paced). */\n  heardText: string;\n  /** `false` when `heard` returned `undefined`; `heardText` is then the full text. */\n  isPaced: boolean;\n  /** Reveals the full text from now on (e.g. when the user stops the AI response). */\n  skip: () => void;\n};\n\ntype PacingState = {\n  /** Number of code points revealed. Never decreases while the text continues. */\n  count: number;\n  isPaced: boolean;\n  /** No more ticking is needed until the inputs change or the source notifies. */\n  settled: boolean;\n};\n\n/** The reveal of one text. Starts over when the text is replaced by a different text. */\ntype RevealState = PacingState & {\n  /** `live` as read when the reveal started. */\n  live: boolean;\n  skipped: boolean;\n  /** The text `count` refers to. */\n  text: string;\n};\n\nconst now = () =>\n  typeof performance !== 'undefined' && typeof performance.now === 'function'\n    ? performance.now()\n    : Date.now();\n\nconst scheduleFrame = (callback: () => void): (() => void) => {\n  if (typeof requestAnimationFrame === 'function') {\n    const id = requestAnimationFrame(callback);\n    return () => cancelAnimationFrame(id);\n  }\n  const id = setTimeout(callback, 16);\n  return () => clearTimeout(id);\n};\n\n/**\n * UTF-16 offsets of the code point boundaries of `text`: `offsets[n]` is the\n * `String.prototype.slice` end index of the first `n` code points, so\n * `offsets.length - 1` is the code point length. Slicing at these offsets never splits\n * a surrogate pair.\n */\nconst getCodePointOffsets = (text: string): number[] => {\n  const offsets = [0];\n  let offset = 0;\n  for (const codePoint of text) {\n    offset += codePoint.length;\n    offsets.push(offset);\n  }\n  return offsets;\n};\n\nconst sample = ({\n  generating,\n  heard,\n  live,\n  previousCount,\n  skipped,\n  textLength,\n}: {\n  generating: boolean;\n  heard: HeardTextFunction;\n  live: boolean;\n  previousCount: number;\n  skipped: boolean;\n  /** Length of the text in code points. */\n  textLength: number;\n}): PacingState => {\n  const progress = heard(now());\n\n  if (!progress) {\n    // Not paced: the full text is shown, so pacing that starts later must not move the\n    // reveal backwards past what has already been shown.\n    return { count: Math.max(previousCount, textLength), isPaced: false, settled: true };\n  }\n\n  if (!live || skipped || (progress.done && !generating)) {\n    return { count: Math.max(previousCount, textLength), isPaced: true, settled: true };\n  }\n\n  // `+Infinity` means the whole text has been heard; NaN, negative and non-numeric\n  // counts mean nothing has\n  const flooredChars = Math.floor(progress.chars);\n  const heardChars = flooredChars > 0 ? flooredChars : 0;\n\n  return {\n    count: Math.max(previousCount, Math.min(heardChars, textLength)),\n    isPaced: true,\n    settled: progress.done,\n  };\n};\n\nconst startReveal = ({\n  generating,\n  heard,\n  live,\n  text,\n  textLength,\n}: {\n  generating: boolean;\n  heard: HeardTextFunction;\n  live: boolean;\n  text: string;\n  textLength: number;\n}): RevealState => ({\n  ...sample({ generating, heard, live, previousCount: 0, skipped: false, textLength }),\n  live,\n  skipped: false,\n  text,\n});\n\n/**\n * Whether `text` continues the reveal of `previous.text`: it extends or truncates the part\n * already shown. Anything else (the next reply rendered by the same component) is a new\n * text, whose reveal must not start from the length shown for the previous one.\n */\nconst continuesReveal = (previous: RevealState, text: string) => {\n  const offsets = getCodePointOffsets(previous.text);\n  const shown = previous.text.slice(\n    0,\n    offsets[Math.min(previous.count, offsets.length - 1)],\n  );\n  return text.startsWith(shown) || shown.startsWith(text);\n};\n\nconst noop = () => undefined;\n\n/**\n * Reveals a text at the pace the user hears it spoken, for example the reply of a voice\n * AI agent that is written into the chat faster than the agent speaks it. The speech\n * progress comes from the app as a plain function, so the hook works with any voice\n * backend and has no dependency on the chat SDK.\n *\n * - Reveals the first `floor(chars)` Unicode code points of `text` (emoji and other\n *   astral characters are never split) and never moves backwards while `text` grows or\n *   is truncated. When `text` is replaced by a different text (the next reply rendered\n *   by the same component), the reveal starts over: the length shown, `skip()` and\n *   `live` are reset.\n * - While the text is paced and its speech is not done, samples `heard` on every\n *   animation frame (a 16 ms timeout without `requestAnimationFrame`). It stops ticking\n *   when the speech is done or the component unmounts; `subscribe` notifications, and\n *   changes of `text` or `generating`, make it check again.\n * - Reveals the full text once `heard` reports `done` and `generating` is falsy, when\n *   `live` is `false`, and after `skip()`.\n * - When `heard` returns `undefined`, `isPaced` is `false` and `heardText` is the full\n *   text. If it becomes paced later, the reveal continues from the length already shown.\n *\n * `heard` and `subscribe` are read through refs, so passing new function identities on\n * every render (inline arrow functions) does not restart the pacing. `subscribe` is\n * called once on mount (and again only if it goes from absent to present) and its\n * unsubscribe function runs on unmount; to switch to another speech source, remount the\n * component. `heard` is also called during render, so keep it free of side effects.\n *\n * @example\n * ```tsx\n * import { useHeardText } from 'stream-chat-react/ai-components';\n *\n * const SpokenReply = ({ generating, session, text, turnId }) => {\n *   const { heardText } = useHeardText({\n *     generating,\n *     heard: (now) => session.speech.heard(turnId, now),\n *     subscribe: (listener) => session.speech.subscribe(listener),\n *     text,\n *   });\n *   return <p>{heardText}</p>;\n * };\n * ```\n */\nexport const useHeardText = ({\n  generating = false,\n  heard,\n  live = true,\n  subscribe,\n  text,\n}: UseHeardTextParams): UseHeardTextResult => {\n  const codePointOffsets = useMemo(() => getCodePointOffsets(text), [text]);\n  const textLength = codePointOffsets.length - 1;\n\n  const heardRef = useRef(heard);\n  heardRef.current = heard;\n  const subscribeRef = useRef(subscribe);\n  subscribeRef.current = subscribe;\n\n  const [revealState, setRevealState] = useState<RevealState>(() =>\n    startReveal({ generating, heard, live, text, textLength }),\n  );\n  let reveal = revealState;\n  if (revealState.text !== text) {\n    // Updated during render so that the new text never renders with the previous reveal.\n    reveal = continuesReveal(revealState, text)\n      ? { ...revealState, count: Math.min(revealState.count, textLength), text }\n      : startReveal({ generating, heard, live, text, textLength });\n    setRevealState(reveal);\n  }\n  const revealRef = useRef(reveal);\n  revealRef.current = reveal;\n  const wakeRef = useRef<() => void>(noop);\n\n  const { live: isLive, skipped } = reveal;\n\n  useEffect(() => {\n    let cancelFrame: (() => void) | undefined;\n    let disposed = false;\n\n    const tick = () => {\n      cancelFrame = undefined;\n      if (disposed) return;\n\n      const previous = revealRef.current;\n      const next = sample({\n        generating,\n        heard: heardRef.current,\n        live: isLive,\n        previousCount: previous.count,\n        skipped,\n        textLength,\n      });\n\n      if (\n        next.count !== previous.count ||\n        next.isPaced !== previous.isPaced ||\n        next.settled !== previous.settled\n      ) {\n        const updated = { ...previous, ...next };\n        revealRef.current = updated;\n        setRevealState(updated);\n      }\n\n      if (!next.settled) cancelFrame = scheduleFrame(tick);\n    };\n\n    wakeRef.current = () => {\n      if (!disposed && !cancelFrame) tick();\n    };\n    tick();\n\n    return () => {\n      disposed = true;\n      cancelFrame?.();\n      wakeRef.current = noop;\n    };\n  }, [generating, isLive, skipped, text, textLength]);\n\n  const hasSubscribe = Boolean(subscribe);\n  useEffect(() => {\n    if (!hasSubscribe) return;\n    return subscribeRef.current?.(() => wakeRef.current());\n  }, [hasSubscribe]);\n\n  const skip = useCallback(\n    () => setRevealState((previous) => ({ ...previous, skipped: true })),\n    [],\n  );\n\n  return {\n    heardText: reveal.isPaced\n      ? text.slice(0, codePointOffsets[Math.min(reveal.count, textLength)])\n      : text,\n    isPaced: reveal.isPaced,\n    skip,\n  };\n};\n"],"mappings":";;AAqFA,IAAM,YACJ,OAAO,gBAAgB,eAAe,OAAO,YAAY,QAAQ,aAC7D,YAAY,IAAI,IAChB,KAAK,IAAI;AAEf,IAAM,iBAAiB,aAAuC;CAC5D,IAAI,OAAO,0BAA0B,YAAY;EAC/C,MAAM,KAAK,sBAAsB,QAAQ;EACzC,aAAa,qBAAqB,EAAE;CACtC;CACA,MAAM,KAAK,WAAW,UAAU,EAAE;CAClC,aAAa,aAAa,EAAE;AAC9B;;;;;;;AAQA,IAAM,uBAAuB,SAA2B;CACtD,MAAM,UAAU,CAAC,CAAC;CAClB,IAAI,SAAS;CACb,KAAK,MAAM,aAAa,MAAM;EAC5B,UAAU,UAAU;EACpB,QAAQ,KAAK,MAAM;CACrB;CACA,OAAO;AACT;AAEA,IAAM,UAAU,EACd,YACA,OACA,MACA,eACA,SACA,iBASiB;CACjB,MAAM,WAAW,MAAM,IAAI,CAAC;CAE5B,IAAI,CAAC,UAGH,OAAO;EAAE,OAAO,KAAK,IAAI,eAAe,UAAU;EAAG,SAAS;EAAO,SAAS;CAAK;CAGrF,IAAI,CAAC,QAAQ,WAAY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