協同編輯
先按協同整合執行官方範例,接入應用,並確認持久化與權限均正常。實現細節與可執行的 Web/Server 範例見協同快速開始。
業務 API 完成認證後呼叫 Collaboration Service 建立單元,瀏覽器隨後載入該呼叫返回的標識。HTTP、Session Ticket 與 WebSocket 三個入口需一併配置,方法見快速開始。資料透過 Database Adapter 持久化,讀取、JOIN 與修改權限由伺服器端 Middleware負責。
使用這些 API 前,請確認目標後端支援 PDF 單元。Sheets 協同範例可以正常執行,並不代表 PDF 同樣受支援。
載入協作 PDF
無論 PDF 單元由伺服器端 API 還是由 importPdfToUnitIdAsync 建立,都需在設定當前使用者之後,透過協作 Facade 載入。使用者設定見協同整合。
import { UserManagerService } from '@univerjs/core'import '@univerjs-pro/collaboration-client/facade'univer.__getInjector().get(UserManagerService).setCurrentUser({ userID, name, avatar })const pdf = await univerAPI.getCollaboration().loadPdfAsync(unitId)if (!pdf) { throw new Error(`PDF unit not found: ${unitId}`)}console.log(pdf.getId(), pdf.getName())loadPdfAsync 載入伺服器端快照,準備協作會話,並返回 FPdf。當該單元無法關聯到 PDF 時,它返回 null。
如需建置儲存狀態提示,或在頁面重新整理前保留伺服器端尚未確認的修改,請參閱同步狀態、重發與衝突恢復。
移除內建 URL 載入協同文件
注意事項
從 1.2.0 版本開始,Univer 移除了協同文件的內建 URL 載入邏輯,不再自動讀取 URL 中的 unit 與 type 參數來載入協同文件。
如果應用依賴此行為,可透過自定義外掛恢復。
接入自訂外掛
將以下四個檔案按下列目錄結構複製到專案中:
custom-url-load/├── plugin.ts├── controllers/│ └── data-loader.controller.ts└── services/ ├── url.service.ts └── web-url.service.ts先初始化編輯器與協同外掛,再設定當前使用者,然後註冊 CustomUrlLoadPlugin。
import { UserManagerService } from '@univerjs/core'import { CustomUrlLoadPlugin } from './custom-url-load/plugin'univer.__getInjector().get(UserManagerService).setCurrentUser({ userID, name, avatar })univer.registerPlugin(CustomUrlLoadPlugin)註冊後,文件載入由該外掛完成,同一文件無需再呼叫 loadPdfAsync()。如果應用已透過 Facade 載入文件,可沿用上一節的做法,URL 的處理方式由業務自行決定。
完整外掛程式碼
import { UniverCollaborationClientPlugin } from '@univerjs-pro/collaboration-client'import { DependentOn, Inject, Injector, Plugin } from '@univerjs/core'import { CollaborationDataLoaderController } from './controllers/data-loader.controller'import { IURLService } from './services/url.service'import { WebURLService } from './services/web-url.service'@DependentOn(UniverCollaborationClientPlugin)export class CustomUrlLoadPlugin extends Plugin { static override pluginName = 'CUSTOM_URL_LOAD_PLUGIN' constructor( _config: undefined, @Inject(Injector) protected override readonly _injector: Injector ) { super() } override onStarting(): void { this._injector.add([IURLService, { useClass: WebURLService }]) this._injector.add([CollaborationDataLoaderController]) this.disposeWithMe(this._injector.get(IURLService)) this.disposeWithMe(this._injector.get(CollaborationDataLoaderController)) }}import { DataLoaderService } from '@univerjs-pro/collaboration-client'import { ILogService, Inject, RxDisposable } from '@univerjs/core'import { IURLService } from '../services/url.service'/** * 透過 URL 參數載入協同文件。 */export class CollaborationDataLoaderController extends RxDisposable { constructor( @IURLService private readonly _urlService: IURLService, @ILogService private readonly _logService: ILogService, @Inject(DataLoaderService) private readonly _dataLoaderService: DataLoaderService ) { super() const unitId = this._urlService.getParam('unit') const type = this._urlService.getParam('type') if (!unitId || !type) { return } this._dataLoaderService.loadUnit(unitId, Number(type)) .catch((error: unknown) => { this._logService.error('[CollaborationDataLoaderController]', error) }) }}import type { IDisposable } from '@univerjs/core'import type { Observable } from 'rxjs'import { createIdentifier } from '@univerjs/core'export interface IURLService extends IDisposable { getParam: (key: string) => string | undefined setParam: (key: string, value: string, useReplace?: boolean) => void removeParam: (key: string, useReplace?: boolean) => void readonly urlChange$: Observable<void>}export const IURLService = createIdentifier<IURLService>('demo.custom-url-load.url-service')import type { IURLService } from './url.service'import { RxDisposable } from '@univerjs/core'import { fromEvent, map, shareReplay, takeUntil } from 'rxjs'export class WebURLService extends RxDisposable implements IURLService { readonly urlChange$ = fromEvent(window, 'popstate').pipe( map(() => undefined), takeUntil(this.dispose$), shareReplay({ bufferSize: 1, refCount: true }) ) getParam(key: string): string | undefined { return new URL(window.location.href).searchParams.get(key) ?? undefined } setParam(key: string, value: string, useReplace = false): void { const url = new URL(window.location.href) url.searchParams.set(key, value) this._updateUrl(url, useReplace) } removeParam(key: string, useReplace = false): void { const url = new URL(window.location.href) url.searchParams.delete(key) this._updateUrl(url, useReplace) } private _updateUrl(url: URL, useReplace: boolean): void { if (useReplace) { window.history.replaceState(window.history.state, '', url.toString()) } else { window.history.pushState(window.history.state, '', url.toString()) } }}你覺得這篇文檔如何?