自定义组件
Web SDK 提供了多种方式来集成自定义组件,使你能够扩展和定制 Web SDK 的功能。本指南将介绍几种常用的方法。
Univer 不接受把组件作为渲染函数的参数。组件必须先通过 Facade API 注册,之后才能在 Univer 挂载自定义内容的各个位置使用。
如果尚未获取 Facade API 实例,请参阅 Facade API。
注册自定义组件
univerAPI.registerComponent(componentKey, CustomComponent, options)使用 univerAPI.registerComponent 注册自定义组件。该方法接受三个参数:
componentKey:组件的唯一标识,Univer 通过它引用该组件。CustomComponent:组件的实现,可以是 React 组件、Vue 组件或 Web Component。options:可选配置,例如组件所依赖的框架。
React 组件
React 组件不需要额外配置,任何合法的 React 组件都可以注册:
function ReactComponent(props: Record<string, any>) { return <div>Hello Univer!</div>}univerAPI.registerComponent('MyReactComponent', ReactComponent)Vue 组件
Vue 3.x
Vue 组件需要通过适配器注册。安装并注册 @univerjs/ui-adapter-vue3 中的 UniverVue3AdapterPlugin:
pnpm add @univerjs/ui-adapter-vue3npm install @univerjs/ui-adapter-vue3yarn add @univerjs/ui-adapter-vue3bun add @univerjs/ui-adapter-vue3import { UniverVue3AdapterPlugin } from '@univerjs/ui-adapter-vue3'univer.registerPlugin(UniverVue3AdapterPlugin)注册 Vue 组件时,将 framework 选项设为 'vue3':
const Vue3Component = defineComponent({ setup(props) { return () => <div>Hello Univer!</div> },})univerAPI.registerComponent('MyVue3Component', Vue3Component, { framework: 'vue3',})Vue 2.x
Vue 2.x 已停止维护(EOL),Univer 不提供对应的 UI 适配器插件。有需要时可以自行编写一个自定义插件实现适配,以下是一份示例代码:
import { DependentOn, Inject, Injector, Plugin } from '@univerjs/core'import { ComponentManager, UniverUIPlugin } from '@univerjs/ui'import Vue from 'vue'/** * The plugin that allows Univer to use Vue 2 components as UI components. */@DependentOn(UniverUIPlugin)export class UniverVue2AdapterPlugin extends Plugin { static override pluginName = 'UNIVER_UI_VUE2_ADAPTER_PLUGIN' constructor( private readonly _config = {}, @Inject(Injector) protected readonly _injector: Injector, @Inject(ComponentManager) protected readonly _componentManager: ComponentManager, ) { super() } override onStarting(): void { const { createElement, useEffect, useRef } = this._componentManager.reactUtils this._componentManager.setHandler('vue2', (component: any) => { return (props: Record<string, any>) => createElement(VueComponentWrapper, { component, props: Object.keys(props).reduce<Record<string, any>>((acc, key) => { if (key !== 'key') { acc[key] = props[key] } return acc }, {}), reactUtils: { createElement, useEffect, useRef }, }) }) }}export function VueComponentWrapper(options: { component: any props: Record<string, any> reactUtils: typeof ComponentManager.prototype.reactUtils}) { const { component, props, reactUtils } = options const { createElement, useEffect, useRef } = reactUtils const domRef = useRef<HTMLDivElement>(null) useEffect(() => { if (!domRef.current) return const Constructor = Vue.extend(component) const instance = new Constructor({ data: props, }) instance.$mount() domRef.current.appendChild(instance.$el) return () => { instance.$destroy() } }, [props]) return createElement('div', { ref: domRef })}然后注册该插件:
import { UniverVue2AdapterPlugin } from './ui-adapter-vue2'univer.registerPlugin(UniverUIPlugin)univer.registerPlugin(UniverVue2AdapterPlugin)Vue 2.x 组件需要将 framework 选项设为 'vue2':
const Vue2Component = Vue.component('MyVue2Component', { template: '<div>Hello, Univer!</div>',})univerAPI.registerComponent('MyVue2Component', Vue2Component, { framework: 'vue2',})Web Components
Web Components 必须符合 Web Components 标准。安装并注册 @univerjs/ui-adapter-web-component 中的 UniverWebComponentAdapterPlugin:
pnpm add @univerjs/ui-adapter-web-componentnpm install @univerjs/ui-adapter-web-componentyarn add @univerjs/ui-adapter-web-componentbun add @univerjs/ui-adapter-web-componentimport { UniverWebComponentAdapterPlugin } from '@univerjs/ui-adapter-web-component'univer.registerPlugin(UniverWebComponentAdapterPlugin)注册 Web Component 时,将 framework 选项设为 'web-component':
class WebComponent extends HTMLElement { constructor() { super() const shadow = this.attachShadow({ mode: 'open' }) const div = document.createElement('div') div.textContent = 'Hello Univer!' shadow.appendChild(div) }}univerAPI.registerComponent('my-web-component', WebComponent, { framework: 'web-component',})Angular
使用 @angular/elements 的 createCustomElement 将 Angular 组件转换为自定义元素,再通过 Univer 的 Web Component 适配器注册。该组件即可用于 Univer 的侧边栏或对话框。
@angular/elements 的版本应与 @angular/core 保持一致,@univerjs/ui-adapter-web-component 的版本应与其他 Univer 包保持一致。
在 Univer 初始化完成后调用该函数,并传入宿主组件的 Angular 注入器。注入器通过 private readonly injector = inject(Injector) 获取,然后调用 registerAngularPanel(univer, univerAPI, this.injector)。宿主组件需从 @angular/core 导入 inject 和 Injector。
import type { Injector } from '@angular/core'import type { FUniver, Univer } from '@univerjs/presets'import { Component } from '@angular/core'import { createCustomElement } from '@angular/elements'import { UniverWebComponentAdapterPlugin } from '@univerjs/ui-adapter-web-component'@Component({ selector: 'app-angular-panel', standalone: true, template: '<p>Hello from Angular!</p>',})export class AngularPanelComponent {}export function registerAngularPanel(univer: Univer, univerAPI: FUniver, injector: Injector) { const element = createCustomElement(AngularPanelComponent, { injector }) univer.registerPlugin(UniverWebComponentAdapterPlugin) return univerAPI.registerComponent('univer-angular-panel', element, { framework: 'web-component', })}编辑器渲染完成后,将注册时使用的 key 作为侧边栏内容:
const sidebar = univerAPI.openSidebar({ header: { title: 'Angular' }, children: { label: 'univer-angular-panel' }, width: 360,})保留返回的注册句柄和侧边栏句柄,不再需要时分别调用 dispose() 释放。每个应用只注册一次该元素,名称必须包含连字符,并且不能与 Angular 组件的 selector 相同。
Angular Elements 将输入映射为元素属性,将输出转换为 DOM 的 CustomEvent 事件。Univer 的适配器会设置属性,但不会订阅 Angular 的输出。需要时应由应用自行订阅这些事件。
使用自定义组件
以下方法涵盖将自定义组件放入 Univer 界面的常见做法。
注意事项
- 调用这些方法前,确认 Univer 已完成渲染。2. 需要注册的组件应先注册再使用。3. 调用
dispose()清理并移除添加的组件,否则会造成内存泄漏。
添加自定义菜单项
顶部菜单栏(Ribbon)和右键菜单(Context Menu)都可以容纳自定义组件。向菜单项添加组件需要编写自定义插件。
替换内置组件
警告
替换内置组件可能破坏依赖该组件的其他功能。替换前请阅读源码和文档,并谨慎操作。
univerAPI.registerComponent 默认注册覆盖组件(override: true)。无论插件是在调用之前还是之后注册内置组件,覆盖组件都会优先生效。每个 componentKey 同时只能有一个生效的覆盖组件,因此再次注册前应先释放上一个。对返回的注册句柄调用 dispose() 会恢复已注册的内置默认组件;传入 { override: false } 则改为注册默认组件。
覆盖组件应在对应视图第一次打开之前注册。注册变化不会自动重新渲染已挂载的视图。
例如,替换内置的 ColorPicker 组件只需要一次调用:
// 此代码仅可在 UI 层面替换内置 ColorPicker 组件,无法替代其功能实现univerAPI.registerComponent('UI_COLOR_PICKER_COMPONENT', () => <input type="color" />)替换用户信息渲染
@univerjs/ui 通过 UserInfo 渲染用户名和头像。UserInfo 使用注册在 USER_INFO_COMPONENT 上的组件进行渲染,未注册时回退到 DefaultUserInfo。在对应视图首次打开前注册宿主组件:
import { USER_INFO_COMPONENT } from '@univerjs/ui'import type { IUserInfoProps } from '@univerjs/ui'function HostUserInfo({ user, part, context, className, fallbackSrc }: IUserInfoProps) { if (part === 'avatar') { return <img className={className} src={user.avatar ?? fallbackSrc} alt="" /> } return ( <span className={className} data-user-id={user.userId} data-scene={context.scene}> {user.name ?? user.userId} </span> )}univerAPI.registerComponent(USER_INFO_COMPONENT, HostUserInfo)UserInfo 会传入以下字段:
user:{ userId?, name?, avatar?, isAnonymous? }。userId是来源用户标识,在用户资料加载完成前即可用,绝不是协同会话 ID。part:'name'或'avatar',组件分别渲染名称和头像。context:{ scene, unitId?, subUnitId?, commentId?, threadId?, versionId?, objectId?, tableId?, fieldId?, recordId? }。scene为'comment-author'、'history-author'、'history-filter'、'permission-member'、'permission-creator'或'base-person'。没有关联文档的独立控件不提供unitId。avatarSize?、fallbackSrc?和className?:头像和名称元素的可选渲染参数。
DefaultUserInfo 渲染内置的名称和头像,可用于宿主未自定义的场景。inheritUserInfoComponent(source, target) 把源 ComponentManager 中的用户信息组件注册到另一个组件管理器(例如用于历史或预览的子 Univer 实例),使同一覆盖组件在这些实例中生效。源管理器未注册时使用 DefaultUserInfo。
该覆盖只改变渲染结果,不影响已持久化的提及、搜索文本或 Canvas 输出。与其他组件覆盖一样,应在视图首次打开前注册。注册变化不会重新渲染已挂载的视图。
作为内容组件添加到……
在侧边栏中使用
univerAPI.openSidebar 可在 Univer 界面中打开一个侧边栏,其内容为已注册的自定义组件。
// 你应该在合适的时机(比如渲染完成)注册组件univerAPI.registerComponent('MyCustomSidebarComponent', () => <div>Hello Univer!</div>)const sidebar = univerAPI.openSidebar({ header: { title: 'My Sidebar' }, children: { label: 'MyCustomSidebarComponent' }, onClose: () => { console.log('close') }, width: 360,})// 稍后关闭侧边栏sidebar.dispose()在对话框中使用
univerAPI.openDialog 可打开一个包含自定义组件的对话框。
// 你应该在合适的时机(比如渲染完成)注册组件univerAPI.registerComponent('MyCustomDialogComponent', () => <div>Hello Univer!</div>)const dialog = univerAPI.openDialog({ id: 'unique-dialog-id', // 对话框的唯一标识符 draggable: true, width: 300, title: { title: 'My Dialog' }, children: { label: 'MyCustomDialogComponent', }, destroyOnClose: true, preservePositionOnDestroy: true, onClose: () => {},})// 稍后关闭对话框dialog.dispose()你觉得这篇文档如何?