sync update from LAN repo (source dhk-1 @ 3e87be55)
This commit is contained in:
1 parent
ab6068a7c1
commit
42f2a26fa8
1482 files changed
+227759
-9584
No files matched your search
@@ -18,7 +18,9 @@ import {
|
||||
} from "lucide-react";
|
||||
import type { ComponentProps, HTMLAttributes, ReactElement } from "react";
|
||||
import { createContext, memo, useContext, useEffect, useState } from "react";
|
||||
import { Streamdown } from "streamdown";
|
||||
import type { StreamdownProps } from "streamdown";
|
||||
|
||||
import { SafeStreamdown } from "@/core/streamdown";
|
||||
|
||||
export type MessageProps = HTMLAttributes<HTMLDivElement> & {
|
||||
from: UIMessage["role"];
|
||||
@@ -302,11 +304,11 @@ export const MessageBranchPage = ({
|
||||
);
|
||||
};
|
||||
|
||||
export type MessageResponseProps = ComponentProps<typeof Streamdown>;
|
||||
export type MessageResponseProps = StreamdownProps;
|
||||
|
||||
export const MessageResponse = memo(
|
||||
({ className, ...props }: MessageResponseProps) => (
|
||||
<Streamdown
|
||||
<SafeStreamdown
|
||||
className={cn(
|
||||
"size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",
|
||||
className,
|
||||
|
||||
@@ -34,9 +34,14 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import type { PromptInputFilePart } from "@/core/uploads";
|
||||
import { splitUnsupportedUploadFiles } from "@/core/uploads";
|
||||
import { isIMEComposing } from "@/lib/ime";
|
||||
import type { PromptInputFilePart, UploadPolicy } from "@/core/uploads";
|
||||
import {
|
||||
DEFAULT_UPLOAD_POLICY,
|
||||
splitUnsupportedUploadFiles,
|
||||
useUploadPolicy,
|
||||
validateChatUploadFiles,
|
||||
} from "@/core/uploads";
|
||||
import { imeEnterAction } from "@/lib/ime";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ChatStatus } from "ai";
|
||||
import {
|
||||
@@ -56,11 +61,12 @@ import {
|
||||
type ChangeEventHandler,
|
||||
Children,
|
||||
type ClipboardEventHandler,
|
||||
type ComponentProps,
|
||||
createContext,
|
||||
type FormEvent,
|
||||
type FormEventHandler,
|
||||
type HTMLAttributes,
|
||||
type ComponentProps,
|
||||
type CompositionEventHandler,
|
||||
createContext,
|
||||
type FormEvent,
|
||||
type FormEventHandler,
|
||||
type HTMLAttributes,
|
||||
type KeyboardEventHandler,
|
||||
type PropsWithChildren,
|
||||
type ReactNode,
|
||||
@@ -123,11 +129,11 @@ export const usePromptInputController = () => {
|
||||
return ctx;
|
||||
};
|
||||
|
||||
// Optional variants (do NOT throw). Useful for dual-mode components and for
|
||||
// Fast Refresh transitions where a page can briefly retain the previous
|
||||
// provider context instance.
|
||||
export const useOptionalPromptInputController = () =>
|
||||
useContext(PromptInputController);
|
||||
// Optional variants (do NOT throw). Useful for dual-mode components and for
|
||||
// Fast Refresh transitions where a page can briefly retain the previous
|
||||
// provider context instance.
|
||||
export const useOptionalPromptInputController = () =>
|
||||
useContext(PromptInputController);
|
||||
|
||||
export const useProviderAttachments = () => {
|
||||
const ctx = useContext(ProviderAttachmentsContext);
|
||||
@@ -145,6 +151,7 @@ const usePromptInputValidation = () => useContext(PromptInputValidationContext);
|
||||
|
||||
export type PromptInputProviderProps = PropsWithChildren<{
|
||||
initialInput?: string;
|
||||
uploadPolicy?: UploadPolicy;
|
||||
}>;
|
||||
|
||||
/**
|
||||
@@ -153,8 +160,12 @@ export type PromptInputProviderProps = PropsWithChildren<{
|
||||
*/
|
||||
export function PromptInputProvider({
|
||||
initialInput: initialTextInput = "",
|
||||
uploadPolicy,
|
||||
children,
|
||||
}: PromptInputProviderProps) {
|
||||
const { data: fetchedUploadPolicy } = useUploadPolicy();
|
||||
const effectiveUploadPolicy =
|
||||
uploadPolicy ?? fetchedUploadPolicy ?? DEFAULT_UPLOAD_POLICY;
|
||||
// ----- textInput state
|
||||
const [textInput, setTextInput] = useState(initialTextInput);
|
||||
const clearInput = useCallback(() => setTextInput(""), []);
|
||||
@@ -163,6 +174,7 @@ export function PromptInputProvider({
|
||||
const [attachmentFiles, setAttachmentFiles] = useState<
|
||||
(PromptInputFilePart & { id: string })[]
|
||||
>([]);
|
||||
const attachmentsRef = useRef(attachmentFiles);
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const openRef = useRef<() => void>(() => {});
|
||||
|
||||
@@ -172,9 +184,26 @@ export function PromptInputProvider({
|
||||
return;
|
||||
}
|
||||
|
||||
setAttachmentFiles((prev) =>
|
||||
prev.concat(
|
||||
incoming.map((file) => ({
|
||||
const current = attachmentsRef.current;
|
||||
const existing = current.map((item) => ({
|
||||
name: item.filename ?? "attachment",
|
||||
size: item.file?.size ?? 0,
|
||||
type: item.mediaType ?? "",
|
||||
}));
|
||||
const validation = validateChatUploadFiles(
|
||||
incoming,
|
||||
existing,
|
||||
effectiveUploadPolicy,
|
||||
);
|
||||
for (const message of new Set(
|
||||
validation.issues.map((issue) => issue.message),
|
||||
)) {
|
||||
toast.error(message);
|
||||
}
|
||||
if (validation.accepted.length === 0) return;
|
||||
|
||||
const next = current.concat(
|
||||
validation.accepted.map((file) => ({
|
||||
id: nanoid(),
|
||||
type: "file" as const,
|
||||
url: URL.createObjectURL(file),
|
||||
@@ -182,33 +211,31 @@ export function PromptInputProvider({
|
||||
filename: file.name,
|
||||
file,
|
||||
})),
|
||||
),
|
||||
);
|
||||
}, []);
|
||||
attachmentsRef.current = next;
|
||||
setAttachmentFiles(next);
|
||||
}, [effectiveUploadPolicy]);
|
||||
|
||||
const remove = useCallback((id: string) => {
|
||||
setAttachmentFiles((prev) => {
|
||||
const found = prev.find((f) => f.id === id);
|
||||
if (found?.url) {
|
||||
URL.revokeObjectURL(found.url);
|
||||
}
|
||||
return prev.filter((f) => f.id !== id);
|
||||
});
|
||||
const current = attachmentsRef.current;
|
||||
const found = current.find((f) => f.id === id);
|
||||
if (found?.url) URL.revokeObjectURL(found.url);
|
||||
const next = current.filter((f) => f.id !== id);
|
||||
attachmentsRef.current = next;
|
||||
setAttachmentFiles(next);
|
||||
}, []);
|
||||
|
||||
const clear = useCallback(() => {
|
||||
setAttachmentFiles((prev) => {
|
||||
for (const f of prev) {
|
||||
if (f.url) {
|
||||
URL.revokeObjectURL(f.url);
|
||||
}
|
||||
for (const f of attachmentsRef.current) {
|
||||
if (f.url) {
|
||||
URL.revokeObjectURL(f.url);
|
||||
}
|
||||
return [];
|
||||
});
|
||||
}
|
||||
attachmentsRef.current = [];
|
||||
setAttachmentFiles([]);
|
||||
}, []);
|
||||
|
||||
// Keep a ref to attachments for cleanup on unmount (avoids stale closure)
|
||||
const attachmentsRef = useRef(attachmentFiles);
|
||||
attachmentsRef.current = attachmentFiles;
|
||||
|
||||
// Cleanup blob URLs on unmount to prevent memory leaks
|
||||
@@ -404,14 +431,14 @@ export function PromptInputAttachments({
|
||||
return (
|
||||
<div
|
||||
className={cn("flex w-full flex-wrap items-center gap-2 p-3", className)}
|
||||
{...props}
|
||||
>
|
||||
{attachments.files.map((file) => (
|
||||
<div key={file.id} className="max-w-60">
|
||||
{children(file)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{...props}
|
||||
>
|
||||
{attachments.files.map((file) => (
|
||||
<div key={file.id} className="max-w-60">
|
||||
{children(file)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -459,8 +486,15 @@ export type PromptInputProps = Omit<
|
||||
// Minimal constraints
|
||||
maxFiles?: number;
|
||||
maxFileSize?: number; // bytes
|
||||
uploadPolicy?: UploadPolicy;
|
||||
onError?: (err: {
|
||||
code: "max_files" | "max_file_size" | "accept" | "unsupported_package";
|
||||
code:
|
||||
| "max_files"
|
||||
| "max_file_size"
|
||||
| "max_total_size"
|
||||
| "unsupported_type"
|
||||
| "accept"
|
||||
| "unsupported_package";
|
||||
message: string;
|
||||
}) => void;
|
||||
onSubmit: (
|
||||
@@ -478,11 +512,22 @@ export const PromptInput = ({
|
||||
syncHiddenInput,
|
||||
maxFiles,
|
||||
maxFileSize,
|
||||
uploadPolicy,
|
||||
onError,
|
||||
onSubmit,
|
||||
children,
|
||||
...props
|
||||
}: PromptInputProps) => {
|
||||
const { data: fetchedUploadPolicy } = useUploadPolicy();
|
||||
const effectiveUploadPolicy =
|
||||
uploadPolicy ?? fetchedUploadPolicy ?? DEFAULT_UPLOAD_POLICY;
|
||||
const policyAccept = useMemo(
|
||||
() =>
|
||||
Object.values(effectiveUploadPolicy.groups)
|
||||
.flatMap((group) => group.extensions)
|
||||
.join(","),
|
||||
[effectiveUploadPolicy],
|
||||
);
|
||||
// Try to use a provider controller if present
|
||||
const controller = useOptionalPromptInputController();
|
||||
const usingProvider = !!controller;
|
||||
@@ -517,6 +562,9 @@ export const PromptInput = ({
|
||||
.filter(Boolean);
|
||||
|
||||
return patterns.some((pattern) => {
|
||||
if (pattern.startsWith(".")) {
|
||||
return f.name.toLowerCase().endsWith(pattern.toLowerCase());
|
||||
}
|
||||
if (pattern.endsWith("/*")) {
|
||||
const prefix = pattern.slice(0, -1); // e.g: image/* -> image/
|
||||
return f.type.startsWith(prefix);
|
||||
@@ -531,52 +579,67 @@ export const PromptInput = ({
|
||||
(fileList: File[] | FileList) => {
|
||||
const incoming = Array.from(fileList);
|
||||
const accepted = incoming.filter((f) => matchesAccept(f));
|
||||
if (incoming.length && accepted.length === 0) {
|
||||
onError?.({
|
||||
if (accepted.length < incoming.length) {
|
||||
const error = {
|
||||
code: "accept",
|
||||
message: "No files match the accepted types.",
|
||||
});
|
||||
return;
|
||||
message: "部分文件不符合当前输入框允许的格式。",
|
||||
} as const;
|
||||
onError?.(error);
|
||||
if (!onError) toast.error(error.message);
|
||||
}
|
||||
const withinSize = (f: File) =>
|
||||
maxFileSize ? f.size <= maxFileSize : true;
|
||||
const sized = accepted.filter(withinSize);
|
||||
if (accepted.length > 0 && sized.length === 0) {
|
||||
onError?.({
|
||||
code: "max_file_size",
|
||||
message: "All files exceed the maximum size.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setItems((prev) => {
|
||||
const capacity =
|
||||
const localPolicy: UploadPolicy = {
|
||||
...effectiveUploadPolicy,
|
||||
max_files_per_message:
|
||||
typeof maxFiles === "number"
|
||||
? Math.max(0, maxFiles - prev.length)
|
||||
: undefined;
|
||||
const capped =
|
||||
typeof capacity === "number" ? sized.slice(0, capacity) : sized;
|
||||
if (typeof capacity === "number" && sized.length > capacity) {
|
||||
onError?.({
|
||||
code: "max_files",
|
||||
message: "Too many files. Some were not added.",
|
||||
});
|
||||
}
|
||||
const next: (PromptInputFilePart & { id: string })[] = [];
|
||||
for (const file of capped) {
|
||||
next.push({
|
||||
? Math.min(effectiveUploadPolicy.max_files_per_message, maxFiles)
|
||||
: effectiveUploadPolicy.max_files_per_message,
|
||||
groups: Object.fromEntries(
|
||||
Object.entries(effectiveUploadPolicy.groups).map(([key, group]) => [
|
||||
key,
|
||||
{
|
||||
...group,
|
||||
max_bytes:
|
||||
typeof maxFileSize === "number"
|
||||
? Math.min(group.max_bytes, maxFileSize)
|
||||
: group.max_bytes,
|
||||
},
|
||||
]),
|
||||
) as UploadPolicy["groups"],
|
||||
};
|
||||
const existing = items.map((item) => ({
|
||||
name: item.filename ?? "attachment",
|
||||
size: item.file?.size ?? 0,
|
||||
type: item.mediaType ?? "",
|
||||
}));
|
||||
const validation = validateChatUploadFiles(
|
||||
accepted,
|
||||
existing,
|
||||
localPolicy,
|
||||
);
|
||||
for (const issue of Array.from(
|
||||
new Map(
|
||||
validation.issues.map((item) => [item.message, item]),
|
||||
).values(),
|
||||
)) {
|
||||
onError?.({ code: issue.code, message: issue.message });
|
||||
if (!onError) toast.error(issue.message);
|
||||
}
|
||||
if (validation.accepted.length === 0) return;
|
||||
|
||||
setItems((prev) =>
|
||||
prev.concat(
|
||||
validation.accepted.map((file) => ({
|
||||
id: nanoid(),
|
||||
type: "file",
|
||||
type: "file" as const,
|
||||
url: URL.createObjectURL(file),
|
||||
mediaType: file.type,
|
||||
filename: file.name,
|
||||
file,
|
||||
});
|
||||
}
|
||||
return prev.concat(next);
|
||||
});
|
||||
})),
|
||||
),
|
||||
);
|
||||
},
|
||||
[matchesAccept, maxFiles, maxFileSize, onError],
|
||||
[effectiveUploadPolicy, items, matchesAccept, maxFiles, maxFileSize, onError],
|
||||
);
|
||||
|
||||
const removeLocal = useCallback(
|
||||
@@ -765,11 +828,17 @@ export const PromptInput = ({
|
||||
event.preventDefault();
|
||||
|
||||
const form = event.currentTarget;
|
||||
// Prefer the live textarea. Firefox 102 applies the chosen candidate to
|
||||
// the DOM before React state catches up, and a send click in that gap
|
||||
// would otherwise submit the previous pinyin-less value.
|
||||
const liveText = form.querySelector<HTMLTextAreaElement>(
|
||||
"textarea[name='message']",
|
||||
)?.value;
|
||||
const text = usingProvider
|
||||
? controller.textInput.value
|
||||
? (liveText ?? controller.textInput.value)
|
||||
: (() => {
|
||||
const formData = new FormData(form);
|
||||
return (formData.get("message") as string) || "";
|
||||
return (formData.get("message") as string) || liveText || "";
|
||||
})();
|
||||
|
||||
// Reset form immediately after capturing text to avoid race condition
|
||||
@@ -832,7 +901,7 @@ export const PromptInput = ({
|
||||
const inner = (
|
||||
<PromptInputValidationContext.Provider value={sanitizeIncomingFiles}>
|
||||
<input
|
||||
accept={accept}
|
||||
accept={accept ?? policyAccept}
|
||||
aria-label="Upload files"
|
||||
className="hidden"
|
||||
multiple={multiple}
|
||||
@@ -847,10 +916,12 @@ export const PromptInput = ({
|
||||
ref={formRef}
|
||||
{...props}
|
||||
>
|
||||
{/* Do not rely on InputGroup's :has(textarea) selector here: Chrome
|
||||
versions before 105 ignore :has(), retain h-9, and clip the whole
|
||||
multi-line composer to a single row. */}
|
||||
<InputGroup className="h-auto min-h-16">{children}</InputGroup>
|
||||
{/* Do not rely on InputGroup's :has() selectors here: Chrome versions
|
||||
before 105 ignore them, keep the horizontal flex layout, and
|
||||
squeeze the textarea beside the footer controls. */}
|
||||
<InputGroup className="h-auto min-h-16 flex-col items-stretch">
|
||||
{children}
|
||||
</InputGroup>
|
||||
</form>
|
||||
</PromptInputValidationContext.Provider>
|
||||
);
|
||||
@@ -877,58 +948,100 @@ export type PromptInputTextareaProps = ComponentProps<
|
||||
typeof InputGroupTextarea
|
||||
>;
|
||||
|
||||
export const PromptInputTextarea = ({
|
||||
onChange,
|
||||
onInput,
|
||||
className,
|
||||
placeholder = "What would you like to know?",
|
||||
...props
|
||||
}: PromptInputTextareaProps) => {
|
||||
const controller = useOptionalPromptInputController();
|
||||
const attachments = usePromptInputAttachments();
|
||||
const sanitizeIncomingFiles = usePromptInputValidation();
|
||||
const [isComposing, setIsComposing] = useState(false);
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
|
||||
const resizeForLegacyChrome = useCallback((textarea: HTMLTextAreaElement) => {
|
||||
if (
|
||||
typeof CSS !== "undefined" &&
|
||||
typeof CSS.supports === "function" &&
|
||||
CSS.supports("field-sizing", "content")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Chrome 109 ignores field-sizing: content. Preserve the same 4rem–12rem
|
||||
// autosize range used by min-h-16/max-h-48 instead of leaving the prompt
|
||||
// stuck at its minimum height.
|
||||
textarea.style.height = "auto";
|
||||
const height = Math.max(64, Math.min(textarea.scrollHeight, 192));
|
||||
textarea.style.height = `${height}px`;
|
||||
textarea.style.overflowY = textarea.scrollHeight > 192 ? "auto" : "hidden";
|
||||
}, []);
|
||||
|
||||
// onInput does not run for a controlled value filled by a suggested question
|
||||
// or restored draft. Resize once after every render in legacy Chrome too.
|
||||
useEffect(() => {
|
||||
const textarea = textareaRef.current;
|
||||
if (!textarea) return;
|
||||
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
resizeForLegacyChrome(textarea);
|
||||
});
|
||||
return () => window.cancelAnimationFrame(frame);
|
||||
}, [controller?.textInput.value, resizeForLegacyChrome]);
|
||||
export const PromptInputTextarea = ({
|
||||
onChange,
|
||||
onInput,
|
||||
onKeyDown,
|
||||
onCompositionStart,
|
||||
onCompositionEnd,
|
||||
className,
|
||||
placeholder = "What would you like to know?",
|
||||
defaultValue,
|
||||
...props
|
||||
}: PromptInputTextareaProps) => {
|
||||
const controller = useOptionalPromptInputController();
|
||||
const attachments = usePromptInputAttachments();
|
||||
const sanitizeIncomingFiles = usePromptInputValidation();
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
const composingRef = useRef(false);
|
||||
const compositionEndedAtRef = useRef(0);
|
||||
const onChangeRef = useRef(onChange);
|
||||
const onInputRef = useRef(onInput);
|
||||
const onKeyDownRef = useRef(onKeyDown);
|
||||
const onCompositionStartRef = useRef(onCompositionStart);
|
||||
const onCompositionEndRef = useRef(onCompositionEnd);
|
||||
const setInputRef = useRef(controller?.textInput.setInput);
|
||||
const attachmentsRef = useRef(attachments);
|
||||
onChangeRef.current = onChange;
|
||||
onInputRef.current = onInput;
|
||||
onKeyDownRef.current = onKeyDown;
|
||||
onCompositionStartRef.current = onCompositionStart;
|
||||
onCompositionEndRef.current = onCompositionEnd;
|
||||
setInputRef.current = controller?.textInput.setInput;
|
||||
attachmentsRef.current = attachments;
|
||||
|
||||
const publishValue = useCallback((value: string) => {
|
||||
setInputRef.current?.(value);
|
||||
}, []);
|
||||
|
||||
const resizeForLegacyChrome = useCallback((textarea: HTMLTextAreaElement) => {
|
||||
// Firefox 102 commits an open IME composition as raw pinyin when the
|
||||
// textarea's height or overflow changes mid-composition.
|
||||
if (composingRef.current) return;
|
||||
if (
|
||||
typeof CSS !== "undefined" &&
|
||||
typeof CSS.supports === "function" &&
|
||||
CSS.supports("field-sizing", "content")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Chrome 109 ignores field-sizing: content. Preserve the same 4rem–12rem
|
||||
// autosize range used by min-h-16/max-h-48 instead of leaving the prompt
|
||||
// stuck at its minimum height.
|
||||
textarea.style.height = "auto";
|
||||
const height = Math.max(64, Math.min(textarea.scrollHeight, 192));
|
||||
textarea.style.height = `${height}px`;
|
||||
textarea.style.overflowY = textarea.scrollHeight > 192 ? "auto" : "hidden";
|
||||
}, []);
|
||||
|
||||
// onInput does not run for a controlled value filled by a suggested question
|
||||
// or restored draft. Resize once after every render in legacy Chrome too.
|
||||
useEffect(() => {
|
||||
if (composingRef.current) return;
|
||||
const textarea = textareaRef.current;
|
||||
if (!textarea) return;
|
||||
|
||||
const frame = window.requestAnimationFrame(() => {
|
||||
resizeForLegacyChrome(textarea);
|
||||
});
|
||||
return () => window.cancelAnimationFrame(frame);
|
||||
}, [controller?.textInput.value, resizeForLegacyChrome]);
|
||||
|
||||
const handleKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = (e) => {
|
||||
if (e.key === "Enter") {
|
||||
if (isIMEComposing(e, isComposing)) {
|
||||
const action = imeEnterAction({
|
||||
isComposing: composingRef.current,
|
||||
nativeIsComposing: e.nativeEvent.isComposing || e.key === "Process",
|
||||
keyCode: e.keyCode,
|
||||
compositionEndedAt: compositionEndedAtRef.current,
|
||||
now: performance.now(),
|
||||
});
|
||||
// Firefox 102 confirms the candidate on this key. preventDefault here
|
||||
// cancels that confirmation and leaves the pinyin in the box.
|
||||
if (action === "ignore") {
|
||||
return;
|
||||
}
|
||||
if (e.shiftKey) {
|
||||
onKeyDownRef.current?.(e);
|
||||
if (e.defaultPrevented || e.shiftKey) {
|
||||
return;
|
||||
}
|
||||
// The confirming Enter already finished the candidate. Swallow it so
|
||||
// Firefox does not also insert a newline or send the message.
|
||||
e.preventDefault();
|
||||
if (action === "swallow") {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if the submit button is disabled before submitting
|
||||
const form = e.currentTarget.form;
|
||||
@@ -940,22 +1053,59 @@ export const PromptInputTextarea = ({
|
||||
}
|
||||
|
||||
form?.requestSubmit();
|
||||
return;
|
||||
}
|
||||
|
||||
onKeyDownRef.current?.(e);
|
||||
if (e.defaultPrevented) return;
|
||||
|
||||
if (composingRef.current) return;
|
||||
|
||||
// Remove last attachment when Backspace is pressed and textarea is empty
|
||||
if (
|
||||
e.key === "Backspace" &&
|
||||
e.currentTarget.value === "" &&
|
||||
attachments.files.length > 0
|
||||
attachmentsRef.current.files.length > 0
|
||||
) {
|
||||
e.preventDefault();
|
||||
const lastAttachment = attachments.files.at(-1);
|
||||
const lastAttachment = attachmentsRef.current.files.at(-1);
|
||||
if (lastAttachment) {
|
||||
attachments.remove(lastAttachment.id);
|
||||
attachmentsRef.current.remove(lastAttachment.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleCompositionStart: CompositionEventHandler<HTMLTextAreaElement> = (
|
||||
event,
|
||||
) => {
|
||||
composingRef.current = true;
|
||||
compositionEndedAtRef.current = 0;
|
||||
onCompositionStartRef.current?.(event);
|
||||
};
|
||||
|
||||
const handleCompositionEnd: CompositionEventHandler<HTMLTextAreaElement> = (
|
||||
event,
|
||||
) => {
|
||||
onCompositionEndRef.current?.(event);
|
||||
composingRef.current = false;
|
||||
compositionEndedAtRef.current = performance.now();
|
||||
const el = event.currentTarget;
|
||||
// Firefox 102 dispatches compositionend before the committed candidate is
|
||||
// visible, and before the input event that carries it. Syncing the
|
||||
// compositionend value here would write the raw pinyin back over 汉字.
|
||||
window.setTimeout(() => {
|
||||
if (el.isConnected) publishValue(el.value);
|
||||
}, 0);
|
||||
};
|
||||
|
||||
const handleChange: ChangeEventHandler<HTMLTextAreaElement> = (event) => {
|
||||
// Keep the controlled value identical to the DOM, including the pinyin
|
||||
// still being composed. Otherwise React restores the previous value at
|
||||
// the end of the input event and Firefox 102 cannot replace it.
|
||||
publishValue(event.currentTarget.value);
|
||||
onChangeRef.current?.(event);
|
||||
};
|
||||
|
||||
const handlePaste: ClipboardEventHandler<HTMLTextAreaElement> = (event) => {
|
||||
const items = event.clipboardData?.items;
|
||||
|
||||
@@ -985,35 +1135,28 @@ export const PromptInputTextarea = ({
|
||||
}
|
||||
};
|
||||
|
||||
const controlledProps = controller
|
||||
? {
|
||||
value: controller.textInput.value,
|
||||
onChange: (e: ChangeEvent<HTMLTextAreaElement>) => {
|
||||
controller.textInput.setInput(e.currentTarget.value);
|
||||
onChange?.(e);
|
||||
},
|
||||
}
|
||||
: {
|
||||
onChange,
|
||||
};
|
||||
|
||||
return (
|
||||
<InputGroupTextarea
|
||||
className={cn("field-sizing-content max-h-48 min-h-16", className)}
|
||||
name="message"
|
||||
ref={textareaRef}
|
||||
rows={3}
|
||||
onCompositionEnd={() => setIsComposing(false)}
|
||||
onCompositionStart={() => setIsComposing(true)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onInput={(event) => {
|
||||
resizeForLegacyChrome(event.currentTarget);
|
||||
onInput?.(event);
|
||||
}}
|
||||
<InputGroupTextarea
|
||||
{...props}
|
||||
className={cn("field-sizing-content max-h-48 min-h-16", className)}
|
||||
name="message"
|
||||
ref={textareaRef}
|
||||
rows={3}
|
||||
onChange={handleChange}
|
||||
onCompositionEnd={handleCompositionEnd}
|
||||
onCompositionStart={handleCompositionStart}
|
||||
onKeyDown={handleKeyDown}
|
||||
onInput={(event) => {
|
||||
if (!composingRef.current) {
|
||||
resizeForLegacyChrome(event.currentTarget);
|
||||
}
|
||||
onInputRef.current?.(event);
|
||||
}}
|
||||
onPaste={handlePaste}
|
||||
placeholder={placeholder}
|
||||
{...props}
|
||||
{...controlledProps}
|
||||
{...(controller
|
||||
? { value: controller.textInput.value }
|
||||
: { defaultValue })}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -1131,20 +1274,24 @@ export const PromptInputSubmit = ({
|
||||
status,
|
||||
children,
|
||||
...props
|
||||
}: PromptInputSubmitProps) => {
|
||||
let Icon = <ArrowUpIcon className="size-4" />;
|
||||
|
||||
if (status === "submitted") {
|
||||
Icon = <Loader2Icon className="size-4 animate-spin" />;
|
||||
} else if (status === "streaming") {
|
||||
Icon = <SquareIcon className="size-4" />;
|
||||
} else if (status === "error") {
|
||||
Icon = <XIcon className="size-4" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<InputGroupButton
|
||||
aria-label="Submit"
|
||||
}: PromptInputSubmitProps) => {
|
||||
let Icon = <ArrowUpIcon className="size-4" />;
|
||||
let ariaLabel = "发送消息";
|
||||
|
||||
if (status === "submitted") {
|
||||
Icon = <Loader2Icon className="size-4 animate-spin" />;
|
||||
ariaLabel = "正在发送";
|
||||
} else if (status === "streaming") {
|
||||
Icon = <SquareIcon className="size-4" />;
|
||||
ariaLabel = "停止生成";
|
||||
} else if (status === "error") {
|
||||
Icon = <XIcon className="size-4" />;
|
||||
ariaLabel = "重新发送";
|
||||
}
|
||||
|
||||
return (
|
||||
<InputGroupButton
|
||||
aria-label={ariaLabel}
|
||||
className={cn(
|
||||
"transition-all duration-300",
|
||||
status === "streaming" &&
|
||||
|
||||
@@ -10,7 +10,7 @@ import { cn } from "@/lib/utils";
|
||||
import { BrainIcon, ChevronDownIcon } from "lucide-react";
|
||||
import type { ComponentProps, ReactNode } from "react";
|
||||
import { createContext, memo, useContext, useEffect, useState } from "react";
|
||||
import { Streamdown } from "streamdown";
|
||||
import { SafeStreamdown } from "@/core/streamdown";
|
||||
import { reasoningPlugins } from "@/core/streamdown/plugins";
|
||||
import { Shimmer } from "./shimmer";
|
||||
|
||||
@@ -179,7 +179,7 @@ export const ReasoningContent = memo(
|
||||
{...props}
|
||||
>
|
||||
{typeof children === "string" ? (
|
||||
<Streamdown {...reasoningPlugins}>{children}</Streamdown>
|
||||
<SafeStreamdown {...reasoningPlugins}>{children}</SafeStreamdown>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
|
||||
Reference in new issue
Block a user