@univerjs/docs-toc 1.5.2 → 1.6.0

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/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { BooleanNumber, BuildTextUtils, CommandType, CustomRangeType, DependentOn, ICommandService, IConfigService, IUndoRedoService, IUniverInstanceService, Inject, Injector, JSONX, NamedStyleType, Plugin, SliceBodyType, TabStopAlignment, TabStopLeader, TextX, Tools, UniverInstanceType, cloneParagraphWithId, createParagraphId, generateRandomId, getBodySlice, getPlainText, getRichTextEditPath, merge } from "@univerjs/core";
1
+ import { BooleanNumber, BuildTextUtils, CommandType, CustomRangeType, DependentOn, DocStyleType, DocumentFlavor, ICommandService, IConfigService, IUndoRedoService, IUniverInstanceService, Inject, Injector, JSONX, LocaleService, LocaleType, NamedStyleType, NumberUnitType, PRESET_LIST_TYPE, Plugin, SliceBodyType, SpecialCharacterKind, TabStopAlignment, TabStopLeader, TextX, Tools, UniverInstanceType, binSearchFirstGreaterThanTarget, cloneParagraphWithId, createParagraphId, generateRandomId, getBodySlice, getPlainText, getRichTextEditPath, merge, resolveDocumentParagraphBullet, resolveDocumentParagraphStyle, resolveDocumentTextStyle } from "@univerjs/core";
2
2
  import { DocSelectionManagerService, DocSkeletonManagerService, DocStateChangeManagerService, RichTextEditingMutation, UniverDocsPlugin } from "@univerjs/docs";
3
- import { IRenderManagerService, UniverRenderEnginePlugin } from "@univerjs/engine-render";
3
+ import { IRenderManagerService, UniverRenderEnginePlugin, getFontStyleString, getNumberUnitValue, measureDocumentNoWrapTextWidth, resolveDocumentDefaultFont, resolveDocumentParagraphNumbering } from "@univerjs/engine-render";
4
4
  import { filter, firstValueFrom, take, timeout } from "rxjs";
5
5
 
6
6
  // src/commands/table-of-contents.command.ts
@@ -59,7 +59,14 @@ async function updateTableOfContents(accessor, params, historyGroupId = generate
59
59
  const pageIndex = skeleton.findBodyPageIndexByCharIndex(offset);
60
60
  return (_skeleton$getSkeleton = skeleton.getSkeletonData()) === null || _skeleton$getSkeleton === void 0 || (_skeleton$getSkeleton = _skeleton$getSkeleton.pages[pageIndex]) === null || _skeleton$getSkeleton === void 0 ? void 0 : _skeleton$getSkeleton.pageNumber;
61
61
  };
62
- const replacement = (params === null || params === void 0 ? void 0 : params.mode) === "pageNumbersOnly" ? buildPageNumberOnlyTableOfContentsBody(currentBody, currentToc, resolvePageNumber) : buildTableOfContentsBody(currentBody, currentToc, resolvePageNumber);
62
+ const replacement = (params === null || params === void 0 ? void 0 : params.mode) === "pageNumbersOnly" ? buildPageNumberOnlyTableOfContentsBody(currentBody, currentToc, resolvePageNumber) : buildTableOfContentsBody(currentBody, currentToc, resolvePageNumber, void 0, {
63
+ documentStyle: doc.getDocumentStyle(),
64
+ locale: accessor.get(LocaleService).getCurrentLocale(),
65
+ styles: doc.getSnapshot().styles,
66
+ lists: doc.getSnapshot().lists,
67
+ tableSource: doc.getSnapshot().tableSource,
68
+ availableWidth: getDocumentTextWidth(currentBody, currentToc.startIndex, doc.getDocumentStyle())
69
+ });
63
70
  if (!replacement) return false;
64
71
  if ((params === null || params === void 0 ? void 0 : params.mode) === "pageNumbersOnly" && Tools.diffValue(getBodySlice(currentBody, currentToc.startIndex, currentToc.endIndex + 1, true, SliceBodyType.cut), replacement)) return true;
65
72
  if (updated && currentBody.dataStream.slice(currentToc.startIndex, currentToc.endIndex + 1) === replacement.dataStream) return true;
@@ -135,12 +142,20 @@ const InsertTableOfContentsCommand = {
135
142
  title: params === null || params === void 0 ? void 0 : params.title
136
143
  }
137
144
  };
138
- const { pageSize, marginLeft = 0, marginRight = 0 } = doc.getDocumentStyle();
145
+ const availableWidth = getDocumentTextWidth(body, selection.startOffset, doc.getDocumentStyle());
139
146
  const replacement = buildTableOfContentsBody(body, toc, (offset) => {
140
147
  var _skeleton$getSkeleton2;
141
148
  const pageIndex = skeleton.findBodyPageIndexByCharIndex(offset);
142
149
  return (_skeleton$getSkeleton2 = skeleton.getSkeletonData()) === null || _skeleton$getSkeleton2 === void 0 || (_skeleton$getSkeleton2 = _skeleton$getSkeleton2.pages[pageIndex]) === null || _skeleton$getSkeleton2 === void 0 ? void 0 : _skeleton$getSkeleton2.pageNumber;
143
- }, generateRandomId, { tabStopOffset: Math.max(72, ((pageSize === null || pageSize === void 0 ? void 0 : pageSize.width) ?? 594.3) - marginLeft - marginRight) });
150
+ }, generateRandomId, {
151
+ tabStopOffset: Math.max(72, availableWidth ?? 594.3),
152
+ availableWidth,
153
+ documentStyle: doc.getDocumentStyle(),
154
+ locale: accessor.get(LocaleService).getCurrentLocale(),
155
+ styles: doc.getSnapshot().styles,
156
+ lists: doc.getSnapshot().lists,
157
+ tableSource: doc.getSnapshot().tableSource
158
+ });
144
159
  if (!replacement) return false;
145
160
  const historyGroupId = generateRandomId();
146
161
  if (!await replaceBodyRange(accessor, doc, unitId, {
@@ -189,6 +204,8 @@ async function waitForCompleteLayout(skeleton) {
189
204
  }
190
205
  }
191
206
  async function waitForNextCompleteLayout(skeleton, generation) {
207
+ const progress = skeleton.getLayoutProgress();
208
+ if (progress == null || progress.complete && progress.generation > generation) return true;
192
209
  try {
193
210
  await firstValueFrom(skeleton.layoutProgress$.pipe(filter((next) => next.generation > generation && next.complete), take(1), timeout({ first: 3e4 })));
194
211
  return true;
@@ -196,7 +213,7 @@ async function waitForNextCompleteLayout(skeleton, generation) {
196
213
  return false;
197
214
  }
198
215
  }
199
- function buildPageNumberOnlyTableOfContentsBody(body, toc, resolvePageNumber) {
216
+ function buildPageNumberOnlyTableOfContentsBody(body, toc, resolvePageNumber, resolvePageField) {
200
217
  var _toc$properties2, _result$customRanges, _result$customRanges2;
201
218
  if (((_toc$properties2 = toc.properties) === null || _toc$properties2 === void 0 ? void 0 : _toc$properties2.locked) === BooleanNumber.TRUE) return null;
202
219
  const result = Tools.deepClone(getBodySlice(body, toc.startIndex, toc.endIndex + 1, true, SliceBodyType.cut));
@@ -208,7 +225,7 @@ function buildPageNumberOnlyTableOfContentsBody(body, toc, resolvePageNumber) {
208
225
  var _body$customRanges4;
209
226
  const originalField = (_body$customRanges4 = body.customRanges) === null || _body$customRanges4 === void 0 ? void 0 : _body$customRanges4.find((range) => range.rangeId === pageField.rangeId);
210
227
  const targetOffset = originalField && resolvePageReferenceOffset(body, originalField);
211
- const pageNumber = targetOffset == null ? void 0 : resolvePageNumber(targetOffset);
228
+ const pageNumber = (originalField && (resolvePageField === null || resolvePageField === void 0 ? void 0 : resolvePageField(originalField))) ?? (targetOffset == null ? void 0 : resolvePageNumber(targetOffset));
212
229
  if (pageNumber == null) return null;
213
230
  replaceFieldResult(result, pageField, String(pageNumber));
214
231
  }
@@ -217,7 +234,7 @@ function buildPageNumberOnlyTableOfContentsBody(body, toc, resolvePageNumber) {
217
234
  return result;
218
235
  }
219
236
  function resolvePageReferenceOffset(body, pageField) {
220
- var _String$match, _pageField$properties, _body$customRanges6, _link$properties, _body$paragraphs;
237
+ var _String$match, _pageField$properties, _body$customRanges6, _link$properties;
221
238
  const targetId = (_String$match = String(((_pageField$properties = pageField.properties) === null || _pageField$properties === void 0 ? void 0 : _pageField$properties.instruction) ?? "").match(/PAGEREF\s+"?([^"\s\\]+)"?/i)) === null || _String$match === void 0 ? void 0 : _String$match[1];
222
239
  if (targetId) {
223
240
  var _body$customRanges5;
@@ -226,13 +243,25 @@ function resolvePageReferenceOffset(body, pageField) {
226
243
  return range.rangeType === CustomRangeType.BOOKMARK && ((_range$properties4 = range.properties) === null || _range$properties4 === void 0 ? void 0 : _range$properties4.bookmarkId) === targetId;
227
244
  });
228
245
  if (bookmark) return bookmark.startIndex;
246
+ const headingOffset = findHeadingOffset(body, targetId);
247
+ if (headingOffset != null) return headingOffset;
229
248
  }
230
249
  const link = (_body$customRanges6 = body.customRanges) === null || _body$customRanges6 === void 0 ? void 0 : _body$customRanges6.find((range) => range.rangeType === CustomRangeType.HYPERLINK && range.startIndex <= pageField.startIndex && pageField.endIndex <= range.endIndex);
231
- const headingId = link === null || link === void 0 || (_link$properties = link.properties) === null || _link$properties === void 0 ? void 0 : _link$properties.headingId;
232
- return (_body$paragraphs = body.paragraphs) === null || _body$paragraphs === void 0 || (_body$paragraphs = _body$paragraphs.find((paragraph) => {
250
+ return findHeadingOffset(body, link === null || link === void 0 || (_link$properties = link.properties) === null || _link$properties === void 0 ? void 0 : _link$properties.headingId);
251
+ }
252
+ function findHeadingOffset(body, headingId) {
253
+ var _body$paragraphs;
254
+ if (!headingId || !body.paragraphs) return;
255
+ const index = body.paragraphs.findIndex((paragraph) => {
233
256
  var _paragraph$paragraphS;
234
- return ((_paragraph$paragraphS = paragraph.paragraphStyle) === null || _paragraph$paragraphS === void 0 ? void 0 : _paragraph$paragraphS.headingId) === headingId;
235
- })) === null || _body$paragraphs === void 0 ? void 0 : _body$paragraphs.startIndex;
257
+ return ((_paragraph$paragraphS = paragraph.paragraphStyle) === null || _paragraph$paragraphS === void 0 ? void 0 : _paragraph$paragraphS.headingId) === headingId || paragraph.paragraphId === headingId;
258
+ });
259
+ if (index < 0) return;
260
+ return skipFieldMarkers(body.dataStream, (((_body$paragraphs = body.paragraphs[index - 1]) === null || _body$paragraphs === void 0 ? void 0 : _body$paragraphs.startIndex) ?? -1) + 1);
261
+ }
262
+ function skipFieldMarkers(dataStream, offset) {
263
+ while (dataStream[offset] === FIELD_START || dataStream[offset] === FIELD_END) offset += 1;
264
+ return offset;
236
265
  }
237
266
  function replaceFieldResult(body, field, value) {
238
267
  var _body$paragraphs2, _body$customRanges7;
@@ -261,47 +290,108 @@ function shiftRuns(runs, start, end, delta) {
261
290
  } else if (run.ed > start) run.ed += delta;
262
291
  });
263
292
  }
293
+ function getDocumentTextWidth(body, offset, documentStyle) {
294
+ var _body$sectionBreaks, _section$pageSize, _documentStyle$pageSi, _section$columnProper;
295
+ const section = (_body$sectionBreaks = body.sectionBreaks) === null || _body$sectionBreaks === void 0 ? void 0 : _body$sectionBreaks.find((entry) => offset <= entry.startIndex);
296
+ const pageWidth = (section === null || section === void 0 || (_section$pageSize = section.pageSize) === null || _section$pageSize === void 0 ? void 0 : _section$pageSize.width) ?? (documentStyle === null || documentStyle === void 0 || (_documentStyle$pageSi = documentStyle.pageSize) === null || _documentStyle$pageSi === void 0 ? void 0 : _documentStyle$pageSi.width);
297
+ return (section === null || section === void 0 || (_section$columnProper = section.columnProperties) === null || _section$columnProper === void 0 || (_section$columnProper = _section$columnProper[0]) === null || _section$columnProper === void 0 ? void 0 : _section$columnProper.width) ?? (pageWidth == null ? void 0 : pageWidth - ((section === null || section === void 0 ? void 0 : section.marginLeft) ?? (documentStyle === null || documentStyle === void 0 ? void 0 : documentStyle.marginLeft) ?? 0) - ((section === null || section === void 0 ? void 0 : section.marginRight) ?? (documentStyle === null || documentStyle === void 0 ? void 0 : documentStyle.marginRight) ?? 0));
298
+ }
264
299
  function buildTableOfContentsBody(body, toc, resolvePageNumber, idFactory = generateRandomId, options) {
265
- var _toc$properties3, _toc$properties4, _toc$properties5, _toc$properties6, _toc$properties7, _toc$properties8, _body$customRanges8, _body$paragraphs3, _toc$properties9;
300
+ var _toc$properties3, _toc$properties4, _toc$properties5, _toc$properties6, _toc$properties7, _toc$properties8, _body$customRanges8, _body$paragraphs3, _toc$properties9, _body$paragraphs4;
266
301
  if (((_toc$properties3 = toc.properties) === null || _toc$properties3 === void 0 ? void 0 : _toc$properties3.locked) === BooleanNumber.TRUE) return null;
302
+ options = {
303
+ ...options,
304
+ availableWidth: (options === null || options === void 0 ? void 0 : options.availableWidth) ?? getDocumentTextWidth(body, toc.startIndex, options === null || options === void 0 ? void 0 : options.documentStyle)
305
+ };
267
306
  const instruction = String(((_toc$properties4 = toc.properties) === null || _toc$properties4 === void 0 ? void 0 : _toc$properties4.instruction) ?? "");
268
- if (/\\c\s+/i.test(instruction)) return null;
307
+ const hyperlinks = instruction.replace(/"[^"]*"/g, "").split(/\s+/).some((token) => token.toLowerCase() === "\\h");
308
+ const hyperlinkFont = resolveEntryHyperlinkFont(hyperlinks, options);
309
+ const titleTabOffsets = getTocTitleTabOffsets(options);
310
+ if (/\\c\s+/i.test(instruction) && !(options === null || options === void 0 ? void 0 : options.entries)) return null;
269
311
  const [minLevel, maxLevel] = parseOutlineLevelRange(instruction);
270
- const headings = collectHeadings(body, toc, minLevel, maxLevel);
312
+ const headings = (options === null || options === void 0 ? void 0 : options.entries) ?? collectHeadings(body, toc, minLevel, maxLevel, options === null || options === void 0 ? void 0 : options.styles, options ?? {});
271
313
  if (headings.length === 0) return null;
272
- const showPageNumbers = ((_toc$properties5 = toc.properties) === null || _toc$properties5 === void 0 ? void 0 : _toc$properties5.showPageNumbers) !== false && !/\\n(?:\s|$)/i.test(instruction);
314
+ const showPageNumbers = (options === null || options === void 0 ? void 0 : options.showPageNumbers) ?? (((_toc$properties5 = toc.properties) === null || _toc$properties5 === void 0 ? void 0 : _toc$properties5.showPageNumbers) !== false && !/\\n(?:\s|$)/i.test(instruction));
273
315
  const rightAlignPageNumbers = showPageNumbers && ((_toc$properties6 = toc.properties) === null || _toc$properties6 === void 0 ? void 0 : _toc$properties6.rightAlignPageNumbers) !== false && !/\\p\s+/i.test(instruction);
274
316
  const tabLeader = normalizeTabLeader((_toc$properties7 = toc.properties) === null || _toc$properties7 === void 0 ? void 0 : _toc$properties7.tabLeader);
275
317
  const format = normalizeFormat((_toc$properties8 = toc.properties) === null || _toc$properties8 === void 0 ? void 0 : _toc$properties8.format);
276
- const oldParagraphs = ((_body$customRanges8 = body.customRanges) === null || _body$customRanges8 === void 0 ? void 0 : _body$customRanges8.some((range) => range.rangeId === toc.rangeId)) ?? false ? ((_body$paragraphs3 = body.paragraphs) === null || _body$paragraphs3 === void 0 ? void 0 : _body$paragraphs3.filter((paragraph) => paragraph.startIndex >= toc.startIndex && paragraph.startIndex <= toc.endIndex)) ?? [] : [];
277
- const title = typeof ((_toc$properties9 = toc.properties) === null || _toc$properties9 === void 0 ? void 0 : _toc$properties9.title) === "string" ? toc.properties.title.trim() : getExistingTableOfContentsTitle(body, oldParagraphs);
318
+ const isExistingToc = ((_body$customRanges8 = body.customRanges) === null || _body$customRanges8 === void 0 ? void 0 : _body$customRanges8.some((range) => range.rangeId === toc.rangeId)) ?? false;
319
+ const oldParagraphs = isExistingToc ? ((_body$paragraphs3 = body.paragraphs) === null || _body$paragraphs3 === void 0 ? void 0 : _body$paragraphs3.filter((paragraph) => paragraph.startIndex >= toc.startIndex && (paragraph.startIndex <= toc.endIndex || paragraph.startIndex === toc.endIndex + 1 && body.dataStream[paragraph.startIndex] === "\r" && /^(toc[1-9]|tableoffigures)$/.test(getTocStyleName(paragraph, options === null || options === void 0 ? void 0 : options.styles))))) ?? [] : [];
320
+ const title = typeof ((_toc$properties9 = toc.properties) === null || _toc$properties9 === void 0 ? void 0 : _toc$properties9.title) === "string" ? toc.properties.title.trim() : getExistingTableOfContentsTitle(body, oldParagraphs, toc.startIndex, options === null || options === void 0 ? void 0 : options.styles);
278
321
  const result = {
279
- dataStream: FIELD_START,
322
+ dataStream: "",
280
323
  paragraphs: [],
281
324
  customRanges: []
282
325
  };
283
326
  const ranges = result.customRanges;
284
- const oldTitleParagraph = oldParagraphs.find((paragraph) => {
285
- var _paragraph$styleId;
286
- return ((_paragraph$styleId = paragraph.styleId) === null || _paragraph$styleId === void 0 ? void 0 : _paragraph$styleId.toLowerCase()) === "tocheading";
287
- });
288
- const oldEntryParagraphs = oldParagraphs.filter((paragraph) => paragraph !== oldTitleParagraph);
327
+ const oldTitleParagraph = oldParagraphs.find((paragraph) => getTocStyleName(paragraph, options === null || options === void 0 ? void 0 : options.styles) === "tocheading");
328
+ const hasExternalTitle = isExistingToc && ((_body$paragraphs4 = body.paragraphs) === null || _body$paragraphs4 === void 0 ? void 0 : _body$paragraphs4.some((paragraph) => paragraph.startIndex === toc.startIndex - 1 && getTocStyleName(paragraph, options === null || options === void 0 ? void 0 : options.styles) === "tocheading"));
329
+ const hasLeadingParagraph = isExistingToc && body.dataStream[toc.startIndex + 1] === "\r";
330
+ const oldLeadingParagraph = hasLeadingParagraph ? oldParagraphs.find((paragraph) => paragraph.startIndex === toc.startIndex + 1) : void 0;
331
+ const oldEntryParagraphs = oldParagraphs.filter((paragraph) => paragraph !== oldTitleParagraph && paragraph !== oldLeadingParagraph);
332
+ const oldParagraphsByTarget = getTocParagraphsByTarget(body, toc, oldEntryParagraphs);
289
333
  const usedParagraphIds = /* @__PURE__ */ new Set();
290
334
  let cachedResult = "";
291
- if (title) {
335
+ if (!isExistingToc && title) {
336
+ result.dataStream = `${title}\r`;
337
+ result.paragraphs.push(cloneParagraphWithId({
338
+ startIndex: result.dataStream.length - 1,
339
+ paragraphId: "",
340
+ styleId: "TOCHeading"
341
+ }, usedParagraphIds));
342
+ }
343
+ const fieldStart = result.dataStream.length;
344
+ result.dataStream += FIELD_START;
345
+ if ((options === null || options === void 0 ? void 0 : options.preserveLeadingParagraph) === true || hasLeadingParagraph && (options === null || options === void 0 ? void 0 : options.preserveLeadingParagraph) !== false) {
346
+ result.dataStream += "\r";
347
+ cachedResult += "\r";
348
+ result.paragraphs.push(cloneParagraphWithId({
349
+ ...Tools.deepClone(oldLeadingParagraph ?? {
350
+ paragraphId: "",
351
+ startIndex: 1
352
+ }),
353
+ startIndex: result.dataStream.length - 1
354
+ }, usedParagraphIds));
355
+ }
356
+ if (title && isExistingToc && !hasExternalTitle) {
292
357
  result.dataStream += `${title}\r`;
293
358
  cachedResult += `${title}\r`;
294
359
  result.paragraphs.push(cloneParagraphWithId({
360
+ ...Tools.deepClone(oldTitleParagraph ?? {}),
295
361
  startIndex: result.dataStream.length - 1,
296
362
  paragraphId: (oldTitleParagraph === null || oldTitleParagraph === void 0 ? void 0 : oldTitleParagraph.paragraphId) ?? "",
297
- styleId: "TOCHeading"
363
+ styleId: (oldTitleParagraph === null || oldTitleParagraph === void 0 ? void 0 : oldTitleParagraph.styleId) ?? "TOCHeading"
298
364
  }, usedParagraphIds));
299
365
  }
300
- for (const [index, heading] of headings.entries()) {
301
- const pageNumber = showPageNumbers ? resolvePageNumber(heading.startOffset) : void 0;
302
- if (showPageNumbers && pageNumber == null) return null;
366
+ for (const [index, entry] of headings.entries()) {
367
+ var _heading$specialChara, _heading$customBlocks, _heading$textRuns, _toc$properties10;
368
+ const heading = applyEntryHyperlinkFont(entry, hyperlinkFont);
369
+ const showEntryPageNumber = showPageNumbers && heading.showPageNumber !== false;
370
+ const pageNumber = showEntryPageNumber ? heading.pageNumber ?? resolvePageNumber(heading.startOffset) : void 0;
371
+ if (showEntryPageNumber && pageNumber == null) return null;
303
372
  const entryStart = result.dataStream.length;
304
- const separator = showPageNumbers ? rightAlignPageNumbers ? " " : " " : "";
373
+ if ((_heading$specialChara = heading.specialCharacters) === null || _heading$specialChara === void 0 ? void 0 : _heading$specialChara.length) ranges.push(...heading.specialCharacters.map((character) => ({
374
+ ...Tools.deepClone(character),
375
+ rangeId: idFactory(),
376
+ startIndex: entryStart + character.startIndex,
377
+ endIndex: entryStart + character.endIndex
378
+ })));
379
+ if ((_heading$customBlocks = heading.customBlocks) === null || _heading$customBlocks === void 0 ? void 0 : _heading$customBlocks.length) {
380
+ result.customBlocks ??= [];
381
+ result.customBlocks.push(...heading.customBlocks.map((block) => ({
382
+ ...block,
383
+ startIndex: entryStart + block.startIndex
384
+ })));
385
+ }
386
+ if ((_heading$textRuns = heading.textRuns) === null || _heading$textRuns === void 0 ? void 0 : _heading$textRuns.length) {
387
+ result.textRuns ??= [];
388
+ result.textRuns.push(...heading.textRuns.map((run) => ({
389
+ ...Tools.deepClone(run),
390
+ st: entryStart + run.st,
391
+ ed: entryStart + run.ed
392
+ })));
393
+ }
394
+ const separator = showEntryPageNumber ? rightAlignPageNumbers ? " " : " " : "";
305
395
  const visibleEntry = `${heading.text}${separator}${pageNumber ?? ""}`;
306
396
  result.dataStream += `${heading.text}${separator}`;
307
397
  const targetId = heading.bookmarkId ?? heading.headingId;
@@ -316,8 +406,8 @@ function buildTableOfContentsBody(body, toc, resolvePageNumber, idFactory = gene
316
406
  textStyleMode: "text"
317
407
  }
318
408
  };
319
- ranges.push(link);
320
- if (showPageNumbers) {
409
+ if (hyperlinks && (heading.text.length || showEntryPageNumber)) ranges.push(link);
410
+ if (showEntryPageNumber) {
321
411
  const pageFieldStart = result.dataStream.length;
322
412
  result.dataStream += `${FIELD_START}${pageNumber}${FIELD_END}`;
323
413
  const pageFieldEnd = result.dataStream.length - 1;
@@ -330,7 +420,7 @@ function buildTableOfContentsBody(body, toc, resolvePageNumber, idFactory = gene
330
420
  wholeEntity: false,
331
421
  properties: {
332
422
  fieldType: "PAGEREF",
333
- instruction: `PAGEREF ${targetId} \\h`,
423
+ instruction: `PAGEREF ${targetId}${hyperlinks ? " \\h" : ""}`,
334
424
  cachedResult: String(pageNumber),
335
425
  sourceKind: "complex"
336
426
  }
@@ -338,11 +428,36 @@ function buildTableOfContentsBody(body, toc, resolvePageNumber, idFactory = gene
338
428
  }
339
429
  result.dataStream += "\r";
340
430
  cachedResult += `${visibleEntry}\r`;
341
- result.paragraphs.push(copyTocParagraph(oldEntryParagraphs, index, heading.level, result.dataStream.length - 1, usedParagraphIds, rightAlignPageNumbers ? options === null || options === void 0 ? void 0 : options.tabStopOffset : void 0, tabLeader, format));
431
+ const paragraph = copyTocParagraph(oldEntryParagraphs, index, heading.level, result.dataStream.length - 1, usedParagraphIds, {
432
+ tabStopOffset: rightAlignPageNumbers ? options === null || options === void 0 ? void 0 : options.tabStopOffset : void 0,
433
+ tabLeader: ((_toc$properties10 = toc.properties) === null || _toc$properties10 === void 0 ? void 0 : _toc$properties10.tabLeader) == null ? void 0 : tabLeader,
434
+ format,
435
+ styles: options === null || options === void 0 ? void 0 : options.styles,
436
+ refreshPageTab: rightAlignPageNumbers,
437
+ resetEntryParagraphFormatting: options === null || options === void 0 ? void 0 : options.resetEntryParagraphFormatting,
438
+ styleName: options === null || options === void 0 ? void 0 : options.entryStyleName,
439
+ sourceParagraph: oldParagraphsByTarget.get(heading.bookmarkId ?? heading.headingId) ?? oldParagraphsByTarget.get(heading.paragraph.paragraphId)
440
+ });
441
+ if (!heading.text && rightAlignPageNumbers && showEntryPageNumber) {
442
+ const tabs = resolveDocumentParagraphStyle(options === null || options === void 0 ? void 0 : options.documentStyle, paragraph.paragraphStyle, {
443
+ styles: options === null || options === void 0 ? void 0 : options.styles,
444
+ paragraphStyleId: paragraph.styleId
445
+ }).tabStops ?? [];
446
+ const pageTab = tabs.find((tab) => !tab.clear && tab.alignment === TabStopAlignment.END);
447
+ if (pageTab) paragraph.paragraphStyle = {
448
+ ...paragraph.paragraphStyle,
449
+ tabStops: tabs.map((tab) => tab.offset < pageTab.offset ? {
450
+ ...tab,
451
+ clear: true
452
+ } : tab)
453
+ };
454
+ }
455
+ formatEntryTab(paragraph, heading, toc.rangeId, titleTabOffsets, options);
456
+ result.paragraphs.push(paragraph);
342
457
  }
343
458
  result.dataStream += FIELD_END;
344
459
  ranges.push({
345
- startIndex: 0,
460
+ startIndex: fieldStart,
346
461
  endIndex: result.dataStream.length - 1,
347
462
  rangeId: toc.rangeId,
348
463
  rangeType: CustomRangeType.FIELD,
@@ -354,90 +469,349 @@ function buildTableOfContentsBody(body, toc, resolvePageNumber, idFactory = gene
354
469
  cachedResult
355
470
  }
356
471
  });
472
+ if (!isExistingToc) {
473
+ result.dataStream += "\r";
474
+ result.paragraphs.push(cloneParagraphWithId({
475
+ startIndex: result.dataStream.length - 1,
476
+ paragraphId: "",
477
+ paragraphStyle: { outlineLevel: 9 }
478
+ }, usedParagraphIds));
479
+ }
357
480
  ranges.sort((left, right) => left.startIndex - right.startIndex || right.endIndex - left.endIndex);
358
481
  return result;
359
482
  }
360
- function getExistingTableOfContentsTitle(body, paragraphs) {
361
- const titleParagraph = paragraphs.find((paragraph) => {
362
- var _paragraph$styleId2;
363
- return ((_paragraph$styleId2 = paragraph.styleId) === null || _paragraph$styleId2 === void 0 ? void 0 : _paragraph$styleId2.toLowerCase()) === "tocheading";
364
- });
483
+ function getTocStyleName(paragraph, styles) {
484
+ var _styles;
485
+ const styleId = (paragraph.styleId ?? "").replace(/\s+/g, "").toLowerCase();
486
+ return /^toc(?:[1-9]|heading)$/.test(styleId) ? styleId : ((styles === null || styles === void 0 || (_styles = styles[paragraph.styleId ?? ""]) === null || _styles === void 0 ? void 0 : _styles.name) ?? styleId).replace(/\s+/g, "").toLowerCase();
487
+ }
488
+ function getExistingTableOfContentsTitle(body, paragraphs, fieldStart, styles) {
489
+ const titleParagraph = paragraphs.find((paragraph) => getTocStyleName(paragraph, styles) === "tocheading");
365
490
  if (!titleParagraph) return "";
366
491
  const allParagraphs = [...body.paragraphs ?? []].sort((left, right) => left.startIndex - right.startIndex);
367
492
  const index = allParagraphs.findIndex((paragraph) => paragraph === titleParagraph || paragraph.paragraphId === titleParagraph.paragraphId);
368
493
  let start = index > 0 ? allParagraphs[index - 1].startIndex + 1 : 0;
494
+ start = Math.max(start, fieldStart + 1);
369
495
  while (body.dataStream[start] === FIELD_START || body.dataStream[start] === FIELD_END) start += 1;
370
496
  return getPlainText(body.dataStream.slice(start, titleParagraph.startIndex)).trim();
371
497
  }
372
- function countTableOfContentsHeadings(body, levels = 3) {
498
+ function countTableOfContentsHeadings(body, levels = 3, styles) {
373
499
  if (!body) return 0;
374
- return collectHeadings(body, void 0, 1, Math.min(9, Math.max(1, Math.trunc(levels)))).length;
500
+ return collectHeadings(body, void 0, 1, Math.min(9, Math.max(1, Math.trunc(levels))), styles).length;
375
501
  }
376
502
  function parseOutlineLevelRange(instruction) {
377
503
  const match = instruction.match(/\\o\s+"(\d+)\s*-\s*(\d+)"/i);
378
504
  const min = Math.max(1, Number((match === null || match === void 0 ? void 0 : match[1]) ?? 1));
379
505
  return [min, Math.min(9, Math.max(min, Number((match === null || match === void 0 ? void 0 : match[2]) ?? 3)))];
380
506
  }
381
- function collectHeadings(body, toc, minLevel, maxLevel) {
507
+ function resolveEntryHyperlinkFont(hyperlinks, options) {
508
+ var _options$documentStyl, _Object$entries$find;
509
+ if (!hyperlinks || !options.resetEntryParagraphFormatting || ((_options$documentStyl = options.documentStyle) === null || _options$documentStyl === void 0 ? void 0 : _options$documentStyl.documentFlavor) === DocumentFlavor.MODERN) return;
510
+ const { styles } = options;
511
+ const styleId = (_Object$entries$find = Object.entries(styles ?? {}).find(([id, style]) => style.type === DocStyleType.character && (style.name ?? id).toLowerCase() === "hyperlink")) === null || _Object$entries$find === void 0 ? void 0 : _Object$entries$find[0];
512
+ const style = resolveDocumentTextStyle(styles, styleId);
513
+ const font = Object.fromEntries([
514
+ "ff",
515
+ "eastAsiaFontFamily",
516
+ "eastAsiaFontTheme",
517
+ "fontHint"
518
+ ].filter((key) => style[key] !== void 0).map((key) => [key, style[key]]));
519
+ return Object.keys(font).length ? font : void 0;
520
+ }
521
+ function applyEntryHyperlinkFont(entry, font) {
522
+ if (!font) return entry;
523
+ const runs = [];
524
+ let start = 0;
525
+ for (const run of entry.textRuns ?? []) {
526
+ if (start < run.st) runs.push({
527
+ st: start,
528
+ ed: run.st,
529
+ ts: font
530
+ });
531
+ runs.push({
532
+ ...run,
533
+ ts: {
534
+ ...font,
535
+ ...run.ts
536
+ }
537
+ });
538
+ start = run.ed;
539
+ }
540
+ if (start < entry.text.length) runs.push({
541
+ st: start,
542
+ ed: entry.text.length,
543
+ ts: font
544
+ });
545
+ return {
546
+ ...entry,
547
+ textRuns: runs
548
+ };
549
+ }
550
+ function getTocTitleTabOffsets(options) {
551
+ if (!(options === null || options === void 0 ? void 0 : options.resetEntryParagraphFormatting) || !options.styles) return [];
552
+ const { styles, documentStyle } = options;
553
+ return Object.entries(styles).filter(([id, style]) => style.type === DocStyleType.paragraph && /^toc[1-9]$/.test((style.name ?? id).replace(/\s+/g, "").toLowerCase())).map(([paragraphStyleId]) => getNumberUnitValue(resolveDocumentParagraphStyle(documentStyle, void 0, {
554
+ styles,
555
+ paragraphStyleId
556
+ }).indentStart, 0)).filter((offset) => offset > 0).sort((left, right) => left - right);
557
+ }
558
+ function formatEntryTab(paragraph, heading, rangeId, titleTabOffsets, options) {
559
+ var _options$documentStyl2, _paragraph$paragraphS2, _heading$textRuns2, _options$documentStyl3, _options$documentStyl4, _heading$textRuns3, _options$documentStyl5;
560
+ const tabIndex = heading.text.indexOf(" ");
561
+ const prefix = heading.numberingText ?? ((options === null || options === void 0 ? void 0 : options.resetEntryParagraphFormatting) && tabIndex > 0 ? heading.text.slice(0, tabIndex) : void 0);
562
+ if (!prefix || (options === null || options === void 0 || (_options$documentStyl2 = options.documentStyle) === null || _options$documentStyl2 === void 0 ? void 0 : _options$documentStyl2.documentFlavor) === DocumentFlavor.MODERN) return;
563
+ if (heading.numberingText && (options === null || options === void 0 ? void 0 : options.resetEntryParagraphFormatting) && ((_paragraph$paragraphS2 = paragraph.paragraphStyle) === null || _paragraph$paragraphS2 === void 0 ? void 0 : _paragraph$paragraphS2.tabStops)) paragraph.paragraphStyle.tabStops = paragraph.paragraphStyle.tabStops.filter((tab) => !tab.clear && tab.alignment === TabStopAlignment.END);
564
+ const style = resolveDocumentParagraphStyle(options === null || options === void 0 ? void 0 : options.documentStyle, paragraph.paragraphStyle, {
565
+ styles: options === null || options === void 0 ? void 0 : options.styles,
566
+ paragraphStyleId: paragraph.styleId
567
+ });
568
+ const numberStyle = (_heading$textRuns2 = heading.textRuns) === null || _heading$textRuns2 === void 0 || (_heading$textRuns2 = _heading$textRuns2.find((run) => run.st === 0 && run.ed >= prefix.length)) === null || _heading$textRuns2 === void 0 ? void 0 : _heading$textRuns2.ts;
569
+ const textStyle = resolveDocumentDefaultFont({
570
+ ...style.textStyle,
571
+ ...numberStyle
572
+ }, options === null || options === void 0 ? void 0 : options.documentStyle, (options === null || options === void 0 ? void 0 : options.locale) ?? LocaleType.EN_US);
573
+ const font = getFontStyleString(textStyle, options === null || options === void 0 || (_options$documentStyl3 = options.documentStyle) === null || _options$documentStyl3 === void 0 ? void 0 : _options$documentStyl3.fontFamilyFallbacks, options === null || options === void 0 || (_options$documentStyl4 = options.documentStyle) === null || _options$documentStyl4 === void 0 ? void 0 : _options$documentStyl4.fontFamilyClasses);
574
+ const width = measureDocumentNoWrapTextWidth({
575
+ id: rangeId,
576
+ documentStyle: {
577
+ ...options === null || options === void 0 ? void 0 : options.documentStyle,
578
+ textStyle
579
+ },
580
+ body: {
581
+ dataStream: prefix,
582
+ textRuns: (_heading$textRuns3 = heading.textRuns) === null || _heading$textRuns3 === void 0 ? void 0 : _heading$textRuns3.filter((run) => run.st < prefix.length)
583
+ }
584
+ }, titleTabOffsets.length > 0);
585
+ const characterWidth = font.originFontSize * 4 / 3;
586
+ const first = getNumberUnitValue(style.indentFirstLine, characterWidth);
587
+ const indentStart = getNumberUnitValue(style.indentStart, characterWidth);
588
+ const hanging = first > 0 ? 0 : getNumberUnitValue(style.hanging, characterWidth);
589
+ const numberEnd = indentStart + Math.max(first, 0) - hanging + width;
590
+ const tabs = style.tabStops ?? [];
591
+ const nextTab = tabs.filter((tab) => !tab.clear && tab.offset > numberEnd).sort((left, right) => left.offset - right.offset)[0];
592
+ if (nextTab && (nextTab.alignment === TabStopAlignment.START || nextTab.alignment === TabStopAlignment.TAB_STOP_ALIGNMENT_UNSPECIFIED) && ((options === null || options === void 0 ? void 0 : options.availableWidth) == null || nextTab.offset < options.availableWidth)) {
593
+ var _paragraph$paragraphS3;
594
+ if ((_paragraph$paragraphS3 = paragraph.paragraphStyle) === null || _paragraph$paragraphS3 === void 0 ? void 0 : _paragraph$paragraphS3.tabStops) paragraph.paragraphStyle = {
595
+ ...paragraph.paragraphStyle,
596
+ tabStops: [...paragraph.paragraphStyle.tabStops].sort((left, right) => left.offset - right.offset)
597
+ };
598
+ return;
599
+ }
600
+ const useHangingStop = hanging > 0 && (options === null || options === void 0 || (_options$documentStyl5 = options.documentStyle) === null || _options$documentStyl5 === void 0 || (_options$documentStyl5 = _options$documentStyl5.compatibilityFlags) === null || _options$documentStyl5 === void 0 ? void 0 : _options$documentStyl5.noTabHangInd) !== BooleanNumber.TRUE && indentStart > numberEnd && indentStart < Math.min((nextTab === null || nextTab === void 0 ? void 0 : nextTab.offset) ?? 1e400, (options === null || options === void 0 ? void 0 : options.availableWidth) ?? 1e400);
601
+ const interval = 44 / 3;
602
+ const styleStop = titleTabOffsets.find((offset) => offset >= numberEnd + interval - 1e-6 && offset < Math.min((nextTab === null || nextTab === void 0 ? void 0 : nextTab.offset) ?? 1e400, (options === null || options === void 0 ? void 0 : options.availableWidth) ?? 1e400));
603
+ const offset = useHangingStop ? indentStart : styleStop ?? (Math.floor(numberEnd / interval + 1e-6) + 2) * 11 * 4 / 3;
604
+ paragraph.paragraphStyle = {
605
+ ...paragraph.paragraphStyle,
606
+ tabStops: [...tabs, {
607
+ offset,
608
+ alignment: TabStopAlignment.START,
609
+ leader: TabStopLeader.NONE
610
+ }].sort((left, right) => left.offset - right.offset)
611
+ };
612
+ }
613
+ function collectHeadings(body, toc, minLevel, maxLevel, styles, options) {
614
+ const snapshot = options && {
615
+ body,
616
+ styles,
617
+ documentStyle: options.documentStyle,
618
+ lists: {
619
+ ...PRESET_LIST_TYPE,
620
+ ...options.lists
621
+ },
622
+ tableSource: options.tableSource
623
+ };
624
+ const numbering = snapshot && resolveDocumentParagraphNumbering(snapshot);
382
625
  const paragraphs = [...body.paragraphs ?? []].sort((left, right) => left.startIndex - right.startIndex);
383
626
  let paragraphStart = 0;
384
627
  return paragraphs.flatMap((paragraph) => {
385
- var _paragraph$paragraphS2, _body$customRanges9, _bookmark$properties;
386
- let startOffset = paragraphStart;
387
- while (body.dataStream[startOffset] === FIELD_START || body.dataStream[startOffset] === FIELD_END) startOffset += 1;
628
+ var _paragraph$paragraphS4, _body$customRanges9, _numbering$get, _definition$nestingLe, _options$lists, _toc$properties11, _definition$nestingLe2, _bookmark$properties;
629
+ const startOffset = skipFieldMarkers(body.dataStream, paragraphStart);
388
630
  paragraphStart = paragraph.startIndex + 1;
389
- const level = getOutlineLevel(paragraph);
390
- const headingId = (_paragraph$paragraphS2 = paragraph.paragraphStyle) === null || _paragraph$paragraphS2 === void 0 ? void 0 : _paragraph$paragraphS2.headingId;
631
+ const level = getOutlineLevel(paragraph, styles);
632
+ const headingId = ((_paragraph$paragraphS4 = paragraph.paragraphStyle) === null || _paragraph$paragraphS4 === void 0 ? void 0 : _paragraph$paragraphS4.headingId) || paragraph.paragraphId;
391
633
  if (!headingId || level == null || level < minLevel || level > maxLevel || toc && startOffset >= toc.startIndex && paragraph.startIndex <= toc.endIndex) return [];
392
- const text = getPlainText(body.dataStream.slice(startOffset, paragraph.startIndex)).trim();
634
+ const characters = (body.customRanges ?? []).filter((range) => {
635
+ var _range$properties5, _range$properties6;
636
+ return range.rangeType === CustomRangeType.CUSTOM && range.wholeEntity === true && range.startIndex === range.endIndex && range.startIndex >= startOffset && range.endIndex < paragraph.startIndex && (((_range$properties5 = range.properties) === null || _range$properties5 === void 0 ? void 0 : _range$properties5.kind) === SpecialCharacterKind.NON_BREAKING_HYPHEN && body.dataStream[range.startIndex] === "‑" || ((_range$properties6 = range.properties) === null || _range$properties6 === void 0 ? void 0 : _range$properties6.kind) === SpecialCharacterKind.OPTIONAL_HYPHEN && body.dataStream[range.startIndex] === "­");
637
+ });
638
+ const optionalHyphens = new Set(characters.filter((range) => range.properties.kind === SpecialCharacterKind.OPTIONAL_HYPHEN).map((range) => range.startIndex));
639
+ const offsets = [];
640
+ let content = "";
641
+ for (let index = startOffset; index < paragraph.startIndex; index++) {
642
+ offsets[index - startOffset] = content.length;
643
+ if (!optionalHyphens.has(index)) content += getPlainText(body.dataStream[index]);
644
+ }
645
+ const leading = content.length - content.trimStart().length;
646
+ let text = content.trim();
393
647
  if (!text) return [];
394
648
  const bookmark = (_body$customRanges9 = body.customRanges) === null || _body$customRanges9 === void 0 ? void 0 : _body$customRanges9.find((range) => {
395
- var _range$properties5;
396
- return range.rangeType === CustomRangeType.BOOKMARK && range.startIndex <= paragraph.startIndex && range.endIndex >= startOffset && ((_range$properties5 = range.properties) === null || _range$properties5 === void 0 ? void 0 : _range$properties5.bookmarkId);
649
+ var _range$properties7;
650
+ return range.rangeType === CustomRangeType.BOOKMARK && range.startIndex <= paragraph.startIndex && range.endIndex >= startOffset && ((_range$properties7 = range.properties) === null || _range$properties7 === void 0 ? void 0 : _range$properties7.bookmarkId);
397
651
  });
652
+ const label = numbering === null || numbering === void 0 || (_numbering$get = numbering.get(paragraph.startIndex)) === null || _numbering$get === void 0 ? void 0 : _numbering$get.label;
653
+ const bullet = snapshot && resolveDocumentParagraphBullet(snapshot, paragraph);
654
+ const definition = bullet && (snapshot === null || snapshot === void 0 ? void 0 : snapshot.lists[bullet.listType]);
655
+ const followNumberWith = bullet && (definition === null || definition === void 0 || (_definition$nestingLe = definition.nestingLevel[bullet.nestingLevel]) === null || _definition$nestingLe === void 0 ? void 0 : _definition$nestingLe.followNumberWith);
656
+ const preset = bullet && (options === null || options === void 0 || (_options$lists = options.lists) === null || _options$lists === void 0 ? void 0 : _options$lists[bullet.listType]) == null && PRESET_LIST_TYPE[bullet.listType];
657
+ const separator = followNumberWith === 0 || followNumberWith == null && preset ? " " : " ";
658
+ const prefix = label ? label.replace(/[ \t]+$/, "") + separator : "";
659
+ if (label && !/\\w(?:\s|$)/i.test(String((toc === null || toc === void 0 || (_toc$properties11 = toc.properties) === null || _toc$properties11 === void 0 ? void 0 : _toc$properties11.instruction) ?? ""))) text = text.replace(/\t/g, " ");
660
+ const sourceStyle = resolveDocumentParagraphStyle(options === null || options === void 0 ? void 0 : options.documentStyle, paragraph.paragraphStyle, {
661
+ styles,
662
+ paragraphStyleId: paragraph.styleId
663
+ });
664
+ const listMarker = !preset && bullet ? definition === null || definition === void 0 || (_definition$nestingLe2 = definition.nestingLevel[bullet.nestingLevel]) === null || _definition$nestingLe2 === void 0 ? void 0 : _definition$nestingLe2.textStyle : void 0;
665
+ const markerStyle = {
666
+ ...sourceStyle.paragraphMarkTextStyle,
667
+ ...bullet === null || bullet === void 0 ? void 0 : bullet.textStyle,
668
+ ...listMarker
669
+ };
670
+ const inheritedStyle = sourceStyle.textStyle;
671
+ const numberFont = Object.fromEntries([
672
+ "ff",
673
+ "eastAsiaFontFamily",
674
+ "eastAsiaFontTheme",
675
+ "complexScriptFontFamily",
676
+ "fontHint",
677
+ "bl",
678
+ "it"
679
+ ].filter((key) => markerStyle[key] !== void 0 && (key === "bl" || key === "it" || markerStyle[key] !== (inheritedStyle === null || inheritedStyle === void 0 ? void 0 : inheritedStyle[key]))).map((key) => [key, markerStyle[key]]));
398
680
  return [{
399
681
  bookmarkId: bookmark === null || bookmark === void 0 || (_bookmark$properties = bookmark.properties) === null || _bookmark$properties === void 0 ? void 0 : _bookmark$properties.bookmarkId,
400
682
  headingId,
401
683
  level,
402
684
  paragraph,
403
685
  startOffset,
404
- text
686
+ text: `${prefix}${text}`,
687
+ numberingText: prefix && separator === " " ? prefix.slice(0, -1) : void 0,
688
+ textRuns: prefix && Object.keys(numberFont).length ? [{
689
+ st: 0,
690
+ ed: prefix.length - separator.length,
691
+ ts: numberFont
692
+ }] : void 0,
693
+ specialCharacters: characters.filter((range) => range.properties.kind === SpecialCharacterKind.NON_BREAKING_HYPHEN).map((range) => ({
694
+ ...range,
695
+ startIndex: prefix.length + offsets[range.startIndex - startOffset] - leading,
696
+ endIndex: prefix.length + offsets[range.endIndex - startOffset] - leading
697
+ }))
405
698
  }];
406
699
  });
407
700
  }
408
- function getOutlineLevel(paragraph) {
409
- var _paragraph$paragraphS3, _paragraph$paragraphS4;
410
- const outlineLevel = (_paragraph$paragraphS3 = paragraph.paragraphStyle) === null || _paragraph$paragraphS3 === void 0 ? void 0 : _paragraph$paragraphS3.outlineLevel;
411
- if (outlineLevel != null && outlineLevel >= 0 && outlineLevel <= 8) return outlineLevel + 1;
412
- const namedStyle = (_paragraph$paragraphS4 = paragraph.paragraphStyle) === null || _paragraph$paragraphS4 === void 0 ? void 0 : _paragraph$paragraphS4.namedStyleType;
701
+ function getOutlineLevel(paragraph, styles) {
702
+ const style = resolveDocumentParagraphStyle(void 0, paragraph.paragraphStyle, {
703
+ styles,
704
+ paragraphStyleId: paragraph.styleId
705
+ });
706
+ const outlineLevel = style.outlineLevel;
707
+ if (outlineLevel != null) return outlineLevel >= 0 && outlineLevel <= 8 ? outlineLevel + 1 : void 0;
708
+ const namedStyle = style.namedStyleType;
413
709
  if (namedStyle != null && namedStyle >= NamedStyleType.HEADING_1 && namedStyle <= NamedStyleType.HEADING_5) return namedStyle - NamedStyleType.HEADING_1 + 1;
414
710
  }
415
- function copyTocParagraph(oldParagraphs, index, level, startIndex, usedParagraphIds, tabStopOffset, tabLeader = "dots", format = "fromTemplate") {
416
- const source = oldParagraphs.find((paragraph) => {
417
- var _paragraph$styleId3;
418
- return ((_paragraph$styleId3 = paragraph.styleId) === null || _paragraph$styleId3 === void 0 || (_paragraph$styleId3 = _paragraph$styleId3.match(/TOC(\d+)/i)) === null || _paragraph$styleId3 === void 0 ? void 0 : _paragraph$styleId3[1]) === String(level);
419
- }) ?? oldParagraphs[Math.min(index, oldParagraphs.length - 1)];
711
+ function getTocParagraphsByTarget(body, toc, entries) {
712
+ const result = /* @__PURE__ */ new Map();
713
+ if (!entries.length) return result;
714
+ const paragraphs = body.paragraphs ?? [];
715
+ const ends = paragraphs.map((paragraph) => paragraph.startIndex);
716
+ const byEnd = new Map(entries.map((paragraph) => [paragraph.startIndex, paragraph]));
717
+ const bookmarks = new Map((body.customRanges ?? []).filter((range) => {
718
+ var _range$properties8;
719
+ return range.rangeType === CustomRangeType.BOOKMARK && ((_range$properties8 = range.properties) === null || _range$properties8 === void 0 ? void 0 : _range$properties8.bookmarkId);
720
+ }).map((range) => [String(range.properties.bookmarkId).toLowerCase(), range.startIndex]));
721
+ for (const range of body.customRanges ?? []) {
722
+ var _paragraphs$binSearch, _range$properties9, _range$properties10;
723
+ if (range.rangeType !== CustomRangeType.HYPERLINK || range.startIndex <= toc.startIndex || range.endIndex >= toc.endIndex) continue;
724
+ const source = byEnd.get((_paragraphs$binSearch = paragraphs[binSearchFirstGreaterThanTarget(ends, range.startIndex - 1)]) === null || _paragraphs$binSearch === void 0 ? void 0 : _paragraphs$binSearch.startIndex);
725
+ const targetId = ((_range$properties9 = range.properties) === null || _range$properties9 === void 0 ? void 0 : _range$properties9.bookmarkId) ?? ((_range$properties10 = range.properties) === null || _range$properties10 === void 0 ? void 0 : _range$properties10.headingId);
726
+ if (!source || !targetId) continue;
727
+ result.set(targetId, source);
728
+ const offset = bookmarks.get(targetId.toLowerCase());
729
+ if (offset != null) {
730
+ const target = paragraphs[binSearchFirstGreaterThanTarget(ends, offset - 1)];
731
+ if (target) {
732
+ var _target$paragraphStyl;
733
+ result.set(target.paragraphId, source);
734
+ if ((_target$paragraphStyl = target.paragraphStyle) === null || _target$paragraphStyl === void 0 ? void 0 : _target$paragraphStyl.headingId) result.set(target.paragraphStyle.headingId, source);
735
+ }
736
+ }
737
+ }
738
+ return result;
739
+ }
740
+ function copyTocParagraph(oldParagraphs, index, level, startIndex, usedParagraphIds, options = {}) {
741
+ var _source$paragraphStyl, _oldTabs$filter$pop;
742
+ const { tabStopOffset, tabLeader, format = "fromTemplate", styles, refreshPageTab = false, resetEntryParagraphFormatting = false } = options;
743
+ const styleName = options.styleName ?? `toc${level}`;
744
+ const byIndex = oldParagraphs[index];
745
+ const byStyleLevel = byIndex && getTocStyleName(byIndex, styles) === styleName ? byIndex : oldParagraphs.find((paragraph) => getTocStyleName(paragraph, styles) === styleName);
746
+ const source = (options.sourceParagraph && getTocStyleName(options.sourceParagraph, styles) === styleName ? options.sourceParagraph : void 0) ?? byStyleLevel ?? oldParagraphs[Math.min(index, oldParagraphs.length - 1)];
747
+ const defaultStyleId = styleName === "tableoffigures" ? "TableOfFigures" : `TOC${level}`;
748
+ const canonicalStyle = styles === null || styles === void 0 ? void 0 : styles[defaultStyleId];
749
+ const styleId = (canonicalStyle === null || canonicalStyle === void 0 ? void 0 : canonicalStyle.type) === DocStyleType.paragraph && (canonicalStyle.name ?? defaultStyleId).replace(/\s+/g, "").toLowerCase() === styleName ? defaultStyleId : Object.keys(styles ?? {}).find((id) => styles[id].type === DocStyleType.paragraph && (styles[id].name ?? id).replace(/\s+/g, "").toLowerCase() === styleName);
750
+ const replaceSourceStyle = !(source === null || source === void 0 ? void 0 : source.styleId) || getTocStyleName(source, styles) === "normal" || resetEntryParagraphFormatting && getTocStyleName(source, styles) !== styleName;
751
+ let paragraphStyleId = source === null || source === void 0 ? void 0 : source.styleId;
752
+ if (replaceSourceStyle) {
753
+ paragraphStyleId = styleId ?? paragraphStyleId;
754
+ if (resetEntryParagraphFormatting && styleId == null) paragraphStyleId = defaultStyleId;
755
+ }
756
+ const namedTabs = resolveDocumentParagraphStyle(void 0, void 0, {
757
+ styles,
758
+ paragraphStyleId
759
+ }).tabStops ?? [];
760
+ const oldTabs = (source === null || source === void 0 || (_source$paragraphStyl = source.paragraphStyle) === null || _source$paragraphStyl === void 0 ? void 0 : _source$paragraphStyl.tabStops) ?? [];
761
+ const namedPageTabs = namedTabs.filter((tab) => tab.alignment === TabStopAlignment.END);
762
+ const pageOffset = tabStopOffset ?? ((_oldTabs$filter$pop = oldTabs.filter((tab) => tab.alignment === TabStopAlignment.END).pop()) === null || _oldTabs$filter$pop === void 0 ? void 0 : _oldTabs$filter$pop.offset);
763
+ const pageTabs = namedPageTabs.map((tab) => ({
764
+ ...tab,
765
+ ...tabLeader == null ? {} : { leader: getTabStopLeader(tabLeader) }
766
+ }));
767
+ if (!pageTabs.length && pageOffset != null) pageTabs.push({
768
+ offset: pageOffset,
769
+ alignment: TabStopAlignment.END,
770
+ leader: getTabStopLeader(tabLeader ?? "dots")
771
+ });
772
+ const tabStops = refreshPageTab && pageTabs.length ? [...oldTabs.filter((tab) => tab.alignment !== TabStopAlignment.END), ...pageTabs] : void 0;
773
+ const fallbackIndent = resetEntryParagraphFormatting && format === "fromTemplate" && styleId == null && /^toc[1-9]$/.test(styleName) ? { indentStart: {
774
+ v: Math.max(0, level - 1) * 2,
775
+ u: NumberUnitType.CHARACTER
776
+ } } : {};
420
777
  if (source) {
421
778
  var _oldParagraphs$index;
779
+ let paragraphStyle = source.paragraphStyle;
780
+ if (resetEntryParagraphFormatting) {
781
+ const entryTabs = tabStops ?? oldTabs.filter((tab) => tab.alignment !== TabStopAlignment.END);
782
+ paragraphStyle = {
783
+ ...fallbackIndent,
784
+ ...entryTabs.length ? { tabStops: entryTabs } : {}
785
+ };
786
+ } else if (tabStops) paragraphStyle = {
787
+ ...paragraphStyle,
788
+ tabStops
789
+ };
422
790
  return cloneParagraphWithId({
423
791
  ...source,
792
+ ...resetEntryParagraphFormatting || tabStops ? { paragraphStyle } : {},
793
+ ...replaceSourceStyle ? { styleId: paragraphStyleId } : {},
424
794
  startIndex,
425
795
  paragraphId: ((_oldParagraphs$index = oldParagraphs[index]) === null || _oldParagraphs$index === void 0 ? void 0 : _oldParagraphs$index.paragraphId) ?? ""
426
796
  }, usedParagraphIds);
427
797
  }
798
+ let paragraphStyle = { indentStart: { v: Math.max(0, level - 1) * getFormatIndent(format) } };
799
+ if (format === "modern" || format === "classic") paragraphStyle.spaceBelow = { v: format === "modern" ? 4 : 2 };
800
+ if (tabStops) paragraphStyle.tabStops = tabStops;
801
+ else if (tabStopOffset != null) paragraphStyle.tabStops = [{
802
+ offset: tabStopOffset,
803
+ alignment: TabStopAlignment.END,
804
+ leader: getTabStopLeader(tabLeader ?? "dots")
805
+ }];
806
+ if (resetEntryParagraphFormatting) paragraphStyle = {
807
+ ...fallbackIndent,
808
+ ...(tabStops === null || tabStops === void 0 ? void 0 : tabStops.length) ? { tabStops } : {}
809
+ };
428
810
  return {
429
811
  startIndex,
430
812
  paragraphId: createParagraphId(usedParagraphIds),
431
- styleId: `TOC${level}`,
432
- paragraphStyle: {
433
- indentStart: { v: Math.max(0, level - 1) * getFormatIndent(format) },
434
- spaceBelow: format === "modern" ? { v: 4 } : format === "classic" ? { v: 2 } : void 0,
435
- tabStops: tabStopOffset == null ? void 0 : [{
436
- offset: tabStopOffset,
437
- alignment: TabStopAlignment.END,
438
- leader: getTabStopLeader(tabLeader)
439
- }]
440
- }
813
+ styleId: styleId ?? defaultStyleId,
814
+ paragraphStyle
441
815
  };
442
816
  }
443
817
  function normalizeTabLeader(value) {
@@ -465,7 +839,7 @@ function getFormatIndent(format) {
465
839
 
466
840
  // package.json
467
841
  var name = "@univerjs/docs-toc";
468
- var version = "1.5.2";
842
+ var version = "1.6.0";
469
843
 
470
844
  // src/config/config.ts
471
845
  /**
@@ -487,14 +861,14 @@ const DOCS_TOC_PLUGIN_CONFIG_KEY = "docs-toc.config";
487
861
  const configSymbol = Symbol(DOCS_TOC_PLUGIN_CONFIG_KEY);
488
862
  const defaultPluginConfig = {};
489
863
 
490
- // \0@oxc-project+runtime@0.157.0/helpers/esm/decorateParam.js
864
+ // \0@oxc-project+runtime@0.158.0/helpers/esm/decorateParam.js
491
865
  function __decorateParam(paramIndex, decorator) {
492
866
  return function(target, key) {
493
867
  decorator(target, key, paramIndex);
494
868
  };
495
869
  }
496
870
 
497
- // \0@oxc-project+runtime@0.157.0/helpers/esm/decorate.js
871
+ // \0@oxc-project+runtime@0.158.0/helpers/esm/decorate.js
498
872
  function __decorate(decorators, target, key, desc) {
499
873
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
500
874
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -502,7 +876,7 @@ function __decorate(decorators, target, key, desc) {
502
876
  return c > 3 && r && Object.defineProperty(target, key, r), r;
503
877
  }
504
878
 
505
- // \0@oxc-project+runtime@0.157.0/helpers/esm/typeof.js
879
+ // \0@oxc-project+runtime@0.158.0/helpers/esm/typeof.js
506
880
  function _typeof(o) {
507
881
  "@babel/helpers - typeof";
508
882
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -512,7 +886,7 @@ function _typeof(o) {
512
886
  }, _typeof(o);
513
887
  }
514
888
 
515
- // \0@oxc-project+runtime@0.157.0/helpers/esm/toPrimitive.js
889
+ // \0@oxc-project+runtime@0.158.0/helpers/esm/toPrimitive.js
516
890
  function toPrimitive(t, e) {
517
891
  if ("object" != _typeof(t) || !t) return t;
518
892
  var r;
@@ -524,13 +898,13 @@ function toPrimitive(t, e) {
524
898
  return ("string" === e ? String : Number)(t);
525
899
  }
526
900
 
527
- // \0@oxc-project+runtime@0.157.0/helpers/esm/toPropertyKey.js
901
+ // \0@oxc-project+runtime@0.158.0/helpers/esm/toPropertyKey.js
528
902
  function toPropertyKey(t) {
529
903
  var i = toPrimitive(t, "string");
530
904
  return "symbol" == _typeof(i) ? i : i + "";
531
905
  }
532
906
 
533
- // \0@oxc-project+runtime@0.157.0/helpers/esm/defineProperty.js
907
+ // \0@oxc-project+runtime@0.158.0/helpers/esm/defineProperty.js
534
908
  function _defineProperty(e, r, t) {
535
909
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
536
910
  value: t,