align.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import type { DocxBlockKey } from "#office/contract.ts";
  2. const squash = (text: string) => text.replace(/\s+/g, "").toLowerCase();
  3. /**
  4. * Map rendered docx elements (paragraphs and top-level tables, in document order) to the server's
  5. * block list by text. A paragraph split across pages renders as several elements; they all map to
  6. * the same block. Elements that cannot be matched within a small look-ahead stay unmapped.
  7. */
  8. export function alignBlocks(
  9. elements: { text: string; table: boolean }[],
  10. blocks: DocxBlockKey[],
  11. ): (string | null)[] {
  12. const keys = blocks.map((block) => ({
  13. at: block.at,
  14. table: block.at.startsWith("t:"),
  15. text: squash(block.text),
  16. }));
  17. const result: (string | null)[] = [];
  18. let j = 0;
  19. let consumed = 0; // characters of keys[j].text already matched by earlier fragments
  20. const LOOKAHEAD = 6;
  21. for (const element of elements) {
  22. const text = squash(element.text);
  23. let matched: number | null = null;
  24. if (j < keys.length && consumed > 0) {
  25. // Continuation of a paragraph split across pages.
  26. const rest = keys[j].text.slice(consumed);
  27. if (text && !element.table && rest.startsWith(text)) {
  28. consumed += text.length;
  29. result.push(keys[j].at);
  30. if (consumed >= keys[j].text.length) {
  31. j++;
  32. consumed = 0;
  33. }
  34. continue;
  35. }
  36. j++;
  37. consumed = 0;
  38. }
  39. for (let k = j; k < Math.min(keys.length, j + LOOKAHEAD); k++) {
  40. const key = keys[k];
  41. if (key.table !== element.table) continue;
  42. // Server text is clipped to 400 characters; compare on the shared prefix.
  43. const probe = text.slice(0, key.text.length);
  44. if (
  45. key.text === text ||
  46. (text && key.text.startsWith(text)) ||
  47. (key.text.length >= 300 && probe === key.text)
  48. ) {
  49. matched = k;
  50. break;
  51. }
  52. if (!text && !key.text) {
  53. matched = k;
  54. break;
  55. }
  56. }
  57. if (matched === null) {
  58. result.push(null);
  59. continue;
  60. }
  61. result.push(keys[matched].at);
  62. const key = keys[matched];
  63. if (
  64. text &&
  65. !element.table &&
  66. text.length < key.text.length &&
  67. key.text.startsWith(text) &&
  68. key.text.length < 400
  69. ) {
  70. j = matched;
  71. consumed = text.length;
  72. } else {
  73. j = matched + 1;
  74. consumed = 0;
  75. }
  76. }
  77. return result;
  78. }