forked from CredenceOrg/Credence-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseReducedTransparency.ts
More file actions
58 lines (50 loc) · 2.1 KB
/
Copy pathuseReducedTransparency.ts
File metadata and controls
58 lines (50 loc) · 2.1 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { useEffect, useState } from 'react'
/**
* Hook to query and subscribe to the user's OS-level transparency preference.
*
* Returns `true` if the user prefers reduced transparency (i.e. `prefers-reduced-transparency: reduce`),
* and `false` otherwise. Safe to run in SSR environments (returns `false` on the server).
*
* When `true`, surfaces should replace semi-transparent backgrounds (e.g. modal
* backdrops, frosted panels) with opaque equivalents so that content behind the
* overlay does not bleed through and cause contrast or readability problems.
*
* @returns boolean indicating whether reduced transparency is preferred.
*/
export function useReducedTransparency(): boolean {
const [reducedTransparency, setReducedTransparency] = useState<boolean>(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
return false
}
return window.matchMedia('(prefers-reduced-transparency: reduce)').matches
})
useEffect(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
return
}
const mql = window.matchMedia('(prefers-reduced-transparency: reduce)')
// Re-sync on mount in case the preference changed before subscribing.
setReducedTransparency(mql.matches)
const handler = (event: MediaQueryListEvent) => {
setReducedTransparency(event.matches)
}
// Modern browsers support addEventListener, but provide a fallback for legacy environments.
const legacyMql = mql as unknown as {
addListener?: (handler: (ev: MediaQueryListEvent) => void) => void
removeListener?: (handler: (ev: MediaQueryListEvent) => void) => void
}
if (typeof mql.addEventListener === 'function') {
mql.addEventListener('change', handler)
return () => {
mql.removeEventListener('change', handler)
}
} else if (typeof legacyMql.addListener === 'function') {
// Fallback for older browsers / legacy environments
legacyMql.addListener(handler)
return () => {
legacyMql.removeListener?.(handler)
}
}
}, [])
return reducedTransparency
}