Compare commits

...

3 Commits

18 changed files with 472 additions and 21 deletions

View File

@ -35,6 +35,13 @@
<data android:scheme="raven.thecommit.company" android:host="oauth" />
</intent-filter>
<!-- OS share sheet. singleTask: a warm share arrives as onNewIntent, read by RavenShellPlugin. -->
<!-- A site link from a browser: raven://open?url=<link> (the web app's OpenInApp). -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="raven" android:host="open" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SEND_MULTIPLE" />

View File

@ -32,18 +32,22 @@ public class MainActivity extends BridgeActivity {
registerPlugin(RavenSocketPlugin.class);
registerPlugin(RavenDownloadPlugin.class);
registerPlugin(RavenMediaPlugin.class);
// A share or notification tap only ever arrives as a fresh launch or onNewIntent.
// A share, notification tap or browser link only ever arrives as a fresh launch or onNewIntent.
// A recreated activity (process death, Recents) gets the task's root intent
// again; drop it, or the share or tap the user already acted on replays.
Intent launch = getIntent();
boolean fromHistory = launch != null && (launch.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0;
boolean replayable = RavenShellPlugin.isShare(launch) || (launch != null && launch.hasExtra("google.message_id"));
boolean replayable = RavenShellPlugin.isShare(launch) || (launch != null && (launch.hasExtra("google.message_id") || isSiteLink(launch)));
if (replayable && (savedInstanceState != null || fromHistory)) setIntent(new Intent());
super.onCreate(savedInstanceState);
serveMediaProxy();
publishSystemBarInsets();
}
private static boolean isSiteLink(Intent intent) {
return Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() != null && "raven".equals(intent.getData().getScheme());
}
// Media proxy requests are answered here; everything else keeps Capacitor's client.
private void serveMediaProxy() {
getBridge().setWebViewClient(new BridgeWebViewClient(getBridge()) {

View File

@ -10,7 +10,7 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
window?.applyStoredTheme()
// A cold-start share arrives here, not in openURLContexts; the proxy replays
// the URL only into its own handler.
for context in connectionOptions.urlContexts where context.url.scheme == "raven" { receiveShare(context.url) }
for context in connectionOptions.urlContexts where Self.isShare(context.url) { receiveShare(context.url) }
SceneDelegateProxy.shared.scene(scene, willConnectTo: session, options: connectionOptions)
}
@ -24,12 +24,15 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {
// Share extension handoff (`raven://?title=…&type=…&url=…`, see README manual
// step 2). Scene-based apps never get application(_:open:), where send-intent's
// README puts this, so it lives here.
let shares = URLContexts.filter { $0.url.scheme == "raven" }
let shares = URLContexts.filter { Self.isShare($0.url) }
for context in shares { receiveShare(context.url) }
let rest = URLContexts.subtracting(shares)
if !rest.isEmpty { SceneDelegateProxy.shared.scene(scene, openURLContexts: rest) }
}
// `raven://open?url=` is a site link from a browser, left to the App plugin's appUrlOpen.
private static func isShare(_ url: URL) -> Bool { url.scheme == "raven" && url.host != "open" }
private func receiveShare(_ url: URL) {
guard let params = URLComponents(url: url, resolvingAgainstBaseURL: true)?.queryItems else { return }
let field = { (name: String) in params.filter { $0.name == name }.map { $0.value ?? "" } }

View File

@ -25,7 +25,7 @@
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#ffffff">
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#171717">
<link rel="mask-icon" href="{{ mask_icon }}" color="#000000">
<meta name="apple-itunes-app" content="app-id=6741682327, app-argument={{sitename}}">
<meta name="apple-itunes-app" content="app-id=6741682327, app-argument={{ app_argument }}">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-title" content="{{ app_name }}" />

View File

@ -40,6 +40,7 @@ import { SessionBroadcast } from "./SessionBroadcast"
import RavenSettingsDialog from "@components/features/settings/SettingsDialog"
import { SetupGate } from "@components/features/setup/SetupGate"
import { MessageActionDialogs } from "@components/features/message/actions/MessageActionDialogs"
import { OpenInAppBar } from "./OpenInAppBar"
/**
* The AppShell is used to wrap the entire application and provide all the utilities
@ -173,6 +174,7 @@ const AppShellLayout = ({ children }: { children: React.ReactNode }) => {
if (isMobile) {
return <div className={cn("flex h-dvh flex-col overflow-hidden", topInset)}>
<OpenInAppBar />
{banner}
{children}
</div>

View File

@ -0,0 +1,96 @@
import { useRef, useState } from "react"
import { ExternalLinkIcon } from "lucide-react"
import { Button } from "@components/ui/button"
import _ from "@lib/translate"
import { cn } from "@lib/utils"
import { dismissApp, offersApp, openInApp } from "@utils/openInApp"
// Travel before a touch counts as a swipe rather than a tap.
const SLOP = 12
// Half the bar's height: past this, letting go dismisses it. A flick clears it anyway.
const DISMISS_DISTANCE = 24
// The slide-out and collapse; the bar is removed once they're done.
const LEAVE_MS = 200
type Drag = { id: number; x: number; y: number; active: boolean }
/** On a phone browser: offers to open this site's links in the Raven app from now on; swipe up to dismiss. */
export const OpenInAppBar = () => {
const [shown, setShown] = useState(offersApp)
const [leaving, setLeaving] = useState(false)
const [offset, setOffset] = useState(0)
const [dragging, setDragging] = useState(false)
const drag = useRef<Drag | null>(null)
// The click a finished drag leaves behind must not open the app.
const swallowClick = useRef(false)
if (!shown) return null
const onPointerDown = (event: React.PointerEvent) => {
if (event.pointerType !== "touch" || drag.current) return
swallowClick.current = false
drag.current = { id: event.pointerId, x: event.clientX, y: event.clientY, active: false }
}
const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
const d = drag.current
if (!d || d.id !== event.pointerId) return
const dx = event.clientX - d.x
const dy = event.clientY - d.y
if (!d.active) {
if (Math.abs(dx) > SLOP && Math.abs(dx) > Math.abs(dy)) { drag.current = null; return }
if (-dy <= SLOP) return
d.active = true
setDragging(true)
event.currentTarget.setPointerCapture(event.pointerId)
}
setOffset(Math.min(0, dy))
}
const onPointerEnd = (event: React.PointerEvent) => {
const d = drag.current
if (!d || d.id !== event.pointerId) return
drag.current = null
if (!d.active) return
setDragging(false)
swallowClick.current = true
if (event.type === "pointercancel" || d.y - event.clientY <= DISMISS_DISTANCE) return setOffset(0)
dismissApp()
setLeaving(true)
// A timer, not transitionend: a browser that can't animate grid rows never sends it.
setTimeout(() => setShown(false), LEAVE_MS)
}
return (
// Collapses after sliding out, so the page closes the gap instead of jumping.
<div className={cn("grid shrink-0 transition-[grid-template-rows] duration-200 ease-out", leaving ? "grid-rows-[0fr]" : "grid-rows-[1fr]")}>
<div
className={cn(
// No padding here: it couldn't collapse. The row inside carries it.
"relative min-h-0 touch-none overflow-hidden border-b border-outline-gray-1 bg-surface-gray-2",
dragging ? "transition-none" : "transition-[transform,opacity] duration-200 ease-out",
)}
style={{ transform: leaving ? "translateY(-100%)" : offset ? `translateY(${offset}px)` : undefined, opacity: leaving ? 0 : undefined }}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerEnd}
onPointerCancel={onPointerEnd}
onClickCapture={(event) => {
if (!swallowClick.current) return
swallowClick.current = false
event.stopPropagation()
}}
>
<div className="flex items-center gap-3 px-3 py-2">
<span className="min-w-0 flex-1 truncate text-base text-ink-gray-8">{_("Open in the Raven app")}</span>
<Button size="md" onClick={() => { setShown(false); openInApp({ orStore: true }) }}>
{_("Open")}
<ExternalLinkIcon aria-hidden />
</Button>
</div>
{/* Handle: says the bar swipes away. */}
<span aria-hidden className="absolute bottom-0.5 left-1/2 h-1 w-8 -translate-x-1/2 rounded-full bg-surface-gray-4" />
</div>
</div>
)
}

View File

@ -1,4 +1,5 @@
import { siteFetch, siteKey } from "@lib/site"
import { isStandalone } from "@utils/platform"
/**
* Web push via Raven Cloud (v3+).
*
@ -73,17 +74,6 @@ export const isPushSupportedByBrowser = (): boolean =>
export const isPushEnabled = (): boolean =>
localStorage.getItem(siteKey(import.meta.env.VITE_NATIVE ? "raven-native-fcm-token" : TOKEN_STORAGE_KEY)) !== null
/**
* Running as an INSTALLED app (home screen / desktop PWA) rather than a browser
* tab. Installation is a personal-device signal — offline persistence of user
* data (rendered shell, boot cache) is gated on it, so shared-machine browser
* sessions leave nothing extra at rest.
*/
export const isStandalone = (): boolean =>
window.matchMedia("(display-mode: standalone)").matches ||
// iOS home-screen apps report through navigator.standalone instead
(navigator as { standalone?: boolean }).standalone === true
/** Lazily create the Firebase Messaging instance from boot config. */
const getMessagingInstance = async () => {
const cfg = getBootPushConfig()

View File

@ -10,7 +10,12 @@ scan({
});
import { initPushNotifications, isStandalone } from "@lib/push";
import { initPushNotifications } from "@lib/push";
import { isStandalone } from "@utils/platform";
import { openInApp, wantsApp } from "@utils/openInApp";
// A link opened in a phone browser goes to the Raven app once someone chose it; the page loads on behind it.
if (wantsApp()) openInApp()
if (import.meta.env.DEV) {
fetch('/api/method/raven.www.raven.get_context_for_dev', {

View File

@ -2,6 +2,7 @@ import { useEffect } from "react"
import { useNavigate } from "react-router-dom"
import { isRootPath, registerAndroidBack } from "./back"
import { subscribeLinkClicks } from "./links"
import { followPendingLink, openSiteLink, subscribeSiteLinks } from "./linkIn"
import { trackKeyboardInset } from "./keyboard"
import { toast } from "sonner"
import _ from "@lib/translate"
@ -10,7 +11,7 @@ import { openNotificationTarget, subscribeForeignSiteNotifications, subscribeNot
import { subscribeShareDelivery } from "./shareIn"
import type { VersionNotice } from "./SitePicker"
/** Listeners that need the router: back, push taps, foreign pushes, share delivery, link clicks. */
/** Listeners that need the router: back, push taps, foreign pushes, share delivery, link clicks, links from a browser. */
export default function NativeBridge() {
const navigate = useNavigate()
@ -23,6 +24,7 @@ export default function NativeBridge() {
const unLinks = subscribeLinkClicks(navigate)
const unKeyboard = trackKeyboardInset()
const unTap = subscribeNotificationTaps((data) => { openNotificationTarget(data, go).catch(() => { }) })
const unSiteLinks = subscribeSiteLinks((link) => { openSiteLink(link, go).catch(() => { }) })
const unForeign = subscribeForeignSiteNotifications()
void watchNotifications(true)
// A page leaving takes its listeners with it, and this effect's cleanup does not run.
@ -30,6 +32,7 @@ export default function NativeBridge() {
window.addEventListener("pagehide", onLeave)
const unShare = subscribeShareDelivery(go)
pendingPath.take().then((path) => path && go(path))
followPendingLink(go).catch(() => { })
pendingNotice.take().then((stored) => {
if (!stored || disposed) return
const notice = JSON.parse(stored) as VersionNotice
@ -40,7 +43,7 @@ export default function NativeBridge() {
disposed = true
window.removeEventListener("pagehide", onLeave)
void watchNotifications(false)
unBack(); unLinks(); unKeyboard(); unTap(); unForeign(); unShare()
unBack(); unLinks(); unKeyboard(); unTap(); unSiteLinks(); unForeign(); unShare()
}
}, [navigate])

View File

@ -7,7 +7,8 @@ import _ from "@lib/translate"
import { cn } from "@lib/utils"
import { revokeTokens, signIn, tokenStore } from "./auth"
import { subscribeNativeKeyboard } from "./keyboard"
import { pendingNotice, pendingPath, pendingRelogin } from "./pending"
import { subscribeSiteLinks } from "./linkIn"
import { pendingLink, pendingNotice, pendingPath, pendingRelogin } from "./pending"
import { unsubscribeSitePush } from "./push"
import { completeSite, forgetSite, loadSites, normalizeSiteUrl, probeSite, saveSite, setDefaultSite, wipeAccountData, wipeSiteData, type ProbeResult, type Site } from "./sites"
import { versionAtLeast, versionMismatch } from "./version"
@ -146,6 +147,21 @@ export const SitePicker = () => {
})
}, [])
// A link from a browser: a saved site opens on it, any other waits in the form to be added.
useEffect(() => {
const offer = async (link: string) => {
await pendingLink.set(link)
const origin = new URL(link).origin
const site = (await loadSites()).find((s) => s.url === origin)
if (site) return run(site.url, () => open(site))
// As typed: the bare host, when the form reads it back to the same address.
const { host } = new URL(origin)
setUrl(normalizeSiteUrl(host) === origin ? host : origin)
}
pendingLink.peek().then((link) => { if (link) void offer(link) }).catch(() => { })
return subscribeSiteLinks((link) => { void offer(link) })
}, [])
const run = async (key: string, action: () => Promise<void>) => {
setBusy(key)
setError(null)

View File

@ -11,6 +11,7 @@ import { getDefaultSite, loadSites, refreshSite } from "./sites"
import { SitePicker } from "./SitePicker"
import { hideNativeSplash } from "./splash"
import { initNativePush } from "./push"
import { routeLaunchLink } from "./linkIn"
// A site that does not answer holds boot for its timeouts. Past this the page says so and
// offers the way out. Longer than a healthy open on a slow network, shorter than the first timeout.
@ -45,6 +46,8 @@ const socketUrl = (origin: string) => {
/** The default site with live tokens opens the app; anything else shows the picker. */
const boot = async () => {
document.documentElement.classList.add("native")
// A browser link the app was opened with picks the site first: the default one may be down.
await routeLaunchLink().catch(() => { })
const url = await getDefaultSite()
const site = url ? (await loadSites()).find((s) => s.url === url) : undefined
if (site) slowBoot = setTimeout(() => render(<BootErrorScreen status="connecting" host={new URL(site.url).host} />), SLOW_BOOT_MS)

View File

@ -0,0 +1,58 @@
import { describe, expect, it } from "vitest"
import { linkAction, linkFromAppUrl, skipsLaunchEcho, withHandled } from "./linkIn"
const site = "https://a.com/raven/ws/general"
describe("linkFromAppUrl", () => {
it("reads the site link a raven://open address carries", () => {
expect(linkFromAppUrl(`raven://open?url=${encodeURIComponent(site)}`)).toBe(site)
})
it("takes the slash some browsers add before the query", () => {
expect(linkFromAppUrl(`raven://open/?url=${encodeURIComponent(site)}`)).toBe(site)
})
it("takes the page Safari's Smart App Banner passes as is", () => {
expect(linkFromAppUrl(site)).toBe(site)
})
it("ignores shares, other schemes and non-web links", () => {
expect(linkFromAppUrl("raven://?title=a&url=b")).toBeNull()
expect(linkFromAppUrl(`raven.thecommit.company://oauth?url=${encodeURIComponent(site)}`)).toBeNull()
expect(linkFromAppUrl(`raven://open?url=${encodeURIComponent("javascript:alert(1)")}`)).toBeNull()
expect(linkFromAppUrl("raven://open")).toBeNull()
})
})
describe("withHandled", () => {
it("keeps the launch link known however many links follow, so a reload never replays it", () => {
let handled = withHandled([], "raven://open?url=launch")
for (let i = 0; i < 50; i++) handled = withHandled(handled, `raven://open?url=${i}`)
expect(handled).toContain("raven://open?url=launch")
})
it("records a link once", () => {
expect(withHandled(withHandled([], "a"), "a")).toEqual(["a"])
})
})
describe("linkAction", () => {
const saved = ["https://a.com", "https://b.com"]
it("stays on the open site for its own links", () => {
expect(linkAction("https://a.com/raven/threads", "https://a.com", saved)).toBe("here")
})
it("switches to another saved site", () => {
expect(linkAction("https://b.com/raven/threads", "https://a.com", saved)).toBe("switch")
})
it("adds a site that isn't saved, with or without a site open", () => {
expect(linkAction("https://c.com/raven/threads", "https://a.com", saved)).toBe("add")
expect(linkAction("https://c.com/raven/threads", null, [])).toBe("add")
})
})
describe("skipsLaunchEcho", () => {
it("skips the event repeating the launch link boot opened, once", () => {
expect(skipsLaunchEcho("raven://open?url=a", "raven://open?url=a")).toBe(true)
expect(skipsLaunchEcho("raven://open?url=a", null)).toBe(false)
})
it("lets other links through", () => {
expect(skipsLaunchEcho("raven://open?url=b", "raven://open?url=a")).toBe(false)
})
})

View File

@ -0,0 +1,89 @@
// Site links a phone's browser hands over: `raven://open?url=<link>` (the web app's OpenInApp), or the page from Safari's Smart App Banner.
import { siteOrigin } from "@lib/site"
import { pendingLink } from "./pending"
import { listenNative, nativePlatform } from "./platform"
import { openNotificationTarget, resolveNotificationTarget } from "./push"
import { loadSites, setDefaultSite } from "./sites"
// Every link handled this session, kept over reloads: getLaunchUrl answers the same one again after each
// (the launch link on Android, the latest link on iOS).
const HANDLED_KEY = "raven-handled-links"
const handledLinks = (): string[] => {
try { return JSON.parse(sessionStorage.getItem(HANDLED_KEY) ?? "[]") as string[] } catch { return [] }
}
/** The session's handled links with one more; none is ever dropped, so none can replay. */
export const withHandled = (handled: string[], appUrl: string): string[] =>
handled.includes(appUrl) ? handled : [...handled, appUrl]
const markHandled = (appUrl: string) => sessionStorage.setItem(HANDLED_KEY, JSON.stringify(withHandled(handledLinks(), appUrl)))
// iOS also holds the launch link for the first appUrlOpen listener. Boot has opened it already.
const LAUNCH_ECHO_KEY = "raven-launch-echo"
/** Whether an event only repeats the launch link boot opened. True once: a later tap on it is real. */
export const skipsLaunchEcho = (appUrl: string, echo: string | null) => appUrl === echo
/**
* The site link in an address the app was opened with: `raven://open?url=<link>` from the web app, or the
* page itself from Safari's Smart App Banner. Null for anything else, shares (`raven://?…`) included.
*/
export const linkFromAppUrl = (appUrl: string): string | null => {
if (/^https?:\/\//i.test(appUrl)) return appUrl
const query = /^raven:\/\/open\/?\?(.*)$/.exec(appUrl)?.[1]
const link = query ? new URLSearchParams(query).get("url") : null
return link && /^https?:\/\//i.test(link) ? link : null
}
/** Links that arrive while the app runs. The one it was launched with is boot's, through routeLaunchLink. */
export const subscribeSiteLinks = (open: (link: string) => void): (() => void) =>
listenNative(async () => (await import("@capacitor/app")).App.addListener("appUrlOpen", ({ url }) => {
if (skipsLaunchEcho(url, sessionStorage.getItem(LAUNCH_ECHO_KEY))) return sessionStorage.removeItem(LAUNCH_ECHO_KEY)
const link = linkFromAppUrl(url)
if (!link) return
markHandled(url)
open(link)
}))
/**
* Boot, before the default site loads: a link the app was opened with picks the site to open, a saved
* site's or the picker. The default site may be down, and the link's site is the one wanted anyway.
* The page follows once that site is open (followPendingLink), or the picker offers the site to add.
*/
export const routeLaunchLink = async () => {
const { App } = await import("@capacitor/app")
const launch = (await App.getLaunchUrl().catch(() => undefined))?.url
if (!launch || handledLinks().includes(launch)) return
markHandled(launch)
const link = linkFromAppUrl(launch)
if (!link) return
if (nativePlatform() === "ios") sessionStorage.setItem(LAUNCH_ECHO_KEY, launch)
await pendingLink.set(link)
const origin = new URL(link).origin
await setDefaultSite((await loadSites()).some((s) => s.url === origin) ? origin : null)
}
/** Whether a link is for the open site, another saved one, or a site to add. */
export const linkAction = (link: string, current: string | null, saved: string[]): "here" | "switch" | "add" => {
const origin = new URL(link).origin
if (origin === current) return "here"
return saved.includes(origin) ? "switch" : "add"
}
/** A link to this site navigates; to another saved site, that site opens on it; to any other, the picker offers it. */
export const openSiteLink = async (link: string, navigate: (path: string) => void) => {
if (linkAction(link, siteOrigin(), (await loadSites()).map((s) => s.url)) !== "add") {
return openNotificationTarget({ message_url: link }, navigate)
}
await pendingLink.set(link)
await setDefaultSite(null)
window.location.replace("/")
}
/** Once a site opens: the page of the link that led here, if the user signed in to that link's site. */
export const followPendingLink = async (navigate: (path: string) => void) => {
const link = await pendingLink.take()
const target = link ? resolveNotificationTarget({ message_url: link }, siteOrigin()) : null
if (target?.kind === "same-site") navigate(target.path)
}

View File

@ -14,6 +14,8 @@ export const pending = (key: string) => ({
/** Route to open after the reload a push tap to another site or a share on the picker causes. */
export const pendingPath = pending("pendingPath")
/** A browser link to a site that wasn't saved: the picker offers the site, and the page opens once it's signed in. */
export const pendingLink = pending("pendingLink")
/** A warning to toast once the app is up (version mismatch, update prompt). */
export const pendingNotice = pending("pendingNotice")
/** Site whose session died: the picker signs it in again on mount. */

View File

@ -0,0 +1,87 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
const store = new Map<string, string>()
let hidden = false
const listeners = new Set<() => void>()
beforeEach(() => {
vi.useFakeTimers()
store.clear()
hidden = false
listeners.clear()
vi.stubGlobal("localStorage", {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => { store.set(k, v) },
removeItem: (k: string) => { store.delete(k) },
})
vi.stubGlobal("document", {
get hidden() { return hidden },
addEventListener: (_: string, fn: () => void) => { listeners.add(fn) },
removeEventListener: (_: string, fn: () => void) => { listeners.delete(fn) },
})
vi.stubGlobal("location", { href: "https://a.com/raven/ws/general" })
vi.stubGlobal("navigator", { userAgent: "Mozilla/5.0 (Linux; Android 16)", platform: "Linux", maxTouchPoints: 5 })
vi.stubGlobal("window", { matchMedia: () => ({ matches: false }) })
vi.resetModules()
})
afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals() })
const load = () => import("./openInApp")
const hide = () => { hidden = true; listeners.forEach((fn) => fn()) }
describe("openInApp", () => {
it("hands the page to the app as a raven://open link", async () => {
const { openInApp } = await load()
openInApp()
expect(location.href).toBe(`raven://open?url=${encodeURIComponent("https://a.com/raven/ws/general")}`)
})
it("remembers the app once it takes over", async () => {
const { openInApp, wantsApp } = await load()
openInApp()
hide()
expect(wantsApp()).toBe(true)
})
it("forgets the app when it doesn't open, and remembers it if it opens later", async () => {
store.set("raven-open-in-app", "1")
const { openInApp, wantsApp } = await load()
openInApp()
vi.advanceTimersByTime(3000)
expect(wantsApp()).toBe(false)
hide()
expect(wantsApp()).toBe(true)
})
it("ignores the page hiding long after, when it can't be the app opening", async () => {
const { openInApp, wantsApp } = await load()
openInApp()
vi.advanceTimersByTime(60_000)
hide()
expect(wantsApp()).toBe(false)
})
it("on Android, a tap opens the app or else its Play Store page", async () => {
const { openInApp } = await load()
openInApp({ orStore: true })
expect(location.href).toMatch(/^intent:\/\/open\?url=.+#Intent;scheme=raven;package=raven\.thecommit\.company;S\.browser_fallback_url=https%3A%2F%2Fplay\.google\.com%2F.+;end$/)
})
it("leaves iPhone Safari to its own Smart App Banner", async () => {
const iphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1"
vi.stubGlobal("navigator", { userAgent: iphone, platform: "iPhone", maxTouchPoints: 5 })
expect((await load()).offersApp()).toBe(false)
vi.resetModules()
vi.stubGlobal("navigator", { userAgent: iphone.replace("Version/18.0", "CriOS/130.0"), platform: "iPhone", maxTouchPoints: 5 })
expect((await load()).offersApp()).toBe(true)
})
it("offers the app on a phone browser until it's chosen or dismissed", async () => {
const { offersApp, dismissApp } = await load()
expect(offersApp()).toBe(true)
dismissApp()
expect(offersApp()).toBe(false)
})
it("never offers it on a desktop or in the installed web app", async () => {
vi.stubGlobal("navigator", { userAgent: "Mozilla/5.0 (Macintosh)", platform: "MacIntel", maxTouchPoints: 0 })
expect((await load()).offersApp()).toBe(false)
vi.resetModules()
vi.stubGlobal("navigator", { userAgent: "Mozilla/5.0 (iPhone)", platform: "iPhone", maxTouchPoints: 5 })
vi.stubGlobal("window", { matchMedia: () => ({ matches: true }) })
expect((await load()).offersApp()).toBe(false)
})
})

View File

@ -0,0 +1,61 @@
import { isAndroid, isIOS, isStandalone } from "@utils/platform"
// "1": links on this site open in the Raven app, in this browser. "0": the offer was dismissed.
const KEY = "raven-open-in-app"
// The page goes to the background within this when the app takes over.
const TAKEOVER_MS = 2500
// Safari's own "Open in Raven?" prompt can take this long to answer; a page hidden later is something else.
const ANSWER_MS = 15_000
const PACKAGE = "raven.thecommit.company"
const PLAY_STORE = `https://play.google.com/store/apps/details?id=${PACKAGE}`
const read = () => { try { return localStorage.getItem(KEY) } catch { return null } }
const write = (value: string | null) => {
try {
if (value === null) localStorage.removeItem(KEY)
else localStorage.setItem(KEY, value)
} catch {
// Storage blocked (private mode): the choice just isn't kept.
}
}
const onPhoneBrowser = () => !import.meta.env.VITE_NATIVE && (isIOS || isAndroid) && !isStandalone()
// Safari's Smart App Banner (index.html) offers the app there itself: Open, or the App Store without it.
// Other iPhone browsers add their own token (CriOS, FxiOS, …) and show no banner.
const inIOSSafari = () => isIOS && /Version\/[\d.]+.*Safari\//.test(navigator.userAgent)
/** Someone chose the app for this site's links. */
export const wantsApp = () => onPhoneBrowser() && read() === "1"
/** The app is offered until it's chosen or the offer is dismissed. */
export const offersApp = () => onPhoneBrowser() && !inIOSSafari() && read() === null
export const dismissApp = () => write("0")
/**
* Hands this page to the app (apps/web/src/native/linkIn.ts). The choice is kept only once the page goes
* to the background: an app that isn't installed, or a cancelled browser prompt, leaves it here.
* `orStore`, for a tap: on Android, without the app, the Play Store opens instead. That hides the page too,
* so the next link tries the app once, and the choice clears if it's still missing. Never for the automatic
* hand-off, which would send someone to a store on every link.
*/
export const openInApp = ({ orStore = false } = {}) => {
const forget = setTimeout(() => { if (!document.hidden) write(null) }, TAKEOVER_MS)
const stop = () => {
clearTimeout(forget)
clearTimeout(giveUp)
document.removeEventListener("visibilitychange", onHide)
}
const onHide = () => {
if (!document.hidden) return
stop()
write("1")
}
const giveUp = setTimeout(stop, ANSWER_MS)
document.addEventListener("visibilitychange", onHide)
const link = `open?url=${encodeURIComponent(location.href)}`
location.href = orStore && isAndroid
? `intent://${link}#Intent;scheme=raven;package=${PACKAGE};S.browser_fallback_url=${encodeURIComponent(PLAY_STORE)};end`
: `raven://${link}`
}

View File

@ -9,3 +9,14 @@ export const isAndroid = typeof navigator !== "undefined" && /android/i.test(nav
export const isIOS = typeof navigator !== "undefined" &&
(/iPad|iPhone|iPod/.test(navigator.userAgent) ||
(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1))
/**
* Running as an INSTALLED app (home screen / desktop PWA) rather than a browser
* tab. Installation is a personal-device signal — offline persistence of user
* data (rendered shell, boot cache) is gated on it, so shared-machine browser
* sessions leave nothing extra at rest.
*/
export const isStandalone = (): boolean =>
window.matchMedia("(display-mode: standalone)").matches ||
// iOS home-screen apps report through navigator.standalone instead
(navigator as { standalone?: boolean }).standalone === true

View File

@ -1,5 +1,6 @@
import json
import re
from urllib.parse import quote
import frappe
import frappe.sessions
@ -51,7 +52,8 @@ def get_context(context):
context["mask_icon"] = favicon or "/assets/raven/raven_logo.svg"
context["favicon_svg"] = favicon or "/assets/raven/raven_logo.svg"
context["favicon_ico"] = favicon or "/assets/raven/favicon.ico"
context["sitename"] = boot.get("sitename")
# Safari's Smart App Banner hands this page to the app, or offers the App Store without it.
context["app_argument"] = get_app_argument()
if frappe.session.user != "Guest":
capture("active_site", "raven")
@ -71,6 +73,18 @@ def get_context(context):
return context
def get_app_argument() -> str:
"""
This page's address for the Smart App Banner. The query stays: a message link's ?message_id= is in it.
Escaped as a whole: the address is the visitor's, and the template doesn't escape it.
"""
if not frappe.request:
return ""
query = frappe.request.query_string.decode(errors="replace")
page = quote(frappe.request.path, safe="/") + (f"?{query}" if query else "")
return frappe.utils.escape_html(frappe.utils.get_url(page))
@frappe.whitelist(methods=["POST"], allow_guest=True)
def get_context_for_dev():
if not frappe.conf.developer_mode: