@goodnight-dev/react-hooks 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -34,12 +34,14 @@ Both are fully typed, ESM-only, and tree-shakable.
34
34
 
35
35
  ## API
36
36
 
37
- | Hook | Description |
38
- | ------------------------------- | ---------------------------------------------------------------------------------- |
39
- | `useTheme()` | Reads the OS `prefers-color-scheme`, live-updating on change. |
40
- | `useLocalStorage(key, initial)` | Reads and writes a JSON-serializable value in `localStorage`, syncing across tabs. |
41
- | `useWindowSize()` | Reads the viewport `width` / `height`, live-updating on resize. |
42
- | `useOnlineStatus()` | Reads whether the browser is online (`navigator.onLine`), live-updating. |
37
+ | Hook | Description |
38
+ | ------------------------------- | ------------------------------------------------------------------------------------------ |
39
+ | `useTheme()` | Reads the OS `prefers-color-scheme`, live-updating on change. |
40
+ | `useMediaQuery(query)` | Reads any CSS media query (`matchMedia`), live-updating — the primitive behind `useTheme`. |
41
+ | `useLocalStorage(key, initial)` | Reads and writes a JSON-serializable value in `localStorage`, syncing across tabs. |
42
+ | `useWindowSize()` | Reads the viewport `width` / `height`, live-updating on resize. |
43
+ | `useOnlineStatus()` | Reads whether the browser is online (`navigator.onLine`), live-updating. |
44
+ | `usePageVisibility()` | Reads whether the page is visible (Page Visibility API), live-updating on tab switch. |
43
45
 
44
46
  ```tsx
45
47
  import { useLocalStorage, useTheme } from '@goodnight-dev/react-hooks';
@@ -68,9 +70,11 @@ function App() {
68
70
  ```
69
71
 
70
72
  See [`src/use-theme.md`](./src/use-theme.md),
73
+ [`src/use-media-query.md`](./src/use-media-query.md),
71
74
  [`src/use-local-storage.md`](./src/use-local-storage.md),
72
- [`src/use-window-size.md`](./src/use-window-size.md), and
73
- [`src/use-online-status.md`](./src/use-online-status.md) for the design
75
+ [`src/use-window-size.md`](./src/use-window-size.md),
76
+ [`src/use-online-status.md`](./src/use-online-status.md), and
77
+ [`src/use-page-visibility.md`](./src/use-page-visibility.md) for the design
74
78
  rationale behind each.
75
79
 
76
80
  ## Project goals
package/dist/index.d.mts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { useLocalStorage } from "./use-local-storage.mjs";
2
+ import { useMediaQuery } from "./use-media-query.mjs";
2
3
  import { useOnlineStatus } from "./use-online-status.mjs";
4
+ import { usePageVisibility } from "./use-page-visibility.mjs";
3
5
  import { Theme, ThemePreference, useTheme } from "./use-theme.mjs";
4
6
  import { WindowSize, useWindowSize } from "./use-window-size.mjs";
5
- export { type Theme, type ThemePreference, type WindowSize, useLocalStorage, useOnlineStatus, useTheme, useWindowSize };
7
+ export { type Theme, type ThemePreference, type WindowSize, useLocalStorage, useMediaQuery, useOnlineStatus, usePageVisibility, useTheme, useWindowSize };
package/dist/index.mjs CHANGED
@@ -1,5 +1,7 @@
1
1
  import { useLocalStorage } from "./use-local-storage.mjs";
2
+ import { useMediaQuery } from "./use-media-query.mjs";
2
3
  import { useOnlineStatus } from "./use-online-status.mjs";
4
+ import { usePageVisibility } from "./use-page-visibility.mjs";
3
5
  import { useTheme } from "./use-theme.mjs";
4
6
  import { useWindowSize } from "./use-window-size.mjs";
5
- export { useLocalStorage, useOnlineStatus, useTheme, useWindowSize };
7
+ export { useLocalStorage, useMediaQuery, useOnlineStatus, usePageVisibility, useTheme, useWindowSize };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Read whether a CSS media query currently matches
3
+ * (`window.matchMedia(query).matches`), staying in sync as it starts and stops
4
+ * matching.
5
+ *
6
+ * The general form of a `matchMedia` subscription — breakpoints
7
+ * (`'(min-width: 768px)'`), `'(prefers-reduced-motion: reduce)'`, pointer /
8
+ * hover capability, `'print'`, and so on. `useTheme` is this hook specialized
9
+ * to `'(prefers-color-scheme: dark)'`.
10
+ *
11
+ * Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
12
+ * and does not tear. The result is `undefined` on the server — and on the
13
+ * client until the first `matchMedia` read commits — the same "unknown until
14
+ * proven otherwise" contract `useTheme` uses for `theme`: there is no honest
15
+ * value to render for a query the server cannot evaluate, so render a neutral
16
+ * state for `undefined` rather than guessing a match.
17
+ *
18
+ * `query` should be a stable string; changing it re-subscribes to the new
19
+ * query (and re-reads), the same way passing a new `key` to `useLocalStorage`
20
+ * switches keys.
21
+ *
22
+ * @param query - A media query string, exactly as `window.matchMedia` takes it.
23
+ *
24
+ * @returns `true` when the query matches, `false` when it does not, and
25
+ * `undefined` until the client has read the real value (always the case during
26
+ * SSR).
27
+ *
28
+ * @example
29
+ * ```tsx
30
+ * const isWide = useMediaQuery('(min-width: 768px)');
31
+ * if (isWide === undefined) return null; // don't guess a breakpoint before we know
32
+ * return isWide ? <Sidebar /> : <Drawer />;
33
+ * ```
34
+ */
35
+ export declare function useMediaQuery(query: string): boolean | undefined;
@@ -0,0 +1,49 @@
1
+ import { useCallback, useSyncExternalStore } from "react";
2
+ // src/use-media-query.ts
3
+ const getServerSnapshot = () => void 0;
4
+ /**
5
+ * Read whether a CSS media query currently matches
6
+ * (`window.matchMedia(query).matches`), staying in sync as it starts and stops
7
+ * matching.
8
+ *
9
+ * The general form of a `matchMedia` subscription — breakpoints
10
+ * (`'(min-width: 768px)'`), `'(prefers-reduced-motion: reduce)'`, pointer /
11
+ * hover capability, `'print'`, and so on. `useTheme` is this hook specialized
12
+ * to `'(prefers-color-scheme: dark)'`.
13
+ *
14
+ * Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
15
+ * and does not tear. The result is `undefined` on the server — and on the
16
+ * client until the first `matchMedia` read commits — the same "unknown until
17
+ * proven otherwise" contract `useTheme` uses for `theme`: there is no honest
18
+ * value to render for a query the server cannot evaluate, so render a neutral
19
+ * state for `undefined` rather than guessing a match.
20
+ *
21
+ * `query` should be a stable string; changing it re-subscribes to the new
22
+ * query (and re-reads), the same way passing a new `key` to `useLocalStorage`
23
+ * switches keys.
24
+ *
25
+ * @param query - A media query string, exactly as `window.matchMedia` takes it.
26
+ *
27
+ * @returns `true` when the query matches, `false` when it does not, and
28
+ * `undefined` until the client has read the real value (always the case during
29
+ * SSR).
30
+ *
31
+ * @example
32
+ * ```tsx
33
+ * const isWide = useMediaQuery('(min-width: 768px)');
34
+ * if (isWide === undefined) return null; // don't guess a breakpoint before we know
35
+ * return isWide ? <Sidebar /> : <Drawer />;
36
+ * ```
37
+ */
38
+ function useMediaQuery(query) {
39
+ const subscribe = useCallback((onStoreChange) => {
40
+ const mediaQueryList = window.matchMedia(query);
41
+ mediaQueryList.addEventListener("change", onStoreChange);
42
+ return () => {
43
+ mediaQueryList.removeEventListener("change", onStoreChange);
44
+ };
45
+ }, [query]);
46
+ const getSnapshot = useCallback(() => window.matchMedia(query).matches, [query]);
47
+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
48
+ }
49
+ export { useMediaQuery };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Read whether the page is currently visible — its tab foregrounded and its
3
+ * window not minimized — staying in sync via the Page Visibility API's
4
+ * `visibilitychange` event.
5
+ *
6
+ * Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
7
+ * and does not tear. The value is `undefined` on the server — and on the client
8
+ * until the first read commits — the same "unknown until proven otherwise"
9
+ * contract `useOnlineStatus` and `useTheme` use: there is no honest value to
10
+ * render for a tab whose focus the server cannot know, so treat `undefined` as
11
+ * a neutral "not yet known" rather than assuming visible.
12
+ *
13
+ * `visibilityState` is the browser's own coarse signal: it reports foreground
14
+ * vs. background/minimized, *not* whether the user is actually looking, whether
15
+ * the window is occluded by another, or whether a visible tab holds input
16
+ * focus. Use it to pause work that is wasteful off-screen — polling, video,
17
+ * animation loops — and resume it on return; reach for the `focus` / `blur`
18
+ * events if you need true input focus instead.
19
+ *
20
+ * @returns `true` when the page is visible, `false` when it is hidden
21
+ * (backgrounded tab or minimized window), and `undefined` until the client has
22
+ * read the real value (always the case during SSR).
23
+ *
24
+ * @example
25
+ * ```tsx
26
+ * const isVisible = usePageVisibility();
27
+ *
28
+ * useEffect(() => {
29
+ * if (isVisible === undefined) return; // don't start or stop before we know
30
+ * if (isVisible) resumePolling();
31
+ * else pausePolling();
32
+ * }, [isVisible]);
33
+ * ```
34
+ */
35
+ export declare function usePageVisibility(): boolean | undefined;
@@ -0,0 +1,48 @@
1
+ import { useSyncExternalStore } from "react";
2
+ // src/use-page-visibility.ts
3
+ const subscribe = (onStoreChange) => {
4
+ document.addEventListener("visibilitychange", onStoreChange);
5
+ return () => {
6
+ document.removeEventListener("visibilitychange", onStoreChange);
7
+ };
8
+ };
9
+ const getSnapshot = () => document.visibilityState === "visible";
10
+ const getServerSnapshot = () => void 0;
11
+ /**
12
+ * Read whether the page is currently visible — its tab foregrounded and its
13
+ * window not minimized — staying in sync via the Page Visibility API's
14
+ * `visibilitychange` event.
15
+ *
16
+ * Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
17
+ * and does not tear. The value is `undefined` on the server — and on the client
18
+ * until the first read commits — the same "unknown until proven otherwise"
19
+ * contract `useOnlineStatus` and `useTheme` use: there is no honest value to
20
+ * render for a tab whose focus the server cannot know, so treat `undefined` as
21
+ * a neutral "not yet known" rather than assuming visible.
22
+ *
23
+ * `visibilityState` is the browser's own coarse signal: it reports foreground
24
+ * vs. background/minimized, *not* whether the user is actually looking, whether
25
+ * the window is occluded by another, or whether a visible tab holds input
26
+ * focus. Use it to pause work that is wasteful off-screen — polling, video,
27
+ * animation loops — and resume it on return; reach for the `focus` / `blur`
28
+ * events if you need true input focus instead.
29
+ *
30
+ * @returns `true` when the page is visible, `false` when it is hidden
31
+ * (backgrounded tab or minimized window), and `undefined` until the client has
32
+ * read the real value (always the case during SSR).
33
+ *
34
+ * @example
35
+ * ```tsx
36
+ * const isVisible = usePageVisibility();
37
+ *
38
+ * useEffect(() => {
39
+ * if (isVisible === undefined) return; // don't start or stop before we know
40
+ * if (isVisible) resumePolling();
41
+ * else pausePolling();
42
+ * }, [isVisible]);
43
+ * ```
44
+ */
45
+ function usePageVisibility() {
46
+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
47
+ }
48
+ export { usePageVisibility };
@@ -12,12 +12,14 @@ export interface ThemePreference {
12
12
  * Read the user's OS-level color scheme preference
13
13
  * (`prefers-color-scheme`), and stay in sync as they change it.
14
14
  *
15
- * Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
16
- * and does not tear. `theme` is `undefined` on the server — and on the client
17
- * until the first `matchMedia` read commits — render a neutral state for that
18
- * case rather than branching on `isDarkMode` / `isLightMode`, which are both
19
- * `false` until `theme` resolves (there are only two real themes, so "both
20
- * false" is unambiguous evidence that the preference isn't known yet).
15
+ * A thin specialization of {@link useMediaQuery} over
16
+ * `'(prefers-color-scheme: dark)'`, so it inherits that hook's
17
+ * `useSyncExternalStore` backing — safe under concurrent rendering, does not
18
+ * tear. `theme` is `undefined` on the server — and on the client until the
19
+ * first `matchMedia` read commits — render a neutral state for that case
20
+ * rather than branching on `isDarkMode` / `isLightMode`, which are both `false`
21
+ * until `theme` resolves (there are only two real themes, so "both false" is
22
+ * unambiguous evidence that the preference isn't known yet).
21
23
  *
22
24
  * @returns `theme` plus `isDarkMode` / `isLightMode` convenience booleans.
23
25
  * The returned object is memoized, so its identity only changes when `theme`
@@ -1,25 +1,19 @@
1
- import { useMemo, useSyncExternalStore } from "react";
1
+ import { useMediaQuery } from "./use-media-query.mjs";
2
+ import { useMemo } from "react";
2
3
  // src/use-theme.ts
3
4
  const QUERY = "(prefers-color-scheme: dark)";
4
- const getSnapshot = () => window.matchMedia(QUERY).matches ? "dark" : "light";
5
- const getServerSnapshot = () => void 0;
6
- const subscribe = (onStoreChange) => {
7
- const mediaQueryList = window.matchMedia(QUERY);
8
- mediaQueryList.addEventListener("change", onStoreChange);
9
- return () => {
10
- mediaQueryList.removeEventListener("change", onStoreChange);
11
- };
12
- };
13
5
  /**
14
6
  * Read the user's OS-level color scheme preference
15
7
  * (`prefers-color-scheme`), and stay in sync as they change it.
16
8
  *
17
- * Backed by `useSyncExternalStore`, so it is safe under concurrent rendering
18
- * and does not tear. `theme` is `undefined` on the server — and on the client
19
- * until the first `matchMedia` read commits — render a neutral state for that
20
- * case rather than branching on `isDarkMode` / `isLightMode`, which are both
21
- * `false` until `theme` resolves (there are only two real themes, so "both
22
- * false" is unambiguous evidence that the preference isn't known yet).
9
+ * A thin specialization of {@link useMediaQuery} over
10
+ * `'(prefers-color-scheme: dark)'`, so it inherits that hook's
11
+ * `useSyncExternalStore` backing — safe under concurrent rendering, does not
12
+ * tear. `theme` is `undefined` on the server — and on the client until the
13
+ * first `matchMedia` read commits — render a neutral state for that case
14
+ * rather than branching on `isDarkMode` / `isLightMode`, which are both `false`
15
+ * until `theme` resolves (there are only two real themes, so "both false" is
16
+ * unambiguous evidence that the preference isn't known yet).
23
17
  *
24
18
  * @returns `theme` plus `isDarkMode` / `isLightMode` convenience booleans.
25
19
  * The returned object is memoized, so its identity only changes when `theme`
@@ -33,11 +27,18 @@ const subscribe = (onStoreChange) => {
33
27
  * ```
34
28
  */
35
29
  function useTheme() {
36
- const theme = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
37
- return useMemo(() => ({
38
- theme,
39
- isDarkMode: theme === "dark",
40
- isLightMode: theme === "light"
41
- }), [theme]);
30
+ const isDark = useMediaQuery(QUERY);
31
+ return useMemo(() => {
32
+ if (isDark === void 0) return {
33
+ theme: void 0,
34
+ isDarkMode: false,
35
+ isLightMode: false
36
+ };
37
+ return {
38
+ theme: isDark ? "dark" : "light",
39
+ isDarkMode: isDark,
40
+ isLightMode: !isDark
41
+ };
42
+ }, [isDark]);
42
43
  }
43
44
  export { useTheme };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodnight-dev/react-hooks",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Small, strict, tree-shakeable React hooks — the ones you end up writing in every project, packaged the right way.",
5
5
  "keywords": [
6
6
  "react",
@@ -31,10 +31,18 @@
31
31
  "types": "./dist/use-local-storage.d.mts",
32
32
  "import": "./dist/use-local-storage.mjs"
33
33
  },
34
+ "./useMediaQuery": {
35
+ "types": "./dist/use-media-query.d.mts",
36
+ "import": "./dist/use-media-query.mjs"
37
+ },
34
38
  "./useOnlineStatus": {
35
39
  "types": "./dist/use-online-status.d.mts",
36
40
  "import": "./dist/use-online-status.mjs"
37
41
  },
42
+ "./usePageVisibility": {
43
+ "types": "./dist/use-page-visibility.d.mts",
44
+ "import": "./dist/use-page-visibility.mjs"
45
+ },
38
46
  "./useTheme": {
39
47
  "types": "./dist/use-theme.d.mts",
40
48
  "import": "./dist/use-theme.mjs"