Skip to content

Commit 65668c0

Browse files
committed
fix: avoid auto-parenthesis for special keywords only MediaQuery
1 parent a5a0b49 commit 65668c0

File tree

4 files changed

+27
-1
lines changed

4 files changed

+27
-1
lines changed

.changeset/sweet-islands-sell.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': patch
3+
---
4+
5+
fix: avoid auto-parenthesis for special keywords only `MediaQuery`

packages/svelte/src/reactivity/media-query.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,19 @@ import { ReactiveValue } from './reactive-value.js';
33

44
const parenthesis_regex = /\(.+\)/;
55

6+
// this keyworks are valid media queries but they need to be without parenthesis
7+
//
8+
// eg: new MediaQuery('screen')
9+
//
10+
// however because of the auto-parenthesis logic in the constructor since there's no parentehesis
11+
// in the media query they'll be surrounded by parentehesis
12+
//
13+
// however we can check if the media query is only composed of these keywords
14+
// and skip the auto-parenthesis
15+
//
16+
// https://github.com/sveltejs/svelte/issues/15930
17+
const non_parenthesized_keywords = new Set(['all', 'print', 'screen', 'and', 'or', 'not', 'only']);
18+
619
/**
720
* Creates a media query and provides a `current` property that reflects whether or not it matches.
821
*
@@ -27,7 +40,11 @@ export class MediaQuery extends ReactiveValue {
2740
* @param {boolean} [fallback] Fallback value for the server
2841
*/
2942
constructor(query, fallback) {
30-
let final_query = parenthesis_regex.test(query) ? query : `(${query})`;
43+
let final_query =
44+
parenthesis_regex.test(query) ||
45+
query.split(' ').every((keyword) => non_parenthesized_keywords.has(keyword))
46+
? query
47+
: `(${query})`;
3148
const q = window.matchMedia(final_query);
3249
super(
3350
() => q.matches,

packages/svelte/tests/runtime-runes/samples/media-query/_config.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,7 @@ export default test({
55
async test({ window }) {
66
expect(window.matchMedia).toHaveBeenCalledWith('(max-width: 599px), (min-width: 900px)');
77
expect(window.matchMedia).toHaveBeenCalledWith('(min-width: 900px)');
8+
expect(window.matchMedia).toHaveBeenCalledWith('screen');
9+
expect(window.matchMedia).toHaveBeenCalledWith('not print');
810
}
911
});

packages/svelte/tests/runtime-runes/samples/media-query/main.svelte

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,6 @@
33
44
const mq = new MediaQuery("(max-width: 599px), (min-width: 900px)");
55
const mq2 = new MediaQuery("min-width: 900px");
6+
const mq3 = new MediaQuery("screen");
7+
const mq4 = new MediaQuery("not print");
68
</script>

0 commit comments

Comments
 (0)