tempest-react-sdk 0.35.0 → 0.37.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.
- package/README.md +72 -70
- package/dist/audio/audio-output.cjs +2 -0
- package/dist/audio/audio-output.cjs.map +1 -0
- package/dist/audio/audio-output.js +17 -0
- package/dist/audio/audio-output.js.map +1 -0
- package/dist/audio/audio-player.cjs +1 -1
- package/dist/audio/audio-player.cjs.map +1 -1
- package/dist/audio/audio-player.js +21 -20
- package/dist/audio/audio-player.js.map +1 -1
- package/dist/audio/audio-recorder.cjs +2 -0
- package/dist/audio/audio-recorder.cjs.map +1 -0
- package/dist/audio/audio-recorder.js +30 -0
- package/dist/audio/audio-recorder.js.map +1 -0
- package/dist/audio/duration.cjs +2 -0
- package/dist/audio/duration.cjs.map +1 -0
- package/dist/audio/duration.js +10 -0
- package/dist/audio/duration.js.map +1 -0
- package/dist/audio/level-meter.cjs +2 -0
- package/dist/audio/level-meter.cjs.map +1 -0
- package/dist/audio/level-meter.js +34 -0
- package/dist/audio/level-meter.js.map +1 -0
- package/dist/audio/media-access.cjs +2 -0
- package/dist/audio/media-access.cjs.map +1 -0
- package/dist/audio/media-access.js +51 -0
- package/dist/audio/media-access.js.map +1 -0
- package/dist/audio/use-audio-recorder.cjs +2 -0
- package/dist/audio/use-audio-recorder.cjs.map +1 -0
- package/dist/audio/use-audio-recorder.js +94 -0
- package/dist/audio/use-audio-recorder.js.map +1 -0
- package/dist/audio/use-audio.cjs.map +1 -1
- package/dist/audio/use-audio.js.map +1 -1
- package/dist/audio/use-microphone.cjs +2 -0
- package/dist/audio/use-microphone.cjs.map +1 -0
- package/dist/audio/use-microphone.js +54 -0
- package/dist/audio/use-microphone.js.map +1 -0
- package/dist/audio/wav.cjs +2 -0
- package/dist/audio/wav.cjs.map +1 -0
- package/dist/audio/wav.js +49 -0
- package/dist/audio/wav.js.map +1 -0
- package/dist/auth/passkey.cjs +2 -0
- package/dist/auth/passkey.cjs.map +1 -0
- package/dist/auth/passkey.js +171 -0
- package/dist/auth/passkey.js.map +1 -0
- package/dist/auth/use-passkey.cjs +2 -0
- package/dist/auth/use-passkey.cjs.map +1 -0
- package/dist/auth/use-passkey.js +120 -0
- package/dist/auth/use-passkey.js.map +1 -0
- package/dist/br/PixQRCode.cjs +2 -0
- package/dist/br/PixQRCode.cjs.map +1 -0
- package/dist/br/PixQRCode.js +70 -0
- package/dist/br/PixQRCode.js.map +1 -0
- package/dist/br/PixQRCode.module.cjs +2 -0
- package/dist/br/PixQRCode.module.cjs.map +1 -0
- package/dist/br/PixQRCode.module.js +15 -0
- package/dist/br/PixQRCode.module.js.map +1 -0
- package/dist/br/boleto.cjs +2 -0
- package/dist/br/boleto.cjs.map +1 -0
- package/dist/br/boleto.js +225 -0
- package/dist/br/boleto.js.map +1 -0
- package/dist/br/holidays.cjs +2 -0
- package/dist/br/holidays.cjs.map +1 -0
- package/dist/br/holidays.js +148 -0
- package/dist/br/holidays.js.map +1 -0
- package/dist/br/nfe.cjs +2 -0
- package/dist/br/nfe.cjs.map +1 -0
- package/dist/br/nfe.js +104 -0
- package/dist/br/nfe.js.map +1 -0
- package/dist/br/pix.cjs +2 -0
- package/dist/br/pix.cjs.map +1 -0
- package/dist/br/pix.js +148 -0
- package/dist/br/pix.js.map +1 -0
- package/dist/br.cjs +1 -1
- package/dist/br.cjs.map +1 -1
- package/dist/br.d.ts +878 -0
- package/dist/br.js +7 -2
- package/dist/br.js.map +1 -1
- package/dist/capture/barcode.cjs +2 -0
- package/dist/capture/barcode.cjs.map +1 -0
- package/dist/capture/barcode.js +59 -0
- package/dist/capture/barcode.js.map +1 -0
- package/dist/capture/media-recorder.cjs +2 -0
- package/dist/capture/media-recorder.cjs.map +1 -0
- package/dist/capture/media-recorder.js +64 -0
- package/dist/capture/media-recorder.js.map +1 -0
- package/dist/capture/use-barcode-scanner.cjs +2 -0
- package/dist/capture/use-barcode-scanner.cjs.map +1 -0
- package/dist/capture/use-barcode-scanner.js +86 -0
- package/dist/capture/use-barcode-scanner.js.map +1 -0
- package/dist/capture/use-screen-capture.cjs +2 -0
- package/dist/capture/use-screen-capture.cjs.map +1 -0
- package/dist/capture/use-screen-capture.js +79 -0
- package/dist/capture/use-screen-capture.js.map +1 -0
- package/dist/capture/use-speech-recognition.cjs +2 -0
- package/dist/capture/use-speech-recognition.cjs.map +1 -0
- package/dist/capture/use-speech-recognition.js +118 -0
- package/dist/capture/use-speech-recognition.js.map +1 -0
- package/dist/capture/use-torch.cjs +2 -0
- package/dist/capture/use-torch.cjs.map +1 -0
- package/dist/capture/use-torch.js +33 -0
- package/dist/capture/use-torch.js.map +1 -0
- package/dist/capture/use-video-recorder.cjs +2 -0
- package/dist/capture/use-video-recorder.cjs.map +1 -0
- package/dist/capture/use-video-recorder.js +90 -0
- package/dist/capture/use-video-recorder.js.map +1 -0
- package/dist/capture/video-recorder.cjs +2 -0
- package/dist/capture/video-recorder.cjs.map +1 -0
- package/dist/capture/video-recorder.js +31 -0
- package/dist/capture/video-recorder.js.map +1 -0
- package/dist/components/AIChat/AIChat.cjs +1 -1
- package/dist/components/AIChat/AIChat.cjs.map +1 -1
- package/dist/components/AIChat/AIChat.js +93 -97
- package/dist/components/AIChat/AIChat.js.map +1 -1
- package/dist/components/AIChat/AIChatComposer.cjs +1 -1
- package/dist/components/AIChat/AIChatComposer.cjs.map +1 -1
- package/dist/components/AIChat/AIChatComposer.js +2 -1
- package/dist/components/AIChat/AIChatComposer.js.map +1 -1
- package/dist/components/AIChat/AIChatTurn.cjs +2 -2
- package/dist/components/AIChat/AIChatTurn.js +6 -6
- package/dist/components/AIChat/AIChatTurn.js.map +1 -1
- package/dist/components/Alert/Alert.module.cjs.map +1 -1
- package/dist/components/Alert/Alert.module.js.map +1 -1
- package/dist/components/AudioPlayer/AudioPlayer.cjs +2 -0
- package/dist/components/AudioPlayer/AudioPlayer.cjs.map +1 -0
- package/dist/components/AudioPlayer/AudioPlayer.js +123 -0
- package/dist/components/AudioPlayer/AudioPlayer.js.map +1 -0
- package/dist/components/AudioPlayer/AudioPlayer.module.cjs +2 -0
- package/dist/components/AudioPlayer/AudioPlayer.module.cjs.map +1 -0
- package/dist/components/AudioPlayer/AudioPlayer.module.js +12 -0
- package/dist/components/AudioPlayer/AudioPlayer.module.js.map +1 -0
- package/dist/components/AudioRecorder/AudioRecorder.cjs +2 -0
- package/dist/components/AudioRecorder/AudioRecorder.cjs.map +1 -0
- package/dist/components/AudioRecorder/AudioRecorder.js +179 -0
- package/dist/components/AudioRecorder/AudioRecorder.js.map +1 -0
- package/dist/components/AudioRecorder/AudioRecorder.module.cjs +2 -0
- package/dist/components/AudioRecorder/AudioRecorder.module.cjs.map +1 -0
- package/dist/components/AudioRecorder/AudioRecorder.module.js +19 -0
- package/dist/components/AudioRecorder/AudioRecorder.module.js.map +1 -0
- package/dist/components/Badge/Badge.module.cjs.map +1 -1
- package/dist/components/Badge/Badge.module.js.map +1 -1
- package/dist/components/BarcodeScanner/BarcodeScanner.cjs +2 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.cjs.map +1 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.js +123 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.js.map +1 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.module.cjs +2 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.module.cjs.map +1 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.module.js +22 -0
- package/dist/components/BarcodeScanner/BarcodeScanner.module.js.map +1 -0
- package/dist/components/BottomNavigation/BottomNavigation.module.cjs.map +1 -1
- package/dist/components/BottomNavigation/BottomNavigation.module.js.map +1 -1
- package/dist/components/Button/Button.module.cjs.map +1 -1
- package/dist/components/Button/Button.module.js.map +1 -1
- package/dist/components/Combobox/Combobox.module.cjs.map +1 -1
- package/dist/components/Combobox/Combobox.module.js.map +1 -1
- package/dist/components/DataTable/DataTable.cjs +1 -1
- package/dist/components/DataTable/DataTable.cjs.map +1 -1
- package/dist/components/DataTable/DataTable.js +203 -66
- package/dist/components/DataTable/DataTable.js.map +1 -1
- package/dist/components/DataTable/DataTable.module.cjs +1 -1
- package/dist/components/DataTable/DataTable.module.cjs.map +1 -1
- package/dist/components/DataTable/DataTable.module.js +9 -3
- package/dist/components/DataTable/DataTable.module.js.map +1 -1
- package/dist/components/DataTable/EditableCell.cjs +2 -0
- package/dist/components/DataTable/EditableCell.cjs.map +1 -0
- package/dist/components/DataTable/EditableCell.js +77 -0
- package/dist/components/DataTable/EditableCell.js.map +1 -0
- package/dist/components/DataTable/edit-labels.cjs +2 -0
- package/dist/components/DataTable/edit-labels.cjs.map +1 -0
- package/dist/components/DataTable/edit-labels.js +11 -0
- package/dist/components/DataTable/edit-labels.js.map +1 -0
- package/dist/components/DateRangePicker/DateRangePicker.module.cjs.map +1 -1
- package/dist/components/DateRangePicker/DateRangePicker.module.js.map +1 -1
- package/dist/components/MultiSelect/MultiSelect.module.cjs.map +1 -1
- package/dist/components/MultiSelect/MultiSelect.module.js.map +1 -1
- package/dist/components/NavigationRail/NavigationRail.module.cjs.map +1 -1
- package/dist/components/NavigationRail/NavigationRail.module.js.map +1 -1
- package/dist/components/SyncStatusBadge/SyncStatusBadge.cjs +1 -1
- package/dist/components/SyncStatusBadge/SyncStatusBadge.cjs.map +1 -1
- package/dist/components/SyncStatusBadge/SyncStatusBadge.js +33 -32
- package/dist/components/SyncStatusBadge/SyncStatusBadge.js.map +1 -1
- package/dist/components/Toast/ToastProvider.cjs +1 -1
- package/dist/components/Toast/ToastProvider.cjs.map +1 -1
- package/dist/components/Toast/ToastProvider.js +1 -2
- package/dist/components/Toast/ToastProvider.js.map +1 -1
- package/dist/hooks/use-announce.cjs +2 -0
- package/dist/hooks/use-announce.cjs.map +1 -0
- package/dist/hooks/use-announce.js +50 -0
- package/dist/hooks/use-announce.js.map +1 -0
- package/dist/hooks/use-media-devices.cjs +2 -0
- package/dist/hooks/use-media-devices.cjs.map +1 -0
- package/dist/hooks/use-media-devices.js +46 -0
- package/dist/hooks/use-media-devices.js.map +1 -0
- package/dist/hooks/use-media-permission.cjs +2 -0
- package/dist/hooks/use-media-permission.cjs.map +1 -0
- package/dist/hooks/use-media-permission.js +33 -0
- package/dist/hooks/use-media-permission.js.map +1 -0
- package/dist/http/resumable-upload.cjs +2 -0
- package/dist/http/resumable-upload.cjs.map +1 -0
- package/dist/http/resumable-upload.js +249 -0
- package/dist/http/resumable-upload.js.map +1 -0
- package/dist/styles.css +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +2485 -29
- package/dist/tempest-react-sdk.js +268 -244
- package/dist/vision/core/graph.cjs +2 -0
- package/dist/vision/core/graph.cjs.map +1 -0
- package/dist/vision/core/graph.js +17 -0
- package/dist/vision/core/graph.js.map +1 -0
- package/dist/vision/core/session.cjs +1 -1
- package/dist/vision/core/session.cjs.map +1 -1
- package/dist/vision/core/session.js +19 -9
- package/dist/vision/core/session.js.map +1 -1
- package/dist/vision/index.cjs +1 -1
- package/dist/vision/index.cjs.map +1 -1
- package/dist/vision/index.js +14 -13
- package/dist/vision/index.js.map +1 -1
- package/dist/vision/tasks/classifier.cjs +1 -1
- package/dist/vision/tasks/classifier.cjs.map +1 -1
- package/dist/vision/tasks/classifier.js +33 -25
- package/dist/vision/tasks/classifier.js.map +1 -1
- package/dist/vision/tasks/detector.cjs +1 -1
- package/dist/vision/tasks/detector.cjs.map +1 -1
- package/dist/vision/tasks/detector.js +28 -20
- package/dist/vision/tasks/detector.js.map +1 -1
- package/dist/vision/tasks/segmenter.cjs +1 -1
- package/dist/vision/tasks/segmenter.cjs.map +1 -1
- package/dist/vision/tasks/segmenter.js +23 -15
- package/dist/vision/tasks/segmenter.js.map +1 -1
- package/dist/vision/use-camera-stream.cjs +1 -1
- package/dist/vision/use-camera-stream.cjs.map +1 -1
- package/dist/vision/use-camera-stream.js +40 -57
- package/dist/vision/use-camera-stream.js.map +1 -1
- package/dist/vision.cjs +1 -1
- package/dist/vision.d.ts +149 -8
- package/dist/vision.js +22 -21
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-speech-recognition.cjs","names":[],"sources":["../../src/capture/use-speech-recognition.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { useStableCallback } from \"@/hooks/use-stable-callback\";\n\n/** One reading of what was heard. */\nexport interface SpeechAlternativeLike {\n transcript: string;\n confidence?: number;\n}\n\n/** One recognised phrase, settled (`isFinal`) or still being revised. */\nexport interface SpeechResultLike {\n isFinal: boolean;\n length: number;\n [index: number]: SpeechAlternativeLike | undefined;\n}\n\n/** The growing list of phrases in a session. */\nexport interface SpeechResultListLike {\n length: number;\n [index: number]: SpeechResultLike | undefined;\n}\n\n/** The `result` event, reduced to what this hook reads. */\nexport interface SpeechRecognitionEventLike {\n /** Index of the first result that changed — everything before it is settled. */\n resultIndex: number;\n results: SpeechResultListLike;\n}\n\n/** The `error` event, reduced to what this hook reads. */\nexport interface SpeechRecognitionErrorEventLike {\n error: string;\n message?: string;\n}\n\n/**\n * The slice of the Web Speech `SpeechRecognition` object this SDK uses.\n *\n * Declared here rather than imported: TypeScript's DOM lib ships the *event* types but\n * not the constructor, because the API is still prefixed in Chromium and absent in\n * Firefox. Exported so a test — or a consumer wrapping a different engine — can hand in\n * something else.\n */\nexport interface SpeechRecognitionLike {\n lang: string;\n continuous: boolean;\n interimResults: boolean;\n maxAlternatives: number;\n start: () => void;\n stop: () => void;\n abort: () => void;\n onresult: ((event: SpeechRecognitionEventLike) => void) | null;\n onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;\n onend: (() => void) | null;\n onstart: (() => void) | null;\n}\n\n/** Classified reason recognition stopped or never started. */\nexport type SpeechErrorKind =\n | \"unsupported\"\n | \"not-allowed\"\n | \"no-speech\"\n | \"audio-capture\"\n | \"network\"\n | \"aborted\"\n | \"language-not-supported\"\n | \"unknown\";\n\n/** A classified speech error with a human-readable, English message. */\nexport interface SpeechError {\n kind: SpeechErrorKind;\n message: string;\n}\n\n/** Options for {@link useSpeechRecognition}. */\nexport interface UseSpeechRecognitionOptions {\n /** BCP-47 tag. Default `\"pt-BR\"`. */\n lang?: string;\n /**\n * Keep listening after the first phrase settles. Default `false`.\n *\n * Even with this on, the engine ends the session by itself after a stretch of\n * silence — that is a server-side timeout, not a bug — so watch `listening` rather\n * than assuming the microphone stays open.\n */\n continuous?: boolean;\n /** Publish the running guess as it changes. Default `true`. */\n interimResults?: boolean;\n /** How many readings per phrase to ask for. Default 1. */\n maxAlternatives?: number;\n /** Every update, settled or not. */\n onResult?: (result: { transcript: string; isFinal: boolean }) => void;\n /** Only the settled text of a phrase. The one to wire dictation to. */\n onFinal?: (transcript: string) => void;\n /** Classified failure. `no-speech` and `aborted` arrive here too — they are routine. */\n onError?: (error: SpeechError) => void;\n /** The session ended, for any reason. */\n onEnd?: () => void;\n /** Build the recogniser yourself — another engine, or a stub in a test. */\n factory?: () => SpeechRecognitionLike;\n}\n\n/** Value returned by {@link useSpeechRecognition}. */\nexport interface UseSpeechRecognitionResult {\n /** `false` in Firefox and in every browser that is not Chromium-based. */\n supported: boolean;\n /** Whether a session is open right now. */\n listening: boolean;\n /** Everything settled so far in this session. Cleared by `reset()`. */\n transcript: string;\n /** The running guess. Replaced on every event, empty once the phrase settles. */\n interim: string;\n /** Classified error, or `null`. */\n error: SpeechError | null;\n /** Open a session. No-op while already listening. */\n start: () => void;\n /** Close the session, keeping what was recognised. */\n stop: () => void;\n /** Close the session and throw the pending phrase away. */\n abort: () => void;\n /** Clear `transcript`, `interim` and `error`. Does not stop a session. */\n reset: () => void;\n}\n\n/** English messages for the `error` codes the spec defines. */\nconst MESSAGES: Record<SpeechErrorKind, string> = {\n unsupported: \"Speech recognition is not supported in this browser.\",\n \"not-allowed\": \"Microphone permission denied. Enable access in your browser settings.\",\n \"no-speech\": \"No speech was detected.\",\n \"audio-capture\": \"No microphone available on this device.\",\n network: \"The recognition service could not be reached.\",\n aborted: \"Recognition was cancelled.\",\n \"language-not-supported\": \"The recognition service does not support this language.\",\n unknown: \"Unexpected error during speech recognition.\",\n};\n\n/**\n * Map a spec `error` code to a kind an app can branch on.\n *\n * `service-not-allowed` collapses into `not-allowed` because the fix is the same from\n * the user's side, and `bad-grammar` into `unknown` because this hook never sets a\n * grammar, so seeing it means something outside our control went wrong.\n *\n * @param code - The `error` property of the event.\n * @returns The classified kind.\n */\nfunction classifySpeechError(code: string): SpeechErrorKind {\n switch (code) {\n case \"not-allowed\":\n case \"service-not-allowed\":\n return \"not-allowed\";\n case \"no-speech\":\n return \"no-speech\";\n case \"audio-capture\":\n return \"audio-capture\";\n case \"network\":\n return \"network\";\n case \"aborted\":\n return \"aborted\";\n case \"language-not-supported\":\n return \"language-not-supported\";\n default:\n return \"unknown\";\n }\n}\n\n/** The constructor, prefixed or not, or `null` where the API does not exist. */\nfunction speechRecognitionConstructor(): (new () => SpeechRecognitionLike) | null {\n const scope = globalThis as {\n SpeechRecognition?: unknown;\n webkitSpeechRecognition?: unknown;\n };\n const candidate = scope.SpeechRecognition ?? scope.webkitSpeechRecognition;\n return typeof candidate === \"function\" ? (candidate as new () => SpeechRecognitionLike) : null;\n}\n\n/** Whether this browser exposes the Web Speech recognition API at all. */\nexport function isSpeechRecognitionSupported(): boolean {\n return speechRecognitionConstructor() !== null;\n}\n\n/**\n * Dictate into your app with the Web Speech API — no dependency, no API key.\n *\n * ## Recognition is not local\n *\n * **Chromium streams the captured audio to a Google server to transcribe it.** Nothing\n * about the API says so, there is no setting that changes it, and it happens on every\n * `start()`. Anything the user says while a session is open leaves the device. Do not\n * put this on a field that takes clinical notes, credentials, or a client's financial\n * detail without telling them first — and if the data cannot leave your infrastructure,\n * this API is the wrong tool and a self-hosted model is the right one.\n *\n * ## What the states mean\n *\n * `transcript` accumulates the phrases the engine has **settled** on; `interim` is the\n * guess it is still revising and is replaced wholesale on every event, so rendering\n * `transcript + interim` gives the live caption effect and rendering `transcript` alone\n * gives the committed text. `no-speech` and `aborted` come through `onError` but are\n * routine — a user who pressed the button and said nothing is not a failure to report.\n *\n * There is deliberately **no auto-restart** when the engine ends a session on silence.\n * A restart loop is how an app ends up holding the microphone indefinitely — and, in\n * Chromium, streaming audio to a third party indefinitely. Show that listening stopped\n * and let the user press again.\n *\n * @param options - See {@link UseSpeechRecognitionOptions}.\n * @returns Session state, the transcript and the controls.\n *\n * @example\n * const speech = useSpeechRecognition({ onFinal: (text) => setPrompt(text) });\n * <button onClick={speech.listening ? speech.stop : speech.start}>\n * {speech.listening ? \"Parar\" : \"Ditar\"}\n * </button>\n * <p>{speech.transcript}{speech.interim}</p>\n */\nexport function useSpeechRecognition(\n options: UseSpeechRecognitionOptions = {},\n): UseSpeechRecognitionResult {\n const {\n lang = \"pt-BR\",\n continuous = false,\n interimResults = true,\n maxAlternatives = 1,\n onResult,\n onFinal,\n onError,\n onEnd,\n factory,\n } = options;\n\n const [supported] = useState(() => factory !== undefined || isSpeechRecognitionSupported());\n const [listening, setListening] = useState(false);\n const [transcript, setTranscript] = useState(\"\");\n const [interim, setInterim] = useState(\"\");\n const [error, setError] = useState<SpeechError | null>(null);\n\n const sessionRef = useRef<SpeechRecognitionLike | null>(null);\n\n const emitResult = useStableCallback((result: { transcript: string; isFinal: boolean }) =>\n onResult?.(result),\n );\n const emitFinal = useStableCallback((text: string) => onFinal?.(text));\n const emitEnd = useStableCallback(() => onEnd?.());\n const emitError = useStableCallback((failure: SpeechError) => {\n setError(failure);\n onError?.(failure);\n });\n\n const teardown = useCallback((): void => {\n const session = sessionRef.current;\n if (!session) return;\n session.onresult = null;\n session.onerror = null;\n session.onend = null;\n session.onstart = null;\n sessionRef.current = null;\n }, []);\n\n const start = useCallback((): void => {\n if (sessionRef.current) return;\n const build =\n factory ??\n (() => {\n const constructor = speechRecognitionConstructor();\n return constructor ? new constructor() : null;\n });\n const session = build();\n if (!session) {\n emitError({ kind: \"unsupported\", message: MESSAGES.unsupported });\n return;\n }\n\n session.lang = lang;\n session.continuous = continuous;\n session.interimResults = interimResults;\n session.maxAlternatives = maxAlternatives;\n\n /**\n * Fold one event into the two published strings.\n *\n * Only the results from `resultIndex` on are new; re-reading the whole list\n * would append phrases that are already in `transcript`. Settled text is\n * accumulated, unsettled text replaces the previous guess entirely — the engine\n * revises a phrase in place, so appending it would stutter the caption.\n */\n session.onresult = (event: SpeechRecognitionEventLike): void => {\n let settled = \"\";\n let pending = \"\";\n for (let index = event.resultIndex; index < event.results.length; index += 1) {\n const result = event.results[index];\n if (!result) continue;\n const text = result[0]?.transcript ?? \"\";\n if (result.isFinal) settled += text;\n else pending += text;\n }\n setInterim(pending);\n if (settled !== \"\") {\n setTranscript((previous) => previous + settled);\n emitFinal(settled);\n }\n emitResult({ transcript: settled !== \"\" ? settled : pending, isFinal: settled !== \"\" });\n };\n\n session.onerror = (event: SpeechRecognitionErrorEventLike): void => {\n const kind = classifySpeechError(event.error);\n emitError({ kind, message: event.message || MESSAGES[kind] });\n };\n\n session.onend = (): void => {\n setListening(false);\n setInterim(\"\");\n teardown();\n emitEnd();\n };\n\n session.onstart = (): void => setListening(true);\n\n setError(null);\n try {\n session.start();\n } catch (failure) {\n // Chromium throws `InvalidStateError` when a session is already running in\n // another component. Reporting it beats leaving a dead handle behind.\n emitError({\n kind: \"unknown\",\n message: failure instanceof Error ? failure.message : MESSAGES.unknown,\n });\n return;\n }\n sessionRef.current = session;\n setListening(true);\n }, [\n lang,\n continuous,\n interimResults,\n maxAlternatives,\n factory,\n emitResult,\n emitFinal,\n emitEnd,\n emitError,\n teardown,\n ]);\n\n const stop = useCallback((): void => {\n sessionRef.current?.stop();\n }, []);\n\n const abort = useCallback((): void => {\n sessionRef.current?.abort();\n }, []);\n\n const reset = useCallback((): void => {\n setTranscript(\"\");\n setInterim(\"\");\n setError(null);\n }, []);\n\n /**\n * Never leave a session open past unmount.\n *\n * `abort()` and not `stop()`: a component that is gone has nowhere to put a final\n * result, and `stop()` would keep the microphone — and the upstream connection —\n * alive while the engine finishes deciding what the last word was.\n */\n useEffect(\n () => () => {\n sessionRef.current?.abort();\n teardown();\n },\n [teardown],\n );\n\n return {\n supported,\n listening,\n transcript,\n interim,\n error,\n start,\n stop,\n abort,\n reset,\n };\n}\n"],"mappings":"2EA8HA,IAAM,EAA4C,CAC9C,YAAa,uDACb,cAAe,wEACf,YAAa,0BACb,gBAAiB,0CACjB,QAAS,gDACT,QAAS,6BACT,yBAA0B,0DAC1B,QAAS,6CACb,EAYA,SAAS,EAAoB,EAA+B,CACxD,OAAQ,EAAR,CACI,IAAK,cACL,IAAK,sBACD,MAAO,cACX,IAAK,YACD,MAAO,YACX,IAAK,gBACD,MAAO,gBACX,IAAK,UACD,MAAO,UACX,IAAK,UACD,MAAO,UACX,IAAK,yBACD,MAAO,yBACX,QACI,MAAO,SACf,CACJ,CAGA,SAAS,GAAyE,CAC9E,IAAM,EAAQ,WAIR,EAAY,EAAM,mBAAqB,EAAM,wBACnD,OAAO,OAAO,GAAc,WAAc,EAAgD,IAC9F,CAGA,SAAgB,GAAwC,CACpD,OAAO,EAA6B,IAAM,IAC9C,CAqCA,SAAgB,EACZ,EAAuC,CAAC,EACd,CAC1B,GAAM,CACF,OAAO,QACP,aAAa,GACb,iBAAiB,GACjB,kBAAkB,EAClB,WACA,UACA,UACA,QACA,WACA,EAEE,CAAC,IAAA,EAAA,EAAA,SAAA,KAA4B,IAAY,IAAA,IAAa,EAA6B,CAAC,EACpF,CAAC,EAAW,IAAA,EAAA,EAAA,SAAA,CAAyB,EAAK,EAC1C,CAAC,EAAY,IAAA,EAAA,EAAA,SAAA,CAA0B,EAAE,EACzC,CAAC,EAAS,IAAA,EAAA,EAAA,SAAA,CAAuB,EAAE,EACnC,CAAC,EAAO,IAAA,EAAA,EAAA,SAAA,CAAyC,IAAI,EAErD,GAAA,EAAA,EAAA,OAAA,CAAkD,IAAI,EAEtD,EAAa,EAAA,kBAAmB,GAClC,IAAW,CAAM,CACrB,EACM,EAAY,EAAA,kBAAmB,GAAiB,IAA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UAAoB,CACxB,EAAa,EAAK,EAClB,EAAW,EAAE,EACb,EAAS,EACT,EAAQ,CACZ,EAEA,EAAQ,YAAsB,EAAa,EAAI,EAE/C,EAAS,IAAI,EACb,GAAI,CACA,EAAQ,MAAM,CAClB,OAAS,EAAS,CAGd,EAAU,CACN,KAAM,UACN,QAAS,aAAmB,MAAQ,EAAQ,QAAU,EAAS,OACnE,CAAC,EACD,MACJ,CACA,EAAW,QAAU,EACrB,EAAa,EAAI,CACrB,EAAG,CACC,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,CACJ,CAAC,EAEK,GAAA,EAAA,EAAA,YAAA,KAA+B,CACjC,EAAW,SAAS,KAAK,CAC7B,EAAG,CAAC,CAAC,EAEC,GAAA,EAAA,EAAA,YAAA,KAAgC,CAClC,EAAW,SAAS,MAAM,CAC9B,EAAG,CAAC,CAAC,EAEC,GAAA,EAAA,EAAA,YAAA,KAAgC,CAClC,EAAc,EAAE,EAChB,EAAW,EAAE,EACb,EAAS,IAAI,CACjB,EAAG,CAAC,CAAC,EAiBL,OARA,EAAA,EAAA,UAAA,SACgB,CACR,EAAW,SAAS,MAAM,EAC1B,EAAS,CACb,EACA,CAAC,CAAQ,CACb,EAEO,CACH,YACA,YACA,aACA,UACA,QACA,QACA,OACA,QACA,OACJ,CACJ"}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { useStableCallback as e } from "../hooks/use-stable-callback.js";
|
|
2
|
+
import { useCallback as t, useEffect as n, useRef as r, useState as i } from "react";
|
|
3
|
+
//#region src/capture/use-speech-recognition.ts
|
|
4
|
+
var a = {
|
|
5
|
+
unsupported: "Speech recognition is not supported in this browser.",
|
|
6
|
+
"not-allowed": "Microphone permission denied. Enable access in your browser settings.",
|
|
7
|
+
"no-speech": "No speech was detected.",
|
|
8
|
+
"audio-capture": "No microphone available on this device.",
|
|
9
|
+
network: "The recognition service could not be reached.",
|
|
10
|
+
aborted: "Recognition was cancelled.",
|
|
11
|
+
"language-not-supported": "The recognition service does not support this language.",
|
|
12
|
+
unknown: "Unexpected error during speech recognition."
|
|
13
|
+
};
|
|
14
|
+
function o(e) {
|
|
15
|
+
switch (e) {
|
|
16
|
+
case "not-allowed":
|
|
17
|
+
case "service-not-allowed": return "not-allowed";
|
|
18
|
+
case "no-speech": return "no-speech";
|
|
19
|
+
case "audio-capture": return "audio-capture";
|
|
20
|
+
case "network": return "network";
|
|
21
|
+
case "aborted": return "aborted";
|
|
22
|
+
case "language-not-supported": return "language-not-supported";
|
|
23
|
+
default: return "unknown";
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function s() {
|
|
27
|
+
let e = globalThis, t = e.SpeechRecognition ?? e.webkitSpeechRecognition;
|
|
28
|
+
return typeof t == "function" ? t : null;
|
|
29
|
+
}
|
|
30
|
+
function c() {
|
|
31
|
+
return s() !== null;
|
|
32
|
+
}
|
|
33
|
+
function l(l = {}) {
|
|
34
|
+
let { lang: u = "pt-BR", continuous: d = !1, interimResults: f = !0, maxAlternatives: p = 1, onResult: m, onFinal: h, onError: g, onEnd: _, factory: v } = l, [y] = i(() => v !== void 0 || c()), [b, x] = i(!1), [S, C] = i(""), [w, T] = i(""), [E, D] = i(null), O = r(null), k = e((e) => m?.(e)), A = e((e) => h?.(e)), j = e(() => _?.()), M = e((e) => {
|
|
35
|
+
D(e), g?.(e);
|
|
36
|
+
}), N = t(() => {
|
|
37
|
+
let e = O.current;
|
|
38
|
+
e && (e.onresult = null, e.onerror = null, e.onend = null, e.onstart = null, O.current = null);
|
|
39
|
+
}, []), P = t(() => {
|
|
40
|
+
if (O.current) return;
|
|
41
|
+
let e = (v ?? (() => {
|
|
42
|
+
let e = s();
|
|
43
|
+
return e ? new e() : null;
|
|
44
|
+
}))();
|
|
45
|
+
if (!e) {
|
|
46
|
+
M({
|
|
47
|
+
kind: "unsupported",
|
|
48
|
+
message: a.unsupported
|
|
49
|
+
});
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
e.lang = u, e.continuous = d, e.interimResults = f, e.maxAlternatives = p, e.onresult = (e) => {
|
|
53
|
+
let t = "", n = "";
|
|
54
|
+
for (let r = e.resultIndex; r < e.results.length; r += 1) {
|
|
55
|
+
let i = e.results[r];
|
|
56
|
+
if (!i) continue;
|
|
57
|
+
let a = i[0]?.transcript ?? "";
|
|
58
|
+
i.isFinal ? t += a : n += a;
|
|
59
|
+
}
|
|
60
|
+
T(n), t !== "" && (C((e) => e + t), A(t)), k({
|
|
61
|
+
transcript: t === "" ? n : t,
|
|
62
|
+
isFinal: t !== ""
|
|
63
|
+
});
|
|
64
|
+
}, e.onerror = (e) => {
|
|
65
|
+
let t = o(e.error);
|
|
66
|
+
M({
|
|
67
|
+
kind: t,
|
|
68
|
+
message: e.message || a[t]
|
|
69
|
+
});
|
|
70
|
+
}, e.onend = () => {
|
|
71
|
+
x(!1), T(""), N(), j();
|
|
72
|
+
}, e.onstart = () => x(!0), D(null);
|
|
73
|
+
try {
|
|
74
|
+
e.start();
|
|
75
|
+
} catch (e) {
|
|
76
|
+
M({
|
|
77
|
+
kind: "unknown",
|
|
78
|
+
message: e instanceof Error ? e.message : a.unknown
|
|
79
|
+
});
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
O.current = e, x(!0);
|
|
83
|
+
}, [
|
|
84
|
+
u,
|
|
85
|
+
d,
|
|
86
|
+
f,
|
|
87
|
+
p,
|
|
88
|
+
v,
|
|
89
|
+
k,
|
|
90
|
+
A,
|
|
91
|
+
j,
|
|
92
|
+
M,
|
|
93
|
+
N
|
|
94
|
+
]), F = t(() => {
|
|
95
|
+
O.current?.stop();
|
|
96
|
+
}, []), I = t(() => {
|
|
97
|
+
O.current?.abort();
|
|
98
|
+
}, []), L = t(() => {
|
|
99
|
+
C(""), T(""), D(null);
|
|
100
|
+
}, []);
|
|
101
|
+
return n(() => () => {
|
|
102
|
+
O.current?.abort(), N();
|
|
103
|
+
}, [N]), {
|
|
104
|
+
supported: y,
|
|
105
|
+
listening: b,
|
|
106
|
+
transcript: S,
|
|
107
|
+
interim: w,
|
|
108
|
+
error: E,
|
|
109
|
+
start: P,
|
|
110
|
+
stop: F,
|
|
111
|
+
abort: I,
|
|
112
|
+
reset: L
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
//#endregion
|
|
116
|
+
export { c as isSpeechRecognitionSupported, l as useSpeechRecognition };
|
|
117
|
+
|
|
118
|
+
//# sourceMappingURL=use-speech-recognition.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-speech-recognition.js","names":[],"sources":["../../src/capture/use-speech-recognition.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { useStableCallback } from \"@/hooks/use-stable-callback\";\n\n/** One reading of what was heard. */\nexport interface SpeechAlternativeLike {\n transcript: string;\n confidence?: number;\n}\n\n/** One recognised phrase, settled (`isFinal`) or still being revised. */\nexport interface SpeechResultLike {\n isFinal: boolean;\n length: number;\n [index: number]: SpeechAlternativeLike | undefined;\n}\n\n/** The growing list of phrases in a session. */\nexport interface SpeechResultListLike {\n length: number;\n [index: number]: SpeechResultLike | undefined;\n}\n\n/** The `result` event, reduced to what this hook reads. */\nexport interface SpeechRecognitionEventLike {\n /** Index of the first result that changed — everything before it is settled. */\n resultIndex: number;\n results: SpeechResultListLike;\n}\n\n/** The `error` event, reduced to what this hook reads. */\nexport interface SpeechRecognitionErrorEventLike {\n error: string;\n message?: string;\n}\n\n/**\n * The slice of the Web Speech `SpeechRecognition` object this SDK uses.\n *\n * Declared here rather than imported: TypeScript's DOM lib ships the *event* types but\n * not the constructor, because the API is still prefixed in Chromium and absent in\n * Firefox. Exported so a test — or a consumer wrapping a different engine — can hand in\n * something else.\n */\nexport interface SpeechRecognitionLike {\n lang: string;\n continuous: boolean;\n interimResults: boolean;\n maxAlternatives: number;\n start: () => void;\n stop: () => void;\n abort: () => void;\n onresult: ((event: SpeechRecognitionEventLike) => void) | null;\n onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;\n onend: (() => void) | null;\n onstart: (() => void) | null;\n}\n\n/** Classified reason recognition stopped or never started. */\nexport type SpeechErrorKind =\n | \"unsupported\"\n | \"not-allowed\"\n | \"no-speech\"\n | \"audio-capture\"\n | \"network\"\n | \"aborted\"\n | \"language-not-supported\"\n | \"unknown\";\n\n/** A classified speech error with a human-readable, English message. */\nexport interface SpeechError {\n kind: SpeechErrorKind;\n message: string;\n}\n\n/** Options for {@link useSpeechRecognition}. */\nexport interface UseSpeechRecognitionOptions {\n /** BCP-47 tag. Default `\"pt-BR\"`. */\n lang?: string;\n /**\n * Keep listening after the first phrase settles. Default `false`.\n *\n * Even with this on, the engine ends the session by itself after a stretch of\n * silence — that is a server-side timeout, not a bug — so watch `listening` rather\n * than assuming the microphone stays open.\n */\n continuous?: boolean;\n /** Publish the running guess as it changes. Default `true`. */\n interimResults?: boolean;\n /** How many readings per phrase to ask for. Default 1. */\n maxAlternatives?: number;\n /** Every update, settled or not. */\n onResult?: (result: { transcript: string; isFinal: boolean }) => void;\n /** Only the settled text of a phrase. The one to wire dictation to. */\n onFinal?: (transcript: string) => void;\n /** Classified failure. `no-speech` and `aborted` arrive here too — they are routine. */\n onError?: (error: SpeechError) => void;\n /** The session ended, for any reason. */\n onEnd?: () => void;\n /** Build the recogniser yourself — another engine, or a stub in a test. */\n factory?: () => SpeechRecognitionLike;\n}\n\n/** Value returned by {@link useSpeechRecognition}. */\nexport interface UseSpeechRecognitionResult {\n /** `false` in Firefox and in every browser that is not Chromium-based. */\n supported: boolean;\n /** Whether a session is open right now. */\n listening: boolean;\n /** Everything settled so far in this session. Cleared by `reset()`. */\n transcript: string;\n /** The running guess. Replaced on every event, empty once the phrase settles. */\n interim: string;\n /** Classified error, or `null`. */\n error: SpeechError | null;\n /** Open a session. No-op while already listening. */\n start: () => void;\n /** Close the session, keeping what was recognised. */\n stop: () => void;\n /** Close the session and throw the pending phrase away. */\n abort: () => void;\n /** Clear `transcript`, `interim` and `error`. Does not stop a session. */\n reset: () => void;\n}\n\n/** English messages for the `error` codes the spec defines. */\nconst MESSAGES: Record<SpeechErrorKind, string> = {\n unsupported: \"Speech recognition is not supported in this browser.\",\n \"not-allowed\": \"Microphone permission denied. Enable access in your browser settings.\",\n \"no-speech\": \"No speech was detected.\",\n \"audio-capture\": \"No microphone available on this device.\",\n network: \"The recognition service could not be reached.\",\n aborted: \"Recognition was cancelled.\",\n \"language-not-supported\": \"The recognition service does not support this language.\",\n unknown: \"Unexpected error during speech recognition.\",\n};\n\n/**\n * Map a spec `error` code to a kind an app can branch on.\n *\n * `service-not-allowed` collapses into `not-allowed` because the fix is the same from\n * the user's side, and `bad-grammar` into `unknown` because this hook never sets a\n * grammar, so seeing it means something outside our control went wrong.\n *\n * @param code - The `error` property of the event.\n * @returns The classified kind.\n */\nfunction classifySpeechError(code: string): SpeechErrorKind {\n switch (code) {\n case \"not-allowed\":\n case \"service-not-allowed\":\n return \"not-allowed\";\n case \"no-speech\":\n return \"no-speech\";\n case \"audio-capture\":\n return \"audio-capture\";\n case \"network\":\n return \"network\";\n case \"aborted\":\n return \"aborted\";\n case \"language-not-supported\":\n return \"language-not-supported\";\n default:\n return \"unknown\";\n }\n}\n\n/** The constructor, prefixed or not, or `null` where the API does not exist. */\nfunction speechRecognitionConstructor(): (new () => SpeechRecognitionLike) | null {\n const scope = globalThis as {\n SpeechRecognition?: unknown;\n webkitSpeechRecognition?: unknown;\n };\n const candidate = scope.SpeechRecognition ?? scope.webkitSpeechRecognition;\n return typeof candidate === \"function\" ? (candidate as new () => SpeechRecognitionLike) : null;\n}\n\n/** Whether this browser exposes the Web Speech recognition API at all. */\nexport function isSpeechRecognitionSupported(): boolean {\n return speechRecognitionConstructor() !== null;\n}\n\n/**\n * Dictate into your app with the Web Speech API — no dependency, no API key.\n *\n * ## Recognition is not local\n *\n * **Chromium streams the captured audio to a Google server to transcribe it.** Nothing\n * about the API says so, there is no setting that changes it, and it happens on every\n * `start()`. Anything the user says while a session is open leaves the device. Do not\n * put this on a field that takes clinical notes, credentials, or a client's financial\n * detail without telling them first — and if the data cannot leave your infrastructure,\n * this API is the wrong tool and a self-hosted model is the right one.\n *\n * ## What the states mean\n *\n * `transcript` accumulates the phrases the engine has **settled** on; `interim` is the\n * guess it is still revising and is replaced wholesale on every event, so rendering\n * `transcript + interim` gives the live caption effect and rendering `transcript` alone\n * gives the committed text. `no-speech` and `aborted` come through `onError` but are\n * routine — a user who pressed the button and said nothing is not a failure to report.\n *\n * There is deliberately **no auto-restart** when the engine ends a session on silence.\n * A restart loop is how an app ends up holding the microphone indefinitely — and, in\n * Chromium, streaming audio to a third party indefinitely. Show that listening stopped\n * and let the user press again.\n *\n * @param options - See {@link UseSpeechRecognitionOptions}.\n * @returns Session state, the transcript and the controls.\n *\n * @example\n * const speech = useSpeechRecognition({ onFinal: (text) => setPrompt(text) });\n * <button onClick={speech.listening ? speech.stop : speech.start}>\n * {speech.listening ? \"Parar\" : \"Ditar\"}\n * </button>\n * <p>{speech.transcript}{speech.interim}</p>\n */\nexport function useSpeechRecognition(\n options: UseSpeechRecognitionOptions = {},\n): UseSpeechRecognitionResult {\n const {\n lang = \"pt-BR\",\n continuous = false,\n interimResults = true,\n maxAlternatives = 1,\n onResult,\n onFinal,\n onError,\n onEnd,\n factory,\n } = options;\n\n const [supported] = useState(() => factory !== undefined || isSpeechRecognitionSupported());\n const [listening, setListening] = useState(false);\n const [transcript, setTranscript] = useState(\"\");\n const [interim, setInterim] = useState(\"\");\n const [error, setError] = useState<SpeechError | null>(null);\n\n const sessionRef = useRef<SpeechRecognitionLike | null>(null);\n\n const emitResult = useStableCallback((result: { transcript: string; isFinal: boolean }) =>\n onResult?.(result),\n );\n const emitFinal = useStableCallback((text: string) => onFinal?.(text));\n const emitEnd = useStableCallback(() => onEnd?.());\n const emitError = useStableCallback((failure: SpeechError) => {\n setError(failure);\n onError?.(failure);\n });\n\n const teardown = useCallback((): void => {\n const session = sessionRef.current;\n if (!session) return;\n session.onresult = null;\n session.onerror = null;\n session.onend = null;\n session.onstart = null;\n sessionRef.current = null;\n }, []);\n\n const start = useCallback((): void => {\n if (sessionRef.current) return;\n const build =\n factory ??\n (() => {\n const constructor = speechRecognitionConstructor();\n return constructor ? new constructor() : null;\n });\n const session = build();\n if (!session) {\n emitError({ kind: \"unsupported\", message: MESSAGES.unsupported });\n return;\n }\n\n session.lang = lang;\n session.continuous = continuous;\n session.interimResults = interimResults;\n session.maxAlternatives = maxAlternatives;\n\n /**\n * Fold one event into the two published strings.\n *\n * Only the results from `resultIndex` on are new; re-reading the whole list\n * would append phrases that are already in `transcript`. Settled text is\n * accumulated, unsettled text replaces the previous guess entirely — the engine\n * revises a phrase in place, so appending it would stutter the caption.\n */\n session.onresult = (event: SpeechRecognitionEventLike): void => {\n let settled = \"\";\n let pending = \"\";\n for (let index = event.resultIndex; index < event.results.length; index += 1) {\n const result = event.results[index];\n if (!result) continue;\n const text = result[0]?.transcript ?? \"\";\n if (result.isFinal) settled += text;\n else pending += text;\n }\n setInterim(pending);\n if (settled !== \"\") {\n setTranscript((previous) => previous + settled);\n emitFinal(settled);\n }\n emitResult({ transcript: settled !== \"\" ? settled : pending, isFinal: settled !== \"\" });\n };\n\n session.onerror = (event: SpeechRecognitionErrorEventLike): void => {\n const kind = classifySpeechError(event.error);\n emitError({ kind, message: event.message || MESSAGES[kind] });\n };\n\n session.onend = (): void => {\n setListening(false);\n setInterim(\"\");\n teardown();\n emitEnd();\n };\n\n session.onstart = (): void => setListening(true);\n\n setError(null);\n try {\n session.start();\n } catch (failure) {\n // Chromium throws `InvalidStateError` when a session is already running in\n // another component. Reporting it beats leaving a dead handle behind.\n emitError({\n kind: \"unknown\",\n message: failure instanceof Error ? failure.message : MESSAGES.unknown,\n });\n return;\n }\n sessionRef.current = session;\n setListening(true);\n }, [\n lang,\n continuous,\n interimResults,\n maxAlternatives,\n factory,\n emitResult,\n emitFinal,\n emitEnd,\n emitError,\n teardown,\n ]);\n\n const stop = useCallback((): void => {\n sessionRef.current?.stop();\n }, []);\n\n const abort = useCallback((): void => {\n sessionRef.current?.abort();\n }, []);\n\n const reset = useCallback((): void => {\n setTranscript(\"\");\n setInterim(\"\");\n setError(null);\n }, []);\n\n /**\n * Never leave a session open past unmount.\n *\n * `abort()` and not `stop()`: a component that is gone has nowhere to put a final\n * result, and `stop()` would keep the microphone — and the upstream connection —\n * alive while the engine finishes deciding what the last word was.\n */\n useEffect(\n () => () => {\n sessionRef.current?.abort();\n teardown();\n },\n [teardown],\n );\n\n return {\n supported,\n listening,\n transcript,\n interim,\n error,\n start,\n stop,\n abort,\n reset,\n };\n}\n"],"mappings":";;;AA8HA,IAAM,IAA4C;CAC9C,aAAa;CACb,eAAe;CACf,aAAa;CACb,iBAAiB;CACjB,SAAS;CACT,SAAS;CACT,0BAA0B;CAC1B,SAAS;AACb;AAYA,SAAS,EAAoB,GAA+B;CACxD,QAAQ,GAAR;EACI,KAAK;EACL,KAAK,uBACD,OAAO;EACX,KAAK,aACD,OAAO;EACX,KAAK,iBACD,OAAO;EACX,KAAK,WACD,OAAO;EACX,KAAK,WACD,OAAO;EACX,KAAK,0BACD,OAAO;EACX,SACI,OAAO;CACf;AACJ;AAGA,SAAS,IAAyE;CAC9E,IAAM,IAAQ,YAIR,IAAY,EAAM,qBAAqB,EAAM;CACnD,OAAO,OAAO,KAAc,aAAc,IAAgD;AAC9F;AAGA,SAAgB,IAAwC;CACpD,OAAO,EAA6B,MAAM;AAC9C;AAqCA,SAAgB,EACZ,IAAuC,CAAC,GACd;CAC1B,IAAM,EACF,UAAO,SACP,gBAAa,IACb,oBAAiB,IACjB,qBAAkB,GAClB,aACA,YACA,YACA,UACA,eACA,GAEE,CAAC,KAAa,QAAe,MAAY,KAAA,KAAa,EAA6B,CAAC,GACpF,CAAC,GAAW,KAAgB,EAAS,EAAK,GAC1C,CAAC,GAAY,KAAiB,EAAS,EAAE,GACzC,CAAC,GAAS,KAAc,EAAS,EAAE,GACnC,CAAC,GAAO,KAAY,EAA6B,IAA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K;GAC5C,EAAU;IAAE;IAAM,SAAS,EAAM,WAAW,EAAS;GAAM,CAAC;EAChE,GAEA,EAAQ,cAAoB;GAIxB,AAHA,EAAa,EAAK,GAClB,EAAW,EAAE,GACb,EAAS,GACT,EAAQ;EACZ,GAEA,EAAQ,gBAAsB,EAAa,EAAI,GAE/C,EAAS,IAAI;EACb,IAAI;GACA,EAAQ,MAAM;EAClB,SAAS,GAAS;GAGd,EAAU;IACN,MAAM;IACN,SAAS,aAAmB,QAAQ,EAAQ,UAAU,EAAS;GACnE,CAAC;GACD;EACJ;EAEA,AADA,EAAW,UAAU,GACrB,EAAa,EAAI;CACrB,GAAG;EACC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ,CAAC,GAEK,IAAO,QAAwB;EACjC,EAAW,SAAS,KAAK;CAC7B,GAAG,CAAC,CAAC,GAEC,IAAQ,QAAwB;EAClC,EAAW,SAAS,MAAM;CAC9B,GAAG,CAAC,CAAC,GAEC,IAAQ,QAAwB;EAGlC,AAFA,EAAc,EAAE,GAChB,EAAW,EAAE,GACb,EAAS,IAAI;CACjB,GAAG,CAAC,CAAC;CAiBL,OARA,cACgB;EAER,AADA,EAAW,SAAS,MAAM,GAC1B,EAAS;CACb,GACA,CAAC,CAAQ,CACb,GAEO;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ;AACJ"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
let e=require("react");function t(t){let[n,r]=(0,e.useState)(!1),[i,a]=(0,e.useState)(!1);(0,e.useEffect)(()=>{let e=t?.getVideoTracks()[0]??null;if(!e){r(!1),a(!1);return}let n=e.getCapabilities?.()??{},i=e.getSettings();r(n.torch!==void 0||i.torch!==void 0),a(i.torch===!0)},[t]);let o=(0,e.useCallback)(async e=>{let n=t?.getVideoTracks()[0]??null;if(!n)return!1;try{return await n.applyConstraints({advanced:[{torch:e}]}),a(e),!0}catch{return r(!1),a(!1),!1}},[t]);return{supported:n,on:i,set:o,toggle:(0,e.useCallback)(()=>o(!i),[o,i])}}exports.useTorch=t;
|
|
2
|
+
//# sourceMappingURL=use-torch.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-torch.cjs","names":[],"sources":["../../src/capture/use-torch.ts"],"sourcesContent":["import { useCallback, useEffect, useState } from \"react\";\n\n/**\n * `torch` is a real constrainable property in the Media Capture spec, but\n * TypeScript's `MediaTrackConstraintSet` does not list it, so the literal has to be\n * widened before `applyConstraints` will take it.\n */\ntype TorchConstraints = MediaTrackConstraints & {\n advanced?: Array<MediaTrackConstraintSet & { torch?: boolean }>;\n};\n\n/** `getCapabilities()` reports `torch` as a list of the values the lamp accepts. */\ntype TorchCapabilities = MediaTrackCapabilities & { torch?: readonly boolean[] };\n\n/** Value returned by {@link useTorch}. */\nexport interface UseTorchResult {\n /** Whether this track has a controllable lamp. `false` on every desktop webcam. */\n supported: boolean;\n /** Whether the lamp is on, as far as this hook knows. */\n on: boolean;\n /**\n * Turn the lamp on or off.\n *\n * @param next - `true` to light it up.\n * @returns `false` when the track refused — treat that as \"no torch\".\n */\n set: (next: boolean) => Promise<boolean>;\n /** Flip it. Same return contract as {@link UseTorchResult.set}. */\n toggle: () => Promise<boolean>;\n}\n\n/**\n * Drive the camera's LED torch on the video track of a stream.\n *\n * The lamp is not a device you can open — it is a **constraint on a live video\n * track**, so there is nothing to control until a camera stream exists, and it\n * disappears when that stream is released. That is also why `supported` can only be\n * answered after the track is live: the same code is `true` on an Android rear camera\n * and `false` on the front one of the same phone.\n *\n * Capability detection prefers `getCapabilities()` and falls back to\n * `getSettings()`, because Firefox implements neither the torch nor\n * `getCapabilities()` and Safari reports the setting without the capability. When\n * neither mentions `torch`, the hook reports `supported: false` instead of offering a\n * button that silently does nothing.\n *\n * @param stream - A live camera stream, or `null` before permission lands.\n * @returns Whether a lamp exists, its state, and setters.\n *\n * @example\n * const camera = useBarcodeScanner();\n * {camera.torch.supported && (\n * <button onClick={() => void camera.torch.toggle()}>Lanterna</button>\n * )}\n */\nexport function useTorch(stream: MediaStream | null): UseTorchResult {\n const [supported, setSupported] = useState(false);\n const [on, setOn] = useState(false);\n\n useEffect(() => {\n const track = stream?.getVideoTracks()[0] ?? null;\n if (!track) {\n setSupported(false);\n setOn(false);\n return;\n }\n const capabilities = (track.getCapabilities?.() ?? {}) as TorchCapabilities;\n const settings = track.getSettings();\n setSupported(capabilities.torch !== undefined || settings.torch !== undefined);\n setOn(settings.torch === true);\n }, [stream]);\n\n const set = useCallback(\n async (next: boolean): Promise<boolean> => {\n const track = stream?.getVideoTracks()[0] ?? null;\n if (!track) return false;\n try {\n await track.applyConstraints({\n advanced: [{ torch: next }],\n } as TorchConstraints);\n setOn(next);\n return true;\n } catch {\n // A track without a lamp rejects with `OverconstrainedError`. There is\n // nothing for the user to fix, and the honest report is \"no torch\".\n setSupported(false);\n setOn(false);\n return false;\n }\n },\n [stream],\n );\n\n const toggle = useCallback((): Promise<boolean> => set(!on), [set, on]);\n\n return { supported, on, set, toggle };\n}\n"],"mappings":"uBAuDA,SAAgB,EAAS,EAA4C,CACjE,GAAM,CAAC,EAAW,IAAA,EAAA,EAAA,SAAA,CAAyB,EAAK,EAC1C,CAAC,EAAI,IAAA,EAAA,EAAA,SAAA,CAAkB,EAAK,GAElC,EAAA,EAAA,UAAA,KAAgB,CACZ,IAAM,EAAQ,GAAQ,eAAe,CAAC,CAAC,IAAM,KAC7C,GAAI,CAAC,EAAO,CACR,EAAa,EAAK,EAClB,EAAM,EAAK,EACX,MACJ,CACA,IAAM,EAAgB,EAAM,kBAAkB,GAAK,CAAC,EAC9C,EAAW,EAAM,YAAY,EACnC,EAAa,EAAa,QAAU,IAAA,IAAa,EAAS,QAAU,IAAA,EAAS,EAC7E,EAAM,EAAS,QAAU,EAAI,CACjC,EAAG,CAAC,CAAM,CAAC,EAEX,IAAM,GAAA,EAAA,EAAA,YAAA,CACF,KAAO,IAAoC,CACvC,IAAM,EAAQ,GAAQ,eAAe,CAAC,CAAC,IAAM,KAC7C,GAAI,CAAC,EAAO,MAAO,GACnB,GAAI,CAKA,OAJA,MAAM,EAAM,iBAAiB,CACzB,SAAU,CAAC,CAAE,MAAO,CAAK,CAAC,CAC9B,CAAqB,EACrB,EAAM,CAAI,EACH,EACX,MAAQ,CAKJ,OAFA,EAAa,EAAK,EAClB,EAAM,EAAK,EACJ,EACX,CACJ,EACA,CAAC,CAAM,CACX,EAIA,MAAO,CAAE,YAAW,KAAI,MAAK,QAAA,EAAA,EAAA,YAAA,KAFsB,EAAI,CAAC,CAAE,EAAG,CAAC,EAAK,CAAE,CAExC,CAAO,CACxC"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { useCallback as e, useEffect as t, useState as n } from "react";
|
|
2
|
+
//#region src/capture/use-torch.ts
|
|
3
|
+
function r(r) {
|
|
4
|
+
let [i, a] = n(!1), [o, s] = n(!1);
|
|
5
|
+
t(() => {
|
|
6
|
+
let e = r?.getVideoTracks()[0] ?? null;
|
|
7
|
+
if (!e) {
|
|
8
|
+
a(!1), s(!1);
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
let t = e.getCapabilities?.() ?? {}, n = e.getSettings();
|
|
12
|
+
a(t.torch !== void 0 || n.torch !== void 0), s(n.torch === !0);
|
|
13
|
+
}, [r]);
|
|
14
|
+
let c = e(async (e) => {
|
|
15
|
+
let t = r?.getVideoTracks()[0] ?? null;
|
|
16
|
+
if (!t) return !1;
|
|
17
|
+
try {
|
|
18
|
+
return await t.applyConstraints({ advanced: [{ torch: e }] }), s(e), !0;
|
|
19
|
+
} catch {
|
|
20
|
+
return a(!1), s(!1), !1;
|
|
21
|
+
}
|
|
22
|
+
}, [r]);
|
|
23
|
+
return {
|
|
24
|
+
supported: i,
|
|
25
|
+
on: o,
|
|
26
|
+
set: c,
|
|
27
|
+
toggle: e(() => c(!o), [c, o])
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
//#endregion
|
|
31
|
+
export { r as useTorch };
|
|
32
|
+
|
|
33
|
+
//# sourceMappingURL=use-torch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-torch.js","names":[],"sources":["../../src/capture/use-torch.ts"],"sourcesContent":["import { useCallback, useEffect, useState } from \"react\";\n\n/**\n * `torch` is a real constrainable property in the Media Capture spec, but\n * TypeScript's `MediaTrackConstraintSet` does not list it, so the literal has to be\n * widened before `applyConstraints` will take it.\n */\ntype TorchConstraints = MediaTrackConstraints & {\n advanced?: Array<MediaTrackConstraintSet & { torch?: boolean }>;\n};\n\n/** `getCapabilities()` reports `torch` as a list of the values the lamp accepts. */\ntype TorchCapabilities = MediaTrackCapabilities & { torch?: readonly boolean[] };\n\n/** Value returned by {@link useTorch}. */\nexport interface UseTorchResult {\n /** Whether this track has a controllable lamp. `false` on every desktop webcam. */\n supported: boolean;\n /** Whether the lamp is on, as far as this hook knows. */\n on: boolean;\n /**\n * Turn the lamp on or off.\n *\n * @param next - `true` to light it up.\n * @returns `false` when the track refused — treat that as \"no torch\".\n */\n set: (next: boolean) => Promise<boolean>;\n /** Flip it. Same return contract as {@link UseTorchResult.set}. */\n toggle: () => Promise<boolean>;\n}\n\n/**\n * Drive the camera's LED torch on the video track of a stream.\n *\n * The lamp is not a device you can open — it is a **constraint on a live video\n * track**, so there is nothing to control until a camera stream exists, and it\n * disappears when that stream is released. That is also why `supported` can only be\n * answered after the track is live: the same code is `true` on an Android rear camera\n * and `false` on the front one of the same phone.\n *\n * Capability detection prefers `getCapabilities()` and falls back to\n * `getSettings()`, because Firefox implements neither the torch nor\n * `getCapabilities()` and Safari reports the setting without the capability. When\n * neither mentions `torch`, the hook reports `supported: false` instead of offering a\n * button that silently does nothing.\n *\n * @param stream - A live camera stream, or `null` before permission lands.\n * @returns Whether a lamp exists, its state, and setters.\n *\n * @example\n * const camera = useBarcodeScanner();\n * {camera.torch.supported && (\n * <button onClick={() => void camera.torch.toggle()}>Lanterna</button>\n * )}\n */\nexport function useTorch(stream: MediaStream | null): UseTorchResult {\n const [supported, setSupported] = useState(false);\n const [on, setOn] = useState(false);\n\n useEffect(() => {\n const track = stream?.getVideoTracks()[0] ?? null;\n if (!track) {\n setSupported(false);\n setOn(false);\n return;\n }\n const capabilities = (track.getCapabilities?.() ?? {}) as TorchCapabilities;\n const settings = track.getSettings();\n setSupported(capabilities.torch !== undefined || settings.torch !== undefined);\n setOn(settings.torch === true);\n }, [stream]);\n\n const set = useCallback(\n async (next: boolean): Promise<boolean> => {\n const track = stream?.getVideoTracks()[0] ?? null;\n if (!track) return false;\n try {\n await track.applyConstraints({\n advanced: [{ torch: next }],\n } as TorchConstraints);\n setOn(next);\n return true;\n } catch {\n // A track without a lamp rejects with `OverconstrainedError`. There is\n // nothing for the user to fix, and the honest report is \"no torch\".\n setSupported(false);\n setOn(false);\n return false;\n }\n },\n [stream],\n );\n\n const toggle = useCallback((): Promise<boolean> => set(!on), [set, on]);\n\n return { supported, on, set, toggle };\n}\n"],"mappings":";;AAuDA,SAAgB,EAAS,GAA4C;CACjE,IAAM,CAAC,GAAW,KAAgB,EAAS,EAAK,GAC1C,CAAC,GAAI,KAAS,EAAS,EAAK;CAElC,QAAgB;EACZ,IAAM,IAAQ,GAAQ,eAAe,CAAC,CAAC,MAAM;EAC7C,IAAI,CAAC,GAAO;GAER,AADA,EAAa,EAAK,GAClB,EAAM,EAAK;GACX;EACJ;EACA,IAAM,IAAgB,EAAM,kBAAkB,KAAK,CAAC,GAC9C,IAAW,EAAM,YAAY;EAEnC,AADA,EAAa,EAAa,UAAU,KAAA,KAAa,EAAS,UAAU,KAAA,CAAS,GAC7E,EAAM,EAAS,UAAU,EAAI;CACjC,GAAG,CAAC,CAAM,CAAC;CAEX,IAAM,IAAM,EACR,OAAO,MAAoC;EACvC,IAAM,IAAQ,GAAQ,eAAe,CAAC,CAAC,MAAM;EAC7C,IAAI,CAAC,GAAO,OAAO;EACnB,IAAI;GAKA,OAJA,MAAM,EAAM,iBAAiB,EACzB,UAAU,CAAC,EAAE,OAAO,EAAK,CAAC,EAC9B,CAAqB,GACrB,EAAM,CAAI,GACH;EACX,QAAQ;GAKJ,OAFA,EAAa,EAAK,GAClB,EAAM,EAAK,GACJ;EACX;CACJ,GACA,CAAC,CAAM,CACX;CAIA,OAAO;EAAE;EAAW;EAAI;EAAK,QAFd,QAAoC,EAAI,CAAC,CAAE,GAAG,CAAC,GAAK,CAAE,CAExC;CAAO;AACxC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../hooks/use-stable-callback.cjs"),t=require("./video-recorder.cjs");let n=require("react");function r(r,i={}){let{maxDurationMs:a,onRecorded:o,onChunk:s,onError:c,mimeType:l,videoBitsPerSecond:u,audioBitsPerSecond:d,timesliceMs:f,tickMs:p=250}=i,[m,h]=(0,n.useState)(`idle`),[g,_]=(0,n.useState)(0),[v,y]=(0,n.useState)(null),[b,x]=(0,n.useState)(null),[S,C]=(0,n.useState)(!1),w=(0,n.useRef)(null),T=e.useStableCallback(e=>o?.(e)),E=e.useStableCallback(e=>s?.(e)),D=e.useStableCallback(e=>{x(e),c?.(e)});(0,n.useEffect)(()=>{if(!r){C(!1);return}let e;try{e=t.createVideoRecorder(r,{mimeType:l,videoBitsPerSecond:u,audioBitsPerSecond:d,timesliceMs:f,onChunk:E,onError:D})}catch(e){x(e),C(!1);return}return w.current=e,C(!0),h(`idle`),()=>{(e.status()===`recording`||e.status()===`paused`)&&e.cancel(),w.current=null,C(!1)}},[r,l,u,d,f,E,D]);let O=(0,n.useCallback)(async()=>{let e=w.current;if(!e)return null;let t=e.status();if(t!==`recording`&&t!==`paused`)return null;let n=await e.stop();return h(`stopped`),_(n.durationMs),y(n),T(n),n},[T]);return(0,n.useEffect)(()=>{if(m!==`recording`&&m!==`paused`)return;let e=setInterval(()=>{let e=w.current;if(!e)return;let t=e.durationMs();_(t),a!==void 0&&t>=a&&O()},p);return()=>clearInterval(e)},[m,p,a,O]),{status:m,durationMs:g,recording:v,error:b,ready:S,start:(0,n.useCallback)(()=>{let e=w.current;e&&(y(null),x(null),_(0),e.start(),h(e.status()))},[]),pause:(0,n.useCallback)(()=>{let e=w.current;e&&(e.pause(),_(e.durationMs()),h(e.status()))},[]),resume:(0,n.useCallback)(()=>{let e=w.current;e&&(e.resume(),h(e.status()))},[]),stop:O,cancel:(0,n.useCallback)(()=>{let e=w.current;e&&(e.cancel(),h(`idle`),_(0),y(null))},[])}}exports.useVideoRecorder=r;
|
|
2
|
+
//# sourceMappingURL=use-video-recorder.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-video-recorder.cjs","names":[],"sources":["../../src/capture/use-video-recorder.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { useStableCallback } from \"@/hooks/use-stable-callback\";\n\nimport type { MediaRecorderHandle, MediaRecorderStatus } from \"./media-recorder\";\nimport {\n createVideoRecorder,\n type VideoRecorderOptions,\n type VideoRecording,\n} from \"./video-recorder\";\n\n/** Options for {@link useVideoRecorder}. */\nexport interface UseVideoRecorderOptions extends VideoRecorderOptions {\n /**\n * Stop automatically after this many milliseconds.\n *\n * Worth setting on anything user-facing, and more so than for audio: a minute of\n * 1080p at 2.5 Mbps is roughly 19 MB, so a recording left running by accident\n * fills memory an order of magnitude faster than a voice note does.\n */\n maxDurationMs?: number;\n /** Called once the recording is assembled, whether by `stop()` or `maxDurationMs`. */\n onRecorded?: (recording: VideoRecording) => void;\n /** How often the clock is published, in ms. Default 250. */\n tickMs?: number;\n}\n\n/** Value returned by {@link useVideoRecorder}. */\nexport interface UseVideoRecorderResult {\n status: MediaRecorderStatus;\n /** Recorded length so far, excluding paused time. */\n durationMs: number;\n /** The finished recording, or `null` before the first `stop()`. */\n recording: VideoRecording | null;\n /** Recorder-level error (encoder failure, share revoked mid-recording). */\n error: unknown;\n /** `false` when there is no stream yet, or the browser cannot record video. */\n ready: boolean;\n start: () => void;\n pause: () => void;\n resume: () => void;\n /** Stop and resolve with the recording. Also published on `recording`. */\n stop: () => Promise<VideoRecording | null>;\n /** Stop and throw the video away. */\n cancel: () => void;\n}\n\n/**\n * Record a video stream — from {@link useScreenCapture}, from a camera, or from a\n * canvas.\n *\n * Pass the stream in; the hook stays `ready: false` until there is one, so a page can\n * render the whole recorder UI before the user has picked a screen and simply have it\n * disabled.\n *\n * There is no level meter here, which is the one real difference from\n * `useAudioRecorder`: metering a screen share means opening an `AudioContext` on a\n * stream that usually has no audio track at all, and browsers cap the number of live\n * contexts. If you are recording a camera **and** want a level, run\n * `createLevelMeter` on the same stream yourself.\n *\n * The clock is published every `tickMs` (default 250 ms) rather than per frame: a\n * video recording UI shows `0:07`, and a hook that re-rendered its parent 60 times a\n * second to move a one-second counter would be the most expensive thing on the page.\n *\n * @param stream - The stream to record, or `null` while the picker is open.\n * @param options - See {@link UseVideoRecorderOptions}.\n *\n * @example\n * const screen = useScreenCapture();\n * const rec = useVideoRecorder(screen.stream, { maxDurationMs: 120_000 });\n * <button disabled={!rec.ready} onClick={rec.start}>Gravar tela</button>\n */\nexport function useVideoRecorder(\n stream: MediaStream | null,\n options: UseVideoRecorderOptions = {},\n): UseVideoRecorderResult {\n const {\n maxDurationMs,\n onRecorded,\n onChunk,\n onError,\n mimeType,\n videoBitsPerSecond,\n audioBitsPerSecond,\n timesliceMs,\n tickMs = 250,\n } = options;\n\n const [status, setStatus] = useState<MediaRecorderStatus>(\"idle\");\n const [durationMs, setDurationMs] = useState(0);\n const [recording, setRecording] = useState<VideoRecording | null>(null);\n const [error, setError] = useState<unknown>(null);\n const [ready, setReady] = useState(false);\n\n const recorderRef = useRef<MediaRecorderHandle | null>(null);\n\n const emitRecorded = useStableCallback((result: VideoRecording) => onRecorded?.(result));\n const emitChunk = useStableCallback((chunk: Blob) => onChunk?.(chunk));\n const emitError = useStableCallback((err: unknown) => {\n setError(err);\n onError?.(err);\n });\n\n /**\n * Build the recorder for a stream, and tear it down when the stream changes.\n *\n * Rebuilt per stream because `MediaRecorder` is bound to the stream it was\n * constructed with: a user who stops sharing and picks a different window hands us\n * a new `MediaStream`, and reusing the old recorder would keep recording a surface\n * that no longer exists. Same reason for a container or bitrate change — both are\n * constructor arguments.\n */\n useEffect(() => {\n if (!stream) {\n setReady(false);\n return;\n }\n let recorder: MediaRecorderHandle;\n try {\n recorder = createVideoRecorder(stream, {\n mimeType,\n videoBitsPerSecond,\n audioBitsPerSecond,\n timesliceMs,\n onChunk: emitChunk,\n onError: emitError,\n });\n } catch (err) {\n setError(err);\n setReady(false);\n return;\n }\n recorderRef.current = recorder;\n setReady(true);\n setStatus(\"idle\");\n\n return () => {\n if (recorder.status() === \"recording\" || recorder.status() === \"paused\") {\n recorder.cancel();\n }\n recorderRef.current = null;\n setReady(false);\n };\n }, [\n stream,\n mimeType,\n videoBitsPerSecond,\n audioBitsPerSecond,\n timesliceMs,\n emitChunk,\n emitError,\n ]);\n\n const stop = useCallback(async (): Promise<VideoRecording | null> => {\n const recorder = recorderRef.current;\n if (!recorder) return null;\n const current = recorder.status();\n if (current !== \"recording\" && current !== \"paused\") return null;\n const result = await recorder.stop();\n setStatus(\"stopped\");\n setDurationMs(result.durationMs);\n setRecording(result);\n emitRecorded(result);\n return result;\n }, [emitRecorded]);\n\n /**\n * Publish the clock while something is running, and enforce `maxDurationMs`.\n *\n * The cap is checked on the same tick rather than with a `setTimeout` armed at\n * `start()`, because a paused recording must not keep counting toward it — a\n * timeout would fire while the user is paused on a slide.\n */\n useEffect(() => {\n if (status !== \"recording\" && status !== \"paused\") return;\n const id = setInterval(() => {\n const recorder = recorderRef.current;\n if (!recorder) return;\n const elapsed = recorder.durationMs();\n setDurationMs(elapsed);\n if (maxDurationMs !== undefined && elapsed >= maxDurationMs) void stop();\n }, tickMs);\n return () => clearInterval(id);\n }, [status, tickMs, maxDurationMs, stop]);\n\n const start = useCallback((): void => {\n const recorder = recorderRef.current;\n if (!recorder) return;\n setRecording(null);\n setError(null);\n setDurationMs(0);\n recorder.start();\n setStatus(recorder.status());\n }, []);\n\n const pause = useCallback((): void => {\n const recorder = recorderRef.current;\n if (!recorder) return;\n recorder.pause();\n setDurationMs(recorder.durationMs());\n setStatus(recorder.status());\n }, []);\n\n const resume = useCallback((): void => {\n const recorder = recorderRef.current;\n if (!recorder) return;\n recorder.resume();\n setStatus(recorder.status());\n }, []);\n\n const cancel = useCallback((): void => {\n const recorder = recorderRef.current;\n if (!recorder) return;\n recorder.cancel();\n setStatus(\"idle\");\n setDurationMs(0);\n setRecording(null);\n }, []);\n\n return { status, durationMs, recording, error, ready, start, pause, resume, stop, cancel };\n}\n"],"mappings":"6GAyEA,SAAgB,EACZ,EACA,EAAmC,CAAC,EACd,CACtB,GAAM,CACF,gBACA,aACA,UACA,UACA,WACA,qBACA,qBACA,cACA,SAAS,KACT,EAEE,CAAC,EAAQ,IAAA,EAAA,EAAA,SAAA,CAA2C,MAAM,EAC1D,CAAC,EAAY,IAAA,EAAA,EAAA,SAAA,CAA0B,CAAC,EACxC,CAAC,EAAW,IAAA,EAAA,EAAA,SAAA,CAAgD,IAAI,EAChE,CAAC,EAAO,IAAA,EAAA,EAAA,SAAA,CAA8B,IAAI,EAC1C,CAAC,EAAO,IAAA,EAAA,EAAA,SAAA,CAAqB,EAAK,EAElC,GAAA,EAAA,EAAA,OAAA,CAAiD,IAAI,EAErD,EAAe,EAAA,kBAAmB,GAA2B,IAAa,CAAM,CAAC,EACjF,EAAY,EAAA,kBAAmB,GAAgB,IAAU,CAAK,CAAC,EAC/D,EAAY,EAAA,kBAAmB,GAAiB,CAClD,EAAS,CAAG,EACZ,IAAU,CAAG,CACjB,CAAC,GAWD,EAAA,EAAA,UAAA,KAAgB,CACZ,GAAI,CAAC,EAAQ,CACT,EAAS,EAAK,EACd,MACJ,CACA,IAAI,EACJ,GAAI,CACA,EAAW,EAAA,oBAAoB,EAAQ,CACnC,WACA,qBACA,qBACA,cACA,QAAS,EACT,QAAS,CACb,CAAC,CACL,OAAS,EAAK,CACV,EAAS,CAAG,EACZ,EAAS,E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AAM,EACf,EAAc,EAAS,WAAW,CAAC,EACnC,EAAU,EAAS,OAAO,CAAC,EAC/B,EAAG,CAAC,CAkByD,EAAO,QAAA,EAAA,EAAA,YAAA,KAhB7B,CACnC,IAAM,EAAW,EAAY,QACxB,IACL,EAAS,OAAO,EAChB,EAAU,EAAS,OAAO,CAAC,EAC/B,EAAG,CAAC,CAWgE,EAAQ,OAAM,QAAA,EAAA,EAAA,YAAA,KAT3C,CACnC,IAAM,EAAW,EAAY,QACxB,IACL,EAAS,OAAO,EAChB,EAAU,MAAM,EAChB,EAAc,CAAC,EACf,EAAa,IAAI,EACrB,EAAG,CAAC,CAE8E,CAAO,CAC7F"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { useStableCallback as e } from "../hooks/use-stable-callback.js";
|
|
2
|
+
import { createVideoRecorder as t } from "./video-recorder.js";
|
|
3
|
+
import { useCallback as n, useEffect as r, useRef as i, useState as a } from "react";
|
|
4
|
+
//#region src/capture/use-video-recorder.ts
|
|
5
|
+
function o(o, s = {}) {
|
|
6
|
+
let { maxDurationMs: c, onRecorded: l, onChunk: u, onError: d, mimeType: f, videoBitsPerSecond: p, audioBitsPerSecond: m, timesliceMs: h, tickMs: g = 250 } = s, [_, v] = a("idle"), [y, b] = a(0), [x, S] = a(null), [C, w] = a(null), [T, E] = a(!1), D = i(null), O = e((e) => l?.(e)), k = e((e) => u?.(e)), A = e((e) => {
|
|
7
|
+
w(e), d?.(e);
|
|
8
|
+
});
|
|
9
|
+
r(() => {
|
|
10
|
+
if (!o) {
|
|
11
|
+
E(!1);
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
let e;
|
|
15
|
+
try {
|
|
16
|
+
e = t(o, {
|
|
17
|
+
mimeType: f,
|
|
18
|
+
videoBitsPerSecond: p,
|
|
19
|
+
audioBitsPerSecond: m,
|
|
20
|
+
timesliceMs: h,
|
|
21
|
+
onChunk: k,
|
|
22
|
+
onError: A
|
|
23
|
+
});
|
|
24
|
+
} catch (e) {
|
|
25
|
+
w(e), E(!1);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
return D.current = e, E(!0), v("idle"), () => {
|
|
29
|
+
(e.status() === "recording" || e.status() === "paused") && e.cancel(), D.current = null, E(!1);
|
|
30
|
+
};
|
|
31
|
+
}, [
|
|
32
|
+
o,
|
|
33
|
+
f,
|
|
34
|
+
p,
|
|
35
|
+
m,
|
|
36
|
+
h,
|
|
37
|
+
k,
|
|
38
|
+
A
|
|
39
|
+
]);
|
|
40
|
+
let j = n(async () => {
|
|
41
|
+
let e = D.current;
|
|
42
|
+
if (!e) return null;
|
|
43
|
+
let t = e.status();
|
|
44
|
+
if (t !== "recording" && t !== "paused") return null;
|
|
45
|
+
let n = await e.stop();
|
|
46
|
+
return v("stopped"), b(n.durationMs), S(n), O(n), n;
|
|
47
|
+
}, [O]);
|
|
48
|
+
return r(() => {
|
|
49
|
+
if (_ !== "recording" && _ !== "paused") return;
|
|
50
|
+
let e = setInterval(() => {
|
|
51
|
+
let e = D.current;
|
|
52
|
+
if (!e) return;
|
|
53
|
+
let t = e.durationMs();
|
|
54
|
+
b(t), c !== void 0 && t >= c && j();
|
|
55
|
+
}, g);
|
|
56
|
+
return () => clearInterval(e);
|
|
57
|
+
}, [
|
|
58
|
+
_,
|
|
59
|
+
g,
|
|
60
|
+
c,
|
|
61
|
+
j
|
|
62
|
+
]), {
|
|
63
|
+
status: _,
|
|
64
|
+
durationMs: y,
|
|
65
|
+
recording: x,
|
|
66
|
+
error: C,
|
|
67
|
+
ready: T,
|
|
68
|
+
start: n(() => {
|
|
69
|
+
let e = D.current;
|
|
70
|
+
e && (S(null), w(null), b(0), e.start(), v(e.status()));
|
|
71
|
+
}, []),
|
|
72
|
+
pause: n(() => {
|
|
73
|
+
let e = D.current;
|
|
74
|
+
e && (e.pause(), b(e.durationMs()), v(e.status()));
|
|
75
|
+
}, []),
|
|
76
|
+
resume: n(() => {
|
|
77
|
+
let e = D.current;
|
|
78
|
+
e && (e.resume(), v(e.status()));
|
|
79
|
+
}, []),
|
|
80
|
+
stop: j,
|
|
81
|
+
cancel: n(() => {
|
|
82
|
+
let e = D.current;
|
|
83
|
+
e && (e.cancel(), v("idle"), b(0), S(null));
|
|
84
|
+
}, [])
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
//#endregion
|
|
88
|
+
export { o as useVideoRecorder };
|
|
89
|
+
|
|
90
|
+
//# sourceMappingURL=use-video-recorder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-video-recorder.js","names":[],"sources":["../../src/capture/use-video-recorder.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { useStableCallback } from \"@/hooks/use-stable-callback\";\n\nimport type { MediaRecorderHandle, MediaRecorderStatus } from \"./media-recorder\";\nimport {\n createVideoRecorder,\n type VideoRecorderOptions,\n type VideoRecording,\n} from \"./video-recorder\";\n\n/** Options for {@link useVideoRecorder}. */\nexport interface UseVideoRecorderOptions extends VideoRecorderOptions {\n /**\n * Stop automatically after this many milliseconds.\n *\n * Worth setting on anything user-facing, and more so than for audio: a minute of\n * 1080p at 2.5 Mbps is roughly 19 MB, so a recording left running by accident\n * fills memory an order of magnitude faster than a voice note does.\n */\n maxDurationMs?: number;\n /** Called once the recording is assembled, whether by `stop()` or `maxDurationMs`. */\n onRecorded?: (recording: VideoRecording) => void;\n /** How often the clock is published, in ms. Default 250. */\n tickMs?: number;\n}\n\n/** Value returned by {@link useVideoRecorder}. */\nexport interface UseVideoRecorderResult {\n status: MediaRecorderStatus;\n /** Recorded length so far, excluding paused time. */\n durationMs: number;\n /** The finished recording, or `null` before the first `stop()`. */\n recording: VideoRecording | null;\n /** Recorder-level error (encoder failure, share revoked mid-recording). */\n error: unknown;\n /** `false` when there is no stream yet, or the browser cannot record video. */\n ready: boolean;\n start: () => void;\n pause: () => void;\n resume: () => void;\n /** Stop and resolve with the recording. Also published on `recording`. */\n stop: () => Promise<VideoRecording | null>;\n /** Stop and throw the video away. */\n cancel: () => void;\n}\n\n/**\n * Record a video stream — from {@link useScreenCapture}, from a camera, or from a\n * canvas.\n *\n * Pass the stream in; the hook stays `ready: false` until there is one, so a page can\n * render the whole recorder UI before the user has picked a screen and simply have it\n * disabled.\n *\n * There is no level meter here, which is the one real difference from\n * `useAudioRecorder`: metering a screen share means opening an `AudioContext` on a\n * stream that usually has no audio track at all, and browsers cap the number of live\n * contexts. If you are recording a camera **and** want a level, run\n * `createLevelMeter` on the same stream yourself.\n *\n * The clock is published every `tickMs` (default 250 ms) rather than per frame: a\n * video recording UI shows `0:07`, and a hook that re-rendered its parent 60 times a\n * second to move a one-second counter would be the most expensive thing on the page.\n *\n * @param stream - The stream to record, or `null` while the picker is open.\n * @param options - See {@link UseVideoRecorderOptions}.\n *\n * @example\n * const screen = useScreenCapture();\n * const rec = useVideoRecorder(screen.stream, { maxDurationMs: 120_000 });\n * <button disabled={!rec.ready} onClick={rec.start}>Gravar tela</button>\n */\nexport function useVideoRecorder(\n stream: MediaStream | null,\n options: UseVideoRecorderOptions = {},\n): UseVideoRecorderResult {\n const {\n maxDurationMs,\n onRecorded,\n onChunk,\n onError,\n mimeType,\n videoBitsPerSecond,\n audioBitsPerSecond,\n timesliceMs,\n tickMs = 250,\n } = options;\n\n const [status, setStatus] = useState<MediaRecorderStatus>(\"idle\");\n const [durationMs, setDurationMs] = useState(0);\n const [recording, setRecording] = useState<VideoRecording | null>(null);\n const [error, setError] = useState<unknown>(null);\n const [ready, setReady] = useState(false);\n\n const recorderRef = useRef<MediaRecorderHandle | null>(null);\n\n const emitRecorded = useStableCallback((result: VideoRecording) => onRecorded?.(result));\n const emitChunk = useStableCallback((chunk: Blob) => onChunk?.(chunk));\n const emitError = useStableCallback((err: unknown) => {\n setError(err);\n onError?.(err);\n });\n\n /**\n * Build the recorder for a stream, and tear it down when the stream changes.\n *\n * Rebuilt per stream because `MediaRecorder` is bound to the stream it was\n * constructed with: a user who stops sharing and picks a different window hands us\n * a new `MediaStream`, and reusing the old recorder would keep recording a surface\n * that no longer exists. Same reason for a container or bitrate change — both are\n * constructor arguments.\n */\n useEffect(() => {\n if (!stream) {\n setReady(false);\n return;\n }\n let recorder: MediaRecorderHandle;\n try {\n recorder = createVideoRecorder(stream, {\n mimeType,\n videoBitsPerSecond,\n audioBitsPerSecond,\n timesliceMs,\n onChunk: emitChunk,\n onError: emitError,\n });\n } catch (err) {\n setError(err);\n setReady(false);\n return;\n }\n recorderRef.current = recorder;\n setReady(true);\n setStatus(\"idle\");\n\n return () => {\n if (recorder.status() === \"recording\" || recorder.status() === \"paused\") {\n recorder.cancel();\n }\n recorderRef.current = null;\n setReady(false);\n };\n }, [\n stream,\n mimeType,\n videoBitsPerSecond,\n audioBitsPerSecond,\n timesliceMs,\n emitChunk,\n emitError,\n ]);\n\n const stop = useCallback(async (): Promise<VideoRecording | null> => {\n const recorder = recorderRef.current;\n if (!recorder) return null;\n const current = recorder.status();\n if (current !== \"recording\" && current !== \"paused\") return null;\n const result = await recorder.stop();\n setStatus(\"stopped\");\n setDurationMs(result.durationMs);\n setRecording(result);\n emitRecorded(result);\n return result;\n }, [emitRecorded]);\n\n /**\n * Publish the clock while something is running, and enforce `maxDurationMs`.\n *\n * The cap is checked on the same tick rather than with a `setTimeout` armed at\n * `start()`, because a paused recording must not keep counting toward it — a\n * timeout would fire while the user is paused on a slide.\n */\n useEffect(() => {\n if (status !== \"recording\" && status !== \"paused\") return;\n const id = setInterval(() => {\n const recorder = recorderRef.current;\n if (!recorder) return;\n const elapsed = recorder.durationMs();\n setDurationMs(elapsed);\n if (maxDurationMs !== undefined && elapsed >= maxDurationMs) void stop();\n }, tickMs);\n return () => clearInterval(id);\n }, [status, tickMs, maxDurationMs, stop]);\n\n const start = useCallback((): void => {\n const recorder = recorderRef.current;\n if (!recorder) return;\n setRecording(null);\n setError(null);\n setDurationMs(0);\n recorder.start();\n setStatus(recorder.status());\n }, []);\n\n const pause = useCallback((): void => {\n const recorder = recorderRef.current;\n if (!recorder) return;\n recorder.pause();\n setDurationMs(recorder.durationMs());\n setStatus(recorder.status());\n }, []);\n\n const resume = useCallback((): void => {\n const recorder = recorderRef.current;\n if (!recorder) return;\n recorder.resume();\n setStatus(recorder.status());\n }, []);\n\n const cancel = useCallback((): void => {\n const recorder = recorderRef.current;\n if (!recorder) return;\n recorder.cancel();\n setStatus(\"idle\");\n setDurationMs(0);\n setRecording(null);\n }, []);\n\n return { status, durationMs, recording, error, ready, start, pause, resume, stop, cancel };\n}\n"],"mappings":";;;;AAyEA,SAAgB,EACZ,GACA,IAAmC,CAAC,GACd;CACtB,IAAM,EACF,kBACA,eACA,YACA,YACA,aACA,uBACA,uBACA,gBACA,YAAS,QACT,GAEE,CAAC,GAAQ,KAAa,EAA8B,MAAM,GAC1D,CAAC,GAAY,KAAiB,EAAS,CAAC,GACxC,CAAC,GAAW,KAAgB,EAAgC,IAAI,GAChE,CAAC,GAAO,KAAY,EAAkB,IAAI,GAC1C,CAAC,GAAO,KAAY,EAAS,EAAK,GAElC,IAAc,EAAmC,IAAI,GAErD,IAAe,GAAmB,MAA2B,IAAa,CAAM,CAAC,GACjF,IAAY,GAAmB,MAAgB,IAAU,CAAK,CAAC,GAC/D,IAAY,GAAmB,MAAiB;EAElD,AADA,EAAS,CAAG,GACZ,IAAU,CAAG;CACjB,CAAC;CAWD,QAAgB;EACZ,IAAI,CAAC,GAAQ;GACT,EAAS,EAAK;GACd;EACJ;EACA,IAAI;EACJ,IAAI;GACA,IAAW,EAAoB,GAAQ;IACnC;IACA;IACA;IACA;IACA,SAAS;IACT,SAAS;GACb,CAAC;EACL,SAAS,GAAK;GAEV,AADA,EAAS,CAAG,GACZ,EAAS,EAAK;GACd;EACJ;EAKA,OAJA,EAAY,UAAU,GACtB,EAAS,EAAI,GACb,EAAU,MAAM,SAEH;GAKT,CAJI,EAAS,OAAO,MAAM,eAAe,EAAS,OAAO,MAAM,aAC3D,EAAS,OAAO,GAEpB,EAAY,UAAU,MACtB,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AAwB;GACnC,IAAM,IAAW,EAAY;GACxB,MACL,EAAS,OAAO,GAChB,EAAU,MAAM,GAChB,EAAc,CAAC,GACf,EAAa,IAAI;EACrB,GAAG,CAAC,CAE8E;CAAO;AAC7F"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./media-recorder.cjs");var t=[`video/webm;codecs=vp9,opus`,`video/webm;codecs=vp8,opus`,`video/webm`,`video/mp4;codecs=avc1.42E01E,mp4a.40.2`,`video/mp4`];function n(){return typeof MediaRecorder<`u`&&r()!==null}function r(n=t){return e.pickRecordingMimeType(n)}function i(n,r={}){return e.createMediaRecorder(n,{candidates:t,kind:`video`,mimeType:r.mimeType,videoBitsPerSecond:r.videoBitsPerSecond,audioBitsPerSecond:r.audioBitsPerSecond,timesliceMs:r.timesliceMs,onChunk:r.onChunk,onError:r.onError})}exports.VIDEO_MIME_CANDIDATES=t,exports.createVideoRecorder=i,exports.isVideoRecordingSupported=n,exports.pickVideoMimeType=r;
|
|
2
|
+
//# sourceMappingURL=video-recorder.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"video-recorder.cjs","names":[],"sources":["../../src/capture/video-recorder.ts"],"sourcesContent":["import {\n createMediaRecorder,\n pickRecordingMimeType,\n type MediaRecorderHandle,\n type MediaRecording,\n} from \"./media-recorder\";\n\n/**\n * Container/codec candidates for video, best first.\n *\n * VP9 in WebM leads because it is the best quality per byte that Chromium and Firefox\n * both encode natively; VP8 is the fallback for older Chromium and for hardware that\n * refuses VP9. `video/mp4` is last and exists for Safari, which produces H.264 in MP4\n * and nothing else — and only since Safari 14.1.\n *\n * Every candidate carries **Opus or AAC audio in the same container**, because a\n * screen recording with the tab's audio dropped is a support ticket, not a\n * simplification. On a stream with no audio track the browser simply omits it.\n *\n * Ported from the intersection of what `MediaRecorder.isTypeSupported` accepts in\n * Chrome 120+, Firefox 115+ and Safari 17. Re-check against\n * <https://developer.mozilla.org/docs/Web/API/MediaRecorder/isTypeSupported> before\n * adding to the list.\n */\nexport const VIDEO_MIME_CANDIDATES: readonly string[] = [\n \"video/webm;codecs=vp9,opus\",\n \"video/webm;codecs=vp8,opus\",\n \"video/webm\",\n \"video/mp4;codecs=avc1.42E01E,mp4a.40.2\",\n \"video/mp4\",\n];\n\n/**\n * A finished video recording.\n *\n * Structurally the same three fields as an audio one — there is nothing\n * video-specific to add, and inventing a `width`/`height` here would be a lie: the\n * browser negotiates the frame size with the device and can change it mid-recording.\n * Read it from the track's `getSettings()` if you need it.\n */\nexport type VideoRecording = MediaRecording;\n\n/** Imperative video recorder. Same shape as the audio one. */\nexport type VideoRecorderHandle = MediaRecorderHandle;\n\n/** Options for {@link createVideoRecorder}. */\nexport interface VideoRecorderOptions {\n /**\n * Force a container. Throws when the browser cannot produce it.\n *\n * Leave it out. The default negotiates from {@link VIDEO_MIME_CANDIDATES}, which\n * is the only way one call site works on both Chromium and Safari.\n */\n mimeType?: string;\n /**\n * Target video bitrate.\n *\n * The browser's default is conservative and a screen recording of text at\n * 1080p looks smeared under it. 2_500_000 is a good floor for a UI capture,\n * 8_000_000 for full-motion camera video.\n */\n videoBitsPerSecond?: number;\n /** Target audio bitrate, when the stream carries audio. 64000–128000 is plenty. */\n audioBitsPerSecond?: number;\n /**\n * Emit a chunk every N ms through `onChunk`, for streaming upload.\n *\n * Worth setting for video far sooner than for audio: a minute of 1080p at\n * 2.5 Mbps is roughly 19 MB sitting in memory.\n */\n timesliceMs?: number;\n /** Receives each chunk when `timesliceMs` is set. Chunks are **not** independently playable. */\n onChunk?: (chunk: Blob) => void;\n /** Recorder-level failure (screen share revoked mid-recording, encoder error). */\n onError?: (error: unknown) => void;\n}\n\n/** Whether `MediaRecorder` exists and can produce at least one video container. */\nexport function isVideoRecordingSupported(): boolean {\n return typeof MediaRecorder !== \"undefined\" && pickVideoMimeType() !== null;\n}\n\n/**\n * First video container in `preferred` the browser can actually produce, or `null`.\n *\n * @param preferred - Candidates, best first. Defaults to {@link VIDEO_MIME_CANDIDATES}.\n * @returns A supported MIME type, or `null` when none is.\n */\nexport function pickVideoMimeType(\n preferred: readonly string[] = VIDEO_MIME_CANDIDATES,\n): string | null {\n return pickRecordingMimeType(preferred);\n}\n\n/**\n * Record a video stream — a camera, a screen share, or a `canvas.captureStream()`.\n *\n * The state machine, the clock that subtracts paused time and the `stop()` that\n * resolves in `onstop` with every chunk in hand are shared with the audio recorder\n * (see `createMediaRecorder`); what this adds is the container list and\n * `videoBitsPerSecond`.\n *\n * The stream is **not** owned here. For a screen share in particular, stopping the\n * recorder must not stop the sharing: a support flow usually records, stops, lets the\n * user look at the result and then records again.\n *\n * @param stream - A live stream carrying at least one video track.\n * @param options - See {@link VideoRecorderOptions}.\n * @returns The imperative recorder.\n * @throws When `MediaRecorder` is unavailable, or an explicit `mimeType` is unsupported.\n *\n * @example\n * const recorder = createVideoRecorder(stream, { videoBitsPerSecond: 2_500_000 });\n * recorder.start();\n * const { blob, durationMs } = await recorder.stop();\n */\nexport function createVideoRecorder(\n stream: MediaStream,\n options: VideoRecorderOptions = {},\n): VideoRecorderHandle {\n return createMediaRecorder(stream, {\n candidates: VIDEO_MIME_CANDIDATES,\n kind: \"video\",\n mimeType: options.mimeType,\n videoBitsPerSecond: options.videoBitsPerSecond,\n audioBitsPerSecond: options.audioBitsPerSecond,\n timesliceMs: options.timesliceMs,\n onChunk: options.onChunk,\n onError: options.onError,\n });\n}\n"],"mappings":"wCAwBA,IAAa,EAA2C,CACpD,6BACA,6BACA,aACA,yCACA,WACJ,EAgDA,SAAgB,GAAqC,CACjD,OAAO,OAAO,cAAkB,KAAe,EAAkB,IAAM,IAC3E,CAQA,SAAgB,EACZ,EAA+B,EAClB,CACb,OAAO,EAAA,sBAAsB,CAAS,CAC1C,CAwBA,SAAgB,EACZ,EACA,EAAgC,CAAC,EACd,CACnB,OAAO,EAAA,oBAAoB,EAAQ,CAC/B,WAAY,EACZ,KAAM,QACN,SAAU,EAAQ,SAClB,mBAAoB,EAAQ,mBAC5B,mBAAoB,EAAQ,mBAC5B,YAAa,EAAQ,YACrB,QAAS,EAAQ,QACjB,QAAS,EAAQ,OACrB,CAAC,CACL"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { createMediaRecorder as e, pickRecordingMimeType as t } from "./media-recorder.js";
|
|
2
|
+
//#region src/capture/video-recorder.ts
|
|
3
|
+
var n = [
|
|
4
|
+
"video/webm;codecs=vp9,opus",
|
|
5
|
+
"video/webm;codecs=vp8,opus",
|
|
6
|
+
"video/webm",
|
|
7
|
+
"video/mp4;codecs=avc1.42E01E,mp4a.40.2",
|
|
8
|
+
"video/mp4"
|
|
9
|
+
];
|
|
10
|
+
function r() {
|
|
11
|
+
return typeof MediaRecorder < "u" && i() !== null;
|
|
12
|
+
}
|
|
13
|
+
function i(e = n) {
|
|
14
|
+
return t(e);
|
|
15
|
+
}
|
|
16
|
+
function a(t, r = {}) {
|
|
17
|
+
return e(t, {
|
|
18
|
+
candidates: n,
|
|
19
|
+
kind: "video",
|
|
20
|
+
mimeType: r.mimeType,
|
|
21
|
+
videoBitsPerSecond: r.videoBitsPerSecond,
|
|
22
|
+
audioBitsPerSecond: r.audioBitsPerSecond,
|
|
23
|
+
timesliceMs: r.timesliceMs,
|
|
24
|
+
onChunk: r.onChunk,
|
|
25
|
+
onError: r.onError
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
export { n as VIDEO_MIME_CANDIDATES, a as createVideoRecorder, r as isVideoRecordingSupported, i as pickVideoMimeType };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=video-recorder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"video-recorder.js","names":[],"sources":["../../src/capture/video-recorder.ts"],"sourcesContent":["import {\n createMediaRecorder,\n pickRecordingMimeType,\n type MediaRecorderHandle,\n type MediaRecording,\n} from \"./media-recorder\";\n\n/**\n * Container/codec candidates for video, best first.\n *\n * VP9 in WebM leads because it is the best quality per byte that Chromium and Firefox\n * both encode natively; VP8 is the fallback for older Chromium and for hardware that\n * refuses VP9. `video/mp4` is last and exists for Safari, which produces H.264 in MP4\n * and nothing else — and only since Safari 14.1.\n *\n * Every candidate carries **Opus or AAC audio in the same container**, because a\n * screen recording with the tab's audio dropped is a support ticket, not a\n * simplification. On a stream with no audio track the browser simply omits it.\n *\n * Ported from the intersection of what `MediaRecorder.isTypeSupported` accepts in\n * Chrome 120+, Firefox 115+ and Safari 17. Re-check against\n * <https://developer.mozilla.org/docs/Web/API/MediaRecorder/isTypeSupported> before\n * adding to the list.\n */\nexport const VIDEO_MIME_CANDIDATES: readonly string[] = [\n \"video/webm;codecs=vp9,opus\",\n \"video/webm;codecs=vp8,opus\",\n \"video/webm\",\n \"video/mp4;codecs=avc1.42E01E,mp4a.40.2\",\n \"video/mp4\",\n];\n\n/**\n * A finished video recording.\n *\n * Structurally the same three fields as an audio one — there is nothing\n * video-specific to add, and inventing a `width`/`height` here would be a lie: the\n * browser negotiates the frame size with the device and can change it mid-recording.\n * Read it from the track's `getSettings()` if you need it.\n */\nexport type VideoRecording = MediaRecording;\n\n/** Imperative video recorder. Same shape as the audio one. */\nexport type VideoRecorderHandle = MediaRecorderHandle;\n\n/** Options for {@link createVideoRecorder}. */\nexport interface VideoRecorderOptions {\n /**\n * Force a container. Throws when the browser cannot produce it.\n *\n * Leave it out. The default negotiates from {@link VIDEO_MIME_CANDIDATES}, which\n * is the only way one call site works on both Chromium and Safari.\n */\n mimeType?: string;\n /**\n * Target video bitrate.\n *\n * The browser's default is conservative and a screen recording of text at\n * 1080p looks smeared under it. 2_500_000 is a good floor for a UI capture,\n * 8_000_000 for full-motion camera video.\n */\n videoBitsPerSecond?: number;\n /** Target audio bitrate, when the stream carries audio. 64000–128000 is plenty. */\n audioBitsPerSecond?: number;\n /**\n * Emit a chunk every N ms through `onChunk`, for streaming upload.\n *\n * Worth setting for video far sooner than for audio: a minute of 1080p at\n * 2.5 Mbps is roughly 19 MB sitting in memory.\n */\n timesliceMs?: number;\n /** Receives each chunk when `timesliceMs` is set. Chunks are **not** independently playable. */\n onChunk?: (chunk: Blob) => void;\n /** Recorder-level failure (screen share revoked mid-recording, encoder error). */\n onError?: (error: unknown) => void;\n}\n\n/** Whether `MediaRecorder` exists and can produce at least one video container. */\nexport function isVideoRecordingSupported(): boolean {\n return typeof MediaRecorder !== \"undefined\" && pickVideoMimeType() !== null;\n}\n\n/**\n * First video container in `preferred` the browser can actually produce, or `null`.\n *\n * @param preferred - Candidates, best first. Defaults to {@link VIDEO_MIME_CANDIDATES}.\n * @returns A supported MIME type, or `null` when none is.\n */\nexport function pickVideoMimeType(\n preferred: readonly string[] = VIDEO_MIME_CANDIDATES,\n): string | null {\n return pickRecordingMimeType(preferred);\n}\n\n/**\n * Record a video stream — a camera, a screen share, or a `canvas.captureStream()`.\n *\n * The state machine, the clock that subtracts paused time and the `stop()` that\n * resolves in `onstop` with every chunk in hand are shared with the audio recorder\n * (see `createMediaRecorder`); what this adds is the container list and\n * `videoBitsPerSecond`.\n *\n * The stream is **not** owned here. For a screen share in particular, stopping the\n * recorder must not stop the sharing: a support flow usually records, stops, lets the\n * user look at the result and then records again.\n *\n * @param stream - A live stream carrying at least one video track.\n * @param options - See {@link VideoRecorderOptions}.\n * @returns The imperative recorder.\n * @throws When `MediaRecorder` is unavailable, or an explicit `mimeType` is unsupported.\n *\n * @example\n * const recorder = createVideoRecorder(stream, { videoBitsPerSecond: 2_500_000 });\n * recorder.start();\n * const { blob, durationMs } = await recorder.stop();\n */\nexport function createVideoRecorder(\n stream: MediaStream,\n options: VideoRecorderOptions = {},\n): VideoRecorderHandle {\n return createMediaRecorder(stream, {\n candidates: VIDEO_MIME_CANDIDATES,\n kind: \"video\",\n mimeType: options.mimeType,\n videoBitsPerSecond: options.videoBitsPerSecond,\n audioBitsPerSecond: options.audioBitsPerSecond,\n timesliceMs: options.timesliceMs,\n onChunk: options.onChunk,\n onError: options.onError,\n });\n}\n"],"mappings":";;AAwBA,IAAa,IAA2C;CACpD;CACA;CACA;CACA;CACA;AACJ;AAgDA,SAAgB,IAAqC;CACjD,OAAO,OAAO,gBAAkB,OAAe,EAAkB,MAAM;AAC3E;AAQA,SAAgB,EACZ,IAA+B,GAClB;CACb,OAAO,EAAsB,CAAS;AAC1C;AAwBA,SAAgB,EACZ,GACA,IAAgC,CAAC,GACd;CACnB,OAAO,EAAoB,GAAQ;EAC/B,YAAY;EACZ,MAAM;EACN,UAAU,EAAQ;EAClB,oBAAoB,EAAQ;EAC5B,oBAAoB,EAAQ;EAC5B,aAAa,EAAQ;EACrB,SAAS,EAAQ;EACjB,SAAS,EAAQ;CACrB,CAAC;AACL"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../../utils/cn.cjs"),t=require("../EmptyState/EmptyState.cjs"),n=require("
|
|
1
|
+
const e=require("../../utils/cn.cjs"),t=require("../EmptyState/EmptyState.cjs"),n=require("../../hooks/use-announce.cjs"),r=require("./ai-chat-turns.cjs"),i=require("./AIChat.module.cjs"),a=require("./AIChatComposer.cjs"),o=require("./AIChatTurn.cjs");let s=require("react"),c=require("react/jsx-runtime"),l=require("lucide-react");var u=48;function d({messages:d,onSend:f,onStop:p,onRegenerate:m,onEditSubmit:h,onFeedback:g,onRetry:_,pending:v=!1,suggestions:y=[],renderAvatar:b,renderContent:x,votes:S,header:C,emptyState:w,showSystem:T=!1,defaultReasoningOpen:E=!1,showLineNumbers:D=!1,locale:O=`pt-BR`,placeholder:k,composerActions:A,composerRef:j,composerFooter:M,composerDisabled:N,maxRows:P,onSendError:F,className:I,...L}){let R=r.aiChatStrings(O),z=r.visibleTurns({messages:d,showSystem:T}),B=v||r.isGenerating(d),V=r.lastAssistantId(d),H=r.tailSignature(d),U=(0,s.useRef)(null),W=(0,s.useRef)(null),G=(0,s.useRef)(!0),K=(0,s.useRef)(!1),[q,J]=(0,s.useState)(!0),Y=n.useAnnounce(),X=()=>{let e=W.current;if(!e)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<u;G.current=t,J(t)},Z=()=>{let e=W.current;e&&(G.current=!0,J(!0),e.scrollTop=e.scrollHeight)};(0,s.useLayoutEffect)(()=>{let e=W.current;!e||!G.current||(e.scrollTop=e.scrollHeight)},[H,v]),(0,s.useEffect)(()=>{let e=W.current;e&&(e.scrollTop=e.scrollHeight)},[]),(0,s.useEffect)(()=>{if(B){Y(R.generating),K.current=!0;return}K.current&&=(Y(R.done),!1)},[B,R.generating,R.done,Y]);let Q=z.length===0&&y.length>0&&f!==void 0,$=!q&&z.length>0;return(0,c.jsxs)(`div`,{className:e.cn(i.default.panel,I),...L,children:[C&&(0,c.jsx)(`header`,{className:i.default.header,children:C}),(0,c.jsxs)(`div`,{className:i.default.threadWrapper,children:[(0,c.jsxs)(`div`,{ref:W,className:i.default.thread,onScroll:X,role:`log`,tabIndex:0,"aria-label":R.thread,children:[z.length===0&&!Q?w??(0,c.jsx)(t.EmptyState,{title:R.empty,description:R.emptyHint}):z.map(e=>(0,c.jsx)(o.AIChatTurn,{message:e,locale:O,canRegenerate:e.id===V&&e.streaming!==!0,onRegenerate:m,onFeedback:g,onEditSubmit:h,onEditError:F,onRetry:_,renderAvatar:b,renderContent:x,vote:S?.[e.id],defaultReasoningOpen:E,showLineNumbers:D},e.id)),Q&&(0,c.jsxs)(`div`,{className:i.default.suggestions,children:[(0,c.jsx)(`p`,{className:i.default.suggestionsTitle,children:R.emptyHint}),y.map(e=>(0,c.jsx)(`button`,{type:`button`,className:i.default.suggestion,onClick:()=>void f?.(e),children:e},e))]}),v&&!r.isGenerating(d)&&(0,c.jsxs)(`p`,{className:i.default.thinking,children:[(0,c.jsxs)(`span`,{className:i.default.dots,"aria-hidden":`true`,children:[(0,c.jsx)(`span`,{}),(0,c.jsx)(`span`,{}),(0,c.jsx)(`span`,{})]}),R.thinking]})]}),$&&(0,c.jsx)(`button`,{type:`button`,className:i.default.jump,onClick:Z,"aria-label":R.jumpToLatest,title:R.jumpToLatest,children:(0,c.jsx)(l.ArrowDown,{size:16,"aria-hidden":!0})})]}),f&&(0,c.jsx)(a.AIChatComposer,{ref:j??U,onSend:f,onStop:p,generating:B,locale:O,placeholder:k,actions:A,footer:M,disabled:N,maxRows:P,onError:F})]})}exports.AIChat=d;
|
|
2
2
|
//# sourceMappingURL=AIChat.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AIChat.cjs","names":[],"sources":["../../../src/components/AIChat/AIChat.tsx"],"sourcesContent":["import { ArrowDown } from \"lucide-react\";\nimport {\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n type HTMLAttributes,\n type ReactNode,\n} from \"react\";\n\nimport { cn } from \"@/utils/cn\";\n\nimport { EmptyState } from \"../EmptyState\";\nimport { VisuallyHidden } from \"../VisuallyHidden\";\nimport {\n aiChatStrings,\n isGenerating,\n lastAssistantId,\n tailSignature,\n visibleTurns,\n type AIChatMessage,\n type AIChatVote,\n} from \"./ai-chat-turns\";\nimport { AIChatComposer, type AIChatComposerHandle } from \"./AIChatComposer\";\nimport { AIChatTurn } from \"./AIChatTurn\";\nimport styles from \"./AIChat.module.css\";\n\n/** DOM attributes this component redefines. */\ntype OverriddenDomProps = \"children\" | \"onSubmit\";\n\nexport interface AIChatProps extends Omit<HTMLAttributes<HTMLDivElement>, OverriddenDomProps> {\n /** The transcript, **oldest first**. Never reordered by the component. */\n messages: readonly AIChatMessage[];\n /** Renders the composer when given. Receives the trimmed prompt. */\n onSend?: (text: string) => void | Promise<void>;\n /** Abort the turn in flight. Shows the stop button while generating. */\n onStop?: () => void;\n /** Ask again for the newest assistant turn. */\n onRegenerate?: (message: AIChatMessage) => void;\n /** Re-submit an edited user turn. The app decides what to drop after it. */\n onEditSubmit?: (message: AIChatMessage, text: string) => void | Promise<void>;\n /** Rating on an assistant turn. */\n onFeedback?: (message: AIChatMessage, vote: AIChatVote) => void;\n /** Retry a turn that carries an `error`. */\n onRetry?: (message: AIChatMessage) => void;\n /**\n * The request is out and nothing has arrived yet.\n *\n * Distinct from a turn with `streaming: true`: apps that only push a message\n * once the first token lands need somewhere to say \"we asked\", and without it the\n * screen is frozen for however long the model takes to start.\n */\n pending?: boolean;\n /** Prompts offered on an empty transcript. Clicking one sends it. */\n suggestions?: readonly string[];\n /** Avatar for a turn — an `<Avatar>`, an `<Icon>`, a logo. */\n renderAvatar?: (message: AIChatMessage) => ReactNode;\n /** Render a body yourself — a tool-call card, a chart, a citation list. */\n renderContent?: (message: AIChatMessage) => ReactNode;\n /** Ratings to show as pressed, by message id. Omit to keep them local. */\n votes?: Readonly<Record<string, AIChatVote>>;\n /** Rendered above the transcript, inside the panel. */\n header?: ReactNode;\n /** Shown when there are no turns and no suggestions. */\n emptyState?: ReactNode;\n /** Show `\"system\"` turns. Default `false`. */\n showSystem?: boolean;\n /** Reasoning blocks start expanded. Default `false`. */\n defaultReasoningOpen?: boolean;\n /** Show line numbers in fenced code. Default `false`. */\n showLineNumbers?: boolean;\n /** Locale for labels. Default `\"pt-BR\"`. */\n locale?: \"pt-BR\" | \"en\";\n /** Placeholder for the composer. */\n placeholder?: string;\n /** Extra controls inside the composer, before the send button. */\n composerActions?: ReactNode;\n /** Under the composer field — token count, model name, a disclaimer. */\n composerFooter?: ReactNode;\n /** Disable the composer — no credits, conversation archived, offline. */\n composerDisabled?: boolean;\n /** Largest height the composer grows to, in lines. Default 8. */\n maxRows?: number;\n /**\n * Called when `onSend` **or** `onEditSubmit` rejects. The draft stays in the field\n * either way.\n */\n onSendError?: (error: unknown) => void;\n}\n\n/** How close to the bottom still counts as \"reading the newest turn\", in pixels. */\nconst BOTTOM_SLACK = 48;\n\n/**\n * A conversation with a model: role-based turns, Markdown answers, a reasoning\n * block, a streaming caret, per-turn actions and a composer that turns into a stop\n * button while a turn is generating.\n *\n * This is the shape ChatGPT, Claude and DeepSeek converged on, and it is a different\n * component from {@link Chat}, not a variant of it. A human thread is addressed by\n * author and cares about delivery state; a model transcript is addressed by role,\n * has no delivery state at all, and needs three things a human thread never does —\n * partial output, reasoning separate from the answer, and re-asking.\n *\n * Presentational and controlled, like the rest of the SDK: it takes a list and emits\n * intent (`onSend`, `onStop`, `onRegenerate`, `onEditSubmit`, `onFeedback`). The\n * transport stays with the app, because \"how do I stream from my backend\" has a\n * different answer per provider — the SDK's `createEventStream` covers SSE, `fetch`\n * with a `ReadableStream` covers the rest, and either way the app owns the\n * `AbortController` it hands to `onStop`.\n *\n * @example\n * <AIChat\n * messages={turns}\n * pending={pending}\n * onSend={(text) => ask(text)}\n * onStop={() => controller.current?.abort()}\n * onRegenerate={(turn) => reask(turn)}\n * onFeedback={(turn, vote) => track(\"answer_rated\", { id: turn.id, vote })}\n * suggestions={[\"Resuma o último relatório\", \"Quais pedidos atrasaram?\"]}\n * />\n */\nexport function AIChat({\n messages,\n onSend,\n onStop,\n onRegenerate,\n onEditSubmit,\n onFeedback,\n onRetry,\n pending = false,\n suggestions = [],\n renderAvatar,\n renderContent,\n votes,\n header,\n emptyState,\n showSystem = false,\n defaultReasoningOpen = false,\n showLineNumbers = false,\n locale = \"pt-BR\",\n placeholder,\n composerActions,\n composerFooter,\n composerDisabled,\n maxRows,\n onSendError,\n className,\n ...rest\n}: AIChatProps) {\n const strings = aiChatStrings(locale);\n const turns = visibleTurns({ messages, showSystem });\n const generating = pending || isGenerating(messages);\n const newestAssistant = lastAssistantId(messages);\n const signature = tailSignature(messages);\n\n const composer = useRef<AIChatComposerHandle | null>(null);\n const thread = useRef<HTMLDivElement | null>(null);\n const stuckToBottom = useRef(true);\n const wasGenerating = useRef(false);\n const [atBottom, setAtBottom] = useState(true);\n const [announcement, setAnnouncement] = useState(\"\");\n\n /**\n * Remember whether the reader is at the bottom, before the next tokens land.\n *\n * A transcript that always scrolls to the newest text yanks somebody out of the\n * answer they were re-reading — and with a streaming answer that would happen\n * dozens of times per second. So the jump only happens when they were already at\n * the bottom. The slack covers a partially visible last line.\n */\n const trackPosition = (): void => {\n const node = thread.current;\n if (!node) return;\n const next = node.scrollHeight - node.scrollTop - node.clientHeight < BOTTOM_SLACK;\n stuckToBottom.current = next;\n setAtBottom(next);\n };\n\n const jumpToLatest = (): void => {\n const node = thread.current;\n if (!node) return;\n stuckToBottom.current = true;\n setAtBottom(true);\n node.scrollTop = node.scrollHeight;\n };\n\n useLayoutEffect(() => {\n const node = thread.current;\n if (!node || !stuckToBottom.current) return;\n node.scrollTop = node.scrollHeight;\n }, [signature, pending]);\n\n useEffect(() => {\n const node = thread.current;\n if (!node) return;\n node.scrollTop = node.scrollHeight;\n // Mount lands on the newest turn; from then on `trackPosition` decides.\n }, []);\n\n /**\n * Announce the start and the end of a generation, and nothing in between.\n *\n * The transcript is a `role=\"log\"` **without** `aria-live`: a live region over\n * streaming text makes a screen reader read the answer again on every token,\n * which is unusable. The two moments that matter are announced here instead, and\n * the finished answer is read from the log at the reader's own pace.\n */\n useEffect(() => {\n if (generating) {\n setAnnouncement(strings.generating);\n wasGenerating.current = true;\n return;\n }\n if (wasGenerating.current) {\n setAnnouncement(strings.done);\n wasGenerating.current = false;\n }\n }, [generating, strings.generating, strings.done]);\n\n const showSuggestions = turns.length === 0 && suggestions.length > 0 && onSend !== undefined;\n const detached = !atBottom && turns.length > 0;\n\n return (\n <div className={cn(styles.panel, className)} {...rest}>\n {header && <header className={styles.header}>{header}</header>}\n\n <div className={styles.threadWrapper}>\n <div\n ref={thread}\n className={styles.thread}\n onScroll={trackPosition}\n role=\"log\"\n tabIndex={0}\n aria-label={strings.thread}\n >\n {turns.length === 0 && !showSuggestions\n ? (emptyState ?? (\n <EmptyState title={strings.empty} description={strings.emptyHint} />\n ))\n : turns.map((message) => (\n <AIChatTurn\n key={message.id}\n message={message}\n locale={locale}\n canRegenerate={\n message.id === newestAssistant && message.streaming !== true\n }\n onRegenerate={onRegenerate}\n onFeedback={onFeedback}\n onEditSubmit={onEditSubmit}\n onEditError={onSendError}\n onRetry={onRetry}\n renderAvatar={renderAvatar}\n renderContent={renderContent}\n vote={votes?.[message.id]}\n defaultReasoningOpen={defaultReasoningOpen}\n showLineNumbers={showLineNumbers}\n />\n ))}\n\n {showSuggestions && (\n <div className={styles.suggestions}>\n <p className={styles.suggestionsTitle}>{strings.emptyHint}</p>\n {suggestions.map((suggestion) => (\n <button\n key={suggestion}\n type=\"button\"\n className={styles.suggestion}\n onClick={() => void onSend?.(suggestion)}\n >\n {suggestion}\n </button>\n ))}\n </div>\n )}\n\n {pending && !isGenerating(messages) && (\n <p className={styles.thinking}>\n <span className={styles.dots} aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n {strings.thinking}\n </p>\n )}\n </div>\n\n {detached && (\n <button\n type=\"button\"\n className={styles.jump}\n onClick={jumpToLatest}\n aria-label={strings.jumpToLatest}\n title={strings.jumpToLatest}\n >\n <ArrowDown size={16} aria-hidden />\n </button>\n )}\n </div>\n\n <VisuallyHidden>\n <div role=\"status\" aria-live=\"polite\">\n {announcement}\n </div>\n </VisuallyHidden>\n\n {onSend && (\n <AIChatComposer\n ref={composer}\n onSend={onSend}\n onStop={onStop}\n generating={generating}\n locale={locale}\n placeholder={placeholder}\n actions={composerActions}\n footer={composerFooter}\n disabled={composerDisabled}\n maxRows={maxRows}\n onError={onSendError}\n />\n )}\n </div>\n );\n}\n"],"mappings":"oVA2FA,IAAM,EAAe,GA+BrB,SAAgB,EAAO,CACnB,WACA,SACA,SACA,eACA,eACA,aACA,UACA,UAAU,GACV,cAAc,CAAC,EACf,eACA,gBACA,QACA,SACA,aACA,aAAa,GACb,uBAAuB,GACvB,kBAAkB,GAClB,SAAS,QACT,cACA,kBACA,iBACA,mBACA,UACA,cACA,YACA,GAAG,GACS,CACZ,IAAM,EAAU,EAAA,cAAc,CAAM,EAC9B,EAAQ,EAAA,aAAa,CAAE,WAAU,YAAW,CAAC,EAC7C,EAAa,GAAW,EAAA,aAAa,CAAQ,EAC7C,EAAkB,EAAA,gBAAgB,CAAQ,EAC1C,EAAY,EAAA,cAAc,CAAQ,EAElC,GAAA,EAAA,EAAA,OAAA,CAA+C,IAAI,EACn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CAAO,CAAA,CACL,IACL,EAAQ,QACV,GAEN,IAEJ,IACG,EAAA,EAAA,IAAA,CAAC,SAAD,CACI,KAAK,SACL,UAAW,EAAA,QAAO,KAClB,QAAS,EACT,aAAY,EAAQ,aACpB,MAAO,EAAQ,uBAEf,EAAA,EAAA,IAAA,CAAC,EAAA,UAAD,CAAW,KAAM,GAAI,cAAA,EAAa,CAAA,CAC9B,CAAA,CAEX,KAEL,EAAA,EAAA,IAAA,CAAC,EAAA,eAAD,CAAA,UACI,EAAA,EAAA,IAAA,CAAC,MAAD,CAAK,KAAK,SAAS,YAAU,kBACxB,CACA,CAAA,CACO,CAAA,EAEf,IACG,EAAA,EAAA,IAAA,CAAC,EAAA,eAAD,CACI,IAAK,EACG,SACA,SACI,aACJ,SACK,cACb,QAAS,EACT,OAAQ,EACR,SAAU,EACD,UACT,QAAS,CACZ,CAAA,CAEJ,GAEb"}
|
|
1
|
+
{"version":3,"file":"AIChat.cjs","names":[],"sources":["../../../src/components/AIChat/AIChat.tsx"],"sourcesContent":["import { ArrowDown } from \"lucide-react\";\nimport {\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n type HTMLAttributes,\n type ReactNode,\n type Ref,\n} from \"react\";\n\nimport { useAnnounce } from \"@/hooks/use-announce\";\nimport { cn } from \"@/utils/cn\";\n\nimport { EmptyState } from \"../EmptyState\";\nimport {\n aiChatStrings,\n isGenerating,\n lastAssistantId,\n tailSignature,\n visibleTurns,\n type AIChatMessage,\n type AIChatVote,\n} from \"./ai-chat-turns\";\nimport { AIChatComposer, type AIChatComposerHandle } from \"./AIChatComposer\";\nimport { AIChatTurn } from \"./AIChatTurn\";\nimport styles from \"./AIChat.module.css\";\n\n/** DOM attributes this component redefines. */\ntype OverriddenDomProps = \"children\" | \"onSubmit\";\n\nexport interface AIChatProps extends Omit<HTMLAttributes<HTMLDivElement>, OverriddenDomProps> {\n /** The transcript, **oldest first**. Never reordered by the component. */\n messages: readonly AIChatMessage[];\n /** Renders the composer when given. Receives the trimmed prompt. */\n onSend?: (text: string) => void | Promise<void>;\n /** Abort the turn in flight. Shows the stop button while generating. */\n onStop?: () => void;\n /** Ask again for the newest assistant turn. */\n onRegenerate?: (message: AIChatMessage) => void;\n /** Re-submit an edited user turn. The app decides what to drop after it. */\n onEditSubmit?: (message: AIChatMessage, text: string) => void | Promise<void>;\n /** Rating on an assistant turn. */\n onFeedback?: (message: AIChatMessage, vote: AIChatVote) => void;\n /** Retry a turn that carries an `error`. */\n onRetry?: (message: AIChatMessage) => void;\n /**\n * The request is out and nothing has arrived yet.\n *\n * Distinct from a turn with `streaming: true`: apps that only push a message\n * once the first token lands need somewhere to say \"we asked\", and without it the\n * screen is frozen for however long the model takes to start.\n */\n pending?: boolean;\n /** Prompts offered on an empty transcript. Clicking one sends it. */\n suggestions?: readonly string[];\n /** Avatar for a turn — an `<Avatar>`, an `<Icon>`, a logo. */\n renderAvatar?: (message: AIChatMessage) => ReactNode;\n /** Render a body yourself — a tool-call card, a chart, a citation list. */\n renderContent?: (message: AIChatMessage) => ReactNode;\n /** Ratings to show as pressed, by message id. Omit to keep them local. */\n votes?: Readonly<Record<string, AIChatVote>>;\n /** Rendered above the transcript, inside the panel. */\n header?: ReactNode;\n /** Shown when there are no turns and no suggestions. */\n emptyState?: ReactNode;\n /** Show `\"system\"` turns. Default `false`. */\n showSystem?: boolean;\n /** Reasoning blocks start expanded. Default `false`. */\n defaultReasoningOpen?: boolean;\n /** Show line numbers in fenced code. Default `false`. */\n showLineNumbers?: boolean;\n /** Locale for labels. Default `\"pt-BR\"`. */\n locale?: \"pt-BR\" | \"en\";\n /** Placeholder for the composer. */\n placeholder?: string;\n /** Extra controls inside the composer, before the send button. */\n composerActions?: ReactNode;\n /**\n * Reach the composer imperatively — `focus()`, `getValue()`, `setValue()`.\n *\n * What makes dictation (or a slash-command menu, or \"edit and resend\") possible\n * without this component knowing anything about them: pair it with\n * `composerActions` and the button you put in the composer can write into the\n * field. Speech recognition is **not** wired in here on purpose — it would make\n * every consumer of `AIChat` pay for an API that streams audio to a third party.\n */\n composerRef?: Ref<AIChatComposerHandle>;\n /** Under the composer field — token count, model name, a disclaimer. */\n composerFooter?: ReactNode;\n /** Disable the composer — no credits, conversation archived, offline. */\n composerDisabled?: boolean;\n /** Largest height the composer grows to, in lines. Default 8. */\n maxRows?: number;\n /**\n * Called when `onSend` **or** `onEditSubmit` rejects. The draft stays in the field\n * either way.\n */\n onSendError?: (error: unknown) => void;\n}\n\n/** How close to the bottom still counts as \"reading the newest turn\", in pixels. */\nconst BOTTOM_SLACK = 48;\n\n/**\n * A conversation with a model: role-based turns, Markdown answers, a reasoning\n * block, a streaming caret, per-turn actions and a composer that turns into a stop\n * button while a turn is generating.\n *\n * This is the shape ChatGPT, Claude and DeepSeek converged on, and it is a different\n * component from {@link Chat}, not a variant of it. A human thread is addressed by\n * author and cares about delivery state; a model transcript is addressed by role,\n * has no delivery state at all, and needs three things a human thread never does —\n * partial output, reasoning separate from the answer, and re-asking.\n *\n * Presentational and controlled, like the rest of the SDK: it takes a list and emits\n * intent (`onSend`, `onStop`, `onRegenerate`, `onEditSubmit`, `onFeedback`). The\n * transport stays with the app, because \"how do I stream from my backend\" has a\n * different answer per provider — the SDK's `createEventStream` covers SSE, `fetch`\n * with a `ReadableStream` covers the rest, and either way the app owns the\n * `AbortController` it hands to `onStop`.\n *\n * @example\n * <AIChat\n * messages={turns}\n * pending={pending}\n * onSend={(text) => ask(text)}\n * onStop={() => controller.current?.abort()}\n * onRegenerate={(turn) => reask(turn)}\n * onFeedback={(turn, vote) => track(\"answer_rated\", { id: turn.id, vote })}\n * suggestions={[\"Resuma o último relatório\", \"Quais pedidos atrasaram?\"]}\n * />\n */\nexport function AIChat({\n messages,\n onSend,\n onStop,\n onRegenerate,\n onEditSubmit,\n onFeedback,\n onRetry,\n pending = false,\n suggestions = [],\n renderAvatar,\n renderContent,\n votes,\n header,\n emptyState,\n showSystem = false,\n defaultReasoningOpen = false,\n showLineNumbers = false,\n locale = \"pt-BR\",\n placeholder,\n composerActions,\n composerRef,\n composerFooter,\n composerDisabled,\n maxRows,\n onSendError,\n className,\n ...rest\n}: AIChatProps) {\n const strings = aiChatStrings(locale);\n const turns = visibleTurns({ messages, showSystem });\n const generating = pending || isGenerating(messages);\n const newestAssistant = lastAssistantId(messages);\n const signature = tailSignature(messages);\n\n const composer = useRef<AIChatComposerHandle | null>(null);\n const thread = useRef<HTMLDivElement | null>(null);\n const stuckToBottom = useRef(true);\n const wasGenerating = useRef(false);\n const [atBottom, setAtBottom] = useState(true);\n const announce = useAnnounce();\n\n /**\n * Remember whether the reader is at the bottom, before the next tokens land.\n *\n * A transcript that always scrolls to the newest text yanks somebody out of the\n * answer they were re-reading — and with a streaming answer that would happen\n * dozens of times per second. So the jump only happens when they were already at\n * the bottom. The slack covers a partially visible last line.\n */\n const trackPosition = (): void => {\n const node = thread.current;\n if (!node) return;\n const next = node.scrollHeight - node.scrollTop - node.clientHeight < BOTTOM_SLACK;\n stuckToBottom.current = next;\n setAtBottom(next);\n };\n\n const jumpToLatest = (): void => {\n const node = thread.current;\n if (!node) return;\n stuckToBottom.current = true;\n setAtBottom(true);\n node.scrollTop = node.scrollHeight;\n };\n\n useLayoutEffect(() => {\n const node = thread.current;\n if (!node || !stuckToBottom.current) return;\n node.scrollTop = node.scrollHeight;\n }, [signature, pending]);\n\n useEffect(() => {\n const node = thread.current;\n if (!node) return;\n node.scrollTop = node.scrollHeight;\n // Mount lands on the newest turn; from then on `trackPosition` decides.\n }, []);\n\n /**\n * Announce the start and the end of a generation, and nothing in between.\n *\n * The transcript is a `role=\"log\"` **without** `aria-live`: a live region over\n * streaming text makes a screen reader read the answer again on every token,\n * which is unusable. The two moments that matter are announced here instead —\n * through the shared `useAnnounce` region rather than a private one, so a page\n * holding a chat plus a table plus toasts still has exactly one live region per\n * politeness — and the finished answer is read from the log at the reader's own\n * pace.\n */\n useEffect(() => {\n if (generating) {\n announce(strings.generating);\n wasGenerating.current = true;\n return;\n }\n if (wasGenerating.current) {\n announce(strings.done);\n wasGenerating.current = false;\n }\n }, [generating, strings.generating, strings.done, announce]);\n\n const showSuggestions = turns.length === 0 && suggestions.length > 0 && onSend !== undefined;\n const detached = !atBottom && turns.length > 0;\n\n return (\n <div className={cn(styles.panel, className)} {...rest}>\n {header && <header className={styles.header}>{header}</header>}\n\n <div className={styles.threadWrapper}>\n <div\n ref={thread}\n className={styles.thread}\n onScroll={trackPosition}\n role=\"log\"\n tabIndex={0}\n aria-label={strings.thread}\n >\n {turns.length === 0 && !showSuggestions\n ? (emptyState ?? (\n <EmptyState title={strings.empty} description={strings.emptyHint} />\n ))\n : turns.map((message) => (\n <AIChatTurn\n key={message.id}\n message={message}\n locale={locale}\n canRegenerate={\n message.id === newestAssistant && message.streaming !== true\n }\n onRegenerate={onRegenerate}\n onFeedback={onFeedback}\n onEditSubmit={onEditSubmit}\n onEditError={onSendError}\n onRetry={onRetry}\n renderAvatar={renderAvatar}\n renderContent={renderContent}\n vote={votes?.[message.id]}\n defaultReasoningOpen={defaultReasoningOpen}\n showLineNumbers={showLineNumbers}\n />\n ))}\n\n {showSuggestions && (\n <div className={styles.suggestions}>\n <p className={styles.suggestionsTitle}>{strings.emptyHint}</p>\n {suggestions.map((suggestion) => (\n <button\n key={suggestion}\n type=\"button\"\n className={styles.suggestion}\n onClick={() => void onSend?.(suggestion)}\n >\n {suggestion}\n </button>\n ))}\n </div>\n )}\n\n {pending && !isGenerating(messages) && (\n <p className={styles.thinking}>\n <span className={styles.dots} aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n {strings.thinking}\n </p>\n )}\n </div>\n\n {detached && (\n <button\n type=\"button\"\n className={styles.jump}\n onClick={jumpToLatest}\n aria-label={strings.jumpToLatest}\n title={strings.jumpToLatest}\n >\n <ArrowDown size={16} aria-hidden />\n </button>\n )}\n </div>\n\n {onSend && (\n <AIChatComposer\n ref={composerRef ?? composer}\n onSend={onSend}\n onStop={onStop}\n generating={generating}\n locale={locale}\n placeholder={placeholder}\n actions={composerActions}\n footer={composerFooter}\n disabled={composerDisabled}\n maxRows={maxRows}\n onError={onSendError}\n />\n )}\n </div>\n );\n}\n"],"mappings":"4UAsGA,IAAM,EAAe,GA+BrB,SAAgB,EAAO,CACnB,WACA,SACA,SACA,eACA,eACA,aACA,UACA,UAAU,GACV,cAAc,CAAC,EACf,eACA,gBACA,QACA,SACA,aACA,aAAa,GACb,uBAAuB,GACvB,kBAAkB,GAClB,SAAS,QACT,cACA,kBACA,cACA,iBACA,mBACA,UACA,cACA,YACA,GAAG,GACS,CACZ,IAAM,EAAU,EAAA,cAAc,CAAM,EAC9B,EAAQ,EAAA,aAAa,CAAE,WAAU,YAAW,CAAC,EAC7C,EAAa,GAAW,EAAA,aAAa,CAAQ,EAC7C,EAAkB,EAAA,gBAAgB,CAAQ,EAC1C,EAAY,EAAA,cAAc,CAAQ,EAElC,GAAA,EAAA,EAAA,OAAA,CAA+C,IAAI,EACnD,GAAA,EAAA,EAAA,OAAA,CAAuC,IAAI,EAC3C,GAAA,EAAA,EAAA,OAAA,CAAuB,EAAI,EAC3B,GAAA,EAAA,EAAA,OAAA,CAAuB,EAAK,EAC5B,CAAC,EAAU,IAAA,EAAA,EAAA,SAAA,CAAwB,EAAI,EACvC,EAAW,EAAA,YAAY,EAUvB,MAA4B,CAC9B,IAAM,EAAO,EAAO,QACpB,GAAI,CAAC,EAAM,OACX,IAAM,EAAO,EAAK,aAAe,EAAK,UAAY,EAAK,aAAe,EACtE,EAAc,QAAU,EACxB,EAAY,CAAI,CACpB,EAEM,MAA2B,CAC7B,IAAM,EAAO,EAAO,QACf,IACL,EAAc,QAAU,GACxB,EAAY,EAAI,EAChB,EAAK,UAAY,EAAK,aAC1B,GAEA,EAAA,EAAA,gBAAA,KAAsB,CAClB,IAAM,EAAO,EAAO,QAChB,CAAC,GAAQ,CAAC,EAAc,UAC5B,EAAK,UAAY,EAAK,aAC1B,EAAG,CAAC,EAAW,CAAO,CAAC,GAEvB,EAAA,EAAA,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