Skip to content

Commit

Permalink
fix: don't add parenthesis to media query if already present (#14699)
Browse files Browse the repository at this point in the history
  • Loading branch information
paoloricciuti authored Dec 12, 2024
1 parent 61a0da8 commit 887ce6a
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/cold-cows-enjoy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'svelte': patch
---

fix: don't add parenthesis to media query if already present
5 changes: 4 additions & 1 deletion packages/svelte/src/reactivity/media-query.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { on } from '../events/index.js';
import { ReactiveValue } from './reactive-value.js';

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

/**
* Creates a media query and provides a `current` property that reflects whether or not it matches.
*
Expand All @@ -25,7 +27,8 @@ export class MediaQuery extends ReactiveValue {
* @param {boolean} [fallback] Fallback value for the server
*/
constructor(query, fallback) {
const q = window.matchMedia(`(${query})`);
let final_query = parenthesis_regex.test(query) ? query : `(${query})`;
const q = window.matchMedia(final_query);
super(
() => q.matches,
(update) => on(q, 'change', update)
Expand Down
5 changes: 3 additions & 2 deletions packages/svelte/tests/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import glob from 'tiny-glob/sync.js';
import { VERSION, compile, compileModule, preprocess } from 'svelte/compiler';
import { vi } from 'vitest';

/**
* @param {string} file
Expand Down Expand Up @@ -176,12 +177,12 @@ export function write(file, contents) {
// Guard because not all test contexts load this with JSDOM
if (typeof window !== 'undefined') {
// @ts-expect-error JS DOM doesn't support it
Window.prototype.matchMedia = (media) => {
Window.prototype.matchMedia = vi.fn((media) => {
return {
matches: false,
media,
addEventListener: () => {},
removeEventListener: () => {}
};
};
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { expect } from 'vitest';
import { test } from '../../test';

export default test({
async test({ window }) {
expect(window.matchMedia).toHaveBeenCalledWith('(max-width: 599px), (min-width: 900px)');
expect(window.matchMedia).toHaveBeenCalledWith('(min-width: 900px)');
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<script>
import { MediaQuery } from "svelte/reactivity"
const mq = new MediaQuery("(max-width: 599px), (min-width: 900px)");
const mq2 = new MediaQuery("min-width: 900px");
</script>

0 comments on commit 887ce6a

Please sign in to comment.