feat(packing): change the sharing of a whole list at once (#2961)

The list menu on desktop and phone gets "Sharing for Whole List": pick
Shared, Personal or Shared with people once and every item of yours in
that list moves there through the existing per-item sharing write. Items
other people added stay as they are, and the dialog says so up front.
This commit is contained in:
Maurice
2026-11-13 09:29:55 +01:00
parent 3f68c8a50e
commit 308daec14e
43 changed files with 1126 additions and 10 deletions
@@ -0,0 +1,78 @@
// FE-PACK-CATSHAREDLG-001 to FE-PACK-CATSHAREDLG-004: the desktop dialog for sharing a whole packing list (#2961).
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import PackingCategorySharingDialog from './PackingCategorySharingDialog';
import type { PackingCategorySharing } from './usePackingCategorySharing';
import type { TripMember } from './usePackingListPanel';
const ME = 1;
const MEMBERS: TripMember[] = [
{ id: ME, username: 'me' },
{ id: 2, username: 'alice' },
];
function sharing(overrides: Partial<PackingCategorySharing> = {}): PackingCategorySharing {
return {
category: 'Camp',
visibility: null,
setVisibility: vi.fn(),
recipientIds: [],
toggleRecipient: vi.fn(),
ownCount: 2,
othersCount: 0,
busy: false,
ready: false,
openFor: vi.fn(),
close: vi.fn(),
apply: vi.fn(() => Promise.resolve()),
...overrides,
};
}
function setup(state: PackingCategorySharing) {
render(<PackingCategorySharingDialog sharing={state} tripMembers={MEMBERS} currentUserId={ME} />);
return state;
}
describe('PackingCategorySharingDialog', () => {
it('FE-PACK-CATSHAREDLG-001: renders nothing until a list is chosen', () => {
setup(sharing({ category: null }));
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-PACK-CATSHAREDLG-002: names the list, offers the three tiers and marks the chosen one', () => {
const state = setup(sharing({ visibility: 'common' }));
expect(screen.getByText('Camp')).toBeInTheDocument();
expect(screen.getByText('Sharing for Whole List')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /In the group pool/ })).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(screen.getByRole('button', { name: /Private/ }));
expect(state.setVisibility).toHaveBeenCalledWith('personal');
// Apply waits until the choice is complete.
expect(screen.getByRole('button', { name: 'Apply to list' })).toBeDisabled();
});
it('FE-PACK-CATSHAREDLG-003: the third tier lists the other members to pick, and applies once ready', () => {
const state = setup(sharing({ visibility: 'shared', recipientIds: [2], ready: true, othersCount: 1 }));
expect(screen.queryByRole('button', { name: 'me' })).toBeNull();
const alice = screen.getByRole('button', { name: 'alice' });
expect(alice).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(alice);
expect(state.toggleRecipient).toHaveBeenCalledWith(2);
expect(
screen.getByText('Items other people added stay as they are. Only they can change them.')
).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Apply to list' }));
expect(state.apply).toHaveBeenCalledOnce();
});
it('FE-PACK-CATSHAREDLG-004: a list of nobody but others explains why and leaves the tiers shut', () => {
setup(sharing({ ownCount: 0, othersCount: 2 }));
expect(
screen.getByText('Every item in this list was added by someone else, so only they can change its sharing.')
).toBeInTheDocument();
expect(screen.getByRole('button', { name: /In the group pool/ })).toBeDisabled();
});
});
@@ -0,0 +1,155 @@
import type { PackingVisibility } from '@trek/shared';
import { Check, Loader2, Share2, UserRound, Users } from 'lucide-react';
import { type ReactNode, useId } from 'react';
import { useTranslation } from '../../i18n';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogShell,
DialogTile,
FooterSpacer,
NEUTRAL_TINT,
fs,
} from '../shared/DialogShell';
import type { PackingCategorySharing } from './usePackingCategorySharing';
import type { TripMember } from './usePackingListPanel';
/**
* The desktop's choice of one sharing tier for a whole packing list (#2961): the
* same three tiers as an item's own sharing control, the people to share with
* under the third, and a note on the items that belong to someone else.
*/
export default function PackingCategorySharingDialog({
sharing,
tripMembers,
currentUserId,
}: {
sharing: PackingCategorySharing;
tripMembers: TripMember[];
currentUserId: number | null | undefined;
}) {
const { t } = useTranslation();
const labelId = useId();
const { category, visibility, recipientIds, ownCount, othersCount, busy, ready } = sharing;
const others = tripMembers.filter((m) => m.id !== currentUserId);
const needsPeople = visibility === 'shared' && others.length > 0 && recipientIds.length === 0;
const tier = (value: PackingVisibility, icon: ReactNode, label: string, hint?: string) => {
const on = visibility === value;
return (
<button
type="button"
aria-pressed={on}
disabled={ownCount === 0}
onClick={() => sharing.setVisibility(value)}
className={`flex min-h-[44px] items-center gap-3 rounded-[10px] px-3 py-2 text-start disabled:opacity-50 ${on ? 'bg-surface-card shadow-sm' : 'enabled:hover:bg-surface-card'}`}
>
<span className={`flex-none ${on ? 'text-content' : 'text-content-muted'}`}>{icon}</span>
<span className="min-w-0 flex-1">
<span className="block font-semibold text-content" style={fs(13, 'body')}>
{label}
</span>
{hint && (
<span className="block text-content-faint" style={fs(11.5)}>
{hint}
</span>
)}
</span>
{on && <Check size={14} className="flex-none text-content-muted" />}
</button>
);
};
return (
<DialogShell
open={category != null}
onClose={sharing.close}
labelledBy={labelId}
width="narrow"
header={
<DialogHeader
tile={
<DialogTile>
<Share2 size={20} strokeWidth={1.9} className="text-content-muted" />
</DialogTile>
}
tint={NEUTRAL_TINT}
labelId={labelId}
onClose={sharing.close}
eyebrow={t('packing.menuShareCat')}
title={category}
/>
}
footer={
<DialogFooter>
<FooterSpacer />
<DialogButton onClick={sharing.close} disabled={busy}>
{t('common.cancel')}
</DialogButton>
<DialogButton
variant="primary"
onClick={() => void sharing.apply()}
disabled={!ready}
icon={busy ? <Loader2 size={14} className="animate-spin" /> : undefined}
>
{t('packing.shareCat.apply')}
</DialogButton>
</DialogFooter>
}
>
<p className="m-0 text-content-muted" style={fs(12.5, 'body')}>
{ownCount === 0 ? t('packing.shareCat.noneOwn') : t('packing.shareCat.hint')}
</p>
<div className="flex flex-col gap-0.5 rounded-[14px] border border-edge-faint bg-surface-secondary p-1.5">
{tier('common', <Users size={15} />, t('packing.viewCommon'), t('packing.tierCommonHint'))}
{tier('personal', <UserRound size={15} />, t('packing.tierPersonal'), t('packing.tierPersonalHint'))}
{tier('shared', <Share2 size={15} />, t('packing.tierShared'))}
{visibility === 'shared' && (
<div className="flex flex-col gap-0.5 ps-6">
{others.length === 0 ? (
<p className="m-0 px-3 py-2 text-content-faint" style={fs(12, 'body')}>
{t('packing.noOneToShare')}
</p>
) : (
others.map((m) => {
const picked = recipientIds.includes(m.id);
return (
<button
key={m.id}
type="button"
aria-pressed={picked}
onClick={() => sharing.toggleRecipient(m.id)}
className="flex min-h-[40px] items-center gap-3 rounded-[10px] px-3 py-1.5 text-start hover:bg-surface-card"
>
<span className="min-w-0 flex-1 truncate text-content" style={fs(13, 'body')}>
{m.username}
</span>
<span
className={`grid h-6 w-6 flex-none place-items-center rounded-[8px] ${picked ? 'bg-accent text-accent-text' : 'border border-edge bg-surface-card text-transparent'}`}
>
<Check size={13} />
</span>
</button>
);
})
)}
</div>
)}
</div>
{needsPeople && (
<p className="m-0 text-content-faint" style={fs(12, 'body')}>
{t('packing.shareCat.pickPeople')}
</p>
)}
{ownCount > 0 && othersCount > 0 && (
<p className="m-0 text-content-faint" style={fs(12, 'body')}>
{t('packing.shareCat.othersKept')}
</p>
)}
</DialogShell>
);
}
@@ -6,13 +6,14 @@ import { PackingList } from './PackingListPanelList'
import { BagSidebar } from './PackingListPanelBagSidebar'
import { BagModal } from './PackingListPanelBagModal'
import { BulkImportModal } from './PackingListPanelImportModal'
import PackingCategorySharingDialog from './PackingCategorySharingDialog'
// Re-exported for tests and external callers that import it from this module.
export { itemWeight } from './packingListPanel.helpers'
export default function PackingListPanel(props: PackingListPanelProps) {
const S = usePackingList(props)
const { font, bagTrackingEnabled, bags, showBagModal, showImportModal } = S
const { font, bagTrackingEnabled, bags, showBagModal, showImportModal, categorySharing, tripMembers, currentUserId } = S
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', ...font }}>
{/* ── Header ── */}
@@ -37,6 +38,8 @@ export default function PackingListPanel(props: PackingListPanelProps) {
{/* Bulk Import Modal */}
{showImportModal && <BulkImportModal {...S} />}
<PackingCategorySharingDialog sharing={categorySharing} tripMembers={tripMembers} currentUserId={currentUserId} />
</div>
)
}
@@ -1,4 +1,4 @@
// FE-W5CAT-001 to FE-W5CAT-040
// FE-W5CAT-001 to FE-W5CAT-042
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import type { ComponentProps } from 'react'
import { http, HttpResponse } from 'msw'
@@ -646,3 +646,23 @@ describe('KategorieGruppe — plugin contributions', () => {
expect(screen.getByText('Forecast')).toBeInTheDocument()
})
})
describe('KategorieGruppe — sharing the whole list (#2961)', () => {
it('FE-W5CAT-041: the list menu offers the sharing of the whole list and closes on it', () => {
const onShareCategory = vi.fn()
const { container } = setup({ onShareCategory })
openCategoryMenu(container)
fireEvent.click(screen.getByText('Sharing for Whole List'))
expect(onShareCategory).toHaveBeenCalledOnce()
expect(screen.queryByText('Sharing for Whole List')).toBeNull()
})
it('FE-W5CAT-042: a read-only member gets no such entry', () => {
const { container } = setup({ onShareCategory: vi.fn(), canEdit: false })
openCategoryMenu(container)
expect(screen.getByText('Uncheck All')).toBeInTheDocument()
expect(screen.queryByText('Sharing for Whole List')).toBeNull()
})
})
@@ -4,7 +4,7 @@ import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import {
Trash2, Plus, ChevronDown, ChevronRight,
X, Pencil, Check, MoreHorizontal, CheckCheck, RotateCcw, UserPlus, GripVertical,
X, Pencil, Check, MoreHorizontal, CheckCheck, RotateCcw, UserPlus, GripVertical, Share2,
} from 'lucide-react'
import type { PackingItem, PackingBag } from '../../types'
import { katColor } from './packingListPanel.helpers'
@@ -54,9 +54,11 @@ interface KategorieGruppeProps {
onClone?: (id: number) => void
onJoin?: (id: number) => void
onLeave?: (id: number, userId: number) => void
// Opens the choice of one sharing tier for the whole list (#2961).
onShareCategory?: () => void
}
export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRename, onDeleteAll, onDeleteItem, onAddItem, assignees, tripMembers, onSetAssignees, bagTrackingEnabled, bags, onCreateBag, canEdit = true, allItems, onReorder, reorderable = true, categoryDrag, currentUserId, onSetSharing, onClone, onJoin, onLeave }: KategorieGruppeProps) {
export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRename, onDeleteAll, onDeleteItem, onAddItem, assignees, tripMembers, onSetAssignees, bagTrackingEnabled, bags, onCreateBag, canEdit = true, allItems, onReorder, reorderable = true, categoryDrag, currentUserId, onSetSharing, onClone, onJoin, onLeave, onShareCategory }: KategorieGruppeProps) {
const [offen, setOffen] = useState(true)
const [dragId, setDragId] = useState<number | null>(null)
const [overId, setOverId] = useState<number | null>(null)
@@ -272,6 +274,7 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
{canEdit && <PopoverItem icon={<Pencil size={13} />} label={t('packing.menuRename')} onClick={() => { setEditingName(true); setShowMenu(false) }} />}
<PopoverItem icon={<CheckCheck size={13} />} label={t('packing.menuCheckAll')} onClick={() => { void handleCheckAll(); setShowMenu(false) }} />
<PopoverItem icon={<RotateCcw size={13} />} label={t('packing.menuUncheckAll')} onClick={() => { void handleUncheckAll(); setShowMenu(false) }} />
{canEdit && onShareCategory && <PopoverItem icon={<Share2 size={13} />} label={t('packing.menuShareCat')} onClick={() => { onShareCategory(); setShowMenu(false) }} />}
{canEdit && <>
<div style={POPOVER_DIVIDER} />
<PopoverItem icon={<Trash2 size={13} />} label={t('packing.menuDeleteCat')} danger onClick={handleDeleteAll} />
@@ -8,7 +8,7 @@ export function PackingList(S: PackingState) {
items, gruppiert, t, tripId, allCategories, handleRenameCategory, handleDeleteCategory, handleDeleteItem,
handleAddItemToCategory, categoryAssignees, tripMembers, handleSetAssignees,
bagTrackingEnabled, bags, handleCreateBagByName, canEdit, reorderPackingItems,
currentUserId, handleSetSharing, handleCloneItem, handleJoinItem, handleLeaveItem, sort, moveCategory,
currentUserId, handleSetSharing, handleCloneItem, handleJoinItem, handleLeaveItem, categorySharing, sort, moveCategory,
} = S
// Which category is being dragged and which card it is over. Held here, above
// the cards, because the drag starts in one card and ends in another.
@@ -59,6 +59,7 @@ export function PackingList(S: PackingState) {
onClone={handleCloneItem}
onJoin={handleJoinItem}
onLeave={handleLeaveItem}
onShareCategory={() => categorySharing.openFor(kat)}
/>
))}
</div>
@@ -2,12 +2,16 @@ import { describe, expect, it } from 'vitest';
import { buildPackingItem } from '../../../tests/helpers/factories';
import {
agreedSharing,
categorySharingSplit,
formatWeight,
groupPackingItems,
isLastCustomItemInCategory,
isPackingPlaceholder,
itemOrderWithCategoryMoved,
itemsToReshare,
packingCategoryOrder,
packingItemSharing,
packingItemWeight,
packingProgress,
packingStatusFiltered,
@@ -15,7 +19,7 @@ import {
} from './packingListModel';
import { PACKING_PLACEHOLDER_NAME } from './packingListPanel.constants';
// FE-PACK-MODEL-001 to FE-PACK-MODEL-009
// FE-PACK-MODEL-001 to FE-PACK-MODEL-013
const shared = buildPackingItem({ id: 1, name: 'Tent', category: 'Camp', checked: 1 });
const mine = buildPackingItem({ id: 2, name: 'Socks', category: 'Clothes', is_private: 1 });
@@ -102,3 +106,46 @@ describe('packingListModel', () => {
expect(itemOrderWithCategoryMoved(items, items, 'Other', 'Camp', 'Other')).toEqual([4, 1, 3]);
});
});
describe('packingListModel: sharing a whole list (#2961)', () => {
const recipients = (...ids: number[]) => ids.map((user_id) => ({ user_id, username: `u${user_id}` }));
const common = buildPackingItem({ id: 10, category: 'Camp', owner_id: 1 });
const personal = buildPackingItem({ id: 11, category: 'Camp', is_private: 1, owner_id: 1 });
const sharedTwo = buildPackingItem({
id: 12,
category: 'Camp',
is_private: 1,
owner_id: 1,
recipients: recipients(3, 2),
});
const legacy = buildPackingItem({ id: 13, category: 'Camp', owner_id: null });
const theirs = buildPackingItem({ id: 14, category: 'Camp', owner_id: 2 });
it('FE-PACK-MODEL-010: an item reads as common, personal or shared with its people in order', () => {
expect(packingItemSharing(common)).toEqual({ visibility: 'common', recipientIds: [] });
expect(packingItemSharing(personal)).toEqual({ visibility: 'personal', recipientIds: [] });
expect(packingItemSharing(sharedTwo)).toEqual({ visibility: 'shared', recipientIds: [2, 3] });
});
it('FE-PACK-MODEL-011: my items and unowned ones can be moved, the ones of others are only counted', () => {
const split = categorySharingSplit([common, legacy, theirs, personal], 1);
expect(split.own.map((i) => i.id)).toEqual([10, 13, 11]);
expect(split.othersCount).toBe(1);
expect(categorySharingSplit([theirs], 1)).toEqual({ own: [], othersCount: 1 });
});
it('FE-PACK-MODEL-012: the tier the items agree on, or none when they differ', () => {
expect(agreedSharing([common, legacy])).toEqual({ visibility: 'common', recipientIds: [] });
const sameTwo = buildPackingItem({ category: 'Camp', is_private: 1, owner_id: 1, recipients: recipients(2, 3) });
expect(agreedSharing([sharedTwo, sameTwo])).toEqual({ visibility: 'shared', recipientIds: [2, 3] });
expect(agreedSharing([common, personal])).toBeNull();
expect(agreedSharing([])).toBeNull();
});
it('FE-PACK-MODEL-013: only the items not yet at the target tier need a write', () => {
const items = [common, personal, sharedTwo];
expect(itemsToReshare(items, { visibility: 'personal', recipientIds: [] }).map((i) => i.id)).toEqual([10, 12]);
expect(itemsToReshare(items, { visibility: 'shared', recipientIds: [3, 2] }).map((i) => i.id)).toEqual([10, 11]);
expect(itemsToReshare(items, { visibility: 'common', recipientIds: [] }).map((i) => i.id)).toEqual([11, 12]);
});
});
@@ -1,3 +1,5 @@
import type { PackingVisibility } from '@trek/shared';
import type { PackingItem } from '../../types';
import { PACKING_PLACEHOLDER_NAME } from './packingListPanel.constants';
@@ -124,3 +126,48 @@ export function isLastCustomItemInCategory(item: PackingItem, allItems: PackingI
export function isPackingPlaceholder(item: Pick<PackingItem, 'name'>): boolean {
return item.name === PACKING_PLACEHOLDER_NAME;
}
/** An item's sharing tier and, for the Shared-with tier, who it is shared with (#858). */
export interface PackingSharing {
visibility: PackingVisibility;
recipientIds: number[];
}
/** The tier an item stands at, read the way the per-item sharing controls read it. */
export function packingItemSharing(item: PackingItem): PackingSharing {
const recipientIds = (item.recipients || []).map((r) => r.user_id).sort((a, b) => a - b);
if (!item.is_private) return { visibility: 'common', recipientIds: [] };
return { visibility: recipientIds.length > 0 ? 'shared' : 'personal', recipientIds };
}
function sameSharing(a: PackingSharing, b: PackingSharing): boolean {
return a.visibility === b.visibility && a.recipientIds.join(',') === b.recipientIds.join(',');
}
/**
* A list's items split for moving the whole list to one tier (#2961). Only an
* item's owner may change its sharing, and an item nobody owns yet is claimed by
* whoever changes it, as with a single item; the rest stay as they are and are
* counted so the user can be told. The placeholder of an empty list is one of
* its items, so the list moves along with it.
*/
export function categorySharingSplit(
categoryItems: PackingItem[],
userId: number | null | undefined
): { own: PackingItem[]; othersCount: number } {
const own = categoryItems.filter((i) => i.owner_id == null || i.owner_id === userId);
return { own, othersCount: categoryItems.length - own.length };
}
/** The tier all of these items already agree on, or null when they differ or there are none. */
export function agreedSharing(items: PackingItem[]): PackingSharing | null {
if (items.length === 0) return null;
const first = packingItemSharing(items[0]);
return items.every((i) => sameSharing(packingItemSharing(i), first)) ? first : null;
}
/** The items that a move to `target` would actually change; those already there need no write. */
export function itemsToReshare(items: PackingItem[], target: PackingSharing): PackingItem[] {
const wanted = { ...target, recipientIds: [...target.recipientIds].sort((a, b) => a - b) };
return items.filter((i) => !sameSharing(packingItemSharing(i), wanted));
}
@@ -0,0 +1,140 @@
// FE-PACK-CATSHARE-001 to FE-PACK-CATSHARE-006: moving a whole packing list to one sharing tier (#2961).
import { act, renderHook } from '@testing-library/react';
import { type Mock, describe, expect, it, vi } from 'vitest';
import { buildPackingItem } from '../../../tests/helpers/factories';
import type { TripStoreState } from '../../store/tripStore';
import type { PackingItem } from '../../types';
import { usePackingCategorySharing } from './usePackingCategorySharing';
type Share = TripStoreState['setPackingItemSharing'];
const ME = 1;
const recipients = (...ids: number[]) => ids.map((user_id) => ({ user_id, username: `u${user_id}` }));
const tent = buildPackingItem({ id: 1, name: 'Tent', category: 'Camp', owner_id: ME });
const stove = buildPackingItem({ id: 2, name: 'Stove', category: 'Camp', owner_id: null, checked: 1 });
const theirs = buildPackingItem({ id: 3, name: 'Lamp', category: 'Camp', owner_id: 2 });
const socks = buildPackingItem({ id: 4, name: 'Socks', category: 'Clothes', owner_id: ME });
const diary = buildPackingItem({ id: 5, name: 'Diary', category: 'Camp', owner_id: ME, is_private: 1 });
function setup(items: PackingItem[], setPackingItemSharing: Mock<Share> = vi.fn<Share>(() => Promise.resolve())) {
const toast = { success: vi.fn() };
const t = vi.fn((key: string) => key);
const hook = renderHook(() =>
usePackingCategorySharing({
tripId: 7,
items,
view: 'common',
defaultCategory: 'Other',
currentUserId: ME,
setPackingItemSharing,
t,
toast,
})
);
return { ...hook, setPackingItemSharing, toast, t };
}
describe('usePackingCategorySharing', () => {
it('FE-PACK-CATSHARE-001: opens on the list of the open view, ticked items included, and counts the items of others', () => {
const { result } = setup([tent, stove, theirs, socks, diary]);
expect(result.current.category).toBeNull();
act(() => result.current.openFor('Camp'));
expect(result.current.category).toBe('Camp');
// The personal Diary is in the other view, Socks in another list.
expect(result.current.ownCount).toBe(2);
expect(result.current.othersCount).toBe(1);
// Tent and Stove both sit on the common list, so that tier is preselected.
expect(result.current.visibility).toBe('common');
expect(result.current.ready).toBe(true);
});
it('FE-PACK-CATSHARE-002: moving to my list writes each own item once, in order, and reports the items left alone', async () => {
const { result, setPackingItemSharing, toast, t } = setup([tent, stove, theirs]);
act(() => result.current.openFor('Camp'));
act(() => result.current.setVisibility('personal'));
await act(() => result.current.apply());
expect(setPackingItemSharing.mock.calls).toEqual([
[7, 1, 'personal', []],
[7, 2, 'personal', []],
]);
expect(t).toHaveBeenCalledWith('packing.shareCat.doneOthersKept', { name: 'Camp' });
expect(toast.success).toHaveBeenCalledWith('packing.shareCat.doneOthersKept');
expect(result.current.category).toBeNull();
});
it('FE-PACK-CATSHARE-003: sharing with people needs at least one of them, and sends who was picked', async () => {
const { result, setPackingItemSharing, toast } = setup([tent]);
act(() => result.current.openFor('Camp'));
act(() => result.current.setVisibility('shared'));
expect(result.current.ready).toBe(false);
act(() => result.current.toggleRecipient(3));
act(() => result.current.toggleRecipient(2));
act(() => result.current.toggleRecipient(3));
expect(result.current.recipientIds).toEqual([2]);
expect(result.current.ready).toBe(true);
await act(() => result.current.apply());
expect(setPackingItemSharing).toHaveBeenCalledWith(7, 1, 'shared', [2]);
expect(toast.success).toHaveBeenCalledWith('packing.shareCat.done');
});
it('FE-PACK-CATSHARE-004: items already at the tier are not written again, and a list that agrees on people starts there', async () => {
const kettle = buildPackingItem({
id: 6,
category: 'Food',
owner_id: ME,
is_private: 1,
recipients: recipients(3, 2),
});
const pans = buildPackingItem({
id: 7,
category: 'Food',
owner_id: ME,
is_private: 1,
recipients: recipients(2, 3),
});
const { result, setPackingItemSharing, toast } = setup([kettle, pans]);
act(() => result.current.openFor('Food'));
expect(result.current.visibility).toBe('shared');
expect(result.current.recipientIds).toEqual([2, 3]);
await act(() => result.current.apply());
expect(setPackingItemSharing).not.toHaveBeenCalled();
expect(toast.success).not.toHaveBeenCalled();
expect(result.current.category).toBeNull();
});
it('FE-PACK-CATSHARE-005: a failed write stops the run and keeps the choice open, without a second message', async () => {
const failing = vi.fn<Share>(() => Promise.reject(new Error('offline')));
const { result, toast } = setup([tent, stove], failing);
act(() => result.current.openFor('Camp'));
act(() => result.current.setVisibility('personal'));
await act(() => result.current.apply());
expect(failing).toHaveBeenCalledOnce();
expect(toast.success).not.toHaveBeenCalled();
expect(result.current.category).toBe('Camp');
expect(result.current.busy).toBe(false);
});
it('FE-PACK-CATSHARE-006: a list of nobody but others cannot be applied, and closing clears the choice', async () => {
const { result, setPackingItemSharing } = setup([theirs]);
act(() => result.current.openFor('Camp'));
act(() => result.current.setVisibility('personal'));
expect(result.current.ownCount).toBe(0);
expect(result.current.ready).toBe(false);
await act(() => result.current.apply());
expect(setPackingItemSharing).not.toHaveBeenCalled();
act(() => result.current.close());
expect(result.current.category).toBeNull();
});
});
@@ -0,0 +1,128 @@
import type { PackingVisibility } from '@trek/shared';
import { useState } from 'react';
import type { TripStoreState } from '../../store/tripStore';
import type { PackingItem } from '../../types';
import {
type PackingSharing,
type PackingView,
agreedSharing,
categorySharingSplit,
itemsToReshare,
packingViewItems,
} from './packingListModel';
/** A list's items in the open view, ticked or not. */
const listItems = (items: PackingItem[], view: PackingView, category: string, defaultCategory: string) =>
packingViewItems(items, view).filter((i) => (i.category || defaultCategory) === category);
type Translate = (key: string, params?: Record<string, string | number>) => string;
interface Toaster {
success: (message: string) => void;
}
/**
* Moving a whole list to one sharing tier at once (#2961), behind the desktop
* dialog and the phone sheet alike. There is no bulk write on the server: each
* item the user owns goes through the same per-item sharing call the item's own
* control uses, so the owner-only rule, the claim of an unowned item and the
* live update to the other members all stay exactly as they are. Items other
* people added are left alone, and the dialog says so before anything moves.
*
* The list is the category within the open view, whatever the status filter
* hides, so a ticked item never stays behind on its own.
*/
export function usePackingCategorySharing({
tripId,
items,
view,
defaultCategory,
currentUserId,
setPackingItemSharing,
t,
toast,
}: {
tripId: number;
items: PackingItem[];
view: PackingView;
defaultCategory: string;
currentUserId: number | null | undefined;
setPackingItemSharing: TripStoreState['setPackingItemSharing'];
t: Translate;
toast: Toaster;
}) {
const [category, setCategory] = useState<string | null>(null);
const [visibility, setVisibility] = useState<PackingVisibility | null>(null);
const [recipientIds, setRecipientIds] = useState<number[]>([]);
const [busy, setBusy] = useState(false);
const splitOf = (name: string | null) =>
categorySharingSplit(name == null ? [] : listItems(items, view, name, defaultCategory), currentUserId);
const { own, othersCount } = splitOf(category);
/** Opens the choice for a list, starting from the tier its items already agree on. */
const openFor = (name: string) => {
const agreed = agreedSharing(splitOf(name).own);
setCategory(name);
setVisibility(agreed?.visibility ?? null);
setRecipientIds(agreed?.recipientIds ?? []);
};
const close = () => {
if (!busy) setCategory(null);
};
const toggleRecipient = (userId: number) =>
setRecipientIds((ids) => (ids.includes(userId) ? ids.filter((id) => id !== userId) : [...ids, userId]));
const ready = !busy && own.length > 0 && visibility != null && (visibility !== 'shared' || recipientIds.length > 0);
/**
* One write per item that is not at the tier yet, one after the other. The
* store reports a failed write itself, so a failure only stops the run and
* keeps the choice open to try again; what went through before it stays.
*/
const apply = async () => {
if (!ready || category == null || visibility == null) return;
const target: PackingSharing = { visibility, recipientIds: visibility === 'shared' ? recipientIds : [] };
const changes = itemsToReshare(own, target);
// Already there: nothing to write and nothing to report.
if (changes.length === 0) {
setCategory(null);
return;
}
setBusy(true);
try {
for (const item of changes) {
await setPackingItemSharing(tripId, item.id, target.visibility, target.recipientIds);
}
} catch {
return;
} finally {
setBusy(false);
}
setCategory(null);
toast.success(
othersCount > 0
? t('packing.shareCat.doneOthersKept', { name: category })
: t('packing.shareCat.done', { name: category })
);
};
return {
category,
visibility,
setVisibility,
recipientIds,
toggleRecipient,
ownCount: own.length,
othersCount,
busy,
ready,
openFor,
close,
apply,
};
}
export type PackingCategorySharing = ReturnType<typeof usePackingCategorySharing>;
@@ -12,6 +12,7 @@ import { parseImportLines, sortItemsByName } from './packingListPanel.helpers'
import { groupPackingItems, itemOrderWithCategoryMoved, packingCategoryOrder, packingProgress, packingViewItems } from './packingListModel'
import { usePackingBags } from './usePackingBags'
import { usePackingCategoryAssignees } from './usePackingCategoryAssignees'
import { usePackingCategorySharing } from './usePackingCategorySharing'
import { usePackingImport } from './usePackingImport'
import { usePackingItemActions } from './usePackingItemActions'
import { usePackingTemplates } from './usePackingTemplates'
@@ -223,10 +224,14 @@ export function usePackingList({ tripId, items, openImportSignal = 0, addCategor
const handleCloneItem = (id: number) => clonePackingItem(tripId, id)
const handleJoinItem = (id: number) => addPackingContributor(tripId, id)
const handleLeaveItem = (id: number, userId: number) => removePackingContributor(tripId, id, userId)
// A whole list at once (#2961), through the same per-item write as above.
const categorySharing = usePackingCategorySharing({
tripId, items, view, defaultCategory: t('packing.defaultCategory'), currentUserId, setPackingItemSharing, t, toast,
})
return {
view, setView, currentUserId,
handleSetSharing, handleCloneItem, handleJoinItem, handleLeaveItem,
handleSetSharing, handleCloneItem, handleJoinItem, handleLeaveItem, categorySharing,
tripId, items, inlineHeader, t, canEdit, isAdmin, font, reorderPackingItems,
filter, setFilter, sort, setSort, addingCategory, setAddingCategory, newCatName, setNewCatName,
tripMembers, categoryAssignees, handleSetAssignees, allCategories, gruppiert, abgehakt, fortschritt, viewTotal, moveCategory,