Options & Callbacks
The collaboration.externalSession option can reuse an application-owned Yjs document and provider. See Host-owned collaboration.
For custom host sizing, see Viewport fitting for fitPadding, maxFitScale, framework-specific examples, and default values.
createPptxViewer(container, options) takes the PptxViewerOptions interface below. Every option is optional, including source (omit it to start empty and call loadFile / loadUrl later). This reference is taken directly from packages/vanilla/src/viewer/types.ts.
import { createPptxViewer } from 'pptx-vanilla-viewer';
import type { PptxViewerOptions, PptxViewerCallbacks } from 'pptx-vanilla-viewer';TIP
The factory also returns an imperative handle, see Viewer Instance API - that is not part of PptxViewerOptions.
Content
| Option | Type | Default | Description |
|---|---|---|---|
source | PptxViewerSource | - | The presentation to open: raw bytes (ArrayBuffer / Uint8Array), a Blob/File, or a URL string to fetch. |
fileName | string | - | Display name shown in the PowerPoint-style title bar. |
fonts | ViewerFontSource[] | - | Licensed font sources supplied by the host application ({ family, src, format?, weight?, style? }). |
type PptxViewerSource = ArrayBuffer | Uint8Array | Blob | string;Chrome & initial state
| Option | Type | Default | Description |
|---|---|---|---|
initialSlide | number | 0 | Zero-based slide to show after load (clamped). |
googleFonts | false | { baseUrl: string } | unset | Google Fonts fallback for deck fonts that are neither installed nor embedded. Unset leaves it to File > Options > Trust Center > "Download fonts that are not installed or embedded" (on by default: loads them from fonts.googleapis.com); false sends no request to Google (text uses installed, embedded or fallback fonts) and locks that option off; { baseUrl } sends the CSS2 request to a self-hosted mirror instead and locks it on (an invalid baseUrl turns the fallback off and locks it off). See Fonts and privacy. |
allowExternalContent | boolean | unset | Host switch for content a deck links from another server (http(s) targets): pictures, picture fills and bullets, video, audio and poster frames. Unset follows PowerPoint: nothing is fetched on open and a security bar offers Enable Content for that presentation (Trust Center > "Allow external content", off by default, fetches without asking). false fetches none of it and shows no bar, true fetches it without asking; either value locks File > Options > Trust Center > "Allow external content" to match. Read when the viewer is created; the building blocks' setAllowExternalContent applies at once. Google Fonts requests are separate (googleFonts). See External content and privacy. |
listConversionScope | 'paragraph' | 'list' | 'paragraph' | How far Bullets / Numbering reach from a bare caret. 'paragraph' converts only the caret's paragraph, as in PowerPoint. 'list' makes a caret that switches a list paragraph between bullets and numbering convert the whole list around it (adjacent items at its level and the deeper items nested between them), as in Word and Google Docs. Turning a list off, listing a plain paragraph and range selections are the same in both modes. |
limits | PptxLoadLimits | unset | Bounds on loading a deck, for hosts that show untrusted decks: maxInputBytes, maxUncompressedBytes, maxEntries, maxSlides, maxShapes. Unset keeps the core defaults (500 MiB inflated, 65,536 ZIP entries, nothing else bounded). A deck over a limit shows the error overlay with the limit and the deck's value, and onError receives the same message. Read on every load. See Load limits. |
showToolbar | boolean | true | Show the title bar, the ribbon, the status bar and the Protected View and read-only banners. setShowToolbar changes it on a live viewer. |
showThumbnails | boolean | true | Show the thumbnail sidebar. |
showCompatibilityToasts | boolean | true | Show the compatibility warning toast stack after a load. false hides the stack only; the warnings are still collected. Independent of showToolbar. |
showFormatToolbar | boolean | true | Build the editing format toolbar row (bold/fill/insert/z-order). The row is only visible while editing is enabled. |
showInspector | boolean | true | Deprecated: hide the inspector with customization.hiddenPanels instead, as the other bindings do. Builds the property inspector panel (position/size/fill/line). Only visible while editing is enabled. |
hiddenActions | ToolbarActionId[] | - | Individually hide toolbar buttons and/or ribbon tabs; see below. |
editable | boolean | false | Enable editing: click to select, drag/resize/rotate, inline text editing, keyboard shortcuts, undo/redo, and the toolbar Save button. Toggle later via setEditable. |
readOnly | boolean | - | Forces the deck read-only. true wins over editable; false only lifts that restriction, and editing is never granted over a collaboration viewer role. setReadOnly changes it on a live viewer. |
inspectorInitiallyOpen | boolean | - | Initial inspector visibility; omitted keeps the desktop/mobile default. |
rulerUnit | RulerUnit | 'inches' | Unit system for the View > Rulers tick labels ('centimetres' labels identically across bindings). |
hiddenActions
Each id in ToolbarActionId controls one quick-access button, one control cluster, or one whole ribbon tab; unlike showToolbar, this hides individual pieces rather than the whole chrome:
- Buttons/clusters:
'share','broadcast','export','undo','redo','record','notes','fullscreen','zoom'(zoom in/out/fit as a unit),'navigation'(prev/next as a unit),'mergeShapes','crop'. - Ribbon tabs:
'file','home','insert','draw','design','transitions','animations','slideShow','record','review','view','help'.
'record' hides both the quick-access Record control and the Record ribbon tab, since they surface the same feature.
UI customization
| Option | Type | Default | Description |
|---|---|---|---|
customization | ViewerCustomization | - | Hide, lock or remap any part of the chrome: ribbon tabs and buttons, File > Options pages, sections and settings (lock a value, set a default), File tab pages and cards, context-menu entries, editor shortcuts, panels, features (AI, collaboration) and dialogs. Unioned with hiddenActions. A new object replaces the whole customisation. |
createPptxViewer(el, {
source: bytes,
editable: true,
customization: { ribbon: { hiddenTabs: ['draw'] }, disabledFeatures: ['ai'] },
});The same helpers (hideRibbonTab, lockSetting, remapShortcut, ...) are available on the returned instance to change it at runtime; see the API page. Every id, the rules and recipes are in the UI Customization guide.
Theming & localization
| Option | Type | Default | Description |
|---|---|---|---|
theme | ViewerTheme | - | Viewer chrome theme (shared ViewerTheme: colors, radius, CSS vars). See Theming. |
locale | string | 'en' | UI locale. Dictionaries come from messages; English is built in. |
defaultLocale | string | - | Initial locale for File > Options > Language. Wins over a persisted choice and over locale; later user picks still apply. |
defaultThemeKey | string | - | Initial key into availableThemes (or the built-in catalog) for File > Options > Appearance. Wins over a persisted choice. |
onThemeChange | (key: string) => void | - | Host callback for theme picks; see Callbacks. |
onLocaleChange | (code: string) => void | - | Host callback for language picks; see Callbacks. |
authorName | string | - | Author for comments and the broadcast presenter. Falls back to Options > General > "User name", then a generic label. |
messages | TranslationMessages | - | Per-locale pptx.* message dictionaries. English falls back to the built-in shared dictionary; other locales fall back to English. |
availableThemes | readonly ThemeCatalogEntry[] | shared theme catalog | Theme choices offered by File > Options > Appearance (default/light/vermilion light/vermilion dark), also highlighted in the Design tab's quick-access gallery. |
availableLocales | readonly LocaleCatalogEntry[] | registered dictionaries | Language choices offered by File > Options > Language. Defaults to every locale with a registered messages dictionary plus 'en'. |
accountAuth | AccountAuthConfig | disabled | Optional hook point wiring a real sign-in flow into File > Account ({ enabled, onSignIn, signedInUser? }); renders nothing unless enabled: true. |
TranslationMessages is a Record<string, Record<string, string>>: locale code to a flat dictionary of dotted pptx.* keys. Theme and locale can be changed later via setTheme / setLocale.
The empty slide area uses pptx.statusBar.noSlides, including when the toolbar is hidden. Register the label in messages. A regional locale such as fr-FR can use a fr dictionary.
const viewer = createPptxViewer(container, {
showToolbar: false,
locale: 'fr-FR',
messages: { fr: { 'pptx.statusBar.noSlides': 'Aucune diapositive' } },
});ThemeCatalogEntry is { key: string; labelKey: string; theme: ViewerTheme | undefined } (undefined resets to the built-in default); LocaleCatalogEntry is { code: string; label: string; nativeLabel: string }.
Extension
| Option | Type | Default | Description |
|---|---|---|---|
registry | ElementRendererRegistry | createDefaultRegistry() | Custom element-renderer registry; pass your own (or mutate the default via getRegistry()) to add or override element renderers. See Element Renderers. |
smartArt3D | boolean | false | Opt-in WebGL SmartArt renderer: renders smartArt elements as an extruded Three.js scene. three is an optional peer dependency, lazily imported only when true; if unavailable, the SVG renderer is used. Set once at construction (no runtime setter). |
surfaceChart3D, barChart3D, lineChart3D, areaChart3D, pieChart3D | boolean | false | Independently opt in to interactive Three.js renderers for the matching 3D chart kinds. Each falls back to SVG when three is unavailable or the chart cannot render as a WebGL scene. |
ai | PptxAiAssistant | PptxAiConfig | - | Enables the optional AI assistant: pass createAiAssistant(config) from pptx-vanilla-viewer/ai, or a plain PptxAiConfig. Its SDK peer loads only when the panel is opened; omit this option to leave the assistant unavailable. |
ribbonAddIns | readonly RibbonAddInTab[] | - | Ribbon tabs the host adds after Help. Each command runs its run callback and dispatches a bubbling office-ribbon-add-in event. setRibbonAddIns on the instance changes them live. |
ribbonDisplay | 'always' | 'tabs' | 'fullScreen' | 'always' | PowerPoint's Ribbon Display Options at start. 'always' docks tabs and commands; 'tabs' shows the tab row and lays a tab's commands over the slide when it is chosen; 'fullScreen' hides the title bar and the ribbon behind a strip at the top. The user changes it from the menu at the right end of the tab row, with Ctrl+F1 or a double click on a tab; setRibbonDisplay changes it from the host. |
Autosave
Crash-recovery snapshots in a shared IndexedDB store, written once per interval while there are unsaved edits. Autosave never replaces the user's real Save; it is a safety net offered back on the next start.
| Option | Type | Default | Description |
|---|---|---|---|
autosave | boolean | true | Recovery autosave; the toolbar shows a small status pill. A policy ceiling over the title-bar toggle; see below. |
autosaveIntervalMs | number | File > Options cadence | Interval (ms) between recovery snapshots while there are unsaved edits. An explicit value outranks the user's AutoRecover setting. |
storage | DocumentStorage | none | Host-owned storage: Save goes to storage.save(), recovery copies to its recovery methods. See Host-owned storage. |
filePath | string | fileName, or 'presentation.pptx' | Original file path, used as the IndexedDB recovery key. |
fileProviders | CloudFileProvider[] | none | Cloud places for File > Open (for example OneDrive from ooxml-core/embedding/onedrive). A file opened from one saves back to its own storage until another document is loaded. |
autosaveFilePath | string | 'presentation.pptx' | Deprecated: use filePath; when both are set, filePath wins. IndexedDB recovery key for autosave. |
Runtime control lives on the instance: autosaveNow / setAutosaveEnabled / isAutosaveEnabled.
Who decides: the autosave prop or the AutoSave toggle?
The rule is the same in all five bindings and lives in one shared decision function, resolveAutosaveActivation:
The
autosaveprop is a policy ceiling. The title-bar AutoSave toggle is the user's preference inside it.
autosave | What runs | The toggle |
|---|---|---|
| omitted | Autosave runs; the user's toggle decides, defaulting to on. | Works. |
true | Same as omitted: the host permits it, the user decides. | Works. |
false | Autosave is off, and no recovery prompt is offered on load. | Inert (it must not move). |
A preference can never exceed a policy, which is why autosave: false also takes the switch away: a control that silently does nothing is worse than no control. canEdit/editable and a filePath key remain hard requirements either way.
The same rule governs the cadence: an explicit autosaveIntervalMs is a host policy honoured as given, and omitting it follows the user's File > Options > Save > "Save AutoRecover information every N minutes" (two minutes by default).
The default is true because crash recovery that is off by default is crash recovery nobody has.
Recovering a snapshot
When a deck finishes loading and a snapshot newer than 24 hours exists for the same key, the viewer raises a "Recover unsaved changes?" dialog offering Restore or Discard. Restore loads the snapshot's bytes; Discard deletes it. It is deliberately not raised for a snapshot this tab has already taken delivery of (for example when the host itself restored it through restoreSessionDeck).
Collaboration
| Option | Type | Default | Description |
|---|---|---|---|
collaboration | CollaborationInput | - | Start a real-time collaboration session immediately (Yjs over y-websocket or serverless y-webrtc): the legacy CollaborationConfig or the shared CollaborationOptions. A role: 'viewer' config forces read-only. |
shareDefaults | ShareDefaults | - | Prefilled values for the built-in Share/Broadcast dialog form fields ({ roomId?, userName?, serverUrl? }); the broadcast dialog uses userName as the presenter's display name. |
Sessions can also be started or stopped later with startCollaboration / stopCollaboration.
Wire-format limitation
Media/OLE/3D/ink binary payloads are not carried over the wire (a shared codec limitation), and a remote update replaces the whole local slide array, so a joiner's host-provided media can degrade.
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:
createPptxViewer(el, {
collaboration: { roomId: 'deck-review', provider, user: { name: 'Ada' }, intent: 'join' },
});
// Same browser only:
createPptxViewer(el, { collaboration: { roomId: 'deck-review', user: { name: 'Ada' } } });provider(aProviderFactory, for exampletransportProvideror an existing provider throughadaptYjsProvider) wins overserverUrl.- With no
session,provider,serverUrlortransport, 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 legacyCollaborationConfigwithserverUrlkeeps y-websocket; one withtransport: 'webrtc'or a blankserverUrlkeeps 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); arole: 'viewer'stays read-only.- The state reports
status: 'connecting'while the session opens anderrorfor an invalid room or an unavailable BroadcastChannel.
Callbacks
PptxViewerOptions extends PptxViewerCallbacks - there is no framework event system, so events are plain callback options:
| Callback | Signature | Description |
|---|---|---|
onLoad | (info: { slideCount: number; canvasSize: CanvasSize }) => void | Fired after a presentation loads successfully. |
onError | (message: string, error: unknown) => void | Fired when a load fails (message is already localised/best-effort). |
onElementRenderError | (error: Error, context: ElementRenderErrorContext) => void | A slide element was omitted because its renderer threw; context is { elementId, elementType, slideId }. Only that element is left out, on every surface. Defaults to console.error(error, context), also used when the callback throws. An unchanged failed element is not retried or reported again on each repaint. |
onSlideChange | (index: number) => void | Fired when the active slide changes (zero-based index). |
onZoomChange | (scale: number) => void | Fired when the editing zoom scale changes (1 = 100%), also during a show. |
onRibbonDisplayChange | (mode: 'always' | 'tabs' | 'fullScreen') => void | Fired when the user picks a Ribbon Display Options mode. Not fired for setRibbonDisplay. The viewer keeps the choice for its own lifetime only; store it here to bring it back on the next visit. |
onPresentationChange | (presenting: boolean) => void | Fired when presentation (fullscreen) mode is entered or exited. |
onChange | () => void | Fired after any document mutation (move, resize, edit, undo, ...). |
onDirtyChange | (dirty: boolean) => void | Fired when the unsaved-edits flag flips (a save resets it). |
onSelectionChange | (elementId: string | null) => void | Fired when the selected element changes (null = no selection). |
onAutosave | (content: Uint8Array) => void | Fired with the serialised .pptx bytes after each recovery autosave snapshot is written. |
onPropertiesChange | (updates: Partial<PptxCoreProperties>) => void | Fired with the changed fields when the user (or the AI assistant) changes the document properties. |
onNotesUpdate | (notes: string) => void | Fired with the new speaker-notes text after a notes edit. |
onAutosaveStatus | (status: AutosaveStatus) => void | Fired on every autosave lifecycle transition ('idle' | 'saving' | 'saved' | 'error'). |
onAutosaveRecovery | (record: AutosaveRecord) => void | Offered a recovery snapshot found on start; the host decides whether to restore it (see below). |
onCollaborationStatus | (status: ConnectionStatus) => void | Fired on every collaboration connection-status transition ('disconnected' | 'connecting' | 'connected' | 'error'). |
onCollaborationChange | (state: CollaborationState) => void | Fired with the shared state (active, roomId, status, synced, people) when a session starts or stops (the off state) and when status, synced or people change, also for a host-owned session. getCollaborationState() returns it on demand. |
onThemeChange | (key: string) => void | Fired when a theme is selected via File > Options > Appearance (or a setTheme call matching a catalog entry). When supplied, the host owns persistence; otherwise the viewer uses localStorage (pptx-viewer-prefs). |
onLocaleChange | (code: string) => void | Fired when a language is selected via File > Options > Language (or any setLocale call). Same persistence rule as onThemeChange. |
onToggleAutosave | (enabled: boolean) => void | Fired when the title-bar AutoSave control enables or disables recovery autosave. |
onContentChange | (content: Uint8Array) => void | Fired with the serialised .pptx bytes after each committed edit. Serialising is asynchronous, so a burst of edits can deliver several snapshots in order. |
onModeChange | (mode: ViewerMode) => void | Fired when the viewer mode changes ('preview', 'edit', 'present', 'master'). |
onSlideCountChange | (count: number) => void | Fired when the total slide count changes (slide added, deleted or a deck loaded). |
onStartCollaboration | (config: CollaborationConfig) => void | Fired when the user starts a session from the Share or Broadcast dialog. |
onStopCollaboration | () => void | Fired when the user stops a session from the Share or Broadcast dialog. |
onOpenFile | () => void | Host override for File > Open: the built-in picker is bypassed and the host supplies the deck through loadFile. |
onHyperlinkClick | HyperlinkClickHandler | Fired before following a link; return false to cancel the default action. |
AutosaveRecord is { key: string; data: Uint8Array; timestamp: number; size: number }; a typical recovery flow is viewer.loadFile(record.data).
Full interface
interface PptxViewerCallbacks {
onLoad?: (info: { slideCount: number; canvasSize: CanvasSize }) => void;
onError?: (message: string, error: unknown) => void;
onElementRenderError?: (error: Error, context: ElementRenderErrorContext) => void;
onSlideChange?: (index: number) => void;
onZoomChange?: (scale: number) => void;
onRibbonDisplayChange?: (mode: 'always' | 'tabs' | 'fullScreen') => void;
onPresentationChange?: (presenting: boolean) => void;
onChange?: () => void;
onDirtyChange?: (dirty: boolean) => void;
onSelectionChange?: (elementId: string | null) => void;
onAutosave?: (content: Uint8Array) => void;
onPropertiesChange?: (updates: Partial<PptxCoreProperties>) => void;
onNotesUpdate?: (notes: string) => void;
onAutosaveStatus?: (status: AutosaveStatus) => void;
onAutosaveRecovery?: (record: AutosaveRecord) => void;
onCollaborationStatus?: (status: ConnectionStatus) => void;
onCollaborationChange?: (state: CollaborationState) => void;
onContentChange?: (content: Uint8Array) => void;
onModeChange?: (mode: ViewerMode) => void;
onSlideCountChange?: (count: number) => void;
onStartCollaboration?: (config: CollaborationConfig) => void;
onStopCollaboration?: () => void;
onOpenFile?: () => void;
onHyperlinkClick?: HyperlinkClickHandler;
}
interface PptxViewerOptions extends PptxViewerCallbacks, ViewportFitOptions {
source?: PptxViewerSource;
fonts?: ViewerFontSource[];
theme?: ViewerTheme;
fileName?: string;
locale?: string;
defaultLocale?: string;
defaultThemeKey?: string;
authorName?: string;
messages?: TranslationMessages;
availableThemes?: readonly ThemeCatalogEntry[];
availableLocales?: readonly LocaleCatalogEntry[];
onThemeChange?: (key: string) => void;
onLocaleChange?: (code: string) => void;
accountAuth?: AccountAuthConfig;
initialSlide?: number;
googleFonts?: false | { baseUrl: string };
allowExternalContent?: boolean;
listConversionScope?: 'paragraph' | 'list';
limits?: PptxLoadLimits;
editable?: boolean;
readOnly?: boolean;
showToolbar?: boolean;
showThumbnails?: boolean;
showCompatibilityToasts?: boolean;
showFormatToolbar?: boolean;
/** @deprecated Use `customization.hiddenPanels`. */
showInspector?: boolean;
inspectorInitiallyOpen?: boolean;
rulerUnit?: RulerUnit;
customization?: ViewerCustomization;
ribbonAddIns?: readonly RibbonAddInTab[];
ribbonDisplay?: 'always' | 'tabs' | 'fullScreen';
hiddenActions?: ToolbarActionId[];
registry?: ElementRendererRegistry;
smartArt3D?: boolean;
surfaceChart3D?: boolean;
barChart3D?: boolean;
lineChart3D?: boolean;
areaChart3D?: boolean;
pieChart3D?: boolean;
ai?: PptxAiConfig | PptxAiAssistant;
autosave?: boolean;
onToggleAutosave?: (enabled: boolean) => void;
autosaveIntervalMs?: number;
storage?: DocumentStorage;
fileProviders?: readonly CloudFileProvider[];
filePath?: string;
/** @deprecated Use `filePath`. */
autosaveFilePath?: string;
collaboration?: CollaborationInput;
shareDefaults?: ShareDefaults;
}Example: everything wired
import { createPptxViewer, vermilionLightTheme } from 'pptx-vanilla-viewer';
const viewer = createPptxViewer(document.getElementById('host')!, {
source: '/decks/quarterly.pptx',
fileName: 'quarterly.pptx',
theme: vermilionLightTheme,
locale: 'en',
initialSlide: 0,
editable: true,
showToolbar: true,
showThumbnails: true,
hiddenActions: ['broadcast', 'record'],
autosave: true,
filePath: 'quarterly.pptx',
onLoad: ({ slideCount }) => console.log(`${slideCount} slides`),
onSlideChange: (index) => console.log('slide', index + 1),
onZoomChange: (scale) => console.log(`${Math.round(scale * 100)}%`),
onPresentationChange: (presenting) => console.log(presenting ? 'presenting' : 'back'),
onDirtyChange: (dirty) => console.log('unsaved edits:', dirty),
onSelectionChange: (elementId) => console.log('selected', elementId),
onAutosaveStatus: (status) => console.log('autosave:', status),
onAutosaveRecovery: (record) => {
if (confirm('Restore unsaved changes from your last session?')) {
void viewer.loadFile(record.data);
}
},
onError: (message) => console.error(message),
});