Skip to content

Commit 887ce6a

Browse files
fix: don't add parenthesis to media query if already present (#14699)
1 parent 61a0da8 commit 887ce6a

File tree

5 files changed

+27
-3
lines changed

5 files changed

+27
-3
lines changed

.changeset/cold-cows-enjoy.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': patch
3+
---
4+
5+
fix: don't add parenthesis to media query if already present

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

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { on } from '../events/index.js';
22
import { ReactiveValue } from './reactive-value.js';
33

4+
const parenthesis_regex = /\(.+\)/;
5+
46
/**
57
* Creates a media query and provides a `current` property that reflects whether or not it matches.
68
*
@@ -25,7 +27,8 @@ export class MediaQuery extends ReactiveValue {
2527
* @param {boolean} [fallback] Fallback value for the server
2628
*/
2729
constructor(query, fallback) {
28-
const q = window.matchMedia(`(${query})`);
30+
let final_query = parenthesis_regex.test(query) ? query : `(${query})`;
31+
const q = window.matchMedia(final_query);
2932
super(
3033
() => q.matches,
3134
(update) => on(q, 'change', update)

packages/svelte/tests/helpers.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import * as fs from 'node:fs';
33
import * as path from 'node:path';
44
import glob from 'tiny-glob/sync.js';
55
import { VERSION, compile, compileModule, preprocess } from 'svelte/compiler';
6+
import { vi } from 'vitest';
67

78
/**
89
* @param {string} file
@@ -176,12 +177,12 @@ export function write(file, contents) {
176177
// Guard because not all test contexts load this with JSDOM
177178
if (typeof window !== 'undefined') {
178179
// @ts-expect-error JS DOM doesn't support it
179-
Window.prototype.matchMedia = (media) => {
180+
Window.prototype.matchMedia = vi.fn((media) => {
180181
return {
181182
matches: false,
182183
media,
183184
addEventListener: () => {},
184185
removeEventListener: () => {}
185186
};
186-
};
187+
});
187188
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { expect } from 'vitest';
2+
import { test } from '../../test';
3+
4+
export default test({
5+
async test({ window }) {
6+
expect(window.matchMedia).toHaveBeenCalledWith('(max-width: 599px), (min-width: 900px)');
7+
expect(window.matchMedia).toHaveBeenCalledWith('(min-width: 900px)');
8+
}
9+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<script>
2+
import { MediaQuery } from "svelte/reactivity"
3+
4+
const mq = new MediaQuery("(max-width: 599px), (min-width: 900px)");
5+
const mq2 = new MediaQuery("min-width: 900px");
6+
</script>

0 commit comments

Comments
 (0)