Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 5 additions & 0 deletions .changeset/sweet-islands-sell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: avoid auto-parenthesis for special-keywords-only `MediaQuery`
19 changes: 18 additions & 1 deletion packages/svelte/src/reactivity/media-query.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,19 @@

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

// this keyworks are valid media queries but they need to be without parenthesis
//
// eg: new MediaQuery('screen')
//
// however because of the auto-parenthesis logic in the constructor since there's no parentehesis
// in the media query they'll be surrounded by parentehesis
//
// however we can check if the media query is only composed of these keywords
// and skip the auto-parenthesis
//
// https://github.com/sveltejs/svelte/issues/15930
const non_parenthesized_keywords = new Set(['all', 'print', 'screen', 'and', 'or', 'not', 'only']);

/**
* Creates a media query and provides a `current` property that reflects whether or not it matches.
*
Expand All @@ -27,7 +40,11 @@
* @param {boolean} [fallback] Fallback value for the server
*/
constructor(query, fallback) {
let final_query = parenthesis_regex.test(query) ? query : `(${query})`;
let final_query =
parenthesis_regex.test(query) ||
query.split(' ').every((keyword) => non_parenthesized_keywords.has(keyword))
? query
: `(${query})`;
const q = window.matchMedia(final_query);
super(
() => q.matches,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@ export default test({
async test({ window }) {
expect(window.matchMedia).toHaveBeenCalledWith('(max-width: 599px), (min-width: 900px)');
expect(window.matchMedia).toHaveBeenCalledWith('(min-width: 900px)');
expect(window.matchMedia).toHaveBeenCalledWith('screen');
expect(window.matchMedia).toHaveBeenCalledWith('not print');
}
});
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@

const mq = new MediaQuery("(max-width: 599px), (min-width: 900px)");
const mq2 = new MediaQuery("min-width: 900px");
const mq3 = new MediaQuery("screen");
const mq4 = new MediaQuery("not print");
</script>