@plaisolutions/react 0.5.1 → 0.6.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/dist/index.js CHANGED
@@ -2552,7 +2552,7 @@ function PromptFormIconButton({ className, type = "button",...props }) {
2552
2552
  ...props
2553
2553
  });
2554
2554
  }
2555
- function PromptForm({ value, onValueChange, onSubmit, status = "ready", uploadState, onStop, disabled = false, clearOnSubmit = true, enabledTools, placeholder = "Type a message...", sendLabel = "Send", stopLabel = "Stop", attachLabel = "Attach file", removeFileLabel = "Remove file", uploadingLabel = "Uploading", processingUploadLabel = "Processing upload", uploadErrorLabel = "Upload failed", enableAttachments = true, files: filesProp, onFilesChange, onInvalidFiles, accept = PROMPT_FORM_FILE_ACCEPT, className, textareaClassName, attachmentsClassName, uploadProgressClassName, maxRows = defaultMaxRows, submitButtonClassName, stopButtonClassName, leftSlot, rightSlot, submitOnEnter = true, onTextareaKeyDown }) {
2555
+ function PromptForm({ value, onValueChange, onSubmit, status = "ready", uploadState, onStop, disabled = false, hasPendingInput = false, clearOnSubmit = true, enabledTools, placeholder = "Type a message...", sendLabel = "Send", stopLabel = "Stop", attachLabel = "Attach file", removeFileLabel = "Remove file", uploadingLabel = "Uploading", processingUploadLabel = "Processing upload", uploadErrorLabel = "Upload failed", enableAttachments = true, files: filesProp, onFilesChange, onInvalidFiles, accept = PROMPT_FORM_FILE_ACCEPT, className, textareaClassName, attachmentsClassName, uploadProgressClassName, maxRows = defaultMaxRows, submitButtonClassName, stopButtonClassName, leftSlot, rightSlot, submitOnEnter = true, onTextareaKeyDown }) {
2556
2556
  const textareaRef = useRef(null);
2557
2557
  const [internalFiles, setInternalFiles] = useState([]);
2558
2558
  const [isSubmitting, setIsSubmitting] = useState(false);
@@ -2560,7 +2560,7 @@ function PromptForm({ value, onValueChange, onSubmit, status = "ready", uploadSt
2560
2560
  const setFiles = onFilesChange ?? setInternalFiles;
2561
2561
  const isStreaming = status === "streaming" || status === "submitted";
2562
2562
  const isUploading = uploadState?.status === "uploading" || uploadState?.status === "processing";
2563
- const hasContent = value.trim().length > 0 || files.length > 0;
2563
+ const hasContent = value.trim().length > 0 || files.length > 0 || hasPendingInput;
2564
2564
  const canSubmit = !disabled && !isSubmitting && !isStreaming && !isUploading && hasContent;
2565
2565
  const isInteractionDisabled = disabled || isSubmitting || isUploading;
2566
2566
  useLayoutEffect(() => {
@@ -2750,57 +2750,162 @@ function useVoiceRecording() {
2750
2750
  }
2751
2751
 
2752
2752
  //#endregion
2753
- //#region src/components/speech-to-text-toggle/speech-to-text-toggle.tsx
2754
- function SpeechToTextToggle({ onTranscriptionComplete, onTranscriptionError, transcribe, disabled = false, label = "Voice input", listeningLabel = "Stop recording", loadingLabel = "Transcribing...", className,...props }) {
2755
- const [isListening, setIsListening] = useState(false);
2756
- const [isTranscribing, setIsTranscribing] = useState(false);
2753
+ //#region src/components/speech-to-text-toggle/use-speech-to-text.ts
2754
+ function normalizeError(error, fallback) {
2755
+ return error instanceof Error ? error : new Error(fallback);
2756
+ }
2757
+ function isAbortError(error) {
2758
+ return error instanceof DOMException && error.name === "AbortError";
2759
+ }
2760
+ /**
2761
+ * Owns the complete voice-input lifecycle. `finish` is safe to call from both
2762
+ * the microphone control and a form submit: concurrent calls share the same
2763
+ * transcription promise.
2764
+ */
2765
+ function useSpeechToText({ transcribe, onTranscriptionComplete, onTranscriptionError }) {
2766
+ const [status, setStatus] = useState("idle");
2767
+ const statusRef = useRef("idle");
2768
+ const operationIdRef = useRef(0);
2769
+ const pendingFinishRef = useRef(null);
2757
2770
  const abortControllerRef = useRef(null);
2758
- const { start, stop, cancel } = useVoiceRecording();
2759
- useEffect(() => {
2760
- return () => {
2761
- abortControllerRef.current?.abort();
2762
- cancel();
2763
- };
2764
- }, [cancel]);
2765
- async function handleToggle() {
2766
- if (disabled || isTranscribing) return;
2767
- if (!isListening) {
2768
- try {
2769
- await start();
2770
- setIsListening(true);
2771
- } catch (error) {
2772
- onTranscriptionError?.(error instanceof Error ? error : /* @__PURE__ */ new Error("Microphone access was denied"));
2771
+ const optionsRef = useRef({
2772
+ transcribe,
2773
+ onTranscriptionComplete,
2774
+ onTranscriptionError
2775
+ });
2776
+ optionsRef.current = {
2777
+ transcribe,
2778
+ onTranscriptionComplete,
2779
+ onTranscriptionError
2780
+ };
2781
+ const { start: startRecording, stop: stopRecording, cancel: cancelRecording } = useVoiceRecording();
2782
+ const updateStatus = useCallback((nextStatus) => {
2783
+ statusRef.current = nextStatus;
2784
+ setStatus(nextStatus);
2785
+ }, []);
2786
+ const start = useCallback(async () => {
2787
+ if (statusRef.current !== "idle" || pendingFinishRef.current) return;
2788
+ const operationId = operationIdRef.current + 1;
2789
+ operationIdRef.current = operationId;
2790
+ updateStatus("requesting");
2791
+ try {
2792
+ await startRecording();
2793
+ if (operationIdRef.current !== operationId) {
2794
+ cancelRecording();
2795
+ return;
2773
2796
  }
2774
- return;
2797
+ updateStatus("recording");
2798
+ } catch (error) {
2799
+ if (operationIdRef.current !== operationId) return;
2800
+ updateStatus("idle");
2801
+ optionsRef.current.onTranscriptionError?.(normalizeError(error, "Microphone access was denied"));
2775
2802
  }
2776
- setIsListening(false);
2777
- setIsTranscribing(true);
2803
+ }, [
2804
+ cancelRecording,
2805
+ startRecording,
2806
+ updateStatus
2807
+ ]);
2808
+ const finish = useCallback(() => {
2809
+ if (pendingFinishRef.current) return pendingFinishRef.current;
2810
+ if (statusRef.current !== "recording") return Promise.resolve(null);
2811
+ const operationId = operationIdRef.current;
2778
2812
  const abortController = new AbortController();
2779
2813
  abortControllerRef.current = abortController;
2780
- try {
2781
- const text$1 = await transcribe(await stop(), abortController.signal);
2782
- if (text$1.trim()) onTranscriptionComplete(text$1);
2783
- } catch (error) {
2784
- if (error instanceof DOMException && error.name === "AbortError") return;
2785
- onTranscriptionError?.(error instanceof Error ? error : /* @__PURE__ */ new Error("Transcription failed"));
2786
- } finally {
2787
- abortControllerRef.current = null;
2788
- setIsTranscribing(false);
2814
+ updateStatus("transcribing");
2815
+ const pending = (async () => {
2816
+ try {
2817
+ const audio = await stopRecording();
2818
+ if (operationIdRef.current !== operationId) return null;
2819
+ const transcription = await optionsRef.current.transcribe(audio, abortController.signal);
2820
+ if (operationIdRef.current !== operationId) return null;
2821
+ const text$1 = transcription.trim();
2822
+ if (!text$1) return null;
2823
+ optionsRef.current.onTranscriptionComplete?.(text$1);
2824
+ return text$1;
2825
+ } catch (error) {
2826
+ if (operationIdRef.current !== operationId || abortController.signal.aborted || isAbortError(error)) return null;
2827
+ optionsRef.current.onTranscriptionError?.(normalizeError(error, "Transcription failed"));
2828
+ return null;
2829
+ } finally {
2830
+ pendingFinishRef.current = null;
2831
+ abortControllerRef.current = null;
2832
+ if (operationIdRef.current === operationId) updateStatus("idle");
2833
+ }
2834
+ })();
2835
+ pendingFinishRef.current = pending;
2836
+ return pending;
2837
+ }, [stopRecording, updateStatus]);
2838
+ const cancel = useCallback(() => {
2839
+ operationIdRef.current += 1;
2840
+ abortControllerRef.current?.abort();
2841
+ cancelRecording();
2842
+ updateStatus("idle");
2843
+ }, [cancelRecording, updateStatus]);
2844
+ const toggle = useCallback(async () => {
2845
+ if (statusRef.current === "idle") {
2846
+ await start();
2847
+ return null;
2789
2848
  }
2790
- }
2791
- const ariaLabel = isTranscribing ? loadingLabel : isListening ? listeningLabel : label;
2849
+ if (statusRef.current === "recording" || statusRef.current === "transcribing") return finish();
2850
+ return null;
2851
+ }, [finish, start]);
2852
+ useEffect(() => {
2853
+ return () => {
2854
+ operationIdRef.current += 1;
2855
+ abortControllerRef.current?.abort();
2856
+ cancelRecording();
2857
+ };
2858
+ }, [cancelRecording]);
2859
+ return useMemo(() => ({
2860
+ status,
2861
+ start,
2862
+ finish,
2863
+ cancel,
2864
+ toggle
2865
+ }), [
2866
+ cancel,
2867
+ finish,
2868
+ start,
2869
+ status,
2870
+ toggle
2871
+ ]);
2872
+ }
2873
+
2874
+ //#endregion
2875
+ //#region src/components/speech-to-text-toggle/speech-to-text-toggle.tsx
2876
+ async function missingTranscribe() {
2877
+ throw new Error("SpeechToTextToggle requires transcribe when no controller is provided.");
2878
+ }
2879
+ function SpeechToTextToggle({ controller, onTranscriptionComplete, onTranscriptionError, transcribe, disabled = false, label = "Voice input", listeningLabel = "Stop recording", cancelLabel = "Cancel recording", requestingLabel = "Requesting microphone access...", loadingLabel = "Transcribing...", cancelOnClickWhileRecording = false, className, onClick,...props }) {
2880
+ const internalController = useSpeechToText({
2881
+ transcribe: transcribe ?? missingTranscribe,
2882
+ onTranscriptionComplete,
2883
+ onTranscriptionError
2884
+ });
2885
+ const speechToText = controller ?? internalController;
2886
+ const isRequesting = speechToText.status === "requesting";
2887
+ const isListening = speechToText.status === "recording";
2888
+ const isTranscribing = speechToText.status === "transcribing";
2889
+ const cancelsRecording = isListening && cancelOnClickWhileRecording;
2890
+ const ariaLabel = isRequesting ? requestingLabel : isTranscribing ? loadingLabel : cancelsRecording ? cancelLabel : isListening ? listeningLabel : label;
2792
2891
  return /* @__PURE__ */ jsx(PromptFormIconButton, {
2793
2892
  type: "button",
2794
2893
  "aria-label": ariaLabel,
2795
2894
  "aria-pressed": isListening,
2796
- "aria-busy": isTranscribing,
2797
- disabled: disabled || isTranscribing,
2895
+ "aria-busy": isRequesting || isTranscribing,
2896
+ disabled: disabled || isRequesting || isTranscribing,
2798
2897
  className: joinClasses(isListening && !isTranscribing ? "text-red-600" : void 0, className),
2799
- onClick: () => {
2800
- handleToggle();
2898
+ onClick: (event) => {
2899
+ onClick?.(event);
2900
+ if (event.defaultPrevented) return;
2901
+ if (cancelsRecording) {
2902
+ speechToText.cancel();
2903
+ return;
2904
+ }
2905
+ speechToText.toggle();
2801
2906
  },
2802
2907
  ...props,
2803
- children: isTranscribing ? /* @__PURE__ */ jsx(Loader, { className: "size-4 animate-spin" }) : /* @__PURE__ */ jsx(Microphone, { className: "size-4" })
2908
+ children: isRequesting || isTranscribing ? /* @__PURE__ */ jsx(Loader, { className: "size-4 animate-spin" }) : cancelsRecording ? /* @__PURE__ */ jsx(X, { className: "size-4" }) : /* @__PURE__ */ jsx(Microphone, { className: "size-4" })
2804
2909
  });
2805
2910
  }
2806
2911
 
@@ -2819,5 +2924,5 @@ async function dummyTranscribeAudio(_audio, signal) {
2819
2924
  }
2820
2925
 
2821
2926
  //#endregion
2822
- export { ArrowUp, Clipboard, DatasourceFolderCard, DatasourceToolResources, DatasourceToolResultCard, Loader, Message, MessageAvatar, MessageContent, MessageFooter, MessageHeader, MessageParts, Microphone, PROMPT_FORM_FILE_ACCEPT, Paperclip, PromptForm, PromptFormAttachButton, PromptFormIconButton, ResourceCard, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle, SheetTrigger, SpeechToTextToggle, Stop, ThumbDown, ThumbUp, ToolResultAgentInvocationCard, ToolResultBrowserCard, ToolResultCard, ToolResultExternalDatasourceCard, ToolResultHttpRequestCard, ToolResultMcpCard, ToolResultOfficeDocumentsCard, ToolResultWebSearchCard, ToolResultWorkflowDispatchCard, X, dummyTranscribeAudio, getLocalizedOpenGraphValue, getResourceDescription, getResourceIcon, getResourceOpenGraphImage, getResourceOpenGraphType, getResourceTitle, getResourceType, getResourceUrl, isAllowedPromptFormFile, partitionPromptFormFiles, useChat };
2927
+ export { ArrowUp, Clipboard, DatasourceFolderCard, DatasourceToolResources, DatasourceToolResultCard, Loader, Message, MessageAvatar, MessageContent, MessageFooter, MessageHeader, MessageParts, Microphone, PROMPT_FORM_FILE_ACCEPT, Paperclip, PromptForm, PromptFormAttachButton, PromptFormIconButton, ResourceCard, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle, SheetTrigger, SpeechToTextToggle, Stop, ThumbDown, ThumbUp, ToolResultAgentInvocationCard, ToolResultBrowserCard, ToolResultCard, ToolResultExternalDatasourceCard, ToolResultHttpRequestCard, ToolResultMcpCard, ToolResultOfficeDocumentsCard, ToolResultWebSearchCard, ToolResultWorkflowDispatchCard, X, dummyTranscribeAudio, getLocalizedOpenGraphValue, getResourceDescription, getResourceIcon, getResourceOpenGraphImage, getResourceOpenGraphType, getResourceTitle, getResourceType, getResourceUrl, isAllowedPromptFormFile, partitionPromptFormFiles, useChat, useSpeechToText };
2823
2928
  //# sourceMappingURL=index.js.map