crush-level-web/docs/URLTextParameter.md

3.2 KiB

URL Text 参数功能说明

功能概述

实现了从 URL 参数中获取 text 并自动填充到聊天输入框的功能。用户点击对话建议时,会跳转到聊天页面并自动填充对应的文本。

实现细节

1. StartChatItem 组件

文件位置: src/app/(main)/home/components/StartChat/StartChatItem.tsx

功能:

  • 对话建议列表中的每一项都是一个链接
  • 点击时跳转到聊天页面,并将建议文本作为 URL 参数传递
  • 使用 encodeURIComponent() 对文本进行编码,确保特殊字符正确传递

示例:

<Link 
  href={`/chat/${character.aiId}?text=${encodeURIComponent(suggestion)}`}
  className="..."
>
  <span>{suggestion}</span>
</Link>

2. ChatInput 组件

文件位置: src/app/(main)/chat/[aiId]/components/ChatMessageAction/ChatInput.tsx

功能:

  • 使用 useSearchParams() Hook 获取 URL 参数
  • 在组件挂载时检查是否有 text 参数
  • 如果有,自动填充到输入框并聚焦

实现代码:

const searchParams = useSearchParams();

useEffect(() => {
  const textFromUrl = searchParams.get('text');
  if (textFromUrl) {
    setMessage(textFromUrl);
    // 聚焦到输入框
    if (textareaRef.current) {
      textareaRef.current.focus();
    }
  }
}, [searchParams]);

使用场景

场景 1: 对话建议快捷回复

用户在首页看到 AI 角色的对话建议,点击后:

  1. 跳转到聊天页面
  2. 建议文本自动填充到输入框
  3. 用户可以直接发送或修改后发送

场景 2: 外部链接跳转

可以通过外部链接直接跳转到聊天页面并预填充文本:

https://your-domain.com/chat/123?text=Hello%20there!

URL 参数格式

  • 参数名: text
  • 编码方式: URL 编码 (使用 encodeURIComponent)
  • 示例:
    • 原始文本: How is your day ?
    • 编码后: How%20is%20your%20day%20%3F
    • 完整 URL: /chat/123?text=How%20is%20your%20day%20%3F

注意事项

  1. URL 编码: 必须使用 encodeURIComponent() 对文本进行编码,避免特殊字符导致 URL 解析错误
  2. 自动聚焦: 填充文本后会自动聚焦到输入框,提升用户体验
  3. 单次触发: URL 参数只在组件挂载或 searchParams 变化时读取一次
  4. 不影响现有功能: 如果 URL 中没有 text 参数,输入框保持原有行为

扩展建议

可能的增强功能:

  1. 清除 URL 参数: 填充文本后清除 URL 中的 text 参数,避免刷新页面时重复填充

    const router = useRouter();
    // 填充后清除参数
    router.replace(`/chat/${aiId}`, { scroll: false });
    
  2. 支持多个参数: 可以扩展支持其他参数,如 imagevoice

    /chat/123?text=Hello&image=https://...
    
  3. 参数验证: 添加文本长度限制和内容验证

    if (textFromUrl && textFromUrl.length <= 1000) {
      setMessage(textFromUrl);
    }
    

相关文件

  • src/app/(main)/home/components/StartChat/StartChatItem.tsx - 发起跳转的组件
  • src/app/(main)/chat/[aiId]/components/ChatMessageAction/ChatInput.tsx - 接收参数的组件
  • src/app/(main)/home/context/AudioPlayerContext.tsx - 音频播放上下文(相关功能)