自訂元件
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'/** * 允許 Univer 使用 Vue 2 元件作為 UI 元件的插件。 */@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()你覺得這篇文檔如何?