@deepseek-ai/libreoffice-kit 0.0.2-rc7 → 0.0.2-rc9

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.
@@ -1,29 +1,42 @@
1
- /** Browser document ownership, cancellation and asynchronous Host font delivery. */
1
+ /** Browser Worker ownership, document lifetime, cancellation and asynchronous Host font delivery. */
2
2
  import { FONT_CHUNK_BYTES, FONT_HEADER_BYTES, FontState } from './protocol.ts'
3
- import type { OwnerMessage, OwnerRequest, WorkerMessage, WorkerOptions } from './protocol.ts'
3
+ import type { OwnerRequest, WorkerDocumentOptions, WorkerMessage, WorkerOptions } from './protocol.ts'
4
4
  import { fontFrames, fontViews } from './font-channel.ts'
5
5
  import { BrowserRenderError } from './types.ts'
6
6
  import { preparedBrowserModule } from './preparation.ts'
7
- import type { BrowserDocumentOptions } from './types.ts'
8
- import type { OfficeDocumentEvent, OfficeDocumentOptions } from './office-types.ts'
7
+ import type { BrowserDocumentOptions, BrowserRuntimeOptions } from './types.ts'
8
+ import type { OfficeDocumentEvent } from './office-types.ts'
9
9
 
10
10
  interface Pending {
11
11
  resolve(message: WorkerMessage): void
12
12
  reject(error: unknown): void
13
13
  }
14
14
 
15
+ /** One engine Worker that owns a LibreOffice instance and opens one document at a time. */
16
+ export interface BrowserWorker {
17
+ /** Load a document, replacing any document this Worker still holds. */
18
+ openDocument(options: WorkerDocumentOptions & Pick<BrowserDocumentOptions, 'resolveFonts' | 'onMissingFonts'>,
19
+ signal?: AbortSignal): Promise<Extract<WorkerMessage, { type: 'opened' }>>
20
+ /** Release the open document; the engine and its pthreads stay initialized. */
21
+ closeDocument(): Promise<void>
22
+ /** Send one typed request owned by the open document. */
23
+ request(message: OwnerRequest, operation?: AbortSignal, transfer?: Transferable[]): Promise<WorkerMessage>
24
+ /** Close the document and terminate the Worker. */
25
+ dispose(): Promise<void>
26
+ }
27
+
15
28
  /**
16
- * Load original Office bytes in a dedicated Worker with no intermediate PDF.
17
- * @param options - Resources, limits, source bytes and asynchronous Host font provider.
18
- * @param signal - Document lifetime; abort closes its Worker and all pending work.
19
- * @returns Initial geometry, ordered Worker requests and joined disposal.
29
+ * Start one LibreOffice Worker without loading a document.
30
+ * @param options - Engine resources, limits and asynchronous Host font provider.
31
+ * @param signal - Engine lifetime; abort closes its Worker and all pending work.
32
+ * @param onEvent - Reading notifications, including fatal Worker failures.
33
+ * @returns Document loading, Worker requests and joined disposal.
20
34
  */
21
- export async function openBrowserConnection(options: BrowserDocumentOptions | OfficeDocumentOptions, signal?: AbortSignal,
22
- office = false, onEvent?: (event: OfficeDocumentEvent) => void) {
35
+ export async function openBrowserWorker(options: BrowserRuntimeOptions, signal?: AbortSignal,
36
+ onEvent?: (event: OfficeDocumentEvent) => void): Promise<BrowserWorker> {
23
37
  signal?.throwIfAborted()
24
38
  if (!globalThis.crossOriginIsolated || typeof SharedArrayBuffer === 'undefined' || typeof Worker === 'undefined') throw new BrowserRenderError('unavailable', 'LibreOffice requires an isolated secure browser context with Worker and SharedArrayBuffer support.')
25
39
  if (![options.timeoutMs, options.maxLoadedFontBytes, options.maxArchiveEntries, options.maxUncompressedBytes].every(value => Number.isSafeInteger(value) && value > 0) || options.timeoutMs > 0x7fffffff) throw new TypeError('Document limits must be positive integers and timeoutMs must fit a browser timer.')
26
- if (!(office ? ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'] : ['pdf']).includes(options.extension) || options.data.byteLength === 0) throw new BrowserRenderError('invalid-document', 'The document is empty or has an unsupported extension.')
27
40
  if (options.preparedEngine !== undefined) preparedBrowserModule(options.preparedEngine, options.assets)
28
41
  const worker = new Worker(options.assets.workerUrl, { name: 'libreoffice-document' })
29
42
  const channel = new SharedArrayBuffer(FONT_HEADER_BYTES + FONT_CHUNK_BYTES)
@@ -34,7 +47,8 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Of
34
47
  let closed = false
35
48
  let disposal: Promise<void> | undefined
36
49
  let frames: ReturnType<typeof fontFrames> | undefined
37
- let opened: Extract<WorkerMessage, { type: 'opened' }> | undefined
50
+ let resolveFonts: BrowserDocumentOptions['resolveFonts'] | undefined
51
+ let onMissingFonts: BrowserDocumentOptions['onMissingFonts'] | undefined
38
52
 
39
53
  function failPending(error: unknown): void {
40
54
  for (const entry of pending.values()) entry.reject(error)
@@ -66,14 +80,15 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Of
66
80
  case 'office-event': if (!closed) { onEvent?.(message.event); if (message.event.type === 'error') void dispose() }; return
67
81
  case 'font':
68
82
  if (closed) return
69
- void Promise.resolve().then(() => options.resolveFonts(message.request, message.known, lifetime.signal)).then(result => {
83
+ if (!resolveFonts) { sendFontError(new BrowserRenderError('font-unavailable', 'No document font resolver is active.')); return }
84
+ void Promise.resolve().then(() => resolveFonts!(message.request, message.known, lifetime.signal)).then(result => {
70
85
  if (closed) return
71
86
  frames = fontFrames(result, message.known)
72
87
  pumpFonts()
73
88
  }, sendFontError)
74
89
  return
75
90
  case 'font-next': pumpFonts(); return
76
- case 'missing-fonts': if (!closed) options.onMissingFonts?.(message.families); return
91
+ case 'missing-fonts': if (!closed) onMissingFonts?.(message.families); return
77
92
  default: {
78
93
  const entry = pending.get(message.id)
79
94
  if (!entry) return
@@ -101,7 +116,7 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Of
101
116
  void dispose()
102
117
  }
103
118
 
104
- function post(message: OwnerMessage, transfer: Transferable[] = []): Promise<WorkerMessage> {
119
+ function post(message: { id: number } & Record<string, unknown>, transfer: Transferable[] = []): Promise<WorkerMessage> {
105
120
  return new Promise((resolve, reject) => {
106
121
  const timer = setTimeout(() => {
107
122
  pending.delete(message.id)
@@ -123,6 +138,8 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Of
123
138
  signal?.removeEventListener('abort', aborted)
124
139
  lifetime.abort()
125
140
  frames = undefined
141
+ resolveFonts = undefined
142
+ onMissingFonts = undefined
126
143
  Atomics.store(control, 0, FontState.Cancelled)
127
144
  Atomics.notify(control, 0)
128
145
  failPending(new BrowserRenderError('disposed', 'The document is closed.'))
@@ -136,36 +153,85 @@ export async function openBrowserConnection(options: BrowserDocumentOptions | Of
136
153
  function aborted(): void { void dispose() }
137
154
  signal?.addEventListener('abort', aborted, { once: true })
138
155
 
156
+ function request(message: OwnerRequest, operation?: AbortSignal, transfer: Transferable[] = []): Promise<WorkerMessage> {
157
+ if (closed) return Promise.reject(new BrowserRenderError('disposed', 'The document is closed.'))
158
+ if (operation?.aborted) return Promise.reject(operation.reason)
159
+ const task = post({ ...message, id: ++sequence }, transfer)
160
+ if (!operation) return task
161
+ return new Promise((resolve, reject) => {
162
+ const abort = (): void => { reject(operation.reason) }
163
+ operation.addEventListener('abort', abort, { once: true })
164
+ void task.then(resolve, reject).finally(() => operation.removeEventListener('abort', abort))
165
+ })
166
+ }
167
+
168
+ const engineOptions: WorkerOptions = { assets: options.assets,
169
+ ...(options.preparedEngine === undefined ? {} : { preparedEngine: options.preparedEngine }),
170
+ timeoutMs: options.timeoutMs, maxLoadedFontBytes: options.maxLoadedFontBytes, fontFallbacks: options.fontFallbacks,
171
+ maxArchiveEntries: options.maxArchiveEntries, maxUncompressedBytes: options.maxUncompressedBytes }
139
172
  try {
140
- const data = new Uint8Array(options.data)
141
- const engineOptions: WorkerOptions = { data, extension: options.extension, assets: options.assets,
142
- ...(options.preparedEngine === undefined ? {} : { preparedEngine: options.preparedEngine }),
143
- timeoutMs: options.timeoutMs, maxLoadedFontBytes: options.maxLoadedFontBytes, fontFallbacks: options.fontFallbacks,
144
- maxArchiveEntries: options.maxArchiveEntries, maxUncompressedBytes: options.maxUncompressedBytes }
145
- const result = await post({ type: 'open', id: ++sequence, options: engineOptions, channel, ...(office ? { office: true } : {}) }, [data.buffer])
146
- if (result.type !== 'opened') throw new BrowserRenderError('invalid-document', 'LibreOffice returned an unexpected load response.')
147
- opened = result
148
- if (opened.type !== 'opened' || opened.pages.length === 0) throw new BrowserRenderError('invalid-document', 'LibreOffice returned no document pages.')
173
+ const started = await post({ type: 'start', id: ++sequence, options: engineOptions, channel })
174
+ if (started.type !== 'started') throw new BrowserRenderError('unavailable', 'LibreOffice returned an unexpected start response.')
149
175
  signal?.throwIfAborted()
150
- } catch (error) {
176
+ } catch (failure) {
151
177
  await dispose()
152
178
  signal?.throwIfAborted()
153
- throw error
179
+ throw failure
154
180
  }
155
181
 
156
182
  return {
157
- opened,
158
- request(message: OwnerRequest, operation?: AbortSignal): Promise<WorkerMessage> {
159
- if (closed) return Promise.reject(new BrowserRenderError('disposed', 'The document is closed.'))
160
- if (operation?.aborted) return Promise.reject(operation.reason)
161
- const task = post({ ...message, id: ++sequence })
162
- if (!operation) return task
163
- return new Promise((resolve, reject) => {
164
- const abort = (): void => { reject(operation.reason) }
165
- operation.addEventListener('abort', abort, { once: true })
166
- void task.then(resolve, reject).finally(() => operation.removeEventListener('abort', abort))
167
- })
183
+ async openDocument(documentOptions, documentSignal) {
184
+ if (closed) throw new BrowserRenderError('disposed', 'The document is closed.')
185
+ if (!['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'].includes(documentOptions.extension) || documentOptions.data.byteLength === 0) throw new BrowserRenderError('invalid-document', 'The document is empty or has an unsupported extension.')
186
+ const data = new Uint8Array(documentOptions.data)
187
+ resolveFonts = documentOptions.resolveFonts
188
+ onMissingFonts = documentOptions.onMissingFonts
189
+ try {
190
+ const result = await request({ type: 'open', options: { data, extension: documentOptions.extension,
191
+ ...(documentOptions.restore === undefined ? {} : { restore: documentOptions.restore }) } }, documentSignal, [data.buffer])
192
+ if (result.type !== 'opened') throw new BrowserRenderError('invalid-document', 'LibreOffice returned an unexpected load response.')
193
+ if (result.pages.length === 0) throw new BrowserRenderError('invalid-document', 'LibreOffice returned no document pages.')
194
+ documentSignal?.throwIfAborted()
195
+ return result
196
+ } catch (failure) {
197
+ await dispose()
198
+ documentSignal?.throwIfAborted()
199
+ throw failure
200
+ }
168
201
  },
202
+ async closeDocument() {
203
+ if (closed) return
204
+ try {
205
+ const result = await request({ type: 'close-document' })
206
+ if (result.type !== 'closed-document') throw new BrowserRenderError('render-failed', 'LibreOffice returned an unexpected close response.')
207
+ } finally {
208
+ resolveFonts = undefined
209
+ onMissingFonts = undefined
210
+ }
211
+ },
212
+ request,
169
213
  dispose,
170
214
  }
171
215
  }
216
+
217
+ /**
218
+ * Load original PDF bytes in a dedicated Worker without Draw import.
219
+ * @param options - Resources, limits, source bytes and asynchronous Host font provider.
220
+ * @param signal - Document lifetime; abort closes its Worker and all pending work.
221
+ * @param onEvent - Reading notifications, including fatal Worker failures.
222
+ * @returns Initial geometry, ordered Worker requests and joined disposal.
223
+ */
224
+ export async function openBrowserConnection(options: BrowserDocumentOptions, signal?: AbortSignal,
225
+ onEvent?: (event: OfficeDocumentEvent) => void) {
226
+ signal?.throwIfAborted()
227
+ if (options.extension !== 'pdf' || options.data.byteLength === 0) throw new BrowserRenderError('invalid-document', 'The document is empty or has an unsupported extension.')
228
+ const connected = await openBrowserWorker(options, signal, onEvent)
229
+ try {
230
+ const opened = await connected.openDocument({ data: options.data, extension: options.extension,
231
+ resolveFonts: options.resolveFonts, ...(options.onMissingFonts === undefined ? {} : { onMissingFonts: options.onMissingFonts }) }, signal)
232
+ return { opened, request: connected.request, dispose: connected.dispose }
233
+ } catch (error) {
234
+ await connected.dispose()
235
+ throw error
236
+ }
237
+ }
@@ -38,6 +38,17 @@ export function* fontFrames(result: BrowserFontResult, known: readonly FontIdent
38
38
 
39
39
  /** One MEMFS font face registered under a document-local family alias. */
40
40
  export interface EngineFontFace { readonly path: string; readonly family: string }
41
+ /** Fonts and internal aliases retained for the lifetime of one engine Worker. */
42
+ export interface EngineFontCache {
43
+ readonly installed: Map<string, { face: EngineFontFace; bytes: number; format: FontIdentity['format'] }>
44
+ readonly aliases: Map<string, { id: string; family: string }>
45
+ loadedBytes: number
46
+ }
47
+
48
+ /** @returns Empty runtime-owned font state shared by successive documents. */
49
+ export function createEngineFontCache(): EngineFontCache {
50
+ return { installed: new Map(), aliases: new Map(), loadedBytes: 0 }
51
+ }
41
52
 
42
53
  const SCRIPT_GROUPS = [
43
54
  ['arabic', /\p{Script_Extensions=Arabic}/u], ['cyrillic', /\p{Script_Extensions=Cyrillic}/u],
@@ -57,10 +68,9 @@ function scriptGroup(point: number): string {
57
68
  export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number, maxLoadedFontBytes: number,
58
69
  declaredFamilies: ReadonlyMap<string, string>, request: (request: BrowserFontRequest, known: readonly FontIdentity[]) => void, next: () => void,
59
70
  install: (path: string, bytes: Uint8Array) => void, missing: (families: readonly string[]) => void,
60
- documentCodePoints: readonly number[] = []): (request: BrowserFontRequest) => EngineFontFace[] {
71
+ documentCodePoints: readonly number[] = [], cache: EngineFontCache = createEngineFontCache()): (request: BrowserFontRequest) => EngineFontFace[] {
61
72
  const { control, bytes } = fontViews(channel)
62
- const installed = new Map<string, { face: EngineFontFace; bytes: number; format: FontIdentity['format'] }>()
63
- const aliases = new Map<string, { id: string; family: string }>()
73
+ const { installed, aliases } = cache
64
74
  const requests = new Map<string, EngineFontFace[]>()
65
75
  const coverage = new Map<string, { readonly points: Set<number>; readonly faces: EngineFontFace[]; complete: boolean }>()
66
76
  const expanded = new Map<string, Set<string>>()
@@ -72,7 +82,6 @@ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number,
72
82
  else documentGroups.set(group, [point])
73
83
  }
74
84
  const families = new Set<string>()
75
- let loadedBytes = 0
76
85
  function read(): { state: FontState; data: Uint8Array } {
77
86
  const started = performance.now()
78
87
  while (Atomics.load(control, 0) === FontState.Waiting) {
@@ -125,7 +134,7 @@ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number,
125
134
  const alias = normalize(font.alias)
126
135
  const previousAlias = aliases.get(alias)
127
136
  if (previousAlias && (previousAlias.family !== font.family || (font.format === undefined && previousAlias.id !== font.id))) throw new BrowserRenderError('font-unavailable', 'Font alias identifies conflicting subsets.')
128
- if (!prior && loadedBytes + font.bytes > maxLoadedFontBytes) throw new BrowserRenderError('font-limit', 'Imported fonts exceed maxLoadedFontBytes.')
137
+ if (!prior && cache.loadedBytes + font.bytes > maxLoadedFontBytes) throw new BrowserRenderError('font-limit', 'Imported fonts exceed maxLoadedFontBytes.')
129
138
  const buffer = prior ? undefined : new Uint8Array(font.bytes)
130
139
  let received = 0
131
140
  while (!font.reference && received < font.bytes) {
@@ -137,7 +146,7 @@ export function createFontReader(channel: SharedArrayBuffer, timeoutMs: number,
137
146
  // A full TTC asset can expose multiple families from the same installed bytes.
138
147
  // Its requested family must not inherit the first family's alias.
139
148
  const face = { path: prior?.face.path ?? (font.format === undefined ? `/dsh-fonts/${installed.size}.font` : `/usr/share/fonts/dsh-pdfium/${installed.size}.${font.format}`), family: font.alias }
140
- if (buffer) { install(face.path, buffer); installed.set(font.id, { face, bytes: buffer.length, format: font.format }); loadedBytes += buffer.length }
149
+ if (buffer) { install(face.path, buffer); installed.set(font.id, { face, bytes: buffer.length, format: font.format }); cache.loadedBytes += buffer.length }
141
150
  aliases.set(alias, { id: font.id, family: font.family })
142
151
  faces.push(face)
143
152
  }
@@ -3,10 +3,10 @@ import { openBrowserConnection } from './connection.ts'
3
3
  import { BrowserRenderError } from './types.ts'
4
4
  import type { BrowserDocument, BrowserDocumentOptions, BrowserTile, BrowserTileRequest } from './types.ts'
5
5
  export { BrowserRenderError } from './types.ts'
6
- export { openOfficeDocument } from './office.ts'
6
+ export { openOfficeDocument, openOfficeRuntime } from './office.ts'
7
7
  export { prepareOfficeBrowser } from './preparation.ts'
8
8
  export type * from './office-types.ts'
9
- export type { BrowserDocument, BrowserDocumentOptions, BrowserEngineAssets, BrowserFontIdentity, BrowserFontRequest, BrowserFontResult, BrowserPage, BrowserRenderErrorCode, BrowserResolvedFont, BrowserTile, BrowserTileRequest, PreparedBrowserEngine } from './types.ts'
9
+ export type { BrowserDocument, BrowserDocumentOptions, BrowserEngineAssets, BrowserFontIdentity, BrowserFontRequest, BrowserFontResult, BrowserPage, BrowserRenderErrorCode, BrowserResolvedFont, BrowserRuntimeOptions, BrowserTile, BrowserTileRequest, PreparedBrowserEngine } from './types.ts'
10
10
 
11
11
  /**
12
12
  * Open a read-only document; each call owns an independent Worker.
@@ -3,7 +3,7 @@ import { BrowserRenderError } from './types.ts'
3
3
  import type { BrowserTile } from './types.ts'
4
4
  import type { EmscriptenModule } from './engine-types.ts'
5
5
  import type { OfficeOperation } from './protocol.ts'
6
- import type { OfficeDocumentEvent, OfficeDocumentFormat, OfficeDocumentState, OfficeDocumentTileRequest, OfficeDocumentRectangle, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult } from './office-types.ts'
6
+ import type { OfficeDocumentEvent, OfficeDocumentFormat, OfficeDocumentState, OfficeDocumentTileRequest, OfficeDocumentRectangle, OfficeDocumentLayoutRequest, OfficeDocumentLayoutResult, OfficeReadingState } from './office-types.ts'
7
7
  import { parseCellRange } from '@deepseek-ai/libreoffice-kit/internal/sheet-geometry'
8
8
  import { renderRegion } from './engine-rendering.ts'
9
9
  import { TWIPS_PER_CSS_PIXEL, writerPages } from './rendering.ts'
@@ -41,7 +41,8 @@ export class OfficeEngine {
41
41
  private geometryDirty = false
42
42
  private stopped = false
43
43
  private layoutWidth = 0
44
- private viewport = ''
44
+ private viewportKey = ''
45
+ private viewportState: OfficeReadingState['viewport'] = null
45
46
  private captureView: number | undefined
46
47
  private readingView: number | undefined
47
48
  private commandResult: { name: string; resolve: () => void; reject: (error: unknown) => void } | undefined
@@ -171,7 +172,7 @@ export class OfficeEngine {
171
172
  case 14: {
172
173
  const part = Number(payload)
173
174
  if (Number.isSafeInteger(part) && part >= 0 && part < this.state.parts.length) {
174
- this.state = { ...this.state, part }; this.viewport = ''; this.geometryDirty = true; changed = true
175
+ this.state = { ...this.state, part }; this.viewportKey = ''; this.viewportState = null; this.geometryDirty = true; changed = true
175
176
  }
176
177
  break
177
178
  }
@@ -239,7 +240,8 @@ export class OfficeEngine {
239
240
  const part = integer(operation.part, this.state.parts.length - 1)
240
241
  if (part === this.state.part) break
241
242
  this.invoke('part', [part])
242
- this.viewport = ''
243
+ this.viewportKey = ''
244
+ this.viewportState = null
243
245
  this.state = { ...this.state, part, cursor: null, selection: [], graphicSelection: null, cellAddress: '', cellFormula: '' }
244
246
  const geometry = this.refreshGeometry()
245
247
  if (geometry !== undefined) this.state = { ...this.state, layoutGeneration: this.state.layoutGeneration + 1,
@@ -253,7 +255,11 @@ export class OfficeEngine {
253
255
  if (!(operation.scale > 0 && operation.scale <= 16 && width > 0 && height > 0)) throw new BrowserRenderError('render-failed', 'Office viewport is invalid.')
254
256
  const args = [Math.max(1, Math.round(256 * operation.scale)), 256 * TWIPS_PER_CSS_PIXEL, twips(x), twips(y), twips(width), twips(height)]
255
257
  const key = args.join(',')
256
- if (key !== this.viewport) { this.invoke('viewport', args); this.viewport = key }
258
+ if (key !== this.viewportKey) {
259
+ this.invoke('viewport', args)
260
+ this.viewportKey = key
261
+ this.viewportState = { rectangle: { ...operation.rectangle }, scale: operation.scale }
262
+ }
257
263
  break
258
264
  }
259
265
  case 'layout': {
@@ -267,7 +273,8 @@ export class OfficeEngine {
267
273
  if (request.mode === this.state.layout && width === this.layoutWidth) return { layout: { changed: false } }
268
274
  const result = this.configure(request)
269
275
  this.layoutWidth = width
270
- this.viewport = ''
276
+ this.viewportKey = ''
277
+ this.viewportState = null
271
278
  this.state = { ...this.state, layout: request.mode, layoutGeneration: this.state.layoutGeneration + 1,
272
279
  renderGeneration: this.state.renderGeneration + 1 }
273
280
  // Establish the requested layout before its acknowledgement pumps any
@@ -303,6 +310,73 @@ export class OfficeEngine {
303
310
  try { this.invoke('command', [name, JSON.stringify(args)]); this.pump(); await result.promise }
304
311
  finally { this.commandResult = undefined }
305
312
  }
313
+ /** Read the part and selection the next open of these bytes must restore. */
314
+ capture(): OfficeReadingState {
315
+ this.requireOpen()
316
+ if (this.readingView !== undefined) this.invoke('set_view', [this.readingView])
317
+ this.flush()
318
+ const raw = this.text('dsh_lok_document_capture_reading_selection', [this.document])
319
+ let text: OfficeReadingState['text'] = null
320
+ let cell: string | null = null
321
+ let object: OfficeReadingState['object'] = null
322
+ if (raw !== null && raw !== '') {
323
+ const selection = JSON.parse(raw) as { kind?: unknown; pointNode?: unknown; pointOffset?: unknown;
324
+ markNode?: unknown; markOffset?: unknown; range?: unknown; paths?: unknown }
325
+ if (selection.kind === 'text') {
326
+ text = { pointNode: integer(selection.pointNode as number), pointOffset: integer(selection.pointOffset as number),
327
+ markNode: integer(selection.markNode as number), markOffset: integer(selection.markOffset as number) }
328
+ } else if (selection.kind === 'cell' && typeof selection.range === 'string') {
329
+ parseCellRange(selection.range)
330
+ cell = selection.range
331
+ } else if (selection.kind === 'object' && typeof selection.paths === 'string') {
332
+ const paths = selection.paths.split(',')
333
+ if (paths.some(path => path === '' || path.split('/').some(value => value === '')))
334
+ throw new BrowserRenderError('render-failed', 'LibreOffice returned an invalid object selection.')
335
+ object = paths.map(path => path.split('/').map(value => integer(Number(value))))
336
+ }
337
+ }
338
+ const layout: OfficeReadingState['layout'] = this.state.layout === 'continuous'
339
+ ? { mode: 'continuous', width: this.layoutWidth / TWIPS_PER_CSS_PIXEL } : { mode: 'paginated' }
340
+ return { version: 1, documentType: this.state.documentType, part: this.state.part,
341
+ layout, viewport: this.viewportState, text, cell, object }
342
+ }
343
+ /**
344
+ * Apply a reading position captured from the same bytes.
345
+ * @param state - Part and selection captured before this document closed.
346
+ */
347
+ async restore(state: OfficeReadingState): Promise<void> {
348
+ this.requireOpen()
349
+ if (state.version !== 1 || state.documentType !== this.state.documentType)
350
+ throw new BrowserRenderError('render-failed', 'The captured reading state belongs to another document.')
351
+ if (this.state.documentType === 'text') {
352
+ if (state.layout.mode === 'continuous') {
353
+ const anchor = state.viewport === null ? undefined
354
+ : { x: state.viewport.rectangle.x, y: state.viewport.rectangle.y }
355
+ await this.operation({ type: 'layout', request: { mode: 'continuous', width: state.layout.width,
356
+ ...(anchor === undefined ? {} : { anchor }) } })
357
+ } else if (state.layout.mode !== 'paginated') {
358
+ throw new BrowserRenderError('render-failed', 'The captured reading layout is invalid.')
359
+ }
360
+ } else if (state.layout.mode !== 'paginated') {
361
+ throw new BrowserRenderError('render-failed', 'The captured reading layout belongs to a Writer document.')
362
+ }
363
+ if (this.state.documentType !== 'text' && state.part !== this.state.part)
364
+ await this.operation({ type: 'part', part: state.part })
365
+ if (state.text && this.state.documentType === 'text') {
366
+ const { pointNode, pointOffset, markNode, markOffset } = state.text
367
+ this.invoke('restore_reading_text_selection', [integer(pointNode), integer(pointOffset),
368
+ integer(markNode), integer(markOffset)])
369
+ }
370
+ if (state.cell && this.state.documentType === 'spreadsheet')
371
+ await this.operation({ type: 'cell', address: state.cell })
372
+ if (state.object && this.state.documentType === 'presentation') {
373
+ const paths = state.object.map(path => path.map(value => integer(value)).join('/')).join(',')
374
+ if (!paths) throw new BrowserRenderError('render-failed', 'The captured object selection is invalid.')
375
+ this.invoke('restore_reading_object_selection', [paths])
376
+ }
377
+ if (state.viewport !== null) await this.operation({ type: 'viewport', ...state.viewport })
378
+ this.pump()
379
+ }
306
380
  /** Direct tiles preserve the active view, navigation state and selection. */
307
381
  render(request: OfficeDocumentTileRequest): BrowserTile {
308
382
  this.requireOpen()
@@ -52,12 +52,51 @@ export interface OfficeDocumentNavigation {
52
52
  }
53
53
  /** One region of the current part. Pixel density does not change document layout. */
54
54
  export interface OfficeDocumentTileRequest extends OfficeDocumentRectangle { readonly part: number; readonly scale: number }
55
+ /** Writer selection as document-model positions; one file always resolves to the same nodes. */
56
+ export interface OfficeTextSelection {
57
+ /** Document node holding the selection point. */
58
+ readonly pointNode: number
59
+ /** Character offset inside the point node's text. */
60
+ readonly pointOffset: number
61
+ /** Document node holding the selection mark. */
62
+ readonly markNode: number
63
+ /** Character offset inside the mark node's text. */
64
+ readonly markOffset: number
65
+ }
66
+ /** Reading position of one document; capturable before it closes and restorable when its bytes reopen. */
67
+ export interface OfficeReadingState {
68
+ readonly version: 1
69
+ readonly documentType: OfficeDocumentState['documentType']
70
+ /** Writer page, Calc worksheet, or Impress slide. */
71
+ readonly part: number
72
+ /** Writer layout parameters; non-Writer documents remain paginated. */
73
+ readonly layout: { readonly mode: 'paginated' } | { readonly mode: 'continuous'; readonly width: number }
74
+ /** Last document-coordinate viewport and raster scale, when one was configured. */
75
+ readonly viewport: { readonly rectangle: OfficeDocumentRectangle; readonly scale: number } | null
76
+ /** Writer text selection; null when the reader holds no text selection. */
77
+ readonly text: OfficeTextSelection | null
78
+ /** Calc selected range in A1 notation; null when the reader holds no cell range. */
79
+ readonly cell: string | null
80
+ /** Selected drawing objects as ordinal paths inside the current slide. */
81
+ readonly object: readonly (readonly number[])[] | null
82
+ }
83
+ /** Source bytes and reading position for one document of a shared runtime. */
84
+ export interface OfficeDocumentOpenOptions {
85
+ readonly data: Uint8Array
86
+ readonly extension: OfficeDocumentFormat
87
+ /** Match fonts for this document without blocking the browser's main thread. */
88
+ readonly resolveFonts: BrowserDocumentOptions['resolveFonts']
89
+ /** Called with unavailable declared families for this document. */
90
+ readonly onMissingFonts?: BrowserDocumentOptions['onMissingFonts']
91
+ /** Reading position captured from an earlier open of the same bytes. */
92
+ readonly restore?: OfficeReadingState
93
+ }
55
94
  /** A null rectangle invalidates an entire part; negative part means every part. */
56
95
  export type OfficeDocumentEvent =
57
96
  | { readonly type: 'state'; readonly state: OfficeDocumentState }
58
97
  | { readonly type: 'invalidate'; readonly part: number; readonly rectangle: OfficeDocumentRectangle | null; readonly generation: number }
59
98
  | { readonly type: 'error'; readonly code: BrowserRenderErrorCode; readonly message: string }
60
- /** Retain this session while hidden; dispose only when the document is closed. */
99
+ /** One open document of a runtime; closing it frees the parsed model without destroying the engine. */
61
100
  export interface OfficeDocument {
62
101
  readonly state: OfficeDocumentState
63
102
  subscribe(listener: (event: OfficeDocumentEvent) => void): () => void
@@ -73,5 +112,17 @@ export interface OfficeDocument {
73
112
  setLayout(request: OfficeDocumentLayoutRequest): Promise<OfficeDocumentLayoutResult>
74
113
  /** Only the current part can be painted; queued requests for a former part reject with stale-part without changing selection. */
75
114
  renderTile(request: OfficeDocumentTileRequest, signal?: AbortSignal): Promise<BrowserTile>
115
+ /** Read the position the next open of the same bytes must restore. */
116
+ captureReadingState(): Promise<OfficeReadingState>
117
+ /** Close this document and release its model; the owning runtime keeps its engine. */
118
+ close(): Promise<void>
119
+ /** Close this document and destroy the owning runtime. */
120
+ dispose(): Promise<void>
121
+ }
122
+ /** One engine Worker that opens documents one at a time without reinitializing LibreOffice. */
123
+ export interface OfficeRuntime {
124
+ /** Open a document, closing the document this runtime currently holds. */
125
+ open(options: OfficeDocumentOpenOptions, signal?: AbortSignal): Promise<OfficeDocument>
126
+ /** Close the open document and release the Worker, its WASM instance and its pthreads. */
76
127
  dispose(): Promise<void>
77
128
  }