40 |
41 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Nathan Reyes
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6 |
7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 |
9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10 |
--------------------------------------------------------------------------------
/src/use/mediaQuery.ts:
--------------------------------------------------------------------------------
1 | import { ref, onMounted, onUnmounted } from 'vue';
2 | import { windowHasFeature } from '../utils/window';
3 |
4 | export type MediaQueryCallback = (ev?: MediaQueryListEvent) => void;
5 |
6 | export function useMediaQuery(query: string, callback: MediaQueryCallback) {
7 | let mediaQuery: MediaQueryList | undefined;
8 | const matches = ref(false);
9 |
10 | function listener(ev: MediaQueryListEvent) {
11 | if (callback) callback(ev);
12 | matches.value = ev.matches;
13 | }
14 |
15 | function cleanup() {
16 | if (mediaQuery) {
17 | mediaQuery.removeEventListener('change', listener);
18 | mediaQuery = undefined;
19 | }
20 | }
21 |
22 | function setup(newQuery = query) {
23 | cleanup();
24 | if (windowHasFeature('matchMedia') && newQuery) {
25 | mediaQuery = window.matchMedia(newQuery);
26 | mediaQuery.addEventListener('change', listener);
27 | matches.value = mediaQuery.matches;
28 | }
29 | }
30 |
31 | onMounted(() => setup());
32 |
33 | onUnmounted(() => cleanup());
34 |
35 | return { matches, setup, cleanup };
36 | }
37 |
--------------------------------------------------------------------------------
/demo/src/components/MediaQuery.vue:
--------------------------------------------------------------------------------
1 |
13 |
14 |
15 |
Media Query
16 |
High-DPI: {{ isHighDPI.matches }}
17 |
Tablet: {{ isTablet.matches }}
18 |
19 |
20 |
21 |
41 |
--------------------------------------------------------------------------------
/demo/src/App.vue:
--------------------------------------------------------------------------------
1 |
12 |
13 |
14 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
46 |
--------------------------------------------------------------------------------
/src/use/resizeObserver.ts:
--------------------------------------------------------------------------------
1 | import { ref, watch, onUnmounted } from 'vue';
2 | import type { Ref, ComponentPublicInstance } from 'vue';
3 | import { windowHasFeature } from '../utils/window';
4 |
5 | export type ResizeObserverCallback = (entries: ReadonlyArray, observer: ResizeObserver) => void;
6 | export interface ResizeObserverOptions {
7 | box?: 'content-box' | 'border-box';
8 | }
9 |
10 | export function useResizeObserver(
11 | target: Ref,
12 | callback?: ResizeObserverCallback,
13 | options: ResizeObserverOptions = {}
14 | ) {
15 | let observer: ResizeObserver | undefined;
16 | const rect = ref();
17 |
18 | const listener: ResizeObserverCallback = (...args) => {
19 | if (callback) callback(...args);
20 | const entry = args[0][0];
21 | rect.value = entry.contentRect;
22 | };
23 |
24 | const stopObserver = () => {
25 | if (observer) {
26 | observer.disconnect();
27 | observer = undefined;
28 | }
29 | };
30 |
31 | const stopWatch = watch(
32 | () => target.value,
33 | (elOrComp) => {
34 | stopObserver();
35 | if (windowHasFeature('ResizeObserver') && elOrComp) {
36 | observer = new ResizeObserver(listener);
37 | observer.observe((elOrComp as ComponentPublicInstance).$el ?? elOrComp, options);
38 | }
39 | },
40 | { immediate: true, flush: 'post' }
41 | );
42 |
43 | const cleanup = () => {
44 | stopObserver();
45 | stopWatch();
46 | };
47 |
48 | onUnmounted(() => cleanup());
49 |
50 | return { rect, cleanup };
51 | }
52 |
--------------------------------------------------------------------------------
/src/utils/normalizeScreens.ts:
--------------------------------------------------------------------------------
1 | export interface NormalizedScreenValue {
2 | min: string;
3 | max: string | undefined;
4 | raw?: string | undefined;
5 | }
6 |
7 | export interface NormalizedScreen {
8 | name: string;
9 | values: NormalizedScreenValue[];
10 | }
11 |
12 | function resolveValue({ 'min-width': _minWidth, min = _minWidth, max, raw }: any = {}): NormalizedScreenValue {
13 | return { min, max, raw };
14 | }
15 |
16 | /**
17 | * A function that normalizes the various forms that the screens object can be
18 | * provided in.
19 | *
20 | * Input(s):
21 | * - ['100px', '200px'] // Raw strings
22 | * - { sm: '100px', md: '200px' } // Object with string values
23 | * - { sm: { min: '100px' }, md: { max: '100px' } } // Object with object values
24 | * - { sm: [{ min: '100px' }, { max: '200px' }] } // Object with object array (multiple values)
25 | *
26 | * Output(s):
27 | * - [{ name: 'sm', values: [{ min: '100px', max: '200px' }] }] // List of objects, that contains multiple values
28 | */
29 | export function normalizeScreens(screens: any, root = true): NormalizedScreen[] {
30 | if (Array.isArray(screens)) {
31 | return screens.map((screen) => {
32 | if (root && Array.isArray(screen)) {
33 | throw new Error('The tuple syntax is not supported for `screens`.');
34 | }
35 |
36 | if (typeof screen === 'string') {
37 | return { name: screen.toString(), values: [{ min: screen, max: undefined }] };
38 | }
39 |
40 | let [name, options] = screen;
41 | name = name.toString();
42 |
43 | if (typeof options === 'string') {
44 | return { name, values: [{ min: options, max: undefined }] };
45 | }
46 |
47 | if (Array.isArray(options)) {
48 | return { name, values: options.map((option) => resolveValue(option)) };
49 | }
50 |
51 | return { name, values: [resolveValue(options)] };
52 | });
53 | }
54 | return normalizeScreens(Object.entries(screens ?? {}), false);
55 | }
56 |
--------------------------------------------------------------------------------
/src/utils/initScreens.ts:
--------------------------------------------------------------------------------
1 | import type { ComputedRef } from 'vue';
2 | import { computed, reactive } from 'vue';
3 | import { NormalizedScreen, normalizeScreens } from './normalizeScreens';
4 | import buildMediaQuery from './buildMediaQuery';
5 | import defaultScreens from './defaultScreens';
6 | import { windowHasFeature } from './window';
7 |
8 | export type Screens = Record;
9 | export type ScreensConfig = Record;
10 |
11 | export interface ScreensOptions {
12 | injectKey?: string;
13 | }
14 |
15 | interface ScreensState {
16 | screens: NormalizedScreen[];
17 | queries: Record;
18 | matches: any;
19 | hasSetup: boolean;
20 | }
21 |
22 | export const defaultInjectKey = '$screens';
23 |
24 | export function initScreens(screens?: Screens) {
25 | const state = reactive({
26 | screens: normalizeScreens(screens || defaultScreens),
27 | queries: {},
28 | matches: {},
29 | hasSetup: false,
30 | });
31 |
32 | function refreshMatches() {
33 | Object.entries(state.queries).forEach(([key, query]) => {
34 | state.matches[key] = query.matches;
35 | });
36 | }
37 |
38 | function mapList(config: ScreensConfig): ComputedRef {
39 | return computed(() =>
40 | Object.keys(state.matches)
41 | .filter((key) => state.matches[key] === true && config.hasOwnProperty(key))
42 | .map((key) => config[key])
43 | );
44 | }
45 |
46 | const list = computed(() => Object.keys(state.matches).filter((k) => state.matches[k]));
47 |
48 | function mapCurrent(config: ScreensConfig, def?: any) {
49 | return computed(() => {
50 | const curr = current.value;
51 | if (curr && config.hasOwnProperty(curr)) return config[curr];
52 | return def;
53 | });
54 | }
55 |
56 | const current = computed(() => {
57 | const arr = list.value;
58 | if (arr.length) return arr[arr.length - 1];
59 | return '';
60 | });
61 |
62 | function cleanup() {
63 | Object.values(state.queries).forEach((query) => query.removeEventListener('change', refreshMatches));
64 | state.queries = {};
65 | state.matches = {};
66 | }
67 |
68 | if (!state.hasSetup && windowHasFeature('matchMedia')) {
69 | cleanup();
70 | state.queries = state.screens.reduce((result, { name, values }) => {
71 | const mediaQuery = window.matchMedia(buildMediaQuery(values));
72 | mediaQuery.addEventListener('change', refreshMatches);
73 | result[name] = mediaQuery;
74 | return result;
75 | }, {} as Record);
76 | refreshMatches();
77 | state.hasSetup = true;
78 | }
79 |
80 | return { matches: state.matches, list, mapList, current, mapCurrent, cleanup };
81 | }
82 |
--------------------------------------------------------------------------------
/src/use/darkMode.ts:
--------------------------------------------------------------------------------
1 | import { Ref, ref, computed, onUnmounted, watch } from 'vue';
2 | import { windowExists, windowHasFeature } from '../utils/window';
3 |
4 | export interface DarkModeClassConfig {
5 | selector: string;
6 | darkClass: string;
7 | }
8 |
9 | export type DarkModeConfig = boolean | 'system' | Partial;
10 |
11 | export function useDarkMode(config: Ref) {
12 | const isDark = ref(false);
13 | const displayMode = computed(() => (isDark.value ? 'dark' : 'light'));
14 |
15 | let mediaQuery: MediaQueryList | undefined;
16 | let mutationObserver: MutationObserver | undefined;
17 |
18 | function mqListener(ev: MediaQueryListEvent) {
19 | isDark.value = ev.matches;
20 | }
21 |
22 | function setupSystem() {
23 | if (windowHasFeature('matchMedia')) {
24 | mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
25 | mediaQuery.addEventListener('change', mqListener);
26 | isDark.value = mediaQuery.matches;
27 | }
28 | }
29 |
30 | function moListener() {
31 | const { selector = ':root', darkClass = 'dark' } = config.value as DarkModeClassConfig;
32 | const el = document.querySelector(selector);
33 | isDark.value = (el as HTMLElement).classList.contains(darkClass);
34 | }
35 |
36 | function setupClass(config: DarkModeClassConfig) {
37 | const { selector = ':root', darkClass = 'dark' } = config;
38 | if (windowExists() && selector && darkClass) {
39 | const el = document.querySelector(selector);
40 | if (el) {
41 | mutationObserver = new MutationObserver(moListener);
42 | mutationObserver.observe(el, {
43 | attributes: true,
44 | attributeFilter: ['class'],
45 | });
46 | isDark.value = (el as HTMLElement).classList.contains(darkClass);
47 | }
48 | }
49 | }
50 |
51 | function setup() {
52 | stopObservers();
53 | const type = typeof config.value;
54 | if (type === 'string' && (config.value as string).toLowerCase() === 'system') {
55 | setupSystem();
56 | } else if (type === 'object') {
57 | setupClass(config.value as DarkModeClassConfig);
58 | } else {
59 | isDark.value = !!config.value;
60 | }
61 | }
62 |
63 | const stopWatch = watch(
64 | () => config.value,
65 | () => setup(),
66 | {
67 | immediate: true,
68 | }
69 | );
70 |
71 | function stopObservers() {
72 | if (mediaQuery) {
73 | mediaQuery.removeEventListener('change', mqListener);
74 | mediaQuery = undefined;
75 | }
76 | if (mutationObserver) {
77 | mutationObserver.disconnect();
78 | mutationObserver = undefined;
79 | }
80 | }
81 |
82 | function cleanup() {
83 | stopObservers();
84 | stopWatch();
85 | }
86 |
87 | onUnmounted(() => cleanup());
88 |
89 | return {
90 | isDark,
91 | displayMode,
92 | cleanup,
93 | };
94 | }
95 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # vue-screen-utils
2 |
3 | A dependency-free collection of screen utility functions in Vue 3, written completely in TypeScript.
4 |
5 | - [**Use Screens**](#use-screens): Use function for mapping screen sizes to media query strings, arrays and custom values
6 | - [**Screens Plugin**](#screens-plugin): Same `useScreens` goodness but applied application-wide in a Vue plugin.
7 | - [**Use Media Query**](#use-media-query): Use function for evaluating simple media query strings.
8 | - [**Use Resize Observer**](#use-resize-observer): Use function for evaluating changes made to an ref element's content rect.
9 | - [**Use Dark Mode**](#use-dark-mode): Use function for observing dark mode using manual, class or system preference strategies.
10 |
11 | ## Install package
12 |
13 | ```console
14 | npm install vue-screen-utils
15 | ```
16 |
17 | ## Use Screens
18 |
19 | ### Step 1. Import and call `useScreens`
20 |
21 | Import and call the `useScreens` function within a parent component, passing a config object that maps custom screen size keys to media query values.
22 |
23 | ```html
24 |
25 |
42 | ```
43 |
44 | The `useScreens` function accepts a config object with screen size keys mapped to query values. A simple pixel value of '640px' will get mapped to 'min-width: 640px'. It is recommended to map a mobile-first key with a '0px' value followed by larger sizes.
45 |
46 | The query value may be in a variety of formats.
47 |
48 | ```js
49 | useScreens(['0px', '100px', '200px']); // Raw strings
50 | useScreens({ xs: '0px', sm: '100px', md: '200px' }); // Object with string values
51 | useScreens({ xs: { min: '0px' }, sm: { min: '100px' }, md: { min: '100px' } }); // Object with object values
52 | useScreens({ xs: [{ min: '0px' }, { max: '100px' }] }); // Object with object array (multiple values)
53 | ```
54 |
55 | The `useScreens` function will return an [object](#screens-object) with a collection of utility properties and functions. This object will also get injected into the parent's child components as `$screens` (or custom `injectKey`).
56 |
57 | See notes about [cleanup](#cleanup).
58 |
59 | ### Step 2. Inject the `$screens` object into nested components.
60 |
61 | ```html
62 |
63 |
68 | ```
69 |
70 | #### Matches Object
71 |
72 | The value of `matches` in the example above is a reactive object of size keys mapped to the match status of their respective media query.
73 |
74 | ```js
75 | // Viewport is 800px wide
76 | console.log(matches.value); // { xs: true, sm: true, md: true, lg: false, xl: false }
77 | ```
78 |
79 | #### Current Screen
80 |
81 | The `current` computed property returns the current max screen size key.
82 |
83 | ```js
84 | console.log(current.value); // 'md'
85 | ```
86 |
87 | The `mapCurrent()` function returns a computed value mapped to the `current` key.
88 |
89 | ```js
90 | const current = mapCurrent({ xs: 0, sm: 1, md: 2, lg: 3, xl: 4 });
91 | console.log(current.value); // 2
92 | ```
93 |
94 | Pass an optional default value that gets returned when no screen sizes are matched.
95 |
96 | ```js
97 | const current = mapCurrent({ lg: 3 }, 0);
98 | console.log(current.value); // 0
99 | ```
100 |
101 | #### List Matching Screens
102 |
103 | The `list` computed property returns a list of media-matched screen size keys.
104 |
105 | ```js
106 | console.log(list.value); // ['xs', 'sm', 'md']
107 | ```
108 |
109 | The `mapList()` function returns a computed property list of custom values mapped to the current matched size keys.
110 |
111 | ```js
112 | const value = mapList({ xs: 0, sm: 1, md: 2, lg: 3, xl: 4 });
113 | console.log(value.value); // [0, 1, 2]
114 | ```
115 |
116 | #### Cleanup
117 |
118 | Event cleanup happens automatically when the parent component is unmounted, but can be manually called if needed.
119 |
120 | ```js
121 | //
122 | const { cleanup } = useScreens({...});
123 | cleanup();
124 | ```
125 |
126 | ## Screens Plugin
127 |
128 | The `screens` plugin is exactly like the `useScreens` method above, but allows for a screen configuration to be used application-wide. Also, a global property will be created for easy access to `$screens` within templates.
129 |
130 | ### Step 1. Import the plugin.
131 |
132 | ```js
133 | // main.js
134 | import { screens } from 'vue-screen-utils';
135 |
136 | // Use plugin with optional config
137 | app.use(screens, {
138 | mobile: '0px',
139 | tablet: '640px',
140 | laptop: '1024px',
141 | desktop: '1280px',
142 | });
143 | ```
144 |
145 | ### Step 2. Repeat step 2 from the [_Use Screens_](#use-screens) method above.
146 |
147 | ### Step 3. Quick reference from component templates
148 |
149 | ```html
150 |
151 |
152 |
153 | ```
154 |
155 | ## Use Media Query
156 |
157 | Import and use the `useMediaQuery` function to evaluate simple media query strings. The function returns a `matches` computed property with the media query match status and an optional `cleanup()` function.
158 |
159 | If you wish to receive a callback of the raw media query event, provide the callback function as the second argument.
160 |
161 | Event cleanup happens automatically when the component is unmounted, but can be manually called via the `cleanup()` function.
162 |
163 | ```html
164 |
165 |
166 |
High-DPI: {{ matches }}
167 |
168 |
169 |
170 |
178 | ```
179 |
180 | ## Use Resize Observer
181 |
182 | Import and use the `useResizeObserver` function to evaluate changes made to an ref element's content rect. The function returns a reactive content `rect` object. It also returns an optional `cleanup()` function.
183 |
184 | If you wish to receive a callback of the raw resize observer event, provide the callback function as the second argument.
185 |
186 | The backing event is cleaned up when the component is unmounted, but `cleanup()` can be called manually.
187 |
188 | ```html
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
205 | ```
206 |
207 | ## Use Dark Mode
208 |
209 | Import and use the `useDarkMode` function to evaluate dark mode using a variety of strategies, based on the argument provided.
210 |
211 | ```ts
212 | declare function useDarkMode(config: Ref>): {
213 | isDark: Ref;
214 | displayMode: ComputedRef<'dark' | 'light'>;
215 | cleanup: () => void;
216 | };
217 | ```
218 |
219 | ### Manual Strategy
220 |
221 | Pass a boolean value for `isDark` to set the dark mode manually.
222 |
223 | ```html
224 |
225 |
Dark Mode Active: {{ isDark ? 'Yes' : 'No' }}
226 |
227 |
228 |
234 | ```
235 |
236 | ### System Preference Strategy
237 |
238 | Pass the `system` string to use the `Window.matchMedia()` API to read the user's system preference. This setting is continually watched to detect future changes made by the user.
239 |
240 | For example, to view the effect on the Mac, you can navigate to **System Preferences › General** and switch the **Appearance** setting between `Light`, `Dark` and `Auto`.
241 |
242 | ```html
243 |
244 |
Dark Mode Active: {{ isDark ? 'Yes' : 'No' }}
245 |
246 |
247 |
253 | ```
254 |
255 | ### Class Strategy
256 |
257 | To use the class strategy, pass an object with the element `selector` and `darkClass` to check against.
258 |
259 | ```ts
260 | interface DarkModeClassConfig {
261 | selector: string;
262 | darkClass: string;
263 | }
264 | ```
265 |
266 | Any class updates made on the element are watched with a `MutationObserver` to detect future changes made by the user.
267 |
268 | ```html
269 |
270 |