diff --git a/apps/web/e2e/account.spec.ts b/apps/web/e2e/account.spec.ts index d74db6a9..c34073c4 100644 --- a/apps/web/e2e/account.spec.ts +++ b/apps/web/e2e/account.spec.ts @@ -122,6 +122,35 @@ test('sign out everywhere ends every session', async ({ newUser, openAs }) => { await expect(phone.getByText(t('auth.signIn.sessionEnded'))).toBeVisible() }) +test('a device left open leaves by itself after sign out everywhere, saying why', async ({ + newUser, + openAs, +}) => { + // The other device notices on its next 30 second check, with nobody touching it. + test.setTimeout(120_000) + const user = await newUser() + const phone = await openAs(null) + await signIn(phone, user.email, user.password) + await expect(phone).toHaveURL(/\/home$/) + + const laptop = await openAs(null) + await signIn(laptop, user.email, user.password) + await expect(laptop).toHaveURL(/\/home$/) + await laptop.goto('/me') + await security(laptop) + .getByRole('button', { name: t('security.sessions.signOutAll') }) + .click() + await laptop + .getByRole('dialog', { name: t('security.sessions.confirmTitle') }) + .getByRole('button', { name: t('security.sessions.signOutAll') }) + .click() + await expect(laptop).toHaveURL(/\/sign-in/) + + // No reload, no click: the phone gets to sign in and says why. + await expect(phone).toHaveURL(/\/sign-in/, { timeout: 60_000 }) + await expect(phone.getByText(t('auth.signIn.sessionEnded'))).toBeVisible() +}) + test('two-step sign in: set up, asked at sign in, wrong code refused, off with a code', async ({ newUser, openAs, diff --git a/apps/web/e2e/groups-invites.spec.ts b/apps/web/e2e/groups-invites.spec.ts index 1639c3b7..1daaa70e 100644 --- a/apps/web/e2e/groups-invites.spec.ts +++ b/apps/web/e2e/groups-invites.spec.ts @@ -54,4 +54,22 @@ test('create a group, share an invite, and a signed out friend joins', async ({ // The owner sees the new member. await page.reload() await expect(page.getByText(friend.name).first()).toBeVisible() + + // Revoking from the invite sheet by mistake: one tap on Undo, right there, brings it back. + await page.getByRole('button', { name: t('members.invite') }).click() + const inviteSheet = page.getByRole('dialog', { name: t('invites.title') }) + const sheetLink = inviteSheet.getByRole('region', { name: t('invites.latest') }) + await expect(sheetLink.getByText(`/join/${code}`)).toBeVisible() + await sheetLink.getByRole('button', { name: t('invites.revoke') }).click() + await expect(inviteSheet.getByText(t('invites.revoked'))).toBeVisible() + await expect(sheetLink).toBeHidden() + await inviteSheet.getByRole('button', { name: t('common.undo') }).click() + await expect(inviteSheet).toBeVisible() + await expect(sheetLink.getByText(`/join/${code}`)).toBeVisible() + await expect(inviteSheet.getByText(t('invites.revoked'))).toBeHidden() + + // And the link still lets people in. + const later = await openAs(null) + await later.goto(`/join/${code}`) + await expect(later.getByRole('link', { name: t('invites.join.signInToJoin') })).toBeVisible() }) diff --git a/apps/web/src/features/auth/sign-in-page.test.tsx b/apps/web/src/features/auth/sign-in-page.test.tsx index 24b91a3d..ed26f4d7 100644 --- a/apps/web/src/features/auth/sign-in-page.test.tsx +++ b/apps/web/src/features/auth/sign-in-page.test.tsx @@ -1,8 +1,8 @@ import { t } from '@potluck/i18n' import { Toaster } from '@potluck/ui' -import { fireEvent, screen, waitFor } from '@testing-library/react' +import { act, fireEvent, screen, waitFor } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { endEndedSession } from '@/lib/auth' +import { confirmSession, endEndedSession } from '@/lib/auth' import { renderWithProviders } from '@/test/render' import { authCallsTo, resetDb, respondAuth } from '@/test/supabase' import { SignInPage } from './sign-in-page' @@ -59,6 +59,20 @@ describe('SignInPage', () => { expect(screen.queryByText(t('auth.signIn.sessionEnded'))).not.toBeInTheDocument() }) + it('says why when the session check finds the session gone after the page opened', async () => { + renderPage() + expect(await screen.findByRole('button', { name: t('auth.signIn.submit') })).toBeVisible() + expect(screen.queryByText(t('auth.signIn.sessionEnded'))).not.toBeInTheDocument() + + respondAuth('getSession', { data: { session: { user: { id: 'u-1' }, access_token: 'x' } } }) + respondAuth('getUser', async () => { + respondAuth('getSession', { data: { session: null } }) + return { data: { user: null }, error: { name: 'AuthSessionMissingError', status: 400 } } + }) + await act(() => confirmSession()) + expect(await screen.findByText(t('auth.signIn.sessionEnded'))).toBeInTheDocument() + }) + it('never redirects off site after signing in', async () => { const { router } = renderPage({ redirect: 'https://evil.example' }) await fill('ava@example.test', 'hunter22') diff --git a/apps/web/src/features/auth/sign-in-page.tsx b/apps/web/src/features/auth/sign-in-page.tsx index 98ca6fe3..c6beb470 100644 --- a/apps/web/src/features/auth/sign-in-page.tsx +++ b/apps/web/src/features/auth/sign-in-page.tsx @@ -2,7 +2,13 @@ import { Link, useNavigate } from '@tanstack/react-router' import { currentLocale, t } from '@potluck/i18n' import { Button, Field, Input, toast } from '@potluck/ui' import { useEffect, useState, type FormEvent } from 'react' -import { authCallbackUrl, clearSessionEnded, safeRedirect, sessionEndedHere } from '@/lib/auth' +import { + authCallbackUrl, + clearSessionEnded, + onSessionEnded, + safeRedirect, + sessionEndedHere, +} from '@/lib/auth' import { errorMessage } from '@/lib/errors' import { detectTimezone } from '@/lib/locale' import { supabase } from '@/lib/supabase' @@ -19,9 +25,17 @@ type Mode = 'password' | 'magic' | 'sent' export function SignInPage({ redirect, notice }: AuthPageProps) { const navigate = useNavigate() - // Signed out because the session ended on another device: say so once, here. - const [ended] = useState(sessionEndedHere) - useEffect(() => clearSessionEnded(), []) + // Signed out because the session ended on another device: say so once, here. The periodic + // check can land on this page a moment before it leaves the note, so listen for it too. + const [ended, setEnded] = useState(sessionEndedHere) + useEffect(() => { + const take = () => { + if (sessionEndedHere()) setEnded(true) + clearSessionEnded() + } + take() + return onSessionEnded(take) + }, []) const [mode, setMode] = useState('password') const [email, setEmail] = useState('') const [password, setPassword] = useState('') diff --git a/apps/web/src/features/expenses/expense-detail-parts.tsx b/apps/web/src/features/expenses/expense-detail-parts.tsx index 9a5a3434..9167382a 100644 --- a/apps/web/src/features/expenses/expense-detail-parts.tsx +++ b/apps/web/src/features/expenses/expense-detail-parts.tsx @@ -64,6 +64,14 @@ export function PayersLine({ ) } +/** "owes €5" or "gets back €5", or for the viewer's own row "owe" and "get back". */ +function owesOrGetsBack(isMe: boolean, getsBack: boolean, amount: string): string { + if (getsBack) { + return t(isMe ? 'expenses.detail.you.getBack' : 'expenses.detail.getsBack', { amount }) + } + return t(isMe ? 'expenses.detail.you.owe' : 'expenses.detail.owes', { amount }) +} + /** * Everyone on the expense: their share on the right, and underneath what they paid (or got * back) and how the share was worked out. Payers who are not in the split are listed too, so @@ -121,19 +129,31 @@ export function SplitCard({ const share = s?.share_cents ?? 0 const paid = paidBy.get(id) const isMe = id === me + // Your own row sits under "You", so its verbs agree with you ("You / owe"). const line = paid !== undefined ? s - ? t(e.is_refund ? 'expenses.detail.gotAndShare' : 'expenses.detail.paidAndShare', { - paid: money(paid), - share: money(share), - }) - : t(e.is_refund ? 'expenses.detail.gotOnly' : 'expenses.detail.paidOnly', { - amount: money(paid), - }) - : e.is_refund - ? t('expenses.detail.getsBack', { amount: money(share) }) - : t('expenses.detail.owes', { amount: money(share) }) + ? t( + e.is_refund + ? isMe + ? 'expenses.detail.you.gotAndShare' + : 'expenses.detail.gotAndShare' + : isMe + ? 'expenses.detail.you.paidAndShare' + : 'expenses.detail.paidAndShare', + { paid: money(paid), share: money(share) }, + ) + : t( + e.is_refund + ? isMe + ? 'expenses.detail.you.gotOnly' + : 'expenses.detail.gotOnly' + : isMe + ? 'expenses.detail.you.paidOnly' + : 'expenses.detail.paidOnly', + { amount: money(paid) }, + ) + : owesOrGetsBack(isMe, e.is_refund, money(share)) return (
  • 0 ? 'text-saffron-ink' : 'text-tomato-ink', )} > - {sign * (paid - share) > 0 - ? t('expenses.detail.getsBack', { amount: money(sign * (paid - share)) }) - : t('expenses.detail.owes', { amount: money(-sign * (paid - share)) })} + {owesOrGetsBack(isMe, sign * (paid - share) > 0, money(Math.abs(paid - share)))} )} diff --git a/apps/web/src/features/expenses/expense-detail.test.tsx b/apps/web/src/features/expenses/expense-detail.test.tsx index e2462fcc..593a69f0 100644 --- a/apps/web/src/features/expenses/expense-detail.test.tsx +++ b/apps/web/src/features/expenses/expense-detail.test.tsx @@ -1,5 +1,5 @@ import { moneyKeys, type ExpenseComment, type ExpenseWithSplits } from '@potluck/api' -import { t } from '@potluck/i18n' +import { formatMoney, setLocale, t } from '@potluck/i18n' import { Toaster } from '@potluck/ui' import { fireEvent, screen, waitFor, within } from '@testing-library/react' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -144,7 +144,9 @@ describe('ExpenseDetail', () => { }) expect(await screen.findByText(t('expenses.detail.receivedBy', { name: 'Ben' }))).toBeVisible() expect(screen.getAllByText(t('expenses.refund.badge')).length).toBeGreaterThan(0) - expect(screen.getAllByText(t('expenses.detail.getsBack', { amount: '$10.00' }))).toHaveLength(2) + // Ben and Cleo get back; under "You" it reads "get back". + expect(screen.getAllByText(t('expenses.detail.getsBack', { amount: '$10.00' }))).toHaveLength(1) + expect(screen.getByText(t('expenses.detail.you.getBack', { amount: '$10.00' }))).toBeVisible() }) it('shows stored items with tax, tip and discount, and adjustments', async () => { @@ -273,11 +275,33 @@ describe('ExpenseDetail', () => { ).closest('li')! expect(ben.querySelector('[data-tone="neutral"]')).not.toBeNull() expect(within(ben).getByText(t('expenses.detail.getsBack', { amount: '$20.00' }))).toBeVisible() - // My line: my share is what I owe. - const mine = screen - .getAllByText(t('expenses.detail.owes', { amount: '$10.00' }))[0]! - .closest('li')! + // My line: my share is what I owe, and it says so in the second person. + const mine = screen.getByText(t('expenses.detail.you.owe', { amount: '$10.00' })).closest('li')! + expect(mine).toHaveTextContent(t('common.you')) expect(mine.querySelector('[data-tone="owe"]')).not.toBeNull() + expect(screen.getAllByText(t('expenses.detail.owes', { amount: '$10.00' }))).toHaveLength(1) + }) + + it('speaks to the viewer on their own row in every language', async () => { + await setLocale('de') + try { + renderDetail({ + amount_cents: 3000, + paid_by: BEN, + expense_payers: [{ user_id: BEN, paid_cents: 3000 }], + }) + // Money formats with a no-break space, which the text matcher folds away. + const text = (key: 'expenses.detail.you.owe' | 'expenses.detail.owes') => + t(key, { amount: formatMoney(1000, 'USD') }).replace(/\s/g, ' ') + const mine = (await screen.findByText(text('expenses.detail.you.owe'))).closest('li')! + expect(mine).toHaveTextContent(t('common.you')) + expect(mine).toHaveTextContent('schuldest') + const cleo = screen.getByText(text('expenses.detail.owes')).closest('li')! + expect(cleo).toHaveTextContent('Cleo') + expect(cleo).toHaveTextContent('schuldet') + } finally { + await setLocale('en') + } }) it('is read only in an archived group', async () => { diff --git a/apps/web/src/features/expenses/expenses-tab.tsx b/apps/web/src/features/expenses/expenses-tab.tsx index f01266a9..404e0b7b 100644 --- a/apps/web/src/features/expenses/expenses-tab.tsx +++ b/apps/web/src/features/expenses/expenses-tab.tsx @@ -374,6 +374,7 @@ export function ExpensesTab({ settlement={item.settlement} viewerId={me} viewerRole={myRole} + archived={archived} blockedInTab={blockedInTab} label={settlementText(item.settlement, me, nameOf)} /> diff --git a/apps/web/src/features/expenses/form/expense-form.test.tsx b/apps/web/src/features/expenses/form/expense-form.test.tsx index 47ad510e..3f3cff88 100644 --- a/apps/web/src/features/expenses/form/expense-form.test.tsx +++ b/apps/web/src/features/expenses/form/expense-form.test.tsx @@ -681,6 +681,21 @@ describe('ExpenseForm offline', () => { await waitFor(() => expect(create).toHaveBeenCalledTimes(1)) }) + it('names everyone blocked in one sentence that reads right for several', async () => { + renderWithClient( + {}} />, + seededClient((c) => + c.setQueryData(peopleKeys.blocks(ME), [ + { user_id: BEN, display_name: 'Ben Okafor', avatar_path: null, blocked_at: 'x' }, + { user_id: CLEO, display_name: 'Cleo Park', avatar_path: null, blocked_at: 'x' }, + ]), + ), + ) + const alert = await screen.findByRole('alert') + expect(alert).toHaveTextContent(t('expenses.form.youBlocked', { names: 'Ben and Cleo' })) + expect(alert).not.toHaveTextContent('you two') + }) + it('still reports a refused save as an error, not as the connection', async () => { setup() create.mockRejectedValueOnce({ message: 'payers_sum_mismatch', code: '23514' }) diff --git a/apps/web/src/features/invites/invite-links.test.tsx b/apps/web/src/features/invites/invite-links.test.tsx index feb309ac..6e360515 100644 --- a/apps/web/src/features/invites/invite-links.test.tsx +++ b/apps/web/src/features/invites/invite-links.test.tsx @@ -1,7 +1,7 @@ import type * as AuthModule from '@/lib/auth' import { t } from '@potluck/i18n' import { Toaster } from '@potluck/ui' -import { fireEvent, screen, waitFor, within } from '@testing-library/react' +import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { group, member, VIEWER } from '@/test/fixtures' import { renderWithProviders } from '@/test/render' @@ -34,6 +34,7 @@ function invite(id: string, patch: object = {}) { function renderPanel( g = group(), invites = [invite('i-1', { role: 'admin', max_uses: 5, uses: 2 })], + inSheet = false, ) { resetDb({ tables: { @@ -43,7 +44,7 @@ function renderPanel( }) return renderWithProviders( <> - + , ) @@ -144,17 +145,95 @@ describe('InvitePanel links', () => { renderPanel() await screen.findByRole('region', { name: t('invites.latest') }) fireEvent.click(screen.getByRole('button', { name: t('invites.revoke') })) - expect(await screen.findByText(t('invites.revoked'))).toBeInTheDocument() + // In the link's place: what happened, and one Undo that already has focus. + const note = await screen.findByRole('status') + expect(note).toHaveTextContent(t('invites.revoked')) expect(rowsOf('group_invites')[0]!.revoked_at).toEqual(expect.any(String)) - expect(await screen.findByText(t('invites.intro', { group: 'Hike crew' }))).toBeInTheDocument() expect(screen.queryByRole('region', { name: t('invites.latest') })).not.toBeInTheDocument() expect(screen.getByRole('button', { name: t('invites.create') })).toBeInTheDocument() + const undo = within(note).getByRole('button', { name: t('common.undo') }) + expect(undo).toHaveFocus() + expect(screen.getAllByRole('button', { name: t('common.undo') })).toHaveLength(1) - fireEvent.click(screen.getByRole('button', { name: t('common.undo') })) + fireEvent.click(undo) expect(await screen.findByRole('region', { name: t('invites.latest') })).toHaveTextContent( '/join/code-i-1-xyz', ) - expect(rowsOf('group_invites')[0]!.revoked_at).toBeNull() + expect(screen.queryByRole('status')).not.toBeInTheDocument() + await waitFor(() => expect(rowsOf('group_invites')[0]!.revoked_at).toBeNull()) + }) + + it('revokes an older link, and undo puts it back in the list', async () => { + renderPanel(group(), [invite('i-2', { created_at: '2026-11-03T00:00:00Z' }), invite('i-1')]) + await screen.findByRole('region', { name: t('invites.latest') }) + fireEvent.click( + within(olderLink('code-i-1-xyz')).getByRole('button', { + name: t('invites.revokeLink', { code: 'code-i-1-xyz' }), + }), + ) + const undo = await within(openLinks()).findByRole('button', { name: t('common.undo') }) + expect(undo).toHaveFocus() + expect(within(openLinks()).queryByText(/code-i-1-xyz/)).not.toBeInTheDocument() + // The newest link stays put. + expect(latest()).toHaveTextContent('/join/code-i-2-xyz') + + fireEvent.click(undo) + expect(await within(openLinks()).findByText(/code-i-1-xyz/)).toBeInTheDocument() + await waitFor(() => + expect(rowsOf('group_invites').find((r) => r.id === 'i-1')!.revoked_at).toBeNull(), + ) + }) + + it('keeps an Undo for each of two quick revokes, focusing the newest', async () => { + renderPanel(group(), [ + invite('i-3', { created_at: '2026-11-03T00:00:00Z' }), + invite('i-2', { created_at: '2026-11-02T00:00:00Z' }), + invite('i-1'), + ]) + await screen.findByRole('region', { name: t('invites.latest') }) + fireEvent.click(within(latest()).getByRole('button', { name: t('invites.revoke') })) + await waitFor(() => expect(latest()).toHaveTextContent('/join/code-i-2-xyz')) + fireEvent.click(within(latest()).getByRole('button', { name: t('invites.revoke') })) + await waitFor(() => expect(latest()).toHaveTextContent('/join/code-i-1-xyz')) + + await waitFor(() => + expect(screen.getAllByRole('button', { name: t('common.undo') })).toHaveLength(2), + ) + const [forI3, forI2] = screen.getAllByRole('button', { name: t('common.undo') }) + expect(forI2).toHaveFocus() + + fireEvent.click(forI3!) + await waitFor(() => expect(latest()).toHaveTextContent('/join/code-i-3-xyz')) + await waitFor(() => + expect(rowsOf('group_invites').find((r) => r.id === 'i-3')!.revoked_at).toBeNull(), + ) + expect(rowsOf('group_invites').find((r) => r.id === 'i-2')!.revoked_at).toEqual( + expect.any(String), + ) + expect(screen.getAllByRole('button', { name: t('common.undo') })).toHaveLength(1) + }) + + it('offers one toast Undo per link revoked before the sheet closed', async () => { + render() + const { router } = renderPanel( + group(), + [invite('i-2', { created_at: '2026-11-02T00:00:00Z' }), invite('i-1')], + true, + ) + await screen.findByRole('region', { name: t('invites.latest') }) + fireEvent.click(within(latest()).getByRole('button', { name: t('invites.revoke') })) + await waitFor(() => expect(latest()).toHaveTextContent('/join/code-i-1-xyz')) + fireEvent.click(within(latest()).getByRole('button', { name: t('invites.revoke') })) + await waitFor(() => expect(screen.getAllByRole('status')).toHaveLength(2)) + + await act(() => router.navigate({ to: '/home' })) + await screen.findByText('elsewhere') + const undos = await screen.findAllByRole('button', { name: t('common.undo') }) + expect(undos).toHaveLength(2) + for (const undo of undos) fireEvent.click(undo) + await waitFor(() => + expect(rowsOf('group_invites').map((r) => r.revoked_at)).toEqual([null, null]), + ) }) it('keeps the link and explains when revoking fails', async () => { diff --git a/apps/web/src/features/invites/invite-sheet.test.tsx b/apps/web/src/features/invites/invite-sheet.test.tsx index 70d990af..d292e646 100644 --- a/apps/web/src/features/invites/invite-sheet.test.tsx +++ b/apps/web/src/features/invites/invite-sheet.test.tsx @@ -1,8 +1,8 @@ import type * as ApiModule from '@potluck/api' import type * as AuthModule from '@/lib/auth' import { t } from '@potluck/i18n' -import { Toaster } from '@potluck/ui' -import { fireEvent, screen, waitFor, within } from '@testing-library/react' +import { toast, Toaster } from '@potluck/ui' +import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { encode } from 'uqr' import { beforeEach, describe, expect, it, vi } from 'vitest' import { inviteUrl } from '@/lib/app-url' @@ -54,10 +54,25 @@ vi.mock('@/lib/auth', async (importOriginal) => ({ vi.mock('./share', () => ({ shareInvite: vi.fn(async () => undefined), copyText: vi.fn() })) +const link = { + id: 'i-9', + code: 'zzzzzzzzzz99', + group_id: 'g-hike', + role: 'member' as const, + max_uses: null, + uses: 0, + expires_at: null, + email: null, + created_at: '2026-11-05T00:00:00Z', + created_by: VIEWER, + revoked_at: null, +} + describe('InvitePanel', () => { beforeEach(() => { vi.clearAllMocks() api.open = [] + toast.dismiss() }) it('puts the newest open link up front, ready to copy', async () => { @@ -84,28 +99,9 @@ describe('InvitePanel', () => { expect(screen.getByRole('button', { name: 'New link' })).toBeInTheDocument() }) - it('keeps Revoke apart from Copy, and offers Undo after revoking', async () => { - api.open = [ - { - id: 'i-9', - code: 'zzzzzzzzzz99', - group_id: 'g-hike', - role: 'member', - max_uses: null, - uses: 0, - expires_at: null, - email: null, - created_at: '2026-11-05T00:00:00Z', - created_by: VIEWER, - revoked_at: null, - }, - ] - renderWithProviders( - <> - - - , - ) + it('keeps Revoke apart from Copy, and offers Undo in its place after revoking', async () => { + api.open = [link] + renderWithProviders() const latest = await screen.findByRole('region', { name: 'Your link' }) const copy = within(latest).getByRole('button', { name: 'Copy link' }) const revoke = within(latest).getByRole('button', { name: t('invites.revoke') }) @@ -113,11 +109,92 @@ describe('InvitePanel', () => { expect(copy.parentElement).not.toBe(revoke.parentElement) fireEvent.click(revoke) await waitFor(() => expect(api.revokeInvite).toHaveBeenCalledTimes(1)) + // Undo is in the panel itself (a sheet blocks the toast), with focus on it. + const note = await screen.findByRole('status') + expect(note).toHaveTextContent(t('invites.revoked')) + const undo = within(note).getByRole('button', { name: t('common.undo') }) + expect(undo).toHaveFocus() + fireEvent.click(undo) + await waitFor(() => expect(api.restoreInvite).toHaveBeenCalledTimes(1)) + expect(api.restoreInvite.mock.calls[0]).toEqual([expect.anything(), 'i-9']) + expect(screen.queryByRole('status')).not.toBeInTheDocument() + }) + + it('offers Undo in a toast once the sheet is gone', async () => { + api.open = [link] + render() + const { router } = renderWithProviders() + const latest = await screen.findByRole('region', { name: 'Your link' }) + fireEvent.click(within(latest).getByRole('button', { name: t('invites.revoke') })) + await screen.findByRole('status') + // One Undo while the panel is open: no toast behind a sheet. + expect(screen.getAllByRole('button', { name: t('common.undo') })).toHaveLength(1) + + await act(() => router.navigate({ to: '/home' })) + await screen.findByText('elsewhere') + fireEvent.click(await screen.findByRole('button', { name: t('common.undo') })) + await waitFor(() => expect(api.restoreInvite).toHaveBeenCalledTimes(1)) + expect(api.restoreInvite.mock.calls[0]).toEqual([expect.anything(), 'i-9']) + }) + + it('offers Undo in a toast when the revoke lands after the sheet closed', async () => { + api.open = [link] + let land = () => {} + api.revokeInvite.mockImplementationOnce( + () => new Promise((resolve) => (land = () => resolve(undefined))), + ) + render() + const { router } = renderWithProviders() + const latest = await screen.findByRole('region', { name: 'Your link' }) + fireEvent.click(within(latest).getByRole('button', { name: t('invites.revoke') })) + await waitFor(() => expect(api.revokeInvite).toHaveBeenCalledTimes(1)) + + await act(() => router.navigate({ to: '/home' })) + await screen.findByText('elsewhere') + await act(async () => {}) + expect(screen.queryByRole('button', { name: t('common.undo') })).not.toBeInTheDocument() + await act(async () => land()) fireEvent.click(await screen.findByRole('button', { name: t('common.undo') })) await waitFor(() => expect(api.restoreInvite).toHaveBeenCalledTimes(1)) expect(api.restoreInvite.mock.calls[0]).toEqual([expect.anything(), 'i-9']) }) + it('on a page, keeps Undo to the note, which goes after a few seconds', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }) + try { + api.open = [link] + render() + const { router } = renderWithProviders() + const latest = await screen.findByRole('region', { name: 'Your link' }) + fireEvent.click(within(latest).getByRole('button', { name: t('invites.revoke') })) + await screen.findByRole('status') + act(() => vi.advanceTimersByTime(8000)) + await waitFor(() => + expect(screen.queryByRole('button', { name: t('common.undo') })).not.toBeInTheDocument(), + ) + + await act(() => router.navigate({ to: '/home' })) + await screen.findByText('elsewhere') + expect(screen.queryByRole('button', { name: t('common.undo') })).not.toBeInTheDocument() + } finally { + vi.useRealTimers() + } + }) + + it('on a page, raises no toast when the panel goes while the note is up', async () => { + api.open = [link] + render() + const { router } = renderWithProviders() + const latest = await screen.findByRole('region', { name: 'Your link' }) + fireEvent.click(within(latest).getByRole('button', { name: t('invites.revoke') })) + await screen.findByRole('status') + + await act(() => router.navigate({ to: '/home' })) + await screen.findByText('elsewhere') + await act(async () => {}) + expect(screen.queryByRole('button', { name: t('common.undo') })).not.toBeInTheDocument() + }) + it('creates a member link in one tap, with sensible defaults', async () => { renderWithProviders() expect(await screen.findByText('Member link: anyone, expires in 7 days.')).toBeInTheDocument() diff --git a/apps/web/src/features/invites/invite-sheet.tsx b/apps/web/src/features/invites/invite-sheet.tsx index 05d0850e..d14a50d3 100644 --- a/apps/web/src/features/invites/invite-sheet.tsx +++ b/apps/web/src/features/invites/invite-sheet.tsx @@ -20,8 +20,8 @@ import { toast, } from '@potluck/ui' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' -import { Check, ChevronDown, Copy, Link2, QrCode, Share2, X } from 'lucide-react' -import { useState } from 'react' +import { Check, ChevronDown, Copy, Link2, QrCode, Share2, Undo2, X } from 'lucide-react' +import { useEffect, useRef, useState } from 'react' import { Help } from '@/features/help/help' import { inviteUrl } from '@/lib/app-url' import { errorMessage } from '@/lib/errors' @@ -34,6 +34,8 @@ type UsesChoice = '1' | '5' | '25' | 'unlimited' type ExpiryChoice = '1' | '7' | '30' | 'never' const DAY = 24 * 60 * 60 * 1000 +/** How long a revoked link can be brought back from the note or the toast. */ +const UNDO_MS = 8000 function inviteMeta(invite: GroupInviteRow, timeZone: string): string { return [ @@ -117,14 +119,28 @@ function InviteRow({ ) } +/** A revoked link that can still be brought back, until `until` (ms since epoch). */ +type Revoked = { invite: GroupInviteRow; wasLatest: boolean; until: number } + +/** A toast that brings back a revoked link, for when the panel is not there to offer it. */ +function offerUndo(onUndo: () => void) { + toast(t('invites.revoked'), { + duration: UNDO_MS, + action: { label: t('common.undo'), onClick: onUndo }, + }) +} + /** Create, share and revoke invite links for one group. */ export function InvitePanel({ group, intro = true, + inSheet = false, }: { group: GroupDetail /** Show the one-line explainer before the first link exists. Off when the host page has its own. */ intro?: boolean + /** Hosted in a sheet: a link revoked just before it closes is offered back in a toast. */ + inSheet?: boolean }) { const queryClient = useQueryClient() const invites = useQuery(groupInvitesQueryOptions(supabase, group.id)) @@ -160,6 +176,61 @@ export function InvitePanel({ onError: (error) => toast.error(errorMessage(error)), }) + // Each revoked link, offered back right where it was for a few seconds. A sheet blocks taps + // and focus outside it, so a toast's Undo would only close the sheet; in a sheet the toasts + // wait for it to close instead. A reply that lands after the panel is gone goes straight to + // a toast. + const [undoable, setUndoable] = useState([]) + const undoableRef = useRef(undoable) + useEffect(() => { + undoableRef.current = undoable + }, [undoable]) + useEffect(() => { + const first = undoable[0] + if (!first) return + const timer = window.setTimeout( + () => setUndoable((list) => list.filter((u) => u !== first)), + first.until - Date.now(), + ) + return () => window.clearTimeout(timer) + }, [undoable]) + + const restore = async (invite: GroupInviteRow) => { + try { + await restoreInvite(supabase, invite.id) + } catch (error) { + toast.error(errorMessage(error)) + } + void queryClient.invalidateQueries({ queryKey: key }) + } + const restoreRef = useRef(restore) + useEffect(() => { + restoreRef.current = restore + }) + + const mounted = useRef(false) + useEffect(() => { + mounted.current = true + return () => { + mounted.current = false + if (!inSheet) return + for (const { invite } of undoableRef.current) { + offerUndo(() => void restoreRef.current(invite)) + } + } + }, [inSheet]) + + const undo = (invite: GroupInviteRow) => { + setUndoable((list) => list.filter((u) => u.invite.id !== invite.id)) + // Back in its place at once (newest first, as the list is read); the refetch confirms it. + queryClient.setQueryData(key, (rows) => + [...(rows ?? []).filter((r) => r.id !== invite.id), invite].sort((a, b) => + b.created_at.localeCompare(a.created_at), + ), + ) + void restore(invite) + } + const revoke = useMutation({ mutationFn: (invite: GroupInviteRow) => revokeInvite(supabase, invite.id), onMutate: async (invite) => { @@ -168,27 +239,17 @@ export function InvitePanel({ queryClient.setQueryData(key, (rows) => rows?.filter((r) => r.id !== invite.id), ) - return { previous } + return { previous, wasLatest: previous?.[0]?.id === invite.id } }, onError: (error, _invite, context) => { if (context?.previous) queryClient.setQueryData(key, context.previous) toast.error(errorMessage(error)) }, - onSuccess: (_data, invite) => { - toast(t('invites.revoked'), { - duration: 8000, - action: { - label: t('common.undo'), - onClick: async () => { - try { - await restoreInvite(supabase, invite.id) - } catch (error) { - toast.error(errorMessage(error)) - } - void queryClient.invalidateQueries({ queryKey: key }) - }, - }, - }) + onSuccess: (_data, invite, context) => { + if (mounted.current) { + const until = Date.now() + UNDO_MS + setUndoable((list) => [...list, { invite, wasLatest: context.wasLatest, until }]) + } else offerUndo(() => void restoreRef.current(invite)) }, }) @@ -215,9 +276,19 @@ export function InvitePanel({ : t('invites.summary.expires', { count: Number(expiry) }), }) const settingsId = `invite-settings-${group.id}` + const byNewest = (a: { invite: GroupInviteRow }, b: { invite: GroupInviteRow }) => + b.invite.created_at.localeCompare(a.invite.created_at) + const revokedLatest = undoable.filter((u) => u.wasLatest).sort(byNewest) + const olderSlots = [ + ...others.map((invite) => ({ invite, revoked: false })), + ...undoable.filter((u) => !u.wasLatest).map(({ invite }) => ({ invite, revoked: true })), + ].sort(byNewest) return (
    + {revokedLatest.map(({ invite }) => ( + undo(invite)} /> + ))} {invites.isPending ? ( ) : latest ? ( @@ -227,7 +298,7 @@ export function InvitePanel({ groupName={group.name} onRevoke={() => revoke.mutate(latest)} /> - ) : intro ? ( + ) : intro && undoable.length === 0 ? (

    {t('invites.intro', { group: group.name })}

    ) : null} @@ -314,21 +385,27 @@ export function InvitePanel({
    - {others.length > 0 && ( + {olderSlots.length > 0 && (

    {t('invites.active')}

      - {others.map((invite) => ( - revoke.mutate(invite)} - /> - ))} + {olderSlots.map(({ invite, revoked }) => + revoked ? ( +
    • + undo(invite)} /> +
    • + ) : ( + revoke.mutate(invite)} + /> + ), + )}
    )} @@ -336,6 +413,33 @@ export function InvitePanel({ ) } +/** + * Where a link was just revoked: one tap, or Enter, brings it back. The Revoke button went away + * with its link, so focus lands here and a keyboard user can undo straight away. + */ +function RevokedNote({ onUndo }: { onUndo: () => void }) { + const button = useRef(null) + useEffect(() => button.current?.focus(), []) + return ( +
    +

    {t('invites.revoked')}

    + +
    + ) +} + /** The newest open link, front and center: the thing people came here to copy. */ function LatestLink({ invite, @@ -397,7 +501,7 @@ function LatestLink({ {/* Revoking sits on its own, below a rule and away from Copy, so a slip never closes - the link; it also leaves an Undo in the toast. */} + the link; it also leaves an Undo in its place. */}