fix: don't add parenthesis to media query if already present (#14699)

pull/14698/head
Paolo Ricciuti 9 months ago committed by GitHub
parent 61a0da8a5f
commit 887ce6ab4b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -0,0 +1,5 @@
---
'svelte': patch
---
fix: don't add parenthesis to media query if already present

@ -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.
*
@ -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)

@ -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
@ -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: () => {}
};
};
});
}

@ -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)');
}
});

@ -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>
Loading…
Cancel
Save