chore(root): archive examples into tech-preview (#315)

This commit is contained in:
rahim
2026-01-20 14:35:51 +11:00
committed by GitHub
parent 78695d4bb6
commit 35c6cb1e16
62 changed files with 33 additions and 1519 deletions
@@ -0,0 +1,2 @@
export * from './useColorScheme';
export * from './useMediaQuery';
@@ -0,0 +1,28 @@
import { useEffect, useState } from 'react';
type ColorScheme = 'light' | 'dark';
export function useColorScheme(): ColorScheme {
const [colorScheme, setColorScheme] = useState<ColorScheme>(() => {
if (typeof window === 'undefined') {
return 'light';
}
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
});
useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = (event: MediaQueryListEvent) => {
setColorScheme(event.matches ? 'dark' : 'light');
};
mediaQuery.addEventListener('change', handleChange);
return () => {
mediaQuery.removeEventListener('change', handleChange);
};
}, []);
return colorScheme;
}
@@ -0,0 +1,4 @@
import { useEffect, useLayoutEffect } from 'react';
export const useIsomorphicLayoutEffect: typeof useLayoutEffect | typeof useEffect
= typeof window !== 'undefined' ? useLayoutEffect : useEffect;
@@ -0,0 +1,53 @@
import { useState } from 'react';
import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect';
interface UseMediaQueryOptions {
defaultValue?: boolean;
initializeWithValue?: boolean;
}
const IS_SERVER = typeof window === 'undefined';
export function useMediaQuery(
query: string,
{
defaultValue = false,
initializeWithValue = true,
}: UseMediaQueryOptions = {},
): boolean {
const getMatches = (query: string): boolean => {
if (IS_SERVER) {
return defaultValue;
}
return window.matchMedia(query).matches;
};
const [matches, setMatches] = useState<boolean>(() => {
if (initializeWithValue) {
return getMatches(query);
}
return defaultValue;
});
// Handles the change event of the media query.
function handleChange() {
// eslint-disable-next-line react-hooks-extra/no-direct-set-state-in-use-effect
setMatches(getMatches(query));
}
useIsomorphicLayoutEffect(() => {
const matchMedia = window.matchMedia(query);
// Triggered at the first client-side load and if query changes
handleChange();
matchMedia.addEventListener('change', handleChange);
return () => {
matchMedia.removeEventListener('change', handleChange);
};
}, [query]);
return matches;
}