### Install mobx-web-api Source: https://context7.com/js2me/mobx-web-api/llms.txt Instructions for installing the mobx-web-api library using npm, pnpm, or yarn package managers. ```bash npm install mobx-web-api # or pnpm add mobx-web-api # or yarn add mobx-web-api ``` -------------------------------- ### Install mobx-web-api using npm, pnpm, or yarn Source: https://github.com/js2me/mobx-web-api/blob/master/docs/introduction/getting-started.md Instructions for installing the mobx-web-api package using different package managers. Ensure you have Node.js and a package manager installed. ```bash npm install {packageJson.name} ``` ```bash pnpm add {packageJson.name} ``` ```bash yarn add {packageJson.name} ``` -------------------------------- ### MobX Web API Usage Example in TypeScript Source: https://github.com/js2me/mobx-web-api/blob/master/docs/introduction/getting-started.md Demonstrates how to import and use various reactive web APIs like geolocation, media query, network status, and page visibility with MobX. It also shows how to set up a MobX reaction to changes in network status. ```typescript import { geolocation, mediaQuery, networkStatus, pageVisibility } from "mobx-web-api"; import { reaction } from "mobx"; pageVisibility.isVisible; reaction( () => networkStatus.isOnline, (isOnline) => { console.log('isOnline', isOnline); } ) ``` -------------------------------- ### Access and React to Screen Properties with MobX Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/screen-info.md Shows how to import and use screenInfo to get screen dimensions and set up a MobX reaction to changes in screen orientation. It logs the available width and any orientation changes. ```typescript import { screenInfo } from "mobx-web-api"; import { reaction } from "mobx"; console.log(screenInfo.availWidth); // 2560 reaction( () => screen.orientation.type, (orientationType) => { console.log(`orientationType: ${orientationType}`); } ); ``` -------------------------------- ### Basic Window Scroll Tracking with MobX Reaction Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/scroll-data.md This example shows how to track scroll data for the entire window using `createScrollData` and set up a MobX reaction to log when the vertical scroll position exceeds 100 pixels. It assumes the default `window` scrolling element. ```typescript import { createScrollData } from "mobx-web-api"; import { reaction } from "mobx"; const scrollData = createScrollData(document.body); reaction( () => scrollData.scrollY, (scrollY) => { if (scrollY > 100) { console.log("Scrolled past 100px"); } } ); ``` -------------------------------- ### Monitor Page Visibility with mobx-web-api Source: https://context7.com/js2me/mobx-web-api/llms.txt Illustrates using the `pageVisibility` object to track if the browser tab is active or hidden. It includes examples of pausing operations when hidden and conditionally fetching data. ```typescript import { pageVisibility } from "mobx-web-api"; import { reaction, autorun } from "mobx"; // Direct property access console.log(pageVisibility.isVisible); // true console.log(pageVisibility.isHidden); // false // Pause video/animations when tab is hidden reaction( () => pageVisibility.isVisible, (isVisible) => { if (isVisible) { console.log("User returned - resuming activity"); resumeVideoPlayback(); startPolling(); } else { console.log("User left - pausing activity"); pauseVideoPlayback(); stopPolling(); } } ); // Conditional data fetching autorun(() => { if (pageVisibility.isVisible) { fetchLatestNotifications(); } }); ``` -------------------------------- ### Reactive Media Queries and Sizes with mobx-web-api Source: https://context7.com/js2me/mobx-web-api/llms.txt Shows how to use the `mediaQuery` object for reactive tracking of media queries and document dimensions. It covers accessing various size properties, reacting to window resize, and tracking custom media query strings. ```typescript import { mediaQuery } from "mobx-web-api"; import { reaction, autorun, computed, makeObservable } from "mobx"; // Access various document sizes console.log(mediaQuery.sizes.inner.width); // 1920 (window.innerWidth) console.log(mediaQuery.sizes.inner.height); // 1080 (window.innerHeight) console.log(mediaQuery.sizes.outer.width); // 1920 (window.outerWidth) console.log(mediaQuery.sizes.client.width); // 1905 (document.documentElement.clientWidth) console.log(mediaQuery.sizes.offset.width); // 1905 (document.documentElement.offsetWidth) // React to window resize reaction( () => mediaQuery.sizes.inner.width, (width) => { console.log(`Window width changed to ${width}px`); adjustLayoutForWidth(width); } ); // Track custom media queries const mobileQuery = mediaQuery.track("(max-width: 767px)"); console.log(mobileQuery.matches); // false reaction( () => mobileQuery.matches, (isMobile) => { if (isMobile) { enableMobileNavigation(); } else { enableDesktopNavigation(); } } ); // Shorthand for checking media query matches const isTablet = mediaQuery.match("(min-width: 768px) and (max-width: 1024px)"); console.log(isTablet); // true or false // Create custom responsive breakpoints API const breakpoints = { get isMobile() { return mediaQuery.match("(max-width: 767px)"); }, get isTablet() { return mediaQuery.match("(min-width: 768px) and (max-width: 1024px)"); }, get isDesktop() { return mediaQuery.match("(min-width: 1025px)"); }, get isLargeDesktop() { return mediaQuery.match("(min-width: 1280px)"); } }; autorun(() => { if (breakpoints.isMobile) { console.log("Rendering mobile layout"); } else if (breakpoints.isTablet) { console.log("Rendering tablet layout"); } else { console.log("Rendering desktop layout"); } }); ``` -------------------------------- ### Creating Custom Media Query APIs Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/media-query.md Illustrates how to extend the base mediaQuery object to create custom APIs for common media query breakpoints like mobiles, tablets, and desktops. This allows for more semantic access to media query states. ```typescript import { mediaQuery } from "mobx-web-api"; // referenced to https://gist.github.com/gokulkrishh/242e68d1ee94ad05f488 export const mediaQueries = { ...mediaQuery, get mobiles() { return mediaQuery. match('(max-width: 767px)'); }, get tablets() { return mediaQuery. match('(min-width: 768px) and (max-width: 1024px)'); }, get desktops(){ return mediaQuery. match('(min-width: 1025px)'); }, get largeDesktops() { return mediaQuery. match('(min-width: 1280px)'); } } ... // Usage example if (mediaQueries.mobiles) { // } ``` -------------------------------- ### Accessing and Watching Document Sizes Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/media-query.md Demonstrates how to access various document size properties like inner, outer, client, and offset widths using the mediaQuery utility. It also shows how to use MobX's reaction to observe changes in these sizes and log them to the console. ```typescript import { mediaQuery } from "mobx-web-api"; import { reaction } from "mobx"; console.log(mediaQuery.sizes.inner.width); // 1920 console.log(mediaQuery.sizes.outer.width); // 1920 console.log(mediaQuery.sizes.client.width); // 1905 console.log(mediaQuery.sizes.offset.width); // 1905 reaction( () => mediaQuery.sizes.inner.width, (innerWidth) => { console.log(`window.innerWidth changed to ${innerWidth}px`); } ); ``` -------------------------------- ### Tracking Specific Media Queries Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/media-query.md Demonstrates how to track the matching state of a specific media query, such as '(max-width: 600px)'. It logs whether the screen matches the query and uses a MobX reaction to provide feedback when the matching state changes. ```typescript import { mediaQuery } from "mobx-web-api"; import { reaction } from "mobx"; const smallScreens = mediaQuery.track('(max-width: 600px)'); console.log(smallScreens.matches); // false reaction( () => smallScreens.matches, (matches) => { console.log( matches ? "You are on a small screen" : "You are on a big screen :)" ); } ) ``` -------------------------------- ### Screen Information Reactivity with MobX Source: https://context7.com/js2me/mobx-web-api/llms.txt Provides reactive access to device screen properties like dimensions and orientation. It wraps the Screen API and updates automatically when screen properties change. Dependencies include 'mobx-web-api' and 'mobx'. ```typescript import { screenInfo } from "mobx-webapi"; import { reaction, autorun } from "mobx"; // Access screen properties console.log(screenInfo.width); // 2560 (total screen width) console.log(screenInfo.height); // 1440 (total screen height) console.log(screenInfo.availWidth); // 2560 (available width, excluding taskbar) console.log(screenInfo.availHeight); // 1400 (available height, excluding taskbar) console.log(screenInfo.colorDepth); // 24 console.log(screenInfo.pixelDepth); // 24 // Access orientation info console.log(screenInfo.orientation.type); // "landscape-primary" console.log(screenInfo.orientation.angle); // 0 // React to orientation changes reaction( () => screenInfo.orientation.type, (orientationType) => { console.log(`Orientation changed to: ${orientationType}`); if (orientationType.includes("portrait")) { enablePortraitLayout(); } else { enableLandscapeLayout(); } } ); // React to screen changes (e.g., moving window between monitors) autorun(() => { const { width, height, colorDepth } = screenInfo; console.log(`Screen: ${width}x${height}, ${colorDepth}-bit color`); adjustQualitySettings(colorDepth); }); ``` -------------------------------- ### Import Media Query Utility Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/media-query.md Imports the mediaQuery utility from the mobx-web-api library. This utility is essential for accessing media query related functionalities. ```typescript import { mediaQuery } from "mobx-web-api"; ``` -------------------------------- ### Import Screen Info from MobX Web API Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/screen-info.md Demonstrates how to import the screenInfo object from the mobx-web-api library. This is the initial step to access screen-related functionalities. ```typescript import { screenInfo } from "mobx-web-api"; ``` -------------------------------- ### Preferred Languages Reactivity with MobX Source: https://context7.com/js2me/mobx-web-api/llms.txt Provides reactive access to the user's language preferences, tracking browser settings and responding to changes. It also supports server-side rendering by accepting the Accept-Language header. Dependencies include 'mobx-web-api' and 'mobx'. ```typescript import { preferredLanguages } from "mobx-webapi"; import { reaction, runInAction } from "mobx"; // Access current language preference console.log(preferredLanguages.current); // "en-US" console.log(preferredLanguages.all); // ["en-US", "en", "fr-FR", "fr"] // React to language changes reaction( () => preferredLanguages.current, (language) => { console.log(`Language changed to: ${language}`); loadTranslations(language); updateDocumentLang(language); } ); // React to full language list changes reaction( () => preferredLanguages.all, (languages) => { console.log(`Available languages: ${languages.join(", ")}`); updateLanguagePicker(languages); } ); // Server-side rendering support // Set the Accept-Language header value for SSR hydration runInAction(() => { preferredLanguages.acceptLanguageHeader = "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7"; }); // Now preferredLanguages.current will return "fr-FR" // and preferredLanguages.all will return ["fr-FR", "fr", "en-US", "en"] console.log(preferredLanguages.current); // "fr-FR" ``` -------------------------------- ### Track Network Status with mobx-web-api Source: https://context7.com/js2me/mobx-web-api/llms.txt Demonstrates how to use the `networkStatus` object to reactively track the browser's online/offline status. It shows direct property access and using MobX reactions to respond to connectivity changes. ```typescript import { networkStatus } from "mobx-web-api"; import { reaction, autorun } from "mobx"; // Direct property access console.log(networkStatus.isOnline); // true console.log(networkStatus.isOffline); // false // React to network changes reaction( () => networkStatus.isOnline, (isOnline) => { if (isOnline) { console.log("Connection restored - syncing data..."); syncPendingData(); } else { console.log("Connection lost - switching to offline mode"); enableOfflineMode(); } } ); // Use in computed values or autorun autorun(() => { if (networkStatus.isOffline) { showOfflineBanner(); } else { hideOfflineBanner(); } }); ``` -------------------------------- ### Monitor Media Query and Network Status with MobX Source: https://github.com/js2me/mobx-web-api/blob/master/README.md This snippet demonstrates how to use mobx-web-api to reactively monitor changes in client width from media queries and the offline status of the network. It utilizes MobX's `reaction` function to trigger side effects when these values change. ```typescript import { mediaQuery, networkStatus } from "mobx-web-api"; import { reaction } from "mobx"; reaction( () => mediaQuery.sizes.client.width, (clientWidth) => { console.log(`clientWidth changed to ${clientWidth}px`); } ) reaction( () => networkStatus.isOffline, (isOffline) => { if (isOffline) { console.log('Oh no you are offline :(') } } ) ``` -------------------------------- ### Create and Use Scroll Data with MobX Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/scroll-data.md Demonstrates how to initialize scroll data tracking for an HTML element and use MobX's reaction to observe changes in scroll position. It logs the initial scroll values and sets up a reaction to log updates to `scrollY`. ```typescript import { createScrollData } from "mobx-web-api"; import { reaction } from "mobx"; const scrollContainer = document.getElementById('container'); const scrollData = createScrollData(scrollContainer); console.log(scrollData.scrollY); // 0 console.log(scrollData.scrollX); // 0 console.log(scrollData.scrollHeight); // 2000 reaction( () => scrollData.scrollY, (scrollY) => { console.log(`scrollY changed to ${scrollY}px`); } ); ``` -------------------------------- ### Track Network Status with mobx-web-api Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/network-status.md Demonstrates how to access and react to network status changes using `mobx-web-api`. It shows how to check the current `isOnline` and `isOffline` states and set up a MobX reaction to log status updates. ```typescript import { networkStatus } from "mobx-web-api"; import { reaction } from "mobx"; console.log(networkStatus.isOnline); // true console.log(networkStatus.isOffline); // false reaction( () => networkStatus.isOnline, (isOnline) => { console.log( isOnline ? "You are Online" : "You are Offline :(" ); } ); ``` -------------------------------- ### Watching Client Width Changes Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/media-query.md This snippet shows how to specifically track changes in the client width of the document using MobX reactions. It logs the new client width whenever it changes. ```typescript import { mediaQuery } from "mobx-web-api"; import { reaction } from "mobx"; reaction( () => mediaQuery.sizes.client.width, (clientWidth) => { console.log(`clientWidth changed to ${clientWidth}px`); } ); ``` -------------------------------- ### Screen Information API Source: https://context7.com/js2me/mobx-web-api/llms.txt Provides reactive access to device screen properties including dimensions, color depth, and orientation. Automatically updates when screen properties change. ```APIDOC ## Screen Information API ### Description Provides reactive access to device screen properties including dimensions, color depth, and orientation. It wraps the Screen API and automatically updates when screen properties change (e.g., orientation changes on mobile devices). ### Method N/A (This is a reactive object, not an endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { screenInfo } from "mobx-web-api"; import { reaction, autorun } from "mobx"; // Access screen properties console.log(screenInfo.width); console.log(screenInfo.height); // Access orientation info console.log(screenInfo.orientation.type); // React to orientation changes reaction( () => screenInfo.orientation.type, (orientationType) => { console.log(`Orientation changed to: ${orientationType}`); } ); // React to screen changes autorun(() => { const { width, height, colorDepth } = screenInfo; console.log(`Screen: ${width}x${height}, ${colorDepth}-bit color`); }); ``` ### Response #### Success Response (N/A) - **width** (number) - Total screen width in pixels. - **height** (number) - Total screen height in pixels. - **availWidth** (number) - Available screen width, excluding taskbar/dock. - **availHeight** (number) - Available screen height, excluding taskbar/dock. - **colorDepth** (number) - Color depth of the screen in bits per pixel. - **pixelDepth** (number) - Pixel depth of the screen in bits per pixel. - **orientation** (object) - **type** (string) - The orientation type (e.g., "landscape-primary"). - **angle** (number) - The orientation angle. #### Response Example ```json { "width": 2560, "height": 1440, "availWidth": 2560, "availHeight": 1400, "colorDepth": 24, "pixelDepth": 24, "orientation": { "type": "landscape-primary", "angle": 0 } } ``` ``` -------------------------------- ### Preferred Languages API Source: https://context7.com/js2me/mobx-web-api/llms.txt Provides reactive access to the user's language preferences, tracking browser settings and responding to language change events. Supports SSR via Accept-Language header. ```APIDOC ## Preferred Languages API ### Description Provides reactive access to the user's language preferences. It tracks the browser's language settings and responds to language change events. It also supports server-side rendering by accepting the Accept-Language header value. ### Method N/A (This is a reactive object, not an endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { preferredLanguages } from "mobx-web-api"; import { reaction, runInAction } from "mobx"; // Access current language preference console.log(preferredLanguages.current); console.log(preferredLanguages.all); // React to language changes reaction( () => preferredLanguages.current, (language) => { console.log(`Language changed to: ${language}`); } ); // Server-side rendering support runInAction(() => { preferredLanguages.acceptLanguageHeader = "fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7"; }); console.log(preferredLanguages.current); // "fr-FR" ``` ### Response #### Success Response (N/A) - **current** (string) - The user's most preferred language (e.g., "en-US"). - **all** (array of strings) - An array of all supported language tags, ordered by preference. - **acceptLanguageHeader** (string) - The value of the Accept-Language header (used for SSR). #### Response Example ```json { "current": "en-US", "all": ["en-US", "en", "fr-FR", "fr"], "acceptLanguageHeader": "en-US,en;q=0.9" } ``` ``` -------------------------------- ### Geolocation Access and Reactivity with MobX Source: https://context7.com/js2me/mobx-web-api/llms.txt Provides reactive access to the user's geographic location using the Geolocation API. It tracks permission states and automatically updates position data. The reactive subscription is only active when the position is observed, optimizing resource usage. Dependencies include 'mobx-web-api' and 'mobx'. ```typescript import { geolocation } from "mobx-webapi"; import { reaction, autorun } from "mobx"; // Access current position (triggers permission request if needed) console.log(geolocation.position.coords.latitude); // 51.5074 console.log(geolocation.position.coords.longitude); // -0.1278 console.log(geolocation.position.coords.accuracy); // 65 (meters) console.log(geolocation.position.coords.altitude); // null or number console.log(geolocation.position.coords.speed); // null or number console.log(geolocation.position.timestamp); // 1699876543210 // Check permission state console.log(geolocation.permission.state); // "prompt" | "granted" | "denied" console.log(geolocation.permission.isGranted); // true console.log(geolocation.permission.isDenied); // false console.log(geolocation.permission.isPrompt); // false // React to location changes reaction( () => [ geolocation.position.coords.latitude, geolocation.position.coords.longitude ], ([latitude, longitude]) => { console.log(`New coordinates: ${latitude}, ${longitude}`); updateMapMarker(latitude, longitude); fetchNearbyPlaces(latitude, longitude); } ); // Handle permission changes reaction( () => geolocation.permission.state, (state) => { switch (state) { case "granted": console.log("Location access granted"); enableLocationFeatures(); break; case "denied": console.log("Location access denied"); showLocationDeniedMessage(); break; case "prompt": console.log("Waiting for user permission"); break; } } ); // Retry permission if there was an error if (geolocation.permission.error) { console.error("Permission error:", geolocation.permission.error); await geolocation.permission.retry(); } ``` -------------------------------- ### Usage of Preferred Languages in MobX Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/preferred-languages.md Demonstrates how to use the `preferredLanguages` object in a MobX application. It shows how to access the current and all preferred languages, and how to set up a reaction to log changes in the current language. ```typescript import { preferredLanguages } from "mobx-web-api"; import { reaction } from "mobx"; console.log(preferredLanguages.current); // ru-RU console.log(preferredLanguages.all); // ['ru-RU', 'en-US', 'ru', 'en'] reaction( () => preferredLanguages.current, (currentLanguage) => { console.log( `current language changed to ${currentLanguage}` ); } ); ``` -------------------------------- ### Create Reactive Scroll Data Tracker with TypeScript Source: https://context7.com/js2me/mobx-web-api/llms.txt The `createScrollData` function generates a reactive tracker for an HTML element's scroll and dimension data. It supports custom computed properties via a mapper and responds to scroll and resize events. Dependencies include 'mobx-web-api' and 'mobx'. ```typescript import { createScrollData } from "mobx-web-api"; import { reaction, autorun } from "mobx"; // Basic usage with document body and window scrolling const bodyScrollData = createScrollData(document.body); console.log(bodyScrollData.top); // Element's scrollTop console.log(bodyScrollData.left); // Element's scrollLeft console.log(bodyScrollData.width); // Element's scrollWidth console.log(bodyScrollData.height); // Element's scrollHeight console.log(bodyScrollData.scrollY); // Window's scrollY console.log(bodyScrollData.scrollX); // Window's scrollX console.log(bodyScrollData.scrollHeight); // Window's innerHeight console.log(bodyScrollData.scrollWidth); // Window's innerWidth // React to scroll changes reaction( () => bodyScrollData.scrollY, (scrollY) => { if (scrollY > 100) { showStickyHeader(); } else { hideStickyHeader(); } } ); // Custom scrolling container const container = document.getElementById("scroll-container"); const containerScrollData = createScrollData(container, { scrollingElement: container }); reaction( () => containerScrollData.scrollY, (scrollY) => { console.log(`Container scrolled: ${scrollY}px`); } ); // Advanced usage with mapper for computed properties const advancedScrollData = createScrollData(document.body, { mapper: { scrollProgress(data) { const maxScroll = data.height - data.scrollHeight; return maxScroll > 0 ? data.scrollY / maxScroll : 0; }, isNearBottom(data) { return data.scrollY + data.scrollHeight >= data.height - 100; }, isAtTop(data) { return data.scrollY === 0; } } }); // React to scroll progress reaction( () => advancedScrollData.scrollProgress, (progress) => { updateProgressBar(progress * 100); console.log(`Read progress: ${(progress * 100).toFixed(1)}%`); } ); // Infinite scroll implementation reaction( () => advancedScrollData.isNearBottom, (isNearBottom) => { if (isNearBottom) { console.log("Loading more content..."); loadMoreItems(); } } ); // Back-to-top button visibility autorun(() => { if (advancedScrollData.isAtTop) { hideBackToTopButton(); } else { showBackToTopButton(); } }); ``` -------------------------------- ### Track Window Focus/Blur with MobX Page Visibility Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/page-visibility.md This snippet demonstrates how to import and use the `pageVisibility` object from `mobx-web-api` to track the visibility state of the browser window. It shows how to access the `isVisible` and `isHidden` properties directly and how to use MobX's `reaction` to log changes in visibility. ```typescript import { pageVisibility } from "mobx-web-api"; import { reaction } from "mobx"; console.log(pageVisibility.isVisible); // true console.log(pageVisibility.isHidden); // false reaction( () => pageVisibility.isVisible, (isVisible) => { console.log( isVisible ? "User is on page" : "User is out of page :(" ); } ); ``` -------------------------------- ### Import Geolocation Module (TypeScript) Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/geolocation.md Imports the geolocation module from the mobx-web-api library. This is the initial step to enable geolocation tracking. ```typescript import { geolocation } from "mobx-web-api"; ``` -------------------------------- ### Track Geolocation Coordinates (TypeScript) Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/geolocation.md Demonstrates how to use MobX's reaction to track changes in geolocation coordinates (latitude and longitude). It logs the updated coordinates to the console whenever they change. This requires the 'mobx' library for the reaction function. ```typescript import { reaction } from 'mobx'; import { geolocation } from 'mobx-web-api'; reaction( () => [ geolocation.position.coords.latitude, geolocation.position.coords.longitude ], ([latitude, longitude]) => { console.log(`coords: ${latitude}, ${longitude}`); } ) ``` -------------------------------- ### Import Preferred Languages from MobX Web API Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/preferred-languages.md This snippet shows the basic import statement for the `preferredLanguages` utility from the 'mobx-web-api' library. It's the first step to utilize its functionality. ```typescript import { preferredLanguages } from "mobx-web-api"; ``` -------------------------------- ### Scroll Data with MobX Ref for Element Reference Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/scroll-data.md Shows how to use `createScrollData` with a MobX `Ref` object to manage the reference to an HTML element. This is useful for scenarios where the element might not be immediately available on component mount. ```typescript import { createScrollData } from "mobx-web-api"; import { createRef } from "yummies/mobx"; import { reaction } from "mobx"; const elementRef = createRef(); const scrollData = createScrollData(elementRef); // Later, when element is mounted elementRef.current = document.getElementById('my-element'); reaction( () => scrollData.scrollY, (scrollY) => { console.log(`Scrolled: ${scrollY}px`); } ); ``` -------------------------------- ### Import Network Status from mobx-web-api Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/network-status.md Imports the `networkStatus` object from the `mobx-web-api` library. This object provides reactive properties to track the network connection state. ```typescript import { networkStatus } from "mobx-web-api"; ``` -------------------------------- ### Import createScrollData from mobx-web-api Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/scroll-data.md This snippet shows the basic import statement required to use the createScrollData function from the mobx-web-api library. It's a prerequisite for utilizing any of the scroll tracking functionalities. ```typescript import { createScrollData } from "mobx-web-api"; ``` -------------------------------- ### Geolocation API Source: https://context7.com/js2me/mobx-web-api/llms.txt Provides reactive access to the user's geographic location, including permission state tracking. Updates automatically when the device moves, and subscriptions are only active when observed. ```APIDOC ## Geolocation API ### Description Provides reactive access to the user's geographic location, wrapping the Geolocation API and including permission state tracking. Position data updates automatically when the device moves, and the reactive subscription is only active when the position is being observed. ### Method N/A (This is a reactive object, not an endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { geolocation } from "mobx-web-api"; import { reaction } from "mobx"; // Access current position console.log(geolocation.position.coords.latitude); console.log(geolocation.position.coords.longitude); // Check permission state console.log(geolocation.permission.state); // React to location changes reaction( () => [ geolocation.position.coords.latitude, geolocation.position.coords.longitude ], ([latitude, longitude]) => { console.log(`New coordinates: ${latitude}, ${longitude}`); } ); // Handle permission changes reaction( () => geolocation.permission.state, (state) => { console.log(`Permission state changed to: ${state}`); } ); // Retry permission if there was an error if (geolocation.permission.error) { await geolocation.permission.retry(); } ``` ### Response #### Success Response (N/A) - **position** (object) - Reactive object containing position data. - **coords** (object) - **latitude** (number) - Latitude of the device. - **longitude** (number) - Longitude of the device. - **accuracy** (number) - Accuracy of the position in meters. - **altitude** (number | null) - Altitude of the device in meters. - **speed** (number | null) - Speed of the device in meters per second. - **timestamp** (number) - Timestamp of the position data in milliseconds. - **permission** (object) - Reactive object containing permission state. - **state** (string) - Current permission state: "prompt", "granted", or "denied". - **isGranted** (boolean) - True if permission is granted. - **isDenied** (boolean) - True if permission is denied. - **isPrompt** (boolean) - True if permission is in prompt state. - **error** (Error | null) - Any error encountered during permission request. #### Response Example ```json { "position": { "coords": { "latitude": 51.5074, "longitude": -0.1278, "accuracy": 65, "altitude": null, "speed": null }, "timestamp": 1699876543210 }, "permission": { "state": "granted", "isGranted": true, "isDenied": false, "isPrompt": false, "error": null } } ``` ``` -------------------------------- ### createScrollData Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/scroll-data.md Initializes and returns a reactive object for tracking scroll data of a given HTML element. ```APIDOC ## createScrollData ### Description Initializes and returns a reactive object for tracking scroll data of a given HTML element. It utilizes browser APIs like `scrollTop`, `scrollLeft`, `scrollY`, `scrollX`, and listens to scroll and resize events. ### Method `createScrollData(element: HTMLElement | Ref, opts?: { scrollingElement?: Window | HTMLElement | Ref, mapper?: ScrollDataMapperConfig })` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### `element` (HTMLElement | Ref) - Required The HTML element to track scroll data for. Can be a direct reference to an HTMLElement or a Ref object. #### `opts` (object) - Optional Optional configuration object: - **`scrollingElement`** (Window | HTMLElement | Ref) - The element or window that triggers scroll events. Defaults to `window`. Can be a direct reference or a Ref object. - **`mapper`** (ScrollDataMapperConfig) - An object with custom computed properties. Each key becomes a property on the returned scroll data object, and the value is a function that receives the internal scroll data and returns the computed value. ### Properties The returned object contains the following reactive properties: - **`top`** (number) - The scroll position from the top of the element (`element.scrollTop`). - **`left`** (number) - The scroll position from the left of the element (`element.scrollLeft`). - **`width`** (number) - The total scrollable width of the element (`element.scrollWidth`). - **`height`** (number) - The total scrollable height of the element (`element.scrollHeight`). - **`scrollY`** (number) - The vertical scroll position of the scrolling element. For `window`, this is `window.scrollY`. For other elements, this is `element.scrollTop`. - **`scrollX`** (number) - The horizontal scroll position of the scrolling element. For `window`, this is `window.scrollX`. For other elements, this is `element.scrollLeft`. - **`scrollHeight`** (number) - The total scrollable height of the scrolling element. For `window`, this is `window.innerHeight`. For other elements, this is `element.scrollHeight`. - **`scrollWidth`** (number) - The total scrollable width of the scrolling element. For `window`, this is `window.innerWidth`. For other elements, this is `element.scrollWidth`. ### Request Example ```javascript import { createScrollData } from "mobx-web-api"; import { reaction } from "mobx"; const scrollContainer = document.getElementById('container'); const scrollData = createScrollData(scrollContainer); console.log(scrollData.scrollY); // 0 console.log(scrollData.scrollX); // 0 console.log(scrollData.scrollHeight); // 2000 reaction( () => scrollData.scrollY, (scrollY) => { console.log(`scrollY changed to ${scrollY}px`); } ); ``` ### Response #### Success Response (200) Returns a reactive object with scroll data properties. #### Response Example ```json { "top": 50, "left": 0, "width": 1000, "height": 2000, "scrollY": 50, "scrollX": 0, "scrollHeight": 2000, "scrollWidth": 1000 } ``` ``` -------------------------------- ### Set Accept-Language Header for SSR Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/preferred-languages.md Illustrates how to set the `acceptLanguageHeader` property of `preferredLanguages` within a MobX action. This is particularly useful for server-side rendering (SSR) to align client-side language preferences with server responses. ```typescript import { runInAction } from "mobx"; import { preferredLanguages } from "mobx-web-api"; // Assuming 'request' is available in the scope, e.g., from an Express.js request object // const request = { headers: { 'Accept-Language': 'en-US,en;q=0.9' } }; runInAction(() => { preferredLanguages.acceptLanguageHeader = request.headers['Accept-Language']; }) ``` -------------------------------- ### Scroll Data with Custom Computed Properties (Mapper) Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/scroll-data.md Demonstrates using the `mapper` option in `createScrollData` to define custom reactive properties like `scrollProgress` and `isNearBottom`. It logs these computed values using MobX reactions. ```typescript import { createScrollData } from "mobx-web-api"; import { reaction } from "mobx"; const scrollData = createScrollData(document.body, { mapper: { scrollProgress() { const { scrollY, scrollHeight } = this; return scrollHeight > 0 ? scrollY / scrollHeight : 0; }, isNearBottom() { const { scrollY, scrollHeight, height } = this; return scrollY + height >= scrollHeight - 100; } } }); reaction( () => scrollData.scrollProgress, (progress) => { console.log(`Scroll progress: ${(progress * 100).toFixed(2)}%`); } ); reaction( () => scrollData.isNearBottom, (isNearBottom) => { if (isNearBottom) { console.log("Near bottom, load more content"); } } ); ``` -------------------------------- ### Scroll Tracking with a Custom Scrolling Element Source: https://github.com/js2me/mobx-web-api/blob/master/docs/apis/scroll-data.md Illustrates how to configure `createScrollData` to track scroll events on a specific HTML element (e.g., a div with id 'scroll-container') rather than the global window. It logs the scrollY value of the custom element. ```typescript import { createScrollData } from "mobx-web-api"; import { reaction } from "mobx"; const container = document.getElementById('scroll-container'); const scrollData = createScrollData(container, { scrollingElement: container }); reaction( () => scrollData.scrollY, (scrollY) => { console.log(`Container scrolled: ${scrollY}px`); } ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.