mirror of
https://github.com/block/buzz.git
synced 2026-11-30 13:12:38 +00:00
- Use OpenAI typed transcription session format (type: "transcription") instead of legacy realtime fields that would fail or produce no transcripts - Sync editor content via syncContentRef before merging dictation text so manually typed prefixes are preserved when dictation starts - Read send-blocked state from refs at transcript time so uploads prevent auto-submit from clearing the composer Signed-off-by: klopez4212 <klopez4212@gmail.com>
83 lines
2.2 KiB
TypeScript
83 lines
2.2 KiB
TypeScript
import type * as React from "react";
|
|
import { useCallback, useMemo, useRef } from "react";
|
|
import {
|
|
DEFAULT_AUTO_SUBMIT_PHRASE,
|
|
getAutoSubmitMatch,
|
|
parseAutoSubmitPhrases,
|
|
replaceTrailingTranscribedText,
|
|
} from "../lib/voiceInput";
|
|
import { useRealtimeDictation } from "./useRealtimeDictation";
|
|
|
|
interface UseDictationOptions {
|
|
/** Returns the current composer text (must be fresh — synced from editor). */
|
|
getText: () => string;
|
|
/** Set composer text */
|
|
setText: (value: string) => void;
|
|
/** Send the message */
|
|
onSend: (text: string) => void;
|
|
/** Ref that is `true` when sending is blocked (uploading, preparing mention, etc.) */
|
|
isSendBlockedRef?: React.MutableRefObject<boolean>;
|
|
}
|
|
|
|
export function useDictation({
|
|
getText,
|
|
setText,
|
|
onSend,
|
|
isSendBlockedRef,
|
|
}: UseDictationOptions) {
|
|
const autoSubmitPhrases = useMemo(
|
|
() => parseAutoSubmitPhrases(DEFAULT_AUTO_SUBMIT_PHRASE),
|
|
[],
|
|
);
|
|
const stopRecordingRef = useRef<() => void>(() => {});
|
|
const lastTranscriptRef = useRef("");
|
|
|
|
const handleTranscript = useCallback(
|
|
(transcript: string) => {
|
|
const previous = lastTranscriptRef.current;
|
|
const latest = getText();
|
|
const merged = replaceTrailingTranscribedText(
|
|
latest,
|
|
previous,
|
|
transcript,
|
|
);
|
|
const match = getAutoSubmitMatch(transcript, autoSubmitPhrases);
|
|
|
|
if (!match) {
|
|
setText(merged);
|
|
lastTranscriptRef.current = transcript;
|
|
return;
|
|
}
|
|
|
|
const textWithoutPhrase = replaceTrailingTranscribedText(
|
|
latest,
|
|
previous,
|
|
match.textWithoutPhrase,
|
|
);
|
|
if (!textWithoutPhrase.trim()) return;
|
|
|
|
stopRecordingRef.current();
|
|
|
|
if (isSendBlockedRef?.current) {
|
|
setText(textWithoutPhrase);
|
|
return;
|
|
}
|
|
|
|
onSend(textWithoutPhrase.trim());
|
|
setText("");
|
|
lastTranscriptRef.current = "";
|
|
},
|
|
[autoSubmitPhrases, getText, onSend, isSendBlockedRef, setText],
|
|
);
|
|
|
|
const dictation = useRealtimeDictation({
|
|
onRecordingStart: () => {
|
|
lastTranscriptRef.current = "";
|
|
},
|
|
onTranscriptText: handleTranscript,
|
|
});
|
|
stopRecordingRef.current = dictation.stopRecording;
|
|
|
|
return dictation;
|
|
}
|