Commit 94b7dbad authored by David Sveningsson's avatar David Sveningsson
Browse files

feat(rules): add autofix support to `no-trailing-whitespace`

parent 72fc6cbe
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -10,6 +10,7 @@ exports[`docs/rules/no-trailing-whitespace.md inline validation: incorrect 1`] =
    "messages": [
      {
        "column": 19,
        "fix": [Function],
        "line": 1,
        "message": "Trailing whitespace",
        "offset": 18,
+9 −0
Original line number Diff line number Diff line
@@ -50,6 +50,15 @@ describe("rule no-trailing-whitespace", () => {
				["no-trailing-whitespace", "Trailing whitespace"],
			]);
		});

		it("should remove trailing whitespace but keep the newline", async () => {
			expect.assertions(1);
			const markup = /* RAW */ `<p>  ${newline}</p>`;
			const report = await htmlvalidate.validateString(markup);
			const [message] = report.results[0].messages;
			const result = await htmlvalidate.autofixString("inline", markup, message.fix!);
			expect(result).toBe(`<p>${newline}</p>`);
		});
	});

	it("smoketest", async () => {
+13 −2
Original line number Diff line number Diff line
@@ -2,6 +2,8 @@ import { type WhitespaceEvent } from "../event";
import { type RuleDocumentation, Rule, ruleDocumentationUrl } from "../rule";

export default class NoTrailingWhitespace extends Rule {
	public static override readonly fixable = true;

	public override documentation(): RuleDocumentation {
		return {
			description:
@@ -12,9 +14,18 @@ export default class NoTrailingWhitespace extends Rule {

	public setup(): void {
		this.on("whitespace", (event: WhitespaceEvent) => {
			if (/^[\t ]+\r?\n$/.test(event.text)) {
				this.report(null, "Trailing whitespace", event.location);
			const match = /^[\t ]+(\r?\n)$/.exec(event.text);
			if (!match) {
				return;
			}
			this.report({
				node: null,
				message: "Trailing whitespace",
				location: event.location,
				fix(fixer) {
					fixer.replaceText(event.location, match[1]);
				},
			});
		});
	}
}