Skip to content

Collaboration ​

For an existing application-owned Yjs provider, use collaboration.externalSession. See Host-owned collaboration for the shared contract.

PowerPointViewerComponent supports real-time, multi-user editing built on Yjs (a CRDT) with either a WebSocket transport (y-websocket, needs a server) or a serverless peer-to-peer transport (y-webrtc). When enabled, it adds granular CRDT document sync (per slide / element / field), live remote cursors, selection highlights, user presence, and follow mode. In single-user mode none of this is loaded.

Optional peer dependencies

Collaboration requires the yjs peer plus the provider for your transport: y-websocket (server-based) or y-webrtc (peer-to-peer). The viewer works fully without them - it simply runs single-user. Install them only when you need co-editing:

bash
npm i yjs y-websocket   # server-based
npm i yjs y-webrtc      # serverless peer-to-peer

Enabling it: the collaboration input ​

Pass a CollaborationConfig to the collaboration input. When present, the viewer wires up presence tracking, remote cursors, and CRDT sync via its internal CollaborationService.

ts
import { Component, signal } from '@angular/core';
import { PowerPointViewerComponent } from 'pptx-angular-viewer';
import type { CollaborationConfig } from 'pptx-angular-viewer';

@Component({
	standalone: true,
	imports: [PowerPointViewerComponent],
	template: `<pptx-viewer [content]="bytes" [canEdit]="true" [collaboration]="config()" />`,
})
export class Example {
	readonly config = signal<CollaborationConfig>({
		roomId: 'my-room-123',
		serverUrl: 'wss://collab.example.com',
		userName: 'Alice',
		userColor: '#6366f1',
	});
}

CollaborationConfig ​

ts
type CollaborationRole = 'owner' | 'collaborator' | 'viewer';
type CollaborationTransport = 'websocket' | 'webrtc';

interface CollaborationConfig {
	/** Unique room id (alphanumeric, hyphens, underscores). */
	roomId: string;
	/** WebSocket URL for the Yjs provider, e.g. "wss://collab.example.com". Ignored for webrtc. */
	serverUrl: string;
	/** Transport - 'websocket' (default) or serverless 'webrtc'. */
	transport?: CollaborationTransport;
	/** WebRTC signaling server URLs (webrtc transport only). */
	signaling?: string[];
	/** Session secret, required for webrtc (see "Serverless peer-to-peer mode"). */
	secret?: string;
	/** Display name for the local user. */
	userName: string;
	/** Avatar URL for the local user (optional). */
	userAvatar?: string;
	/** Hex colour for the local user's cursor / presence indicator. */
	userColor?: string;
	/** Optional auth token sent with the WebSocket handshake (webrtc uses `secret`). */
	authToken?: string;
	/** Session role - defaults to 'collaborator'. */
	role?: CollaborationRole;
	/** Elected-writer persistence: the 'owner' peer receives debounced PPTX snapshots. */
	onWriteBack?: (bytes: Uint8Array) => void | Promise<void>;
	/** Debounce (ms) between the last change and onWriteBack. Default 5000. */
	writeBackDebounceMs?: number;
	/** Retries of a rejected onWriteBack, exponential backoff. Default: none. */
	writeBackRetry?: { attempts: number; baseDelayMs?: number; maxDelayMs?: number };
}
FieldTypeRequiredNotes
roomIdstringyesSanitized; restrict to alphanumeric / - / _.
serverUrlstringyesy-websocket server URL; may be '' when transport: 'webrtc'.
transportCollaborationTransportno'websocket' (default) or 'webrtc' (serverless P2P).
signalingstring[]noy-webrtc signaling URLs; defaults to y-webrtc's public list.
secretstringwebrtcSession secret from createShareSecret(); hashed into the signaling room and used as the y-webrtc password.
userNamestringyesLocal user's display name; also used as comment/annotation author when authorName is unset.
userAvatarstringnoValidated avatar URL.
userColorstringnoHex colour for the user's cursor ring.
authTokenstringnoWebSocket handshake param (webrtc uses secret).
roleCollaborationRoleno'owner', 'collaborator' (default), or 'viewer'.
onWriteBack(bytes) => void | Promise<void>noOnly fires for the 'owner' peer: debounced serialized PPTX snapshots. A returned promise is the acknowledgement; status is in collaborationState.writeBack.
writeBackDebounceMsnumbernoDefault 5000 ms.
writeBackRetry{ attempts: number; baseDelayMs?: number; maxDelayMs?: number }noRetries of a rejected onWriteBack with exponential backoff. Default: none.

Serverless peer-to-peer mode ​

With transport: 'webrtc' no document server is needed: peers exchange updates directly over WebRTC, and tabs in the same browser connect through BroadcastChannel even with no network at all. This is how the hosted GitHub Pages demos collaborate. Cross-device sessions meet through WebRTC signaling servers (metadata only - document data never passes through them); supply your own via signaling for production use. In the built-in Share/Broadcast dialogs, leaving the server URL empty selects this transport.

A 'webrtc' session needs secret, a fresh 128-bit value from createShareSecret() (exported by ooxml-core/collab and ooxml-ui/pptx). A SHA-256 hash of the secret names the signaling room and the secret is the y-webrtc password, so the signaling servers see neither roomId nor clear signaling data. The built-in dialogs generate one, invitation links carry it in their #key= fragment (which browsers never send to a server), and a 'webrtc' config without it fails to connect.

Input is sanitized

Room ids, user names, avatar URLs, cursor positions, and presence data pass through sanitization in the collaboration layer (collaboration-helpers.ts). Keep roomId to alphanumerics, hyphens, and underscores to avoid surprises.

Your own provider, or sharing in one browser ​

Besides CollaborationConfig, the collaboration option takes the shared contract of Word, Excel and Visio (CollaborationOptions from ooxml-core/collab). Two forms need no host-owned session; the viewer opens the session itself and destroys it when collaboration stops:

ts
// provider created by the host
collaboration = { roomId: 'deck-review', provider, user: { name: 'Ada' }, intent: 'join' as const };
// Same browser only:
collaboration = { roomId: 'deck-review', user: { name: 'Ada' } };
html
<pptx-power-point-viewer [content]="bytes" [collaboration]="collaboration" />
  • provider (a ProviderFactory, for example transportProvider or an existing provider through adaptYjsProvider) wins over serverUrl.
  • With no session, provider, serverUrl or transport, the room is shared between tabs and windows of this browser over a BroadcastChannel (ooxml-pptx:<roomId>), with no server.
  • Precedence is session (borrowed, never destroyed) > provider > serverUrl > BroadcastChannel. A legacy CollaborationConfig with serverUrl keeps y-websocket; one with transport: 'webrtc' or a blank serverUrl keeps the serverless y-webrtc transport.
  • intent: 'join' never seeds an empty room with the local deck. The session is writable once it syncs (or after the grace period for a lone peer); a role: 'viewer' stays read-only.
  • The state reports status: 'connecting' while the session opens and error for an invalid room or an unavailable BroadcastChannel.

Controlling sessions: Share/Broadcast dialog events ​

Collaboration is controlled by the host app, same as React/Vue. The viewer's Share and Broadcast dialogs report intent via outputs; you flip the collaboration input in response.

Output/InputTypePurpose
startCollaborationoutput<CollaborationConfig>User started a session from the Share/Broadcast dialog - set the collaboration input with this config.
stopCollaborationoutput<void>User stopped the session - clear the collaboration input.
collaborationChangeoutput<CollaborationState>The shared state (active, roomId, status, synced, people), also for a host-owned session; the off state on stop.
shareDefaultsinput<{ roomId?; userName?; serverUrl? }>Pre-fills the Share dialog fields; falls back to authorName for userName, empty otherwise.
ts
@Component({
	template: `
		<pptx-viewer
			[content]="content"
			[canEdit]="true"
			[collaboration]="collab()"
			[shareDefaults]="{ serverUrl: 'wss://collab.example.com', userName: 'Alice' }"
			(startCollaboration)="collab.set($event)"
			(stopCollaboration)="collab.set(undefined)"
		/>
	`,
})
export class CollaborativeEditorComponent {
	readonly collab = signal<CollaborationConfig | undefined>(undefined);
}

Presence and remote cursors ​

While a session is active the viewer renders:

  • Remote cursors on the slide canvas (CollaborationCursorsComponent), each labelled with the user's name and colour.
  • Remote selection highlights (RemoteSelectionOverlayComponent) around elements another peer has selected.
  • A follow-mode banner (FollowModeBarComponent) letting the local user follow a peer's active slide.

Presence data is broadcast via Yjs awareness. Each participant publishes a presence record (client id, name, colour, active slide index, clamped cursor X/Y, selected element id, role, last-updated timestamp), which drives the cursor and presence UI.

Building custom collaboration UI ​

For a custom editor shell, use ViewerCollaborationShellService alongside POWER_POINT_VIEWER_PROVIDERS. It composes the existing loader, editor, session, canvas-editing, and cursor services; it does not create a second collaboration controller or transport. Call bind() once from the host component constructor with reactive accessors:

ts
import { Component, inject, input, viewChild } from '@angular/core';
import {
	POWER_POINT_VIEWER_PROVIDERS,
	SlideCanvasComponent,
	ViewerCollaborationShellService,
} from 'pptx-angular-viewer';
import type {
	CollaborationConfig,
	CollaborationShellState,
	ViewerCollaborationShellOptions,
} from 'pptx-angular-viewer';

@Component({
	selector: 'app-custom-slides',
	standalone: true,
	providers: [...POWER_POINT_VIEWER_PROVIDERS, ViewerCollaborationShellService],
	imports: [SlideCanvasComponent],
	template: `
		<pptx-slide-canvas
			[slide]="shell.activeSlide()"
			[canvasSize]="shell.loader.canvasSize()"
			[mediaDataUrls]="shell.loader.mediaDataUrls()"
			[templateElements]="shell.activeTemplateElements()"
			[editable]="shell.canEdit()"
			[selectedIds]="shell.editor.selectedIds()"
			[editingId]="shell.canvasEditing.editingId()"
			(elementSelect)="shell.canvasEditing.onElementSelect($event)"
			(textEditStart)="shell.canvasEditing.onTextEditStart($event.id)"
			(textInput)="shell.canvasEditing.onTextInput($event)"
			(textCommit)="shell.canvasEditing.onTextCommit($event)"
			(textCancel)="shell.canvasEditing.editingId.set(null)"
			(listSession)="shell.canvasEditing.onListSession($event)"
		/>
	`,
})
export class CustomSlidesComponent {
	readonly content = input<Uint8Array | null>(null);
	readonly collaboration = input<CollaborationConfig>();
	readonly canEdit = input(true);
	readonly shell = inject(ViewerCollaborationShellService);
	readonly canvas = viewChild(SlideCanvasComponent);

	constructor() {
		const options: ViewerCollaborationShellOptions = {
			content: this.content,
			collaboration: this.collaboration,
			canEdit: this.canEdit,
			stageElement: () => this.canvas()?.getStageElement(),
		};
		this.shell.bind(options);
	}

	getState(): CollaborationShellState {
		return this.shell.state();
	}
	getContent(): Promise<Uint8Array> {
		return this.shell.getContent();
	}
}

The example wires text editing; connect the canvas transform, table, and other outputs for the operations your shell exposes. Gate custom mutation controls with shell.canEdit(), not just the requested host permission. Save rejects unfinished native input or IME composition instead of serializing an older text snapshot. The effective gate also accounts for the active session's role/readiness and a real source still loading or failing to load. A blank editor without collaboration retains its ordinary host-controlled permission. getContent() saves the current editable model even when a viewer role or a paused session disables editing.

shell.state() exposes normalized remoteUsers, connection status, and connectedCount. For canvas presence, forward pointer movement to shell.cursor.onPointerMove($event) and project CollaborationCursorsComponent and RemoteSelectionOverlayComponent inside SlideCanvasComponent. Supply shell.cursor.cursors(), shell.collaboration.presence(), the active slide's elements, and shell.activeSlideIndex(). Both overlays use unscaled slide coordinates; the canvas applies zoom once. getStageElement() supplies the actual scaled slide origin without depending on internal CSS selectors.

See demos/pptx/demo-angular/src/host-owned-headless-editor.component.ts for a runnable custom shell with text and shape editing, save, zoom, and both presence overlays. The host-owned collaboration contract and its same-textbox concurrency limitations apply equally to custom and full-viewer UI.

Slide thumbnail rail ​

SlidesPanelComponent (<pptx-slides-panel>) is the rail of slide thumbnails that PowerPointViewerComponent shows beside the canvas, and a custom shell can place it beside its own canvas. It lists every slide (grouped by section when the deck has sections) and highlights the active one; clicking a thumbnail emits select and edits nothing, so the deck stays clean. With [canEdit], it also adds, duplicates, deletes, hides, reorders and groups slides.

Setting [slides] makes the rail host-driven: it renders only its inputs and emits every command as an output. createSlidesPanelEditorCommands(editor, canEdit) applies those outputs through the shell's EditorStateService, so they share the canvas's undo history and collaboration sync; the multi-selection commands duplicate each slide right after itself.

ts
import {
	createSlidesPanelEditorCommands,
	SlidesPanelComponent,
	ViewerCollaborationShellService,
} from 'pptx-angular-viewer';

@Component({
	// ...providers and canvas as in the example above
	imports: [SlideCanvasComponent, SlidesPanelComponent],
	template: `
		<div style="display: flex; height: 600px">
			<pptx-slides-panel
				[slides]="shell.editor.slides()"
				[templateElementsBySlideId]="shell.editor.templateElementsBySlideId()"
				[sections]="shell.editor.sections()"
				[canvasSize]="shell.loader.canvasSize()"
				[mediaDataUrls]="shell.loader.mediaDataUrls()"
				[activeIndex]="shell.activeSlideIndex()"
				[canEdit]="shell.canEdit()"
				[firstSlideNumber]="shell.loader.firstSlideNumber()"
				(select)="shell.activeSlideIndex.set($event)"
				(addSlide)="rail.addSlideAfter($event)"
				(moveSlide)="rail.moveSlide($event)"
				(duplicateSlides)="rail.duplicateSlides($event)"
				(deleteSlides)="rail.deleteSlides($event)"
				(toggleHideSlides)="rail.toggleHideSlides($event)"
				(openLayoutGallery)="openLayouts($event)"
			/>
			<pptx-slide-canvas style="flex: 1; min-width: 0" ... />
		</div>
	`,
})
export class CustomSlidesComponent {
	readonly shell = inject(ViewerCollaborationShellService);
	readonly rail = createSlidesPanelEditorCommands(this.shell.editor, () => this.shell.canEdit());
}

The section outputs (addSectionAt, renameSection, deleteSection, moveSectionUp, moveSectionDown, toggleSectionCollapse) and addSlideAfter (the menu's New Slide and Enter) map onto the commands of the same name. The thumbnails draw what the canvas draws: their field context (slide numbers, including a deck whose numbering starts at firstSlideNum, header/footer text, document properties) and table styles come from [headerFooter], [customProperties], [firstSlideNumber], [locale], [theme] and [tableStyleMap], each falling back to the enclosing LoadContentService when unset. The "Layout" entry of a slide's context menu emits select for that slide, then openLayoutGallery({ slideIndex, x, y }), since a custom shell renders its own Layout gallery. Read-only ([canEdit]="false") shows no footer and no menus. The rail has no collapse control; show or hide it with @if. Without [slides] the rail reads and edits the enclosing EditorStateService itself, as it does inside PowerPointViewerComponent.

The rail's layout is in its own component styles; load pptx-angular-viewer/styles.css once through your global styles (as for any building block, see Getting Started) for the theme tokens and the scoped reset its thumbnails use.

Single slide thumbnail ​

SlideThumbnailComponent (<pptx-slide-thumbnail>, exported from the package root) draws one slide the way <pptx-slides-panel> draws it, for a host that keeps its own thumbnail strip. It renders from the slide model, so it follows unsaved edits, and it is static: no selection, editing, pointer handlers, focus stops or element ids, so it never competes with the editing canvas. A slide with a transition other than Cut shows the transition's name in a small badge in its top-right corner, as the thumbnail does in every binding (<pptx-slides-panel> draws no badge). Its inputs are [slide], [templateElements] (the slide's layout and master elements, drawn beneath its own; default none), [canvasSize] and [previewWidth] (pixels; default the rail thumbnail width; the height follows the deck's aspect ratio), plus these rail inputs with the same meaning and the same fallback to the enclosing LoadContentService: [mediaDataUrls], [headerFooter], [customProperties], [firstSlideNumber], [locale], [theme] and [tableStyleMap]. [linkedContent] says whether it draws the deck's linked web content: unset follows the enclosing viewer providers (ExternalContentService.allowed(), or the building blocks' externalContent().allowed), so it redraws when the user chooses Enable Content; outside them linked content is withheld. Feed it from the values you bind on the rail:

ts
import { SlideThumbnailComponent, ViewerCollaborationShellService } from 'pptx-angular-viewer';

@Component({
	// ...providers as in the example above
	imports: [SlideThumbnailComponent],
	template: `
		<ul class="my-strip">
			@for (slide of shell.editor.slides(); track slide.id) {
				<li style="width: 120px">
					<pptx-slide-thumbnail
						[slide]="slide"
						[templateElements]="shell.editor.templateElementsBySlideId()[slide.id] ?? []"
						[canvasSize]="shell.loader.canvasSize()"
						[mediaDataUrls]="shell.loader.mediaDataUrls()"
						[firstSlideNumber]="shell.loader.firstSlideNumber()"
						[previewWidth]="120"
					/>
				</li>
			}
		</ul>
	`,
})
export class CustomStripComponent {
	readonly shell = inject(ViewerCollaborationShellService);
}

The thumbnail fills its container's width and is as tall as previewWidth at the deck's aspect ratio, so give the container that width. It needs the same pptx-angular-viewer/styles.css.

The collaboration service and components are exported from the package root (there is no separate subpath the way pptx-react-viewer/viewer has one) if you want to drive sync or render your own presence UI:

ts
import {
	CollaborationService,
	CollaborationCursorsComponent,
	RemoteSelectionOverlayComponent,
	FollowModeBarComponent,
} from 'pptx-angular-viewer';
import type { CollaborationConfig, RemoteCursor, RemotePresence } from 'pptx-angular-viewer';

CollaborationService exposes status, connected, active, activeRole, presence, cursors, and connectedCount as signals, plus connect(), retry(), disconnect(), broadcastSlides(), setCursor(), setSelection(), setActiveSlide(), and followUser() methods. See Services › Complete Services Reference for the full set of lower-level collaboration building blocks (LocalPresencePublisher, createWebsocketBundle/createWebrtcBundle, WriteBackScheduler).

Server side ​

With the default websocket transport you need a running y-websocket-compatible relay reachable at serverUrl. Two production-shaped reference servers ship in demos/pptx/ and are shared across all five bindings (React, Vue, Angular, Svelte and vanilla all speak the same sync schema):

  • demos/pptx/collab-server.example.mjs - zero-dependency Bun server (uses the repo's existing yjs / y-protocols / lib0). Auth has two modes, both validated at the websocket handshake (401 before upgrade):

    • JWT mode (production): set COLLAB_AUTH_JWT_SECRET and have your app server mint short-lived HS256 tokens.
    • Allowlist mode (dev): COLLAB_AUTH_TOKENS=a,b,c static tokens.

    A role: 'viewer' token gets a read-only connection: the relay drops its document writes, so read-only is enforced server-side rather than trusting client-side canEdit. Each room's Y.Doc is snapshotted to COLLAB_DATA_DIR and restored on the next join, so documents survive restarts.

    bash
    COLLAB_AUTH_JWT_SECRET=change-me bun demos/pptx/collab-server.example.mjs
  • demos/pptx/collab-server-hocuspocus.example.mjs - the same contract on a Node/Hocuspocus stack (SQLite persistence via @hocuspocus/extension-sqlite).

Both validate the token every binding sends: authToken in CollaborationConfig becomes the ?token= query parameter on the websocket handshake. In production, terminate TLS in front of the relay (wss://) and prefer the JWT mode with short TTLs.

With transport: 'webrtc' no document server is required.

The MCP package ships its own server-side Yjs codec (/packages/mcp); note its Y.Doc key layout differs from the viewer bindings' sync schema, so the two cannot share one Y.Doc.

Released under the Apache-2.0 License.