summaryrefslogtreecommitdiff
path: root/packages/webapi/src/lib/MediaQueryList.ts
blob: cc913718333054afd005f66579c3240cb1989316 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import * as _ from './utils'

export class MediaQueryList extends EventTarget {
	get matches(): boolean {
		return _.internalsOf(this, 'MediaQueryList', 'matches').matches
	}

	get media(): string {
		return _.internalsOf(this, 'MediaQueryList', 'media').media
	}
}

_.allowStringTag(MediaQueryList)

export const initMediaQueryList = (target: Target, exclude: Set<string>) => {
	if (exclude.has('MediaQueryList') || exclude.has('matchMedia')) return

	const EventTarget = target.EventTarget || globalThis.EventTarget
	const MediaQueryList = target.MediaQueryList || globalThis.MediaQueryList

	target.matchMedia = function matchMedia(media: string) {
		const mql = Object.setPrototypeOf(
			new EventTarget(),
			MediaQueryList.prototype
		) as MediaQueryList

		_.INTERNALS.set(mql, {
			matches: false,
			media,
		})

		return mql
	}
}

interface Target extends Record<any, any> {
	matchMedia: {
		(media: string): MediaQueryList
	}
}