사용자 지정 컴포넌트
Web SDK는 사용자 정의 컴포넌트를 통합하는 다양한 방법을 제공하여 기능을 확장하고 원하는 대로 구성할 수 있도록 지원합니다. 이 가이드에서는 일반적으로 사용하는 몇 가지 방법을 소개합니다.
Univer는 렌더링 기능에 인수로 구성 요소를 허용하지 않습니다. 구성 요소는 Facade API가 사용자 정의 콘텐츠를 마운트하는 모든 위치에서 사용할 수있는 Univer를 통해 먼저 등록해야합니다.
Facade API 인스턴스가 아직 사용할 수없는 경우 Facade API를 참조하십시오.
사용자 지정 컴포넌트 등록
univerAPI.registerComponent(componentKey, CustomComponent, options)univerAPI.registerComponent를 사용하여 사용자 정의 구성 요소를 등록하십시오. 방법은 세 가지 매개 변수를 받아들입니다.
componentKey: Univer가 나중에 참조하는 구성 요소의 고유 식별자.CustomComponent: React 구성 요소, Vue 부품 또는 웹 구성 요소가 될 수있는 구성 요소 구현.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 부품이 등록되면 'vue3'에 framework 옵션을 설정하십시오.
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 접합기 플러그인을 제공하지 않습니다. 주문 플러그인은 접합기를 대신 실행할 수 있습니다. 뒤에 오는 예는 1개의 실시를 보여줍니다:
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
웹 구성 요소는 웹 구성 요소 표준을 따르야한다. @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 옵션을 설정:
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 웹 구성 요소 어댑터를 통해 요소를 등록하십시오. 구성 요소는 Univer 측바 또는 대화 상자에서 사용할 수 있습니다.
@angular/core, @univerjs/ui-adapter-web-component와 같은 버전에서 @angular/elements를 다른 Univer 패키지와 같은 버전으로 유지하십시오.
Univer가 초기화되고, 호스트 구성 요소의 Angular 인젝터를 통과 한 후 함수를 호출합니다. 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', })}편집기 렌더링 후 등록한 키를 사이드바 콘텐츠로 사용하세요.
const sidebar = univerAPI.openSidebar({ header: { title: 'Angular' }, children: { label: 'univer-angular-panel' }, width: 360,})반환된 등록 및 사이드바 핸들을 유지하고 dispose()를 호출하면 더 이상 필요하지 않습니다. 응용 프로그램에 한 번 요소를 등록하십시오. 그 이름은 하이픈을 포함해야하며 Angular 구성 요소 선택기와 다릅니다.
Angular 요소 맵은 요소 속성에 입력하고 DOM CustomEvent 이벤트에 출력합니다. Univer 어댑터 세트 속성을 설정하지만 Angular 출력에 가입하지 않습니다. 응용 프로그램은 필요한 경우 해당 이벤트에 가입합니다.
사용자 지정 컴포넌트 사용
아래의 방법은 Univer UI에서 사용자 정의 구성 요소를 배치하는 일반적인 방법을 다룹니다.
주의
- Univer가이 방법을 호출하기 전에 렌더링을 완료 할 때까지 기다리십시오. 2. 사용 전에 등록해야하는 등록 구성 요소. 3.
dispose()를 청소하고 추가 구성 요소를 제거하십시오. 그렇지 않으면 응용 프로그램 누출 메모리.
사용자 지정 메뉴 항목 추가
상단 메뉴 바 (Ribbon) 및 오른쪽 클릭 메뉴 (Context Menu)는 사용자 정의 구성 요소를 포함 할 수 있습니다. 메뉴 항목에 구성 요소를 추가하면 사용자 정의 플러그인이 필요합니다.
기본 제공 컴포넌트 교체
- 기타
내장 구성 요소를 대체하기 전에 소스 코드와 문서를 읽고 caution로 진행할 수 있습니다.
univerAPI.registerComponent는 기본 (override: true)에 의해 과속을 기록합니다. 과속은 플러그인이 이전 또는이 호출 후 기본을 등록하는 경우 내장 구성 요소에 대해 우선적으로 걸립니다. 하나의 과속은 componentKey 당 활성 할 수 있으므로 다른 등록을 해제하기 전에 이전 등록을 해제합니다. 반환 등록에 dispose()를 호출하면 내장 기본을 복원합니다. 대신 기본을 등록하려면 { override: false }를 통과하십시오.
해당 뷰가 처음 열리기 전에 오버라이드를 등록하십시오. 등록 변경은 이미 장착 된 레이아웃을 자동으로 렌더링하지 않습니다.
예를 들어, 내장 ColorPicker 구성 요소를 대체하면 단일 통화가 필요합니다.
// Following code only replaces the UI of the built-in ColorPicker component, not its functionalityuniverAPI.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 인터페이스의 사이드 바를 엽니다.
// You should register the component at an appropriate time (e.g., after Univer has loaded)univerAPI.registerComponent('MyCustomSidebarComponent', () => <div>Hello Univer!</div>)const sidebar = univerAPI.openSidebar({ header: { title: 'My Sidebar' }, children: { label: 'MyCustomSidebarComponent' }, onClose: () => { console.log('close') }, width: 360,})// Later close the sidebarsidebar.dispose()univerAPI.openSidebar를 참조하십시오.
대화 상자에서 사용
univerAPI.openDialog는 사용자 정의 구성 요소인 대화 상자를 엽니다.
// You should register the component at an appropriate time (e.g., after Univer has loaded)univerAPI.registerComponent('MyCustomDialogComponent', () => <div>Hello Univer!</div>)const dialog = univerAPI.openDialog({ id: 'unique-dialog-id', // The unique identifier for the dialog draggable: true, width: 300, title: { title: 'My Dialog' }, children: { label: 'MyCustomDialogComponent', }, destroyOnClose: true, preservePositionOnDestroy: true, onClose: () => {},})// Later close the dialogdialog.dispose()univerAPI.openDialog를 참조하십시오.
이 가이드는 어떠셨나요?