@betteroffice/pptx-react 0.2.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,20 +1,17 @@
1
1
  # @betteroffice/pptx-react
2
2
 
3
- React chrome for the BetterOffice PPTX editor — wraps
4
- [`@betteroffice/pptx`](https://www.npmjs.com/package/@betteroffice/pptx) in a
5
- slide canvas, slide strip, formatting toolbar, and keyboard editing surface.
6
- Parsing, layout, and text shaping run in the core's Rust/WebAssembly engine;
7
- slides are painted onto canvas.
3
+ React presentation editor with a slide canvas, slide strip, formatting toolbar, and keyboard editing.
4
+ The engine runs in a Web Worker by default, with promise-returning reads and exports.
8
5
 
9
- <!-- TODO(author): add a screenshot/GIF here once hosted; an <img> with an unresolvable src renders broken on npm -->
6
+ ## Install
10
7
 
11
8
  ```bash
12
- bun add @betteroffice/pptx-react @betteroffice/pptx react react-dom
9
+ bun add @betteroffice/pptx-react react react-dom
13
10
  ```
14
11
 
15
- `react` and `react-dom` (18 or 19) are peer dependencies.
12
+ Peer dependencies: `react` and `react-dom`, version 18 or 19; the PPTX core is a package dependency.
16
13
 
17
- ## Render a presentation
14
+ ## Usage
18
15
 
19
16
  ```tsx
20
17
  import { PptxEditor } from '@betteroffice/pptx-react';
@@ -31,355 +28,123 @@ export function Presentation({ file, fontBytes }: {
31
28
  }
32
29
  ```
33
30
 
34
- Font bytes are supplied by the host and registered with the Rust shaper; pair
35
- with [`@betteroffice/fonts`](https://www.npmjs.com/package/@betteroffice/fonts)
36
- for metric-compatible open faces.
37
-
38
- ## Edit
39
-
40
- Click text to place the Rust-computed caret, type to edit the yrs story and
41
- trigger Rust reflow, drag or resize shapes on the canvas, or use the toolbar
42
- for bold, italic, size, color, slides, text boxes, image insertion, and shape ordering.
43
-
44
- Props: `file`, `fonts`, `collaboration`, `i18n`, `className`, `fileName`,
45
- `onReady` (exposes the core `PresentationHandle`, the editor's `commands`, a
46
- `refresh` callback for host-driven edits, `refreshProposals`, and `save`),
47
- `onChange` (deck snapshots), `onError`, `onSave` (receives the saved bytes;
48
- without it, saving downloads the file), `readOnly`, `toolbar`, and `showToolbar`.
49
-
50
- ## Compose the toolbar
51
-
52
- Every built-in control runs through one command store per editor,
53
- `api.commands`. Hosts arrange the same controls with their own actions:
54
-
55
- ```tsx
56
- import {
57
- EditorToolbar,
58
- PptxEditor,
59
- ToolbarButton,
60
- ToolbarCommandButton,
61
- ToolbarCommandSelect,
62
- ToolbarGroup,
63
- } from '@betteroffice/pptx-react';
64
-
65
- <PptxEditor
66
- file={file}
67
- fonts={fonts}
68
- toolbar={
69
- <EditorToolbar mode="commands">
70
- <EditorToolbar.Toolbar>
71
- <ToolbarGroup label="Text">
72
- <ToolbarCommandSelect id="fontFamily" />
73
- <ToolbarCommandButton id="bold" />
74
- </ToolbarGroup>
75
- <ToolbarCommandButton id="undo" />
76
- <ToolbarCommandButton id="slideshow" />
77
- <ToolbarButton title="Share" onClick={share}>Share</ToolbarButton>
78
- </EditorToolbar.Toolbar>
79
- </EditorToolbar>
80
- }
81
- />;
82
- ```
83
-
84
- - **Toolbar region.** `showToolbar={false}` hides it; otherwise omitting
85
- `toolbar` keeps the default controls (read-only shows only the Present
86
- button), `null` removes them, and supplied chrome replaces them, also while
87
- `readOnly`. Collaborator chips stay beside supplied chrome.
88
- - **Outside the editor.** Capture `api.commands` from `onReady` into state and
89
- render the parts under `<PptxCommandProvider commands={commands}>`;
90
- `commands={null}` reports the editor as unavailable until it is ready. Such
91
- chrome follows the editor's locale, and shortcuts pressed inside it reach the
92
- editor.
93
- - **Command contract.** `getState(id, args?)` returns serializable state
94
- (`enabled`, `active` with `'mixed'`, `value`, and `options` that each carry
95
- their own `state`); a disabled state
96
- always carries `disabledReason: { code, message }`, for example
97
- `text-selection-required`, `shape-required`, `z-order-boundary`,
98
- `review-active` or `proposal-stale`. `getDescriptor(id)` lists the label key
99
- and shortcuts, which labels show per platform (`Ctrl+B`, `⌘B`).
100
- `usePptxCommand` and `usePptxCommandState` bind custom controls.
101
- - **Ordering.** `execute(id, args)` waits for input accepted before it, such as
102
- a picture still decoding, keeps later typing behind it, checks availability
103
- again and resolves to `{ ok: true, status }` or `{ ok: false, failure }`
104
- (`input-failed`, `document-replaced`, `target-changed`,
105
- `gesture-active`, `command-failed`). Keystrokes typed meanwhile land in the
106
- text they were typed into, and a picture on the slide the picker opened on;
107
- input queued for a replaced document is dropped. Save runs the host's `onSaveRequest` outside that queue, so the request
108
- may await `flushPendingInput()`.
109
- - **Authority.** Commands enforce read-only mode and the other gates for the UI.
110
- `api.handle` stays direct, unrestricted host access; call `api.refresh()`
111
- after using it.
112
- - **Overflow.** At narrow widths trailing groups move into a More menu with
113
- arrow, Home/End, typeahead and submenu navigation. Built-in controls keep all
114
- their choices there; host buttons and dropdowns get entries automatically,
115
- and `ToolbarOverflow` gives other content one. A group holding content
116
- without an entry stays in the row, which scrolls horizontally when that
117
- content does not fit.
118
- - **Compatibility.** The prop-based `EditorToolbar`, `Toolbar`,
119
- `EditorToolbarContext` and `useEditorToolbar` still work and are deprecated:
120
- without `mode` they bind to their props, host children follow the default
121
- controls, and command-mode chrome rejects those props. Inside
122
- `EditorToolbar mode="commands"`, `useEditorToolbar()` returns a view of the
123
- commands whose callbacks run them; mixed marks read as `undefined`.
124
-
125
- ## Host editing controls
126
-
127
- `onSaveRequest` runs for toolbar and Ctrl/Cmd+S saves before serialization.
128
- Return `true` to continue built-in saving; `false` or `void` handles or cancels
129
- it. Promises are awaited and concurrent requests are coalesced. `onSave` still
130
- receives the resulting bytes when built-in saving continues. A request waiting
131
- on a replaced or closed document is discarded.
132
-
133
- The API received by `onReady` exposes `flushPendingInput(): Promise<void>` and
134
- the `commands` store described above.
135
- Await it before inspecting or mutating the core from a host workflow, then call
136
- `api.save()` for explicit serialization without re-entering `onSaveRequest`.
137
- `save()` remains synchronous and rejects while asynchronous input is pending.
138
- Flush rejects stale document handles, failed input, and unfinished pointer
139
- gestures. Finish or cancel the gesture before retrying.
140
-
141
- PPTX keyboard and notes edits are synchronous; flushing also waits for accepted
142
- image imports. A failed import rejects a flush waiting for it and is reported
143
- through `onError`; it does not block later saves of the existing presentation.
144
-
145
- `api.getPositionAtPoint(clientX, clientY)` returns a shape or text hit with
146
- `slide` (1-based), `slideId`, and `shapeId`; text hits include `storyId` and the
147
- UTF-16 `position`. It uses the current slide and canvas bounds without changing
148
- focus or selection. Outside content, unavailable geometry, stale handles, and
149
- proposal previews return `null`. Use `api.refresh()` after core mutations.
150
-
151
- `api.readContent()`, `api.findText()`, `api.validateEdits()` and
152
- `api.applyEdits()` run the core's version-checked edit batches after flushing
153
- pending input, and `api.version()` returns the flushed session version:
154
-
155
- ```ts
156
- const read = await api.readContent();
157
- if (read.ok) {
158
- const result = await api.applyEdits({
159
- expectVersion: read.version,
160
- steps: [{ op: 'setSlideNotes', target: { slideId: read.slides[0].id }, text: 'Opening' }],
161
- });
162
- if (!result.ok) console.warn(result.failure.code);
163
- }
164
- ```
165
-
166
- An applied batch refreshes the slides, history and proposals once and calls
167
- `onChange`; refusals and no-op batches refresh nothing. A refusal never rolls
168
- back input the flush committed, so an edit that lands between the read and the
169
- batch refuses with `stale-version`. Read-only editors refuse `validateEdits` and
170
- `applyEdits` with `read-only`, and the promises reject when the presentation is
171
- replaced while input flushes.
172
-
173
- ## Host plugins
174
-
175
- Host-owned tools (review aids, checks, templates) install through the `plugins`
176
- prop. A plugin contributes a docked panel, an overlay and commands, and works
177
- through restricted clients rather than the editor API or the presentation
178
- handle:
179
-
180
- ```tsx
181
- import { PptxEditor, definePptxPlugin } from '@betteroffice/pptx-react';
182
-
183
- type State = { version: string | null; slides: number };
184
-
185
- const review = definePptxPlugin<State>({
186
- id: 'acme.review',
187
- createState: () => ({ version: null, slides: 0 }),
188
- async onEvent(context, event) {
189
- if (event.type !== 'load' && event.type !== 'document-change') return;
190
- const read = await context.read.readContent();
191
- if (read.ok) context.setState({ version: read.version, slides: read.slides.length }, read.version);
192
- },
193
- panel: {
194
- title: 'Review',
195
- placement: 'right',
196
- render: ({ context }) => <p>{context.state.slides} slides</p>,
197
- },
198
- overlay: ({ context, geometry }) => {
199
- const target = context.snapshot.selection?.target;
200
- const box = target && target.kind !== 'slide' ? geometry.getShapeRect(target.shapeId) : null;
201
- return box ? (
202
- <div style={{ position: 'absolute', left: box.x, top: box.y, width: box.width, height: box.height, outline: '2px dashed #2563eb' }} />
203
- ) : null;
204
- },
205
- });
206
-
207
- <PptxEditor
208
- file={bytes}
209
- fonts={fonts}
210
- plugins={[review]}
211
- pluginGrants={{ 'acme.review': { document: 'write', editBatches: true } }}
212
- onPluginError={(error) => report(error)}
213
- />;
214
- ```
215
-
216
- - **Lifecycle.** Once a presentation is open, each plugin gets fresh state,
217
- `initialize`, then one `load` event (`loaded`, `replaced`, or `attached` for a
218
- plugin added to an open presentation), and its contributions appear. A
219
- presentation change the hook did not make itself aborts it and delivers
220
- `load` again; after ten such runs the plugin is stopped and reported. It then
221
- receives `document-change` (the committed version only, for typing, commands,
222
- batches, its own included, undo, redo and remote updates, never for refusals
223
- or no-ops), `selection-change`, `mode-change` (with `readOnly`),
224
- `layout-change` and `grants-change`. Events describe current state: several
225
- changes may arrive as one, and a newer one aborts the hook still handling the
226
- previous (`context.signal`), except a change that hook's own edit batch made.
227
- Replacing the presentation, removing the plugin, changing its `revision`,
228
- unmounting, or a failure ends the activation: its signals abort, its clients
229
- refuse, and every `onCleanup` disposer runs once with the reason. Plugins are
230
- matched by `id` and `revision`, so new array or callback identities and
231
- reordering keep their state. `definePptxPlugin` copies the panel, commands
232
- and toolbar, so changing them takes a new definition. `context.run(action)`
233
- gives event handlers a fresh context and isolates their failures. `onReady` is
234
- unaffected by plugins.
235
- - **Stale results.** `setState` returns false once the context is superseded or
236
- ended, or when the presentation is no longer at `atVersion` (by default the
237
- version the context was created at).
238
- - **Reads and edits.** `context.read` offers `version`, `readContent`,
239
- `findText` and `validateEdits`, and `context.edits.applyEdits` the editor's
240
- version-checked batches. Each call waits for pending input in order with it,
241
- but plugin handlers run outside that queue, so a command can await its own
242
- batch.
243
- - **Grants.** Without a grant a plugin reads, validates and navigates only, and
244
- `context.edits` is null. Built-in commands need their id in `commands`, and
245
- mutating ones also `document: 'write'`; edit batches need `document: 'write'`
246
- and `editBatches`, and `history: 'none'` also `untrackedHistory`. The grant
247
- and `readOnly` are checked again right before each change, so a revoked grant,
248
- `readOnly` or a replaced presentation refuses even through a client obtained
249
- earlier. Mutating built-in commands refuse plugins with `unsupported-policy`;
250
- plugins change presentations through edit batches.
251
- - **Contributed commands** register as `plugin:<pluginId>/<id>` on
252
- `api.commands`. They always run with their own plugin's clients, even when the
253
- toolbar, a shortcut or the host invokes them. `execute` returns
254
- `{ ok: true, status }` or a failure with the plugin's own code, or a refused
255
- edit batch as-is; callers receive it unchanged. `mutatesDocument` disables a
256
- command while read-only but grants nothing. Plugin shortcuts must use Mod or
257
- Alt, or a function key; built-in and clipboard shortcuts win, and a clashing
258
- plugin shortcut is not bound and is reported. `toolbar` lists local ids in
259
- order: the default toolbar shows them, and replacement chrome places
260
- `<PptxPluginToolbar />` where it wants them. `ToolbarCommandButton`,
261
- `ToolbarCommand`, `usePptxCommand` and `usePptxCommandState` also take a
262
- contributed id.
263
- - **Selection and navigation.** `snapshot.selection` names the current slide
264
- (`slideId` and the one-based `slide`) and a slide, shape or text target; text
265
- keeps its `anchor` and `focus` direction in UTF-16 story offsets.
266
- `navigation.goToSlide`, `selectShape` and `selectText` resolve session ids
267
- after pending input against `expectVersion`, keep keyboard focus unless
268
- `focus: true`, and refuse with `stale-version`, `missing-target`,
269
- `layout-unavailable` or `unsupported` (during proposal review) rather than
270
- retarget. Ids are session-scoped.
271
- - **Geometry.** `context.geometry` describes the painted current version, and is
272
- `null` during proposal review.
273
- `layout.width` and `height` are the unzoomed slide in display-list pixels and
274
- `layout.zoom` the resolved scale, fit included. `geometry.toOverlayRect` takes
275
- a `slide-emu` (9,525 EMU per pixel) or `slide-px` rectangle and returns pixels
276
- of the unscaled overlay layer, which sits on the slide canvas below selection
277
- handles and proposal controls and ignores the pointer unless an element sets
278
- `pointer-events: auto`. `getShapeRect(shapeId)` returns the rendered bounds of
279
- a shape and its group descendants, and `getPositionAtPoint` adds `version` and
280
- `layoutId` to a hit. Every method returns null once its layout is gone.
281
- - **Panels** dock left, right or bottom of the slide, beside the thumbnail rail
282
- and outside the slide's keyboard handling, with tabs when several share a
283
- side. `preferredSize` is clamped to 40% of the workspace. In a narrow editor
284
- side docks show their tabs, and a tab opens its panel as a drawer that Escape
285
- closes. Collapsing a panel keeps the plugin running.
286
- - **Failures.** Every contribution renders behind its own error boundary with a
287
- command context restricted to its plugin. Keys pressed in plugin chrome are
288
- the user's: built-in shortcuts act on the editor there, and a plugin's text
289
- fields keep their own editing keys. A throwing hook, renderer,
290
- command-state function, command or `context.run` action stops only that
291
- plugin, runs its cleanups and reports `{ pluginId, generation, phase, error }`
292
- to `onPluginError`. Plugins run in the page's realm: grants govern the
293
- supported API, not a sandbox.
294
-
295
- ## What works today
296
-
297
- - Slide rendering with Rust layout and text shaping, painted onto canvas
298
- - Canvas interactions: shape selection, drag, and resize
299
- - Text editing with caret and selection computed by the engine
300
- - Slide management (add, delete), text boxes, image insertion, shape ordering, undo/redo
301
- - Saving the deck back to `.pptx` — toolbar button, Ctrl/Cmd+S, or `api.save()`
302
- - A command store behind every control, with composable toolbar parts and an
303
- accessible overflow menu
304
- - Host-owned plugins with panels, overlays, lifecycle events, and explicitly
305
- granted commands and edit batches
306
- - Localized UI via the `i18n` prop
307
- ([`@betteroffice/pptx-i18n`](https://www.npmjs.com/package/@betteroffice/pptx-i18n))
308
- - Real-time collaboration with people or agents; the deck is a CRDT
309
- - Live collaborator shape selections and presence chips, shown in each peer's color
310
- - Agent proposal review directly on the slide canvas, with inline text diffs,
311
- old/new shape bounds, before/after previews, acceptance, rejection, and Undo
31
+ `fonts` is required. Each entry is a family name and the bytes of a TTF or OTF file, for example
32
+ fetched from your server or loaded with `loadBundledFontBytes` from
33
+ [`@betteroffice/fonts`](https://www.npmjs.com/package/@betteroffice/fonts).
34
+
35
+ ## Key options
36
+
37
+ The exported `PptxAsyncEditorProps` type describes the default editor props. All props below are
38
+ optional except `fonts`.
39
+
40
+ | prop | type | description |
41
+ | --- | --- | --- |
42
+ | `file` | `Uint8Array \| ArrayBuffer` | Presentation bytes to open. |
43
+ | `fonts` | `ReadonlyArray<PptxFontFace>` | Font families and bytes for text layout. |
44
+ | `readOnly` | `boolean` | Block user edits while retaining navigation and selection. |
45
+ | `initialSlide` | `number` | Initial slide, numbered from 1 and clamped to the deck. |
46
+ | `fileName` | `string` | Download name; defaults to `presentation.pptx`. |
47
+ | `className` | `string` | Class for the editor container. |
48
+ | `style` | `CSSProperties` | Inline styles for the editor container. |
49
+ | `initialZoom` | `number` | Initial zoom scale from 0.1 to 5; omitted, the slide fits the stage. |
50
+ | `loadingIndicator` | `ReactNode` | Shown while the presentation opens. |
51
+ | `i18n` | `PptxAsyncEditorProps['i18n']` | UI translations from `@betteroffice/pptx-i18n`. |
52
+ | `onReady` | `(api: PptxAsyncEditorApi) => void \| (() => void)` | Receive the async API; optionally return cleanup. |
53
+ | `onChange` | `(snapshot: DeckSnapshot) => void` | Receive deck snapshots after changes. |
54
+ | `onDocumentChange` | `(change: PptxDocumentChange) => void` | Receive `{ version }` after a committed edit, alongside `onChange`. |
55
+ | `onError` | `(error: Error) => void` | Receive loading and editing errors. |
56
+ | `onSave` | `(bytes: Uint8Array) => void` | Receive saved bytes; omitted, saving downloads the file. |
57
+ | `downloadOnSave` | `boolean` | Whether saving also downloads a copy; defaults to `true` only without `onSave`. |
58
+ | `onSaveRequest` | `() => boolean \| void \| Promise<boolean \| void>` | Intercept toolbar and keyboard saves; return `true` to continue. |
59
+ | `toolbar` | `ReactNode` | Replace built-in controls; `null` removes them. |
60
+ | `showToolbar` | `boolean` | Show the toolbar region; defaults to `true`. |
61
+ | `collaboration` | `PptxAsyncCollaborationOptions` | Shared seed, replica callback, and presence options. |
62
+ | `plugins` | `readonly PptxPlugin[]` | Host-owned tools, panels, and overlays. |
63
+ | `pluginGrants` | `Readonly<Record<string, PptxPluginGrant>>` | Permissions keyed by plugin ID. |
64
+ | `onPluginError` | `(error: PptxPluginError) => void` | Receive isolated plugin failures. |
65
+
66
+ `PptxFontFace` and `DeckSnapshot` are exported by `@betteroffice/pptx`; editor and plugin types are
67
+ exported by `@betteroffice/pptx-react`. `ReactNode` is a React type.
68
+
69
+ Deprecated: `legacySyncApi` keeps the synchronous API on the in-thread engine and is removed in 0.6.0;
70
+ omit it to use the default async editor. Also omit the deprecated `experimentalWorkerOpen` prop.
71
+
72
+ ## Editor API
73
+
74
+ `onReady` receives `PptxAsyncEditorApi`. Await `save()` to serialize the presentation (`saveAsync()` is a
75
+ deprecated alias), and await
76
+ `handleAsync()` for asynchronous document access, including `snapshot()`, `exportStructured()`, and
77
+ `exportMarkdown()`. Reads and exports through that access object return promises; the API also has
78
+ `exportStructured()` and `exportMarkdown()` directly. Work that cannot run against its input or
79
+ target rejects with `PptxCommandAdmissionError`.
80
+
81
+ `flushPendingInput()` waits for accepted input. `goToSlide(slide)` and `selectText(target)` return
82
+ promises; slide numbers are 1-based and text offsets use UTF-16. `getPositionAtPoint(clientX, clientY)`
83
+ asynchronously returns a hit on the current slide or `null` outside slide content.
84
+
85
+ Finish pointer gestures before workflows that flush input. Keep the API tied to the mounted
86
+ presentation; replacing or closing the document invalidates its access.
87
+
88
+ ## Saving
89
+
90
+ The toolbar and Ctrl/Cmd+S invoke `onSaveRequest` before serialization. Its result is awaited:
91
+ `true` continues saving, while `false` or `void` handles or cancels the request. If saving continues,
92
+ `onSave` receives the bytes, and the editor downloads the file using `fileName` when `downloadOnSave`
93
+ is `true` (the default without `onSave`).
94
+
95
+ Calling `save()` directly returns bytes without invoking those save callbacks.
96
+
97
+ ## Toolbar
98
+
99
+ The toolbar composition API is experimental. `api.commands` is shared by the built-in controls and
100
+ host toolbar parts. Replace controls with
101
+ `toolbar`, or hide the region with `showToolbar={false}`.
102
+ See [Compose the PPTX toolbar](https://docs.betteroffice.dev/docs/javascript#compose-the-pptx-toolbar)
103
+ for composition, external controls, command state, and overflow.
104
+
105
+ Deprecated: prop-based `EditorToolbar` and `Toolbar` usage is replaced by command-mode controls;
106
+ use `EditorToolbar` with `mode="commands"`.
107
+
108
+ ## Plugins
109
+
110
+ `definePptxPlugin` defines tools installed through `plugins`, with permissions supplied by
111
+ `pluginGrants`. This plugin API is experimental and may change in minor releases.
112
+ See [Host PPTX editor plugins](https://docs.betteroffice.dev/docs/javascript#host-pptx-editor-plugins)
113
+ for panels, overlays, lifecycle, permissions, and error handling.
114
+
115
+ ## Version-checked edit batches
116
+
117
+ `readContent`, `findText`, `validateEdits`, and `applyEdits` on the editor API return promises and run
118
+ after pending input. See [Edit PPTX in version-checked batches](https://docs.betteroffice.dev/docs/javascript#edit-pptx-in-version-checked-batches)
119
+ for requests, atomicity, and typed refusals.
312
120
 
313
121
  ## Review agent proposals
314
122
 
315
- Use the editor API supplied to `onReady` to stage edits from your agent, then
316
- refresh the pending list:
317
-
318
- ```ts
319
- api.handle.propose('editor-agent', 'Clarify the speaker notes', [{
320
- type: 'setSlideNotes',
321
- slideId: api.handle.snapshot().slides[0].id,
322
- text: 'Explain the customer outcome before the implementation details.',
323
- }]);
324
- api.refreshProposals();
325
- ```
123
+ Use the access returned by `handleAsync()` to call `propose`, then await `refreshProposals()`.
124
+ Pending proposals appear on the canvas with text differences, shape bounds, and speaker-note diffs.
125
+ The review controls preview, accept, or reject a group; acceptance creates one undo step.
326
126
 
327
- Pending edits appear directly on the slide canvas: deleted text is red and
328
- struck through, inserted text is green and underlined, and moved/resized shapes
329
- show their previous and proposed bounds. Speaker notes have their own inline
330
- text diff. The canvas toolbar selects a proposal when several affect the slide
331
- and provides acceptance, rejection, and access to review details. Acceptance is
332
- available after the current diff has painted successfully.
333
-
334
- The canvas is in review mode while showing a diff. **Edit slide** (or Escape)
335
- returns to normal editing; **Show changes** restores the diff. This keeps
336
- temporary review offsets separate from editable text. Saving, PNG export, and
337
- presentation mode use the actual document. Changes from other users refresh the
338
- review, and stale targets require the explicit review described below.
339
-
340
- The **Agent proposals** button shows the pending count. Each group shows its
341
- author, rationale, targets, and text changes. **Preview** opens current and
342
- proposed slide renderings, with a target selector for groups spanning multiple
343
- shapes or slides. Notes changes also appear as text because notes are outside
344
- the slide canvas.
345
-
346
- Accepting a group updates the editor, calls `onChange`, and creates one Undo
347
- step. Rejecting it leaves the deck untouched. If a target changed, preview its
348
- current state before choosing **Apply updated proposal**. A further target
349
- change detected at that click refreshes the preview for another review.
350
-
351
- Accepted proposals are saved and synchronized. `api.refresh()` also refreshes the
352
- proposal list.
127
+ Escape or **Edit slide** exits review mode. Saving, PNG export, and presentation mode use committed
128
+ content. Pending proposals stay in the session; accepted edits are saved and synchronized.
353
129
 
354
130
  ## Collaboration
355
131
 
356
- Pass a `collaboration` prop to co-edit a deck live. `onReplica` hands you the
357
- session; drive it with a `CollaborationProvider` over any transport. Every peer
358
- must boot from the same `initialUpdate` seed.
132
+ Pass `collaboration` to co-edit a deck; `onReplica` receives an async replica or `null` on cleanup.
133
+ Set `roomId` when switching rooms and seed peers from the same update. Omit `clientId` to generate
134
+ one for each opened session.
135
+ See the [collaboration guide](https://docs.betteroffice.dev/docs/collaboration) for transport setup.
359
136
 
360
- ```tsx
361
- import { CollaborationProvider } from '@betteroffice/pptx';
362
-
363
- <PptxEditor
364
- file={file}
365
- fonts={fonts}
366
- collaboration={{
367
- clientId,
368
- initialUpdate: sharedSeed,
369
- onReplica: (replica) => {
370
- if (!replica) return;
371
- const provider = new CollaborationProvider(replica, transport, {
372
- user: { name: "Ada" }, // shown on this peer's presence chip
373
- });
374
- provider.connect();
375
- },
376
- }}
377
- />;
378
- ```
137
+ ## Browser integration
379
138
 
380
- ## Framework notes
139
+ Mount the editor in the browser with a container of explicit height. Frameworks that render on the
140
+ server should load the editor client-side with server rendering disabled. See [hosting](https://docs.betteroffice.dev/docs/migrating-to-0-5#hosting) for
141
+ worker, chunk and CSP needs.
381
142
 
382
- Under Next.js, load the editor with `next/dynamic` and `ssr: false`.
143
+ ## Documentation
383
144
 
384
- [JavaScript guide](https://docs.betteroffice.dev/docs/javascript) ·
385
- [Changelog](https://github.com/openooxml/betteroffice/blob/main/packages/pptx-react/CHANGELOG.md) · Apache-2.0.
145
+ - [JavaScript guide](https://docs.betteroffice.dev/docs/javascript)
146
+ - [Collaboration guide](https://docs.betteroffice.dev/docs/collaboration)
147
+ - [Package guide](https://docs.betteroffice.dev/docs/packages)
148
+ - [PPTX core: @betteroffice/pptx](https://www.npmjs.com/package/@betteroffice/pptx)
149
+ - [UI translations: @betteroffice/pptx-i18n](https://www.npmjs.com/package/@betteroffice/pptx-i18n)
150
+ - [Repository](https://github.com/openooxml/betteroffice)
@@ -0,0 +1 @@
1
+ import'./chunk-O2XFH626.js';import {sizeCanvasForSlide,paintSlide}from'@betteroffice/pptx';import {useRef,useState,useEffect}from'react';import {jsx,jsxs}from'react/jsx-runtime';function K({handle:x,slideCount:n,startIndex:H,resolveImage:y,label:P,counterLabel:S,exitLabel:k,previousLabel:D,nextLabel:W,onExit:d,onError:E}){let C=useRef(null),m=useRef(null),M=useRef(null),u=useRef({onExit:d,onError:E});u.current={onExit:d,onError:E};let[z,h]=useState(H),a=Math.max(0,Math.min(z,n-1)),[f,B]=useState({width:0,height:0}),s=e=>h(Math.max(0,Math.min(a+e,n-1)));return useEffect(()=>{h(e=>Math.max(0,Math.min(e,n-1))),n===0&&u.current.onExit();},[n]),useEffect(()=>{let e=m.current,o=C.current,p=document.activeElement,r=true;e.showModal(),e.focus(),o.requestFullscreen?.().then(()=>{r?(e.close(),e.showModal(),e.focus()):document.fullscreenElement===o&&document.exitFullscreen().catch(()=>{});}).catch(()=>{});let c=()=>{document.fullscreenElement||u.current.onExit();},l=()=>B({width:window.innerWidth,height:window.innerHeight});return l(),window.addEventListener("resize",l),document.addEventListener("fullscreenchange",c),()=>{r=false,window.removeEventListener("resize",l),document.removeEventListener("fullscreenchange",c),document.fullscreenElement===o&&document.exitFullscreen().catch(()=>{}),e.close(),p instanceof HTMLElement&&p.isConnected&&p.focus();}},[]),useEffect(()=>{let e=M.current;if(!e||n===0||f.width<=0||f.height<=0)return;let o=false;return (async()=>{let r=x.layoutSlide(a),c=document.createElement("canvas"),l=c.getContext("2d");if(!l)return;let b=Math.min(f.width/r.width,f.height/r.height),v=window.devicePixelRatio||1;sizeCanvasForSlide(c,r,v,b),await paintSlide(l,r,v,b,{resolveImage:y}),!o&&(sizeCanvasForSlide(e,r,v,b),e.getContext("2d")?.drawImage(c,0,0));})().catch(r=>{o||(u.current.onError(r),u.current.onExit());}),()=>{o=true;}},[x,a,n,y,f]),jsx("div",{ref:C,children:jsxs("dialog",{ref:m,"aria-label":P,tabIndex:-1,style:i.presentationOverlay,onCancel:e=>{e.preventDefault(),d();},onClick:e=>{e.target===m.current&&s(1);},onKeyDown:e=>{if(!(e.altKey||e.ctrlKey||e.metaKey)){switch(e.key){case " ":if(e.target instanceof HTMLElement&&e.target.closest("button"))return;s(1);break;case "ArrowRight":case "ArrowDown":case "PageDown":s(1);break;case "ArrowLeft":case "ArrowUp":case "PageUp":s(-1);break;case "Home":h(0);break;case "End":h(Math.max(0,n-1));break;case "Escape":d();break;default:return}e.preventDefault(),e.stopPropagation();}},children:[jsx("canvas",{ref:M,style:i.presentationCanvas}),jsx("button",{type:"button",onClick:d,"aria-label":k,title:k,style:i.presentationExit,children:jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:jsx("path",{d:"M6 6 18 18M18 6 6 18"})})}),jsxs("div",{style:i.presentationControls,children:[jsx("button",{type:"button",onClick:()=>s(-1),disabled:a===0,"aria-label":D,style:i.presentationNavButton,children:jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4","aria-hidden":"true",children:jsx("path",{d:"m15 6-6 6 6 6"})})}),jsx("span",{style:i.presentationCounter,"aria-live":"polite",children:S(a+1,n)}),jsx("button",{type:"button",onClick:()=>s(1),disabled:a>=n-1,"aria-label":W,style:i.presentationNavButton,children:jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4","aria-hidden":"true",children:jsx("path",{d:"m9 6 6 6-6 6"})})})]})]})})}var i={presentationOverlay:{position:"fixed",margin:0,padding:0,border:0,width:"100vw",height:"100vh",maxWidth:"none",maxHeight:"none",inset:0,zIndex:2147483e3,display:"flex",alignItems:"center",justifyContent:"center",background:"#000000",cursor:"pointer"},presentationCanvas:{display:"block",pointerEvents:"none"},presentationExit:{position:"absolute",top:16,right:16,display:"inline-flex",alignItems:"center",justifyContent:"center",width:36,height:36,border:0,borderRadius:999,background:"rgba(255, 255, 255, 0.14)",color:"#ffffff",cursor:"pointer"},presentationControls:{position:"absolute",bottom:20,left:"50%",transform:"translateX(-50%)",display:"flex",alignItems:"center",gap:12,padding:"6px 14px",borderRadius:999,background:"rgba(255, 255, 255, 0.12)"},presentationNavButton:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:28,height:28,border:0,borderRadius:999,background:"rgba(255, 255, 255, 0.14)",color:"#ffffff",cursor:"pointer"},presentationCounter:{minWidth:64,color:"#ffffff",fontSize:12,fontWeight:600,textAlign:"center"}};export{K as PresentationOverlay};
@@ -0,0 +1 @@
1
+ import'./chunk-O2XFH626.js';function c(o){try{let t=new DataView(o.buffer,o.byteOffset,o.byteLength);if(t.byteLength<12)return;let n=0;if(t.getUint32(0)===1953784678){let e=t.getUint32(4),r=t.getUint32(8);if(e!==65536&&e!==131072||r===0||12+r*4+(e===131072?12:0)>t.byteLength)return;n=t.getUint32(12);}if(n+12>t.byteLength)return;let u=t.getUint32(n);if(u!==65536&&u!==1953658213&&u!==1330926671)return;let l=t.getUint16(n+4);if(n+12+l*16>t.byteLength)return;let i,f;for(let e=0;e<l;e++){let r=n+12+e*16,a=t.getUint32(r),g=t.getUint32(r+8),s=t.getUint32(r+12);if(g+s>t.byteLength)return;if(a===1330851634){if(i)return;i={offset:g,length:s};}else if(a===1751474532){if(f)return;f={offset:g,length:s};}}if(i){if(i.length<64)return;let e=t.getUint16(i.offset+62);return {weight:Math.max(1,Math.min(1e3,t.getUint16(i.offset+4))),bold:(e&32)!==0,italic:(e&1)!==0,oblique:(e&512)!==0}}if(f){if(f.length<46)return;let e=t.getUint16(f.offset+44);return {weight:e&1?700:400,bold:(e&1)!==0,italic:(e&2)!==0,oblique:!1}}}catch{return}}export{c as readFontTraits};