공동 편집
협업 편집은 브라우저 편집기 뒤에 백엔드가 필요합니다. 협업 통합: 예제를 실행하면 애플리케이션의 정체성, 권한 및 저장을 연결합니다. 협업 빠른 시작는 브라우저와 서버 구성을 다룹니다.
응용 프로그램에 인증된 API를 통해 문서를 작성한 후, API가 아래의 메소드를 반환하는 단위 식별자를 로드합니다. 동일한 문서가 다시 열릴 때마다 식별자를 재사용합니다.
문서 로드
문서를 로딩하기 전에 현재 사용자를 설정합니다. 현재 사용자는 콜레터를 식별하고 로컬 오프라인 캐시를 소유합니다. 그 후 Facade를 통해 명시적으로 문서를로드하십시오.
import { UserManagerService } from '@univerjs/core'import '@univerjs-pro/collaboration-client/facade'univer.__getInjector().get(UserManagerService).setCurrentUser({ userID, name, avatar })const collaboration = univerAPI.getCollaboration()const unit = await collaboration.loadSheetAsync('your-unit-id')저장 표시기를 위해, 또는 서버가 재부하의 앞에 인식되지 않은 편집을 보호하는 것은, 동기화 상태, retries 및 충돌 복구를 보십시오.
공동 편집 문서의 기본 URL 로드 기능 제거
* 이름 *
1.2.0 버전으로 Univer는 공동 문서에 대한 내장 URL로드를 제거했습니다. 더 이상 unit, type 및 subunit URL 매개 변수를 자동으로 읽을 수 없습니다.
응용 프로그램이 그 행동에 따라 달라지면 사용자 정의 플러그인이 복원 할 수 있습니다.
사용자 정의 플러그인 연결
프로젝트 아래에 4개의 파일을 복사하고 이 디렉토리 구조를 유지하십시오:
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)그 후, 플러그인은 문서 자체를로드하므로 응용 프로그램은 동일한 문서에 loadSheetAsync()를 호출하지 않습니다. 응용 프로그램은 이미 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 type { ISetWorksheetActivateCommandParams } from '@univerjs/sheets'import type { Subscription } from 'rxjs'import { DataLoaderService } from '@univerjs-pro/collaboration-client'import { ICommandService, ILogService, Inject, IUniverInstanceService, RxDisposable, toDisposable, UniverInstanceType, Workbook,} from '@univerjs/core'import { SetWorksheetActivateCommand } from '@univerjs/sheets'import { takeUntil } from 'rxjs'import { IURLService } from '../services/url.service'/** * URL 매개변수로 공동 편집 문서를 로드하고 같은 문서 내 워크시트 탐색을 동기화한다. */export class CollaborationDataLoaderController extends RxDisposable { private _unitId: string | undefined private _unitType = UniverInstanceType.UNIVER_SHEET private _workbook: Workbook | null = null private _activeSheetSubscription: Subscription | null = null constructor( @IURLService private readonly _urlService: IURLService, @ILogService private readonly _logService: ILogService, @ICommandService private readonly _commandService: ICommandService, @Inject(DataLoaderService) private readonly _dataLoaderService: DataLoaderService, @IUniverInstanceService private readonly _instanceService: IUniverInstanceService ) { super() this._init() } private _init(): void { this._unitId = this._urlService.getParam('unit') const type = this._urlService.getParam('type') if (!this._unitId || !type) { return } this._unitType = Number(type) this.disposeWithMe(toDisposable(() => this._unbindWorkbook())) // 이력 복원 시 문서 ID를 유지하면서 Workbook이 교체될 수 있으므로 다시 바인딩한다. this._dataLoaderService.unitLoaded$.pipe(takeUntil(this.dispose$)).subscribe((unit) => { if (unit instanceof Workbook && unit.getUnitId() === this._unitId) { this._bindWorkbook(unit).catch((error: unknown) => this._reportError(error)) } }) this._instanceService.unitDisposed$.pipe(takeUntil(this.dispose$)).subscribe((unit) => { if (unit === this._workbook) { this._unbindWorkbook() } }) this._urlService.urlChange$.pipe(takeUntil(this.dispose$)).subscribe(() => { if (this._workbook) { this._activateWorksheetFromUrl(this._workbook).catch((error: unknown) => this._reportError(error)) } }) this._dataLoaderService.loadUnit(this._unitId, this._unitType, this._urlService.getParam('subunit')) .catch((error: unknown) => this._reportError(error)) } private async _bindWorkbook(workbook: Workbook): Promise<void> { this._unbindWorkbook() this._workbook = workbook // 스냅샷 재생은 모델을 직접 갱신하므로 워크시트를 한 번 활성화하여 렌더러에 알린다. await this._activateWorksheetFromUrl(workbook, true) if (this._workbook !== workbook || this._disposed) { return } this._activeSheetSubscription = workbook.activeSheet$.subscribe((worksheet) => { if (worksheet) { this._updateUrl(worksheet.getSheetId()) } }) } private _unbindWorkbook(): void { this._activeSheetSubscription?.unsubscribe() this._activeSheetSubscription = null this._workbook = null } private _matchesDocument(): boolean { return this._urlService.getParam('unit') === this._unitId && Number(this._urlService.getParam('type')) === this._unitType } private async _activateWorksheetFromUrl(workbook: Workbook, forceActivate = false): Promise<void> { if (this._disposed || this._workbook !== workbook || !this._matchesDocument()) { return } const requestedSheetId = this._urlService.getParam('subunit') const worksheet = (requestedSheetId ? workbook.getSheetBySheetId(requestedSheetId) : null) ?? workbook.getSheetBySheetId(workbook.getUnhiddenWorksheets()[0]) if (!worksheet) { return } const subUnitId = worksheet.getSheetId() if (subUnitId !== requestedSheetId) { this._updateUrl(subUnitId, true) } if (!forceActivate && workbook.getActiveSheet()?.getSheetId() === subUnitId) { return } await this._commandService.executeCommand<ISetWorksheetActivateCommandParams>(SetWorksheetActivateCommand.id, { unitId: workbook.getUnitId(), subUnitId, }) } private _updateUrl(subUnitId: string, replace = false): void { if (this._matchesDocument() && this._urlService.getParam('subunit') !== subUnitId) { this._urlService.setParam('subunit', subUnitId, replace) } } private _reportError(error: unknown): void { 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()) } }}이 가이드는 어떠셨나요?