自訂元件
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)註冊元件時將 framework 指定為 'vue3':
const Vue3Component = defineComponent({ setup(props) { return () => <div>Hello Univer!</div> },})univerAPI.registerComponent('MyVue3Component', Vue3Component, { framework: 'vue3',})Vue 2.x
Vue 2.x 已停止維護,Univer 目前未提供 Vue 2.x 的 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)註冊元件時將 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 介面卡註冊該元素後,Angular 元件即可顯示在 Univer 的側邊欄或對話方塊中。
@angular/elements 的版本需與 @angular/core 一致,@univerjs/ui-adapter-web-component 的版本需與其他 Univer 包一致。
在 Univer 初始化之後呼叫該函式。注入器由宿主元件傳入:宿主元件用 private readonly injector = inject(Injector) 取得注入器,然後呼叫 registerAngularPanel(univer, univerAPI, this.injector)。宿主元件中的 inject 和 Injector 均從 @angular/core 匯入。
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 已完成渲染後再呼叫這些方法。
- 使用元件前先完成註冊。
- 使用
dispose()清理新增的內容,避免記憶體洩漏。
添加自訂選單項目
頂部選單欄(Ribbon)和右鍵選單(Context Menu)都可以承載自定義元件。選單項由外掛註冊,因此新增選單項需要編寫自定義外掛。新增自定義選單項的最佳實踐可以作為起點。
替換內建元件
警告
替換內建元件可能導致依賴該元件的功能失效。替換前請閱讀原始碼和文件,確認哪些元件可以替換,並謹慎操作。
univerAPI.registerComponent 預設註冊覆蓋元件(override: true)。無論外掛在呼叫之前還是之後註冊內建預設元件,覆蓋元件都優先。每個 componentKey 同時只能有一個生效的覆蓋元件,因此再次註冊前需先釋放上一個註冊。對返回值呼叫 dispose() 可以恢復已註冊的內建預設元件。傳入 { override: false } 則註冊預設元件。
覆蓋元件需要在對應檢視第一次開啟之前完成註冊。註冊發生變化不會讓已經掛載的檢視自動重新渲染。
Sheets 從包的公共入口匯出以下標識,覆蓋對應的內建元件時使用這些標識:
| 元件 | 匯出的識別碼 | 套件 |
|---|---|---|
| 定義名稱 | DEFINED_NAME_CONTAINER | @univerjs/sheets-ui |
| 更多函數 | MORE_FUNCTIONS_COMPONENT | @univerjs/sheets-formula-ui |
| 資料驗證 | DATA_VALIDATION_PANEL | @univerjs/sheets-data-validation-ui |
| 條件式格式 | CF_PANEL_KEY | @univerjs/sheets-conditional-formatting-ui |
例如,以下程式碼替換內建的 ColorPicker 元件:
// 此程式碼僅可在 UI 層面替換內建 ColorPicker 元件,無法替代其功能實現univerAPI.registerComponent('UI_COLOR_PICKER_COMPONENT', () => <input type="color" />)作為內容元件添加到……
在側邊欄中使用
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()將彈出框附加到儲存格
FRange.attachPopup 將自定義彈出框附加到指定的單元格範圍。
- Popup 是依附在單元格上的臨時 DOM 元素,通常用於顯示臨時狀態資訊,不支援持久化儲存。
- 方法簽名是
FRange.attachPopup(popup: IFCanvasPopup)。 - Popup 附著在單元格的四邊,被遮擋時會自動調整位置和方向。
// 你應該在合適的時機(例如渲染完成)註冊元件univerAPI.registerComponent( 'MyCustomPopupComponent', () => <div>Hello Univer!</div>,)const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:J10')// 將彈出窗口附加到範圍的第一個儲存格// 如果 `disposable` 為 null,則表示 popup 添加失敗const disposable = fRange.attachPopup({ componentKey: 'MyCustomPopupComponent',})// 移除彈出框disposable.dispose()附加警告彈出框
FRange.attachAlertPopup 在指定範圍的起始單元格上附加警告彈出框。
const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()const fRange = fWorksheet.getRange('A1:B2')const disposable = fRange.attachAlertPopup({ key: 'unique-alert-key', // 唯一識別符 title: '這是一個警告!', message: '這是一個警告!', width: 300, height: 200, // 0: 資訊 // 1: 警告 // 2: 錯誤 type: 0,})// 稍後移除警告disposable.dispose()添加浮動 DOM 到工作表
FWorksheet.addFloatDomToPosition 在工作表中新增浮動 DOM 元素。
- 使用前需要安裝
@univerjs/sheets-drawing-ui外掛或@univerjs/preset-sheets-drawing預設。 - 浮動 DOM 元素是懸浮在工作表上、可以拖動的元件,支援持久化儲存。
- 需要在 Univer 渲染完成後呼叫。
componentKey:元件的唯一標識,Univer 內部透過它引用元件。- 完整的參數定義
// 你應該在合適的時機(例如渲染完成)註冊元件univerAPI.registerComponent( 'MyCustomFloatingDOMComponent', ({ data }) => ( <div> Hello {data?.label} ! </div> ),)const fWorkbook = univerAPI.getActiveWorkbook()const fWorksheet = fWorkbook.getActiveSheet()// 添加一個浮動 DOM// 如果 `disposable` 為 null,則表示浮動 DOM 添加失敗const disposable = fWorksheet.addFloatDomToPosition({ componentKey: 'MyCustomFloatingDOMComponent', initPosition: { startX: 100, endX: 200, startY: 100, endY: 200, }, // 這是元件的資料 data: { label: 'Univer', },})// 移除浮動 DOMdisposable.dispose()你覺得這篇文檔如何?