@plaisolutions/react 0.5.1 → 0.7.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
@@ -1,7 +1,7 @@
1
1
  import { PlaiChat } from "@plaisolutions/client";
2
2
  import { createContext, forwardRef, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
3
3
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
4
- import { Bot, Check, CheckCircle2, Copy, Database, File, FileText, Globe, LoaderCircle, MessageSquare, Minus, Plug, Plus, ThumbsDown, ThumbsUp, Workflow, XCircle } from "lucide-react";
4
+ import { Bot, Brain, Check, CheckCircle2, ChevronDown, Copy, Database, File, FileText, Globe, LoaderCircle, MessageSquare, Minus, Plug, Plus, ThumbsDown, ThumbsUp, Workflow, XCircle } from "lucide-react";
5
5
 
6
6
  //#region src/use-chat.ts
7
7
  function useChat(options) {
@@ -2186,6 +2186,61 @@ function ToolResultCard({ part, className, detailsOpen = true, locale, onOpenAge
2186
2186
  });
2187
2187
  }
2188
2188
 
2189
+ //#endregion
2190
+ //#region src/components/thinking.tsx
2191
+ function Thinking({ part, thinkingLabel = "Thinking…", completedLabel = "Thought process", defaultOpen, className,...props }) {
2192
+ const isStreaming = part.state === "streaming";
2193
+ const hasContent = Boolean(part.thinking.trim());
2194
+ const [isOpen, setIsOpen] = useState(defaultOpen ?? isStreaming);
2195
+ const previousState = useRef(part.state);
2196
+ const contentId = useId();
2197
+ const label = isStreaming ? thinkingLabel : completedLabel;
2198
+ useEffect(() => {
2199
+ if (previousState.current === "streaming" && !isStreaming) setIsOpen(false);
2200
+ previousState.current = part.state;
2201
+ }, [isStreaming, part.state]);
2202
+ return /* @__PURE__ */ jsxs("section", {
2203
+ className: joinClasses("text-sm text-neutral-600", className),
2204
+ "data-thinking-state": part.state,
2205
+ ...props,
2206
+ children: [
2207
+ /* @__PURE__ */ jsxs("button", {
2208
+ type: "button",
2209
+ "aria-controls": hasContent ? contentId : void 0,
2210
+ "aria-expanded": hasContent ? isOpen : void 0,
2211
+ "aria-label": hasContent ? `${isOpen ? "Collapse" : "Expand"} ${label}` : label,
2212
+ disabled: !hasContent,
2213
+ className: joinClasses("inline-flex items-center gap-2 rounded-md py-1 text-left font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950", hasContent ? "cursor-pointer hover:text-neutral-900" : "cursor-default"),
2214
+ onClick: () => setIsOpen((value) => !value),
2215
+ children: [
2216
+ isStreaming ? /* @__PURE__ */ jsx(LoaderCircle, {
2217
+ className: "size-4 shrink-0 animate-spin motion-reduce:animate-none",
2218
+ "aria-hidden": "true"
2219
+ }) : /* @__PURE__ */ jsx(Brain, {
2220
+ className: "size-4 shrink-0",
2221
+ "aria-hidden": "true"
2222
+ }),
2223
+ /* @__PURE__ */ jsx("span", { children: label }),
2224
+ hasContent ? /* @__PURE__ */ jsx(ChevronDown, {
2225
+ className: joinClasses("size-4 shrink-0 transition-transform motion-reduce:transition-none", isOpen ? "rotate-180" : void 0),
2226
+ "aria-hidden": "true"
2227
+ }) : null
2228
+ ]
2229
+ }),
2230
+ /* @__PURE__ */ jsx("span", {
2231
+ className: "sr-only",
2232
+ "aria-live": "polite",
2233
+ children: isStreaming ? "Thinking in progress" : "Thinking complete"
2234
+ }),
2235
+ hasContent && isOpen ? /* @__PURE__ */ jsx("p", {
2236
+ id: contentId,
2237
+ className: "mt-1 whitespace-pre-wrap border-l-2 border-neutral-200 pl-3 text-sm leading-6 text-neutral-600",
2238
+ children: part.thinking
2239
+ }) : null
2240
+ ]
2241
+ });
2242
+ }
2243
+
2189
2244
  //#endregion
2190
2245
  //#region src/components/message.tsx
2191
2246
  function Message({ align = "start", className,...props }) {
@@ -2253,7 +2308,7 @@ function getDisplayExtension(label) {
2253
2308
  if (!ext || ext === label.toUpperCase()) return void 0;
2254
2309
  return ext;
2255
2310
  }
2256
- function renderPart(part, index, message, isStreaming, onOpenAgentThread, locale, renderText, renderToolCall) {
2311
+ function renderPart(part, index, message, isStreaming, onOpenAgentThread, locale, renderText, renderToolCall, renderThinking, thinkingLabel, completedThinkingLabel) {
2257
2312
  if (part.type === "text") {
2258
2313
  if (renderText) return /* @__PURE__ */ jsx("div", { children: renderText(part, {
2259
2314
  message,
@@ -2312,6 +2367,14 @@ function renderPart(part, index, message, isStreaming, onOpenAgentThread, locale
2312
2367
  onOpenAgentThread
2313
2368
  }, `tool-${part.id}-${index}`);
2314
2369
  }
2370
+ if (part.type === "thinking") {
2371
+ if (renderThinking) return /* @__PURE__ */ jsx("div", { children: renderThinking(part, { message }) }, `thinking-${index}`);
2372
+ return /* @__PURE__ */ jsx(Thinking, {
2373
+ part,
2374
+ thinkingLabel,
2375
+ completedLabel: completedThinkingLabel
2376
+ }, `thinking-${index}`);
2377
+ }
2315
2378
  if (part.type === "guardrail") return /* @__PURE__ */ jsx("p", {
2316
2379
  className: "rounded-lg border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900",
2317
2380
  children: part.content
@@ -2330,7 +2393,7 @@ function orderMessageParts(parts, position) {
2330
2393
  else remainingParts.push(indexedPart);
2331
2394
  return [...datasourceParts, ...remainingParts];
2332
2395
  }
2333
- function MessageParts({ message, collapseThreshold = DEFAULT_COLLAPSE_THRESHOLD, datasourceToolResultsPosition = "inline", onOpenAgentThread, locale, renderText, renderToolCall, isStreaming = false, readMoreLabel = "Read more", readLessLabel = "Read less", className,...props }) {
2396
+ function MessageParts({ message, collapseThreshold = DEFAULT_COLLAPSE_THRESHOLD, datasourceToolResultsPosition = "inline", onOpenAgentThread, locale, renderText, renderToolCall, renderThinking, isStreaming = false, thinkingLabel, completedThinkingLabel, readMoreLabel = "Read more", readLessLabel = "Read less", className,...props }) {
2334
2397
  const [isExpanded, setIsExpanded] = useState(false);
2335
2398
  const textContent = useMemo(() => message.parts.filter((part) => part.type === "text").map((part) => part.text).join("\n"), [message.parts]);
2336
2399
  const canCollapse = message.role === "user" && message.parts.every((part) => part.type === "text") && textContent.length > collapseThreshold;
@@ -2343,7 +2406,7 @@ function MessageParts({ message, collapseThreshold = DEFAULT_COLLAPSE_THRESHOLD,
2343
2406
  children: [canCollapse && !isExpanded ? /* @__PURE__ */ jsx("p", {
2344
2407
  className: "whitespace-pre-wrap text-sm leading-6",
2345
2408
  children: previewText
2346
- }) : orderedParts.map(({ part, index }) => renderPart(part, index, message, isStreaming, onOpenAgentThread, locale, renderText, renderToolCall)), canCollapse ? /* @__PURE__ */ jsx("button", {
2409
+ }) : orderedParts.map(({ part, index }) => renderPart(part, index, message, isStreaming, onOpenAgentThread, locale, renderText, renderToolCall, renderThinking, thinkingLabel, completedThinkingLabel)), canCollapse ? /* @__PURE__ */ jsx("button", {
2347
2410
  type: "button",
2348
2411
  className: "text-left text-xs font-medium text-slate-600 hover:text-slate-900",
2349
2412
  onClick: () => setIsExpanded((previous) => !previous),
@@ -2552,7 +2615,7 @@ function PromptFormIconButton({ className, type = "button",...props }) {
2552
2615
  ...props
2553
2616
  });
2554
2617
  }
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 }) {
2618
+ 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
2619
  const textareaRef = useRef(null);
2557
2620
  const [internalFiles, setInternalFiles] = useState([]);
2558
2621
  const [isSubmitting, setIsSubmitting] = useState(false);
@@ -2560,7 +2623,7 @@ function PromptForm({ value, onValueChange, onSubmit, status = "ready", uploadSt
2560
2623
  const setFiles = onFilesChange ?? setInternalFiles;
2561
2624
  const isStreaming = status === "streaming" || status === "submitted";
2562
2625
  const isUploading = uploadState?.status === "uploading" || uploadState?.status === "processing";
2563
- const hasContent = value.trim().length > 0 || files.length > 0;
2626
+ const hasContent = value.trim().length > 0 || files.length > 0 || hasPendingInput;
2564
2627
  const canSubmit = !disabled && !isSubmitting && !isStreaming && !isUploading && hasContent;
2565
2628
  const isInteractionDisabled = disabled || isSubmitting || isUploading;
2566
2629
  useLayoutEffect(() => {
@@ -2750,57 +2813,162 @@ function useVoiceRecording() {
2750
2813
  }
2751
2814
 
2752
2815
  //#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);
2816
+ //#region src/components/speech-to-text-toggle/use-speech-to-text.ts
2817
+ function normalizeError(error, fallback) {
2818
+ return error instanceof Error ? error : new Error(fallback);
2819
+ }
2820
+ function isAbortError(error) {
2821
+ return error instanceof DOMException && error.name === "AbortError";
2822
+ }
2823
+ /**
2824
+ * Owns the complete voice-input lifecycle. `finish` is safe to call from both
2825
+ * the microphone control and a form submit: concurrent calls share the same
2826
+ * transcription promise.
2827
+ */
2828
+ function useSpeechToText({ transcribe, onTranscriptionComplete, onTranscriptionError }) {
2829
+ const [status, setStatus] = useState("idle");
2830
+ const statusRef = useRef("idle");
2831
+ const operationIdRef = useRef(0);
2832
+ const pendingFinishRef = useRef(null);
2757
2833
  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"));
2834
+ const optionsRef = useRef({
2835
+ transcribe,
2836
+ onTranscriptionComplete,
2837
+ onTranscriptionError
2838
+ });
2839
+ optionsRef.current = {
2840
+ transcribe,
2841
+ onTranscriptionComplete,
2842
+ onTranscriptionError
2843
+ };
2844
+ const { start: startRecording, stop: stopRecording, cancel: cancelRecording } = useVoiceRecording();
2845
+ const updateStatus = useCallback((nextStatus) => {
2846
+ statusRef.current = nextStatus;
2847
+ setStatus(nextStatus);
2848
+ }, []);
2849
+ const start = useCallback(async () => {
2850
+ if (statusRef.current !== "idle" || pendingFinishRef.current) return;
2851
+ const operationId = operationIdRef.current + 1;
2852
+ operationIdRef.current = operationId;
2853
+ updateStatus("requesting");
2854
+ try {
2855
+ await startRecording();
2856
+ if (operationIdRef.current !== operationId) {
2857
+ cancelRecording();
2858
+ return;
2773
2859
  }
2774
- return;
2860
+ updateStatus("recording");
2861
+ } catch (error) {
2862
+ if (operationIdRef.current !== operationId) return;
2863
+ updateStatus("idle");
2864
+ optionsRef.current.onTranscriptionError?.(normalizeError(error, "Microphone access was denied"));
2775
2865
  }
2776
- setIsListening(false);
2777
- setIsTranscribing(true);
2866
+ }, [
2867
+ cancelRecording,
2868
+ startRecording,
2869
+ updateStatus
2870
+ ]);
2871
+ const finish = useCallback(() => {
2872
+ if (pendingFinishRef.current) return pendingFinishRef.current;
2873
+ if (statusRef.current !== "recording") return Promise.resolve(null);
2874
+ const operationId = operationIdRef.current;
2778
2875
  const abortController = new AbortController();
2779
2876
  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);
2877
+ updateStatus("transcribing");
2878
+ const pending = (async () => {
2879
+ try {
2880
+ const audio = await stopRecording();
2881
+ if (operationIdRef.current !== operationId) return null;
2882
+ const transcription = await optionsRef.current.transcribe(audio, abortController.signal);
2883
+ if (operationIdRef.current !== operationId) return null;
2884
+ const text$1 = transcription.trim();
2885
+ if (!text$1) return null;
2886
+ optionsRef.current.onTranscriptionComplete?.(text$1);
2887
+ return text$1;
2888
+ } catch (error) {
2889
+ if (operationIdRef.current !== operationId || abortController.signal.aborted || isAbortError(error)) return null;
2890
+ optionsRef.current.onTranscriptionError?.(normalizeError(error, "Transcription failed"));
2891
+ return null;
2892
+ } finally {
2893
+ pendingFinishRef.current = null;
2894
+ abortControllerRef.current = null;
2895
+ if (operationIdRef.current === operationId) updateStatus("idle");
2896
+ }
2897
+ })();
2898
+ pendingFinishRef.current = pending;
2899
+ return pending;
2900
+ }, [stopRecording, updateStatus]);
2901
+ const cancel = useCallback(() => {
2902
+ operationIdRef.current += 1;
2903
+ abortControllerRef.current?.abort();
2904
+ cancelRecording();
2905
+ updateStatus("idle");
2906
+ }, [cancelRecording, updateStatus]);
2907
+ const toggle = useCallback(async () => {
2908
+ if (statusRef.current === "idle") {
2909
+ await start();
2910
+ return null;
2789
2911
  }
2790
- }
2791
- const ariaLabel = isTranscribing ? loadingLabel : isListening ? listeningLabel : label;
2912
+ if (statusRef.current === "recording" || statusRef.current === "transcribing") return finish();
2913
+ return null;
2914
+ }, [finish, start]);
2915
+ useEffect(() => {
2916
+ return () => {
2917
+ operationIdRef.current += 1;
2918
+ abortControllerRef.current?.abort();
2919
+ cancelRecording();
2920
+ };
2921
+ }, [cancelRecording]);
2922
+ return useMemo(() => ({
2923
+ status,
2924
+ start,
2925
+ finish,
2926
+ cancel,
2927
+ toggle
2928
+ }), [
2929
+ cancel,
2930
+ finish,
2931
+ start,
2932
+ status,
2933
+ toggle
2934
+ ]);
2935
+ }
2936
+
2937
+ //#endregion
2938
+ //#region src/components/speech-to-text-toggle/speech-to-text-toggle.tsx
2939
+ async function missingTranscribe() {
2940
+ throw new Error("SpeechToTextToggle requires transcribe when no controller is provided.");
2941
+ }
2942
+ 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 }) {
2943
+ const internalController = useSpeechToText({
2944
+ transcribe: transcribe ?? missingTranscribe,
2945
+ onTranscriptionComplete,
2946
+ onTranscriptionError
2947
+ });
2948
+ const speechToText = controller ?? internalController;
2949
+ const isRequesting = speechToText.status === "requesting";
2950
+ const isListening = speechToText.status === "recording";
2951
+ const isTranscribing = speechToText.status === "transcribing";
2952
+ const cancelsRecording = isListening && cancelOnClickWhileRecording;
2953
+ const ariaLabel = isRequesting ? requestingLabel : isTranscribing ? loadingLabel : cancelsRecording ? cancelLabel : isListening ? listeningLabel : label;
2792
2954
  return /* @__PURE__ */ jsx(PromptFormIconButton, {
2793
2955
  type: "button",
2794
2956
  "aria-label": ariaLabel,
2795
2957
  "aria-pressed": isListening,
2796
- "aria-busy": isTranscribing,
2797
- disabled: disabled || isTranscribing,
2958
+ "aria-busy": isRequesting || isTranscribing,
2959
+ disabled: disabled || isRequesting || isTranscribing,
2798
2960
  className: joinClasses(isListening && !isTranscribing ? "text-red-600" : void 0, className),
2799
- onClick: () => {
2800
- handleToggle();
2961
+ onClick: (event) => {
2962
+ onClick?.(event);
2963
+ if (event.defaultPrevented) return;
2964
+ if (cancelsRecording) {
2965
+ speechToText.cancel();
2966
+ return;
2967
+ }
2968
+ speechToText.toggle();
2801
2969
  },
2802
2970
  ...props,
2803
- children: isTranscribing ? /* @__PURE__ */ jsx(Loader, { className: "size-4 animate-spin" }) : /* @__PURE__ */ jsx(Microphone, { className: "size-4" })
2971
+ 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
2972
  });
2805
2973
  }
2806
2974
 
@@ -2819,5 +2987,5 @@ async function dummyTranscribeAudio(_audio, signal) {
2819
2987
  }
2820
2988
 
2821
2989
  //#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 };
2990
+ 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, Thinking, 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
2991
  //# sourceMappingURL=index.js.map