### Install and Start Application Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md Run these commands to install dependencies and start the development server. ```bash pnpm install pnpm start ``` -------------------------------- ### Setup React-Query Client and Provider Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md Initialize a QueryClient and wrap your application with QueryClientProvider in main.tsx. ```tsx import { QueryClient, QueryClientProvider } from '@tanstack/react-query' // ... const queryClient = new QueryClient() // ... if (!rootElement.innerHTML) { const root = ReactDOM.createRoot(rootElement) root.render( , ) } ``` -------------------------------- ### Install React-Query Dependencies Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md Add React-Query and its devtools to your project using pnpm. ```bash pnpm add @tanstack/react-query @tanstack/react-query-devtools ``` -------------------------------- ### Install TanStack Store Dependency Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md Add TanStack Store to your project dependencies using pnpm. ```bash pnpm add @tanstack/store ``` -------------------------------- ### Fetch Data with useQuery Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md Example of fetching data from an API using the `useQuery` hook in a React component. ```tsx import { useQuery } from '@tanstack/react-query' import './App.css' function App() { const { data } = useQuery({ queryKey: ['people'], queryFn: () => fetch('https://swapi.dev/api/people') .then((res) => res.json()) .then((data) => data.results as { name: string }[]), initialData: [], }) return (
) } export default App ``` -------------------------------- ### Get Available Size Options Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Determines which size properties (rendered, gzip, brotli) are available based on the provided options object. 'renderedLength' is always included. ```javascript const getAvailableSizeOptions = (options) => { const availableSizeProperties = ["renderedLength"]; if (options.gzip) { availableSizeProperties.push("gzipLength"); } if (options.brotli) { availableSizeProperties.push("brotliLength"); } return availableSizeProperties; }; ``` -------------------------------- ### Derive State with TanStack Store Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md Example of creating a derived store that automatically updates based on changes in a base store. ```tsx import { useStore } from '@tanstack/react-store' import { Store, Derived } from '@tanstack/store' import './App.css' const countStore = new Store(0) const doubledStore = new Derived({ fn: () => countStore.state * 2, deps: [countStore], }) doubledStore.mount() function App() { const count = useStore(countStore) const doubledCount = useStore(doubledStore) return (
Doubled - {doubledCount}
) } export default App ``` -------------------------------- ### React Component Initialization Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Initializes React component state and lifecycle hooks. This snippet appears to be part of a larger React component setup, likely handling component mounting and updates. ```javascript var t,r,u,i,o=0,f=[],c=l$1,e=c.__b,a=c.__r,v=c.diffed,l=c.__c,m=c.unmount,s=c.__;function p(n,t){c.__h&&c.__h(r,n,o||t),o=0;var u=r.__H|| ``` -------------------------------- ### Build Application for Production Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md Execute this command to create a production-ready build of the application. ```bash pnpm build ``` -------------------------------- ### Setting Up Web3Provider with NexusProvider Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt This component wraps the entire application with necessary providers including Wagmi, ConnectKit, and NexusProvider. Ensure your WalletConnect project ID is set in your environment variables. ```tsx import { NexusProvider } from '@avail-project/nexus-widgets' import { createConfig, WagmiProvider } from 'wagmi' import { defineChain } from 'viem' import { base, polygon, arbitrum, optimism, mainnet } from 'wagmi/chains' import { ConnectKitProvider, getDefaultConfig } from 'connectkit' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' const config = createConfig( getDefaultConfig({ appName: 'Avail Nexus', walletConnectProjectId: process.env.VITE_WALLETCONNECT_PROJECT_ID!, multiInjectedProviderDiscovery: true, chains: [mainnet, base, polygon, arbitrum, optimism], }), ) const queryClient = new QueryClient() const Web3Provider = ({ children }: { children: React.ReactNode }) => ( {children} ) export default Web3Provider ``` -------------------------------- ### Initialize and Manage Nexus SDK with useNexus Hook Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt Use the `useNexus` hook to access the SDK instance, manage its initialization state, and control the provider. It's essential for integrating the SDK into your application's lifecycle, especially for wallet connections and disconnections. ```tsx // src/components/connect-wallet.tsx import { useNexus, type EthereumProvider } from '@avail-project/nexus-widgets' import { useAccount, useWalletClient } from 'wagmi' import { useEffect } from 'react' function WalletConnection() { const { setProvider, provider, isSdkInitialized, deinitializeSdk, initializeSdk, sdk } = useNexus() const { status } = useAccount() const { data: walletClient } = useWalletClient() useEffect(() => { // Inject EIP-1193 provider when wallet connects if (!provider && status === 'connected' && walletClient) { const ethProvider: EthereumProvider = { request: (args: unknown) => walletClient.request(args as any), } setProvider(ethProvider) } // Clean up SDK when wallet disconnects if (isSdkInitialized && provider && status === 'disconnected') { deinitializeSdk() } }, [status, provider, isSdkInitialized]) // Lazily initialize the SDK on user demand const handleInit = async () => { if (!isSdkInitialized) { try { await initializeSdk() console.log('SDK initialized. Instance:', sdk) } catch (err) { console.error('SDK init failed:', err) } } } return } ``` -------------------------------- ### Query Supported Chains and Tokens with sdk.utils Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt Utilize the `sdk.utils` namespace to programmatically discover supported chains and tokens for bridging and swapping operations. This is useful for dynamically configuring UI elements or validating user selections. ```typescript import { useNexus } from '@avail-project/nexus-widgets' function SupportedChainsList() { const { sdk } = useNexus() const logSupportedData = () => { // Returns array of supported chain IDs/metadata const chains = sdk?.utils?.getSupportedChains() console.log('Supported chains:', chains) // e.g. [{ id: 8453, name: 'Base' }, { id: 42161, name: 'Arbitrum' }, ...] // Returns a map of chainId → supported token symbols for swaps const swapTokens = sdk?.utils?.getSwapSupportedChainsAndTokens() console.log('Swap supported tokens by chain:', swapTokens) // e.g. { 8453: ['USDC', 'ETH'], 42161: ['USDC', 'USDT', 'ETH'], ... } } return } ``` -------------------------------- ### Get Module IDs from Cache Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Retrieves module IDs from a cache. This is a utility function for accessing cached module identifiers. ```javascript const getModuleIds = (node) => nodeIdsCache.get(node); ``` -------------------------------- ### Create a Simple Counter with TanStack Store Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md Demonstrates creating a basic counter store and using it in a React component with the `useStore` hook. ```tsx import { useStore } from '@tanstack/react-store' import { Store } from '@tanstack/store' import './App.css' const countStore = new Store(0) function App() { const count = useStore(countStore) return (
) } export default App ``` -------------------------------- ### picomatch.toRegex Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Creates a regular expression directly from a glob pattern string. This is a convenient way to get a RegExp object for matching. ```APIDOC ## picomatch.toRegex(source, options) ### Description Creates a regular expression from the given regex source string. This is a convenient way to get a RegExp object for matching. ### Parameters #### Path Parameters - **source** (String) - Required - Regular expression source string. - **options** (Object) - Optional - Configuration options for the RegExp constructor, such as flags. ### Request Example ```js const picomatch = require('picomatch'); const { output } = picomatch.parse('*.js'); console.log(picomatch.toRegex(output)); //=> /^(?:(?!\.)(?=.)[^/]*\.js)$/ ``` ### Response #### Success Response (RegExp) - **RegExp** - A regular expression object created from the given source string. #### Response Example ```js /^(?:(?!\.)(?=.)[^/]*\.js)$/ ``` ``` -------------------------------- ### formatTrim Function Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Trims insignificant zeros from a formatted number string, for example, converting '1.2000k' to '1.2k'. Useful for cleaning up SI-prefixed numbers. ```javascript function formatTrim(s) { out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) { switch (s[i]) { case ".": i0 = i1 = i; break; case "0": if (i0 === 0) i0 = i; i1 = i; break; default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break; } } return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s; } ``` -------------------------------- ### Run Tests with Vitest Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md Use this command to execute the test suite powered by Vitest. ```bash pnpm test ``` -------------------------------- ### Tick Specification Calculation Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Calculates tick specifications for generating axis ticks, considering start, stop, and desired count. Handles logarithmic scales. ```javascript const e10 = Math.sqrt(50), e5 = Math.sqrt(10), e2 = Math.sqrt(2); function tickSpec(start, stop, count) { const step = (stop - start) / Math.max(0, count), power = Math.floor(Math.log10(step)), error = step / Math.pow(10, power), factor = error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1; let i1, i2, inc; if (power < 0) { inc = Math.pow(10, -power) / factor; i1 = Math.round(start * inc); i2 = Math.round(stop ``` -------------------------------- ### Tooltip for Compressed Byte Size Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Displays a tooltip explaining 'gzipLength' and 'brotliLength'. These values represent the byte size of an individual file after transformations, tree-shaking, and compression. ```jsx const COMPRESSED = (u$1("span", { children: [u$1("b", { children: LABELS.gzipLength }), " and ", u$1("b", { children: LABELS.brotliLength }), " is a byte size of individual file after individual transformations,", u$1("br", {}), " treeshake and compression."] })); ``` -------------------------------- ### Load Route Data Before Rendering Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md Utilize the 'loader' functionality in TanStack Router to fetch data for a route before it is rendered. This example fetches people data from an API. ```tsx const peopleRoute = createRoute({ getParentRoute: () => rootRoute, path: '/people', loader: async () => { const response = await fetch('https://swapi.dev/api/people') return response.json() as Promise<{ results: { name: string }[] }> // Added type assertion for clarity }, component: () => { const data = peopleRoute.useLoaderData() return ( ) }, }) ``` -------------------------------- ### Module Initialization and State Management Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Internal module logic for managing component updates, subscriptions, and lifecycle methods. It handles component mounting, diffing, and unmounting. ```javascript (r.__H={__:[],__h:[]});return n>=u.__.length&&u.__.push({}),u.__[n]}function d(n){return o=1,h(D,n)}function h(n,u,i){var o=p(t++,2);if(o.t=n,!o.__c&&(o.__=[D(void 0,u),function(n){var t=o.__N?o.__N[0]:o.__[0],r=o.t(t,n);t!==r&&(o.__N=[r,o.__[1]],o.__c.setState({}));}],o.__c=r,!r.__f)){var f=function(n,t,r){if(!o.__c.__H)return true;var u=o.__c.__H.__.filter(function(n){return !!n.__c});if(u.every(function(n){return !n.__N}))return !c||c.call(this,n,t,r);var i=o.__c.props!==n;return u.forEach(function(n){if(n.__N){var t=n.__[0];n.__=n.__N,n.__N=void 0,t!==n.__[0]&&(i=true);}}),c&&c.call(this,n,t,r)||i};r.__f=true;var c=r.shouldComponentUpdate,e=r.componentWillUpdate;r.componentWillUpdate=function(n,t,r){if(this.__e){var u=c;c=void 0,f(n,t,r),c=u;}e&&e.call(this,n,t,r);},r.shouldComponentUpdate=f;}return o.__N||o.__}function y(n,u){var i=p(t++,3);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__H.__h.push(i));}function _(n,u){var i=p(t++,4);!c.__s&&C(i.__H,u)&&(i.__=n,i.u=u,r.__h.push(i));}function A(n){return o=5,T(function(){return {current:n}},[])}function T(n,r){var u=p(t++,7);return C(u.__H,r)&&(u.__=n(),u.__H=r,u.__h=n),u.__}function q(n,t){return o=8,T(function(){return n},t)}function x(n){var u=r.context[n.__c],i=p(t++,9);return i.c=n,u?(null==i.__&&(i.__=true,u.sub(r)),u.props.value):n.__}function j(){for(var n;n=f.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(z),n.__H.__h.forEach(B),n.__H.__h=[]}catch(t){n.__H.__h=[],c.__e(t,n.__v);}}c.__b=function(n){r=null,e&&e(n);},c.__=function(n,t){n&&t.__k&&t.__k.__m&&(n.__m=t.__k.__m),s&&s(n,t);},c.__r=function(n){a&&a(n),t=0;var i=(r=n.__c).__H;i&&(u===r?(i.__h=[],r.__h=[],i.__.forEach(function(n){n.__N&&(n.__=n.__N),n.u=n.__N=void 0;})):(i.__h.forEach(z),i.__h.forEach(B),i.__h=[],t=0)),u=r;},c.diffed=function(n){v&&v(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(1!==f.push(t)&&i===c.requestAnimationFrame||((i=c.requestAnimationFrame)||w)(j)),t.__H.__.forEach(function(n){n.u&&(n.__H=n.u),n.u=void 0;})),u=r=null;},c.__c=function(n,t){t.some(function(n){try{n.__h.forEach(z),n.__h=n.__h.filter(function(n){return !n.__||B(n)});}catch(r){t.some(function(n){n.__h&&(n.__h=[]);}),t=[],c.__e(r,n.__v);}}),l&&l(n,t);},c.unmount=function(n){m&&m(n);var t,r=n.__c;r&&r.__H&&(r.__H.__.forEach(function(n){try{z(n);}catch(n){t=n;}}),r.__H=void 0,t&&c.__e(t,r.__v));};var k="function"==typeof requestAnimationFrame;function w(n){var t,r=function(){clearTimeout(u),k&&cancelAnimationFrame(t),setTimeout(n);},u=setTimeout(r,35);k&&(t=requestAnimationFrame(r));}function z(n){var t=r,u=n.__c;"function"==typeof u&&(n.__c=void 0,u()),r=t;}function B(n){var t=r;n.__c=n.__(),r=t;}function C(n,t){return !n||n.length!==t.length||t.some(function(t,r){return t!==n[r]})}function D(n,t){return "function"==typeof t?t(n):t} ``` -------------------------------- ### Render Main Component with Context Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Renders the main application component, providing a static context with various data and utility functions. This sets up the application's state for rendering. ```javascript E(u$1(StaticContext.Provider, { value: { data, availableSizeProperties, width, height, getModuleSize, getModuleIds, getModuleColor, rawHierarchy, layout, }, children: u$1(Main, {}) }), parentNode); ``` -------------------------------- ### Initialize Treemap Layout Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Sets up a treemap layout with specified dimensions, padding, and tiling algorithm. This is used for hierarchical data visualization. ```javascript const layout = treemap() .size([width, height]) .paddingOuter(PADDING) .paddingTop(TOP_PADDING) .paddingInner(PADDING) .round(true) .tile(treemapResquarify); ``` -------------------------------- ### Create a Context Provider/Consumer Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Defines a React-like Context API with Provider and Consumer components. The Provider manages context value and notifies subscribers of changes. The Consumer accesses the context value via a render prop. ```javascript function K(n){function l(n){var u,t;return this.getChildContext||(u=new Set,(t={})[l.__c]=this,this.getChildContext=function(){return t},this.componentWillUnmount=function(){u=null;},this.shouldComponentUpdate=function(n){this.props.value!=n.value&&u.forEach(function(n){n.__e=true,M(n);});},this.sub=function(n){u.add(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u&&u.delete(n),l&&l.call(n);};}),n.children}return l.__c="__cC"+h$1++,l.__=n,l.Provider=l.__l=(l.Consumer=function(n,l){return n.children(l)}).contextType=l,l} ``` -------------------------------- ### Create a Root Layout with Header and Navigation Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md Define a root route component that includes a header with navigation links and an outlet for child routes. Includes TanStack Router Devtools. ```tsx import { Outlet, createRootRoute } from '@tanstack/react-router' import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' import { Link } from '@tanstack/react-router' export const Route = createRootRoute({ component: () => ( <>
), }) ``` -------------------------------- ### Lint, Format, and Check Code Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/README.md These scripts help maintain code quality using ESLint and Prettier. ```bash pnpm lint pnpm format pnpm check ``` -------------------------------- ### Configuring NexusProvider Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt The `NexusProvider` component from `@avail-project/nexus-widgets` must wrap all components utilizing Nexus hooks or widget buttons. Configure the SDK's network and debug mode via the `config` prop. ```tsx import { NexusProvider } from '@avail-project/nexus-widgets' // Minimal setup inside your provider tree {children} ``` -------------------------------- ### sdk.utils Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt Provides utility methods for querying supported chains and tokens within the Nexus SDK. ```APIDOC ## `sdk.utils` — Query Supported Chains and Tokens The `sdk.utils` namespace exposes utility methods to discover which chains and tokens are supported for bridging and swapping. ### Usage ```tsx import { useNexus } from '@avail-project/nexus-widgets' function SupportedChainsList() { const { sdk } = useNexus() const logSupportedData = () => { // Returns array of supported chain IDs/metadata const chains = sdk?.utils?.getSupportedChains() console.log('Supported chains:', chains) // e.g. [{ id: 8453, name: 'Base' }, { id: 42161, name: 'Arbitrum' }, ...] // Returns a map of chainId → supported token symbols for swaps const swapTokens = sdk?.utils?.getSwapSupportedChainsAndTokens() console.log('Swap supported tokens by chain:', swapTokens) // e.g. { 8453: ['USDC', 'ETH'], 42161: ['USDC', 'USDT', 'ETH'], ... } } return } ``` ### Methods in `sdk.utils` - **`getSupportedChains()`**: Returns an array of supported chain objects, each containing `id` and `name`. - **`getSwapSupportedChainsAndTokens()`**: Returns a map where keys are chain IDs and values are arrays of token symbols supported for swaps on that chain. ``` -------------------------------- ### Fetch Unified User Balances with sdk.getUnifiedBalances() Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt After initializing the SDK, call `sdk.getUnifiedBalances()` to retrieve an aggregated list of the user's token holdings across all supported chains. This function returns a `UserAsset[]` array, useful for displaying a consolidated view of a user's assets. ```tsx // src/components/view-balance.tsx import { useNexus, CHAIN_METADATA, SUPPORTED_CHAINS } from '@avail-project/nexus-widgets' import type { UserAsset } from '@avail-project/nexus-widgets' import { useState } from 'react' function ViewUnifiedBalance() { const { isSdkInitialized, sdk, initializeSdk } = useNexus() const [balances, setBalances] = useState() const fetchBalance = async () => { if (!isSdkInitialized) await initializeSdk() const result = await sdk?.getUnifiedBalances() // result example: // [ // { // symbol: 'USDC', // balance: '250.500000', // balanceInFiat: 250.5, // icon: 'https://...', // breakdown: [ // { chain: { id: 8453, name: 'Base' }, balance: '100.0', balanceInFiat: 100.0, decimals: 6 }, // { chain: { id: 42161, name: 'Arbitrum' }, balance: '150.5', balanceInFiat: 150.5, decimals: 6 }, // ] // } // ] setBalances(result) } const totalFiat = balances ?.reduce((acc, asset) => acc + asset.balanceInFiat, 0) .toFixed(2) return (
{balances && (
    {balances .filter((t) => parseFloat(t.balance) > 0) .map((token) => (
  • {token.symbol}: {parseFloat(token.balance).toFixed(6)} (${token.balanceInFiat.toFixed(2)})
      {token.breakdown .filter((c) => parseFloat(c.balance) > 0) .map((chain) => (
    • {chain.chain.name}: {chain.balance} — ${chain.balanceInFiat.toFixed(2)} {/* Display chain logo using CHAIN_METADATA */} {chain.chain.name}
    • ))}
  • ))}
  • Total: ${totalFiat}
)}
) } ``` -------------------------------- ### useNexus Hook Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt The `useNexus` hook provides access to the Nexus SDK instance, its initialization state, and provider control. It's the main interface for programmatic SDK interaction. ```APIDOC ## `useNexus` Hook — SDK Lifecycle Management `useNexus` exposes the Nexus SDK instance, initialization state, and provider control. It is the primary hook for interacting with the SDK programmatically. ### Usage ```tsx import { useNexus, type EthereumProvider } from '@avail-project/nexus-widgets' import { useAccount, useWalletClient } from 'wagmi' import { useEffect } from 'react' function WalletConnection() { const { setProvider, provider, isSdkInitialized, deinitializeSdk, initializeSdk, sdk } = useNexus() const { status } = useAccount() const { data: walletClient } = useWalletClient() useEffect(() => { // Inject EIP-1193 provider when wallet connects if (!provider && status === 'connected' && walletClient) { const ethProvider: EthereumProvider = { request: (args: unknown) => walletClient.request(args as any), } setProvider(ethProvider) } // Clean up SDK when wallet disconnects if (isSdkInitialized && provider && status === 'disconnected') { deinitializeSdk() } }, [status, provider, isSdkInitialized]) // Lazily initialize the SDK on user demand const handleInit = async () => { if (!isSdkInitialized) { try { await initializeSdk() console.log('SDK initialized. Instance:', sdk) } catch (err) { console.error('SDK init failed:', err) } } } return } ``` ### Methods Exposed by `useNexus` - **`setProvider(provider: EthereumProvider)`**: Sets the Ethereum provider for the SDK. - **`provider`**: The current Ethereum provider instance. - **`isSdkInitialized`**: Boolean indicating if the SDK has been initialized. - **`deinitializeSdk()`**: Function to deinitialize the SDK. - **`initializeSdk()`**: Function to initialize the SDK. - **`sdk`**: The Nexus SDK instance. ``` -------------------------------- ### Define Constructor and Prototype Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Defines a constructor, its factory, and prototype, establishing the inheritance chain. ```javascript function define(constructor, factory, prototype) { constructor.prototype = factory.prototype = prototype; prototype.constructor = constructor; } ``` -------------------------------- ### Open On-Chain Token Swap Interface with SwapButton Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt Use SwapButton to open the Nexus swap interface for exchanging tokens on supported chains. Note that swap functionality is currently in beta. Ensure the SDK is initialized before proceeding. ```tsx import { SwapButton, useNexus } from '@avail-project/nexus-widgets' import { useState } from 'react' function SwapWidget() { const { initializeSdk, isSdkInitialized } = useNexus() const [loading, setLoading] = useState(false) const handleClick = async (onClick: () => void) => { if (!isSdkInitialized) { setLoading(true) await initializeSdk().finally(() => setLoading(false)) } onClick() } return ( {({ onClick, isLoading }) => ( )} ) } ``` -------------------------------- ### Picomatch Main Function Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html The main picomatch function for matching strings against glob patterns. It automatically detects the operating system for Windows-specific path handling if not explicitly provided. ```javascript function picomatch(glob, options, returnState = false) { // default to os.platform() if if (options && (options.windows === null || options.windows === undefined)) { // don't mutate the original options object options = { ...options, windows: utils.isWindows() }; } return pico(glob, options, returnState); } ``` -------------------------------- ### Implement Network Switching with useWeb3Context Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt Use the useWeb3Context hook to access and modify the current network ('mainnet' or 'testnet') within your application, enabling dynamic network toggling. ```tsx // src/providers/Web3Provider.tsx import { createContext, useContext, useMemo, useState } from 'react' import type { NexusNetwork } from '@avail-project/nexus-widgets' const Web3Context = createContext<{ network: NexusNetwork setNetwork: React.Dispatch> } | null>(null) export function useWeb3Context() { const context = useContext(Web3Context) if (!context) throw new Error('useWeb3Context must be used within a Web3Provider') return context } // Usage in a network toggle component: function NetworkToggle() { const { network, setNetwork } = useWeb3Context() return ( ) } ``` -------------------------------- ### CSS Variables and Basic Styling Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Defines CSS variables for theming and sets up basic box-sizing and body styles for the application. Ensures consistent styling across different elements. ```css :root { --font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; --background-color: #2b2d42; --text-color: #edf2f4; } html { box-sizing: border-box; } *, *:before, *:after { box-sizing: inherit; } html { background-color: var(--background-color); color: var(--text-color); font-family: var(--font-family); } body { padding: 0; margin: 0; } html, body { height: 100%; width: 100%; overflow: hidden; } body { display: flex; flex-direction: column; } svg { vertical-align: middle; width: 100%; height: 100%; max-height: 100vh; } main { flex-grow: 1; height: 100vh; padding: 20px; } .tooltip { position: absolute; z-index: 1070; border: 2px solid; border-radius: 5px; padding: 5px; font-size: 0.875rem; background-color: var(--background-color); color: var(--text-color); } .tooltip-hidden { visibility: hidden; opacity: 0; } .sidebar { position: fixed; top: 0; left: 0; right: 0; display: flex; flex-direction: row; font-size: 0.7rem; align-items: center; margin: 0 50px; height: 20px; } .size-selectors { display: flex; flex-direction: row; align-items: center; } .size-selector { display: flex; flex-direction: row; align-items: center; justify-content: center; margin-right: 1rem; } .size-selector input { margin: 0 0.3rem 0 0; } .filters { flex: 1; display: flex; flex-direction: row; align-items: center; } .module-filters { display: flex; flex-grow: 1; } .module-filter { display: flex; flex-direction: row; align-items: center; justify-content: center; flex: 1; } .module-filter input { flex: 1; height: 1rem; padding: 0.01rem; font-size: 0.7rem; margin-left: 0.3rem; } .module-filter + .module-filter { margin-left: 0.5rem; } .node { cursor: pointer; } ``` -------------------------------- ### Color Constructor and Utilities Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Defines a Color constructor and associated utility functions for color manipulation and formatting. Includes regex for parsing various color formats. ```javascript function Color() {} ``` ```javascript var darker = 0.7; var brighter = 1 / darker; var reI = "\\s*(\[+-\]?\\d+)\\s*", reN = "\\s*(\[+-\]?(?:\\d*\\.)?\\d+(?:[eE][+-\]?\d+)?)\\s*", reP = "\\s*(\[+-\]?(?:\\d*\\.)?\\d+(?:[eE][+-\]?\d+)?)\\s*", reHex = /^#([0-9a-f]{3,8})$/, reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`), reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`), reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`), reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`), reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`), reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`); ``` ```javascript var named = { aliceblue: 0xf0f8ff, antiquewhite: 0xfaebd7, aqua: 0x00ffff, aquamarine: 0x7fffd4, azure: 0xf0ffff, beige: 0xf5f5dc, bisque: 0xffe4c4, black: 0x000000, blanchedalmond: 0xffebcd, blue: 0x0000ff, blueviolet: 0x8a2be2, brown: 0xa52a2a, burlywood: 0xdeb887, cadetblue: 0x5f9ea0, chartreuse: 0x7fff00, chocolate: 0xd2691e, coral: 0xff7f50, cornflowerblue: 0x6495ed, cornsilk: 0xfff8dc, crimson: 0xdc143c, cyan: 0x00ffff, darkblue: 0x00008b, darkcyan: 0x008b8b, darkgoldenrod: 0xb8860b, darkgray: 0xa9a9a9, darkgreen: 0x006400, darkgrey: 0xa9a9a9, darkkhaki: 0xbdb76b, darkmagenta: 0x8b008b, darkolivegreen: 0x556b2f, darkorange: 0xff8c00, darkorchid: 0x9932cc, darkred: 0x8b0000, darksalmon: 0xe9967a, darkseagreen: 0x8fbc8f, darkslateblue: 0x483d8b, darkslategray: 0x2f4f4f, darkslategrey: 0x2f4f4f, darkturquoise: 0x00ced1, darkviolet: 0x9400d3, deeppink: 0xff1493, deepskyblue: 0x00bfff, dimgray: 0x696969, dimgrey: 0x696969, dodgerblue: 0x1e90ff, firebrick: 0xb22222, floralwhite: 0xfffaf0, forestgreen: 0x228b22, fuchsia: 0xff00ff, gainsboro: 0xdcdcdc, ghostwhite: 0xf8f8ff, gold: 0xffd700, goldenrod: 0xdaa520, gray: 0x808080, green: 0x008000, greenyellow: 0xadff2f, grey: 0x808080, honeydew: 0xf0fff0, hotpink: 0xff69b4, indianred: 0xcd5c5c, indigo: 0x4b0082, ivory: 0xfffff0, khaki: 0xf0e68c, lavender: 0xe6e6fa, lavenderblush: 0xfff0f5, lawngreen: 0x7cfc00, lemonchiffon: 0xfffacd, lightblue: 0xadd8e6, lightcoral: 0xf08080, lightcyan: 0xe0ffff, lightgoldenrodyellow: 0xfafad2, lightgray: 0xd3d3d3, lightgreen: 0x90ee90, lightgrey: 0xd3d3d3, lightpink: 0xffb6c1, lightsalmon: 0xffa07a, lightseagreen: 0x20b2aa, lightskyblue: 0x87cefa, lightslategray: 0x778899, lightslategrey: 0x778899, lightsteelblue: 0xb0c4de, lightyellow: 0xffffe0, lime: 0x00ff00, limegreen: 0x32cd32, linen: 0xfaf0e6, magenta: 0xff00ff, maroon: 0x800000, mediumaquamarine: 0x66cdaa, mediumblue: 0x0000cd, mediumorchid: 0xba55d3, mediumpurple: 0x9370db, mediumseagreen: 0x3cb371, mediumslateblue: 0x7b68ee, mediumspringgreen: 0x00fa9a, mediumturquoise: 0x48d1cc, mediumvioletred: 0xc71585, midnightblue: 0x191970, mintcream: 0xf5fffa, mistyrose: 0xffe4e1, moccasin: 0xffe4b5, navajowhite: 0xffdead, navy: 0x000080, oldlace: 0xfdf5e6, olive: 0x808000, olivedrab: 0x6b8e23, orange: 0xffa500, orangered: 0xff4500, orchid: 0xda70d6, palegoldenrod: 0xeee8aa, palegreen: 0x98fb98, paleturquoise: 0xafeeee, palevioletred: 0xdb7093, papayawhip: 0xffefd5, peachpuff: 0xffdab9, peru: 0xcd853f, pink: 0xffc0cb, plum: 0xdda0dd, powderblue: 0xb0e0e6, purple: 0x800080, rebeccapurple: 0x663399, red: 0xff0000, rosybrown: 0xbc8f8f, royalblue: 0x4169e1, saddlebrown: 0x8b4513, salmon: 0xfa8072, sandybrown: 0xf4a460, seagreen: 0x2e8b57, seashell: 0xfff5ee, sienna: 0xa0522d, silver: 0xc0c0c0, skyblue: 0x87ceeb, slateblue: 0x6a5acd, slategray: 0x708090, slategrey: 0x708090, snow: 0xfffafa, springgreen: 0x00ff7f, steelblue: 0x4682b4, tan: 0xd2b48c, teal: 0x008080, thistle: 0xd8bfd8, tomato: 0xff6347, turquoise: 0x40e0d0, violet: 0xee82ee, wheat: 0xf5deb3, white: 0xffffff, whitesmoke: 0xf5f5f5, yellow: 0xffff00, yellowgreen: 0x9acd32 }; ``` ```javascript define(Color, color, { copy(channels) { return Object.assign(new this.constructor, this, channels); }, displayable() { return this.rgb().displayable(); }, hex: color_formatHex, // Deprecated! Use color.formatHex. formatHex: color_formatHex, formatHex8: color_formatHex8, formatHsl: color_formatHsl, formatRgb: color_formatRgb, toString: color_formatRgb }); ``` ```javascript function color_formatHex() { return this.rgb().formatHex(); } ``` ```javascript function color_formatHex8() { ``` -------------------------------- ### Bootstrap Application with TanStack Router Source: https://context7.com/availproject/nexus-ui-components-demo/llms.txt Initializes the React application using TanStack Router for file-based routing. The router is configured with route definitions, default preloading, scroll restoration, and structural sharing. ```typescript import ReactDOM from 'react-dom/client' import { RouterProvider, createRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' import './styles.css' const router = createRouter({ routeTree, context: {}, defaultPreload: 'intent', // Preload routes on hover/focus scrollRestoration: true, // Restore scroll position on navigation defaultStructuralSharing: true, // Share route data structures defaultPreloadStaleTime: 0, }) // Type-safe router registration declare module '@tanstack/react-router' { interface Register { router: typeof router } } const rootElement = document.getElementById('app') if (rootElement && !rootElement.innerHTML) { ReactDOM.createRoot(rootElement).render() } ``` -------------------------------- ### Bytes Parsing and Formatting Utility Source: https://github.com/availproject/nexus-ui-components-demo/blob/main/stats.html Provides utilities for parsing and formatting byte values. Includes functions to format byte sizes into human-readable strings and parse such strings back into byte counts. Useful for file size displays and data transfer metrics. ```javascript var bytes = {exports: {}}; /*! * bytes * Copyright(c) 2012-2014 TJ Holowaychuk * Copyright(c) 2015 Jed Watson * MIT Licensed */ var hasRequiredBytes; function requireBytes () { if (hasRequiredBytes) return bytes.exports; hasRequiredBytes = 1; /** * Module exports. * @public */ bytes.exports = bytes$1; bytes.exports.format = format; bytes.exports.parse = parse; /** * Module variables. * @private */ var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; var formatDecimalsRegExp = /(?:\.0*|(\.["0 ```