AI 组件

聊天输入框

用于 AI 聊天场景下的输入框

使用场景

在 AI 聊天场景下,用户可通过 AIChatInput实现富文本输入、上传、引用、建议、模版、功能配置、及丰富自定义展示等需求。

AIChatInput 的富文本输入是基于 tiptap 实现,tiptap 是一款现代的富文本编辑器开发框架,支持 React、Vue 前端框架,具备极强的可定制性和扩展性。其组件化能力优秀,性能优良,内置多种常用拓展,并支持用户自定义节点、命令、插件与菜单,使复杂 AI 场景下的富文本输入能力能够灵活适配和扩展。Semi 的 AIChatInput 组件对 tiptap 进行了封装,开发者可开箱即用或按需按业务扩展。

代码演示

如何引入

<script lang="ts">
    import { AIChatInput } from '@fibrae/semi-ai-svelte';
</script>

基本用法

支持文本输入以及文件上传,使用时可按需配置以下参数:

  • uploadProps 配置文件上传相关的参数,取值同 Upload 的属性,不含 fileList、listType 与 children;初始附件用 uploadProps.defaultFileList
  • onUploadChange 获取文件上传变化
  • 删除上传文件时,会调用 uploadProps.onRemove,并遵循 uploadProps.beforeRemove(支持 Promise)
  • placeholder 输入框的占位符
  • defaultContent 输入框的默认内容
  • onContentChange 输入框内容变化时的回调函数,参数为当前输入框的内容
代码
<script lang="ts">
    import { AIChatInput, type AIChatInputContent as Content } from '@fibrae/semi-ai-svelte';
    import type { UploadOnChangeProps as OnChangeProps } from '@fibrae/semi-ui-svelte';

    const uploadProps = { action: 'https://api.semi.design/upload' };

    const onContentChange = (content: Content[]) => {
        console.log('onContentChange', content);
    };

    const onUploadChange = (fileList: OnChangeProps) => {
        console.log('onUploadChange', fileList);
    };
</script>

<AIChatInput {onContentChange} {onUploadChange} placeholder="输入内容或者上传内容..." style="margin: 12px" {uploadProps} />

消息发送

当输入框中有内容(包括输入文本、上传内容),将允许发送消息。点击消息发送按钮,会调用 onMessageSend,参数为当前输入框的内容,包括输入区域的文本,引用内容,上传文件,配置区域内容。引用内容不参与是否可发送的判断,也可通过 canSend 直接指定。

用户可在 onMessageSend 中根据判断是否设置 generating 表示消息正在处理中,如果 generating 为 true,则 AIChatInput 会在发送按钮位置显示停止生成按钮,并清空输入区的消息,以及上传文件,另外,引用内容需要用户自行清除。

点击停止生成按钮,会调用 onStopGenerate,用户可在该回调中处理停止生成的逻辑, 如将 generating 设为 false。

dy.jpeg
jpeg 130kb
resso.jpeg
jpeg 222kb
代码
<script lang="ts">
    import { AIChatInput, type AIChatInputContent as Content, type AIChatInputReference as Reference, type AIChatInputUploadProps } from '@fibrae/semi-ai-svelte';
    import type { UploadOnChangeProps } from '@fibrae/semi-ui-svelte';

    const uploadProps: AIChatInputUploadProps = {
        action: 'https://api.semi.design/upload',
        defaultFileList: [
            {
                uid: '1',
                name: 'dy.jpeg',
                status: 'success',
                size: '130kb',
                url: '/assets/placeholder/avatar-a.svg',
            },
            {
                uid: '5',
                name: 'resso.jpeg',
                status: 'uploading',
                percent: 50,
                size: '222kb',
                url: '/assets/placeholder/avatar-b.svg',
            },
        ],
    };

    let references = $state<Reference[]>([
        {
            id: '1',
            type: 'text',
            content: '测试文本,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字',
        },
    ]);
    let generating = $state(false);

    const onContentChange = (content: Content[]) => {
        console.log('onContentChange', content);
    };

    const onUploadChange = (fileList: UploadOnChangeProps) => {
        console.log('onUploadChange', fileList);
    };

    const toggleGenerate = () => {
        generating = !generating;
    };

    const onMessageSend = () => {
        toggleGenerate();
        references = [];
    };

    const handleReferenceDelete = (item: Reference) => {
        references = references.filter((ref) => ref.id !== item.id);
    };
</script>

<AIChatInput defaultContent="点击发送按钮,观察上传内容、引用内容、输入框内容变化" {generating} {onContentChange} {onMessageSend} onReferenceDelete={handleReferenceDelete} onStopGenerate={toggleGenerate} {onUploadChange} {references} style="margin: 12px" {uploadProps} />

富文本输入区

AIChatInput 使用 tiptap 作为富文本输入框的编辑器,用户可以在输入框中输入文本,使用 AIChatInput 内置的 extensions(包括 input-slot,select-slot,skill-slot)。用户也可以自定义 extensions 来扩展编辑器的功能。

  • input-slot 支持用户输入文本,并支持 placeholder 占位符。
  • select-slot 支持用户进行简单的选择,选项仅支持 string 类型。
  • skill-slot 是用于技能展示的块,方便用户理解当前输入框中的技能。

可以通过组件实例(bind:this)的 setContent 方法来设置输入框的内容,使用 focusEditor 方法可以将输入框的焦点设置到编辑器中。

代码
<script lang="ts">
    import { AIChatInput } from '@fibrae/semi-ai-svelte';

    const uploadProps = { action: 'https://api.semi.design/upload' };
    const temp = {
        'input-slot': '我是一个<input-slot placeholder="[职业]">程序员</input-slot>',
        'select-slot': `我是<select-slot value="前端开发" options='["设计","前端开发","后端开发"]'></select-slot>,帮我完成...`,
        'skill-slot': `<skill-slot data-label="AI Coding" data-value="AI Coding" data-template=false></skill-slot> 帮我完成...`,
    };
    const names = Object.keys(temp);
    const contents = Object.values(temp);

    let activeIndex = $state(0);
    let input = $state<ReturnType<typeof AIChatInput>>();

    const setTemplate = (index: number) => {
        activeIndex = index;
        input?.setContent(contents[index]);
        input?.focusEditor();
    };
</script>

<div class="aiChatInput-radio" role="tablist">
    {#each names as item, index (item)}
        <div
            aria-selected={index === activeIndex}
            class={['aiChatInput-radio-item', { 'aiChatInput-radio-item-selected': index === activeIndex }]}
            role="tab"
            tabindex="0"
            onclick={() => setTemplate(index)}
            onkeydown={(event) => {
                if (event.key === 'Enter') {
                    setTemplate(index);
                }
            }}
        >
            {item}
        </div>
    {/each}
</div>
<AIChatInput bind:this={input} defaultContent={temp['input-slot']} placeholder="输入内容或者上传内容" style="margin: 12px" {uploadProps} />

引用

用户可以 references 传入引用内容,引用内容会展示在输入框的顶部。

  • reference snippet 自定义单个引用内容的渲染,参数为 { item, index }。
  • onReferenceDelete 处理引用内容的删除。
  • onReferenceClick 处理引用内容的点击。
代码
<script lang="ts">
    import { AIChatInput, type AIChatInputReference as Reference } from '@fibrae/semi-ai-svelte';

    const uploadProps = { action: 'https://api.semi.design/upload' };
    let references = $state<Reference[]>([
        {
            id: '1',
            type: 'text',
            content: '测试文本,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字,这里是一段很长的文字',
        },
        {
            id: '2',
            name: '飞书文档.docx',
        },
        {
            id: '3',
            name: '飞书文档.pdf',
        },
        {
            id: '4',
            name: 'Music.mp4',
        },
        {
            id: '5',
            name: 'Image.jpeg',
            url: '/assets/placeholder/avatar-b.svg',
        },
        {
            id: '6',
            name: 'code.json',
        },
    ]);

    const handleReferenceDelete = (item: Reference) => {
        references = references.filter((ref) => ref.id !== item.id);
    };

    const handleReferenceClick = (item: Reference) => {
        console.log('点击了引用', item);
    };
</script>

<AIChatInput onReferenceClick={handleReferenceClick} onReferenceDelete={handleReferenceDelete} placeholder="用于查看引用内容的用例" {references} style="margin: 12px" {uploadProps} />

配置区域

用户可以通过配置区域设置使用模型参数、联网搜索、深度思考等配置项,展示或者查看 MCP 工具。

可通过 configureArea snippet 自定义输入框的操作按钮。

使用 AIChatInput.Configure 中的 Select、Button、Mcp、RadioButton 等组件可以自定义配置项。

AIChatInput 将管理配置项的状态,用户可以通过 onConfigureChange 监听配置项的变化。一定要配置 field 属性,用于标识配置项的唯一标识。如需设置初始值,可通过 initValue 属性设置。配置项自身的值变化也可通过 onChange 监听,参数为该项的新值。

如果用户有其他形式的配置需求,可以通过 AIChatInput.Configure.Item 把自定义组件扩展成配置项。

代码
<script lang="ts">
    import type { Component } from 'svelte';
    import { AIChatInput, type AIChatInputLeftMenuChangeProps as LeftMenuChangeProps } from '@fibrae/semi-ai-svelte';
    import { IconBookOpenStroked, IconFeishuLogo, IconFigma, IconGit } from '@fibrae/semi-icons-svelte';

    const { Configure } = AIChatInput;
    const uploadProps = { action: 'https://api.semi.design/upload' };

    const modelOptions = [
        { value: 'GPT-5', label: 'GPT-5' },
        { value: 'GPT-4o', label: 'GPT-4o' },
        { value: 'Claude 3.5 Sonnet', label: 'Claude 3.5 Sonnet' },
    ];

    const mcpOptions = [
        { label: '飞书文档', value: 'feishu' },
        { label: 'Github Mcp', value: 'github' },
        { label: 'IconFigma Mcp', value: 'IconFigma' },
    ];
    const mcpIcons: Record<string, Component> = { feishu: IconFeishuLogo, github: IconGit, IconFigma };

    const radioButtonProps = [
        { label: '极速', value: 'fast' },
        { label: '思考', value: 'think' },
        { label: '超能', value: 'super' },
    ];

    const onConfigureButtonClick = () => {
        console.log('onConfigureButtonClick');
    };

    const onConfigureChange = (value: LeftMenuChangeProps, changedValue?: LeftMenuChangeProps) => {
        console.log('onConfigureChange', value, changedValue);
    };
</script>

<AIChatInput {onConfigureChange} placeholder="用于查看左下方配置项的用例" style="margin: 12px" {uploadProps}>
    {#snippet configureArea()}
        <Configure.Select field="model" initValue="GPT-4o" optionList={modelOptions} />
        <Configure.Button field="onlineSearch">
            {#snippet icon()}
                <IconBookOpenStroked />
            {/snippet}
            联网搜索
        </Configure.Button>
        <Configure.Mcp {onConfigureButtonClick} options={mcpOptions} showConfigure>
            {#snippet optionIcon({ item })}
                {@const Icon = mcpIcons[item.value]}
                <Icon />
            {/snippet}
        </Configure.Mcp>
        <Configure.RadioButton field="thinkType" initValue="fast" options={radioButtonProps} />
    {/snippet}
</AIChatInput>

使用 getConfigureItem 扩展自定义组件为 Configure 类型组件。

interface ConfigureItemProps {
    // 被包装的组件:接收配置项的值,并报告变化
    component: Component<any>;
    // 配置项在 AIChatInput 配置值中的 key,必填
    field: string;
    // 配置项挂载时写入的初始值
    initValue?: unknown;
    // 接收值的 prop,默认是 value
    valueKey?: string;
    // 值变化的回调对应的 prop,默认是 onChange
    changeKey?: string;
    // 回调第一个参数中值所在的路径,默认参数本身就是值
    valuePath?: string;
    // 配置项的基础类名,与 class 合并
    baseClass?: ClassValue;
    // 传给被包装组件的默认属性,其余属性覆盖它
    defaultProps?: Record<string, unknown>;
    // 该项的值变化时调用,参数为新值
    onChange?: (value: any) => void;
    // 其余属性原样传给被包装组件
    [key: string]: unknown;
}

<AIChatInput.Configure.Item component={Cascader} field="model" /> 把任意接收值和变化回调的组件变成配置项。被包装组件自己的 onChange 不会收到调用,该项的值变化由 Configure.Item 的 onChange 收到。

使用示例如下:

代码
<script lang="ts">
    import { AIChatInput, type AIChatInputLeftMenuChangeProps as LeftMenuChangeProps } from '@fibrae/semi-ai-svelte';
    import { Cascader } from '@fibrae/semi-ui-svelte';

    const uploadProps = { action: 'https://api.semi.design/upload' };
    const cascaderModalOptions = [
        {
            label: 'GPT',
            value: 'GPT',
            children: [
                { label: 'GPT-4o', value: 'GPT-4o' },
                { value: 'GPT-5', label: 'GPT-5' },
            ],
        },
        {
            label: 'Claude',
            value: 'Claude',
            children: [{ label: 'Claude 3.5 Sonnet', value: 'Claude 3.5 Sonnet' }],
        },
    ];

    const onConfigureChange = (value: LeftMenuChangeProps, changedValue?: LeftMenuChangeProps) => {
        console.log('onConfigureChange', value, changedValue);
    };
</script>

<AIChatInput {onConfigureChange} placeholder="用于查看左下方配置项的用例" style="margin: 12px" {uploadProps}>
    {#snippet configureArea()}
        <AIChatInput.Configure.Item baseClass="aiChatInput-cascader-configure" component={Cascader} field="model" initValue={['GPT', 'GPT-4o']} treeData={cascaderModalOptions} />
    {/snippet}
</AIChatInput>

操作区域

输入框右下角为操作区域,用户可以通过 actionArea snippet 自定义操作区域,展示自定义的操作按钮。upload 是上传节点(showUploadButton 为 false 时是隐藏的 Upload,仍需渲染才能粘贴上传),send 是发送或停止按钮,都是 snippet,用 {@render} 渲染。

import type { Snippet } from 'svelte';

interface AIChatInputActionAreaSnippetProps {
    upload: Snippet;
    send: Snippet;
    class: string;
}

使用示例如下:

代码
<script lang="ts">
    import { AIChatInput } from '@fibrae/semi-ai-svelte';
    import { IconDeleteStroked } from '@fibrae/semi-icons-svelte';
    import { Button, Divider } from '@fibrae/semi-ui-svelte';

    const uploadProps = { action: 'https://api.semi.design/upload' };
</script>

<AIChatInput placeholder="输入内容或者上传内容..." style="margin: 12px" {uploadProps}>
    {#snippet actionArea({ upload, send, class: actionClass })}
        <div class={actionClass}>
            <div style="display: flex; align-items: center">
                <Button aria-label="清空内容" style="border-radius: 50%" type="tertiary">
                    {#snippet icon()}
                        <IconDeleteStroked />
                    {/snippet}
                </Button>
                <Divider layout="vertical" style="margin-left: 8px" />
            </div>
            {@render upload()}
            {@render send()}
        </div>
    {/snippet}
</AIChatInput>

自定义上传按钮

底部操作区左侧默认会渲染上传按钮。你可以通过 uploadButton snippet 仅自定义按钮 UI(例如改成图标按钮、加 Tooltip 等)。

注意:这不会影响上传/粘贴上传逻辑(Upload 仍由组件内部托管),onOpenFileDialog 会触发内部 Upload 的文件选择。点击事件冒泡到 Upload 时它自己会打开文件选择,自定义内容阻止了冒泡时才需要调用 onOpenFileDialog。

import type { Snippet } from 'svelte';

interface AIChatInputUploadButtonSnippetProps {
    // 默认的按钮内容,是 snippet,用 {@render defaultNode()} 渲染
    defaultNode: Snippet;
    onOpenFileDialog: () => void;
    disabled: boolean;
    attachments: Attachment[];
}
代码
<script lang="ts">
    import { AIChatInput } from '@fibrae/semi-ai-svelte';
    import { IconUpload } from '@fibrae/semi-icons-svelte';

    const uploadProps = { action: 'https://api.semi.design/upload' };

    // Upload opens the dialog on a click that reaches it; stopping the click here opens it once, from the callback
    const open = (event: MouseEvent, onOpenFileDialog: () => void) => {
        event.stopPropagation();
        onOpenFileDialog();
    };
</script>

<AIChatInput placeholder="自定义上传按钮(仍支持粘贴上传)" style="margin: 12px" {uploadProps}>
    {#snippet uploadButton({ onOpenFileDialog, disabled })}
        <button aria-label="上传" class="semi-button semi-button-borderless" {disabled} type="button" onclick={(event) => open(event, onOpenFileDialog)}>
            <IconUpload />
        </button>
    {/snippet}
</AIChatInput>

底部按钮形状

用户可以通过 round API 配置底部按钮的形状,默认是 true,是圆角按钮, 可以设置为 false 来配置为方形按钮。

代码
<script lang="ts">
    import type { Component } from 'svelte';
    import { AIChatInput } from '@fibrae/semi-ai-svelte';
    import { IconBookOpenStroked, IconFeishuLogo, IconFigma, IconGit } from '@fibrae/semi-icons-svelte';
    import { Radio, RadioGroup, type RadioValue } from '@fibrae/semi-ui-svelte';

    const { Configure } = AIChatInput;
    const uploadProps = { action: 'https://api.semi.design/upload' };
    const modelOptions = [
        { value: 'GPT-5', label: 'GPT-5' },
        { value: 'GPT-4o', label: 'GPT-4o' },
        { value: 'Claude 3.5 Sonnet', label: 'Claude 3.5 Sonnet' },
    ];

    const mcpOptions = [
        { label: '飞书文档', value: 'feishu' },
        { label: 'Github Mcp', value: 'github' },
        { label: 'IconFigma Mcp', value: 'IconFigma' },
    ];
    const mcpIcons: Record<string, Component> = { feishu: IconFeishuLogo, github: IconGit, IconFigma };

    const radioButtonProps = [
        { label: '极速', value: 'fast' },
        { label: '思考', value: 'think' },
        { label: '超能', value: 'super' },
    ];

    let shape = $state<RadioValue | undefined>('square');
</script>

<RadioGroup aria-label="单选组合示例" bind:value={shape} name="demo-radio-group">
    <Radio value="round">圆形</Radio>
    <Radio value="square">方形</Radio>
</RadioGroup>
<AIChatInput placeholder="下方按钮为方形的用例" round={shape === 'round'} style="margin: 12px" {uploadProps}>
    {#snippet configureArea()}
        <Configure.Select field="model" initValue="GPT-4o" optionList={modelOptions} />
        <Configure.Button field="onlineSearch">
            {#snippet icon()}
                <IconBookOpenStroked />
            {/snippet}
            联网搜索
        </Configure.Button>
        <Configure.Mcp options={mcpOptions}>
            {#snippet optionIcon({ item })}
                {@const Icon = mcpIcons[item.value]}
                <Icon />
            {/snippet}
        </Configure.Mcp>
        <Configure.RadioButton field="mode" initValue="fast" options={radioButtonProps} />
    {/snippet}
</AIChatInput>

建议

用户可通过 suggestions API 配置建议列表,功能类似于 AutoComplete 组件,用户可以根据输入的内容实现根据输入的内容动态展示建议列表。

使用键盘上下方向键切换建议列表的选项。按下 ESC 或者点击非建议列表,输入框区域,建议列表将关闭。

还可通过 suggestionItem snippet 自定义建议列表的展示,需要把参数里除 suggestion 之外的 id、class、role、aria-selected、onclick、onmouseenter 绑定到根元素上。

代码
<script lang="ts">
    import { AIChatInput, type AIChatInputContent as Content } from '@fibrae/semi-ai-svelte';

    const uploadProps = { action: 'https://api.semi.design/upload' };
    const suggestionTemplate = ['天气如何', '空气质量', '工作进程', '日程安排'];

    let suggestions = $state<string[]>([]);

    const onChange = (content: Content[]) => {
        const value: string | undefined = content.length && content[0].text ? content[0].text : undefined;
        if (value === undefined || value.includes('\n') || value.length >= 4) {
            if (suggestions.length) {
                suggestions = [];
            }
            return;
        }
        suggestions = value.length ? suggestionTemplate.map((item) => `${value},${item}`) : [];
    };
</script>

<AIChatInput onContentChange={onChange} placeholder="输入内容,当内容长度小于 4个字符可以看到建议,使用上下按键可切换侯选项" style="margin: 12px" {suggestions} {uploadProps} />

技能及模版

用户可以通过 skills API 配置技能列表,使用 skillHotKey 配置技能的触发键。

skills 的格式如下

interface Skill {
    label?: string;
    value?: string;
    // 技能是否有模版,有模版的技能被选中后,将在输入框的底部展示模版按钮
    hasTemplate?: boolean;
}

技能只含数据,技能前的图标通过 skillIcon snippet 渲染,参数为 { item, index },整项的展示可通过 skillItem snippet 自定义(绑定方式同建议项)。

由于模版的展示形式丰富,因此我们不提供默认的展示形式,用户可以通过 template snippet 自定义模版的展示。模版面板的展示和关闭可通过点击模版按钮实现。

interface AIChatInputTemplateSnippetProps {
    skill: Skill | undefined;
    // 模版点击回调,点击模版后,用模版的内容替换输入框的内容
    onTemplateClick: (content: string) => void;
}

使用示例如下:

代码
<script lang="ts">
    import type { Component } from 'svelte';
    import { AIChatInput } from '@fibrae/semi-ai-svelte';
    import { IconSearch, IconTemplateStroked } from '@fibrae/semi-icons-svelte';

    const { Configure } = AIChatInput;
    const modelOptions = [
        { value: 'GPT-5', label: 'GPT-5' },
        { value: 'GPT-4o', label: 'GPT-4o' },
        { value: 'Claude 3.5 Sonnet', label: 'Claude 3.5 Sonnet' },
    ];
    const uploadProps = { action: 'https://api.semi.design/upload' };
    const skills = [
        {
            value: 'writing',
            label: '帮我写作',
            hasTemplate: true,
        },
        {
            value: 'AI 编程',
            label: 'AI coding',
        },
    ];
    const skillIcons: Record<string, Component> = { writing: IconTemplateStroked, 'AI 编程': IconSearch };

    const templates = [
        {
            group: '工作',
            children: [
                {
                    bg: 'var(--semi-color-primary)',
                    title: '总结汇报',
                    desc: '凝练你的工作成效',
                    content: `我的职业是<input-slot placeholder="[请输入职业]"></input-slot>,帮我写一份关于<input-slot placeholder="[输入目的:项目进展总结、团队工作成果或其他]"></input-slot>的总结汇报`,
                },
                {
                    bg: 'var(--semi-color-warning)',
                    title: '话术',
                    desc: '满足不同场景表达需求',
                    content: `我是一名<select-slot value="打工人" options='["打工人","学生"]'></select-slot> ,帮我写一段面向<input-slot placeholder="[输入对象]">陌生同事</input-slot>的话术内容`,
                },
            ],
        },
        {
            group: '商业营销',
            children: [
                {
                    bg: 'var(--semi-color-primary)',
                    title: '宣传文案',
                    desc: '撰写各平台的推广文案',
                    content: '帮我写一篇面向<input-slot placeholder="[输入目标人群]"></input-slot>职场人士,关于<input-slot placeholder="[输入产品]"></input-slot>的宣传文案,需要直击痛点,吸引用户点击。',
                },
                {
                    bg: 'var(--semi-color-warning)',
                    title: '方案策划',
                    desc: '量身定制各种方案',
                    content: '我是一名<input-slot placeholder="[输入职业]"></input-slot>职业策划人 ,帮我写一个<input-slot placeholder="[方案类型:如线下读书会活动方案等]"></input-slot>线下读书会活动 的方案,需要包含但不限于策划目标、详细计划、所需资源和预算、效果评估、风险应对等。',
                },
            ],
        },
    ];

    let groupIndex = $state(0);
    let input = $state<ReturnType<typeof AIChatInput>>();

    const setTemplate = (content: string) => {
        input?.setContentWhileSaveTool(content);
        input?.focusEditor();
    };
</script>

<AIChatInput bind:this={input} placeholder="输入 / 唤起技能,选择技能后,点击模版按钮可查看模版,可通过鼠标上下按键切换侯选项" skillHotKey="/" {skills} style="margin: 12px" {uploadProps}>
    {#snippet configureArea()}
        <Configure.Select field="model" initValue="GPT-4o" optionList={modelOptions} />
    {/snippet}
    {#snippet skillIcon({ item })}
        {@const Icon = skillIcons[item.value ?? '']}
        <Icon />
    {/snippet}
    {#snippet template({ skill })}
        {#if skill?.value === 'writing'}
            <div class="aiChatInput-template">
                <div class="template-header">
                    {#each templates as item, index (item.group)}
                        <button class={['template-header-item', { 'template-header-item-active': groupIndex === index }]} style="border: none; font-family: inherit" type="button" onclick={() => (groupIndex = index)}>
                            {item.group}
                        </button>
                    {/each}
                </div>
                <div class="template-content">
                    {#each templates[groupIndex].children as item (item.title)}
                        <button class="template-content-item" style="font: inherit; text-align: left" type="button" onclick={() => setTemplate(item.content)}>
                            <span class="template-content-item-icon" style="background: {item.bg}">
                                <IconTemplateStroked />
                            </span>
                            <span class="template-content-item-title">{item.title}</span>
                            <span class="template-content-item-desc">{item.desc}</span>
                        </button>
                    {/each}
                </div>
            </div>
        {/if}
    {/snippet}
</AIChatInput>

自定义渲染顶部区域

用户可以通过 topSlot snippet 自定义渲染顶部区域,可自行渲染引用,上传内容以及配置项。可结合 showReference 和 showUploadFile API 控制是否展示引用和上传文件。另外,可通过 topSlotPosition API 配置自定义渲染内容相对于引用区域,上传展示区域的相对位置。

interface AIChatInputTopSlotSnippetProps {
    // 引用
    references: Reference[];
    // 上传内容
    attachments: Attachment[];
    // 输入框消息
    content: Content[];
    onUploadFileDelete: (attachment: Attachment) => void;
    // 调用 onReferenceDelete,引用由使用方持有,需要在回调中移除
    onReferenceDelete: (reference: Reference) => void;
}

使用用例如下:

horizontalScroller.tsx
AIChatInput
web
recentChange
Branch Diff with Main Branch
From 1-2
代码
<script lang="ts">
    import type { Component } from 'svelte';
    import { AIChatInput, type AIChatInputAttachment as Attachment, type AIChatInputReference as Reference } from '@fibrae/semi-ai-svelte';
    import { IconBranch, IconClose, IconCode, IconConnectionPoint2, IconFile, IconFolder, IconGit, IconGlobeStroke, IconSearch, IconTemplateStroked, IconTerminal, IconUpload } from '@fibrae/semi-icons-svelte';

    const { Configure } = AIChatInput;
    const radioButtonProps = [
        { label: '快速', value: 'fast' },
        { label: '深度思考', value: 'think' },
    ];
    const modeIcons: Record<string, Component> = { fast: IconTemplateStroked, think: IconSearch };
    const uploadProps = { action: 'https://api.semi.design/upload' };

    let references = $state<Reference[]>([
        {
            type: 'file',
            id: '1',
            name: 'horizontalScroller.tsx',
            path: 'packages/semi-ui-react/AIChatInput/horizontalScroller.tsx',
        },
        {
            type: 'folder',
            id: '2',
            name: 'AIChatInput',
            path: 'packages/semi-ui-react/AIChatInput',
        },
        {
            type: 'web',
            id: '3',
            name: 'web',
        },
        {
            type: 'change',
            id: '4',
            name: 'recentChange',
        },
        {
            type: 'branch',
            id: '5',
            name: 'Branch',
            detail: 'Diff with Main Branch',
            branch: 'feat/aichatinput',
            targetBranch: 'feat/targetBranch',
        },
        {
            type: 'terminal',
            id: '6',
            name: 'From 1-2',
            from: 1,
            to: 2,
        },
    ]);

    const isImageType = ({ name = '', fileInstance }: Attachment) => {
        const PIC_PREFIX = 'image/';
        const PIC_SUFFIX_ARRAY = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'];
        const suffix = name.split('.').pop() ?? '';
        let result = false;
        const type = fileInstance?.type ?? '';
        if (type.startsWith(PIC_PREFIX)) {
            result = true;
        } else if (PIC_SUFFIX_ARRAY.includes(suffix)) {
            result = true;
        }
        return result;
    };

    const refTypeToIconMap: Record<string, Component> = {
        file: IconFile,
        folder: IconFolder,
        branch: IconBranch,
        terminal: IconTerminal,
        web: IconGlobeStroke,
        change: IconConnectionPoint2,
        git: IconGit,
        code: IconCode,
    };

    const onReferenceDelete = (reference: Reference) => {
        references = references.filter((item) => item.id !== reference.id);
    };
</script>

<AIChatInput class="aiChatInput-customTopSlot" {onReferenceDelete} placeholder="自定义渲染顶部内容,可用于渲染上传内容、引用内容" {references} showReference={false} showUploadFile={false} style="margin: 12px" {uploadProps}>
    {#snippet topSlot({ attachments, references: items, onReferenceDelete: deleteReference, onUploadFileDelete })}
        <div class="ai-chat-input-topSlot">
            {#each items as item (item.id)}
                {@const Icon = refTypeToIconMap[item.type ?? '']}
                <div class="item">
                    <span class="item-icon">
                        {#if Icon}
                            <Icon class="item-left item-icon" size="small" />
                        {/if}
                        <button aria-label="删除" class="item-icon-delete" type="button" onclick={() => deleteReference(item)}>
                            <IconClose size="small" />
                        </button>
                    </span>
                    <span class="item-content">
                        {item.name}
                        {#if item.type === 'branch'}
                            <span class="detail">{item.detail}</span>
                        {/if}
                    </span>
                </div>
            {/each}
            {#each attachments as item (item.uid)}
                <div class="item">
                    <span class="item-icon">
                        {#if isImageType(item)}
                            <img alt={item.name} class="item-image item-left" src={item.url} />
                        {:else}
                            <IconUpload class="item-left item-icon" size="small" />
                        {/if}
                        <button aria-label="删除" class="item-icon-delete" type="button" onclick={() => onUploadFileDelete(item)}>
                            <IconClose size="small" />
                        </button>
                    </span>
                    <span class="item-content">{item.name}</span>
                </div>
            {/each}
        </div>
    {/snippet}
    {#snippet configureArea()}
        <Configure.RadioButton field="mode" initValue="fast" options={radioButtonProps}>
            <!-- the icon is the only label, so it carries the name -->
            {#snippet label({ option })}
                {@const Icon = modeIcons[String(option.value)]}
                <Icon aria-label={option.label} />
            {/snippet}
        </Configure.RadioButton>
    {/snippet}
</AIChatInput>

自定义扩展

富文本区域可以自定义扩展,自定义扩展的实现可参考 Tiptap 自定义扩展。通过 extensions API 可将自定义扩展添加到 AIChatInput 组件中。

如果添加了自定义扩展,需要在 transformer 中添加对应的转换规则, 以保证在 onContentChange 中得到的该节点数据符合用户预期。示例中的节点视图直接用 DOM 实现(tiptap 的 addNodeView),候选面板用 Svelte 渲染并挂载到 body。

添加自定义扩展时有以下注意事项:

  • 请在自定义扩展中添加 isCustomSlot 的属性,该属性和自定义扩展前后的光标高度有关
  • 由于 AIChatInput 使用 Enter 作为发送热键,如果自定义扩展有使用 Enter 作为快捷操作,需要自行设置 editor.storage 中的 SemiAIChatInput.allowHotKeySend 用于表示热键是否应该被 AIChatInput 用于发送,避免热键冲突。sendHotKey 为 shift+enter 时,allowHotKeySend 为 false 期间单独按下的 Enter 不再换行,交给自定义扩展处理

自定义扩展定义及注意事项的示例如下:

horizontalScroller.tsx
AIChatInput
web
recentChange
Branch Diff with Main Branch
From 1-2
代码
<script lang="ts">
    import type { Component } from 'svelte';
    import { computePosition, shift } from '@floating-ui/dom';
    import { Node, mergeAttributes, posToDOMRect } from '@tiptap/core';
    import { Mention, type MentionNodeAttrs, type MentionOptions } from '@tiptap/extension-mention';
    import { AIChatInput, type AIChatInputAttachment as Attachment, type AIChatInputContent as Content, type AIChatInputReference as Reference } from '@fibrae/semi-ai-svelte';
    import { IconBranch, IconChevronRight, IconClose, IconCode, IconConnectionPoint2, IconFile, IconFolder, IconGit, IconGlobeStroke, IconTerminal, IconUpload } from '@fibrae/semi-icons-svelte';

    const uploadProps = { action: 'https://api.semi.design/upload' };

    interface PanelItem {
        icon: Component;
        key: string;
        type: string;
        name: string;
        path?: string;
    }

    const TestAction: Record<string, PanelItem[]> = {
        'Files & Folders': [
            {
                icon: IconFile,
                key: '1-1',
                type: 'file',
                name: 'TagInput.scss',
                path: 'package/semi-founctaion/TagInput.scss',
            },
            {
                icon: IconFolder,
                key: '1-2',
                type: 'folder',
                name: 'package',
                path: '/package',
            },
            {
                icon: IconFolder,
                key: '1-3',
                type: 'folder',
                name: 'semi-ui',
                path: '/package/semi-ui',
            },
        ],
        Git: [
            {
                icon: IconBranch,
                key: '2-1',
                type: 'branch',
                name: 'fix/tag',
            },
            {
                icon: IconCode,
                key: '2-2',
                type: 'code',
                name: 'v2.86.0',
                path: '/package',
            },
            {
                icon: IconGit,
                key: '2-3',
                type: 'git',
                name: 'chore: publish',
            },
        ],
    };

    const FirstLevel = Object.keys(TestAction);

    // A ProseMirror node view that renders plain DOM: tiptap has no Svelte binding, and the value is the only state
    const ReferSlot = Node.create({
        name: 'referSlot',
        inline: true,
        group: 'inline',
        atom: true,
        selectable: false,
        addAttributes() {
            return {
                value: {
                    default: '输入内容',
                    parseHTML: (element) => element.getAttribute('data-value'),
                    renderHTML: (attributes) => ({
                        'data-value': attributes.value,
                    }),
                },
                info: {
                    default: '',
                    parseHTML: (element) => element.getAttribute('data-info'),
                    renderHTML: (attributes) => ({
                        'data-info': attributes.info,
                    }),
                },
                type: {
                    default: 'text',
                    parseHTML: (element) => element.getAttribute('data-type'),
                    renderHTML: (attributes) => ({
                        'data-type': attributes.type,
                    }),
                },
                uniqueKey: {
                    default: '',
                    parseHTML: (element) => element.getAttribute('data-unique-key'),
                    renderHTML: (attributes) => ({
                        'data-unique-key': attributes.uniqueKey,
                    }),
                },
                // Sizes the caret around the custom node; every custom node needs it
                isCustomSlot: AIChatInput.getCustomSlotAttribute(),
            };
        },
        parseHTML() {
            return [
                {
                    tag: 'refer-slot',
                },
            ];
        },
        renderHTML({ HTMLAttributes }) {
            return ['refer-slot', mergeAttributes(HTMLAttributes)];
        },
        addNodeView() {
            return ({ node }) => {
                const dom = document.createElement('span');
                dom.className = 'ai-chat-input-refer-slot-wrapper';
                const slot = document.createElement('span');
                slot.className = 'ai-chat-input-refer-slot';
                slot.textContent = node.attrs.value ? node.attrs.value : '';
                dom.append(slot);
                return {
                    dom,
                    update: (updated) => {
                        if (updated.type !== node.type) {
                            return false;
                        }
                        slot.textContent = updated.attrs.value ? updated.attrs.value : '';
                        return true;
                    },
                };
            };
        },
    });

    interface ReferSlotAttrs {
        value: string;
        info: string;
        type?: string;
        uniqueKey: string;
    }

    type MentionSuggestion = MentionOptions['suggestion'];
    type MentionStartProps = Parameters<NonNullable<ReturnType<NonNullable<MentionSuggestion['render']>>['onStart']>>[0];

    // Content the panel returns through command, not limited to Mention's own attributes
    interface MentionCommandProps extends Partial<MentionNodeAttrs> {
        item?: PanelItem;
        allowHotKeySend?: boolean;
    }

    type MentionPanelProps = Omit<MentionStartProps, 'command'> & {
        command: (props: MentionCommandProps) => void;
    };

    // Suggestion panel state; null means closed
    let panel = $state.raw<MentionPanelProps | null>(null);
    let level = $state(1);
    let options = $state.raw<(string | PanelItem)[]>(FirstLevel);
    let selectedIndex = $state(0);
    let floating = $state<HTMLElement>();
    let floatingStyle = $state('position: absolute; width: max-content; left: 0px; top: 0px');

    const filterOptions = $derived.by(() => {
        const query = panel?.query;
        return query
            ? options.filter((item) => {
                  const name = typeof item === 'string' ? item : item.name;
                  return name.toLowerCase().includes(query.toLowerCase());
              })
            : options;
    });

    // a new list or query starts again from the first match
    $effect(() => {
        void options;
        void panel?.query;
        selectedIndex = 0;
    });

    // The panel follows the caret; option changes resize it, so reposition
    $effect(() => {
        void filterOptions;
        const current = panel;
        if (!current?.clientRect || !floating) {
            return;
        }
        const virtualElement = {
            getBoundingClientRect: () => posToDOMRect(current.editor.view, current.editor.state.selection.from, current.editor.state.selection.to),
        };
        void computePosition(virtualElement, floating, {
            placement: 'bottom-start',
            strategy: 'absolute',
            middleware: [shift()],
        }).then(({ x, y, strategy }) => {
            floatingStyle = `position: ${strategy}; width: max-content; left: ${x}px; top: ${y}px`;
        });
    });

    // Mounted in the body so no ancestor's overflow clips the panel
    const portal = (element: HTMLElement) => {
        document.body.append(element);
        return () => element.remove();
    };

    const setHotKeySend = (allow: boolean) => {
        // While the panel is open, Enter belongs to it, not to AIChatInput's send
        panel?.command({ allowHotKeySend: allow });
    };

    const closePanel = () => {
        setHotKeySend(true);
        panel = null;
    };

    const selectItem = (item: string | PanelItem) => {
        if (typeof item === 'string') {
            level = 2;
            options = TestAction[item];
        } else {
            panel?.command({ item });
        }
    };

    const onItemClick = (item: string | PanelItem) => {
        selectItem(item);
        // Clicking an option blurs the editor, so return focus after entering the second level
        if (level === 1) {
            panel?.editor.commands.focus();
        }
    };

    const suggestion: MentionSuggestion = {
        items: () => FirstLevel,
        command: ({ editor, range, props }) => {
            const { item, allowHotKeySend } = props as MentionCommandProps;
            if (typeof allowHotKeySend === 'boolean') {
                // AIChatInput registers its state under the extension name, which tiptap's Storage type does not know
                (editor.storage as Record<string, { allowHotKeySend: boolean }>).SemiAIChatInput.allowHotKeySend = allowHotKeySend;
            }
            if (item) {
                editor
                    .chain()
                    .focus()
                    .insertContentAt(range, {
                        type: 'referSlot',
                        attrs: {
                            type: item.type,
                            value: item.name || '',
                            info: JSON.stringify({ path: item.path }),
                            uniqueKey: item.key,
                        },
                    })
                    .run();
            }
        },
        render: () => ({
            onStart: (props) => {
                level = 1;
                options = FirstLevel;
                panel = props as MentionPanelProps;
                setHotKeySend(false);
            },
            onUpdate: (props) => {
                // After Escape closes the panel it stays closed until this suggestion ends
                if (panel) {
                    panel = props as MentionPanelProps;
                }
            },
            onKeyDown: ({ event }) => {
                if (!panel) {
                    return false;
                }
                if (event.key === 'ArrowUp') {
                    selectedIndex = (selectedIndex + filterOptions.length - 1) % filterOptions.length;
                    return true;
                }
                if (event.key === 'ArrowDown') {
                    selectedIndex = (selectedIndex + 1) % filterOptions.length;
                    return true;
                }
                if (event.key === 'Enter') {
                    const item = filterOptions[selectedIndex];
                    if (item) {
                        selectItem(item);
                    }
                    return true;
                }
                if (event.key === 'Escape') {
                    if (level === 1) {
                        closePanel();
                    } else {
                        level = 1;
                        options = FirstLevel;
                    }
                    return true;
                }
                return false;
            },
            onExit: closePanel,
        }),
    };

    const extensions = [
        ReferSlot,
        Mention.configure({
            HTMLAttributes: {
                class: 'mention',
            },
            suggestion,
        }),
    ];

    let references = $state<Reference[]>([
        {
            type: 'file',
            id: '1',
            name: 'horizontalScroller.tsx',
            path: 'packages/semi-ui-react/AIChatInput/horizontalScroller.tsx',
        },
        {
            type: 'folder',
            id: '2',
            name: 'AIChatInput',
            path: 'packages/semi-ui-react/AIChatInput',
        },
        {
            type: 'web',
            id: '3',
            name: 'web',
        },
        {
            type: 'change',
            id: '4',
            name: 'recentChange',
        },
        {
            type: 'branch',
            id: '5',
            name: 'Branch',
            detail: 'Diff with Main Branch',
            branch: 'feat/aichatinput',
            targetBranch: 'feat/targetBranch',
        },
        {
            type: 'terminal',
            id: '6',
            name: 'From 1-2',
            from: 1,
            to: 2,
        },
    ]);

    const isImageType = ({ name = '', fileInstance }: Attachment) => {
        const PIC_PREFIX = 'image/';
        const PIC_SUFFIX_ARRAY = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'];
        const suffix = name.split('.').pop() ?? '';
        let result = false;
        const type = fileInstance?.type ?? '';
        if (type.startsWith(PIC_PREFIX)) {
            result = true;
        } else if (PIC_SUFFIX_ARRAY.includes(suffix)) {
            result = true;
        }
        return result;
    };

    const refTypeToIconMap: Record<string, Component> = {
        file: IconFile,
        folder: IconFolder,
        branch: IconBranch,
        terminal: IconTerminal,
        web: IconGlobeStroke,
        change: IconConnectionPoint2,
        git: IconGit,
        code: IconCode,
    };

    let input = $state<ReturnType<typeof AIChatInput>>();

    const richContent = (content: Content[]) => content.filter((item) => item.type !== 'text');

    const onReferenceDelete = (reference: Reference) => {
        references = references.filter((item) => item.id !== reference.id);
    };

    const onContentChange = (content: Content[]) => {
        console.log('onContentChange', content);
    };

    const transformer = new Map([
        [
            'referSlot',
            ({ attrs }: { attrs: ReferSlotAttrs }) => {
                const { value, info, type = 'text', uniqueKey } = attrs;
                return {
                    type: type,
                    value: value,
                    uniqueKey: uniqueKey,
                    ...JSON.parse(info),
                };
            },
        ],
    ]);
</script>

<AIChatInput bind:this={input} class="aiChatInput-customTopSlot" {extensions} {onContentChange} {onReferenceDelete} placeholder="使用 @ 触发" {references} showReference={false} showUploadFile={false} style="margin: 12px" {transformer} {uploadProps}>
    {#snippet topSlot({ attachments, content, references: items, onReferenceDelete: deleteReference, onUploadFileDelete })}
        <div class="ai-chat-input-topSlot">
            {#each richContent(content) as item, index (item.key ?? index)}
                {@const Icon = refTypeToIconMap[item.type]}
                <div class="item">
                    <span class="item-icon">
                        {#if Icon}
                            <Icon class="item-left item-icon" size="small" />
                        {/if}
                        <button aria-label="删除" class="item-icon-delete" type="button" onclick={() => input?.deleteContent(item)}>
                            <IconClose size="small" />
                        </button>
                    </span>
                    <span class="item-content">
                        {item.name ? item.name : item.value}
                        {#if item.type === 'branch'}
                            <span class="detail">{item.detail}</span>
                        {/if}
                    </span>
                </div>
            {/each}
            {#each items as item (item.id)}
                {@const Icon = refTypeToIconMap[item.type ?? '']}
                <div class="item">
                    <span class="item-icon">
                        {#if Icon}
                            <Icon class="item-left item-icon" size="small" />
                        {/if}
                        <button aria-label="删除" class="item-icon-delete" type="button" onclick={() => deleteReference(item)}>
                            <IconClose size="small" />
                        </button>
                    </span>
                    <span class="item-content">
                        {item.name}
                        {#if item.type === 'branch'}
                            <span class="detail">{item.detail}</span>
                        {/if}
                    </span>
                </div>
            {/each}
            {#each attachments as item (item.uid)}
                <div class="item">
                    <span class="item-icon">
                        {#if isImageType(item)}
                            <img alt={item.name} class="item-image item-left" src={item.url} />
                        {:else}
                            <IconUpload class="item-left item-icon" size="small" />
                        {/if}
                        <button aria-label="删除" class="item-icon-delete" type="button" onclick={() => onUploadFileDelete(item)}>
                            <IconClose size="small" />
                        </button>
                    </span>
                    <span class="item-content">{item.name}</span>
                </div>
            {/each}
        </div>
    {/snippet}
</AIChatInput>
{#if panel}
    <div {@attach portal} bind:this={floating} style={floatingStyle}>
        <div class="ai-chat-input-custom-extension-dropdown-menu" role="menu" style="width: {level === 1 ? '200px' : '300px'}">
            {#if filterOptions.length}
                {#each filterOptions as item, index (index)}
                    <div
                        class={['optionItem', { 'is-selected': index === selectedIndex }]}
                        role="menuitem"
                        tabindex="-1"
                        onclick={() => onItemClick(item)}
                        onfocusin={() => (selectedIndex = index)}
                        onkeydown={(event) => {
                            if (event.key === 'Enter') {
                                onItemClick(item);
                            }
                        }}
                        onmouseenter={() => (selectedIndex = index)}
                    >
                        {#if typeof item === 'string'}
                            <span>{item}</span>
                        {:else}
                            <div class="level2Item">
                                <item.icon />
                                <span class="name">{item.name}</span>
                                <span class="path">{item.path}</span>
                            </div>
                        {/if}
                        {#if level === 1}
                            <IconChevronRight class="option-item-arrow" />
                        {/if}
                    </div>
                {/each}
            {:else}
                <div class="item">No result</div>
            {/if}
        </div>
    </div>
{/if}

API 参考

根元素带 aria-label 或 aria-labelledby 且未传 role 时,自动加 role="group"。附件卡的缩略图是装饰图(alt 为空),文件名由卡片内的可见文字提供。

AIChatInput

Props

属性说明类型默认值
actionArea自定义底部操作区域的 snippet,参数 upload 为上传节点(showUploadButton 为 false 时是隐藏的 Upload,仍需渲染才能粘贴上传)、send 为发送或停止按钮,均是 snippet,用 {@render} 渲染;class 为操作区域的类名。TypeSnippet<[AIChatInputActionAreaSnippetProps]>-
canSend是否可以发送。未设置时,根据输入框内容和上传内容决定;引用内容不参与判断。boolean-
clearContentOnGeneratinggenerating 从 false 变为 true 时,是否清空输入框内容和附件。设为 false 可保留输入内容(适用于无限画布等非对话场景)。booleantrue
configureArea底部配置区域的 snippet,放置 AIChatInput.Configure 的各配置项。Snippet-
defaultContent输入框默认内容,支持 html string 以及 json 格式,同 Tiptap 的 Content;只在创建编辑器时读取。TiptapContent-
dropdownMatchTriggerWidth下拉弹出层是否与输入框宽度一致。booleantrue
extensions自定义 tiptap 扩展;只在创建编辑器时读取,之后变化不生效。Extensions-
generating是否正在生成中。为 true 时发送按钮变为停止生成按钮。booleanfalse
keepSkillAfterSend发送消息后是否保留已选的技能。booleanfalse
onBlur富文本输入框失焦时的回调。会遮住根元素上的原生 onblur。Type(event: FocusEvent) => void-
onConfigureChange配置区域发生变化时的回调,参数为全部配置值和本次变化的值;移除配置项时第二个参数为 undefined。Type(value: LeftMenuChangeProps, changedValue?: LeftMenuChangeProps) => void-
onContentChange输入框内容变化时的回调,参数为当前内容项列表。Type(contents: Content[]) => void-
onFocus富文本输入框聚焦时的回调。会遮住根元素上的原生 onfocus。Type(event: FocusEvent) => void-
onMessageSend点击发送按钮时的回调,参数包含引用、上传文件、输入内容和配置区域内容。Type(message: MessageContent) => void-
onPaste监听输入框的粘贴事件,不阻止默认粘贴行为,可通过 event.clipboardData 获取内容。会遮住根元素上的原生 onpaste。Type(event: ClipboardEvent) => void-
onReferenceClick点击引用时的回调。Type(reference: Reference) => void-
onReferenceDelete删除引用时的回调。引用由使用方持有,需要在回调中自行移除。Type(reference: Reference) => void-
onSkillChange技能切换时的回调,移除技能时参数为 undefined。Type(skill?: Skill) => void-
onStopGenerate点击停止生成按钮时的回调。Type() => void-
onUploadChange上传文件列表变化时的回调。Type(props: UploadOnChangeProps) => void-
placeholder输入框占位符,可以是字符串,也可以是按节点返回字符串的函数。PlaceholderProps-
popoverProps下拉弹出层的配置参数;class 与内部类名合并,style 字符串与面板宽度合并。AIChatInputPopoverProps-
reference自定义渲染每个引用的 snippet,参数为 item 与 index。TypeSnippet<[AIChatInputReferenceSnippetProps]>-
references输入框的引用列表。Reference[]-
round底部的配置区域和操作区域按钮是否为全圆角。booleantrue
sendHotKey发送输入内容的键盘快捷键。enter 表示单独按下 Enter 发送,Shift 与 Enter 同时按下仅换行;shift+enter 相反。'enter' | 'shift+enter'"enter"
showPlaceholderWhenSkillOnly仅选中技能(无其他内容)时是否显示占位符,开启后占位符显示在技能后方;只在创建编辑器时读取。booleanfalse
showReference是否展示引用区域,用于配合 topSlot 使用。booleantrue
showTemplateButton是否展示模板按钮。未设置时,根据当前选中技能的 hasTemplate 决定。booleanfalse
showUploadButton是否显示右侧上传按钮。设为 false 时粘贴上传仍然有效。booleantrue
showUploadFile是否展示上传文件区域,用于配合 topSlot 使用。booleantrue
skillHotKey输入框中触发技能面板的热键。string-
skillIcon技能面板中每个技能前的图标 snippet,参数为 item 与 index。TypeSnippet<[AIChatInputSkillIconSnippetProps]>-
skillItem自定义技能列表每一项的 snippet,参数含 skill 和需要展开到根元素上的 id、class、role、aria-selected、onclick、onmouseenter。TypeSnippet<[AIChatInputSkillItemSnippetProps]>-
skills技能列表。技能只含数据,图标使用 skillIcon snippet。Skill[]-
suggestionItem自定义每个建议项的 snippet,参数含 suggestion 和需要展开到根元素上的 id、class、role、aria-selected、onclick、onmouseenter。TypeSnippet<[AIChatInputSuggestionItemSnippetProps]>-
suggestions建议列表,每项为字符串或带 content 的对象。Suggestion[]-
template模板面板内容的 snippet,参数为当前技能 skill 与用传入内容替换输入框内容的 onTemplateClick。TypeSnippet<[AIChatInputTemplateSnippetProps]>-
templatesCls模板面板的类名。string-
templatesStyle模板面板的样式字符串。string-
topSlot自定义顶部区域的 snippet,参数含引用、上传内容、输入内容和删除方法(references、attachments、content、onUploadFileDelete、onReferenceDelete)。位置由 topSlotPosition 决定。TypeSnippet<[AIChatInputTopSlotSnippetProps]>-
topSlotPositiontopSlot 的位置,相对于引用区域与上传文件区域。'top' | 'middle' | 'bottom'"top"
transformer自定义扩展的转换规则,键为节点名,值为把节点转换成 onContentChange 内容项的函数。TypeMap<string, (obj: any) => any>-
uploadButton自定义上传按钮内容的 snippet,上传与粘贴上传逻辑仍由组件托管;参数含 defaultNode(snippet)、onOpenFileDialog、disabled、attachments。TypeSnippet<[AIChatInputUploadButtonSnippetProps]>-
uploadProps上传文件相关配置,同 Upload,但不接受 fileList、listType 与 children;初始附件用 defaultFileList;onChange、onRemove 由 AIChatInput 自己调用,beforeRemove 支持 Promise。AIChatInputUploadProps-
uploadTip上传按钮提示内容的 snippet。Snippet-
uploadTipProps上传按钮提示的 Tooltip 配置,不含 content;提示内容使用 uploadTip snippet。TypeOmit<TooltipProps, 'content' | 'children' | 'child' | 'arrow'>-

Methods

方法说明类型
changeTemplateVisible切换模板弹出层的可见性。Type(visible: boolean) => void
deleteContent删除富文本中的某一项,按 content 中的 uniqueKey 匹配。Type(content: Content) => void
deleteUploadFile删除上传文件中的某一项。Type(item: Attachment) => void
focusEditor聚焦输入框,默认聚焦到末尾。Type(pos?: FocusPosition) => void
getEditor获取 tiptap 的 editor 实例,编辑器创建前为 undefined。Type() => Editor | undefined
setContent设置输入框内容。Type(content: TiptapContent) => void
setContentWhileSaveTool保留技能项的同时设置输入框内容。Type(content: string) => void

class、style 与未声明的属性和事件(如 onclick)落在根元素上。onFocus、onBlur、onPaste 来自富文本输入框,会遮住根元素上的原生 onfocus、onblur、onpaste。

数据项类型:

type Suggestion = string | { content: string; [key: string]: any };

interface Reference {
    type?: string;
    id: string;
    [key: string]: any;
}

interface Content {
    type: string;
    [key: string]: any;
}

interface MessageContent {
    references?: Reference[];
    attachments?: Attachment[];
    inputContents?: Content[];
    setup?: Setup;
}

Configure.Select、Configure.Button、Configure.RadioButton 的值由 AIChatInput 接管:不接受 value,field 必填,initValue 设置初始值,onChange 收到该项的新值。

属性说明类型默认值
field配置项在配置值中的 key,必填string-
initValue初始值与被包装组件的 value 一致-
onChange该项的值变化时调用,参数为新值(value: unknown) => void-

Configure.Select

其余属性同 SelectProps

Configure.Button

其余属性同 ButtonProps,图标使用 icon snippet;值为 boolean,点击时切换,onClick 收到切换后的值 (value: boolean) => void,并输出 aria-pressed

Configure.RadioButton

其余属性同 RadioGroupProps

Configure.Mcp

属性说明类型默认值
optionsMCP 选项列表。选项只含数据,图标使用 optionIconMcpOption[]-
num触发器与标题中显示的数量,不传时为 options 的数量number-
showConfigure是否显示配置按钮booleantrue
onConfigureButtonClick点击配置按钮时的回调() => void-
optionIcon每个选项图标的 snippet,参数为 { item, index }Snippet<[McpOptionIconSnippetProps]>-
children替换标题下方内置菜单的 snippetSnippet-

未声明的属性(Dropdown 的属性以及 class、style)透传给内部的 Dropdown,落点同 Dropdown。

选项只含数据,图标通过 optionIcon snippet 渲染:

interface McpOption {
    value: string;
    label: string;
    disabled?: boolean;
    [key: string]: unknown;
}

Configure.Item

把任意接收值和变化回调的组件变成配置项,属性见「配置区域」一节中的 ConfigureItemProps。

设计变量

下表是组件内部的 Sass 变量,不能覆写。定制样式请覆写 --semi-* CSS 变量(见 Design Token 页),或写不分层的 CSS 规则。
Sass 变量值用法
$color-aiChatInput-bordervar(--semi-color-border)AIChatInput的边框颜色
$color-aiChatInput_skill_item-bg-activevar(--semi-color-fill-0)AIChatInput技能项悬停时的背景颜色
$color-aiChatInput_suggestion_item-textvar(--semi-color-text-0)AIChatInput建议项的文本颜色
$color-aiChatInput_suggestion_item-bg-activevar(--semi-color-fill-0)AIChatInput建议项悬停时的背景颜色
$color-aiChatInput_references-textvar(--semi-color-text-2)AIChatInput引用项的文本颜色
$color-aiChatInput_reference-bgvar(--semi-color-fill-0)AIChatInput引用项的背景色
$color-aiChatInput_footer_send-textvar(--semi-white)AIChatInput底部发送按钮的内容颜色
$color-aiChatInput_footer_send-bg-defaultvar(--semi-color-primary)AIChatInput底部发送按钮的背景颜色 - 默认
$color-aiChatInput_footer_send-bg-hovervar(--semi-color-primary-hover)AIChatInput底部发送按钮的背景颜色-悬停态
$color-aiChatInput_footer_send-bg-activevar(--semi-color-primary-active)AIChatInput底部发送按钮的背景颜色-激活态
$color-aiChatInput_footer_send-bg-disabledvar(--semi-color-fill-2)AIChatInput底部发送按钮的背景颜色-禁用态
$color-aiChatInput_footer_upload-textvar(--semi-color-text-1)AIChatInput底部上传按钮的内容颜色
$color-aiChatInput_footer_upload-bg-defaulttransparentAIChatInput底部上传按钮的背景颜色 - 默认
$color-aiChatInput_footer_upload-bg-hovervar(--semi-color-fill-0)AIChatInput底部上传按钮的背景颜色-悬停态
$color-aiChatInput_footer_upload-bg-activevar(--semi-color-fill-1)AIChatInput底部上传按钮的背景颜色-悬停态
$color-aiChatInput_footer_configure_button-border-activevar(--semi-color-primary)AIChatInput底部配置区域按钮的按钮边框颜色 - 激活态
$color-aiChatInput_footer_configure_button-textvar(--semi-color-primary)AIChatInput底部配置区域按钮的按钮文字颜色 - 激活态
$color-aiChatInput_footer_configure_select-bordervar(--semi-color-border)AIChatInput底部配置区域下拉选择的按钮边框颜色
$color-aiChatInput_footer_configure_radio_button_checkedvar(--semi-color-text-1)AIChatInput底部配置区域下拉选择的单选按钮选中时的背景颜色
$color-aiChatInput_footer_configure_radio_button_checked-bgvar(--semi-color-bg-2)AIChatInput底部配置区域下拉选择的单选按钮选中时的背景颜色
$color-aiChatInput_footer-configure_mcp_header_title-textvar(--semi-color-text-2)AIChatInput底部配置区域mcp配置下拉的顶部内容的标题颜色
$color-aiChatInput_attachment-bgvar(--semi-color-fill-0)AIChatInput附件项的背景颜色
$color-aiChatInput_attachment_name-textvar(--semi-color-text-0)AIChatInput附件项内容名称的文本颜色
$color-aiChatInput_attachment_delete-bgvar(--semi-color-text-1)AIChatInput附件项内容的删除按钮的背景颜色
$color-aiChatInput_attachment_delete-iconvar(--semi-color-bg-0)AIChatInput附件项内容的删除按钮的图标颜色
$color-aiChatInput_attachment_scroll_button-bgvar(--semi-color-bg-2)AIChatInput附件项滚动按钮的背景颜色
$color-aiChatInput_attachment_scroll_buttonvar(--semi-color-text-2)AIChatInput附件项滚动按钮的背景颜色
$color-aiChatInput_rich_text-input_slot-bgvar(--semi-color-primary-light-default)AIChatInput富文本编辑器输入插槽的背景颜色
$color-aiChatInput_rich_text-input_slot-textvar(--semi-color-primary)AIChatInput富文本编辑器输入插槽的文本颜色
$color-aiChatInput_rich_text-input_slot_placeholdervar(--semi-color-primary-disabled)AIChatInput富文本编辑器输入插槽占位符的文本颜色
$color-aiChatInput_rich_text-select_slot-bgvar(--semi-color-primary-light-default)AIChatInput富文本编辑器选择器插槽的背景颜色
$color-aiChatInput_rich_text-select_selection-textvar(--semi-color-primary)AIChatInput富文本编辑器选择器插槽的选择器文本颜色
$color-aiChatInput_rich_text-select_slot_arrowvar(--semi-color-text-2)AIChatInput富文本编辑器选择器插槽的下拉箭头颜色
$color-aiChatInput_rich_text-skill_slot-textvar(--semi-color-primary)AIChatInput富文本编辑器技能插槽的文本颜色
$color-aiChatInput_rich_text-skill_slot-bg-hovervar(--semi-color-primary-light-default)AIChatInput富文本编辑器技能插槽的背景色 - 悬停态
$color-aiChatInput_rich_text-skill_slot_delete-bgvar(--semi-color-text-1)AIChatInput富文本编辑器技能插槽的删除按钮的背景颜色
$color-aiChatInput_rich_text-skill_slot_delete-textvar(--semi-color-bg-0)AIChatInput富文本编辑器技能插槽的删除按钮的背景颜色
$color-aiChatInput_ref_icon_word-bgvar(--semi-blue-4)AIChatInput 引用/上传内容为文本文件时的图标背景色
$color-aiChatInput_ref_icon_word-pdfvar(--semi-red-4)AIChatInput 引用/上传内容为 pdf 时的图标背景色
$color-aiChatInput_ref_icon_word-codevar(--semi-teal-5)AIChatInput 引用/上传内容为代码的图标背景色
$color-aiChatInput_ref_icon_word-excelvar(--semi-green-5)AIChatInput 引用/上传内容为表格类型的图标背景色
$color-aiChatInput_ref_icon_word-videovar(--semi-purple-4)AIChatInput 引用/上传内容为视频类型的图标背景色
$color-aiChatInput_ref_icon_word-audiovar(--semi-purple-4)AIChatInput 引用/上传内容为音频类型的图标背景色
$color-aiChatInput_ref_icon_word-unknownvar(--semi-grey-5)AIChatInput 引用/上传内容为未知类型的图标背景色
$color-aiChatInput_reference_delete-bgvar(--semi-color-fill-1)AIChatInput引用项删除图标的背景色 - 悬停态
$color-aiChatInput_footer_configure_select-textvar(--semi-color-text-1)AIChatInput底部配置区域下拉选择的按钮文字颜色
$color-aiChatInput_footer_configure_select-textvar(--semi-color-text-1)AIChatInput底部配置区域下拉选择的按钮文字颜色
$spacing-aiChatInput-padding20pxAIChatInput的外边距
$spacing-aiChatInput_skill-paddingY4pxAIChatInput技能面板的垂直内边距
$spacing-aiChatInput_skill-paddingX0pxAIChatInput技面板的水平内边距
$spacing-aiChatInput_skill_item-columnGap8pxAIChatInput技能项内容的水平间距
$spacing-aiChatInput_skill_item-paddingY8pxAIChatInput技能项的垂直内边距
$spacing-aiChatInput_skill_item-paddingX20pxAIChatInput技能项的水平内边距
$spacing-aiChatInput_suggestion_item-paddingY8pxAIChatInput建议项的垂直内边距
$spacing-aiChatInput_suggestion_item-paddingX20pxAIChatInput建议项的水平内边距
$spacing-aiChatInput_references-marginBottom8pxAIChatInput引用项的底部外边距
$spacing-aiChatInput_references-columnGap4pxAIChatInput技能块内容的水平间距
$spacing-aiChatInput_references-rowGap4pxAIChatInput技能块内容的垂直间距
$spacing-aiChatInput_reference-paddingY8pxAIChatInput引用项的垂直内边距
$spacing-aiChatInput_reference-paddingX12pxAIChatInput引用项的水平内边距
$spacing-aiChatInput_reference-columnGap8pxAIChatInput引用项内容的水平间距
$spacing-aiChatInput_footer-marginTop20pxAIChatInput引用项的顶部外边距
$spacing-aiChatInput_footer_action-columnGap8pxAIChatInput底部右侧操作区域项目的水平间距
$spacing-aiChatInput_footer_configure-columnGap8pxAIChatInput底部配置区域项目的水平间距
$spacing-aiChatInput_footer_configure_radio_button-padding4pxAIChatInput底部配置区域下拉选择的单选按钮的内边距
$spacing-aiChatInput_footer_configure_mcp_header-paddingTop8pxAIChatInput底部配置区域mcp配置下拉的顶部内容的上外边距
$spacing-aiChatInput_footer_configure_mcp_header-paddingBottom0pxAIChatInput底部配置区域mcp配置下拉的顶部内容的下外边距
$spacing-aiChatInput_footer_configure_mcp_header-paddingX16pxAIChatInput底部配置区域mcp配置下拉的顶部内容的水平外边距
$spacing-aiChatInput_footer_configure_mcp_columnGap4pxAIChatInput底部配置区域mcp配置下拉的顶部内容的水平间距
$spacing-aiChatInput_attachment-columnGap8pxAIChatInput附件项的水平间距
$spacing-aiChatInput_attachment-padding8pxAIChatInput附件项的内间距
$spacing-aiChatInput_attachment_content_size-columnGap4pxAIChatInput附件项类型和大小的间距
$spacing-aiChatInput_attachment_scroll_wrapper-marginBottom8pxAIChatInput附件项滚动区域的底部外边距
$spacing-aiChatInput_attachment_scroll_container8pxAIChatInput附件项滚动区域的内间距
$spacing-aiChatInput_attachment_scroll_button_offsetX10pxAIChatInput附件项滚动按钮的和滚动区域的水平距离
$spacing-aiChatInput_rich_text-input_slot-paddingY2pxAIChatInput富文本编辑器输入插槽的垂直内边距
$spacing-aiChatInput_rich_text-input_slot-paddingX4pxAIChatInput富文本编辑器输入插槽的水平内边距
$spacing-aiChatInput_rich_text-input_slot-marginY2pxAIChatInput富文本编辑器输入插槽的垂直内边距
$spacing-aiChatInput_rich_text-input_slot-marginX2pxAIChatInput富文本编辑器输入插槽的水平内边距
$spacing-aiChatInput_rich_text-select_slot-paddingX4pxAIChatInput富文本编辑器选择器插槽的水平内边距
$spacing-aiChatInput_rich_text-select_slot-paddingY2pxAIChatInput富文本编辑器选择器插槽的垂直内边距
$spacing-aiChatInput_rich_text-select_slot-marginX4pxAIChatInput富文本编辑器选择器插槽的垂直外边距
$spacing-aiChatInput_rich_text-select_slot-marginY2pxAIChatInput富文本编辑器选择器插槽的水平外边距
$spacing-aiChatInput_rich_text-select_selection-marginLeft0pxAIChatInput富文本编辑器选择器插槽的选择器文本的左侧外边距
$spacing-aiChatInput_rich_text-skill_slot-paddingX4pxAIChatInput富文本编辑器技能插槽的水平内边距
$spacing-aiChatInput_rich_text-skill_slot-paddingY0pxAIChatInput富文本编辑器技能插槽的垂直内边距
$spacing-aiChatInput_rich_text-skill_slot-marginX2pxAIChatInput富文本编辑器技能插槽的水平外边距
$spacing-aiChatInput_rich_text-skill_slot-marginY2pxAIChatInput富文本编辑器技能插槽的垂直外边距
$spacing-aiChatInput_rich_text-skill_slot-top0pxAIChatInput富文本编辑器技能插槽删除按钮距离顶部距离
$spacing-aiChatInput_rich_text-skill_slot-right0pxAIChatInput富文本编辑器技能插槽删除按钮距离右侧距离
$spacing-aiChatInput_reference_icon-marginRight4pxAIChatInput 引用项的图标距离右侧距离
$spacing-aiChatInput_references_delete-padding2pxAIChatInput引用项删除图标的内间距
$width-aiChatInput-border1pxAIChatInput的边框宽度
$width-aiChatInput_footer_action_button32pxAIChatInput底部右侧操作按钮的宽度
$height-aiChatInput_footer_action_button32pxAIChatInput底部右侧操作按钮的高度
$width-aiChatInput_footer_configure_button-border1pxAIChatInput底部配置区域按钮的边框宽度
$width-aiChatInput_footer_configure_select-border1pxAIChatInput底部配置区域下拉选择的边框宽度
$height-aiChatInput_footer_configure_mcp_header16pxAIChatInput底部配置区域mcp配置下拉的顶部内容的高度
$width-aiChatInput_attachment240pxAIChatInput附件项的宽度(含内边距)
$height-aiChatInput_attachment_left36pxAIChatInput附件项左侧图标/图片的宽高
$width-aiChatInput_attachment-content180pxAIChatInput附件项内容的宽度
$height-aiChatInput_attachment-content20pxAIChatInput附件项内容的高度
$width-aiChatInput_attachment_delete16pxAIChatInput附件项内容的删除按钮的宽度
$width-aiChatInput_attachment_scroll_button16pxAIChatInput附件项滚动按钮的宽度
$width-aiChatInput_attachment_scroll_button_icon12pxAIChatInput附件项滚动按钮的图标大小
$height-aiChatInput_rich_text-select-slot24pxAIChatInput富文本编辑器选择器插槽的高度
$width-aiChatInput_rich_text-select_slot_arrow16pxAIChatInput富文本编辑器选择器插槽的下拉箭头宽度
$width-aiChatInput_rich_text-select_slot_delete12pxAIChatInput富文本编辑器选择器插槽的删除按钮的宽高
$width-aiChatInput_rich_text-select_slot_delete_icon8pxAIChatInput富文本编辑器选择器插槽的删除按钮icon的宽高
$width-aiChatInput_rich_text-input_slot2pxAIChatInput富文本编辑器输入插槽的最小宽度
$width-aiChatInput_reference_icon16pxAIChatInput 引用项的图标宽度
$radius-aiChatInput12pxAIChatInput输入框的圆角
$radius-aiChatInput_skill8pxAIChatInput技能块的圆角
$radius-aiChatInput_reference6pxAIChatInput引用项的圆角
$radius-aiChatInput_footer_round9999pxAIChatInput底部操作项目全圆角模式的圆角
$radius-aiChatInput_footer_action_button8pxAIChatInput底部右侧操作按钮的圆角
$radius-aiChatInput_attachment6pxAIChatInput附件项的圆角
$radius-aiChatInput_rich_text-input_slot4pxAIChatInput富文本编辑器输入插槽的圆角
$radius-aiChatInput_rich_text-select_slot4pxAIChatInput富文本编辑器选择器插槽的圆角
$radius-aiChatInput_rich_text-skill_slot4pxAIChatInput富文本编辑器技能插槽的圆角
$radius-aiChatInput_reference_icon2pxAIChatInput 引用项的图标圆角
$radius-aiChatInput_suggestion_item6pxAIChatInput 建议项的圆角
$font-aiChatInput_footer_configure_select-fontWeight600AIChatInput底部配置区域下拉选择的字体粗细
$font-aiChatInput_attachment_content_name-fontWeight600AIChatInput附件项内容的名称字体粗细
$font-aiChatInput_attachment_content_delete-fontSize12pxAIChatInput附件项内容的删除按钮的图标大小
$font-aiChatInput_rich_text-fontSize$font-size-regularAIChatInput富文本编辑器文字大小
$font-aiChatInput_rich_text-lineHeight24pxAIChatInput富文本编辑器文本行高
$font-aiChatInput_rich_text-input_slot-fontSize$font-size-regularAIChatInput富文本编辑器输入插槽文字大小
$font-aiChatInput_rich_text-input_slot-lineHeight20pxAIChatInput富文本编辑器输入框插槽文本行高
$font-aiChatInput_rich_text-input_slot-fontWeight600AIChatInput富文本编辑器输入插槽文本字重
$font-aiChatInput_rich_text-skill_slot-fontWeight600AIChatInput富文本编辑器技能插槽文本字重
$font-aiChatInput_footer_configure_radio_button-fontSize14pxAIChatInput底部配置区域下拉选择的单选按钮的文字大小
$z-aiChatInput_attachment_scroll_button10AIChatInput附件项滚动按钮的z-index
$z-aiChatInput_rich_text-input_slot_placeholder1AIChatInput富文本编辑器输入插槽占位符的z-index
$shadow-aiChatInput_attachment_scroll_buttonvar(--semi-shadow-elevated)AIChatInput附件项滚动按钮的阴影