Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions packages/language-server/src/lib/documents/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,46 @@ const parser = getLanguageService();
* Parses text as HTML
*/
export function parseHtml(text: string): HTMLDocument {
const html = parseHTMLDocument(text);
return tryParse(text, html, 0) || html;
}

/**
* Tries to parse the HTML document and work around the limitations of the underlying
* parsers which will trip up when there's a non-closed tag and treat everything afterwards as its child.
*/
function tryParse(text: string, html: HTMLDocument, run: number): HTMLDocument | null {
if (run > 5) {
// Stop before doing too much work, possibly having an endless loop
return null;
}

let sanitizedText = text;
html.roots.forEach((node) => {
if (
!(<any>node).closed &&
// This indicates a child tag falsely identified as an attribute
Object.keys(node.attributes || {}).some((key) => key.startsWith('<')) &&
node.tag
) {
// Replace <some-unclosed-tag with whitespaces of same length
sanitizedText = replaceRangeWithStr(
sanitizedText,
node.start,
node.start + node.tag.length + 1,
' '.repeat(node.tag.length + 1),
);
}
});

if (sanitizedText !== text) {
return tryParse(sanitizedText, parseHTMLDocument(sanitizedText), run + 1);
} else {
return html;
}
}

function parseHTMLDocument(text: string) {
// We can safely only set getText because only this is used for parsing
return parser.parseHTMLDocument(<any>{ getText: () => text });
}
Expand Down Expand Up @@ -332,3 +372,12 @@ export function getWordAt(

return str.slice(left, right + pos);
}

export function replaceRangeWithStr(
text: string,
start: number,
end: number,
replacement: string,
): string {
return text.substring(0, start) + replacement + text.substring(end);
}
15 changes: 15 additions & 0 deletions packages/language-server/test/lib/documents/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,21 @@ describe('document/utils', () => {
container: { start: 151, end: 181 },
});
});

it('extract script when unclosed tag preceeding', () => {
const text = `
<Unclosed-Tag
<script>let value = 2</script>`;
assert.deepStrictEqual(extractScriptTags(text)?.script, {
content: 'let value = 2',
attributes: {},
start: 43,
end: 56,
startPos: Position.create(2, 18),
endPos: Position.create(2, 31),
container: { start: 35, end: 65 },
});
});
});

describe('#getLineAtPosition', () => {
Expand Down