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