-
-
Notifications
You must be signed in to change notification settings - Fork 65
feat: NetworkStatus
#117
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
Open
michal-weglarz
wants to merge
14
commits into
svecosystem:main
Choose a base branch
from
michal-weglarz:feat-add-use-network-status-util
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feat: NetworkStatus
#117
Changes from 2 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
e529bf5
feat: add useNetworkStatus util
michal-weglarz c9f45b2
refactor: refactor the way event listeners are removed on unmount
michal-weglarz 15ccf0a
refactor: rewrite useNetworkStatus to a class
michal-weglarz 2d02f6f
touch ups
huntabyte 1096b1f
more touch ups
huntabyte f1e39ae
formatting
huntabyte c406865
chore: minor fixes
michal-weglarz 14c85cb
refactor: replace addEventListener with useEventListener
michal-weglarz baaff33
refactor: simplify internal state by depending on derived connection
michal-weglarz bae76e6
Merge branch 'main' into feat-add-use-network-status-util
huntabyte ffa8774
fix lockfile
huntabyte 831df2d
tidy up
huntabyte 6b7f63e
more
huntabyte 3b2a6a8
Merge branch 'main' into feat-add-use-network-status-util
huntabyte File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export * from "./useNetworkStatus.svelte.js"; |
146 changes: 146 additions & 0 deletions
146
packages/runed/src/lib/utilities/useNetworkStatus/useNetworkStatus.svelte.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,146 @@ | ||
| import { browser } from "$lib/internal/utils/browser.js"; | ||
| import { addEventListener } from "$lib/internal/utils/event.js"; | ||
| import { Previous } 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 = { | ||
| 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 }; | ||
|
|
||
| interface NetworkStatus { | ||
| /** | ||
| * @desc Returns the online status of the browser. | ||
| * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine | ||
| */ | ||
| online: boolean; | ||
| /** | ||
| * @desc The {Date} object pointing to the moment when state update occurred. | ||
| */ | ||
| updatedAt: Date; | ||
| /** | ||
| * @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 | ||
| */ | ||
| downlink?: NetworkInformation["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 | ||
| */ | ||
| downlinkMax?: NetworkInformation["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 | ||
| */ | ||
| effectiveType?: NetworkInformation["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 | ||
| */ | ||
| rtt?: NetworkInformation["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 | ||
| */ | ||
| saveData?: NetworkInformation["saveData"]; | ||
| /** | ||
| * @desc The type of connection a device is using to communicate with the network. | ||
| * It will be one of the following values: | ||
| * - bluetooth | ||
| * - cellular | ||
| * - ethernet | ||
| * - none | ||
| * - wifi | ||
| * - wimax | ||
| * - other | ||
| * - unknown | ||
| * @see https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/type | ||
| */ | ||
| type?: NetworkInformation["type"]; | ||
| } | ||
|
|
||
| /** | ||
| * Tracks the state of browser's network connection. | ||
| * @returns null if the function is not run in the browser | ||
| */ | ||
| export function useNetworkStatus() { | ||
| console.log("browser", browser); | ||
michal-weglarz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if (!browser) { | ||
| return { | ||
| get current() { | ||
| return null; | ||
| }, | ||
| get previous() { | ||
| return null; | ||
| }, | ||
| }; | ||
| } | ||
| const navigator = window.navigator; | ||
| const connection = | ||
| "connection" in navigator ? (navigator as NavigatorWithConnection).connection : undefined; | ||
| const getConnectionStatus = (): NetworkStatus => { | ||
| return { | ||
| online: navigator.onLine, | ||
| updatedAt: new Date(), | ||
| downlink: connection?.downlink, | ||
| downlinkMax: connection?.downlinkMax, | ||
| effectiveType: connection?.effectiveType, | ||
| rtt: connection?.rtt, | ||
| saveData: connection?.saveData, | ||
| type: connection?.type, | ||
| }; | ||
| }; | ||
|
|
||
| let current = $state(getConnectionStatus()); | ||
| const previous = new Previous(() => current); | ||
michal-weglarz marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| const handleStatusChange = () => { | ||
| current = getConnectionStatus(); | ||
| }; | ||
|
|
||
| $effect(() => { | ||
| const callbacks: VoidFunction[] = []; | ||
|
|
||
| // The connection event handler also manages online and offline states. | ||
| if (connection) { | ||
| callbacks.push(addEventListener(connection, "change", handleStatusChange, { passive: true })); | ||
| } else { | ||
| callbacks.push(addEventListener(window, "online", handleStatusChange, { passive: true })); | ||
| callbacks.push(addEventListener(window, "offline", handleStatusChange, { passive: true })); | ||
| } | ||
|
|
||
| return () => { | ||
| callbacks.forEach((c) => c()); | ||
| }; | ||
| }); | ||
|
|
||
| return { | ||
| get current() { | ||
| return current; | ||
| }, | ||
| get previous() { | ||
| return previous.current; | ||
| }, | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| --- | ||
| title: useNetworkStatus | ||
| description: Watch for network status changes. | ||
| category: Browser | ||
| --- | ||
|
|
||
| <script> | ||
| import Demo from '$lib/components/demos/use-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 = useNetworkStatus(); | ||
|
|
||
| $effect(() => { | ||
| if (!networkStatus.current) { | ||
| return; | ||
| } | ||
| if (networkStatus.current.online === false) { | ||
| toast.error("No internet connection."); | ||
| } | ||
| if (networkStatus.current.effectiveType === "2g") { | ||
| toast.warning("You are experiencing a slow connection."); | ||
| } | ||
| if (networkStatus.current.online === true && networkStatus.previous?.online === false) { | ||
| toast.success("You are back online!"); | ||
| } | ||
| }); | ||
| </script> | ||
|
|
||
|
|
||
| {#if networkStatus.current} | ||
| <p>online: {networkStatus.current.online}</p> | ||
| {/if} | ||
| ``` | ||
|
|
||
| ### Current | ||
|
|
||
| You can get the current status by calling the `current` method. | ||
|
|
||
|
|
||
| ```ts | ||
| const networkStatus = useNetworkStatus(); | ||
|
|
||
| networkStatus.current; | ||
| ``` | ||
|
|
||
| ### Previous | ||
|
|
||
| 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; | ||
| ``` | ||
|
|
||
| ## 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"; | ||
| } | ||
| ``` | ||
|
|
||
|
|
||
|
|
54 changes: 54 additions & 0 deletions
54
sites/docs/src/lib/components/demos/use-network-status.svelte
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| <script lang="ts"> | ||
| import { useNetworkStatus } from "runed"; | ||
| import { toast } from "svelte-sonner"; | ||
| import DemoContainer from "$lib/components/demo-container.svelte"; | ||
|
|
||
| const networkStatus = useNetworkStatus(); | ||
|
|
||
| const timeOffline = $derived(() => { | ||
| if (networkStatus && networkStatus.previous) { | ||
| const now = networkStatus.current.updatedAt; | ||
| const prev = networkStatus.previous.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.current) { | ||
| return; | ||
| } | ||
|
|
||
| if (networkStatus.current.online === false) { | ||
| toast.error("No internet connection. Reconnect to continue using the app."); | ||
| } | ||
| if ( | ||
| networkStatus.current.effectiveType === "3g" || | ||
| networkStatus.current.effectiveType === "2g" || | ||
| networkStatus.current.effectiveType === "slow-2g" | ||
| ) { | ||
| toast.warning( | ||
| "You are experiencing a slow connection. Some features may take longer to load." | ||
| ); | ||
| } | ||
| if (networkStatus.current.online === true && networkStatus.previous?.online === false) { | ||
| toast.success( | ||
| `You are back online! Catch up with what you missed during your ${timeOffline()} seconds offline.` | ||
| ); | ||
| } | ||
| }); | ||
| </script> | ||
|
|
||
| <DemoContainer> | ||
| {#if networkStatus.current} | ||
| <pre>{JSON.stringify(networkStatus.current, null, 2)}</pre> | ||
| {/if} | ||
| </DemoContainer> |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.