From 67142b61cdbdaca99effb4f18e86b56bcb07c57e Mon Sep 17 00:00:00 2001 From: Michael Williamson Date: Sun, 1 Aug 2021 17:11:32 +0100 Subject: Handle internal hyperlinks created with complex fields --- lib/docx/body-reader.js | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) (limited to 'lib') diff --git a/lib/docx/body-reader.js b/lib/docx/body-reader.js index 90c2b39..0d04ccd 100644 --- a/lib/docx/body-reader.js +++ b/lib/docx/body-reader.js @@ -139,28 +139,33 @@ function BodyReader(options) { } else if (type === "end") { complexFieldStack.pop(); } else if (type === "separate") { - var href = parseHyperlinkFieldCode(currentInstrText.join('')); - var complexField = href === null ? unknownComplexField : {type: "hyperlink", href: href}; + var hyperlinkOptions = parseHyperlinkFieldCode(currentInstrText.join('')); + var complexField = hyperlinkOptions === null ? unknownComplexField : {type: "hyperlink", options: hyperlinkOptions}; complexFieldStack.pop(); complexFieldStack.push(complexField); } return emptyResult(); } - function currentHyperlinkHref() { + function currentHyperlinkOptions() { var topHyperlink = _.last(complexFieldStack.filter(function(complexField) { return complexField.type === "hyperlink"; })); - return topHyperlink ? topHyperlink.href : null; + return topHyperlink ? topHyperlink.options : null; } function parseHyperlinkFieldCode(code) { - var result = /\s*HYPERLINK "(.*)"/.exec(code); - if (result) { - return result[1]; - } else { - return null; + var externalLinkResult = /\s*HYPERLINK "(.*)"/.exec(code); + if (externalLinkResult) { + return {href: externalLinkResult[1]}; + } + + var internalLinkResult = /\s*HYPERLINK\s+\\l\s+"(.*)"/.exec(code); + if (internalLinkResult) { + return {anchor: internalLinkResult[1]}; } + + return null; } function readInstrText(element) { @@ -236,9 +241,9 @@ function BodyReader(options) { var properties = _.find(children, isRunProperties); children = children.filter(negate(isRunProperties)); - var hyperlinkHref = currentHyperlinkHref(); - if (hyperlinkHref !== null) { - children = [new documents.Hyperlink(children, {href: hyperlinkHref})]; + var hyperlinkOptions = currentHyperlinkOptions(); + if (hyperlinkOptions !== null) { + children = [new documents.Hyperlink(children, hyperlinkOptions)]; } return new documents.Run(children, properties); -- cgit v1.2.3