diff --git a/CHANGELOG.md b/CHANGELOG.md index e885bf842a..c900898216 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,16 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +- **OpenBot Mobile: four tabs, one place for notifications, and Account in the look of the other + tabs.** The tabs are Chats, Bots, Account and More. Notifications, in More, is everything that + waits on you: approvals and questions from your Bots, what their check-ins found, and the tasks + that wait, with the phone's switch for notifications at its top, which now turns them off too. It + replaces the approval inbox and the Needs you tab, and More's badge counts what is in it. More + opens a small menu above the tab bar, over the tab you are on: Material's own on Android. + Account is a list to the screen's edges: who is signed in, each organization with its letter and + a tick on the one you work in, then Sign out and Delete account. Swipe an organization to delete + it, if you own it, or to leave it. The Delete account and Delete organization sheets follow. A + list with nothing in it yet says so in the middle of the screen. - **Delete your account from OpenBot Mobile.** Account, then Delete account: type your email address and "delete my account". The account goes in 14 days, or at once with Delete now, as in the web app. A sign-in older than ten minutes is asked for again first. Somebody who signs in again before diff --git a/docs/app-guidelines.md b/docs/app-guidelines.md index a718bbcbcb..015bdd6df9 100644 --- a/docs/app-guidelines.md +++ b/docs/app-guidelines.md @@ -228,13 +228,39 @@ Native's, and builds its own only when neither fits. The development build shows security floor, the session and the version check have answered, and then the orb glides into Welcome, or swells and fades into a signed-in screen. Nothing else draws a loading screen of its own while the app opens. -- **The tabs** are the signed-in app's five, in the platform's tab bar, as icons with no words: - Chats, Bots (OpenBot's orb as a flat glyph), your Account in the middle, Needs you (its badge - counts what waits), and More (Routines, the approval inbox with a count of what waits there, Memory, - Skills and Connections). Each tab is a stack of its own with the native header, its title at the +- **The tabs** are the signed-in app's four, in the platform's tab bar, as icons with no words: + Chats, Bots (OpenBot's orb as a flat glyph), your Account, and More (Routines, Notifications, + Memory, Skills and Connections). More's badge counts what waits on the person, which + Notifications lists. Each tab is a stack of its own with the native header, its title at the start of the bar. A conversation, a Bot and everything else opened from a tab open in the app's - stack over the tabs, so the tab bar steps aside and the message box has the bottom to itself; - what opens from More stays in More. + stack over the tabs, so the tab bar steps aside and the message box has the bottom to itself. +- **More is a menu.** The bar's last button opens a small menu above the bar, over the tab the + person is on, and what is picked opens in the app's stack. A tab that only held a list of five + links cost a screen and a second tap. On Android it is Material's own menu + (`mobile/src/more-menu.android.tsx`), as one surface with a line between its two parts: + Material's grouped menu draws two surfaces, and one casts its shadow onto the other. On iOS it is drawn by the app with the phone's own glass + and SF Symbols (`mobile/src/more-menu.tsx`), because iOS's own menu (`@expo/ui`'s `Menu`) always + opens over the button that opens it, so it covered the tab bar, and can't be hung from anything + else. Both read `mobile/src/more-items.ts`, and so does More as a screen, which opens where a + press reaches the tab itself. +- **Notifications is one place**, in More: the phone's switch for them, and under it everything + that waits on the person, by kind: approvals and questions from their Bots, what the Bots' + check-ins found, and the tasks that wait. It was the approval inbox and the Needs you tab. The + address `needs-you`, which a ping's notification opens, goes there. +- **A tab's own list runs to the screen's edges, with no card** (`ListRow`): Chats, Bots, and your + Account, where an organization is a row with its letter and the one worked in has the tick. A + card of rows with hairlines and icon tiles (`Rows`) is for a page of settings opened from one. + What a row is about shows in its shape: a person is a circle, a Bot its orb, an organization a + rounded square with its letter. +- **A row's own action is a swipe** (`SwipeRow`): the row slides left and one button, its glyph + alone, is in the room it leaves, as in the phone's own lists. A swipe alone never does it, and what deletes still asks + first. An organization on Account swipes for Delete (its owner) or Leave (anybody else). +- **An empty list says so in the middle of the screen** (`EmptyState`): a glyph, its name, a line or + two, and one button when the way on is right there. No box around it. A page (`ScrollScreen`) and a + tab's list (`ScreenList`) are as tall as what the bars leave, so it centers in what the person + sees and the empty page doesn't scroll. +- **The fade under the header is for what has scrolled under it.** A page at rest has none over its + own first lines. - **Chats** is the word for conversations, everywhere a person reads it. - **A chat** is headed as iMessage heads one: the orbs of the Bots in it and their names, and tapping it opens the Bot's page, or a group's Bots. It reads from the top down, and opens at its diff --git a/mobile/app/(tabs)/(account)/account.tsx b/mobile/app/(tabs)/(account)/account.tsx index ed9dc872a0..a2ea0b452b 100644 --- a/mobile/app/(tabs)/(account)/account.tsx +++ b/mobile/app/(tabs)/(account)/account.tsx @@ -1,58 +1,64 @@ -import { router } from "expo-router"; -import { useCallback, useEffect, useState } from "react"; -import { View } from "react-native"; -import { chooseOrganization, organizationChoices } from "../../../src/api"; +import { router, useFocusEffect } from "expo-router"; +import { Button } from "heroui-native/button"; +import { useCallback, useState } from "react"; +import { ActivityIndicator, Alert, View } from "react-native"; +import { useCSSVariable } from "uniwind"; +import { + chooseOrganization, + ME, + organizationChoices, + rereadOrganizations, +} from "../../../src/api"; +import { removeOrganizationMember } from "../../../src/api/generated/organizations/organizations"; import { getAccountDeletion } from "../../../src/api/generated/people/people"; import { authClient, serverUrl } from "../../../src/auth"; import { Icon, + ListRow, + Monogram, Notice, PersonAvatar, - Row, - Rows, ScrollScreen, - Section, + type SwipeAction, + SwipeRow, Text, } from "../../../src/components"; -import { - IconBell, - IconBuilding, - IconCheck, - IconLogout, - IconTrash, -} from "../../../src/icons"; -import { - pushTurnedOn, - registerPush, - unregisterPush, -} from "../../../src/notifications"; +import { IconCheck, IconLogout, IconTrash } from "../../../src/icons"; +import { unregisterPush } from "../../../src/notifications"; +import { type ListedOrganization, wayOut } from "../../../src/organization"; import { useLoad } from "../../../src/use-load"; /** - * Your account, a tab of its own: who is signed in, the organization they work in - * (and the others they can switch to), notifications on this phone, and signing out. It opens as a - * Bot's page does: the person, centered, then a card of rows for each part. + * Your account, a tab of its own: who is signed in, the organizations they can work in, and the two ways out. + * + * Everything starts on one line down the screen, as the other tabs' lists do, with no cards. Who is signed in + * is the first row. An organization is a row with its letter, and the one worked in has the tick: a tap works + * in another, and a swipe to the left is the way out of one (src/organization.ts), where its owner deletes it, + * anybody else leaves it, and the person's own has none. Sign out and Delete account are the two buttons at + * the foot, the second in the quieter red of what can't be taken back, and which OpenBot this is under them. + * Notifications are in More (app/approvals.tsx). */ export default function Account() { const { data: session } = authClient.useSession(); + const muted = useCSSVariable("--color-muted") as string | undefined; const [busy, setBusy] = useState(""); const [error, setError] = useState(""); - const [pushRegistered, setPushRegistered] = useState(false); - // Said as it is on this phone, not as it was before the app last started. - useEffect(() => { - void pushTurnedOn() - .then(setPushRegistered) - .catch(() => {}); - }, []); const loadOrganizations = useCallback(() => organizationChoices(), []); // The person's own list, whichever organization they work in: it stays on screen while it is read again. const organizations = useLoad(loadOrganizations, Boolean(session), { keep: true, }); // Deleting the account is offered where this OpenBot has it: one that answers where the deletion stands. - // The person's own too, so the line stays while it is read again. + // The person's own too, so the button stays while it is read again. const loadDeletion = useCallback(() => getAccountDeletion(), []); const deletion = useLoad(loadDeletion, Boolean(session), { keep: true }); + // Read again each time the tab comes back: an organization deleted in the sheet over it is gone from the list. + const rereadList = organizations.refresh; + useFocusEffect( + useCallback(() => { + void rereadList(); + }, [rereadList]), + ); async function act(name: string, work: () => Promise) { setBusy(name); setError(""); @@ -68,43 +74,110 @@ export default function Account() { setBusy(""); } } + /** What a row offers when it is swiped: the way out of that organization, asked about before it is done. */ + function swipe(organization: ListedOrganization): SwipeAction | undefined { + const name = organization.name ?? organization.id; + const way = wayOut(organization); + if (way === "delete") + return { + label: `Delete ${name}`, + icon: IconTrash, + tone: "danger", + // The sheet says what goes with it, and waits for its name to be typed. + onPress: () => + router.push({ + pathname: "/delete-organization", + params: { id: organization.id, name }, + }), + }; + if (way === "leave") + return { + label: `Leave ${name}`, + icon: IconLogout, + onPress: () => + Alert.alert( + `Leave ${name}?`, + "You stop being a member. What you made there stays there.", + [ + { text: "Cancel", style: "cancel" }, + { + text: "Leave", + style: "destructive", + onPress: () => + void act(organization.id, async () => { + await removeOrganizationMember(organization.id, ME); + await rereadOrganizations(); + await organizations.refresh(); + }), + }, + ], + ), + }; + return undefined; + } const person = session?.user.name || session?.user.email || ""; const listed = organizations.data?.organizations ?? []; // The OpenBot this phone is signed in to, as its address reads without the scheme. const server = serverUrl.replace(/^https?:\/\//, "").replace(/\/$/, ""); return ( - - - - - + + + + + {person} {session?.user.name && session.user.email ? ( - + {session.user.email} ) : null} - + {error || organizations.error ? ( + + + + ) : null} {listed.length > 0 ? ( -
1 ? "Organizations" : "Organization"}> - - {listed.map((organization) => { - const current = organization.id === organizations.data?.currentId; - return ( - + + {listed.length > 1 ? "Organizations" : "Organization"} + + {listed.map((organization) => { + const current = organization.id === organizations.data?.currentId; + const name = organization.name ?? organization.id; + return ( + + } + title={name} + accessibilityLabel={ + current ? `${name}, you're working here` : `Work in ${name}` + } + accessibilityState={{ + selected: current, + busy: busy === organization.id, + }} trailing={ - current ? : undefined + busy === organization.id ? ( + + ) : current ? ( + + ) : undefined } - chevron={false} + disabled={Boolean(busy)} onPress={ - current || busy + current ? undefined : () => void act(organization.id, async () => { @@ -117,70 +190,37 @@ export default function Account() { }) } /> - ); - })} - -
+ + ); + })} + ) : null} -
- - - ) : ( - - Turn on - - ) - } - chevron={false} - onPress={ - pushRegistered || busy - ? undefined - : () => - void act("push", async () => { - await registerPush(); - setPushRegistered(true); - }) - } - /> - -
- - - void act("sign-out", async () => { - await unregisterPush(); - await authClient.signOut(); - }) + + {deletion.data ? ( - router.push("/delete-account")} - /> + ) : null} - + + {`Signed in to ${server}`} + +
); } diff --git a/mobile/app/(tabs)/(bots)/bots.tsx b/mobile/app/(tabs)/(bots)/bots.tsx index 33230e40b2..18e1a9ad11 100644 --- a/mobile/app/(tabs)/(bots)/bots.tsx +++ b/mobile/app/(tabs)/(bots)/bots.tsx @@ -1,6 +1,6 @@ import { router, Stack } from "expo-router"; import { useCallback } from "react"; -import { FlatList, View } from "react-native"; +import { View } from "react-native"; import { everyBot } from "../../../src/api"; import { authClient } from "../../../src/auth"; import { @@ -9,6 +9,7 @@ import { Notice, Refresh, Screen, + ScreenList, } from "../../../src/components"; import { tabRoot } from "../../../src/header"; import { IconPlus, IconRobot } from "../../../src/icons"; @@ -34,7 +35,7 @@ export default function Bots() { }, ])} /> - bot.id} diff --git a/mobile/app/(tabs)/(conversations)/index.tsx b/mobile/app/(tabs)/(conversations)/index.tsx index 3768c55170..839d7f3e5d 100644 --- a/mobile/app/(tabs)/(conversations)/index.tsx +++ b/mobile/app/(tabs)/(conversations)/index.tsx @@ -1,7 +1,7 @@ import { router, Stack } from "expo-router"; import { Button } from "heroui-native/button"; import { useCallback, useEffect, useMemo, useState } from "react"; -import { FlatList, View } from "react-native"; +import { View } from "react-native"; import { useCSSVariable } from "uniwind"; import { type ConversationSummary, @@ -24,6 +24,7 @@ import { Notice, Refresh, Screen, + ScreenList, } from "../../../src/components"; import { tabRoot } from "../../../src/header"; import { homeView } from "../../../src/home-view"; @@ -248,7 +249,7 @@ export default function Conversations() { ]), }} /> - item.id} @@ -328,7 +329,7 @@ export default function Conversations() { description={ query ? "No chat has those words in it." - : "Start one with a Bot with the + button." + : "Start one with the + button." } /> ) : undefined diff --git a/mobile/app/(tabs)/(more)/_layout.tsx b/mobile/app/(tabs)/(more)/_layout.tsx index a11c9ed1c2..2ac464c879 100644 --- a/mobile/app/(tabs)/(more)/_layout.tsx +++ b/mobile/app/(tabs)/(more)/_layout.tsx @@ -2,7 +2,7 @@ import { Stack } from "expo-router"; import { tabRoot, useHeaderOptions } from "../../../src/header"; /** - * More's stack: the list. What it opens (Routines, Memory, Skills, Connections, the approval inbox) + * More's stack: the list. What it opens (Routines, Memory, Skills, Connections, Notifications) * lives in the app's own stack, so a Bot's page opens the same screens, and nothing stacks. */ export default function MoreLayout() { diff --git a/mobile/app/(tabs)/(more)/more.tsx b/mobile/app/(tabs)/(more)/more.tsx index 919124fcc5..b45f9853ab 100644 --- a/mobile/app/(tabs)/(more)/more.tsx +++ b/mobile/app/(tabs)/(more)/more.tsx @@ -1,7 +1,6 @@ import { router, useFocusEffect } from "expo-router"; -import { useCallback } from "react"; +import { useCallback, useState } from "react"; import { View } from "react-native"; -import { loadApprovalInbox } from "../../../src/api"; import { authClient } from "../../../src/auth"; import { Icon, @@ -11,79 +10,50 @@ import { Section, Text, } from "../../../src/components"; -import { - IconBook, - IconBrain, - IconChecks, - IconChevronRight, - IconClock, - IconPlug, -} from "../../../src/icons"; -import { useLoad } from "../../../src/use-load"; +import { IconChevronRight } from "../../../src/icons"; +import { MORE_ICONS } from "../../../src/more-icons"; +import { MORE_ITEMS, type MoreItem } from "../../../src/more-items"; +import { useWaitingCount } from "../../../src/waiting-count"; /** - * More: the parts of the app that don't have a tab. The routines Bots run, what every Bot - * remembers, knows and connects to, and the approval inbox. + * More: the parts of the app that don't have a tab (src/more-items.ts). The routines Bots run, what every Bot + * remembers, knows and connects to, and Notifications. Android's tab. On iOS the same list is the system's menu + * over the tab bar's last button (app/(tabs)/_layout.tsx), and this screen opens only if that press is missed. */ export default function More() { const { data: session } = authClient.useSession(); - // How many approvals and questions wait on the person, read again each time More comes to the front. - const loadInbox = useCallback(() => loadApprovalInbox(), []); - const inbox = useLoad(loadInbox, Boolean(session)); - const { refresh: refreshInbox } = inbox; - useFocusEffect( - useCallback(() => { - void refreshInbox(); - }, [refreshInbox]), + // How many things wait on the person, read again each time More comes to the front. + const [front, setFront] = useState(0); + useFocusEffect(useCallback(() => setFront((times) => times + 1), [])); + const waiting = useWaitingCount(Boolean(session), front); + const row = (item: MoreItem) => ( + + ) : undefined + } + onPress={() => router.push(item.route)} + /> ); - const waiting = - (inbox.data?.requests.filter((request) => request.status === "pending") - .length ?? 0) + (inbox.data?.questions.length ?? 0); return ( - - router.push("/routines")} - /> - : undefined} - onPress={() => router.push("/approvals")} - /> - + {MORE_ITEMS.filter((item) => !item.yourBots).map(row)}
- - router.push("/memory")} - /> - router.push("/skills")} - /> - router.push("/connections")} - /> - + {MORE_ITEMS.filter((item) => item.yourBots).map(row)}
); diff --git a/mobile/app/(tabs)/(needs-you)/_layout.tsx b/mobile/app/(tabs)/(needs-you)/_layout.tsx deleted file mode 100644 index aa87ae16f5..0000000000 --- a/mobile/app/(tabs)/(needs-you)/_layout.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { Stack } from "expo-router"; -import { tabRoot, useHeaderOptions } from "../../../src/header"; - -/** The Needs you tab's stack, with the native header. */ -export default function NeedsYouLayout() { - return ( - - - - ); -} diff --git a/mobile/app/(tabs)/(needs-you)/needs-you.tsx b/mobile/app/(tabs)/(needs-you)/needs-you.tsx deleted file mode 100644 index 9c228ff983..0000000000 --- a/mobile/app/(tabs)/(needs-you)/needs-you.tsx +++ /dev/null @@ -1,136 +0,0 @@ -import { Redirect } from "expo-router"; -import { useCallback, useEffect } from "react"; -import { View } from "react-native"; -import { everyBot, everyPage, ORGANIZATION_ID } from "../../../src/api"; -import { listCheckInItems } from "../../../src/api/generated/check-ins/check-ins"; -import { listTasks } from "../../../src/api/generated/tasks/tasks"; -import { authClient } from "../../../src/auth"; -import { hideItem, ItemRow, startItem, TaskRow } from "../../../src/check-ins"; -import { - EmptyState, - Notice, - ScrollScreen, - Text, -} from "../../../src/components"; -import { IconBell } from "../../../src/icons"; -import { showNeedsYouCount } from "../../../src/needs-you-count"; -import { waitingTasks } from "../../../src/tasks"; -import { useAction } from "../../../src/use-action"; -import { useLoad } from "../../../src/use-load"; - -/** - * Needs you: what every Bot's check-ins found that the person hasn't started or hidden, and the - * tasks started from them that wait on the person. A ping's notification opens here, since one ping - * folds several Bots' items. Each row is a chat's: its Bot's orb and name, then what it is. - */ -export default function NeedsYouScreen() { - const { data: session, isPending } = authClient.useSession(); - const action = useAction(); - const loadItems = useCallback( - () => - everyPage( - (page) => listCheckInItems(ORGANIZATION_ID, page), - (page) => page.checkInItems, - ), - [], - ); - const items = useLoad(loadItems, Boolean(session)); - const loadTasks = useCallback(async () => { - // Every page: the count of what waits on the person is of all of them. - return { - tasks: await everyPage( - (page) => listTasks(ORGANIZATION_ID, page), - (page) => page.tasks, - ), - }; - }, []); - const tasks = useLoad(loadTasks, Boolean(session)); - const loadBots = useCallback(() => everyBot(), []); - const bots = useLoad(loadBots, Boolean(session)); - const waiting = waitingTasks(tasks.data?.tasks ?? []); - const found = items.data ?? []; - // The tab's badge follows what this list shows, once both halves of it have been read. - const count = - items.data && tasks.data ? found.length + waiting.length : undefined; - useEffect(() => { - if (count !== undefined) showNeedsYouCount(count); - }, [count]); - if (!session && !isPending) return ; - const botOf = (agentId: string) => { - const bot = bots.data?.find((item) => item.id === agentId); - return { name: bot?.name ?? "A Bot", seed: bot?.avatarSeed || agentId }; - }; - - const problem = - action.error || items.error || tasks.error || bots.error || undefined; - return ( - // Rows run the width of the screen, as the Chats and Bots lists do. - { - void items.refresh(); - void tasks.refresh(); - }} - > - {problem ? ( - - - - ) : null} - {found.length > 0 ? ( - - {found.map((item) => ( - { - void action.run(`start:${item.id}`, async () => { - await startItem(item); - void items.refresh(); - void tasks.refresh(); - }); - }} - onHide={() => { - void action.run(`hide:${item.id}`, async () => { - await hideItem(item); - await items.refresh(); - }); - }} - /> - ))} - - ) : null} - {items.data && found.length === 0 && waiting.length === 0 ? ( - - ) : null} - {waiting.length > 0 ? ( - 0 ? "pt-4" : undefined}> - - Tasks - - {waiting.map((task) => ( - - ))} - - ) : null} - - ); -} diff --git a/mobile/app/(tabs)/_layout.tsx b/mobile/app/(tabs)/_layout.tsx index eb4e81e2a8..a37f62506c 100644 --- a/mobile/app/(tabs)/_layout.tsx +++ b/mobile/app/(tabs)/_layout.tsx @@ -1,7 +1,34 @@ import { usePathname } from "expo-router"; import { NativeTabs } from "expo-router/native-tabs"; +import { useState } from "react"; +import { Platform, Pressable, useWindowDimensions, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useCSSVariable } from "uniwind"; -import { useNeedsYouCount } from "../../src/needs-you-count"; +import { MoreMenu } from "../../src/more-menu"; +import { useWaitingCount } from "../../src/waiting-count"; + +/** + * More is a menu: the bar's last button opens it over the tab the person is on, and what they pick opens in the + * app's stack. On iOS it is drawn by the app above the bar (src/more-menu.tsx), and on Android it is Material's + * own (src/more-menu.android.tsx). The tab is told not to open, and still says it was pressed. Where a press + * opens the tab all the same, it is the same list as a screen (app/(tabs)/(more)/more.tsx). + */ + +/** How many tabs the bar has. */ +const TABS = 4; + +/** + * Where iOS draws the bar's buttons, measured on the phone: they share the bar's width less this much, the bar + * is this tall, and it sits this far into the room the home indicator keeps. For the press that is caught over + * More, below. + */ +const BAR_SIDES = 57; +const BAR_HEIGHT = 62; +const BAR_INTO_HOME_ROOM = 12; + +/** Material's navigation bar: its buttons share the screen's width, and it is this tall from the screen's foot. */ +const ANDROID_BAR_HEIGHT = 80; +const MENU_GAP = 8; /** * The Bots tab is OpenBot's orb as a flat glyph, at SF Symbols' line weight: an outline with the orb's @@ -13,13 +40,19 @@ const ORB_FILLED = require("../../assets/tab-orb-filled.png"); /** * The signed-in app's tabs, in the platform's own tab bar: UIKit's on iOS (iOS 26's glass, with SF * Symbols), Material 3's navigation bar on Android (with Material Symbols), as icons with no words - * under them: Chats, Bots (OpenBot's orb), your account in the middle, Needs you and More. Each tab is a stack of - * its own with the native header. A conversation, a Bot and the rest of what is pushed from a tab - * open in the app's stack over the tabs, so the tab bar steps aside for them. + * under them: Chats, Bots (OpenBot's orb), your account and More. Each tab is a stack of its own with the + * native header. A conversation, a Bot and the rest of what is pushed from a tab open in the app's stack over + * the tabs, so the tab bar steps aside for them. + * + * More's badge counts what waits on the person, which Notifications lists (app/approvals.tsx): it is in More, + * so the count is on the way to it. */ export default function TabsLayout() { - // Read again on each move between tabs, so starting or hiding something in Needs you shows here. - const waiting = useNeedsYouCount(true, usePathname()); + // Read again on each move between screens, so answering or hiding something in Notifications shows here. + const waiting = useWaitingCount(true, usePathname()); + const [menuOpen, setMenuOpen] = useState(false); + const insets = useSafeAreaInsets(); + const { width } = useWindowDimensions(); const [foreground, muted, background, highlight, danger] = useCSSVariable([ "--color-foreground", "--color-muted", @@ -27,66 +60,106 @@ export default function TabsLayout() { "--color-sidebar-accent", "--color-danger", ]) as (string | undefined)[]; + // Where the bar's last button is, on each platform. + const moreButton = + Platform.OS === "ios" + ? ({ + position: "absolute", + right: BAR_SIDES / 2, + width: (width - BAR_SIDES) / TABS, + height: BAR_HEIGHT, + bottom: Math.max(insets.bottom - BAR_INTO_HOME_ROOM, 8), + } as const) + : ({ + position: "absolute", + // Clear of the screen's edge, which the menu lines up with. + right: MENU_GAP, + width: width / TABS - MENU_GAP, + // A little taller than the bar, so the menu stands clear of it and its shadow has room. + height: ANDROID_BAR_HEIGHT + MENU_GAP, + bottom: 0, + } as const); return ( - - - - - - - - - - - - - - 0 ? `Needs you, ${waiting} waiting` : "Needs you" - } + + { + // The route's key starts with its name: only More's press opens the menu. + if (event.target?.startsWith("(more)")) setMenuOpen(true); + }, + }} + // The open tab in the text color, the rest in the quieter one: the scheme has no brand blue. + tintColor={foreground} + iconColor={{ default: muted, selected: foreground }} + // Android's bar on the screen's ground, with the sidebar's soft highlight behind the open tab. + backgroundColor={background} + indicatorColor={highlight} + badgeBackgroundColor={danger} + labelVisibilityMode="unlabeled" > - + + + + + + + + + + + + 0 ? `More, ${waiting} waiting for you` : "More" + } + disabled + > + + + {waiting > 0 ? ( + + {waiting > 99 ? "99+" : String(waiting)} + + ) : null} + + + {/* + * The press on More is caught over the button, before the bar has it: by the button below on iOS, and by + * the menu's own on Android. A tab that is told not to open still slid the bar's highlight to itself and + * back on every press. The tab stays told not to open, for a screen reader, which presses the tab itself, + * and for a bar laid out another way. + */} + {Platform.OS === "ios" ? ( + setMenuOpen(true)} + style={moreButton} /> - - {waiting > 0 ? ( - - {waiting > 99 ? "99+" : String(waiting)} - - ) : null} - - - - - - + ) : null} + setMenuOpen(false)} + count={waiting} + anchor={moreButton} + /> + ); } diff --git a/mobile/app/_layout.tsx b/mobile/app/_layout.tsx index efda1414d5..c529295e27 100644 --- a/mobile/app/_layout.tsx +++ b/mobile/app/_layout.tsx @@ -177,7 +177,7 @@ function Layout() { /> diff --git a/mobile/app/approvals.tsx b/mobile/app/approvals.tsx index 72fef337ef..f85335fe26 100644 --- a/mobile/app/approvals.tsx +++ b/mobile/app/approvals.tsx @@ -2,13 +2,21 @@ import { Redirect, useLocalSearchParams } from "expo-router"; import { Button } from "heroui-native/button"; import { TextArea } from "heroui-native/text-area"; import { TextField } from "heroui-native/text-field"; -import { type ReactNode, useCallback, useState } from "react"; +import { type ReactNode, useCallback, useEffect, useState } from "react"; import { View } from "react-native"; -import { everyBot, loadApprovalInbox, ME, ORGANIZATION_ID } from "../src/api"; +import { + everyBot, + everyPage, + loadApprovalInbox, + ME, + ORGANIZATION_ID, +} from "../src/api"; import { decideApproval, respondToQuestion, } from "../src/api/generated/approvals/approvals"; +import { listCheckInItems } from "../src/api/generated/check-ins/check-ins"; +import { listTasks } from "../src/api/generated/tasks/tasks"; import { type ApprovalChange, approvalChange, @@ -19,21 +27,50 @@ import { type PhoneDecision, } from "../src/approval-words"; import { authClient } from "../src/auth"; +import { hideItem, ItemRow, startItem, TaskRow } from "../src/check-ins"; import { BotOrb, cn, EmptyState, + ListRow, Notice, + RowGlyph, ScrollScreen, Text, + Toggle, } from "../src/components"; -import { IconChecks } from "../src/icons"; +import { IconBell } from "../src/icons"; +import { + pushTurnedOn, + registerPush, + unregisterPush, +} from "../src/notifications"; +import { waitingTasks } from "../src/tasks"; +import { useAction } from "../src/use-action"; import { useLoad } from "../src/use-load"; +import { showWaitingCount } from "../src/waiting-count"; + +/** The name over one kind of what waits, on the line the rows' words start on. */ +function Kind({ children }: { children: string }) { + return ( + + {children} + + ); +} /** - * The approval inbox: what the person's Bots want to do and asked first about, each with only the - * answers the server takes, and the questions they asked. Each is a row like a chat's, under its - * Bot's orb, with hairlines between them. A notification opens it at one of them, which is ringed. + * Notifications: whether this phone is told, and everything that waits on the person. The phone's own switch + * is the first row. Under it, by kind: what the person's Bots want to do and asked first about, each with only + * the answers the server takes, and the questions they asked; what the Bots' check-ins found that the person + * hasn't started or hidden; and the tasks started from those that wait on the person. Each is a row like a + * chat's, under its Bot's orb. A notification opens it, at the approval or question it is about, which is + * ringed. It was two places, the approval inbox and the Needs you tab. */ export default function ApprovalsScreen() { const { requestId } = useLocalSearchParams<{ requestId?: string }>(); @@ -41,14 +78,66 @@ export default function ApprovalsScreen() { const [error, setError] = useState(""); const [busy, setBusy] = useState(""); const [answers, setAnswers] = useState>({}); + const [pushOn, setPushOn] = useState(false); + // Said as it is on this phone, not as it was before the app last started. + useEffect(() => { + void pushTurnedOn() + .then(setPushOn) + .catch(() => {}); + }, []); + /** The switch moves at once, and goes back if the phone or OpenBot refuses. */ + function setNotifications(on: boolean) { + setPushOn(on); + setError(""); + void (on ? registerPush() : unregisterPush()).catch((failure) => { + setPushOn(!on); + setError( + failure instanceof Error + ? failure.message + : "Couldn't change notifications. Try again.", + ); + }); + } const load = useCallback(() => loadApprovalInbox(), []); const inbox = useLoad(load, Boolean(session)); + // What the Bots' check-ins found, and the tasks: every page, since the count is of all of them. + const action = useAction(); + const loadItems = useCallback( + () => + everyPage( + (page) => listCheckInItems(ORGANIZATION_ID, page), + (page) => page.checkInItems, + ), + [], + ); + const items = useLoad(loadItems, Boolean(session)); + const loadTasks = useCallback( + () => + everyPage( + (page) => listTasks(ORGANIZATION_ID, page), + (page) => page.tasks, + ), + [], + ); + const tasks = useLoad(loadTasks, Boolean(session)); // Each Bot by its name: the list carries only its id. const loadBots = useCallback(() => everyBot(), []); const bots = useLoad(loadBots, Boolean(session)); const botName = (id: string) => bots.data?.find((bot) => bot.id === id)?.name; const botSeed = (id: string) => bots.data?.find((bot) => bot.id === id)?.avatarSeed || id; + // More's badge follows what this screen lists, once every part of it has been read. + const listed = + inbox.data && items.data && tasks.data + ? inbox.data.requests.filter((request) => request.status === "pending") + .length + + inbox.data.questions.length + + items.data.length + + waitingTasks(tasks.data).length + : undefined; + useEffect(() => { + if (listed !== undefined) showWaitingCount(listed); + }, [listed]); if (!session && !isPending) return ; async function decide(id: string, decision: PhoneDecision) { setBusy(id); @@ -88,20 +177,51 @@ export default function ApprovalsScreen() { (request) => request.status === "pending", ); const questions = inbox.data?.questions ?? []; - const empty = inbox.data && !pending?.length && !questions.length; - const problem = error || inbox.error || undefined; + const found = items.data ?? []; + const waiting = waitingTasks(tasks.data ?? []); + const asked = (pending?.length ?? 0) + questions.length; + const read = Boolean(inbox.data && items.data && tasks.data); + const empty = read && !asked && !found.length && !waiting.length; + const problem = + error || + action.error || + inbox.error || + items.error || + tasks.error || + undefined; return ( // Rows run the width of the screen, as the Chats and Bots lists do. void inbox.refresh()} + refreshing={inbox.pending || items.pending || tasks.pending} + onRefresh={() => { + void inbox.refresh(); + void items.refresh(); + void tasks.refresh(); + }} > {problem ? ( ) : null} + } + title="Allow notifications" + description={ + pushOn + ? "Bots tell you when they finish or need you." + : "Get told when a Bot finishes or needs you." + } + trailing={ + + } + /> + {asked ? Approvals and questions : null} {pending?.map((request, index) => { // In the web card's words: what the Bot wants to do, why it asks, and what would change. const change = approvalChange(request.action.target); @@ -217,11 +337,51 @@ export default function ApprovalsScreen() { ))} + {found.length > 0 ? ( + <> + From check-ins + {found.map((item) => ( + { + void action.run(`start:${item.id}`, async () => { + await startItem(item); + void items.refresh(); + void tasks.refresh(); + }); + }} + onHide={() => { + void action.run(`hide:${item.id}`, async () => { + await hideItem(item); + await items.refresh(); + }); + }} + /> + ))} + + ) : null} + {waiting.length > 0 ? ( + <> + Tasks + {waiting.map((task) => ( + + ))} + + ) : null} {empty ? ( ) : null} diff --git a/mobile/app/delete-account.tsx b/mobile/app/delete-account.tsx index 3157e0800f..473377cf02 100644 --- a/mobile/app/delete-account.tsx +++ b/mobile/app/delete-account.tsx @@ -4,7 +4,8 @@ import { Input } from "heroui-native/input"; import { Label } from "heroui-native/label"; import { TextField } from "heroui-native/text-field"; import { useCallback, useState } from "react"; -import { Alert, View } from "react-native"; +import { ActivityIndicator, Alert, View } from "react-native"; +import { useCSSVariable } from "uniwind"; import { blockerWayOn, blockerWords, @@ -14,6 +15,7 @@ import { scheduledSentence, typedRight, } from "../src/account-deletion"; +import { rereadOrganizations } from "../src/api"; import type { AccountDeletionBlocker } from "../src/api/generated/model"; import { removeOrganizationMember } from "../src/api/generated/organizations/organizations"; import { @@ -22,26 +24,43 @@ import { } from "../src/api/generated/people/people"; import { authClient, signIn } from "../src/auth"; import { + ListRow, + Monogram, Notice, - Row, - Rows, + RowGlyph, Screen, ScrollScreen, - Section, SheetTitle, Text, } from "../src/components"; -import { IconBuilding } from "../src/icons"; +import { IconArchive, IconTrash, type TablerIcon } from "../src/icons"; import { useLoad } from "../src/use-load"; const TITLE = "Delete account"; -/** One line of what is deleted or kept. */ -function Line({ children }: { children: string }) { +/** What happens to one kind of thing: its glyph, the word for it, and each thing it covers on a line of its own. */ +function Outcome({ + icon, + tone, + title, + lines, +}: { + icon: TablerIcon; + tone?: "danger"; + title: string; + lines: string[]; +}) { return ( - - • - {children} + + + + {title} + {lines.map((line) => ( + + {line} + + ))} + ); } @@ -69,6 +88,7 @@ export default function DeleteAccount() { ); const [error, setError] = useState(""); const [signInAgain, setSignInAgain] = useState(false); + const muted = useCSSVariable("--color-muted") as string | undefined; // Back from deleting an organization that stopped it: the list is read again, and has one less. const { refresh: readStanding } = standing; @@ -144,6 +164,8 @@ export default function DeleteAccount() { setError(""); try { await removeOrganizationMember(blocker.organizationId, "me"); + // Gone from the person's own list too, and from what the app works in if it was that one. + await rereadOrganizations().catch(() => {}); await standing.refresh(); } catch (failure) { setError( @@ -175,98 +197,108 @@ export default function DeleteAccount() { } } + const said = error || standing.error; return ( - - void again()} - > - {busy === "sign-in" ? "Opening sign-in…" : "Sign in again"} - - ) : undefined - } - /> - {blockers.length > 0 ? ( - // A sentence, not a section's label: a label is one line, and this one doesn't fit one. - - + + {said ? ( + + void again()} + > + {busy === "sign-in" ? "Opening sign-in…" : "Sign in again"} + + ) : undefined + } + /> + + ) : null} + {!standing.data ? ( + // Whether an organization stops the deletion decides what this sheet is, so it waits to be told. + standing.error ? null : ( + + + + ) + ) : blockers.length > 0 ? ( + <> + Before you can delete your account, sort out these organizations. - - {blockers.map((blocker) => { - const onPress = wayOn(blocker); - return ( - - ); - })} - - + {blockers.map((blocker) => { + const onPress = wayOn(blocker); + return ( + } + title={blocker.organizationName} + description={blockerWords(blocker)} + chevron={Boolean(onPress)} + disabled={Boolean(busy)} + onPress={onPress} + /> + ); + })} + ) : ( - <> + {`Your account is deleted in ${DELETION_WAIT_DAYS} days. Sign in before then to cancel. Delete now deletes it straight away, and you can't undo it.`} -
- - - Your conversations, memory, Bots, skills and routines that are - only yours. - - Your saved logins, connections and computer. - -
-
- - - Messages you sent in organizations you share with others. They - show as from Deleted user. - - - Security log entries, for 180 days, without your name or - email. - - -
- - - + - - - - - - + + + + + + + + + + + + - +
)}
diff --git a/mobile/app/delete-organization.tsx b/mobile/app/delete-organization.tsx index fc2c130325..f77fcd67ae 100644 --- a/mobile/app/delete-organization.tsx +++ b/mobile/app/delete-organization.tsx @@ -5,6 +5,7 @@ import { Label } from "heroui-native/label"; import { TextField } from "heroui-native/text-field"; import { useState } from "react"; import { typedOrganizationName } from "../src/account-deletion"; +import { rereadOrganizations } from "../src/api"; import { deleteOrganization } from "../src/api/generated/organizations/organizations"; import { Notice, @@ -17,12 +18,13 @@ import { const TITLE = "Delete organization"; /** - * Deleting an organization the person is the only owner of, opened from the list of what stops their account - * being deleted (./delete-account.tsx). Without it that list had no way on from the phone. + * Deleting an organization the person owns, opened from its row on Account (a swipe) and from the list of what + * stops their account being deleted (./delete-account.tsx). * - * The web app's step (Organization settings, Delete), in its words: everything in the organization goes for - * everybody, so the person types its name first. OpenBot decides whether it can go, and its refusal is shown as - * it says it: a person's own organization, and the one that comes with OpenBot, stay. + * One thing is asked here, so one thing is on the sheet: what goes, the organization's name to type, and the + * button. It is the web app's step (Organization settings, Delete): everything in the organization goes for + * everybody, so the person types its name first. OpenBot decides whether it can go, and its refusal is shown as it + * says it: a person's own organization, and the one that comes with OpenBot, stay. */ export default function DeleteOrganization() { const { id, name } = useLocalSearchParams<{ id: string; name: string }>(); @@ -37,7 +39,9 @@ export default function DeleteOrganization() { setError(""); try { await deleteOrganization(id); - // Back to the list of what stops the account being deleted, which reads again and has one less. + // Gone from the person's list, and from what the app works in if it was that one. It is deleted either + // way, so a list that can't be read now is read again by the screen under this sheet. + await rereadOrganizations().catch(() => {}); router.back(); } catch (failure) { setError( @@ -54,20 +58,16 @@ export default function DeleteOrganization() { - + - {`Delete ${name ?? "this organization"}?`} - Its Bots, conversations and computers are deleted for everyone. - Members keep their accounts and their other organizations. You can't - undo it. + {name || "This organization"} + { + " and its Bots, conversations and computers are deleted for everyone. You can't undo it." + } - - To keep the organization, make someone else an owner first. You do - that in OpenBot in a browser, in the organization's settings. - - - + + {}} />
+ + + } + title="Acme" + description="You're working here" + trailing={} + /> + {}, + }} + > + } + title="Hill Climbing" + description="Swipe it to the left" + onPress={() => {}} + /> + + } + title="Notifications" + description="Get told when a Bot finishes or needs you." + onPress={() => {}} + chevron + /> + + @@ -447,7 +486,7 @@ export default function Gallery() { New chat} /> diff --git a/mobile/app/memory.tsx b/mobile/app/memory.tsx index a35f484038..16b0ba1538 100644 --- a/mobile/app/memory.tsx +++ b/mobile/app/memory.tsx @@ -145,8 +145,8 @@ export default function MemoryScreen() { {list?.length === 0 && !adding ? ( Add a memory diff --git a/mobile/app/needs-you.tsx b/mobile/app/needs-you.tsx new file mode 100644 index 0000000000..d9db9f8f3b --- /dev/null +++ b/mobile/app/needs-you.tsx @@ -0,0 +1,9 @@ +import { Redirect } from "expo-router"; + +/** + * Needs you was a tab. What it listed is in Notifications now (./approvals.tsx), with what the person's Bots + * ask them. Its address stays, since a ping's notification opens it (src/links.ts): it goes there. + */ +export default function NeedsYou() { + return ; +} diff --git a/mobile/app/routines.tsx b/mobile/app/routines.tsx index 0d67796855..b1a8a13e8b 100644 --- a/mobile/app/routines.tsx +++ b/mobile/app/routines.tsx @@ -124,7 +124,7 @@ export default function Routines() { ) : null} diff --git a/mobile/package-lock.json b/mobile/package-lock.json index 9b6f7250c8..7b19412fa7 100644 --- a/mobile/package-lock.json +++ b/mobile/package-lock.json @@ -27,6 +27,7 @@ "expo-document-picker": "~58.0.5", "expo-file-system": "~58.0.14", "expo-font": "~58.0.12", + "expo-glass-effect": "~58.0.5", "expo-image-picker": "~58.0.10", "expo-linking": "~58.0.17", "expo-network": "~58.0.5", diff --git a/mobile/package.json b/mobile/package.json index 0b5897e539..ca19cae44c 100644 --- a/mobile/package.json +++ b/mobile/package.json @@ -34,6 +34,7 @@ "expo-document-picker": "~58.0.5", "expo-file-system": "~58.0.14", "expo-font": "~58.0.12", + "expo-glass-effect": "~58.0.5", "expo-image-picker": "~58.0.10", "expo-linking": "~58.0.17", "expo-network": "~58.0.5", diff --git a/mobile/src/api/index.ts b/mobile/src/api/index.ts index 68af8f103a..4705479954 100644 --- a/mobile/src/api/index.ts +++ b/mobile/src/api/index.ts @@ -40,12 +40,13 @@ export { ApiError, chooseOrganization, DEPLOYMENT_ORGANIZATION_ID, - readDeployment, ME, ORGANIZATION_ID, organizationAddress, organizationChoices, organizationsHeld, + readDeployment, + rereadOrganizations, setSignedInPerson, } from "./request"; diff --git a/mobile/src/api/request.ts b/mobile/src/api/request.ts index fc49d29b16..67c382e2cc 100644 --- a/mobile/src/api/request.ts +++ b/mobile/src/api/request.ts @@ -238,6 +238,18 @@ export async function chooseOrganization( return chosen; } +/** + * The person deleted one of their organizations from this phone, or left it: read which ones they have now. When it + * was the one they worked in, they work in another of theirs from here on, and every screen is told, as for a pick. + */ +export async function rereadOrganizations(): Promise { + const token = (await authClient.getAccessToken()) ?? ""; + const before = await organizations.current(token).catch(() => undefined); + const now = await organizations.reread(token); + if (now.currentId !== before) reportOrganizationChosen(); + return now; +} + /** The person asking, as the API addresses them in its `people/{personId}` operations. */ export const ME = "me"; diff --git a/mobile/src/components/empty-state.tsx b/mobile/src/components/empty-state.tsx index 609c54191a..8774d033ce 100644 --- a/mobile/src/components/empty-state.tsx +++ b/mobile/src/components/empty-state.tsx @@ -6,7 +6,13 @@ import { Text } from "./text"; /** * What a list shows while it has nothing in it: what will appear, and how to make it appear - * ("No conversations yet. Start one with a Bot."). + * ("No chats yet. Start one with the + button."). + * + * It stands in the middle of what the person sees, as the phone's own empty lists do: it takes the room its + * screen has left (`Screen` and `ScrollScreen` are as tall as what no bar covers) and centers in it, a little + * above the middle, where the eye puts the center. Under a page's own top (a Bot's name and tabs) it centers + * in what is left below. Nothing is drawn around it: its glyph, its name, one or two lines, and one button + * when the way on is here. */ export function EmptyState({ icon, @@ -20,23 +26,30 @@ export function EmptyState({ action?: ReactNode; }) { return ( - + {icon ? ( - - + + ) : null} - - + + {title} {description ? ( - + {description} ) : null} - {action} + {action ? ( + {action} + ) : null} ); } diff --git a/mobile/src/components/index.ts b/mobile/src/components/index.ts index 604409d9a4..8f6729deab 100644 --- a/mobile/src/components/index.ts +++ b/mobile/src/components/index.ts @@ -21,6 +21,7 @@ export { EmptyState } from "./empty-state"; export { Icon } from "./icon"; export { IconButton } from "./icon-button"; export { KeyboardBar } from "./keyboard-bar"; +export { ListRow, Monogram, RowGlyph } from "./list-row"; export { Message, MessageDay, @@ -30,12 +31,13 @@ export { export { Notice } from "./notice"; export { PersonAvatar } from "./person-avatar"; export { Row, Rows } from "./rows"; -export { Refresh, Screen, ScrollScreen } from "./screen"; +export { Refresh, Screen, ScreenList, ScrollScreen } from "./screen"; export { SearchBar } from "./search-bar"; export { SearchField } from "./search-field"; export { Section } from "./section"; export { Segmented } from "./segmented"; export { SheetTitle } from "./sheet-title"; +export { type SwipeAction, SwipeRow } from "./swipe-row"; export { Text, type TextVariant } from "./text"; export { Toggle } from "./toggle"; export { DecisionCard, StepsLine } from "./transcript"; diff --git a/mobile/src/components/list-row.tsx b/mobile/src/components/list-row.tsx new file mode 100644 index 0000000000..78da2dfe8e --- /dev/null +++ b/mobile/src/components/list-row.tsx @@ -0,0 +1,131 @@ +import type { ReactNode } from "react"; +import { Pressable, View } from "react-native"; +import type { TablerIcon } from "../icons"; +import { IconChevronRight } from "../icons"; +import { cn } from "./cn"; +import { Icon } from "./icon"; +import { Text } from "./text"; + +/** How wide what leads a row is, so every row's words start on the same line down the screen. */ +const LEAD = 40; + +/** + * A row of a phone's own list, edge to edge with no card around it, as Chats and Bots are drawn: what leads it, + * its name, a line under it, and what trails it. For a top-level screen's list. A page of settings, with its + * card and hairlines, is `Rows`. + * + * It presses to the screen's edges. A row that opens something shows a chevron. One that acts where it is (a + * pick, a switch) brings its own `trailing` or none. + */ +export function ListRow({ + leading, + title, + description, + trailing, + onPress, + chevron = false, + disabled, + accessibilityLabel, + accessibilityState, +}: { + leading?: ReactNode; + title: string; + description?: string; + trailing?: ReactNode; + onPress?: () => void; + /** True for a row that opens a page. */ + chevron?: boolean; + disabled?: boolean; + accessibilityLabel?: string; + accessibilityState?: { selected?: boolean; busy?: boolean }; +}) { + const content = ( + + {leading} + + + {title} + + {description ? ( + + {description} + + ) : null} + + {trailing ?? + (chevron ? ( + + ) : null)} + + ); + if (!onPress) return content; + return ( + + {content} + + ); +} + +/** + * What leads a row for an organization: its first letter on a quiet rounded square. A person is a circle + * (`PersonAvatar`) and a Bot is its orb, so the shape alone says which of the three a row is. + */ +export function Monogram({ + name, + size = LEAD, +}: { + name: string; + size?: number; +}) { + const letter = name.trim()[0]?.toUpperCase() ?? "?"; + return ( + + + {letter} + + + ); +} + +/** What leads a row that is about a thing, not somebody: its icon on the same quiet ground, round. */ +export function RowGlyph({ + icon, + tone = "default", + size = LEAD, +}: { + icon: TablerIcon; + tone?: "default" | "danger"; + size?: number; +}) { + return ( + + + + ); +} diff --git a/mobile/src/components/person-avatar.tsx b/mobile/src/components/person-avatar.tsx index 40cdfb3a26..a7375d4e5a 100644 --- a/mobile/src/components/person-avatar.tsx +++ b/mobile/src/components/person-avatar.tsx @@ -23,7 +23,11 @@ export function PersonAvatar({ className="items-center justify-center rounded-full border border-border bg-fill" style={{ width: size, height: size }} > - + {/* The letters grow with the circle: at a list's size they are a caption, on a profile a heading. */} + {initials || "?"} diff --git a/mobile/src/components/screen.tsx b/mobile/src/components/screen.tsx index aa8be71063..4d9d190fcb 100644 --- a/mobile/src/components/screen.tsx +++ b/mobile/src/components/screen.tsx @@ -2,14 +2,35 @@ import { useFocusEffect } from "expo-router"; import { HeaderHeightContext } from "expo-router/react-navigation"; import { type ComponentRef, + createContext, type ReactNode, useCallback, useContext, + useEffect, + useMemo, useRef, useState, } from "react"; -import { RefreshControl, type RefreshControlProps, View } from "react-native"; +import { + FlatList, + type FlatListProps, + type NativeScrollEvent, + type NativeSyntheticEvent, + RefreshControl, + type RefreshControlProps, + View, +} from "react-native"; import { KeyboardAwareScrollView } from "react-native-keyboard-controller"; +import Animated, { + useAnimatedStyle, + useSharedValue, + withTiming, +} from "react-native-reanimated"; +import { + SafeAreaProvider, + useSafeAreaFrame, + useSafeAreaInsets, +} from "react-native-safe-area-context"; import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg"; import { useCSSVariable, withUniwind } from "uniwind"; import { cn } from "./cn"; @@ -23,12 +44,24 @@ const ABOVE_KEYBOARD = 24; /** How far above the header's edge what scrolls under it fades into the page. */ const FADE = 36; +/** How far a page has to be scrolled before its top counts as under the header. */ +const UNDER = 6; + /** * The top edge of a screen's content: what scrolls up toward the header fades into the page's ground * over a few points, rather than being cut off at a hard line by the bar. + * + * `under` is whether anything has scrolled under the header. A page at rest has nothing there, and the fade + * would only lie over the page's own first lines, so it shows once the page is scrolled. A screen whose list + * doesn't say (`under` is undefined) keeps it always. */ -export function TopFade() { +export function TopFade({ under }: { under?: boolean }) { const background = useCSSVariable("--color-background") as string | undefined; + const shown = useSharedValue(under === false ? 0 : 1); + useEffect(() => { + shown.value = withTiming(under === false ? 0 : 1, { duration: 160 }); + }, [under, shown]); + const fading = useAnimatedStyle(() => ({ opacity: shown.value })); // The header's bottom edge, from the top of the window (it counts the status bar). Some screens' content runs // under the header and some starts below it, so where this screen starts is measured, and the fade sits at the // header's edge either way: never inside the content, never hidden behind the bar. @@ -60,10 +93,12 @@ export function TopFade() { onLayout={measure} /> {top === null ? null : ( - @@ -78,12 +113,71 @@ export function TopFade() { - + )} ); } +/** + * What the phone's bars leave of a screen: how tall the part is that none covers (under the header, over the + * tab bar and the home indicator), and how far the header reaches into the screen from its top. + */ +type Seen = { height: number; top: number }; + +/** + * What a `Screen` tells the list inside it (`ScreenList`): the room it has ({@link Seen}), so a list as tall as + * that at least can put what it says while it is empty in the middle of what the person sees (`EmptyState`) and + * is never made taller than the screen by it, and where to say how far it is scrolled, for the fade at the top. + */ +const ScreenRoom = createContext< + { height: number | undefined; scrolledTo: (y: number) => void } | undefined +>(undefined); + +/** Says what the bars leave once the phone knows it, and again each time a bar grows or goes. */ +function SeenReader({ onChange }: { onChange: (seen: Seen) => void }) { + const frame = useSafeAreaFrame(); + const insets = useSafeAreaInsets(); + const height = Math.max(0, frame.height - insets.top - insets.bottom); + const top = insets.top; + useEffect(() => onChange({ height, top }), [height, top, onChange]); + return null; +} + +/** + * Measures {@link Seen} for the screen it lies over. The phone knows how far its bars reach into a view, and a + * safe area provider of the screen's own reads that for this screen: the app's one provider, at the root, knows + * only the status bar and the home indicator. It draws nothing and takes no touch, and nothing is drawn inside + * it, so what the screen's own parts read as the safe area stays the app's. + */ +function SeenProbe({ onChange }: { onChange: (seen: Seen) => void }) { + return ( + + + + + + ); +} + +/** + * A screen's room, and whether its page is scrolled under the header. A page at rest starts where the header + * ends: scrolled to minus the header's reach where the page runs under the header, and to nothing where it + * starts below it. `under` is undefined until a list has said where it is. + */ +function useScreenRoom() { + const [seen, setSeen] = useState(); + const [under, setUnder] = useState(); + // Read when a list says where it is, so what says it stays the same as the header grows and shrinks. + const top = useRef(0); + top.current = seen?.top ?? 0; + const scrolledTo = useCallback( + (y: number) => setUnder(y + top.current > UNDER), + [], + ); + return { seen, setSeen, under, scrolledTo }; +} + /** A screen's ground: the scheme's `background`, under the native header the route draws. */ export function Screen({ children, @@ -95,10 +189,16 @@ export function Screen({ /** False in a sheet, which has no header for its content to fade under. */ fade?: boolean; }) { + const { seen, setSeen, under, scrolledTo } = useScreenRoom(); + const room = useMemo( + () => ({ height: seen?.height, scrolledTo }), + [seen?.height, scrolledTo], + ); return ( - {children} - {fade ? : null} + {children} + + {fade ? : null} ); } @@ -124,16 +224,22 @@ export function ScrollScreen({ /** False in a sheet, which has no header for its content to fade under. */ fade?: boolean; }) { + const { seen, setSeen, under, scrolledTo } = useScreenRoom(); // Inside a View: as the screen's own first child, the scroll view leaves an iOS 26 large title blank. return ( ) => + scrolledTo(event.nativeEvent.contentOffset.y) + } refreshControl={ onRefresh ? ( @@ -142,11 +248,40 @@ export function ScrollScreen({ > {children} - {fade ? : null} + + {/* A page that hasn't been scrolled yet is at rest: nothing is under the header. */} + {fade ? : null} ); } +/** + * A `Screen`'s long list: a `FlatList` as tall as what the person sees at least ({@link ScreenRoom}), so what + * it says while it is empty stands in the middle of the screen, and one that says how far it is scrolled, so + * the fade at the top shows only over what has scrolled under the header. It takes what a `FlatList` takes. + */ +export function ScreenList(props: FlatListProps) { + const room = useContext(ScreenRoom); + const scrolledTo = room?.scrolledTo; + // At rest until it scrolls. + useEffect(() => scrolledTo?.(Number.NEGATIVE_INFINITY), [scrolledTo]); + const { onScroll } = props; + return ( + { + scrolledTo?.(event.nativeEvent.contentOffset.y); + onScroll?.(event); + }} + contentContainerStyle={[ + { minHeight: room?.height }, + props.contentContainerStyle, + ]} + /> + ); +} + /** Pull to refresh, its spinner in the scheme's quieter text color. */ export function Refresh({ refreshing, diff --git a/mobile/src/components/swipe-row.tsx b/mobile/src/components/swipe-row.tsx new file mode 100644 index 0000000000..be4051765a --- /dev/null +++ b/mobile/src/components/swipe-row.tsx @@ -0,0 +1,126 @@ +import { type ReactNode, useEffect, useRef } from "react"; +import { Pressable, View } from "react-native"; +import Swipeable, { + type SwipeableMethods, +} from "react-native-gesture-handler/ReanimatedSwipeable"; +import Animated, { + type SharedValue, + useAnimatedStyle, +} from "react-native-reanimated"; +import { useCSSVariable } from "uniwind"; +import type { TablerIcon } from "../icons"; +import { cn } from "./cn"; +import { Icon } from "./icon"; + +/** What a row offers when it is swiped: `danger` for what deletes. */ +export type SwipeAction = { + /** What a screen reader calls it, with the row's name in it ("Delete HillClimbing"). Never drawn. */ + label: string; + icon: TablerIcon; + tone?: "default" | "danger"; + onPress: () => void; +}; + +/** The action's button: a square of this size, with its glyph alone. */ +const SIZE = 52; + +/** The one row whose action shows, so swiping a second row puts the first away, as the phone's lists do. */ +let shown: { close: () => void } | null = null; + +/** The action's button: it fades and grows into the room the row leaves as it is swiped. */ +function Action({ + action, + progress, + onPress, +}: { + action: SwipeAction; + progress: SharedValue; + onPress: () => void; +}) { + const arriving = useAnimatedStyle(() => { + const along = Math.min(1, Math.max(0, progress.value)); + return { opacity: along, transform: [{ scale: 0.85 + 0.15 * along }] }; + }); + const danger = action.tone === "danger"; + return ( + + + + + + + + ); +} + +/** + * A row that can be swiped to the left for one action, as the phone's own lists are: the row slides, the action's + * button is in the room it leaves, and a tap on the button does it. A swipe alone never does: what these do can't + * be taken back. Without an `action` it is the row and nothing else. + * + * The same action is the row's own for somebody who can't swipe: a screen reader offers it on the row. + */ +export function SwipeRow({ + action, + disabled, + children, +}: { + action?: SwipeAction; + disabled?: boolean; + children: ReactNode; +}) { + const swipeable = useRef(null); + const self = useRef({ close: () => swipeable.current?.close() }).current; + // The row slides over its action, so it has the page's ground: a row with none would show the action through it. + const ground = useCSSVariable("--color-background") as string | undefined; + useEffect( + () => () => { + if (shown === self) shown = null; + }, + [self], + ); + if (!action) return children; + const act = () => { + self.close(); + action.onPress(); + }; + return ( + { + if (shown !== self) shown?.close(); + shown = self; + }} + onSwipeableClose={() => { + if (shown === self) shown = null; + }} + renderRightActions={(progress) => ( + + )} + > + + {children} + + + ); +} diff --git a/mobile/src/icons.ts b/mobile/src/icons.ts index 708b9aa2d2..43572372a1 100644 --- a/mobile/src/icons.ts +++ b/mobile/src/icons.ts @@ -6,6 +6,7 @@ export type { Icon as TablerIcon } from "@tabler/icons-react-native"; export { default as IconAlertCircle } from "@tabler/icons-react-native/IconAlertCircle"; export { default as IconAlertTriangle } from "@tabler/icons-react-native/IconAlertTriangle"; +export { default as IconArchive } from "@tabler/icons-react-native/IconArchive"; export { default as IconArrowsExchange } from "@tabler/icons-react-native/IconArrowsExchange"; export { default as IconArrowUp } from "@tabler/icons-react-native/IconArrowUp"; export { default as IconBell } from "@tabler/icons-react-native/IconBell"; diff --git a/mobile/src/more-icons.ts b/mobile/src/more-icons.ts new file mode 100644 index 0000000000..be37cdd898 --- /dev/null +++ b/mobile/src/more-icons.ts @@ -0,0 +1,22 @@ +/** + * Each part of More's glyph in the app's own set (Tabler), by the part's key (./more-items.ts): for Android's + * menu (./more-menu.android.tsx) and for More as a screen (app/(tabs)/(more)/more.tsx). iOS's menu draws the + * phone's own glyphs, which the list names itself (`sf`). + */ +import { + IconBell, + IconBook, + IconBrain, + IconClock, + IconPlug, + type TablerIcon, +} from "./icons"; +import type { MoreItem } from "./more-items"; + +export const MORE_ICONS: Record = { + routines: IconClock, + notifications: IconBell, + memory: IconBrain, + skills: IconBook, + connections: IconPlug, +}; diff --git a/mobile/src/more-items.ts b/mobile/src/more-items.ts new file mode 100644 index 0000000000..e27b4011a9 --- /dev/null +++ b/mobile/src/more-items.ts @@ -0,0 +1,70 @@ +/** + * The parts of the app that have no tab of their own, in the order they are listed: what the More menu offers + * on iOS (./more-menu.tsx) and what the More screen lists on Android (app/(tabs)/(more)/more.tsx). One + * list, so the two never say different things. + * + * It imports nothing, so it can be tested without a phone. + */ +export type MoreItem = { + key: "routines" | "notifications" | "memory" | "skills" | "connections"; + title: string; + /** What the screen's row says under the title. The menu has no room for it. */ + description: string; + /** The screen it opens, in the app's stack over the tabs. */ + route: "/routines" | "/approvals" | "/memory" | "/skills" | "/connections"; + /** Its glyph in iOS's own set, which the platform's chrome is drawn with. */ + sf: string; + /** The screen's second group, under "Your Bots". The menu draws a line before the first of them. */ + yourBots: boolean; +}; + +export const MORE_ITEMS: readonly MoreItem[] = [ + { + key: "routines", + title: "Routines", + description: "What your Bots do for you on a schedule", + route: "/routines", + sf: "clock", + yourBots: false, + }, + { + // Everything that waits on the person (what their Bots ask and what their check-ins found), and whether + // this phone is told: one place. + key: "notifications", + title: "Notifications", + description: "What waits on you, and this phone's alerts", + route: "/approvals", + sf: "bell.badge", + yourBots: false, + }, + { + key: "memory", + title: "Memory", + description: "What your Bots remember about you", + route: "/memory", + sf: "brain", + yourBots: true, + }, + { + key: "skills", + title: "Skills", + description: "What your Bots know how to do", + route: "/skills", + sf: "book", + yourBots: true, + }, + { + key: "connections", + title: "Connections", + description: "The apps your Bots use as you", + route: "/connections", + sf: "powerplug", + yourBots: true, + }, +]; + +/** How many wait in Notifications, as a row says it: nothing for none, and no more than two digits. */ +export function waitingLabel(count: number): string | undefined { + if (count <= 0) return undefined; + return count > 99 ? "99+" : String(count); +} diff --git a/mobile/src/more-menu.android.tsx b/mobile/src/more-menu.android.tsx new file mode 100644 index 0000000000..47dcb876a5 --- /dev/null +++ b/mobile/src/more-menu.android.tsx @@ -0,0 +1,127 @@ +/** + * The More menu on Android: what has no tab of its own (./more-items.ts), in Material's own menu, opened by the + * navigation bar's last button. What is picked opens in the app's stack. + * + * The menu is the platform's (Material 3's `DropdownMenu`, drawn by Jetpack Compose): it opens above the button, + * as Material's menus do near the bottom of a screen. It is one surface in the scheme's own colors, with a line + * between its two parts and Material's one shadow under it. (Material's newer grouped menu draws each part as a + * surface of its own, and two of them cast shadows onto each other, cut off at each one's edge.) Nothing of it + * is drawn here but what it opens from: a clear button the size of the bar's own, laid over it (`anchor`, from + * app/(tabs)/_layout.tsx), since a tab can't be told to open a menu. iOS's is ./more-menu.tsx. + */ +import { + DropdownMenu, + DropdownMenuItem, + HorizontalDivider, + Host, + Text as MenuText, + RNHostView, +} from "@expo/ui/jetpack-compose"; +import { router } from "expo-router"; +import { Fragment, useEffect, useState } from "react"; +import { + Pressable, + type StyleProp, + StyleSheet, + View, + type ViewStyle, +} from "react-native"; +import { useCSSVariable, useUniwind } from "uniwind"; +import { Icon } from "./components/icon"; +import { MORE_ICONS } from "./more-icons"; +import { MORE_ITEMS, waitingLabel } from "./more-items"; + +export function MoreMenu({ + open, + onClose, + count, + anchor, +}: { + /** True once the tab itself was pressed, where the press reached the bar and not the button over it. */ + open: boolean; + onClose: () => void; + /** How many things wait on the person, said beside Notifications. */ + count: number; + /** Where the bar's last button is, and how large. */ + anchor: StyleProp; +}) { + const { theme } = useUniwind(); + const [surface, foreground, muted, border] = useCSSVariable([ + "--color-overlay", + "--color-foreground", + "--color-muted", + "--color-border", + ]) as (string | undefined)[]; + const [expanded, setExpanded] = useState(false); + useEffect(() => { + if (open) setExpanded(true); + }, [open]); + const close = () => { + setExpanded(false); + onClose(); + }; + const waiting = waitingLabel(count); + const { width, height } = StyleSheet.flatten(anchor) ?? {}; + return ( + + + + + + {/* Said by the tab under it, which a screen reader presses. */} + setExpanded(true)} + > + + + + + + {MORE_ITEMS.map((item, index) => ( + + {/* A line before what every Bot shares. */} + {item.yourBots && !MORE_ITEMS[index - 1]?.yourBots ? ( + + ) : null} + { + close(); + router.push(item.route); + }} + > + + {/* The app's own glyph, as More's screen and every other screen draw it. */} + + + + + + + + {item.title} + + {item.key === "notifications" && waiting ? ( + + {waiting} + + ) : null} + + + ))} + + + + + ); +} diff --git a/mobile/src/more-menu.tsx b/mobile/src/more-menu.tsx new file mode 100644 index 0000000000..1303a445b7 --- /dev/null +++ b/mobile/src/more-menu.tsx @@ -0,0 +1,235 @@ +/** + * The More menu: what has no tab of its own (./more-items.ts), in a small menu that rises from the tab bar's + * last button and opens the screen that is picked. On iOS, where a tab that only held a list of five links + * cost a screen and a second tap. + * + * It is the platform's chrome, so it is drawn as iOS draws a menu: its own glass where the phone has it (iOS 26) + * and its blur material before that, SF Symbols, and a row to a line. A tap outside puts it away. It grows from + * the corner it was called from, and only fades where the person asked for less motion. + * + * This is iOS's. Android's is Material's own menu (./more-menu.android.tsx), which opens above its button. + * + * It is drawn here and is not iOS's own menu (`@expo/ui`'s `Menu`) for where it stands: the system's menu opens + * over the button that opens it, so it covered the tab bar, and it opens only from a press inside that button's + * own frame, so it can't be hung from anything above the bar. This one stands clear of the bar. + */ +import { BlurView } from "expo-blur"; +import { GlassView, isLiquidGlassAvailable } from "expo-glass-effect"; +import { router } from "expo-router"; +import { SymbolView } from "expo-symbols"; +import { type ReactNode, useCallback, useEffect, useState } from "react"; +import { + Pressable, + type StyleProp, + StyleSheet, + View, + type ViewStyle, +} from "react-native"; +import Animated, { + Easing, + runOnJS, + useAnimatedStyle, + useReducedMotion, + useSharedValue, + withTiming, +} from "react-native-reanimated"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; +import { useCSSVariable } from "uniwind"; +import { Text } from "./components"; +import { MORE_ITEMS, type MoreItem, waitingLabel } from "./more-items"; + +/** How far the tab bar's top edge is above the home indicator's room, and the gap the menu leaves over it. */ +const TAB_BAR = 54; +const GAP = 10; +const WIDTH = 248; +const RADIUS = 26; +const OPEN_MS = 260; +const CLOSE_MS = 150; + +/** + * The menu's ground: the phone's own glass, and its blur where there is none. Either stands off the screen by a + * soft shadow under it, on a view of its own: one that clips to its corners would clip its shadow too. On a + * light page glass alone has no edge to see. + */ +function Ground({ children }: { children: ReactNode }) { + // A hairline in the scheme's border: on a light page, glass over white has no edge of its own to see. + const edge = useCSSVariable("--color-border") as string | undefined; + return ( + + {isLiquidGlassAvailable() ? ( + + {children} + + ) : ( + + + {children} + + )} + + ); +} + +export function MoreMenu({ + open, + onClose, + count, +}: { + open: boolean; + onClose: () => void; + /** How many things wait on the person, said beside Notifications. */ + count: number; + /** Where the bar's last button is. Android's menu hangs from it (./more-menu.android.tsx); this one doesn't. */ + anchor?: StyleProp; +}) { + const insets = useSafeAreaInsets(); + const reduceMotion = useReducedMotion(); + const [foreground, border] = useCSSVariable([ + "--color-foreground", + "--color-border", + ]) as (string | undefined)[]; + // Drawn until it has finished leaving, so closing is seen. + const [drawn, setDrawn] = useState(open); + const shown = useSharedValue(0); + useEffect(() => { + if (open) { + setDrawn(true); + shown.value = withTiming(1, { + duration: OPEN_MS, + easing: Easing.out(Easing.exp), + }); + return; + } + shown.value = withTiming( + 0, + { duration: CLOSE_MS, easing: Easing.in(Easing.quad) }, + (finished) => { + if (finished) runOnJS(setDrawn)(false); + }, + ); + }, [open, shown]); + const rising = useAnimatedStyle(() => ({ + opacity: Math.min(1, shown.value * 1.6), + transform: reduceMotion + ? [] + : [ + { scale: 0.82 + 0.18 * shown.value }, + { translateY: 10 * (1 - shown.value) }, + ], + })); + + const waiting = waitingLabel(count); + + const pick = useCallback( + (item: MoreItem) => { + onClose(); + router.push(item.route); + }, + [onClose], + ); + + if (!drawn) return null; + return ( + + + + + {MORE_ITEMS.map((item, index) => ( + + {item.yourBots && !MORE_ITEMS[index - 1]?.yourBots ? ( + + ) : null} + pick(item)} + className="active:bg-foreground/10" + style={styles.row} + > + + + {item.title} + + {item.key === "notifications" && waiting ? ( + + + {waiting} + + + ) : null} + + + ))} + + + + ); +} + +const styles = StyleSheet.create({ + menu: { + position: "absolute", + right: 21, + width: WIDTH, + transformOrigin: "bottom right", + }, + ground: { + borderRadius: RADIUS, + borderCurve: "continuous", + overflow: "hidden", + paddingVertical: 8, + }, + // Drawn by React Native, so it shows under glass, which has no layer of its own to cast one. + lifted: { + borderRadius: RADIUS, + borderCurve: "continuous", + boxShadow: "0 14 34 rgba(0, 0, 0, 0.2), 0 2 6 rgba(0, 0, 0, 0.08)", + }, + edged: { borderWidth: StyleSheet.hairlineWidth }, + row: { + minHeight: 48, + flexDirection: "row", + alignItems: "center", + gap: 14, + paddingHorizontal: 18, + }, + symbol: { width: 24, height: 24 }, + rule: { + height: StyleSheet.hairlineWidth, + marginVertical: 6, + marginHorizontal: 18, + }, +}); diff --git a/mobile/src/organization.ts b/mobile/src/organization.ts index cbba077b8c..fcece5f721 100644 --- a/mobile/src/organization.ts +++ b/mobile/src/organization.ts @@ -13,8 +13,24 @@ export type ListedOrganization = { id: string; name?: string; active?: boolean; + /** The person's role in it, as the server answers it: "owner", "admin", "member", or one this app doesn't know. */ + role?: string; + /** Whether it is the person's own: the one OpenBot made for them when they first signed in. */ + personal?: boolean; }; +/** + * How somebody is rid of one of their organizations from the phone: its owner deletes it, anybody else leaves it, + * and their own stays with their account. Where the server didn't say which it is to them, nothing is offered. + * OpenBot decides in the end, and its refusal is shown as it says it: the last owner can't leave. + */ +export type WayOut = "delete" | "leave" | "none"; + +export function wayOut(organization: ListedOrganization): WayOut { + if (organization.personal !== false || !organization.role) return "none"; + return organization.role === "owner" ? "delete" : "leave"; +} + /** What somebody in no organization is told. */ export const IN_NO_ORGANIZATION = "You aren't a member of an organization here. Ask an admin to add you."; @@ -128,6 +144,15 @@ export function createOrganizationChoice( return chosen; }, + /** + * The person's organizations changed from this phone (they deleted one, or left it): what is known is forgotten, + * and they are read again. A pick that is gone is not used, so the person works in another of theirs. + */ + async reread(signedInAs: string): Promise { + known = undefined; + return choices(signedInAs); + }, + /** * The organization `organizationId` answered that it isn't there for this person: they were removed from it, or it * was deleted. When it is the one they work in, what is known is forgotten, so the next request reads their diff --git a/mobile/src/needs-you-count.ts b/mobile/src/waiting-count.ts similarity index 51% rename from mobile/src/needs-you-count.ts rename to mobile/src/waiting-count.ts index 1413528b46..0f777c5a6d 100644 --- a/mobile/src/needs-you-count.ts +++ b/mobile/src/waiting-count.ts @@ -1,29 +1,31 @@ import { useCallback, useEffect, useState } from "react"; import { AppState } from "react-native"; -import { everyPage, ORGANIZATION_ID } from "./api"; +import { everyPage, loadApprovalInbox, ORGANIZATION_ID } from "./api"; import { listCheckInItems } from "./api/generated/check-ins/check-ins"; import { listTasks } from "./api/generated/tasks/tasks"; import { waitingTasks } from "./tasks"; const counted = new Set<(count: number) => void>(); -/** What Needs you lists now, said by the screen itself once it has read the list: the badge follows at once. */ -export function showNeedsYouCount(count: number) { +/** What Notifications lists now, said by the screen itself once it has read the lists: the badge follows at once. */ +export function showWaitingCount(count: number) { for (const show of counted) show(count); } /** - * How many things Needs you lists: what the Bots' check-ins found and the tasks that wait on the - * person. The Needs you tab's badge. Read when the tabs open, each time the person moves to another tab, - * and when the app comes back to the front; it doesn't poll, as the badge is a hint and Needs you - * itself reads the full list, and says its count here as it changes ({@link showNeedsYouCount}). - * A count that fails to read keeps the last one. + * How many things wait on the person, which is what Notifications lists (app/approvals.tsx): what their Bots + * asked to approve, the questions they asked, what the Bots' check-ins found, and the tasks that wait on the + * person. The badge on More, and the count beside Notifications there. Read when the tabs open, each time the + * person moves to another screen, and when the app comes back to the front; it doesn't poll, as the badge is a + * hint and Notifications itself reads the full lists, and says its count here as it changes + * ({@link showWaitingCount}). A count that fails to read keeps the last one. */ -export function useNeedsYouCount(enabled: boolean, readAgain: unknown) { +export function useWaitingCount(enabled: boolean, readAgain: unknown) { const [count, setCount] = useState(0); const read = useCallback(async () => { try { - const [items, tasks] = await Promise.all([ + const [inbox, items, tasks] = await Promise.all([ + loadApprovalInbox(), everyPage( (page) => listCheckInItems(ORGANIZATION_ID, page), (page) => page.checkInItems, @@ -33,7 +35,13 @@ export function useNeedsYouCount(enabled: boolean, readAgain: unknown) { (page) => page.tasks, ), ]); - setCount(items.length + waitingTasks(tasks).length); + setCount( + inbox.requests.filter((request) => request.status === "pending") + .length + + inbox.questions.length + + items.length + + waitingTasks(tasks).length, + ); } catch { // The badge keeps what it last showed. } diff --git a/mobile/tests/more-items.test.ts b/mobile/tests/more-items.test.ts new file mode 100644 index 0000000000..5017b93278 --- /dev/null +++ b/mobile/tests/more-items.test.ts @@ -0,0 +1,111 @@ +/** + * What has no tab of its own (src/more-items.ts): the one list the More menu on iOS and the More screen on Android + * both draw, and the button that opens the menu. + */ + +import { expect, test } from "bun:test"; +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { MORE_ITEMS, waitingLabel } from "../src/more-items"; + +const app = (...parts: string[]) => + join(import.meta.dir, "..", "app", ...parts); + +test("every part opens a screen the app has", () => { + for (const item of MORE_ITEMS) + expect(existsSync(app(`${item.route.slice(1)}.tsx`))).toBe(true); +}); + +test("no part is listed twice, and each has its words and its glyph", () => { + expect(new Set(MORE_ITEMS.map((item) => item.key)).size).toBe( + MORE_ITEMS.length, + ); + expect(new Set(MORE_ITEMS.map((item) => item.route)).size).toBe( + MORE_ITEMS.length, + ); + for (const item of MORE_ITEMS) { + expect(item.title.length).toBeGreaterThan(0); + expect(item.description.length).toBeGreaterThan(0); + expect(item.sf).toMatch(/^[a-z0-9.]+$/); + } +}); + +test("the parts that are about every Bot come last, together", () => { + // The menu draws one line before the first of them, and the screen puts them under one heading. + const groups = MORE_ITEMS.map((item) => item.yourBots); + expect(groups).toEqual([...groups].sort((a, b) => Number(a) - Number(b))); + expect(groups.includes(true)).toBe(true); + expect(groups.includes(false)).toBe(true); +}); + +test("how many wait is said only when some do, and in no more than two digits", () => { + expect(waitingLabel(0)).toBeUndefined(); + expect(waitingLabel(-1)).toBeUndefined(); + expect(waitingLabel(1)).toBe("1"); + expect(waitingLabel(99)).toBe("99"); + expect(waitingLabel(100)).toBe("99+"); +}); + +test("everything that waits on the person, and this phone's switch, are one part called Notifications", () => { + const notifications = MORE_ITEMS.find((item) => item.key === "notifications"); + expect(notifications?.title).toBe("Notifications"); + // The screen keeps its address, which a notification opens. + expect(notifications?.route).toBe("/approvals"); + expect(MORE_ITEMS.some((item) => /approval/i.test(item.title))).toBe(false); + const screen = readFileSync(app("approvals.tsx"), "utf8"); + expect(screen).toContain('title="Allow notifications"'); + expect(screen).toContain("onValueChange={setNotifications}"); + // What the Needs you tab listed is here too: what check-ins found, and the tasks that wait. + expect(screen).toContain(" { + const tabs = readFileSync(app("(tabs)", "_layout.tsx"), "utf8"); + expect(tabs).not.toContain("needs-you"); + expect(existsSync(app("(tabs)", "(needs-you)"))).toBe(false); + // A ping's notification opens openbotmobile://needs-you (src/links.ts): it goes to Notifications. + expect(readFileSync(app("needs-you.tsx"), "utf8")).toContain( + '', + ); + // More's badge counts what waits there, with the bar's buttons counted right for the press over More. + expect(tabs).toContain("useWaitingCount(true, usePathname())"); + expect(tabs).toContain("const TABS = 4;"); + expect( + ( + tabs.match( + / { + // The tab bar needs a phone, so its source is read: the tab is told not to open, and its press opens the menu. + const tabs = readFileSync(app("(tabs)", "_layout.tsx"), "utf8"); + expect(tabs).toMatch(/name="\(more\)"[\s\S]{0,400}?\n\s+disabled\n/); + expect(tabs).toContain('event.target?.startsWith("(more)")'); + expect(tabs).toContain(" { + const read = (...parts: string[]) => + readFileSync(join(import.meta.dir, "..", ...parts), "utf8"); + expect(read("src", "more-menu.tsx")).toContain("MORE_ITEMS.map("); + expect(read("app", "(tabs)", "(more)", "more.tsx")).toContain( + "MORE_ITEMS.filter(", + ); +}); diff --git a/mobile/tests/organization-way-out.test.ts b/mobile/tests/organization-way-out.test.ts new file mode 100644 index 0000000000..526e9c261f --- /dev/null +++ b/mobile/tests/organization-way-out.test.ts @@ -0,0 +1,119 @@ +/** + * The way out of an organization from the phone (src/organization.ts): which one a row on Account offers when it is + * swiped, and that the person's organizations are read again once one of them is gone. + */ + +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { + createOrganizationChoice, + type ListedOrganization, + wayOut, +} from "../src/organization"; + +const source = (...parts: string[]) => + readFileSync(join(import.meta.dir, "..", ...parts), "utf8"); + +const organization = ( + change: Partial, +): ListedOrganization => ({ + id: "org_work", + name: "Work", + role: "member", + personal: false, + ...change, +}); + +test("an owner deletes an organization, and anybody else leaves it", () => { + expect(wayOut(organization({ role: "owner" }))).toBe("delete"); + expect(wayOut(organization({ role: "admin" }))).toBe("leave"); + expect(wayOut(organization({ role: "member" }))).toBe("leave"); + // A role this app doesn't know is a member's. + expect(wayOut(organization({ role: "auditor" }))).toBe("leave"); +}); + +test("a person's own organization has no way out, whatever their role in it", () => { + expect(wayOut(organization({ personal: true, role: "owner" }))).toBe("none"); + expect(wayOut(organization({ personal: true, role: "member" }))).toBe("none"); +}); + +test("nothing is offered where the server didn't say what the organization is to the person", () => { + // An OpenBot that keeps one organization has no list of them: the phone knows only its id. + expect(wayOut({ id: "default", active: true })).toBe("none"); + expect(wayOut(organization({ role: undefined }))).toBe("none"); + expect(wayOut(organization({ personal: undefined }))).toBe("none"); +}); + +test("after one is deleted or left, the list is read again and a pick that is gone is not used", async () => { + let listed: ListedOrganization[] = [ + { id: "org_own", active: true }, + { id: "org_work" }, + ]; + let reads = 0; + const kept = new Map([["person_1", "org_work"]]); + const choice = createOrganizationChoice( + async () => { + reads += 1; + return listed; + }, + { + read: async (person) => kept.get(person) ?? null, + write: async (person, id) => { + kept.set(person, id); + }, + }, + () => "person_1", + ); + expect(await choice.current("token")).toBe("org_work"); + // Asked again, it is what is known: one read for the sign-in. + expect(await choice.current("token")).toBe("org_work"); + expect(reads).toBe(1); + + listed = [{ id: "org_own", active: true }]; + const now = await choice.reread("token"); + expect(reads).toBe(2); + expect(now.organizations.map((one) => one.id)).toEqual(["org_own"]); + expect(now.currentId).toBe("org_own"); + expect(await choice.current("token")).toBe("org_own"); +}); + +test("Account's rows swipe for the way out, and both ways read the person's organizations again", () => { + // The screens need a phone, so their source is read. + const account = source("app", "(tabs)", "(account)", "account.tsx"); + expect(account).toContain("action={swipe(organization)}"); + expect(account).toContain("wayOut(organization)"); + expect(account).toContain("await rereadOrganizations();"); + expect(source("app", "delete-organization.tsx")).toContain( + "await rereadOrganizations()", + ); + // A swipe alone does nothing: what it offers can't be taken back, so only a tap on the button does it. + const row = source("src", "components", "swipe-row.tsx"); + expect(row).toContain("overshootRight={false}"); + expect(row).not.toContain("onSwipeableOpen="); +}); + +test("an empty list says so in the middle of the screen", () => { + // The page and the list are as tall as what the person sees, and the empty state takes the room left in them. + const screen = source("src", "components", "screen.tsx"); + expect(screen).toContain( + "contentContainerStyle={{ minHeight: seen?.height }}", + ); + expect(screen).toContain("{ minHeight: room?.height },"); + expect(source("src", "components", "empty-state.tsx")).toContain( + 'className="grow items-center justify-center', + ); + for (const list of [ + ["app", "(tabs)", "(bots)", "bots.tsx"], + ["app", "(tabs)", "(conversations)", "index.tsx"], + ]) + expect(source(...list)).toContain(" { + const screen = source("src", "components", "screen.tsx"); + // A page says where it is scrolled to, and one that is at rest has no fade over its own first lines. + expect(screen).toContain("scrolledTo(event.nativeEvent.contentOffset.y)"); + expect(screen).toContain(""); + expect(screen).toContain("under === false ? 0 : 1"); +});