|
| 1 | +import * as htmlLangService from 'vscode-html-languageservice'; |
| 2 | + |
| 3 | +const service = htmlLangService.getLanguageService(); |
| 4 | +export const HTML_MODES = { |
| 5 | + HTML: "html", |
| 6 | + XHTML: "xhtml", |
| 7 | + HTM: "htm", |
| 8 | + PHP: "php", |
| 9 | +}; |
| 10 | + |
| 11 | +function getTextDocument(text, languageID, filePath = "file:///placeholder.html") { |
| 12 | + return htmlLangService.TextDocument.create(filePath, languageID, 1, text); |
| 13 | +} |
| 14 | + |
| 15 | +// Properly setup DocumentContext with resolveReference function |
| 16 | +function getLocalLinkDocumentContext() { |
| 17 | + return { |
| 18 | + resolveReference: (ref) => { // the second argument base is unused, base is the textDocument url |
| 19 | + // we return the links as i, won't resolve relative to the text document base |
| 20 | + return ref; |
| 21 | + } |
| 22 | + }; |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * Given a text, returns all links in the file as an array of strings |
| 27 | + * @param {string} text |
| 28 | + * @param {string} htmlMode |
| 29 | + * @param {string} filePath - the path will be used to figure out relative urls. |
| 30 | + * @return {Array[string]} all file links in the file as an array of strings |
| 31 | + */ |
| 32 | +export function getAllDocumentLinks(text, htmlMode, filePath) { |
| 33 | + const textDocument = getTextDocument(text, htmlMode, filePath); |
| 34 | + const documentContext = getLocalLinkDocumentContext(); // textDocument.uri |
| 35 | + const documentLinks = service.findDocumentLinks(textDocument, documentContext); |
| 36 | + const linksArray = []; |
| 37 | + for(let link of documentLinks){ |
| 38 | + if(link.target){ |
| 39 | + linksArray.push(link.target); |
| 40 | + } |
| 41 | + } |
| 42 | + return linksArray; |
| 43 | +} |
0 commit comments