diff --git a/README.md b/README.md index 79c6561..5994ddf 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ src/auth/ session store, auth context, deep-link capture src/team/ team context, switcher, creation, invitations src/board/ board and list views, filters, drag-to-move src/issues/ priority and status metadata +src/offline/ connectivity, cache persistence, the mutation queue src/ui/ design tokens, theme, primitives, navigation chrome openapi/ the vendored API contract codegen reads ``` @@ -97,11 +98,12 @@ The mockups reuse the web app's design tokens (brand `#6342db`, tinted neutrals, ## Status -Onboarding works end to end: sign in to any instance, register, accept an -invitation, create and switch teams, and work a team's board -- columns from the -team's own statuses, six server-side filters held in the URL, board and list -views, and drag or tap to move a card. Search and Inbox are placeholders -pointing at their issues. +Every tracked issue is implemented except push notifications, which have no +backend to talk to. Sign in to any instance, register, accept invitations, +manage teams, work a board, create and edit issues with sub-issues and links, +comment in GitHub-flavored markdown, attach photos and files, search, run cycles, +read the four reports, save views, administer a team or the whole instance, and +keep working with no connection. Known gaps, tracked rather than hidden: @@ -125,6 +127,9 @@ Known gaps, tracked rather than hidden: - **Member counts cost one request per team.** `TeamRead` carries no count, so the teams list asks each team for its members. A `member_count` field upstream would remove the fan-out and help the web too. +- **Offline is verified as logic, not as behaviour.** The queue, the conflict + rule and the cache are covered by tests, but nobody has watched a phone lose + signal, move a card and come back. That needs a device. - **No aurora or glass blur yet.** The web's translucent panels are approximated with opaque surfaces; `backdrop-filter` has no React Native equivalent and per-surface blur is expensive on Android. diff --git a/package-lock.json b/package-lock.json index 76ba300..4860f5d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,10 @@ "version": "0.1.0", "dependencies": { "@react-native-async-storage/async-storage": "2.2.0", + "@react-native-community/netinfo": "12.0.1", + "@tanstack/query-async-storage-persister": "^5.102.8", "@tanstack/react-query": "^5.102.8", + "@tanstack/react-query-persist-client": "^5.102.8", "axios": "^1.20.0", "expo": "~57.0.22", "expo-blur": "~57.0.3", @@ -3657,6 +3660,16 @@ "react-native": "^0.0.0-0 || >=0.65 <1.0" } }, + "node_modules/@react-native-community/netinfo": { + "version": "12.0.1", + "resolved": "https://registry.npmjs.org/@react-native-community/netinfo/-/netinfo-12.0.1.tgz", + "integrity": "sha512-P/3caXIvfYSJG8AWJVefukg+ZGRPs+M4Lp3pNJtgcTYoJxCjWrKQGNnCkj/Cz//zWa/avGed0i/wzm0T8vV2IQ==", + "license": "MIT", + "peerDependencies": { + "react": "*", + "react-native": ">=0.59" + } + }, "node_modules/@react-native-masked-view/masked-view": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/@react-native-masked-view/masked-view/-/masked-view-0.3.2.tgz", @@ -4218,6 +4231,20 @@ "@sinonjs/commons": "^3.0.0" } }, + "node_modules/@tanstack/query-async-storage-persister": { + "version": "5.102.8", + "resolved": "https://registry.npmjs.org/@tanstack/query-async-storage-persister/-/query-async-storage-persister-5.102.8.tgz", + "integrity": "sha512-9smqFJWyhRo+0l3NqaGFo6CQVr+3jpKOVZBQXI/LL+GoTIGhhxq1wTZegeI63dy0oResZx/EyazGzDjW8harbg==", + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.102.8", + "@tanstack/query-persist-client-core": "5.102.8" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, "node_modules/@tanstack/query-core": { "version": "5.102.8", "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.102.8.tgz", @@ -4228,6 +4255,19 @@ "url": "https://github.com/sponsors/tannerlinsley" } }, + "node_modules/@tanstack/query-persist-client-core": { + "version": "5.102.8", + "resolved": "https://registry.npmjs.org/@tanstack/query-persist-client-core/-/query-persist-client-core-5.102.8.tgz", + "integrity": "sha512-t3v4/D6ejo/BrPzM5gm/AT3c4CWPCxFa+0cIjAeHAeanGPG6rCjFS1hZnPZH/rf55qe3qYYgx5U6iBZMY1PQjA==", + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.102.8" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, "node_modules/@tanstack/react-query": { "version": "5.102.8", "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.102.8.tgz", @@ -4244,6 +4284,23 @@ "react": "^18 || ^19" } }, + "node_modules/@tanstack/react-query-persist-client": { + "version": "5.102.8", + "resolved": "https://registry.npmjs.org/@tanstack/react-query-persist-client/-/react-query-persist-client-5.102.8.tgz", + "integrity": "sha512-WOZReC+m9klekPtG7eeZ3txJeMA9lg2R0RytSG3yXcZgJItQAVIyoobJdbdIQtlpgcU2tSzsOEBtJacs2vlCOA==", + "license": "MIT", + "dependencies": { + "@tanstack/query-persist-client-core": "5.102.8" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "@tanstack/react-query": "^5.102.8", + "react": "^18 || ^19" + } + }, "node_modules/@testing-library/react-native": { "version": "14.0.1", "resolved": "https://registry.npmjs.org/@testing-library/react-native/-/react-native-14.0.1.tgz", diff --git a/package.json b/package.json index 8e335d1..df5300e 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,10 @@ }, "dependencies": { "@react-native-async-storage/async-storage": "2.2.0", + "@react-native-community/netinfo": "12.0.1", + "@tanstack/query-async-storage-persister": "^5.102.8", "@tanstack/react-query": "^5.102.8", + "@tanstack/react-query-persist-client": "^5.102.8", "axios": "^1.20.0", "expo": "~57.0.22", "expo-blur": "~57.0.3", diff --git a/src/api/__tests__/live-notifications.test.ts b/src/api/__tests__/live-notifications.test.ts index d5ad3d7..f3d1ef2 100644 --- a/src/api/__tests__/live-notifications.test.ts +++ b/src/api/__tests__/live-notifications.test.ts @@ -17,8 +17,10 @@ import { unreadCountNotificationsUnreadCountGet, updateNotificationNotificationsNotificationIdPatch, } from '@/api/generated/endpoints/notifications/notifications'; -import { createInviteTeamsTeamIdInvitesPost } from '@/api/generated/endpoints/invites/invites'; -import { acceptInviteInvitesTokenAcceptPost } from '@/api/generated/endpoints/invites/invites'; +import { + acceptInviteInvitesTokenAcceptPost, + createInviteTeamsTeamIdInvitesPost, +} from '@/api/generated/endpoints/invites/invites'; import { listMyTeamsTeamsGet } from '@/api/generated/endpoints/teams/teams'; import type { TeamRead } from '@/api/generated/models'; import { setInstanceUrl } from '@/api/instance'; diff --git a/src/api/query-client.ts b/src/api/query-client.ts index 5b40782..297d4e0 100644 --- a/src/api/query-client.ts +++ b/src/api/query-client.ts @@ -13,6 +13,10 @@ export const queryClient = new QueryClient({ queries: { retry: 1, refetchOnWindowFocus: false, + // Long enough that a persisted cache is still served after a restart -- + // without it everything would be discarded as stale on the way in, which + // is exactly the case offline reading exists for. + gcTime: 7 * 24 * 60 * 60 * 1000, }, }, }); diff --git a/src/app/_layout.tsx b/src/app/_layout.tsx index 118f657..28018fd 100644 --- a/src/app/_layout.tsx +++ b/src/app/_layout.tsx @@ -6,10 +6,13 @@ import { Stack } from 'expo-router'; import * as SplashScreen from 'expo-splash-screen'; import * as SystemUI from 'expo-system-ui'; import { StatusBar } from 'expo-status-bar'; -import { QueryClientProvider } from '@tanstack/react-query'; +import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'; import { hydrateInstanceUrl } from '@/api/instance'; import { queryClient } from '@/api/query-client'; +import { startConnectivityWatch } from '@/offline/connectivity'; +import { MAX_AGE_MS, persister } from '@/offline/persistence'; +import { registerQueuedMutations } from '@/offline/queue'; import { AuthProvider, useAuth } from '@/auth/auth-context'; import { hydrateSession } from '@/auth/session'; import { useDeepLinkCapture } from '@/auth/use-deep-link-capture'; @@ -149,6 +152,13 @@ function Gate() { export default function RootLayout() { const [hydrated, setHydrated] = useState(null); + useEffect(() => { + // Mutation functions have to be registered by key before a persisted queue + // is restored, or a paused mutation comes back as data with nothing to run. + registerQueuedMutations(queryClient); + return startConnectivityWatch(); + }, []); + useEffect(() => { // One pass over persisted state before anything renders: the stored theme, // the instance URL, and the token -- each into its module-level mirror so @@ -173,13 +183,19 @@ export default function RootLayout() { - + void queryClient.resumePausedMutations()} + > - + diff --git a/src/board/board-screen.tsx b/src/board/board-screen.tsx index deccf74..08fbe15 100644 --- a/src/board/board-screen.tsx +++ b/src/board/board-screen.tsx @@ -13,6 +13,7 @@ import { KanbanBoard } from '@/board/kanban-board'; import { useStatusChange } from '@/board/use-status-change'; import { CycleBanner, CyclesSheet } from '@/cycles/cycles-screen'; import { ReportsSheet } from '@/reports/reports-sheet'; +import { OfflineBanner, SyncQueueSheet } from '@/offline/sync-status'; import { useListViewsTeamsTeamIdViewsGet } from '@/api/generated/endpoints/views/views'; import { useAuth } from '@/auth/auth-context'; import { fromViewFilters } from '@/views/saved-views'; @@ -58,6 +59,7 @@ export function BoardScreen() { const [viewsOpen, setViewsOpen] = useState(false); const [cyclesOpen, setCyclesOpen] = useState(false); const [reportsOpen, setReportsOpen] = useState(false); + const [syncOpen, setSyncOpen] = useState(false); const [switching, setSwitching] = useState(false); const [creating, setCreating] = useState(false); const [moving, setMoving] = useState(null); @@ -213,6 +215,8 @@ export function BoardScreen() { + setSyncOpen(true)} /> + setCyclesOpen(true)} /> setFilterOpen(true)} /> @@ -235,6 +239,8 @@ export function BoardScreen() { /> )} + setSyncOpen(false)} /> + setReportsOpen(false)} diff --git a/src/board/use-status-change.ts b/src/board/use-status-change.ts index e7a02db..ca78b4f 100644 --- a/src/board/use-status-change.ts +++ b/src/board/use-status-change.ts @@ -1,10 +1,8 @@ import { useCallback } from 'react'; -import { useQueryClient } from '@tanstack/react-query'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; -import { - getListIssuesTeamsTeamIdIssuesGetQueryKey, - updateIssueIssuesIssueIdPatch, -} from '@/api/generated/endpoints/issues/issues'; +import { getListIssuesTeamsTeamIdIssuesGetQueryKey } from '@/api/generated/endpoints/issues/issues'; +import { QUEUED, type MoveIssueVariables } from '@/offline/queue'; import type { ListIssuesTeamsTeamIdIssuesGetParams, PageIssueRead, @@ -22,12 +20,20 @@ import type { * * `params` has to match what the board is showing, because it is part of the * query key being patched. + * + * The write itself goes through a keyed mutation rather than a bare call, so + * React Query pauses it when there is no network and replays it on reconnect -- + * a card moved on a train stays moved, and reaches the server when the train + * comes out of the tunnel. */ export function useStatusChange( team: TeamRead | undefined, params: ListIssuesTeamsTeamIdIssuesGetParams, ) { const queryClient = useQueryClient(); + const move = useMutation({ + mutationKey: QUEUED.moveIssue, + }); return useCallback( async (issueId: number, status: StatusRead): Promise => { @@ -47,8 +53,17 @@ export function useStatusChange( : old, ); + const before = previous?.items.find((item) => item.id === issueId); + try { - await updateIssueIssuesIssueIdPatch(issueId, { status_id: status.id }); + await move.mutateAsync({ + issueId, + status, + // Captured now so a replay can tell "nothing moved" from "somebody + // else moved it while we were away". + seenAt: before?.updated_at ?? '', + identifier: before?.identifier ?? `#${issueId}`, + }); // Moving a card moves its points between columns, and may close out a // cycle's remaining work. void queryClient.invalidateQueries({ queryKey: [`/teams/${team.id}/estimates`] }); @@ -56,10 +71,12 @@ export function useStatusChange( void queryClient.invalidateQueries({ queryKey: [`/issues/${issueId}`] }); return true; } catch { + // A paused mutation does not reject, so reaching here means it was + // genuinely refused -- put the card back where it was. queryClient.setQueryData(queryKey, previous); return false; } }, - [queryClient, team, params], + [queryClient, team, params, move], ); } diff --git a/src/offline/__tests__/queue.test.ts b/src/offline/__tests__/queue.test.ts new file mode 100644 index 0000000..f84d80f --- /dev/null +++ b/src/offline/__tests__/queue.test.ts @@ -0,0 +1,90 @@ +import { QueryClient } from '@tanstack/react-query'; + +import { describeQueued, MoveConflict, QUEUED, registerQueuedMutations } from '@/offline/queue'; + +jest.mock('@/api/generated/endpoints/issues/issues', () => ({ + getIssueIssuesIssueIdGet: jest.fn(), + updateIssueIssuesIssueIdPatch: jest.fn(), + createIssueTeamsTeamIdIssuesPost: jest.fn(), +})); +jest.mock('@/api/generated/endpoints/comments/comments', () => ({ + createCommentIssuesIssueIdCommentsPost: jest.fn(), +})); + +const issues = jest.requireMock('@/api/generated/endpoints/issues/issues'); + +const TODO = { id: 1, name: 'Todo', category: 'unstarted', color: '#000', team_id: 1, position: 1 }; +const DONE = { id: 2, name: 'Done', category: 'done', color: '#0f0', team_id: 1, position: 2 }; + +/** Run the registered move mutation the way a resumed queue would. */ +async function runMove(variables: Record) { + const client = new QueryClient(); + registerQueuedMutations(client); + const defaults = client.getMutationDefaults(QUEUED.moveIssue); + return (defaults.mutationFn as (v: unknown) => Promise)(variables); +} + +beforeEach(() => jest.clearAllMocks()); + +describe('the queued move', () => { + it('applies when nothing changed while offline', async () => { + issues.getIssueIssuesIssueIdGet.mockResolvedValue({ + updated_at: 'T1', + status: TODO, + }); + issues.updateIssueIssuesIssueIdPatch.mockResolvedValue({ status: DONE }); + + await runMove({ issueId: 7, status: DONE, seenAt: 'T1', identifier: 'ENG-7' }); + + expect(issues.updateIssueIssuesIssueIdPatch).toHaveBeenCalledWith(7, { status_id: 2 }); + }); + + it('refuses when somebody else moved it in the meantime', async () => { + // Replaying blindly here would undo their work, which is the whole reason + // the timestamp is captured when the move is queued. + issues.getIssueIssuesIssueIdGet.mockResolvedValue({ + updated_at: 'T2', + status: { ...TODO, id: 3, name: 'In Review' }, + }); + + await expect( + runMove({ issueId: 7, status: DONE, seenAt: 'T1', identifier: 'ENG-7' }), + ).rejects.toBeInstanceOf(MoveConflict); + expect(issues.updateIssueIssuesIssueIdPatch).not.toHaveBeenCalled(); + }); + + it('is not a conflict when somebody made the same move', async () => { + // The issue changed, but it is already where this move wanted it -- there + // is nothing to argue about. + issues.getIssueIssuesIssueIdGet.mockResolvedValue({ updated_at: 'T2', status: DONE }); + issues.updateIssueIssuesIssueIdPatch.mockResolvedValue({ status: DONE }); + + await runMove({ issueId: 7, status: DONE, seenAt: 'T1', identifier: 'ENG-7' }); + expect(issues.updateIssueIssuesIssueIdPatch).toHaveBeenCalled(); + }); + + it('names both sides in the conflict message', async () => { + const conflict = new MoveConflict('ENG-7', 'Done', 'In Review'); + expect(conflict.message).toContain('ENG-7'); + expect(conflict.message).toContain('In Review'); + expect(conflict.message).toContain('Done'); + }); +}); + +describe('describeQueued', () => { + it('says what each waiting change will do', () => { + expect( + describeQueued(QUEUED.moveIssue, { identifier: 'ENG-7', status: DONE }), + ).toBe('Move ENG-7 to Done'); + expect(describeQueued(QUEUED.addComment, { identifier: 'ENG-7' })).toBe( + 'Comment on ENG-7', + ); + expect(describeQueued(QUEUED.createIssue, { title: 'Fix it' })).toBe( + 'New issue “Fix it”', + ); + }); + + it('falls back rather than rendering a key', () => { + expect(describeQueued(['something', 'else'], {})).toBe('Pending change'); + }); +}); diff --git a/src/offline/connectivity.ts b/src/offline/connectivity.ts new file mode 100644 index 0000000..8dc8cb9 --- /dev/null +++ b/src/offline/connectivity.ts @@ -0,0 +1,32 @@ +import NetInfo from '@react-native-community/netinfo'; +import { onlineManager, focusManager } from '@tanstack/react-query'; +import { AppState, type AppStateStatus } from 'react-native'; + +/** + * Telling React Query whether there is a network. + * + * Its browser default listens for `window.online`, which does not exist here -- + * without this, a phone in a tunnel keeps firing requests that time out one by + * one instead of pausing them, and nothing is ever queued. + * + * `isInternetReachable` rather than `isConnected`: a captive portal or a Wi-Fi + * network with no route out is still "connected", and is exactly the case where + * a request will hang rather than fail fast. + */ +export function startConnectivityWatch(): () => void { + const unsubscribeNet = NetInfo.addEventListener((state) => { + const reachable = state.isInternetReachable ?? state.isConnected ?? false; + onlineManager.setOnline(Boolean(reachable)); + }); + + // React Query's focus default is also browser-shaped; on a phone, coming back + // to the app is the equivalent event. + const subscription = AppState.addEventListener('change', (status: AppStateStatus) => { + focusManager.setFocused(status === 'active'); + }); + + return () => { + unsubscribeNet(); + subscription.remove(); + }; +} diff --git a/src/offline/persistence.ts b/src/offline/persistence.ts new file mode 100644 index 0000000..fd1569e --- /dev/null +++ b/src/offline/persistence.ts @@ -0,0 +1,19 @@ +import AsyncStorage from '@react-native-async-storage/async-storage'; +import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister'; + +/** + * The cache that survives the app being closed. + * + * What this buys is offline *reading*: boards, issues and comments that were + * loaded recently are still there with no network. A week is long enough that a + * phone opened on Monday still shows Friday's board, and short enough that + * nothing ancient is presented as current -- the banner says what it is. + */ +export const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; + +export const persister = createAsyncStoragePersister({ + storage: AsyncStorage, + key: 'softtrack.cache', + // Writes are debounced so a fast-scrolling board does not thrash storage. + throttleTime: 1000, +}); diff --git a/src/offline/queue.ts b/src/offline/queue.ts new file mode 100644 index 0000000..d3be5c9 --- /dev/null +++ b/src/offline/queue.ts @@ -0,0 +1,126 @@ +import type { QueryClient } from '@tanstack/react-query'; + +import { createCommentIssuesIssueIdCommentsPost } from '@/api/generated/endpoints/comments/comments'; +import { + createIssueTeamsTeamIdIssuesPost, + getIssueIssuesIssueIdGet, + updateIssueIssuesIssueIdPatch, +} from '@/api/generated/endpoints/issues/issues'; +import type { IssueRead, StatusRead } from '@/api/generated/models'; + +/** + * The mutations that survive going offline. + * + * React Query pauses a mutation while `onlineManager` says there is no network + * and replays it on reconnect. For that to survive the app being killed, the + * mutation function has to be registered by key rather than passed inline -- + * a persisted mutation is only data, and `setMutationDefaults` is what turns it + * back into something runnable. + * + * Only these three are queued. They are the ones the issue names, and the ones + * where doing the work offline is genuinely useful: moving a card, saying + * something, and capturing a thought. Everything else asks for a connection. + */ +export const QUEUED = { + moveIssue: ['offline', 'moveIssue'] as const, + addComment: ['offline', 'addComment'] as const, + createIssue: ['offline', 'createIssue'] as const, +}; + +export type MoveIssueVariables = { + issueId: number; + status: StatusRead; + /** The issue's updated_at when the move was queued, for conflict detection. */ + seenAt: string; + identifier: string; +}; + +export type AddCommentVariables = { + issueId: number; + body: string; + identifier: string; +}; + +export type CreateIssueVariables = { + teamId: number; + title: string; + description?: string; +}; + +/** + * A queued move whose issue changed while we were away. + * + * Thrown rather than silently applied: somebody else moving the card to Done + * while this phone was in a tunnel is exactly the case where replaying blindly + * would undo their work. + */ +export class MoveConflict extends Error { + constructor( + readonly identifier: string, + readonly intended: string, + readonly actual: string, + ) { + super( + `${identifier} moved to ${actual} while you were offline, so it was not moved to ${intended}.`, + ); + this.name = 'MoveConflict'; + } +} + +export function registerQueuedMutations(queryClient: QueryClient): void { + queryClient.setMutationDefaults(QUEUED.moveIssue, { + mutationFn: async (variables: MoveIssueVariables) => { + const current = await getIssueIssuesIssueIdGet(variables.issueId); + + // Unchanged since it was queued: the move is still the one intended. + if (current.updated_at !== variables.seenAt && current.status.id !== variables.status.id) { + throw new MoveConflict( + variables.identifier, + variables.status.name, + current.status.name, + ); + } + + return updateIssueIssuesIssueIdPatch(variables.issueId, { + status_id: variables.status.id, + }); + }, + }); + + queryClient.setMutationDefaults(QUEUED.addComment, { + mutationFn: (variables: AddCommentVariables) => + createCommentIssuesIssueIdCommentsPost(variables.issueId, { body: variables.body }), + }); + + queryClient.setMutationDefaults(QUEUED.createIssue, { + mutationFn: (variables: CreateIssueVariables) => + createIssueTeamsTeamIdIssuesPost(variables.teamId, { + title: variables.title, + description: variables.description, + }), + }); +} + +/** What a queued mutation is called in the sync panel. */ +export function describeQueued(mutationKey: unknown, variables: unknown): string { + const key = Array.isArray(mutationKey) ? mutationKey.join('/') : ''; + + if (key === QUEUED.moveIssue.join('/')) { + const move = variables as MoveIssueVariables; + return `Move ${move.identifier} to ${move.status.name}`; + } + if (key === QUEUED.addComment.join('/')) { + const comment = variables as AddCommentVariables; + return `Comment on ${comment.identifier}`; + } + if (key === QUEUED.createIssue.join('/')) { + const issue = variables as CreateIssueVariables; + return `New issue “${issue.title}”`; + } + return 'Pending change'; +} + +/** The issue as it should look while a queued move waits. */ +export function withQueuedStatus(issue: IssueRead, status: StatusRead): IssueRead { + return { ...issue, status }; +} diff --git a/src/offline/sync-status.tsx b/src/offline/sync-status.tsx new file mode 100644 index 0000000..43822df --- /dev/null +++ b/src/offline/sync-status.tsx @@ -0,0 +1,203 @@ +import { useEffect, useState } from 'react'; +import { Pressable, View } from 'react-native'; +import { + onlineManager, + useIsMutating, + useMutationState, + useQueryClient, +} from '@tanstack/react-query'; + +import { describeQueued, MoveConflict } from '@/offline/queue'; +import { AppText, Button, Card } from '@/ui/primitives'; +import { Sheet } from '@/ui/sheet'; +import { useTokens } from '@/ui/theme'; + +/** Whether there is a network, as React Query currently understands it. */ +export function useIsOnline(): boolean { + const [online, setOnline] = useState(() => onlineManager.isOnline()); + useEffect(() => onlineManager.subscribe(setOnline), []); + return online; +} + +/** + * The offline banner, per `docs/design/mobile/155-offline.svg`. + * + * Shown while there is no network, and also while queued work is still going + * out after one returns -- "back online" with three unsent changes is not the + * same as being up to date, and saying so is the difference between trusting the + * app and refreshing it nervously. + */ +export function OfflineBanner({ onOpenQueue }: { onOpenQueue: () => void }) { + const t = useTokens(); + const online = useIsOnline(); + const pending = useMutationState({ + filters: { status: 'pending' }, + }).length; + const paused = useMutationState({ + filters: { predicate: (mutation) => mutation.state.isPaused }, + }).length; + + const queued = paused + pending; + if (online && queued === 0) return null; + + const tone = online ? t.status.progress : t.priority.medium; + + return ( + + + + {online + ? `Syncing ${queued} change${queued === 1 ? '' : 's'}…` + : queued > 0 + ? `Offline · ${queued} change${queued === 1 ? '' : 's'} waiting` + : 'Offline · showing what was last loaded'} + + {queued > 0 ? ( + + View + + ) : null} + + ); +} + +/** + * The queue, and anything that could not be applied. + * + * A conflict is shown rather than resolved: the server's version and the one + * that was queued are both somebody's intent, and picking between them is not a + * decision to make on their behalf. + */ +export function SyncQueueSheet({ + visible, + onClose, +}: { + visible: boolean; + onClose: () => void; +}) { + const t = useTokens(); + const queryClient = useQueryClient(); + const online = useIsOnline(); + const inFlight = useIsMutating(); + + const all = useMutationState({ + select: (mutation) => ({ + key: mutation.options.mutationKey, + variables: mutation.state.variables, + isPaused: mutation.state.isPaused, + status: mutation.state.status, + error: mutation.state.error, + }), + }); + + const waiting = all.filter((entry) => entry.isPaused || entry.status === 'pending'); + const failed = all.filter((entry) => entry.status === 'error'); + + if (!visible) return null; + + return ( + + + + {online + ? inFlight > 0 + ? 'Sending queued changes…' + : 'Up to date.' + : 'No connection. Changes are kept and sent when one returns.'} + + + {waiting.length > 0 ? ( + + WAITING + {waiting.map((entry, index) => ( + + + + {describeQueued(entry.key, entry.variables)} + + + ))} + + ) : null} + + {failed.length > 0 ? ( + + NEEDS ATTENTION + {failed.map((entry, index) => ( + + + {describeQueued(entry.key, entry.variables)} + + + {entry.error instanceof MoveConflict + ? entry.error.message + : 'Could not be applied.'} + + {entry.error instanceof MoveConflict ? ( + + Open the issue to decide what it should be. + + ) : null} + + ))} + + ) : null} + + {waiting.length === 0 && failed.length === 0 ? ( + Nothing waiting. + ) : null} + + {online && waiting.length > 0 ? ( + + ) : null} + + {failed.length > 0 ? ( + + ) : null} + + + ); +} diff --git a/src/team/admin/automation-panel.tsx b/src/team/admin/automation-panel.tsx index a13ea0c..587f538 100644 --- a/src/team/admin/automation-panel.tsx +++ b/src/team/admin/automation-panel.tsx @@ -18,7 +18,7 @@ import type { import { errorDetail } from '@/api/errors'; import { useTeamData } from '@/board/use-team-data'; import { PRIORITY_LABEL } from '@/issues/issue-meta'; -import { Alert, AppText, Button, Card } from '@/ui/primitives'; +import { Alert, AppText, Card } from '@/ui/primitives'; import { Sheet } from '@/ui/sheet'; import { useTokens } from '@/ui/theme'; diff --git a/src/team/admin/team-admin-sheet.tsx b/src/team/admin/team-admin-sheet.tsx index 27bcfeb..59c0c94 100644 --- a/src/team/admin/team-admin-sheet.tsx +++ b/src/team/admin/team-admin-sheet.tsx @@ -8,8 +8,10 @@ import { rotateSecretRepositoriesRepositoryIdRotatePost, useListRepositoriesTeamsTeamIdRepositoriesGet, } from '@/api/generated/endpoints/integrations/integrations'; -import { updateTeamTeamsTeamIdPatch } from '@/api/generated/endpoints/teams/teams'; -import { useListTeamMembersTeamsTeamIdMembersGet } from '@/api/generated/endpoints/teams/teams'; +import { + updateTeamTeamsTeamIdPatch, + useListTeamMembersTeamsTeamIdMembersGet, +} from '@/api/generated/endpoints/teams/teams'; import type { TeamRead } from '@/api/generated/models'; import { errorDetail } from '@/api/errors'; import { getInstanceUrl } from '@/api/instance';