one

  • Version 1.2.60
  • Published
  • 14.4 MB
  • 57 dependencies
  • BSD-3-Clause license

Install

npm i one
yarn add one
pnpm add one

Overview

One is a new React Framework that makes Vite serve both native and web.

Index

Variables

Functions

Classes

Interfaces

Type Aliases

Namespaces

Variables

variable route

const route: { feed: { $id: typeof postIdRoute }; notifications: {}; profile: {} };

    variable router

    const router: OneRouter.Router;

      Functions

      function createMiddleware

      createMiddleware: (middleware: Middleware) => Middleware;

        function createRoute

        createRoute: <Path extends string = string>() => {
        useParams: () => any;
        useActiveParams: () => any;
        createLoader: <T>(
        fn: (props: LoaderProps<Params>) => T
        ) => (props: LoaderProps<Params>) => T;
        };

          function getLoaderTimingHistory

          getLoaderTimingHistory: () => LoaderTimingEntry[];

            function getURL

            getURL: () => any;

              function href

              href: <A extends OneRouter.Href<{ __branded__: any }>>(a: A) => A;
              • Type-level utility function to help pass valid Href typed strings. Does not actually validate at runtime, though we could add this later.

              function isResponse

              isResponse: (res: any) => res is Response;

                function onClientLoaderResolve

                onClientLoaderResolve: (resolver: ClientLoaderResolver) => void;

                  function redirect

                  redirect: (
                  path: '__branded__' extends keyof OneRouter.Href ? string : OneRouter.Href,
                  status?: number
                  ) => Response;

                    function refetchLoader

                    refetchLoader: (pathname: string) => Promise<void>;
                    • Imperatively refetch loader data for a given path.

                      Parameter pathname

                      The route path to refetch (e.g., '/users/123')

                      Returns

                      Promise that resolves when refetch completes https://onestack.dev/docs/api/hooks/useLoaderState#refetchloader

                      Example 1

                      await refetchLoader('/users/123')

                    function useBlocker

                    useBlocker: (shouldBlock: BlockerFunction | boolean) => Blocker;
                    • Block navigation when a condition is met.

                      This is useful for preventing users from accidentally leaving a page with unsaved changes. Works with both browser navigation (back/forward, URL changes) and programmatic navigation.

                      Parameter shouldBlock

                      Either a boolean or a function that returns whether to block. When using a function, you receive the current and next locations and can make dynamic decisions.

                      Example 1

                      function EditForm() {
                      const [isDirty, setIsDirty] = useState(false)
                      const blocker = useBlocker(isDirty)
                      return (
                      <>
                      <form onChange={() => setIsDirty(true)}>
                      {// form fields}
                      </form>
                      {blocker.state === 'blocked' && (
                      <Dialog>
                      <p>You have unsaved changes. Leave anyway?</p>
                      <button onClick={blocker.reset}>Stay</button>
                      <button onClick={blocker.proceed}>Leave</button>
                      </Dialog>
                      )}
                      </>
                      )
                      }

                      Example 2

                      // Function-based blocking with location info
                      const blocker = useBlocker(({ currentLocation, nextLocation }) => {
                      // Only block when leaving this specific section
                      return currentLocation.startsWith('/edit') && !nextLocation.startsWith('/edit')
                      })

                    function useFocusEffect

                    useFocusEffect: (effect: EffectCallback, deps: any[]) => void;
                    • Run side effects when a screen is focused. The effect runs when the screen gains focus and cleans up when it loses focus.

                      Parameter effect

                      Memoized callback containing the effect, optionally returns cleanup function

                      Parameter deps

                      Dependency array, effect re-runs when dependencies change (if focused) https://onestack.dev/docs/api/hooks/useFocusEffect

                      Example 1

                      useFocusEffect(
                      useCallback(() => {
                      const subscription = subscribeToUpdates()
                      return () => subscription.unsubscribe()
                      }, []),
                      []
                      )

                    function useLoader

                    useLoader: <
                    Loader extends Function,
                    Returned = Loader extends (p: any) => any ? ReturnType<Loader> : unknown
                    >(
                    loader: Loader
                    ) => Returned extends Promise<any> ? Awaited<Returned> : Returned;
                    • Load route data with SSR/SSG support. Returns the loader's data directly. For loading state and refetch capability, use useLoaderState instead.

                      Parameter loader

                      The loader function exported from the route file

                      Returns

                      The awaited return value of your loader function https://onestack.dev/docs/api/hooks/useLoader

                      Example 1

                      export async function loader({ params }) {
                      return { user: await fetchUser(params.id) }
                      }
                      export default function UserPage() {
                      const { user } = useLoader(loader)
                      return <div>{user.name}</div>
                      }

                    function useLoaderState

                    useLoaderState: <
                    Loader extends Function = any,
                    Returned = Loader extends (p: any) => any ? ReturnType<Loader> : unknown
                    >(
                    loader?: Loader
                    ) => Loader extends undefined
                    ? { refetch: () => Promise<void>; state: 'idle' | 'loading' }
                    : {
                    data: Returned extends Promise<any> ? Awaited<Returned> : Returned;
                    refetch: () => Promise<void>;
                    state: 'idle' | 'loading';
                    };
                    • Access loader data with full state control including refetch capability. Use this when you need loading state or refetch; use useLoader for just data.

                      Parameter loader

                      The loader function (optional - omit for just refetch/state)

                      Returns

                      Object with data, state ('idle' | 'loading'), and refetch function https://onestack.dev/docs/api/hooks/useLoaderState

                      Example 1

                      const { data, state, refetch } = useLoaderState(loader)
                      return (
                      <div>
                      {state === 'loading' && <Spinner />}
                      <button onClick={refetch}>Refresh</button>
                      <pre>{JSON.stringify(data)}</pre>
                      </div>
                      )

                    function useNavigation

                    useNavigation: <T = NavigationProp<ReactNavigation.RootParamList>>(
                    parent?: string
                    ) => T;
                    • Returns the React Navigation navigation object for the current route. Provides low-level access to navigation actions, events, and screen options.

                      Parameter parent

                      Optional path to parent navigator (absolute like /(tabs) or relative like ../)

                      Returns

                      The navigation object with methods like setOptions, addListener, getParent https://onestack.dev/docs/api/hooks/useNavigation

                      Example 1

                      const navigation = useNavigation()
                      navigation.setOptions({ title: 'My Screen' })

                    function useScrollGroup

                    useScrollGroup: (groupPath?: string) => void;
                    • Register a route as a scroll group. Routes within the same scroll group preserve their scroll position when navigating between them.

                      Parameter groupPath

                      Optional path to define the group. Defaults to current pathname. https://onestack.dev/docs/api/hooks/useScrollGroup

                      Example 1

                      // app/dashboard/_layout.tsx
                      export default function DashboardLayout() {
                      useScrollGroup() // All /dashboard/* routes share scroll
                      return <Slot />
                      }

                    function useValidationState

                    useValidationState: () => any;

                      function validateParams

                      validateParams: <
                      T extends ParamValidator<Record<string, unknown>, Record<string, unknown>>
                      >(
                      validator: T,
                      input: Record<string, unknown>
                      ) => InferParamOutput<T>;
                      • Validate route params using the provided validator

                        Parameter validator

                        The validator to use (Standard Schema, Zod-like, or function)

                        Parameter input

                        The raw route params to validate

                        Returns

                        The validated and transformed params

                        Throws

                        ParamValidationError if validation fails

                      function watchFile

                      watchFile: (path: string) => void;
                      • Register a file dependency for loader HMR. No-op on client, registers file path for watching on server.

                      function zodParamValidator

                      zodParamValidator: <T extends ZodLikeSchema<unknown>>(schema: T) => T;
                      • Create a route param validator from a Zod schema.

                        Example 1

                        import { z } from 'zod'
                        import { zodParamValidator } from 'one'
                        export const validateParams = zodParamValidator(z.object({
                        id: z.string().uuid('Invalid ID format'),
                        slug: z.string().min(1, 'Slug is required'),
                        }))

                      Classes

                      class ParamValidationError

                      class ParamValidationError extends Error {}
                      • Error thrown when route param validation fails

                      constructor

                      constructor(
                      message: string,
                      params: Record<string, unknown>,
                      issues?: unknown[]
                      );

                        property issues

                        readonly issues: unknown[];

                          property params

                          readonly params: Record<string, unknown>;

                            property routerCode

                            readonly routerCode: string;

                              class RouteValidationError

                              class RouteValidationError extends Error {}
                              • Error thrown when async route validation fails

                              constructor

                              constructor(message: string, details?: Record<string, unknown>);

                                property details

                                readonly details?: Record<string, unknown>;

                                  property routerCode

                                  readonly routerCode: string;

                                    Interfaces

                                    interface ImageData

                                    interface ImageData {}
                                    • Image data returned by ?imagedata imports. Install sharp to enable this feature: npm install sharp

                                      NOTE: This interface is also declared in types/env.d.ts for Vite module augmentation. Keep both definitions in sync.

                                    property blurDataURL

                                    blurDataURL: string;
                                    • Base64 blur placeholder (10px wide)

                                    property height

                                    height: number;
                                    • Image height in pixels

                                    property src

                                    src: string;
                                    • URL path to the image

                                    property width

                                    width: number;
                                    • Image width in pixels

                                    Type Aliases

                                    type Blocker

                                    type Blocker =
                                    | {
                                    state: 'unblocked';
                                    reset?: undefined;
                                    proceed?: undefined;
                                    location?: undefined;
                                    }
                                    | {
                                    state: 'blocked';
                                    reset: () => void;
                                    proceed: () => void;
                                    location: string;
                                    }
                                    | {
                                    state: 'proceeding';
                                    reset?: undefined;
                                    proceed?: undefined;
                                    location: string;
                                    };

                                      type BlockerFunction

                                      type BlockerFunction = (args: {
                                      currentLocation: string;
                                      nextLocation: string;
                                      historyAction: 'push' | 'pop' | 'replace';
                                      }) => boolean;

                                        type BlockerState

                                        type BlockerState = 'unblocked' | 'blocked' | 'proceeding';

                                          type Endpoint

                                          type Endpoint = (req: Request) => Response | string | object | null;

                                            type Href

                                            type Href = '__branded__' extends keyof OneRouter.Href ? string : OneRouter.Href;

                                              type InferParamInput

                                              type InferParamInput<T> = T extends StandardSchema<infer I, any>
                                              ? I
                                              : T extends ZodLikeSchema<any>
                                              ? Record<string, unknown>
                                              : T extends SearchValidatorFn<infer I, any>
                                              ? I
                                              : never;
                                              • Infer the input type from a param validator

                                              type InferParamOutput

                                              type InferParamOutput<T> = T extends StandardSchema<any, infer O>
                                              ? O
                                              : T extends ZodLikeSchema<infer O>
                                              ? O
                                              : T extends SearchValidatorFn<any, infer O>
                                              ? O
                                              : never;
                                              • Infer the output type from a param validator

                                              type LinkProps

                                              type LinkProps<T extends string | object = string> = OneRouter.LinkProps<T>;

                                                type LoaderProps

                                                type LoaderProps<Params extends object = Record<string, string | string[]>> = {
                                                path: string;
                                                search?: string;
                                                params: Params;
                                                request?: Request;
                                                };

                                                  type LoaderTimingEntry

                                                  type LoaderTimingEntry = {
                                                  path: string;
                                                  startTime: number;
                                                  moduleLoadTime?: number;
                                                  executionTime?: number;
                                                  totalTime?: number;
                                                  error?: string;
                                                  source: 'preload' | 'initial' | 'refetch';
                                                  };

                                                    type Middleware

                                                    type Middleware = (props: {
                                                    request: Request;
                                                    next: () => Promise<MaybeResponse>;
                                                    context: MiddlewareContext;
                                                    }) => RequestResponse;

                                                      type ParamValidator

                                                      type ParamValidator<TInput = Record<string, unknown>, TOutput = TInput> =
                                                      | StandardSchema<TInput, TOutput>
                                                      | ZodLikeSchema<TOutput>
                                                      | SearchValidatorFn<TInput, TOutput>;
                                                      • All supported validator types for route params

                                                      type RouteType

                                                      type RouteType<Path extends string = string> = OneRouter.RouteType<Path>;
                                                      • Helper type to get route information including params and loader props. Can be overridden in generated routes.d.ts for per-route types.

                                                        Example 1

                                                        import type { RouteType } from 'one'

                                                        type MyRoute = RouteType<'(site)/docs/[slug]'> // MyRoute.Params = { slug: string } // MyRoute.LoaderProps = { params: { slug: string }, path: string, request?: Request }

                                                      type RouteValidationFn

                                                      type RouteValidationFn = (
                                                      props: ValidateRouteProps
                                                      ) => ValidationResult | Promise<ValidationResult> | void | Promise<void>;
                                                      • Async route validation function type

                                                      type ValidateRouteProps

                                                      type ValidateRouteProps = {
                                                      params: Record<string, string | string[]>;
                                                      search: Record<string, string | string[]>;
                                                      pathname: string;
                                                      href: string;
                                                      };
                                                      • Props passed to validateRoute function

                                                      type ValidationResult

                                                      type ValidationResult =
                                                      | { valid: true }
                                                      | { valid: false; error: string; details?: Record<string, unknown> };
                                                      • Result from validateRoute function

                                                      type ValidationState

                                                      type ValidationState = {
                                                      status: 'idle' | 'validating' | 'error' | 'valid';
                                                      error?: Error;
                                                      lastValidatedHref?: string;
                                                      };

                                                        Namespaces

                                                        namespace One

                                                        namespace One {}

                                                          type Route

                                                          type Route<Path> = OneRouter.Route<Path>;

                                                            type RouteSitemap

                                                            type RouteSitemap = {
                                                            /**
                                                            * Priority for this route (0.0 to 1.0).
                                                            */
                                                            priority?: number;
                                                            /**
                                                            * Change frequency for this route.
                                                            */
                                                            changefreq?: SitemapChangefreq;
                                                            /**
                                                            * Last modification date for this route.
                                                            */
                                                            lastmod?: string | Date;
                                                            /**
                                                            * Exclude this route from the sitemap.
                                                            */
                                                            exclude?: boolean;
                                                            };

                                                              type SitemapChangefreq

                                                              type SitemapChangefreq =
                                                              | 'always'
                                                              | 'hourly'
                                                              | 'daily'
                                                              | 'weekly'
                                                              | 'monthly'
                                                              | 'yearly'
                                                              | 'never';

                                                                namespace OneRouter

                                                                namespace OneRouter {}
                                                                  const Link: LinkComponent;
                                                                  • Component to render link to another route using a path. Uses an anchor tag on the web.

                                                                    Parameter

                                                                    props.href Absolute path to route (e.g. `/feeds/hot`).

                                                                    Parameter

                                                                    props.replace Should replace the current route without adding to the history.

                                                                    Parameter

                                                                    props.asChild Forward props to child component. Useful for custom buttons.

                                                                    Parameter

                                                                    props.children Child elements to render the content.

                                                                    Parameter

                                                                    props.className On web, this sets the HTML `class` directly. On native, this can be used with CSS interop tools like Nativewind.

                                                                  variable router

                                                                  const router: Router;
                                                                  • The imperative router.

                                                                  function Redirect

                                                                  Redirect: (props: React.PropsWithChildren<{ href: Href }>) => ReactNode;
                                                                  • Redirects to the href as soon as the component is mounted.

                                                                  function useActiveParams

                                                                  useActiveParams: <
                                                                  T extends string | UnknownOutputParams = UnknownOutputParams
                                                                  >() => T extends AllRoutes ? SearchParams<T> : T;
                                                                  • Get the globally selected query parameters, including dynamic path segments. This function will update even when the route is not focused. Useful for analytics or other background operations that don't draw to the screen.

                                                                    When querying search params in a stack, opt-towards using `useParams` as these will only update when the route is focused.

                                                                    See Also

                                                                    • `useParams`

                                                                  function useParams

                                                                  useParams: <
                                                                  TParams extends string | UnknownOutputParams = UnknownOutputParams
                                                                  >() => TParams extends AllRoutes ? SearchParams<TParams> : TParams;
                                                                  • Returns the URL search parameters for the contextually focused route. e.g. `/acme?foo=bar` -> `{ foo: "bar" }`. This is useful for stacks where you may push a new screen that changes the query parameters.

                                                                    To observe updates even when the invoking route is not focused, use `useActiveParams()`.

                                                                    See Also

                                                                    • `useActiveParams`

                                                                  function useRouter

                                                                  useRouter: () => Router;
                                                                  • Hooks

                                                                  function useSegments

                                                                  useSegments: <T extends string | [string]>() => T extends AbsoluteRoute
                                                                  ? RouteSegments<T>
                                                                  : T extends string
                                                                  ? string[]
                                                                  : T;
                                                                  • Get a list of selected file segments for the currently selected route. Segments are not normalized, so they will be the same as the file path. e.g. /[id]?id=normal -> ["[id]"]

                                                                    `useSegments` can be typed using an abstract. Consider the following file structure, and strictly typed `useSegments` function:

                                                                    ```md - app - [user] - index.js - followers.js - settings.js ``` This can be strictly typed using the following abstract:

                                                                    ```ts const [first, second] = useSegments<['settings'] | ['[user]'] | ['[user]', 'followers']>() ```

                                                                  interface LinkComponent

                                                                  interface LinkComponent {}

                                                                    property resolveHref

                                                                    resolveHref: (href: Href) => string;
                                                                    • Helper method to resolve an Href object into a string.

                                                                    call signature

                                                                    <T extends string | object>(
                                                                    props: React.PropsWithChildren<LinkProps<T>>
                                                                    ): JSX.Element;

                                                                      interface LinkProps

                                                                      interface LinkProps<T extends string | object>
                                                                      extends Omit<
                                                                      TextProps,
                                                                      'href' | 'disabled' | 'onLongPress' | 'onPressIn' | 'onPressOut'
                                                                      >,
                                                                      Pick<
                                                                      PressableProps,
                                                                      'disabled' | 'onLongPress' | 'onPressIn' | 'onPressOut'
                                                                      >,
                                                                      WebAnchorProps {}

                                                                        property asChild

                                                                        asChild?: boolean;
                                                                        • Forward props to child component. Useful for custom buttons.

                                                                        property className

                                                                        className?: string;
                                                                        • On web, this sets the HTML class directly. On native, this can be used with CSS interop tools like Nativewind.

                                                                        property href

                                                                        href: Href<T>;
                                                                        • Path to route to.

                                                                        property mask

                                                                        mask?: Href<T>;
                                                                        • Display a different URL in the browser than the actual route. Useful for modals and overlays that should show a clean URL.

                                                                          Example 1

                                                                          <Link href="/photos/5/modal" mask="/photos/5">
                                                                          View Photo
                                                                          </Link>

                                                                        property onPress

                                                                        onPress?: (
                                                                        e: React.MouseEvent<HTMLAnchorElement, MouseEvent> | GestureResponderEvent
                                                                        ) => void;

                                                                          property push

                                                                          push?: boolean;
                                                                          • Should push the current route

                                                                          property replace

                                                                          replace?: boolean;
                                                                          • Should replace the current route without adding to the history.

                                                                          interface WebAnchorProps

                                                                          interface WebAnchorProps {}
                                                                          • ********** * **********

                                                                          property download

                                                                          download?: string;
                                                                          • **Web only:** Specifies that the href should be downloaded when the user clicks on the link, instead of navigating to it. It is typically used for links that point to files that the user should download, such as PDFs, images, documents, etc.

                                                                            The value of the download property, which represents the filename for the downloaded file. This property is passed to the underlying anchor (<a>) tag.

                                                                            Example 1

                                                                            Download image

                                                                          property rel

                                                                          rel?: string;
                                                                          • **Web only:** Specifies the relationship between the href and the current route.

                                                                            Common values: - **nofollow**: Indicates to search engines that they should not follow the href. This is often used for user-generated content or links that should not influence search engine rankings. - **noopener**: Suggests that the href should not have access to the opening window's window.opener object, which is a security measure to prevent potentially harmful behavior in cases of links that open new tabs or windows. - **noreferrer**: Requests that the browser not send the Referer HTTP header when navigating to the href. This can enhance user privacy.

                                                                            The rel property is primarily used for informational and instructive purposes, helping browsers and web crawlers make better decisions about how to handle and interpret the links on a web page. It is important to use appropriate rel values to ensure that links behave as intended and adhere to best practices for web development and SEO (Search Engine Optimization).

                                                                            This property is passed to the underlying anchor (<a>) tag.

                                                                            Example 1

                                                                            Go to Expo

                                                                          property target

                                                                          target?: '_self' | '_blank' | '_parent' | '_top' | (string & object);
                                                                          • **Web only:** Specifies where to open the href.

                                                                            - **_self**: the current tab. - **_blank**: opens in a new tab or window. - **_parent**: opens in the parent browsing context. If no parent, defaults to **_self**. - **_top**: opens in the highest browsing context ancestor. If no ancestors, defaults to **_self**.

                                                                            This property is passed to the underlying anchor (<a>) tag.

                                                                            '_self'

                                                                            Example 1

                                                                            Go to Expo in new tab

                                                                          type AbsoluteRoute

                                                                          type AbsoluteRoute = DynamicRouteTemplate | StaticRoutes;

                                                                            type AllRoutes

                                                                            type AllRoutes = OneRouterRoutes | ExternalPathString;

                                                                              type CatchAllRoutePart

                                                                              type CatchAllRoutePart<S extends string> = S extends `${string}${SearchOrHash}`
                                                                              ? never
                                                                              : S extends ''
                                                                              ? never
                                                                              : S extends `${string}(${string})${string}`
                                                                              ? never
                                                                              : S extends `${string}[${string}]${string}`
                                                                              ? never
                                                                              : S;
                                                                              • Return only the CatchAll router part. If the string has search parameters or a hash return never

                                                                              type DynamicRoutesHref

                                                                              type DynamicRoutesHref = DynamicRouteString<
                                                                              { __branded__: any },
                                                                              DynamicRouteTemplate
                                                                              >;
                                                                              • ******* Href * *******

                                                                              type DynamicRoutesHref2

                                                                              type DynamicRoutesHref2 = DynamicRouteString<string, DynamicRouteTemplate>;

                                                                                type DynamicRouteTemplate

                                                                                type DynamicRouteTemplate = __routes extends {
                                                                                DynamicRouteTemplate: string;
                                                                                }
                                                                                ? __routes['DynamicRouteTemplate']
                                                                                : string;

                                                                                  type ExternalPathString

                                                                                  type ExternalPathString = `${string}:${string}`;

                                                                                    type Href

                                                                                    type Href<T extends string | object = { __branded__: any }> =
                                                                                    | StringRouteToType<
                                                                                    AllUngroupedRoutes<StaticRoutes> | RelativePathString | ExternalPathString
                                                                                    >
                                                                                    | DynamicRouteString<T, DynamicRouteTemplate>
                                                                                    | DynamicRouteObject<
                                                                                    | StaticRoutes
                                                                                    | RelativePathString
                                                                                    | ExternalPathString
                                                                                    | DynamicRouteTemplate
                                                                                    >;
                                                                                    • The main routing type for One. Includes all available routes with strongly typed parameters.

                                                                                    type InpurRouteParamsGeneric

                                                                                    type InpurRouteParamsGeneric = InputRouteParamsBlank | InputRouteParams<any>;

                                                                                      type InputRouteParams

                                                                                      type InputRouteParams<Path> = {
                                                                                      [Key in ParameterNames<Path> as Key extends `...${infer Name}`
                                                                                      ? Name
                                                                                      : Key]: Key extends `...${string}` ? string[] : string;
                                                                                      };
                                                                                      • Returns a Record of the routes parameters as strings and CatchAll parameters

                                                                                        There are two versions, input and output, as you can input 'string | number' but the output will always be 'string'

                                                                                        /[id]/[...rest] -> { id: string, rest: string[] } /no-params -> {}

                                                                                      type InputRouteParamsBlank

                                                                                      type InputRouteParamsBlank = Record<string, string | undefined | null>;
                                                                                      • ********************* One Exports * *********************

                                                                                      type LinkToOptions

                                                                                      type LinkToOptions = {
                                                                                      scroll?: boolean;
                                                                                      /**
                                                                                      * Display a different URL in the browser than the actual route.
                                                                                      * Useful for modals and overlays that should show a clean URL.
                                                                                      *
                                                                                      * @example
                                                                                      * ```tsx
                                                                                      * // Navigate to /photos/5/modal but show /photos/5 in browser
                                                                                      * router.navigate('/photos/5/modal', {
                                                                                      * mask: { href: '/photos/5' }
                                                                                      * })
                                                                                      * ```
                                                                                      */
                                                                                      mask?: {
                                                                                      /** The URL to display in the browser address bar */
                                                                                      href: Href;
                                                                                      /**
                                                                                      * If true, unmask on page reload (show the masked URL in browser).
                                                                                      * If false (default), keep masking (navigate to actual route on reload).
                                                                                      */
                                                                                      unmaskOnReload?: boolean;
                                                                                      };
                                                                                      /**
                                                                                      * Specify a scroll group for this navigation.
                                                                                      * Routes within the same scroll group will preserve scroll position
                                                                                      * when navigating between them.
                                                                                      *
                                                                                      * @example
                                                                                      * ```tsx
                                                                                      * // Use scroll group to preserve scroll when switching tabs
                                                                                      * router.navigate('/dashboard/settings', {
                                                                                      * scrollGroup: '/dashboard'
                                                                                      * })
                                                                                      * ```
                                                                                      */
                                                                                      scrollGroup?: string;
                                                                                      };

                                                                                        type LoadingState

                                                                                        type LoadingState = 'loading' | 'loaded';

                                                                                          type LoadingStateListener

                                                                                          type LoadingStateListener = (state: LoadingState) => void;

                                                                                            type NavigationRef

                                                                                            type NavigationRef =
                                                                                            NavigationContainerRefWithCurrent<ReactNavigation.RootParamList>;

                                                                                              type OneRouterRoutes

                                                                                              type OneRouterRoutes = DynamicRouteTemplate | StaticRoutes | RelativePathString;

                                                                                                type Redirect

                                                                                                type Redirect = typeof Redirect;

                                                                                                  type RelativePathString

                                                                                                  type RelativePathString = `./${string}` | `../${string}` | '..';

                                                                                                    type ResultState

                                                                                                    type ResultState = PartialState<NavigationState> & {
                                                                                                    state?: ResultState;
                                                                                                    hash?: string;
                                                                                                    linkOptions?: OneRouter.LinkToOptions;
                                                                                                    };

                                                                                                      type RootStateListener

                                                                                                      type RootStateListener = (state: ResultState) => void;

                                                                                                        type Route

                                                                                                        type Route<Path> = {
                                                                                                        Params: InputRouteParams<Path>;
                                                                                                        Props: { params: InputRouteParams<Path> };
                                                                                                        Loader: (props: { params: InputRouteParams<Path> }) => any;
                                                                                                        };

                                                                                                          type Router

                                                                                                          type Router = {
                                                                                                          /** Go back in the history. */
                                                                                                          back: () => void;
                                                                                                          /** If there's history that supports invoking the `back` function. */
                                                                                                          canGoBack: () => boolean;
                                                                                                          /** Navigate to the provided href using a push operation if possible. */
                                                                                                          push: (href: Href, options?: LinkToOptions) => void;
                                                                                                          /** Navigate to the provided href. */
                                                                                                          navigate: (href: Href, options?: LinkToOptions) => void;
                                                                                                          /** Navigate to route without appending to the history. */
                                                                                                          replace: (href: Href, options?: LinkToOptions) => void;
                                                                                                          /** Navigate to the provided href using a push operation if possible. */
                                                                                                          dismiss: (count?: number) => void;
                                                                                                          /** Navigate to first screen within the lowest stack. */
                                                                                                          dismissAll: () => void;
                                                                                                          /** If there's history that supports invoking the `dismiss` and `dismissAll` function. */
                                                                                                          canDismiss: () => boolean;
                                                                                                          /** Update the current route query params. */
                                                                                                          setParams: <T = ''>(
                                                                                                          params?: T extends '' ? InputRouteParamsBlank : InputRouteParams<T>
                                                                                                          ) => void;
                                                                                                          /** Subscribe to state updates from the router */
                                                                                                          subscribe: (listener: RootStateListener) => () => void;
                                                                                                          /** Subscribe to loading state updates */
                                                                                                          onLoadState: (listener: LoadingStateListener) => () => void;
                                                                                                          };

                                                                                                            type RouteType

                                                                                                            type RouteType<Path extends string> = Path extends keyof __routes['RouteTypes']
                                                                                                            ? __routes['RouteTypes'][Path]
                                                                                                            : {
                                                                                                            Params: InputRouteParams<Path>;
                                                                                                            LoaderProps: import('../types').LoaderProps<InputRouteParams<Path>>;
                                                                                                            };
                                                                                                            • Helper type to get route information including params and loader props. Uses generated RouteTypes from routes.d.ts if available for better intellisense.

                                                                                                              Example 1

                                                                                                              const route = createRoute<'/docs/[slug]'>() // route.createLoader gets params typed as { slug: string }

                                                                                                              type Route = RouteType<'/docs/[slug]'> // Route.Params = { slug: string } // Route.LoaderProps = { path: string; params: { slug: string }; request?: Request }

                                                                                                            type SearchParams

                                                                                                            type SearchParams<T extends AllRoutes = never> = T extends DynamicRouteTemplate
                                                                                                            ? OutputRouteParams<T>
                                                                                                            : T extends StaticRoutes
                                                                                                            ? never
                                                                                                            : UnknownOutputParams;
                                                                                                            • Returns the search parameters for a route.

                                                                                                            type SingleRoutePart

                                                                                                            type SingleRoutePart<S extends string> = S extends `${string}/${string}`
                                                                                                            ? never
                                                                                                            : S extends `${string}${SearchOrHash}`
                                                                                                            ? never
                                                                                                            : S extends ''
                                                                                                            ? never
                                                                                                            : S extends `(${string})`
                                                                                                            ? never
                                                                                                            : S extends `[${string}]`
                                                                                                            ? never
                                                                                                            : S;
                                                                                                            • Return only the RoutePart of a string. If the string has multiple parts return never

                                                                                                              string | type ---------|------ 123 | 123 /123/abc | never 123?abc | never ./123 | never /123 | never 123/../ | never

                                                                                                            type UnknownInputParams

                                                                                                            type UnknownInputParams = Record<
                                                                                                            string,
                                                                                                            string | number | undefined | null | (string | number)[]
                                                                                                            >;

                                                                                                              namespace routerStore

                                                                                                              module 'src/router/router.ts' {}
                                                                                                              • Note: this entire module is exported as an interface router.* We need to treat exports as an API and not change them, maybe not the best decision.

                                                                                                              variable hasAttemptedToHideSplash

                                                                                                              let hasAttemptedToHideSplash: boolean;

                                                                                                                variable initialState

                                                                                                                let initialState: any;

                                                                                                                  variable navigationRef

                                                                                                                  let navigationRef: NavigationContainerRefWithCurrent<ReactNavigation.RootParamList>;

                                                                                                                    variable preloadedLoaderData

                                                                                                                    const preloadedLoaderData: Record<string, any>;

                                                                                                                      variable preloadingLoader

                                                                                                                      const preloadingLoader: Record<string, Promise<any>>;

                                                                                                                        variable rootComponent

                                                                                                                        let rootComponent: ComponentType;

                                                                                                                          variable rootState

                                                                                                                          let rootState: any;

                                                                                                                            variable routeInfo

                                                                                                                            let routeInfo: any;

                                                                                                                              variable routeNode

                                                                                                                              let routeNode: any;

                                                                                                                                function canDismiss

                                                                                                                                canDismiss: () => boolean;

                                                                                                                                  function canGoBack

                                                                                                                                  canGoBack: () => boolean;

                                                                                                                                    function cleanup

                                                                                                                                    cleanup: () => void;

                                                                                                                                      function dismiss

                                                                                                                                      dismiss: (count?: number) => void;

                                                                                                                                        function dismissAll

                                                                                                                                        dismissAll: () => void;

                                                                                                                                          function getPreloadHistory

                                                                                                                                          getPreloadHistory: () => PreloadEntry[];

                                                                                                                                            function getSortedRoutes

                                                                                                                                            getSortedRoutes: () => any;

                                                                                                                                              function getValidationState

                                                                                                                                              getValidationState: () => ValidationState;

                                                                                                                                                function goBack

                                                                                                                                                goBack: () => void;

                                                                                                                                                  function initialize

                                                                                                                                                  initialize: (
                                                                                                                                                  context: One.RouteContext,
                                                                                                                                                  ref: NavigationContainerRefWithCurrent<ReactNavigation.RootParamList>,
                                                                                                                                                  initialLocation?: URL
                                                                                                                                                  ) => void;

                                                                                                                                                    function isRouteProtected

                                                                                                                                                    isRouteProtected: (href: string) => boolean;
                                                                                                                                                    • Check if a route path is protected and should be blocked. Returns true if the route is protected.

                                                                                                                                                    function linkTo

                                                                                                                                                    linkTo: (
                                                                                                                                                    href: string,
                                                                                                                                                    event?: string,
                                                                                                                                                    options?: OneRouter.LinkToOptions
                                                                                                                                                    ) => Promise<void>;

                                                                                                                                                      function navigate

                                                                                                                                                      navigate: (
                                                                                                                                                      url: OneRouter.Href,
                                                                                                                                                      options?: OneRouter.LinkToOptions
                                                                                                                                                      ) => Promise<void>;

                                                                                                                                                        function preloadRoute

                                                                                                                                                        preloadRoute: (href: string, injectCSS?: boolean) => Promise<any> | undefined;

                                                                                                                                                          function push

                                                                                                                                                          push: (url: OneRouter.Href, options?: OneRouter.LinkToOptions) => Promise<void>;

                                                                                                                                                            function registerProtectedRoutes

                                                                                                                                                            registerProtectedRoutes: (
                                                                                                                                                            contextKey: string,
                                                                                                                                                            protectedScreens: Set<string>
                                                                                                                                                            ) => void;
                                                                                                                                                            • Register protected routes for a navigator context. Called by navigators when their protectedScreens changes.

                                                                                                                                                            function replace

                                                                                                                                                            replace: (
                                                                                                                                                            url: OneRouter.Href,
                                                                                                                                                            options?: OneRouter.LinkToOptions
                                                                                                                                                            ) => Promise<void>;

                                                                                                                                                              function rootStateSnapshot

                                                                                                                                                              rootStateSnapshot: () => any;

                                                                                                                                                                function routeInfoSnapshot

                                                                                                                                                                routeInfoSnapshot: () => any;

                                                                                                                                                                  function setLoadingState

                                                                                                                                                                  setLoadingState: (state: OneRouter.LoadingState) => void;

                                                                                                                                                                    function setParams

                                                                                                                                                                    setParams: (params?: OneRouter.InpurRouteParamsGeneric) => any;

                                                                                                                                                                      function setValidationState

                                                                                                                                                                      setValidationState: (state: ValidationState) => void;

                                                                                                                                                                        function snapshot

                                                                                                                                                                        snapshot: () => {
                                                                                                                                                                        linkTo: (
                                                                                                                                                                        href: string,
                                                                                                                                                                        event?: string,
                                                                                                                                                                        options?: OneRouter.LinkToOptions
                                                                                                                                                                        ) => Promise<void>;
                                                                                                                                                                        routeNode: any;
                                                                                                                                                                        rootComponent: ComponentType;
                                                                                                                                                                        linking: any;
                                                                                                                                                                        hasAttemptedToHideSplash: boolean;
                                                                                                                                                                        initialState: any;
                                                                                                                                                                        rootState: any;
                                                                                                                                                                        nextState: any;
                                                                                                                                                                        routeInfo: any;
                                                                                                                                                                        splashScreenAnimationFrame: number;
                                                                                                                                                                        navigationRef: NavigationContainerRefWithCurrent<ReactNavigation.RootParamList>;
                                                                                                                                                                        navigationRefSubscription: () => void;
                                                                                                                                                                        rootStateSubscribers: Set<OneRouter.RootStateListener>;
                                                                                                                                                                        storeSubscribers: Set<() => void>;
                                                                                                                                                                        };

                                                                                                                                                                          function subscribeToLoadingState

                                                                                                                                                                          subscribeToLoadingState: (
                                                                                                                                                                          subscriber: OneRouter.LoadingStateListener
                                                                                                                                                                          ) => () => void;

                                                                                                                                                                            function subscribeToRootState

                                                                                                                                                                            subscribeToRootState: (subscriber: OneRouter.RootStateListener) => () => void;

                                                                                                                                                                              function subscribeToStore

                                                                                                                                                                              subscribeToStore: (subscriber: () => void) => () => void;

                                                                                                                                                                                function subscribeToValidationState

                                                                                                                                                                                subscribeToValidationState: (
                                                                                                                                                                                subscriber: (state: ValidationState) => void
                                                                                                                                                                                ) => () => boolean;

                                                                                                                                                                                  function unregisterProtectedRoutes

                                                                                                                                                                                  unregisterProtectedRoutes: (contextKey: string) => void;
                                                                                                                                                                                  • Unregister protected routes for a navigator context. Called when a navigator unmounts.

                                                                                                                                                                                  function updateState

                                                                                                                                                                                  updateState: (state: OneRouter.ResultState, nextStateParam?: any) => void;

                                                                                                                                                                                    function useOneRouter

                                                                                                                                                                                    useOneRouter: () => any;

                                                                                                                                                                                      function useStoreRootState

                                                                                                                                                                                      useStoreRootState: () => any;

                                                                                                                                                                                        function useStoreRouteInfo

                                                                                                                                                                                        useStoreRouteInfo: () => any;

                                                                                                                                                                                          function useValidationState

                                                                                                                                                                                          useValidationState: () => any;

                                                                                                                                                                                            type PreloadEntry

                                                                                                                                                                                            type PreloadEntry = {
                                                                                                                                                                                            href: string;
                                                                                                                                                                                            status: PreloadStatus;
                                                                                                                                                                                            startTime: number;
                                                                                                                                                                                            endTime?: number;
                                                                                                                                                                                            error?: string;
                                                                                                                                                                                            hasLoader: boolean;
                                                                                                                                                                                            hasCss: boolean;
                                                                                                                                                                                            };

                                                                                                                                                                                              type PreloadStatus

                                                                                                                                                                                              type PreloadStatus = 'pending' | 'loading' | 'loaded' | 'error';

                                                                                                                                                                                                type ValidationState

                                                                                                                                                                                                type ValidationState = {
                                                                                                                                                                                                status: 'idle' | 'validating' | 'error' | 'valid';
                                                                                                                                                                                                error?: Error;
                                                                                                                                                                                                lastValidatedHref?: string;
                                                                                                                                                                                                };

                                                                                                                                                                                                  Package Files (19)

                                                                                                                                                                                                  Dependencies (57)

                                                                                                                                                                                                  Dev Dependencies (13)

                                                                                                                                                                                                  Peer Dependencies (5)

                                                                                                                                                                                                  Badge

                                                                                                                                                                                                  To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                                                                                                                                                  You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/one.

                                                                                                                                                                                                  • Markdown
                                                                                                                                                                                                    [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/one)
                                                                                                                                                                                                  • HTML
                                                                                                                                                                                                    <a href="https://www.jsdocs.io/package/one"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>