Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add useNetworkStatus #117

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
166 changes: 166 additions & 0 deletions packages/runed/src/lib/utilities/NetworkStatus/NetworkStatus.svelte.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import { untrack } from "svelte";
import { browser } from "$lib/internal/utils/browser.js";
import { addEventListener } from "$lib/internal/utils/event.js";
import { IsSupported } from "$lib/utilities/index.js";

/**
* @desc The `NetworkInformation` interface of the Network Information API
* @see https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation
*/
type NetworkInformation = {
michal-weglarz marked this conversation as resolved.
Show resolved Hide resolved
readonly downlink: number;
readonly downlinkMax: number;
readonly effectiveType: "slow-2g" | "2g" | "3g" | "4g";
readonly rtt: number;
readonly saveData: boolean;
readonly type:
| "bluetooth"
| "cellular"
| "ethernet"
| "none"
| "wifi"
| "wimax"
| "other"
| "unknown";
} & EventTarget;

type NavigatorWithConnection = Navigator & { connection: NetworkInformation };

/**
* Tracks the state of browser's network connection.
*/
export class NetworkStatus {
#isNetworkStatusSupported = new IsSupported(() => browser && "navigator" in window);
#navigator?: Navigator = $derived(
this.#isNetworkStatusSupported.current ? window.navigator : undefined
);
#connection?: NetworkInformation = $derived(
this.#navigator && "connection" in this.#navigator
? (this.#navigator as NavigatorWithConnection).connection
: undefined
);

#isSupported = $derived(this.#isNetworkStatusSupported.current);
#online: boolean = $state(false);
#updatedAt: Date = $state(new Date());
#downlink?: NetworkInformation["downlink"] = $state();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't these be deriveds that depend on connection?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, can't we just use gets that use connection? Why do we need these individual fields?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we get the updated state without these? If connection or its properties, or online/offline status changes (e.g., random internet disconnection), how will the client be notified?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

connection can be a state, since all of the other ones are just set from it. then updateStatus updates connection, and that's it

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pushed the commit where I simplified the state by depending solely on the derived connection. Seems like it's working exactly the same as before so definitely a great suggestion :)

#downlinkMax?: NetworkInformation["downlinkMax"] = $state();
#effectiveType?: NetworkInformation["effectiveType"] = $state();
#rtt?: NetworkInformation["rtt"] = $state();
#saveData?: NetworkInformation["saveData"] = $state();
#type?: NetworkInformation["type"] = $state();

constructor() {
$effect(() => {
untrack(() => {
this.#updateStatus();
});

const callbacks: VoidFunction[] = [];

// The connection event handler also manages online and offline states.
if (this.#connection) {
callbacks.push(
michal-weglarz marked this conversation as resolved.
Show resolved Hide resolved
addEventListener(this.#connection, "change", this.#updateStatus, { passive: true })
);
} else {
callbacks.push(addEventListener(window, "online", this.#updateStatus, { passive: true }));
callbacks.push(addEventListener(window, "offline", this.#updateStatus, { passive: true }));
}

return () => {
callbacks.forEach((c) => c());
};
});
}

#updateStatus = () => {
if (this.#navigator) {
this.#online = this.#navigator.onLine;
this.#updatedAt = new Date();
if (this.#connection) {
this.#downlink = this.#connection.downlink;
this.#downlinkMax = this.#connection.downlinkMax;
this.#effectiveType = this.#connection.effectiveType;
this.#rtt = this.#connection.rtt;
this.#saveData = this.#connection.saveData;
this.#type = this.#connection.type;
}
}
michal-weglarz marked this conversation as resolved.
Show resolved Hide resolved
};

/**
* @returns {boolean} Whether the network status API is supported on this device.
*/
get isSupported() {
return this.#isSupported;
}

/**
* @desc Returns the online status of the browser.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine
*/
get online() {
return this.#online;
}

/**
* @desc The {Date} object pointing to the moment when state update occurred.
*/
get updatedAt() {
return this.#updatedAt;
}

/**
* @desc Effective bandwidth estimate in megabits per second, rounded to the
* nearest multiple of 25 kilobits per seconds.
* @see https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
*/
get downlink() {
return this.#downlink;
}

/**
* @desc Maximum downlink speed, in megabits per second (Mbps), for the
* underlying connection technology
* @see https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlinkMax
*/
get downlinkMax() {
return this.#downlinkMax;
}

/**
* @desc Effective type of the connection meaning one of 'slow-2g', '2g', '3g', or '4g'.
* This value is determined using a combination of recently observed round-trip time
* and downlink values.
* @see https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/effectiveType
*/
get effectiveType() {
return this.#effectiveType;
}

/**
* @desc Estimated effective round-trip time of the current connection, rounded
* to the nearest multiple of 25 milliseconds
* @see https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/rtt
*/
get rtt() {
return this.#rtt;
}

/**
* @desc {true} if the user has set a reduced data usage option on the user agent.
* @see https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/saveData
*/
get saveData() {
return this.#saveData;
}

/**
* @desc The type of connection a device is using to communicate with the network.
* @see https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/type
*/
get type() {
return this.#type;
}
}
1 change: 1 addition & 0 deletions packages/runed/src/lib/utilities/NetworkStatus/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./NetworkStatus.svelte.js";
1 change: 1 addition & 0 deletions packages/runed/src/lib/utilities/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ export * from "./AnimationFrames/index.js";
export * from "./useIntersectionObserver/index.js";
export * from "./IsFocusWithin/index.js";
export * from "./FiniteStateMachine/index.js";
export * from "./NetworkStatus/index.js";
104 changes: 104 additions & 0 deletions sites/docs/content/utilities/network-status.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
---
title: NetworkStatus
description: Watch for network status changes.
category: Browser
---

<script>
import Demo from "$lib/components/demos/network-status.svelte";
import { Callout } from "$lib/components";
</script>

## Demo

To see it in action, try disabling and then re-enabling your Internet connection.
If you're using Google Chrome, you can
also [artificially throttle the network](https://developer.chrome.com/docs/devtools/settings/throttling) to test its
behavior under different conditions.

<Demo />

## Usage

You can use `useNetworkStatus()` to retrieve both current and previous network status.
It must be used within the `browser` context, otherwise it will return `null`.

```svelte
<script lang="ts">
import { useNetworkStatus } from "runed";
import { toast } from "svelte-sonner";

const networkStatus = new NetworkStatus();
const previousNetworkStatus = new Previous(() => ({
online: networkStatus.online,
updatedAt: networkStatus.updatedAt,
}));

$effect(() => {
if (!networkStatus.isSupported) {
return;
}
if (networkStatus.online === false) {
toast.error("No internet connection.");
}
if (networkStatus.effectiveType === "2g") {
toast.warning("You are experiencing a slow connection.");
}
if (networkStatus.online === true && previousNetworkStatus.current?.online === false) {
toast.success("You are back online!");
}
});
</script>


{#if networkStatus.isSupported}
<p>online: {networkStatus.online}</p>
{:else}
<p>Network Status is currently not available.</p>
{/if}
```

### Current

You can get the current status by calling the `current` method.

```ts
const networkStatus = useNetworkStatus();

networkStatus.current;
```

### Previous
michal-weglarz marked this conversation as resolved.
Show resolved Hide resolved

You can get the previous status by calling the `previous` method.
It defaults to `undefined` if the network status hasn't been updated since the component mounted.

```ts
const networkStatus = useNetworkStatus();

networkStatus.previous;
```

michal-weglarz marked this conversation as resolved.
Show resolved Hide resolved
## Reference

The returned status always includes `online` and `updatedAt`.
Other properties are returned based on
the [NetworkInformation](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation#instance_properties)
interface and depend
on [your browser's compatibility](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation#browser_compatibility).

```typescript
interface NetworkStatus {
online: boolean;
updatedAt: Date;
downlink?: number;
downlinkMax?: number;
effectiveType?: "slow-2g" | "2g" | "3g" | "4g";
rtt?: number;
saveData?: boolean;
type?: "bluetooth" | "cellular" | "ethernet" | "none" | "wifi" | "wimax" | "other" | "unknown";
}
```



71 changes: 71 additions & 0 deletions sites/docs/src/lib/components/demos/network-status.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<script lang="ts">
import { NetworkStatus, Previous } from "runed";
import { toast } from "svelte-sonner";
import DemoContainer from "$lib/components/demo-container.svelte";

const networkStatus = new NetworkStatus();
const previousNetworkStatus = new Previous(() => ({
online: networkStatus.online,
updatedAt: networkStatus.updatedAt,
}));

const timeOffline = $derived.by(() => {
if (networkStatus.isSupported) {
const now = networkStatus.updatedAt;
const prev = previousNetworkStatus.current?.updatedAt;
if (!now || !prev) {
return 0;
}
const differenceMs = now.getTime() - prev.getTime();
if (differenceMs < 0) {
return 0;
}
const differenceSeconds = differenceMs / 1000;
return Math.round(differenceSeconds);
}
return 0;
});


$effect(() => {
if (!networkStatus.isSupported) {
return;
}
if (networkStatus.online === false) {
toast.error("No internet connection. Reconnect to continue using the app.");
}
if (
networkStatus.effectiveType === "3g" ||
networkStatus.effectiveType === "2g" ||
networkStatus.effectiveType === "slow-2g"
) {
toast.warning(
"You are experiencing a slow connection. Some features may take longer to load.",
);
}
if (networkStatus.online === true && previousNetworkStatus.current?.online === false) {
toast.success(
`You are back online! Catch up with what you missed during your ${timeOffline} seconds offline.`,
);
}
});

const networkStatusCombined = $derived(({
online: networkStatus.online,
updatedAt: networkStatus.updatedAt,
effectiveType: networkStatus.effectiveType,
downlink: networkStatus.downlink,
downlinkMax: networkStatus.downlinkMax,
rtt: networkStatus.rtt,
saveData: networkStatus.saveData,
type: networkStatus.type,
}));
</script>

<DemoContainer>
{#if networkStatus.isSupported}
<pre>{JSON.stringify(networkStatusCombined, null, 2)}</pre>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@huntabyte is it too hard to get syntax highlighting here?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@TGlide, uhh, we could hack it a bit, but without hacks, we'd need to ship Shiki to the browser.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need then!

{:else}
<p>Network Status is currently not available.</p>
{/if}
</DemoContainer>