# 協同編輯

- Human documentation: [https://docs.univer.ai/zh-TW/guides/sheets/features/collaboration](https://docs.univer.ai/zh-TW/guides/sheets/features/collaboration)

- Agent Markdown: [https://docs.univer.ai/zh-TW/guides/sheets/features/collaboration.md](https://docs.univer.ai/zh-TW/guides/sheets/features/collaboration.md)

- Requested language: `zh-TW`

- Content language: `zh-TW`

- Documentation version: `1.2.0`

- Source: [sheets/features/collaboration.zh-TW.mdx](https://github.com/dream-num/documentation/blob/dev/content/guides/sheets/features/collaboration.zh-TW.mdx)

---

#### Package metadata

```json
{
  "preset": [
    {
      "client": "@univerjs/preset-sheets-collaboration",
      "locale": "@univerjs/preset-sheets-collaboration/locales/zh-TW",
      "style": "@univerjs/preset-sheets-collaboration/lib/index.css"
    }
  ],
  "plugins": [
    {
      "client": "@univerjs-pro/collaboration"
    },
    {
      "client": "@univerjs-pro/collaboration-client",
      "facade": "@univerjs-pro/collaboration-client/facade",
      "locale": "@univerjs-pro/collaboration-client/locale/zh-TW"
    },
    {
      "client": "@univerjs-pro/collaboration-client-ui",
      "facade": "@univerjs-pro/collaboration-client-ui/facade",
      "locale": "@univerjs-pro/collaboration-client-ui/locale/zh-TW",
      "style": "@univerjs-pro/collaboration-client-ui/lib/index.css"
    }
  ],
  "license": true,
  "server": true
}
```

請從[協同整合](https://docs.univer.ai/zh-TW/server/collaboration/browser-integration.md)開始，依序執行範例、接入業務、驗證持久化和權限。實作細節與可執行的 Web/Server 範例請見 [協同快速開始](https://docs.univer.ai/zh-TW/server/collaboration/quick-start.md)。

先由經過認證的業務 API 呼叫 Collaboration Service 建立 Unit，再於瀏覽器載入回傳的識別碼。依[協同快速開始](https://docs.univer.ai/zh-TW/server/collaboration/quick-start.md)一起設定 HTTP、Session Ticket 和 WebSocket，以 Database Adapter 持久化，並透過[伺服器端 Middleware](https://docs.univer.ai/zh-TW/server/collaboration/identity-and-authorization.md)分別檢查讀取、JOIN 和修改權限。

## 載入文件

先設定目前使用者，再載入文件。目前使用者決定協同編輯的身分與本機離線快取的歸屬。設定目前使用者後呼叫 Facade 方法明確載入：

```ts
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')
```

透過[同步狀態、重送與衝突復原](https://docs.univer.ai/zh-TW/server/collaboration/browser-integration.md#sync-status)實作儲存提示，並在重新整理前保護尚未確認的修改。

## 移除內建 URL 載入協同文件

> [!WARNING: 注意事項]
> 從 **1.2.0** 版本開始，Univer 移除了內建的 URL 協同文件載入邏輯，不再自動讀取 URL 中的 `unit`、`type` 和 `subunit` 參數來載入協同文件及定位工作表。

如果你的應用程式依賴這項行為，可以透過自訂外掛恢復。

### 接入自訂外掛

將下方四個檔案依照以下目錄結構複製到專案中：

```text
custom-url-load/
├── plugin.ts
├── controllers/
│   └── data-loader.controller.ts
└── services/
    ├── url.service.ts
    └── web-url.service.ts
```

完成編輯器和協同外掛初始化後，先設定目前使用者，再註冊 `CustomUrlLoadPlugin`。外掛模式和預設模式皆可使用此接入方式：

```ts
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。

### 完整外掛程式碼

#### plugin.ts

```ts
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))
  }
}
```

#### controllers/data-loader.controller.ts

```ts
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)
  }
}
```

#### services/url.service.ts

```ts
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')
```

#### services/web-url.service.ts

```ts
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())
    }
  }
}
```

[Node.js / AI SDK](https://docs.univer.ai/zh-TW/ai/content-operations.md) · [OT](/blog/ot)
