Commit 41f332aa authored by David Sveningsson's avatar David Sveningsson
Browse files

Merge branch 'fix/close-order-optional-end' into 'master'

Skip omitted end tags

Closes #378

See merge request !1491
parents 2d8c0a3b 1f92180b
Loading
Loading
Loading
Loading
Loading
+33 −34
Changes for src/parser/parser.ts: 33 added lines, 34 removed lines.
Original line number Diff line number Diff line
@@ -92,6 +92,36 @@ function matchesParent(parent: HtmlElement, selector: string): boolean {
	return parent.meta ? matchesContentCategory(parent.meta, selector) : false;
}

/**
 * Returns `true` if the element’s parent is listed in its
 * `optionalEndExcludedParents`, i.e., its end tag must not be omitted.
 */
function hasExcludedParent(element: HtmlElement): boolean {
	const excluded = element.meta?.optionalEndExcludedParents;
	const { parent } = element;
	if (!excluded || !parent || parent.isRootElement()) {
		return false;
	}
	return excluded.some((entry) => matchesParent(parent, entry));
}

/**
 * Returns `true` if the element’s end tag may be omitted, either because
 * its `implicitClosed` list includes its own tag name (e.g. `<li>`, `<td>`)
 * or because `optionalEnd` is set, and the parent isn’t listed in
 * `optionalEndExcludedParents` (e.g. `<p>` as last child of `<a>`).
 *
 * @internal
 */
export function canOmitEndTag(element: HtmlElement): boolean {
	if (!element.meta) {
		return false;
	}
	const { implicitClosed, optionalEnd } = element.meta;
	const isOmittable = Boolean(implicitClosed?.includes(element.tagName)) || Boolean(optionalEnd);
	return isOmittable && !hasExcludedParent(element);
}

function isAttrValueToken(token?: Token): token is AttrValueToken {
	return token?.type === TokenType.ATTR_VALUE;
}
@@ -268,34 +298,6 @@ export class Parser {
		return this.closeOptionalEndTag(token, active);
	}

	/**
	 * Returns `true` if the element’s end tag may be omitted, either because
	 * its `implicitClosed` list includes its own tag name (e.g. `<li>`, `<td>`)
	 * or because `optionalEnd` is set, and the parent isn’t listed in
	 * `optionalEndExcludedParents` (e.g. `<p>` as last child of `<a>`).
	 */
	private canOmitEndTag(element: HtmlElement): boolean {
		if (!element.meta) {
			return false;
		}
		const { implicitClosed, optionalEnd } = element.meta;
		const isOmittable = Boolean(implicitClosed?.includes(element.tagName)) || Boolean(optionalEnd);
		return isOmittable && !this.hasExcludedParent(element);
	}

	/**
	 * Returns `true` if the element’s parent is listed in its
	 * `optionalEndExcludedParents`, i.e. its end tag must not be omitted.
	 */
	private hasExcludedParent(element: HtmlElement): boolean {
		const excluded = element.meta?.optionalEndExcludedParents;
		const { parent } = element;
		if (!excluded || !parent || parent.isRootElement()) {
			return false;
		}
		return excluded.some((entry) => matchesParent(parent, entry));
	}

	/**
	 * Check whether the active element can be implicitly closed by an incoming
	 * end tag. The end tag may close a direct parent or any ancestor, as long as
@@ -310,7 +312,7 @@ export class Parser {
			return false;
		}

		if (!this.canOmitEndTag(active)) {
		if (!canOmitEndTag(active)) {
			return false;
		}

@@ -319,7 +321,7 @@ export class Parser {
			if (ancestor.is(tagName)) {
				return true;
			}
			if (!this.canOmitEndTag(ancestor)) {
			if (!canOmitEndTag(ancestor)) {
				return false;
			}
			ancestor = ancestor.parent;
@@ -1073,10 +1075,7 @@ export class Parser {
		const documentElement = this.dom.root;
		let active = this.dom.getActive();
		while (!active.isRootElement()) {
			if (
				(active.meta?.implicitClosed || active.meta?.optionalEnd) &&
				!this.hasExcludedParent(active)
			) {
			if ((active.meta?.implicitClosed || active.meta?.optionalEnd) && !hasExcludedParent(active)) {
				active.closed = Node.CLOSED_IMPLICIT_CLOSED;
				this.closeElement(source, documentElement, active, location);
			} else {
+172
Changes for src/rules/close-order.spec.ts: 172 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -345,6 +345,178 @@ describe("rule close-order", () => {
		`);
	});

	it("should not report omitted `</html>` and `</body>` after misnested end tag", async () => {
		expect.assertions(2);
		const markup = /* RAW */ `
			<!DOCTYPE html>
			<html lang="en">
			<title>Test</title>
			<main>
			<div>
			</main>
		`;
		const report = await htmlvalidate.validateString(markup);
		expect(report).toBeInvalid();
		expect(report).toMatchInlineCodeframe(`
			"error: Unclosed element '<div>' (close-order)
			  4 | 			<title>Test</title>
			  5 | 			<main>
			> 6 | 			<div>
			    | 			 ^^^
			  7 | 			</main>
			  8 |
			Selector: html > body > main > div
			error: End tag '</main>' seen but there were open elements (close-order)
			  5 | 			<main>
			  6 | 			<div>
			> 7 | 			</main>
			    | 			 ^^^^^
			  8 |
			Selector: -"
		`);
	});

	it("should not report omitted `</body>` when `</html>` is misnested", async () => {
		expect.assertions(2);
		const markup = /* RAW */ `<html><body><div></html>`;
		const report = await htmlvalidate.validateString(markup);
		expect(report).toBeInvalid();
		expect(report).toMatchInlineCodeframe(`
			"error: Unclosed element '<div>' (close-order)
			> 1 | <html><body><div></html>
			    |              ^^^
			Selector: html > body > div
			error: End tag '</html>' seen but there were open elements (close-order)
			> 1 | <html><body><div></html>
			    |                   ^^^^^
			Selector: -"
		`);
	});

	it("should not report omitted `</caption>` when `</table>` is misnested", async () => {
		expect.assertions(2);
		const markup = /* RAW */ `<table><caption><span></table>`;
		const report = await htmlvalidate.validateString(markup);
		expect(report).toBeInvalid();
		expect(report).toMatchInlineCodeframe(`
			"error: Unclosed element '<span>' (close-order)
			> 1 | <table><caption><span></table>
			    |                  ^^^^
			Selector: table > caption > span
			error: End tag '</table>' seen but there were open elements (close-order)
			> 1 | <table><caption><span></table>
			    |                        ^^^^^^
			Selector: -"
		`);
	});

	it("should only report elements with required end tag at document end", async () => {
		expect.assertions(2);
		const markup = /* RAW */ `<html><body><main><div>`;
		const report = await htmlvalidate.validateString(markup);
		expect(report).toBeInvalid();
		expect(report).toMatchInlineCodeframe(`
			"error: Unclosed element '<main>' (close-order)
			> 1 | <html><body><main><div>
			    |              ^^^^
			Selector: html > body > main
			error: Unclosed element '<div>' (close-order)
			> 1 | <html><body><main><div>
			    |                    ^^^
			Selector: html > body > main > div"
		`);
	});

	it.each([
		["<ul><li><div></ul>", "div"],
		["<dl><dt><div></dl>", "div"],
		["<dl><dd><div></dl>", "div"],
		["<table><tr><td><span></table>", "span"],
		["<table><tr><th><span></table>", "span"],
		["<table><tbody><tr><span></table>", "span"],
		["<select><optgroup><b></select>", "b"],
		["<main><p><span></main>", "span"],
	])(
		"should not report ancestors with omitted end tag in %s",
		async (markup: string, unclosed: string) => {
			expect.assertions(1);
			const report = await htmlvalidate.validateString(markup);
			const messages = report.results.flatMap((result) =>
				result.messages.map((message) => message.message),
			);
			expect(messages.filter((message) => message.startsWith("Unclosed"))).toEqual([
				`Unclosed element '<${unclosed}>'`,
			]);
		},
	);

	it("should not report `<p>` with omitted end tag at document end", async () => {
		expect.assertions(2);
		const markup = /* RAW */ `<main><p><span>`;
		const report = await htmlvalidate.validateString(markup);
		expect(report).toBeInvalid();
		expect(report).toMatchInlineCodeframe(`
			"error: Unclosed element '<main>' (close-order)
			> 1 | <main><p><span>
			    |  ^^^^
			Selector: main
			error: Unclosed element '<span>' (close-order)
			> 1 | <main><p><span>
			    |           ^^^^
			Selector: main > p > span"
		`);
	});

	it("should report `<p>` when end tag is required by parent", async () => {
		expect.assertions(2);
		const markup = /* RAW */ `<a href="#"><p><span></a>`;
		const report = await htmlvalidate.validateString(markup);
		expect(report).toBeInvalid();
		expect(report).toMatchInlineCodeframe(`
			"error: Unclosed element '<p>' (close-order)
			> 1 | <a href="#"><p><span></a>
			    |              ^
			Selector: a > p
			error: Unclosed element '<span>' (close-order)
			> 1 | <a href="#"><p><span></a>
			    |                 ^^^^
			Selector: a > p > span
			error: End tag '</a>' seen but there were open elements (close-order)
			> 1 | <a href="#"><p><span></a>
			    |                       ^^
			Selector: -"
		`);
	});

	it("should report element with optional end tag in excluded parent", async () => {
		expect.assertions(2);
		const htmlvalidate = new HtmlValidate({
			root: true,
			elements: [
				"html5",
				{ "x-foo": { optionalEnd: true, optionalEndExcludedParents: ["x-bar"] } },
			],
			rules: { "close-order": "error" },
		});
		const markup = /* RAW */ `<x-bar><x-foo><div>`;
		const report = await htmlvalidate.validateString(markup);
		expect(report).toBeInvalid();
		expect(report).toMatchInlineCodeframe(`
			"error: Unclosed element '<x-bar>' (close-order)
			> 1 | <x-bar><x-foo><div>
			    |  ^^^^^
			Selector: x-bar
			error: Unclosed element '<x-foo>' (close-order)
			> 1 | <x-bar><x-foo><div>
			    |         ^^^^^
			Selector: x-bar > x-foo
			error: Unclosed element '<div>' (close-order)
			> 1 | <x-bar><x-foo><div>
			    |                ^^^
			Selector: x-bar > x-foo > div"
		`);
	});

	it("should report error when elements have wrong end tag (root)", async () => {
		expect.assertions(2);
		const markup = `
+3 −2
Changes for src/rules/close-order.ts: 3 added lines, 2 removed lines.
Original line number Diff line number Diff line
import { type DOMInternalID, type HtmlElement, Node } from "../dom";
import { type TagEndEvent } from "../event";
import { type Location } from "../location";
import { canOmitEndTag } from "../parser/parser";
import { type RuleDocumentation, Rule, ruleDocumentationUrl } from "../rule";

/**
@@ -64,7 +65,7 @@ export default class CloseOrder extends Rule {

			const active = event.previous; // The current active element (that is, the current element on the stack)
			for (const ancestor of ancestors(active)) {
				if (ancestor.isRootElement() || reported.has(ancestor.unique)) {
				if (ancestor.isRootElement() || reported.has(ancestor.unique) || canOmitEndTag(ancestor)) {
					continue;
				}
				this.report({
@@ -128,7 +129,7 @@ export default class CloseOrder extends Rule {
					if (ancestor.isSameNode(element)) {
						break;
					}
					if (reported.has(element.unique)) {
					if (reported.has(element.unique) || canOmitEndTag(element)) {
						continue;
					}
					this.report({