UNPKG

2.5 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var tslib_1 = require("tslib");
4function noop() { }
5var MatchMedia = /** @class */ (function () {
6 function MatchMedia() {
7 this.isUsingMockMatchMedia = false;
8 }
9 MatchMedia.prototype.mock = function (media) {
10 if (media === void 0) { media = defaultMatcher; }
11 if (this.isUsingMockMatchMedia) {
12 throw new Error('You tried to mock window.matchMedia when it was already mocked.');
13 }
14 this.originalMatchMedia = window.matchMedia;
15 this.isUsingMockMatchMedia = true;
16 this.setMedia(media);
17 };
18 MatchMedia.prototype.restore = function () {
19 if (!this.isUsingMockMatchMedia) {
20 throw new Error('You tried to restore window.matchMedia when it was already restored.');
21 }
22 window.matchMedia = this.originalMatchMedia;
23 this.isUsingMockMatchMedia = false;
24 };
25 MatchMedia.prototype.isMocked = function () {
26 return this.isUsingMockMatchMedia;
27 };
28 MatchMedia.prototype.setMedia = function (media) {
29 if (media === void 0) { media = defaultMatcher; }
30 this.ensureMatchMediaIsMocked();
31 window.matchMedia = function (query) { return mediaQueryList(media(query)); };
32 };
33 MatchMedia.prototype.ensureMatchMediaIsMocked = function () {
34 if (!this.isUsingMockMatchMedia) {
35 throw new Error('You must call matchMedia.mock() before interacting with the mock matchMedia.');
36 }
37 };
38 return MatchMedia;
39}());
40exports.default = MatchMedia;
41function defaultMatcher() {
42 return {
43 media: '',
44 addListener: noop,
45 addEventListener: noop,
46 removeListener: noop,
47 removeEventListener: noop,
48 onchange: noop,
49 dispatchEvent: function () { return false; },
50 matches: false,
51 };
52}
53function mediaQueryList(values) {
54 // Explictly state a return type as TypeScript does not attempt to shrink the
55 // type when using Object spread. Without the explicit return type TypeScript
56 // exports a type that exposes the internals of `MediaQueryList` (which
57 // changed in TS 3.1.0).
58 // This ensures that this function can be used in projects that use any
59 // version of Typescript instead of only <3.1.0 or >= 3.1.0 depending on the
60 // version that this library was compiled using.
61 return tslib_1.__assign({}, defaultMatcher(), values);
62}
63exports.mediaQueryList = mediaQueryList;