Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/famous-memes-add.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tiny-hooks": minor
---

Add new `useConnectionType` hook
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export { useBrowserCapabilities } from "./useBrowserCapabilities";
export { useClickAnywhere } from "./useClickAnywhere";
export { useClickOutside } from "./useClickOutside";
export { useClipboard } from "./useClipboard";
export { useConnectionType } from "./useConnectionType";
export { useCookie } from "./useCookie";
export { useCounter } from "./useCounter";
export { useDebounce } from "./useDebounce";
Expand Down
2 changes: 2 additions & 0 deletions src/useConnectionType/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export type { ConnectionInfo } from "./types";
export { useConnectionType } from "./useConnectionType";
9 changes: 9 additions & 0 deletions src/useConnectionType/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export interface ConnectionInfo {
supported: boolean;
type?: string;
effectiveType?: string;
downlink?: number;
rtt?: number;
saveData?: boolean;
speedCategory?: "slow" | "medium" | "fast";
}
117 changes: 117 additions & 0 deletions src/useConnectionType/useConnectionType.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { beforeEach, describe, expect, it, vi } from "bun:test";
import { renderHook, waitFor } from "@testing-library/react";
import { useConnectionType } from "./useConnectionType";

const createMockConnection = (overrides = {}) => ({
type: "wifi",
effectiveType: "4g",
downlink: 45,
rtt: 20,
saveData: false,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
...overrides,
});

describe("useConnectionType", () => {
beforeEach(() => {
vi.restoreAllMocks();
});

it("should return supported=false if Network Information API not available", async () => {
const originalNavigator = global.navigator;
// @ts-expect-error
globalThis.navigator = {};

const { result } = renderHook(() => useConnectionType());

await waitFor(() => {
expect(result.current.supported).toBe(false);
});

globalThis.navigator = originalNavigator;
});

it("should return connection info and fast speedCategory when API is supported", async () => {
// @ts-expect-error
global.navigator.connection = createMockConnection({
downlink: 10,
rtt: 50,
});

const { result } = renderHook(() => useConnectionType());

await waitFor(() => {
expect(result.current.supported).toBe(true);
expect(result.current.type).toBe("wifi");
expect(result.current.effectiveType).toBe("4g");
expect(result.current.downlink).toBe(10);
expect(result.current.rtt).toBe(50);
expect(result.current.saveData).toBe(false);
expect(result.current.speedCategory).toBe("fast");
});
});

it("should correctly calculate medium speedCategory", async () => {
// @ts-expect-error
global.navigator.connection = createMockConnection({
downlink: 3,
rtt: 150,
});

const { result } = renderHook(() => useConnectionType());

await waitFor(() => {
expect(result.current.speedCategory).toBe("medium");
});
});

it("should correctly calculate slow speedCategory", async () => {
// @ts-expect-error
global.navigator.connection = createMockConnection({
downlink: 1,
rtt: 400,
});

const { result } = renderHook(() => useConnectionType());

await waitFor(() => {
expect(result.current.speedCategory).toBe("slow");
});
});

it("should update when connection change event fires", async () => {
let changeHandler: (() => void) | undefined;

const mockConnection = createMockConnection({
addEventListener: vi.fn((event, handler) => {
if (event === "change") changeHandler = handler;
}),
});

// @ts-expect-error
global.navigator.connection = mockConnection;

const { result } = renderHook(() => useConnectionType());

await waitFor(() => expect(result.current.speedCategory).toBe("fast"));

mockConnection.downlink = 0.5;
mockConnection.rtt = 500;

changeHandler?.();

await waitFor(() => {
expect(result.current.speedCategory).toBe("slow");
});

mockConnection.downlink = 10;
mockConnection.rtt = 50;

changeHandler?.();

await waitFor(() => {
expect(result.current.speedCategory).toBe("fast");
});
});
});
49 changes: 49 additions & 0 deletions src/useConnectionType/useConnectionType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { useEffect, useState } from "react";
import type { ConnectionInfo } from "./types.ts";

export function useConnectionType(): ConnectionInfo {
const [connectionInfo, setConnectionInfo] = useState<ConnectionInfo>({
supported: true,
});

useEffect(() => {
// biome-ignore lint/suspicious/noExplicitAny: TS is dumb
const nav = navigator as any;
const connection =
nav.connection || nav.mozConnection || nav.webkitConnection;

if (!connection) {
setConnectionInfo({ supported: false });
return;
}

const calculateSpeedCategory = (rtt?: number, downlink?: number) => {
if (!rtt || !downlink) return "medium";
if (rtt > 300 || downlink < 1.5) return "slow";
if (rtt > 100 || downlink < 5) return "medium";
return "fast";
};

const updateConnection = () => {
setConnectionInfo({
supported: true,
type: connection.type,
effectiveType: connection.effectiveType,
downlink: connection.downlink,
rtt: connection.rtt,
saveData: connection.saveData,
speedCategory: calculateSpeedCategory(
connection.rtt,
connection.downlink,
),
});
};

updateConnection();

connection.addEventListener("change", updateConnection);
return () => connection.removeEventListener("change", updateConnection);
}, []);

return connectionInfo;
}