Skip to content

Base 组件扩展

baseComponent 是一个包裹每个渲染区块的组件,可以统一处理普通文本、已注册组件和 fallback。

Props

属性类型说明
blockStreamBlockData区块结构化数据
tagNamestring标签名,普通文本为 text
attrsRecord<string, string | boolean>标签属性
contentstring区块原始内容
isClosedboolean是否闭合
reportData(payload: unknown) => void数据回传

插槽

插槽名说明
defaultStream UI 解析出的原始渲染结果
raw区块的纯文本内容(字符串)
vue
<script setup>
const MarkdownBase = defineComponent({
  props: ['block', 'content'],
  setup(props, { slots }) {
    return () => props.block.category === 'text'
      ? h('span', { innerHTML: renderMarkdown(props.content) })
      : slots.default?.()
  }
})
</script>

<template>
  <StreamContains :model-value="text" :base-component="MarkdownBase">
    <Think />
  </StreamContains>
</template>

StreamBase.with()

Stream UI 内置的 StreamBase 是一个预制的 Base 组件,支持插件式扩展。

vue
<script setup>
import { StreamContains, StreamBase, MdSupport, LatexSupport } from '@huiol/stream-ui'

const BaseComponent = StreamBase.with([MdSupport, LatexSupport])
</script>

<template>
  <StreamContains :model-value="text" :base-component="BaseComponent" />
</template>

插件接口

ts
interface StreamBaseSupport {
  name: string
  match?: (ctx: StreamBaseContext) => boolean    // 是否应用此插件
  transform?: (html: string, ctx: StreamBaseContext) => string  // HTML 转换
  render?: (ctx: StreamBaseContext, next: () => VNodeChild[]) => VNodeChild | VNodeChild[]  // 覆盖渲染
}
  • transformescapeHtml(content) 基础上做字符串替换
  • render 支持覆盖默认渲染,多个插件通过 reduceRight 链式组合(数组后面的先执行)
  • match 返回 false 时跳过该插件,默认始终匹配

内置插件

插件默认 match转换
MdSupportcategory === 'text' || format === 'md'反引号→<code>**bold**<strong>*italic*<em>[link](url)<a>,换行→<br>
LatexSupportcategory === 'text' || format === 'latex' || format === 'md'$...$→行内公式,$$...$$→展示公式

CLI 复制源码

bash
npx @huiol/stream-ui add base base-md base-latex

生成的 src/components/ui/stream-base.tsmd-support.tslatex-support.ts 可以直接修改。

Released under the MIT License.