Skip to content

Commit

Permalink
fix: refine attributeRegex (sveltejs#345)
Browse files Browse the repository at this point in the history
Fix attributeRegex so that it correctly matches attributes that are not enclosed in quotes.
fix sveltejs#344

---------

Co-authored-by: Simon Holthausen <simon.holthausen@vercel.com>
  • Loading branch information
Rolaka and dummdidumm authored Mar 22, 2023
1 parent a94563c commit 4ce3dd3
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
- (feat) support `requirePragma` and `insertPragma` options ([#350](https://github.com/sveltejs/prettier-plugin-svelte/issues/350))
- (feat) support `<svelte:document>`
- (feat) trim whitespace in `class` attributes ([#339](https://github.com/sveltejs/prettier-plugin-svelte/issues/339))
- (fix) handle script/style attributes without quotes ([#344](https://github.com/sveltejs/prettier-plugin-svelte/issues/344))

## 2.9.0

Expand Down
5 changes: 3 additions & 2 deletions src/lib/extractAttributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@ import { AttributeNode, TextNode } from '../print/nodes';

export function extractAttributes(html: string): AttributeNode[] {
const extractAttributesRegex = /<[a-z]+[\s\n]*([\s\S]*?)>/im;
const attributeRegex = /([^\s=]+)(?:=("|')([\s\S]*?)\2)?/gim;
const attributeRegex = /([^\s=]+)(?:=(?:(?:("|')([\s\S]*?)\2)|(?:(\S+?)(?:\s|>|$))))?/gim;

const [, attributesString] = html.match(extractAttributesRegex)!;

const attrs: AttributeNode[] = [];

let match: RegExpMatchArray | null;
while ((match = attributeRegex.exec(attributesString))) {
const [all, name, quotes, value] = match;
const [all, name, quotes, valueQuoted, valueUnquoted] = match;
const value = valueQuoted || valueUnquoted;
const attrStart = match.index!;

let valueNode: AttributeNode['value'];
Expand Down
13 changes: 13 additions & 0 deletions test/formatting/samples/attributes-without-quotes/input.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script lang="ts"context=module
></script>

<script lang=ts boolean></script>

<p class=foo>asd</p>
<div>
<script lang=ts>d</script>
</div>

<style lang="less
"></style>
16 changes: 16 additions & 0 deletions test/formatting/samples/attributes-without-quotes/output.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<script lang="ts" context="module"></script>

<script lang="ts" boolean></script>

<p class="foo">asd</p>
<div>
<script lang="ts">
d;
</script>
</div>

<style
lang="less
"
></style>

0 comments on commit 4ce3dd3

Please sign in to comment.