/** * The Router for a native app: `Router.make` on a history kept in memory, * with Android's Back button and deep links. * * **Details** * * `layer` provides the `Router` and its Commands, as `BrowserRouter` does * in the browser. Each history entry is a screen: the root holds a * `RouterStack.Stack`, follows it with `RouterStack.subscription` and * `RouterStack.follow`, and draws it with the kit's `Stack`. Covered * screens stay mounted, so the Router saves nothing of a page it leaves: * Back shows the screen that is still there. * * Back goes back one entry while there is one, and otherwise runs Android's * default, which closes the app. A `BackHandler.onPress` on the top screen * gets the press first. While a `Router.blocked` block is held, Back does * nothing, and a block with a mapper hears it as an attempt. Retrying a Back * from the first screen closes the app. * * Deep links need `prefixes`. A URL that starts with one is routed, with * the rest as its path: with `"myapp://"`, `myapp://people/1?tab=a` opens * `/people/1?tab=a`, and with `"https://example.com"`, * `https://example.com/people/1` opens `/people/1`. The app starts at the * URL that launched it, and a URL that arrives while it runs is pushed. A * path the routes don't parse, with no catch-all route, is ignored. Without * a deep link, or without `prefixes`, the app starts at the routes' base * root: `/`, `#/` for a `"#"` base, or the base itself. * * An href the routes don't parse, as from `Router.load` or a `Link`, * opens with `Linking.openURL`. * * The screen reader's focus moves to a screen that comes to the top, which * reads it, so nothing is announced. A screen that has more to say runs * `AccessibilityInfo.announce`. * * **Example** (An app with two screens) * * ```ts * import { RouterStack } from "effect/ui" * import { Native, NativeApp, NativeRouter } from "@effect/ui-native" * import { Stack } from "@effect/ui-native/kit" * import { Layer, Schema } from "effect" * import { AppRoute, Message, screen } from "./routes.ts" * * const App = Native.component({ * name: "App", * props: Schema.Struct({ stack: RouterStack.Stack(AppRoute) }), * model: RouterStack.Stack(AppRoute), * message: Message * }).make({ * init: ($) => $.props.stack, * update: { * Navigated: ($, { navigation }) => * $.set(RouterStack.follow(AppRoute, $.model, navigation)) * }, * subscriptions: ({ model }) => [ * RouterStack.subscription(AppRoute, model, (navigation) => Message.Navigated({ navigation })) * ], * view: (h, stack) => Stack(h, { entries: stack, screen }) * }) * * NativeApp.register( * NativeApp.mount(App, RouterStack.props(AppRoute)).pipe( * Layer.provide(NativeRouter.layer({ routes: AppRoute, prefixes: ["myapp://"] })) * ) * ) * ``` * * @stability experimental * @since 4.2.0 */ import * as Effect from "effect/Effect" import * as Layer from "effect/Layer" import * as Option from "effect/Option" import * as Stream from "effect/Stream" import type * as Route from "effect/ui/Route" import * as Router from "effect/ui/Router" import * as RouterStack from "effect/ui/RouterStack" import { exitWith, handle } from "./kit/internal/back.ts" import * as Linking from "./kit/Linking.ts" import * as Native from "./Native.ts" /** * The options of `layer`. * * @stability experimental * @category models * @since 4.2.0 */ export interface Options { readonly routes: Route.AnyUnion /** * The URLs that are deep links: each is the start of the URLs routed with * the rest as their path, or a function that returns a URL's path, or * `undefined` when it isn't a deep link. */ readonly prefixes?: | ReadonlyArray | ((url: string) => string | undefined) | undefined } /** * The path a URL opens, if it starts with one of `prefixes`. * * @stability experimental * @category utils * @since 4.2.0 */ export const pathOf = ( prefixes: NonNullable, url: string ): Option.Option => { if (typeof prefixes === "function") { return Option.fromUndefinedOr(prefixes(url)) } for (const prefix of prefixes) { if (!url.startsWith(prefix)) continue const rest = url.slice(prefix.length) // A prefix such as `https://example.com` doesn't match `https://example.community`. if (rest !== "" && !"/?#".includes(rest[0]!) && !prefix.endsWith("/")) { continue } return Option.some(rest.startsWith("/") ? rest : "/" + rest) } return Option.none() } /** * Provides the `Router` and its Commands on a history in memory, with * Android's Back button and the deep links `prefixes` match. * * **Details** * * With `prefixes`, the Layer asks for the URL that launched the app before * it builds the Router, so the root mounts one native round trip later. * * @stability experimental * @category layers * @since 4.2.0 */ export const layer = (options: Options): Layer.Layer => Layer.unwrap(Effect.gen(function*() { const device = yield* Native.Device const { prefixes } = options // A deep link the routes don't parse, with no catch-all, isn't one. const routed = (url: string) => Option.filter( pathOf(prefixes!, url), (path) => Option.isSome(options.routes.resolve(path)) ) // `RouterStack.layer` starts at the root when this doesn't parse. const start = prefixes === undefined ? undefined : yield* Linking.initialURL.pipe( Effect.map((url) => Option.getOrUndefined( Option.flatMap(url, (url) => pathOf(prefixes, url)) ) ), Effect.orElseSucceed(() => undefined), Effect.provideService(Native.Device, device) ) const follow = Layer.effectDiscard(Effect.gen(function*() { const router = yield* Router.Router // The bottom handler: a BackHandler.onPress gets the press first. yield* Effect.acquireRelease( Effect.sync(() => handle(device)(() => { // Back on the first screen exits through the history, so a block can stop it. Effect.runSync(router.back) return true }, true) ), (off) => Effect.sync(off) ) if (prefixes !== undefined) { yield* Effect.forkScoped(Stream.runForEach( Linking.urls, (url) => Option.match(routed(url), { onNone: () => Effect.void, onSome: (path) => router.navigate(path) }) )) } })).pipe(Layer.provide(Layer.succeed(Native.Device, device))) return Layer.provideMerge( follow, RouterStack.layer({ routes: options.routes, url: start, exit: () => exitWith(device), load: (href) => { Effect.runFork( Linking.openURL(href).pipe( Effect.ignore, Effect.provideService(Native.Device, device) ) ) } }) ) }))