flotilla/src/routes/+layout.svelte

306 lines
10 KiB
Svelte
Raw Normal View History

2024-08-05 21:45:16 +00:00
<script lang="ts">
import "@lib/components/theme.css"
2026-04-07 21:53:19 +00:00
import "@welshman/editor/index.css"
import {debounce} from "throttle-debounce"
2025-01-28 21:04:37 +00:00
import * as nip19 from "nostr-tools/nip19"
import type {Unsubscriber} from "svelte/store"
2025-10-06 18:23:19 +00:00
import {get} from "svelte/store"
2025-08-26 16:14:11 +00:00
import {App, type URLOpenListenerEvent} from "@capacitor/app"
2024-10-23 16:45:06 +00:00
import {dev} from "$app/environment"
2025-01-28 21:04:37 +00:00
import {goto} from "$app/navigation"
import {page} from "$app/stores"
import {context as pomadeContext} from "@pomade/core"
2026-07-28 16:16:26 +00:00
import {sync, throttled} from "@welshman/store"
import * as domain from "@welshman/domain"
import * as util from "@welshman/util"
2026-07-28 16:16:26 +00:00
import * as lib from "@welshman/lib"
import {Logger} from "@welshman/app"
import {isMobile, documentActive} from "@lib/html"
import AppContainer from "@app/components/AppContainer.svelte"
import ModalContainer from "@app/components/ModalContainer.svelte"
2026-07-28 16:16:26 +00:00
import {app} from "@app/core"
2026-06-08 21:14:40 +00:00
import {setupHistory} from "@app/routes"
import {setupAnalytics} from "@app/analytics"
2026-08-13 19:57:42 +00:00
import {setupLogging} from "@app/logger"
2026-07-28 16:16:26 +00:00
import "@app/policies"
import {restoreSession} from "@app/session"
import {signerRequests} from "@app/signer"
import {wallet} from "@app/lightning"
import {kv, ss, storage} from "@app/storage"
import {device} from "@app/device"
2026-07-28 16:16:26 +00:00
import {userSettingsValues, notificationSettings} from "@app/settings"
2026-08-11 21:54:05 +00:00
import {setupShareIntents, shareFromNative} from "@app/share"
2026-07-28 16:16:26 +00:00
import {shouldUnwrap, syncApplicationData} from "@app/sync"
import * as env from "@app/env"
2026-08-12 23:37:51 +00:00
import {activeTheme, flTheme, theme} from "@app/theme"
2026-06-08 21:14:40 +00:00
import {toast, pushToast} from "@app/toast"
import * as notifications from "@app/notifications"
2026-08-17 16:41:38 +00:00
import {
notifications as notificationPaths,
allNotifications,
latestActivityByPath,
} from "@app/notifications"
2026-06-08 21:14:40 +00:00
import {Push} from "@app/push"
2026-07-28 16:16:26 +00:00
import {onPushNotificationAction, pushState} from "@app/push/adapters/common"
2026-06-08 21:14:40 +00:00
import {syncKeyboard} from "@app/keyboard"
import {syncCallAudioResume} from "@app/call"
2026-06-08 21:14:40 +00:00
import {getPageTitle} from "@app/title"
import NewNotificationSound from "@src/app/components/NewNotificationSound.svelte"
2025-09-30 23:11:49 +00:00
2025-10-21 15:27:30 +00:00
const {children} = $props()
2024-08-05 21:45:16 +00:00
2026-08-12 23:37:51 +00:00
// Do this asap to avoid a flash of the wrong font size or theme. The stores these mirror live in
// indexeddb, which doesn't load until well after first paint.
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches
2026-07-01 23:32:25 +00:00
// @ts-ignore
document.documentElement.style["font-size"] = `${localStorage.getItem("font-size") || 1.1}rem`
2026-08-12 23:37:51 +00:00
document.body.setAttribute("data-fl-theme", localStorage.getItem("fl-theme") || env.FL_THEME)
document.body.setAttribute(
"data-theme",
localStorage.getItem("theme") || (prefersDark ? "dark" : "light"),
)
2026-07-01 23:32:25 +00:00
2025-10-21 15:27:30 +00:00
// Add stuff to window for convenience
2026-07-28 16:16:26 +00:00
Object.assign(window, {get, nip19, theme, app, domain, Logger, ...lib, ...util})
2024-10-23 00:29:43 +00:00
// Set up context for various modules
2026-07-28 16:16:26 +00:00
pomadeContext.setSignerUrls(env.POMADE_SIGNERS)
pomadeContext.setArgonWorker(import("@pomade/core/argon-worker.js?worker"))
// Handle a deep link (universal/app link or custom scheme). Used for both
// warm-start links (via the appUrlOpen event) and cold-start links (via
// getLaunchUrl below) so the invite relay/claim query params are preserved
// in either case.
const handleDeepLink = (rawUrl: string) => {
const url = new URL(rawUrl)
const relay = url.searchParams.get("relay")
const id = url.searchParams.get("id")
if (relay && id) {
onPushNotificationAction({notification: {data: {relay, id}}} as any)
return
}
2026-08-11 21:54:05 +00:00
// The iOS share extension can't talk to us directly, so it hands its payload over as a
// flotilla://share url
if (url.host === "share") {
shareFromNative(Object.fromEntries(url.searchParams))
return
}
if (url.host === "x-callback-url") {
if (url.pathname === "/authError") {
const errorMessage = url.searchParams.get("errorMessage")
pushToast({
theme: "error",
message: errorMessage || "Signer authorization failed.",
})
}
if (["/authSuccess", "/authError"].includes(url.pathname)) {
return
}
}
2025-10-21 15:27:30 +00:00
const target = `${url.pathname}${url.search}${url.hash}`
goto(target, {replaceState: false, noScroll: false})
}
// Listen for deep link events. Capacitor only emits this from onNewIntent, so
// it fires when the app is already running (warm start). Cold-start links are
// handled by getLaunchUrl in the setup block below.
App.addListener("appUrlOpen", (event: URLOpenListenerEvent) => handleDeepLink(event.url))
2025-06-19 17:22:17 +00:00
2025-10-21 15:27:30 +00:00
// Handle back button on mobile
App.addListener("backButton", () => {
if (window.history.length > 1) {
window.history.back()
} else {
App.exitApp()
}
})
2025-08-26 16:14:11 +00:00
2026-07-28 16:16:26 +00:00
const closeStorage = () => storage.get()?.close()
2025-11-14 22:59:27 +00:00
// Cleanup on page close
2026-07-28 16:16:26 +00:00
window.addEventListener("beforeunload", closeStorage)
2025-11-14 22:59:27 +00:00
2026-07-28 16:16:26 +00:00
const unsubscribe = lib.call(async () => {
const unsubscribers: Unsubscriber[] = []
2024-10-25 21:15:35 +00:00
2026-07-28 16:16:26 +00:00
// Attach the user before anything reads or decrypts on their behalf
unsubscribers.push(await restoreSession())
2026-08-13 19:57:42 +00:00
// Set up logging
unsubscribers.push(setupLogging())
2026-03-24 00:51:51 +00:00
// Sync stuff to storage
2025-10-21 15:27:30 +00:00
await Promise.all([
2026-01-28 01:15:22 +00:00
sync({
key: "device",
store: device,
storage: kv,
}),
2025-10-21 15:27:30 +00:00
sync({
2026-07-28 16:16:26 +00:00
key: "shouldUnwrap",
store: shouldUnwrap,
2025-11-12 01:49:22 +00:00
storage: kv,
2025-10-21 15:27:30 +00:00
}),
sync({
2026-07-28 16:16:26 +00:00
key: "wallet",
store: wallet,
2026-03-24 00:51:51 +00:00
storage: ss,
2025-10-21 15:27:30 +00:00
}),
2026-01-24 00:51:02 +00:00
sync({
key: "notificationSettings",
store: notificationSettings,
storage: kv,
}),
sync({
key: "notificationState",
store: pushState,
storage: kv,
}),
2025-10-21 15:27:30 +00:00
])
2026-03-12 18:33:04 +00:00
// Wait for critical storage data only
2026-07-28 16:16:26 +00:00
await storage.get()?.ready
2025-11-14 22:59:27 +00:00
// Handle cold-start deep links. When a link launches the app from a killed
// state the intent arrives via onCreate, so Capacitor never emits
// appUrlOpen for it — the URL is only reachable through getLaunchUrl.
// Without this, invite links opened while the app is closed lose their
// relay/claim params and the space is never joined.
const launch = await App.getLaunchUrl()
if (launch?.url) {
handleDeepLink(launch.url)
}
2025-11-14 22:59:27 +00:00
// Close the database connection on reload
2026-07-28 16:16:26 +00:00
unsubscribers.push(closeStorage)
2025-10-21 15:27:30 +00:00
2026-01-16 23:19:52 +00:00
// History, navigation, application data
2026-07-27 23:20:27 +00:00
unsubscribers.push(setupHistory(), setupAnalytics(), syncApplicationData())
2026-08-11 21:54:05 +00:00
// Listen for links shared into the app from elsewhere on the device
unsubscribers.push(setupShareIntents())
2025-11-25 23:30:40 +00:00
// Initialize keyboard state tracking
unsubscribers.push(syncKeyboard())
// Reacquire the mic if the screen locked mid-call and capture died
unsubscribers.push(syncCallAudioResume())
// Subscribe to badge count for changes
unsubscribers.push(notifications.syncBadges())
// Subscribe to page history to update checked state
unsubscribers.push(notifications.syncChecked())
// Sync checked state across devices
unsubscribers.push(notifications.syncCheckedRemote())
2026-01-20 18:40:33 +00:00
// Initialize background notifications
unsubscribers.push(Push.sync())
2026-01-20 18:40:33 +00:00
2026-07-28 16:16:26 +00:00
// Logging in swaps in a fresh app — its policies rebind themselves, we just have to sync
// application data against the new identity's relays.
let currentApp = app.get()
unsubscribers.push(
2026-07-28 16:16:26 +00:00
app.subscribe($app => {
if ($app !== currentApp) {
currentApp = $app
2026-07-27 23:20:27 +00:00
syncApplicationData()
}
}),
)
// Listen for signer errors, report to user via toast
unsubscribers.push(
2026-07-28 16:16:26 +00:00
throttled(10_000, signerRequests).subscribe($requests => {
2026-02-09 19:12:54 +00:00
if ($toast) return
2026-01-06 23:30:54 +00:00
2026-02-09 19:12:54 +00:00
const longCutoff = Date.now() - 30_000
const shortCutoff = Date.now() - 10_000
2026-07-28 16:16:26 +00:00
const pending = $requests.filter(r => !r.finishedAt && r.startedAt < longCutoff)
const completed = $requests.filter(r => r.finishedAt && r.finishedAt > shortCutoff)
2026-02-09 19:12:54 +00:00
const showPendingError = pending.length > 10
2026-07-28 16:16:26 +00:00
const showCompletedError = completed.length > 5 && completed.filter(r => r.ok).length === 0
2026-02-09 19:12:54 +00:00
if (showPendingError || showCompletedError) {
2026-01-06 23:30:54 +00:00
pushToast({
theme: "error",
timeout: 60_000,
2026-02-09 19:12:54 +00:00
message: "Your signer isn't responding.",
2026-01-06 23:30:54 +00:00
action: {
message: "Details",
onclick: () => goto("/settings/profile"),
},
})
}
}),
)
// Sync theme and font size
unsubscribers.push(
2026-08-12 23:37:51 +00:00
activeTheme.subscribe($activeTheme => {
localStorage.setItem("theme", $activeTheme)
document.body.setAttribute("data-theme", $activeTheme)
}),
flTheme.subscribe($flTheme => {
localStorage.setItem("fl-theme", $flTheme)
document.body.setAttribute("data-fl-theme", $flTheme)
}),
2026-07-28 16:16:26 +00:00
userSettingsValues.subscribe(
debounce(100, $settings => {
localStorage.setItem("font-size", String($settings.font_size))
// @ts-ignore
document.documentElement.style["font-size"] = `${$settings.font_size}rem`
}),
),
)
2026-07-28 16:16:26 +00:00
return () => unsubscribers.forEach(lib.call)
})
2025-10-21 15:27:30 +00:00
// Cleanup on hot reload
import.meta.hot?.dispose(() => {
App.removeAllListeners()
2026-07-28 16:16:26 +00:00
unsubscribe.then(lib.call)
2024-08-09 00:22:17 +00:00
})
$effect(() => {
const title = getPageTitle({page: $page, pubkey: $app.user?.pubkey})
// While the tab isn't actively focused the user isn't actually looking at the
// active page, so count notifications for it too rather than treating it as read.
2026-08-17 16:41:38 +00:00
const paths = $documentActive ? $notificationPaths : $allNotifications
const unreadCount = [...$latestActivityByPath.keys()].filter(path => paths.has(path)).length
document.title = unreadCount > 0 ? `(${unreadCount}) ${title}` : title
})
2024-08-05 21:45:16 +00:00
</script>
2024-10-23 16:45:06 +00:00
<svelte:head>
{#if !dev}
<link rel="manifest" href="/manifest.webmanifest" />
{/if}
</svelte:head>
{#await unsubscribe}
2025-10-21 16:26:06 +00:00
<!-- pass -->
2024-08-14 19:46:25 +00:00
{:then}
2026-08-12 23:37:51 +00:00
<div class={isMobile ? "fl mobile" : "fl"} data-fl-theme={$flTheme}>
<AppContainer>
2025-02-04 00:37:14 +00:00
{@render children()}
</AppContainer>
<ModalContainer />
2025-02-03 23:01:42 +00:00
<div class="tippy-target"></div>
<NewNotificationSound />
2024-08-05 21:45:16 +00:00
</div>
2024-08-14 19:46:25 +00:00
{/await}