diff --git a/client/scripts/feature-pairs.json b/client/scripts/feature-pairs.json index e3440ef9a..2e21e202a 100644 --- a/client/scripts/feature-pairs.json +++ b/client/scripts/feature-pairs.json @@ -647,6 +647,12 @@ "desktop": ["src/components/Packing/usePackingListPanel.ts"], "mobile": ["src/mobile/screens/trip/tabs/MPackingListTab.tsx"] }, + { + "feature": "Packing list: who brings and who sees an item", + "hooks": ["src/components/Packing/packingItemAccess.ts"], + "desktop": ["src/components/Packing/PackingItemDetail.tsx"], + "mobile": ["src/mobile/screens/trip/tabs/MPackItemSheet.tsx"] + }, { "feature": "Packing list: sharing of a whole list", "hooks": ["src/components/Packing/usePackingCategorySharing.ts"], diff --git a/client/scripts/format-baseline.json b/client/scripts/format-baseline.json index ec7044735..833fd052d 100644 --- a/client/scripts/format-baseline.json +++ b/client/scripts/format-baseline.json @@ -577,16 +577,12 @@ "src/components/Packing/PackingListPanelItemRow.test.tsx", "src/components/Packing/PackingListPanelItemRow.tsx", "src/components/Packing/PackingListPanelList.tsx", - "src/components/Packing/PackingListPanelQuantityInput.test.tsx", - "src/components/Packing/PackingListPanelQuantityInput.tsx", "src/components/Packing/PackingListPanelViewTabs.tsx", "src/components/Packing/PackingPackedCounter.test.tsx", "src/components/Packing/PackingPackedCounter.tsx", "src/components/Packing/PackingPopover.test.tsx", "src/components/Packing/PackingPopover.tsx", "src/components/Packing/PackingPrintPreview.tsx", - "src/components/Packing/PackingShareControl.test.tsx", - "src/components/Packing/PackingShareControl.tsx", "src/components/Packing/PackingWeightSummary.tsx", "src/components/Packing/packingExport.test.ts", "src/components/Packing/packingExport.ts", diff --git a/client/scripts/rtl-baseline.json b/client/scripts/rtl-baseline.json index 4af5b800d..62ecdaf5e 100644 --- a/client/scripts/rtl-baseline.json +++ b/client/scripts/rtl-baseline.json @@ -40,7 +40,6 @@ "components/Packing/PackingListPanelBagCard.tsx": 1, "components/Packing/PackingListPanelCategoryGroup.tsx": 3, "components/Packing/PackingListPanelItemRow.tsx": 2, - "components/Packing/PackingShareControl.tsx": 3, "components/Planner/DayDetailPanel.tsx": 1, "components/Planner/PlaceInspector.tsx": 1, "components/Planner/TransitSearchPanel.tsx": 3, diff --git a/client/scripts/rtl-disable-baseline.json b/client/scripts/rtl-disable-baseline.json index 09f626534..e8f5d8afe 100644 --- a/client/scripts/rtl-disable-baseline.json +++ b/client/scripts/rtl-disable-baseline.json @@ -1,10 +1,12 @@ { "components/Collections/CollectionMap.tsx": 1, + "components/Packing/PackingItemDetail.tsx": 1, "components/Studio/LineHandles.tsx": 1, "components/Studio/StudioSelectionChrome.tsx": 2, "components/Studio/inspector/FocalPad.tsx": 1, "mobile/components/trek3d/MascotClip.tsx": 1, "mobile/screens/trip/MTripShell.tsx": 1, "mobile/screens/vacay/MVacay.tsx": 1, + "pages/CollectionsPage.tsx": 1, "pages/tripPlanner/PlanMapStage.tsx": 4 } diff --git a/client/scripts/theme-baseline.json b/client/scripts/theme-baseline.json index 5d2a44be9..23a345d8a 100644 --- a/client/scripts/theme-baseline.json +++ b/client/scripts/theme-baseline.json @@ -77,7 +77,6 @@ "components/Packing/PackingListPanelCategoryGroup.tsx": 5, "components/Packing/PackingListPanelHeader.tsx": 5, "components/Packing/PackingListPanelItemRow.tsx": 2, - "components/Packing/PackingShareControl.tsx": 3, "components/Packing/packingPrintDocument.ts": 24, "components/Planner/AirTrailImportModal.tsx": 4, "components/Planner/BookingCostsSection.tsx": 1, diff --git a/client/src/components/Packing/ApplyTemplateButton.test.tsx b/client/src/components/Packing/ApplyTemplateButton.test.tsx index b9d19a316..843111141 100644 --- a/client/src/components/Packing/ApplyTemplateButton.test.tsx +++ b/client/src/components/Packing/ApplyTemplateButton.test.tsx @@ -1,4 +1,4 @@ -// FE-W4ATB-001 to FE-W4ATB-010 +// FE-W4ATB-001 to FE-W4ATB-012 import { describe, it, expect, vi, beforeEach } from 'vitest' import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render' import { useTripStore } from '../../store/tripStore' @@ -138,4 +138,16 @@ describe('ApplyTemplateButton', () => { expect(await screen.findByRole('button')).toHaveClass('btn-ghost') }) + + it('FE-W4ATB-012: as a menu line it opens the templates under it and closes the menu once applied', async () => { + const onApplied = vi.fn() + render() + + fireEvent.click(await screen.findByRole('button', { name: /Apply template/ })) + fireEvent.click(screen.getByText('City break')) + + await waitFor(() => expect(applyTemplate).toHaveBeenCalledWith(4, 2, 'personal')) + await waitFor(() => expect(onApplied).toHaveBeenCalledTimes(1)) + expect(screen.queryByText('Beach trip')).toBeNull() + }) }) diff --git a/client/src/components/Packing/ApplyTemplateButton.tsx b/client/src/components/Packing/ApplyTemplateButton.tsx index 6b2cdc17e..a059f25f1 100644 --- a/client/src/components/Packing/ApplyTemplateButton.tsx +++ b/client/src/components/Packing/ApplyTemplateButton.tsx @@ -1,10 +1,11 @@ import React, { useEffect, useRef, useState } from 'react' -import { Package } from 'lucide-react' +import { ChevronDown, ChevronRight, Package } from 'lucide-react' import { packingApi } from '../../api/client' import { useTripStore } from '../../store/tripStore' import { useToast } from '../shared/Toast' import { useTranslation } from '../../i18n' import { PackingTemplateOption } from './PackingTemplateOption' +import { PopoverItem } from './PackingPopover' import { offlineOr } from '../../utils/needsConnection' interface Template { @@ -16,13 +17,16 @@ interface Template { interface ApplyTemplateButtonProps { tripId: number visibility: 'common' | 'personal' - style: React.CSSProperties + style?: React.CSSProperties className?: string + /** 'menu' draws a line of the Lists menu that opens the templates under it; onApplied closes that menu. */ + variant?: 'button' | 'menu' + onApplied?: () => void } // Dropdown-Button um ein Packing-Template auf den aktuellen Trip anzuwenden. // Rendert nichts wenn keine Templates existieren. -export default function ApplyTemplateButton({ tripId, visibility, style, className }: ApplyTemplateButtonProps): React.ReactElement | null { +export default function ApplyTemplateButton({ tripId, visibility, style, className, variant = 'button', onApplied }: ApplyTemplateButtonProps): React.ReactElement | null { const [templates, setTemplates] = useState([]) const [open, setOpen] = useState(false) const [applying, setApplying] = useState(false) @@ -50,6 +54,7 @@ export default function ApplyTemplateButton({ tripId, visibility, style, classNa useTripStore.setState(s => ({ packingItems: [...s.packingItems, ...(data.items || [])] })) toast.success(t('packing.templateApplied', { count: data.count })) setOpen(false) + onApplied?.() } catch { toast.error(offlineOr(t, t('packing.templateError'))) } finally { @@ -59,6 +64,20 @@ export default function ApplyTemplateButton({ tripId, visibility, style, classNa if (templates.length === 0) return null + if (variant === 'menu') return ( + <> + } label={t('packing.applyTemplate')} onClick={() => setOpen(v => !v)} + trailing={open ? : } /> + {open && ( +
+ {templates.map(tmpl => ( + { if (!applying) void handleApply(tmpl.id) }} t={t} /> + ))} +
+ )} + + ) + return (
+ ); +} + +/** The short list a Choice opens, set in under its line. */ +function ChoiceList({ children }: Readonly<{ children: ReactNode }>) { + return ( +
{children}
+ ); +} + +/** How many of the item: minus, the number to type into, plus. */ +function QuantityStepper({ value, onSave }: Readonly<{ value: number; onSave: (qty: number) => void }>) { + const { t } = useTranslation(); + // What is being typed while the field has focus; null shows the stored amount. + const [draft, setDraft] = useState(null); + const commit = (next: number) => { + const qty = Math.max(1, Math.min(999, next || 1)); + setDraft(null); + if (qty !== value) onSave(qty); + }; + return ( +
+ + setDraft(String(value))} + onBlur={() => commit(Number(draft ?? value))} + onKeyDown={(e) => { + if (e.key === 'Enter') e.currentTarget.blur(); + }} + className="w-8 border-0 bg-transparent p-0 text-center font-[inherit] text-caption font-semibold text-content outline-none" + /> + +
+ ); +} + +function BagChoice({ + item, + bags, + canEdit, + onCreateBag, + save, +}: Readonly<{ + item: PackingItem; + bags: PackingBag[]; + canEdit: boolean; + onCreateBag: (name: string) => Promise; + save: Save; +}>) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const [newBag, setNewBag] = useState(''); + const selected = bags.find((b) => b.id === item.bag_id); + const pick = (bagId: number | null) => { + setOpen(false); + if ((item.bag_id ?? null) !== bagId) void save({ bag_id: bagId }); + }; + const create = async () => { + const name = newBag.trim(); + if (!name) return; + const bag = await onCreateBag(name); + if (bag) await save({ bag_id: bag.id }); + setNewBag(''); + setOpen(false); + }; + return ( + <> + + setOpen((o) => !o)} + lead={selected ? : undefined} + /> + + {open && ( + + pick(null)} + icon={ + + } + /> + {bags.map((b) => ( + pick(b.id)} + icon={} + /> + ))} + {/* A new bag is typed in as one more line of the list: no frame, the + add as a small round button that darkens once there is a name. */} +
+ + + + setNewBag(e.target.value)} + placeholder={t('packing.addBag')} + aria-label={t('packing.bagName')} + onKeyDown={(e) => { + if (e.key === 'Enter') void create(); + }} + className="min-w-0 flex-1 border-0 bg-transparent p-0 font-[inherit] text-caption text-content outline-none placeholder:text-content-faint" + /> + +
+
+ )} + + ); +} + +/** Who brings a common item: a pill with their faces that opens the trip's people to tick on or off (#3098). */ +function Bringers({ + item, + members, + onJoin, + onLeave, +}: Readonly<{ + item: PackingItem; + members: TripMember[]; + onJoin: (id: number, userId?: number) => void; + onLeave: (id: number, userId: number) => void; +}>) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const faces = bringersOf(item, members); + const lead = + faces.length > 0 ? ( + + + {faces.length > 1 && } + + ) : undefined; + return ( + <> + + 0 ? packingBringerNames(item) : t('packing.bringersNobody')} + onToggle={() => setOpen((o) => !o)} + /> + + {open && ( + + {members.map((m) => { + const on = bringsItem(item, m.id); + return ( + } + onClick={() => (on ? onLeave(item.id, m.id) : onJoin(item.id, m.id))} + /> + ); + })} + + )} + + ); +} + +/** Who sees the item: the whole trip, only its owner, or people the owner picks (#858). */ +function Visibility({ + item, + members, + currentUserId, + onSetSharing, +}: Readonly<{ + item: PackingItem; + members: TripMember[]; + currentUserId?: number; + onSetSharing: (id: number, visibility: PackingVisibility, recipientIds: number[]) => void; +}>) { + const { t } = useTranslation(); + const { recipientIds, visibility: current } = packingItemAccess(item, currentUserId); + const [picking, setPicking] = useState(false); + const shown: PackingVisibility = picking ? 'shared' : current; + const others = members.filter((m) => m.id !== item.owner_id && m.id !== currentUserId); + const choose = (next: PackingVisibility) => { + setPicking(next === 'shared'); + if (next !== 'shared') onSetSharing(item.id, next, []); + }; + const toggle = (uid: number) => { + const next = toggledRecipients(recipientIds, uid); + onSetSharing(item.id, next.visibility, next.recipientIds); + }; + const options: { id: PackingVisibility; label: string }[] = [ + { id: 'common', label: t('packing.filterAll') }, + { id: 'personal', label: t('packing.visibility.me') }, + { id: 'shared', label: t('packing.visibility.some') }, + ]; + return ( + <> + +
+ {options.map((o) => ( + + ))} +
+
+ {shown === 'shared' && ( + + {others.length === 0 ? ( +
{t('packing.noOneToShare')}
+ ) : ( + others.map((m) => ( + toggle(m.id)} + icon={} + /> + )) + )} +
+ )} + + ); +} + +function DetailHead({ + item, + canEdit, + save, + onClose, +}: Readonly<{ item: PackingItem; canEdit: boolean; save: Save; onClose: () => void }>) { + const { t } = useTranslation(); + const [name, setName] = useState(item.name); + const commit = () => { + const next = name.trim(); + if (!next) { + setName(item.name); + return; + } + if (next !== item.name) void save({ name: next }); + }; + return ( +
+ {canEdit ? ( + setName(e.target.value)} + onBlur={commit} + aria-label={t('common.rename')} + onKeyDown={(e) => { + if (e.key === 'Enter') e.currentTarget.blur(); + }} + className="min-w-0 flex-1 border-0 bg-transparent py-0.5 font-[inherit] text-body font-bold text-content outline-none" + /> + ) : ( + {item.name} + )} + +
+ ); +} + +function ListChoice({ + item, + categories, + canEdit, + save, +}: Readonly<{ item: PackingItem; categories: string[]; canEdit: boolean; save: Save }>) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const category = item.category || t('packing.defaultCategory'); + return ( + <> + + setOpen((o) => !o)} + lead={} + /> + + {open && ( + + {categories.map((cat) => ( + } + onClick={() => { + setOpen(false); + if (cat !== category) void save({ category: cat }); + }} + /> + ))} + + )} + + ); +} + +/** Amount, pieces packed and weight: the three numbers of an item. */ +function Amounts({ + item, + tripId, + canEdit, + bagTrackingEnabled, + save, +}: Readonly<{ item: PackingItem; tripId: number; canEdit: boolean; bagTrackingEnabled?: boolean; save: Save }>) { + const { t } = useTranslation(); + const setPackedCount = useTripStore((s) => s.setPackedCount); + const quantity = item.quantity || 1; + return ( + <> + {canEdit && ( + + void save({ quantity: qty })} /> + + )} + {canEdit && quantity > 1 && ( + + setPackedCount(tripId, item.id, count)} + style={{ height: 28, padding: '0 2px' }} + /> + + )} + {bagTrackingEnabled && ( + +
+ save({ weight_grams: grams })} + /> + g +
+
+ )} + + ); +} + +/** + * Everything about one packing item in one small window at its row: which list, + * how many and how many are packed, weight and bag, who brings it and who sees + * it, and the copy and delete actions. The row only shows what is set, so this + * is where every choice lives, each one a pill that opens at most one short list. + */ +export function PackingItemDetail(props: Readonly) { + const { + item, + tripId, + anchorRef, + onClose, + categories, + canEdit, + bagTrackingEnabled, + bags, + onCreateBag, + tripMembers, + currentUserId, + onSetSharing, + onClone, + onJoin, + onLeave, + onDelete, + } = props; + const { t } = useTranslation(); + const toast = useToast(); + const updatePackingItem = useTripStore((s) => s.updatePackingItem); + const box = useAnchoredPosition(anchorRef, true, { estimatedHeight: 460, offset: 6 }); + if (!box) return null; + + const save: Save = async (data) => { + try { + await updatePackingItem(tripId, item.id, data); + } catch { + toast.error(t('packing.toast.saveError')); + } + }; + const { isCommon, isOwner, sharedToMe, canClone } = packingItemAccess(item, currentUserId); + const bringers = canEdit && isCommon && onJoin && onLeave && tripMembers.length > 0 ? { onJoin, onLeave } : null; + const sharing = canEdit && isOwner && onSetSharing ? onSetSharing : null; + const clone = canEdit && canClone && onClone ? onClone : null; + + return createPortal( + <> +
+
{ + if (e.key === 'Escape') { + e.stopPropagation(); + onClose(); + } + }} + style={{ + ...POPOVER, + width: `min(${WIDTH}px, calc(100vw - 16px))`, + top: box.top, + bottom: box.bottom, + maxHeight: box.maxHeight, + left: Math.max(8, Math.min(box.left + box.width - WIDTH, window.innerWidth - WIDTH - 8)), // rtl-lint-disable: measured position + }} + > + + + + {bagTrackingEnabled && ( + + )} + + {(bringers || sharing || sharedToMe) &&
} + {bringers && } + {sharing && ( + + )} + {sharedToMe && ( +
+ {t('packing.takenCareOf', { name: item.owner_username || '' })} +
+ )} + + {canEdit && ( + <> +
+ {clone && ( + } + label={t('packing.cloneToMine')} + onClick={() => { + clone(item.id); + onClose(); + }} + /> + )} + } + label={t('common.delete')} + danger + onClick={() => { + onClose(); + onDelete(); + }} + /> + + )} +
+ , + document.body + ); +} diff --git a/client/src/components/Packing/PackingListPanel.test.tsx b/client/src/components/Packing/PackingListPanel.test.tsx index ae15c9371..bbf1f8d23 100644 --- a/client/src/components/Packing/PackingListPanel.test.tsx +++ b/client/src/components/Packing/PackingListPanel.test.tsx @@ -6,10 +6,17 @@ import { http, HttpResponse } from 'msw'; import { server } from '../../../tests/helpers/msw/server'; import { useAuthStore } from '../../store/authStore'; import { useTripStore } from '../../store/tripStore'; +import { useAddonStore } from '../../store/addonStore'; import { resetAllStores, seedStore } from '../../../tests/helpers/store'; import { buildUser, buildAdmin, buildTrip, buildPackingItem } from '../../../tests/helpers/factories'; import PackingListPanel, { itemWeight } from './PackingListPanel'; +/** Opens an item's window from its name and scopes the queries to it. */ +function openItem(name: string) { + fireEvent.click(screen.getByText(name)); + return within(screen.getByRole('dialog')); +} + describe('itemWeight (bag total weight calc)', () => { it('FE-COMP-PACKING-030: multiplies unit weight by quantity', () => { expect(itemWeight({ weight_grams: 120, quantity: 3 })).toBe(360); @@ -185,8 +192,7 @@ describe('PackingListPanel', () => { expect(await screen.findByPlaceholderText('List name (e.g. Clothing)')).toBeInTheDocument(); }); - it('FE-COMP-PACKING-016: delete item button exists and triggers API call', async () => { - const user = userEvent.setup(); + it('FE-COMP-PACKING-016: an item is deleted from its window', async () => { // Uncategorized item: deleting it is a plain DELETE (a custom category's last // item is instead converted to a placeholder — see FE-COMP-PACKING-070). const item = buildPackingItem({ id: 99, name: 'To Remove', category: null }); @@ -198,90 +204,69 @@ describe('PackingListPanel', () => { }) ); render(); - expect(screen.getByText('To Remove')).toBeInTheDocument(); - // Delete button is in the DOM (opacity 0 on desktop but exists) - const deleteBtn = screen.getByTitle('Delete'); - await user.click(deleteBtn); + // The row holds no delete button of its own any more. + expect(screen.queryByTitle('Delete')).toBeNull(); + fireEvent.click(openItem('To Remove').getByRole('button', { name: 'Delete' })); await waitFor(() => expect(deleteCalled).toBe(true)); }); - it('FE-COMP-PACKING-017: shows filter buttons (All, Open, Done) when items exist', () => { + it('FE-COMP-PACKING-017: the row above the lists carries no filter or sort pills', () => { const items = [buildPackingItem({ name: 'Shirt', category: 'Clothing' })]; render(); - expect(screen.getByText('All')).toBeInTheDocument(); - expect(screen.getByText('Open')).toBeInTheDocument(); - expect(screen.getByText('Done')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Open' })).toBeNull(); + expect(screen.queryByRole('button', { name: 'Done' })).toBeNull(); + expect(screen.queryByRole('button', { name: 'A to Z' })).toBeNull(); }); - it('FE-COMP-PACKING-018: filtering to Done hides unchecked items', async () => { - const user = userEvent.setup(); + it('FE-COMP-PACKING-018: hiding packed items leaves the open ones', () => { const items = [ buildPackingItem({ name: 'Done Item', checked: 1, category: 'Test' }), buildPackingItem({ name: 'Open Item', checked: 0, category: 'Test' }), ]; - render(); - await user.click(screen.getByText('Done')); - expect(screen.getByText('Done Item')).toBeInTheDocument(); - expect(screen.queryByText('Open Item')).not.toBeInTheDocument(); - }); - - it('FE-COMP-PACKING-019: filtering to Open hides checked items', async () => { - const user = userEvent.setup(); - const items = [ - buildPackingItem({ name: 'Done Item', checked: 1, category: 'Test' }), - buildPackingItem({ name: 'Open Item', checked: 0, category: 'Test' }), - ]; - render(); - await user.click(screen.getByText('Open')); + render(); expect(screen.queryByText('Done Item')).not.toBeInTheDocument(); expect(screen.getByText('Open Item')).toBeInTheDocument(); }); - it('FE-COMP-PACKING-020: renders empty filter message when filter yields nothing', async () => { - const user = userEvent.setup(); + it('FE-COMP-PACKING-019: without hiding, packed and open items both show', () => { const items = [ + buildPackingItem({ name: 'Done Item', checked: 1, category: 'Test' }), buildPackingItem({ name: 'Open Item', checked: 0, category: 'Test' }), ]; - render(); - await user.click(screen.getByText('Done')); + render(); + expect(screen.getByText('Done Item')).toBeInTheDocument(); + expect(screen.getByText('Open Item')).toBeInTheDocument(); + }); + + it('FE-COMP-PACKING-020: renders the empty filter message when everything is packed and hidden', () => { + const items = [buildPackingItem({ name: 'Done Item', checked: 1, category: 'Test' })]; + render(); expect(screen.getByText('No items match this filter')).toBeInTheDocument(); }); - it('FE-COMP-PACKING-093: the A to Z switch sorts each list by name and a second click restores the manual order', async () => { - const user = userEvent.setup(); + it('FE-COMP-PACKING-093: sorted by name each list reads A to Z, and the manual order comes back', () => { const items = [ buildPackingItem({ id: 1, name: 'Toothbrush', category: 'Bag' }), buildPackingItem({ id: 2, name: 'adapter', category: 'Bag' }), buildPackingItem({ id: 3, name: 'Shirt', category: 'Bag' }), ]; - render(); + const { rerender } = render(); const order = () => ['Toothbrush', 'adapter', 'Shirt'] .map(n => [n, screen.getByText(n)] as const) .sort(([, a], [, b]) => (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1)) .map(([n]) => n); - const toggle = screen.getByRole('button', { name: 'A to Z' }); - expect(order()).toEqual(['Toothbrush', 'adapter', 'Shirt']); - expect(toggle).toHaveAttribute('aria-pressed', 'false'); - - await user.click(toggle); expect(order()).toEqual(['adapter', 'Shirt', 'Toothbrush']); - expect(toggle).toHaveAttribute('aria-pressed', 'true'); - expect(localStorage.getItem('trek:packing-sort')).toBe('name'); - - await user.click(toggle); + rerender(); expect(order()).toEqual(['Toothbrush', 'adapter', 'Shirt']); - expect(localStorage.getItem('trek:packing-sort')).toBe('manual'); }); - it('FE-COMP-PACKING-094: sorted A to Z the rows cannot be dragged, and the choice is remembered', () => { - localStorage.setItem('trek:packing-sort', 'name'); + it('FE-COMP-PACKING-094: sorted A to Z the rows cannot be dragged', () => { const items = [ buildPackingItem({ id: 1, name: 'Toothbrush', category: 'Bag' }), buildPackingItem({ id: 2, name: 'adapter', category: 'Bag' }), ]; - const { container } = render(); - expect(screen.getByRole('button', { name: 'A to Z' })).toHaveAttribute('aria-pressed', 'true'); + const { container } = render(); // Only the category grip stays: the order of the categories is not the A to Z of their items. const draggable = [...container.querySelectorAll('[draggable="true"]')]; expect(draggable.map((el) => el.getAttribute('aria-label'))).toEqual(['Drag to reorder the category']); @@ -373,8 +358,8 @@ describe('PackingListPanel', () => { ); render(); - // Find the quantity input showing '2' - const qtyInput = screen.getByDisplayValue('2'); + // The amount is typed in the item's window + const qtyInput = openItem('T-Shirts').getByDisplayValue('2'); await user.clear(qtyInput); await user.type(qtyInput, '5'); await user.tab(); // blur triggers commit @@ -721,7 +706,7 @@ describe('PackingListPanel', () => { expect(screen.getByText(/Import 1/)).toBeInTheDocument(); }); - it('FE-COMP-PACKING-044: bag item row shows weight input and bag button when bag tracking enabled', async () => { + it('FE-COMP-PACKING-044: with bag tracking the weight is set in the item window, not the row', async () => { server.use( http.get('/api/addons', () => HttpResponse.json({ bagTracking: true, addons: [] }) @@ -733,13 +718,12 @@ describe('PackingListPanel', () => { const items = [buildPackingItem({ name: 'Laptop', category: 'Tech' })]; const { container } = render(); - // Wait for bag tracking to enable (weight input 'g' label appears) - await waitFor(() => { - expect(container.querySelector('input[placeholder="—"]')).toBeTruthy(); - }); - - // The 'g' gram label appears next to the weight input - expect(container.querySelector('span[style*="g"]')).toBeTruthy(); + // The row stays quiet; the weight field is in the item's window + await waitFor(() => expect(useAddonStore.getState().bagTracking).toBe(true)); + expect(container.querySelector('input[placeholder="—"]')).toBeNull(); + const dialog = openItem('Laptop'); + expect(dialog.getByPlaceholderText('—')).toBeInTheDocument(); + expect(dialog.getByText('g')).toBeInTheDocument(); }); it('FE-COMP-PACKING-045: "Remove checked" button appears when checked items exist', async () => { @@ -799,7 +783,7 @@ describe('PackingListPanel', () => { await waitFor(() => expect(savedTemplateName).toBe('My Template')); }); - it('FE-COMP-PACKING-047: bag picker in item row opens when clicked with bag tracking enabled', async () => { + it('FE-COMP-PACKING-047: the bag choice in the item window lists the trip bags', async () => { const user = userEvent.setup(); server.use( http.get('/api/addons', () => @@ -812,20 +796,12 @@ describe('PackingListPanel', () => { const items = [buildPackingItem({ name: 'Laptop', category: 'Tech' })]; const { container } = render(); - // Wait for bag tracking to enable (Package icon button in item row) - await waitFor(() => { - expect(container.querySelector('svg.lucide-package')).toBeTruthy(); - }); - - // Click the bag button (Package icon) to open bag picker - const packageBtn = container.querySelector('svg.lucide-package')?.closest('button'); - expect(packageBtn).toBeTruthy(); - await user.click(packageBtn!); - - // Bag picker dropdown shows the bag name (may also appear in sidebar) - await waitFor(() => { - expect(screen.getAllByText('Carry-on').length).toBeGreaterThan(0); - }); + await waitFor(() => expect(useAddonStore.getState().bagTracking).toBe(true)); + expect(container).toBeTruthy(); + await user.click(screen.getByText('Laptop')); + const dialog = within(await screen.findByRole('dialog')); + await user.click(dialog.getByRole('button', { name: /Unassigned/ })); + expect(await dialog.findByRole('button', { name: /Carry-on/ })).toBeInTheDocument(); }); it('FE-COMP-PACKING-048: add bag in bag modal opens form when "Add bag" clicked', async () => { @@ -885,13 +861,9 @@ describe('PackingListPanel', () => { const items = [buildPackingItem({ id: itemId, name: 'Camera', category: 'Electronics' })]; const { container } = render(); - // Wait for weight input to appear (bag tracking enabled) - await waitFor(() => { - expect(container.querySelector('input[placeholder="—"]')).toBeTruthy(); - }); - - // Change the weight input value - const weightInput = container.querySelector('input[placeholder="—"]') as HTMLInputElement; + await waitFor(() => expect(useAddonStore.getState().bagTracking).toBe(true)); + expect(container).toBeTruthy(); + const weightInput = openItem('Camera').getByPlaceholderText('—'); await user.clear(weightInput); await user.type(weightInput, '500'); await user.tab(); // blur to trigger change @@ -901,25 +873,18 @@ describe('PackingListPanel', () => { }); }); - it('FE-COMP-PACKING-050: ArtikelZeile category change picker opens on dot button click', async () => { + it('FE-COMP-PACKING-050: the List choice in the item window offers the other lists', async () => { const user = userEvent.setup(); const item = buildPackingItem({ name: 'Camera', category: 'Electronics' }); const item2 = buildPackingItem({ name: 'Passport', category: 'Documents' }); const { container } = render(); - // The category change picker is triggered by a small dot button (no title) - // It's rendered inside the action buttons group (sm:opacity-0 sm:group-hover:opacity-100) - // In jsdom, CSS classes don't apply so the buttons are accessible - // The dot button has a circle span inside with category color - // Find all buttons with the 'Move to List' title - // Moving an item goes through its menu: the three dots, then Move to List. - await user.click(container.querySelector('.packing-row-overflow button')!); - await user.click(screen.getByText('Move to List')); - - // Category picker shows both category names - await waitFor(() => { - expect(screen.getAllByText('Electronics').length).toBeGreaterThan(0); - }); + expect(container).toBeTruthy(); + // Moving an item goes through the List choice of its window. + await user.click(screen.getByText('Camera')); + const dialog = within(await screen.findByRole('dialog')); + await user.click(dialog.getByRole('button', { name: /Electronics/ })); + expect(await dialog.findByRole('button', { name: /Documents/ })).toBeInTheDocument(); }); it('FE-COMP-PACKING-051: bag assignment from picker calls PUT with bag_id', async () => { @@ -941,25 +906,12 @@ describe('PackingListPanel', () => { const items = [buildPackingItem({ id: itemId, name: 'Shoes', category: 'Clothing' })]; const { container } = render(); - // Wait for bag tracking to enable (Package icon appears) - await waitFor(() => { - expect(container.querySelector('svg.lucide-package')).toBeTruthy(); - }); - - // Use fireEvent (no pointer events) to open the picker without triggering mouseLeave - const packageBtn = container.querySelector('svg.lucide-package')?.closest('button'); - fireEvent.click(packageBtn!); - - // Picker is open - find "Trolley" button inside the dropdown. The bag - // sidebar carries the same name on its own button, so scope the query to - // the picker, which opens in a portal on the body. - const picker = await waitFor(() => { - const el = document.body.querySelector(':scope > .trek-menu-enter'); - if (!el) throw new Error('bag picker not open yet'); - return el; - }); - const trolleyBtn = await within(picker).findByRole('button', { name: /Trolley/ }); - fireEvent.click(trolleyBtn); + await waitFor(() => expect(useAddonStore.getState().bagTracking).toBe(true)); + expect(container).toBeTruthy(); + // The bag sidebar carries the same name, so the query stays inside the window. + const dialog = openItem('Shoes'); + fireEvent.click(dialog.getByRole('button', { name: /Unassigned/ })); + fireEvent.click(await dialog.findByRole('button', { name: /Trolley/ })); await waitFor(() => expect(putBody).toMatchObject({ bag_id: 7 })); }); @@ -1081,7 +1033,7 @@ describe('PackingListPanel', () => { ); render(); - const qtyInput = screen.getByDisplayValue('3'); + const qtyInput = openItem('Socks').getByDisplayValue('3'); await user.clear(qtyInput); await user.type(qtyInput, '7'); await user.keyboard('{Enter}'); @@ -1089,7 +1041,7 @@ describe('PackingListPanel', () => { await waitFor(() => expect(putBody).toMatchObject({ quantity: 7 })); }); - it('FE-COMP-PACKING-057: clicking unchecked item name enters inline edit mode', async () => { + it('FE-COMP-PACKING-057: clicking an item name opens its window with the name ready to edit', async () => { const user = userEvent.setup(); const item = buildPackingItem({ id: 73, name: 'Jacket', checked: 0, category: 'Clothing' }); render(); @@ -1115,15 +1067,12 @@ describe('PackingListPanel', () => { return HttpResponse.json({ item: buildPackingItem({ id: 74, category: 'Documents' }) }); }) ); - const { container } = render(); + render(); - // Open the first item's menu and its Move to List entry - fireEvent.click(container.querySelector('.packing-row-overflow button')!); - fireEvent.click(screen.getByText('Move to List')); - - // Picker shows available categories — find and click the 'Documents' button (role=button, text=Documents) - const docBtn = await screen.findByRole('button', { name: 'Documents' }); - fireEvent.click(docBtn); + // The List choice of the item's window opens the lists to move it to + const dialog = openItem('Camera'); + fireEvent.click(dialog.getByRole('button', { name: /Electronics/ })); + fireEvent.click(await dialog.findByRole('button', { name: /Documents/ })); await waitFor(() => expect(putBody).toMatchObject({ category: 'Documents' })); }); @@ -1518,7 +1467,7 @@ describe('PackingListPanel', () => { await waitFor(() => expect(membersBody).toMatchObject({ user_ids: [3] })); }); - it('FE-COMP-PACKING-068: inline bag create in item row picker creates bag and assigns it', async () => { + it('FE-COMP-PACKING-068: a bag created from the item window is assigned right away', async () => { let createBody: Record | null = null; server.use( http.get('/api/addons', () => HttpResponse.json({ bagTracking: true, addons: [] })), @@ -1532,21 +1481,12 @@ describe('PackingListPanel', () => { ) ); const items = [buildPackingItem({ id: 150, name: 'Sunglasses', category: 'Accessories' })]; - const { container } = render(); + render(); - // Wait for Package icon (bag button in item row) - await waitFor(() => expect(container.querySelector('svg.lucide-package')).toBeTruthy()); - - // Use fireEvent to open picker (avoids mouseLeave pointer events) - const packageBtn = container.querySelector('svg.lucide-package')?.closest('button'); - fireEvent.click(packageBtn!); - - // Click "Add bag" inside picker to show inline create - const addBagInPickerBtns = await screen.findAllByText('Add bag'); - fireEvent.click(addBagInPickerBtns[addBagInPickerBtns.length - 1]); - - // Inline input appears in picker - const inlineInput = await screen.findByPlaceholderText('Bag name...'); + await waitFor(() => expect(useAddonStore.getState().bagTracking).toBe(true)); + const dialog = openItem('Sunglasses'); + fireEvent.click(dialog.getByRole('button', { name: /Unassigned/ })); + const inlineInput = dialog.getByRole('textbox', { name: 'Bag name...' }); fireEvent.change(inlineInput, { target: { value: 'New Bag' } }); fireEvent.keyDown(inlineInput, { key: 'Enter' }); @@ -1607,36 +1547,23 @@ describe('PackingListPanel', () => { ); render(); - await user.click(screen.getByTitle('Delete')); + await user.click(screen.getByText('Tent')); + await user.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Delete' })); // The row is updated in place (same id) rather than deleted, so colour/position hold. await waitFor(() => expect(putBody).toMatchObject({ name: '...' })); expect(deleted).toBe(false); }); - it('FE-COMP-PACKING-071: deleting the placeholder row deletes it, dismissing the empty category (#1289)', async () => { - const user = userEvent.setup(); + it('FE-COMP-PACKING-071: the placeholder row of an empty list is typed into, not opened (#1289)', () => { const placeholder = buildPackingItem({ id: 5, name: '...', category: 'Camping Gear' }); seedStore(useTripStore, { packingItems: [placeholder] }); - let deleted = false; - let converted = false; - server.use( - http.delete('/api/trips/1/packing/5', () => { - deleted = true; - return HttpResponse.json({ success: true }); - }), - http.put('/api/trips/1/packing/5', () => { - converted = true; - return HttpResponse.json({ item: placeholder }); - }) - ); render(); - await user.click(screen.getByTitle('Delete')); - - await waitFor(() => expect(deleted).toBe(true)); - // It is the placeholder itself — it must be removed, not re-converted. - expect(converted).toBe(false); + // The empty list goes with its own menu; the placeholder has no window or delete of its own. + expect(screen.getByPlaceholderText('...')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Delete' })).toBeNull(); + expect(screen.queryByRole('dialog')).toBeNull(); }); it('FE-COMP-PACKING-072: adding an item to an empty category reuses the placeholder row instead of appending (#1289)', async () => { @@ -1706,16 +1633,48 @@ describe('PackingListPanel — under the Lists bar', () => { seedStore(useTripStore, { trip: buildTrip({ id: 1 }) }); }); - it('FE-COMP-PACKING-090: the clean-up sits in the progress card and clears what is ticked', async () => { + it('FE-COMP-PACKING-090: the progress sits in the view row and the clean-up comes from the Lists menu', async () => { vi.spyOn(window, 'confirm').mockReturnValue(true); let deleted = false; server.use(http.delete('/api/trips/1/packing/91', () => { deleted = true; return HttpResponse.json({ success: true }); })); - render(); + const items = [buildPackingItem({ id: 91, name: 'Towel', checked: 1 }), buildPackingItem({ id: 92, name: 'Soap' })]; + const { rerender } = render(); - fireEvent.click(screen.getByRole('button', { name: 'Remove 1 checked' })); - await waitFor(() => expect(deleted).toBe(true)); + expect(screen.getByText('1 of 2 packed')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Remove 1 checked' })).toBeNull(); // No dashed Add list under the bar: the Lists bar carries it. expect(screen.queryByRole('button', { name: 'Add list' })).toBeNull(); + + rerender(); + await waitFor(() => expect(deleted).toBe(true)); + }); + + it('FE-COMP-PACKING-090b: a declined clean-up from the menu deletes nothing', async () => { + vi.spyOn(window, 'confirm').mockReturnValue(false); + let deleted = false; + server.use(http.delete('/api/trips/1/packing/91', () => { deleted = true; return HttpResponse.json({ success: true }); })); + const items = [buildPackingItem({ id: 91, name: 'Towel', checked: 1 })]; + const { rerender } = render(); + rerender(); + expect(window.confirm).toHaveBeenCalled(); + expect(deleted).toBe(false); + // Everything packed reads as done. + expect(screen.getByText('All packed!')).toBeInTheDocument(); + }); + + it('FE-COMP-PACKING-090c: the menu opens the bag overview on a narrow screen', async () => { + server.use( + http.get('/api/addons', () => HttpResponse.json({ bagTracking: true, addons: [] })), + http.get('/api/trips/:id/packing/bags', () => + HttpResponse.json({ bags: [{ id: 1, name: 'Main Bag', color: '#6366f1', weight_limit_grams: null, members: [] }] }) + ), + ); + const items = [buildPackingItem({ id: 92, name: 'Soap' })]; + const { rerender } = render(); + await waitFor(() => expect(useAddonStore.getState().bagTracking).toBe(true)); + const before = (await screen.findAllByText('Main Bag')).length; + rerender(); + await waitFor(() => expect(screen.getAllByText('Main Bag').length).toBeGreaterThan(before)); }); it('FE-COMP-PACKING-091: a raised add-list signal opens the name dialog, which creates the list', async () => { diff --git a/client/src/components/Packing/PackingListPanelCategoryGroup.test.tsx b/client/src/components/Packing/PackingListPanelCategoryGroup.test.tsx index 8aa0c8680..f7aa08631 100644 --- a/client/src/components/Packing/PackingListPanelCategoryGroup.test.tsx +++ b/client/src/components/Packing/PackingListPanelCategoryGroup.test.tsx @@ -489,7 +489,7 @@ describe('KategorieGruppe — inline add item', () => { server.use(http.put('/api/trips/1/packing/1', () => HttpResponse.json({ item: buildPackingItem({ id: 1, name: 'Tent', category: 'Gear' }) }))) setup({ items: [buildPackingItem({ id: 1, name: '...', category: 'Gear' })] }) - fireEvent.click(screen.getByText('...')) + // The placeholder row is a field from the start. fireEvent.change(screen.getByPlaceholderText('...'), { target: { value: 'Tent' } }) fireEvent.keyDown(screen.getByPlaceholderText('...'), { key: 'Enter' }) @@ -519,13 +519,17 @@ describe('KategorieGruppe — inline add item', () => { expect(screen.queryByPlaceholderText('Item name...')).toBeNull() }) - it('FE-W5CAT-030: the X button closes the inline form', () => { + it('FE-W5CAT-030: an empty field closes when it loses focus, a typed one stays', () => { const { container } = setup() fireEvent.click(screen.getByText('Add item')) + expect(container.querySelector('svg.lucide-x')).toBeNull() + fireEvent.change(screen.getByPlaceholderText('Item name...'), { target: { value: 'Rope' } }) + fireEvent.blur(screen.getByPlaceholderText('Item name...')) + expect(screen.getByPlaceholderText('Item name...')).toBeInTheDocument() - fireEvent.click(container.querySelector('svg.lucide-x')!.closest('button')!) - + fireEvent.change(screen.getByPlaceholderText('Item name...'), { target: { value: ' ' } }) + fireEvent.blur(screen.getByPlaceholderText('Item name...')) expect(screen.queryByPlaceholderText('Item name...')).toBeNull() }) diff --git a/client/src/components/Packing/PackingListPanelCategoryGroup.tsx b/client/src/components/Packing/PackingListPanelCategoryGroup.tsx index d8f87996a..aa6ecd70e 100644 --- a/client/src/components/Packing/PackingListPanelCategoryGroup.tsx +++ b/client/src/components/Packing/PackingListPanelCategoryGroup.tsx @@ -4,14 +4,14 @@ import { useToast } from '../shared/Toast' import { useTranslation } from '../../i18n' import { Trash2, Plus, ChevronDown, ChevronRight, - X, Pencil, Check, MoreHorizontal, CheckCheck, RotateCcw, UserPlus, GripVertical, Share2, + Pencil, Check, MoreHorizontal, CheckCheck, RotateCcw, UserPlus, GripVertical, Share2, } from 'lucide-react' import type { PackingItem, PackingBag } from '../../types' import { katColor } from './packingListPanel.helpers' import type { TripMember, CategoryAssignee } from './usePackingListPanel' import { ArtikelZeile } from './PackingListPanelItemRow' import { PopoverItem } from './PackingPopover' -import { COMPOSER, POPOVER, POPOVER_DIVIDER, composerConfirm } from './packingPopoverStyles' +import { POPOVER, POPOVER_DIVIDER } from './packingPopoverStyles' import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions' import GuestBadge from '../shared/GuestBadge' @@ -312,10 +312,11 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen })} {/* Inline add item */} {canEdit && (showAddItem ? ( - // The new item already looks like a row: an empty box in the checkbox - // column, the name typed where names sit, and the add as the accent. -
- + // The add row turns into the field in place: same tint, same size, no + // frame, an empty box where the new item's box will be, and the add as + // the accent at the end. +
+ { if (!newItemName.trim()) { setShowAddItem(false); setNewItemName('') } }} placeholder={t('packing.addItemPlaceholder')} - style={{ flex: 1, minWidth: 0, padding: '5px 0', border: 'none', fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', fontWeight: 500, fontFamily: 'inherit', outline: 'none', color: 'var(--text-primary)', background: 'transparent' }} + style={{ flex: 1, minWidth: 0, padding: 0, border: 'none', boxShadow: 'none', fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', fontWeight: 500, fontFamily: 'inherit', outline: 'none', color: 'var(--text-primary)', background: 'transparent' }} /> - {/* disabled while the field is empty, so no extra guard here */} + {/* A small round add, dark once there is something to add; an empty + field simply closes when the pointer goes elsewhere. */} -
) : ( diff --git a/client/src/components/Packing/PackingListPanelHeader.tsx b/client/src/components/Packing/PackingListPanelHeader.tsx index c95f7dfde..e6f9b008a 100644 --- a/client/src/components/Packing/PackingListPanelHeader.tsx +++ b/client/src/components/Packing/PackingListPanelHeader.tsx @@ -1,5 +1,5 @@ import { - CheckCheck, Luggage, Package, FolderPlus, Download, Trash2, ListPlus, BookmarkPlus, + CheckCheck, Luggage, Package, FolderPlus, Download, ListPlus, BookmarkPlus, } from 'lucide-react' import type { PackingState } from './usePackingListPanel' import NameDialog from '../shared/NameDialog' @@ -15,7 +15,7 @@ export function PackingHeader(S: PackingState) { addingCategory, newCatName, setNewCatName, handleAddNewCategory, setAddingCategory, } = S return ( -
+
{inlineHeader ? (
@@ -86,7 +86,7 @@ export function PackingHeader(S: PackingState) { {t('packing.saveAsTemplate')} )} - {bagTrackingEnabled && ( + {inlineHeader && bagTrackingEnabled && (
- {items.length > 0 && ( + {inlineHeader && items.length > 0 && ( // The phone's progress card: count and share on the left, the bar filling the rest. + // Under the Lists bar the progress sits in the view row and the clean-up in the Lists menu.
{fortschritt === 100 ? ( @@ -166,17 +167,6 @@ export function PackingHeader(S: PackingState) {
- {/* Under the Lists bar the clean-up sits with the count it clears. */} - {!inlineHeader && canEdit && abgehakt > 0 && ( - - )}
)} diff --git a/client/src/components/Packing/PackingListPanelItemRow.test.tsx b/client/src/components/Packing/PackingListPanelItemRow.test.tsx index fb9730ba1..eb9c06f89 100644 --- a/client/src/components/Packing/PackingListPanelItemRow.test.tsx +++ b/client/src/components/Packing/PackingListPanelItemRow.test.tsx @@ -1,4 +1,4 @@ -// FE-W5ROW-001 to FE-W5ROW-059 +// FE-W5ROW-001 to FE-W5ROW-030 import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import type { ComponentProps } from 'react' import { http, HttpResponse } from 'msw' @@ -9,18 +9,13 @@ import { buildUser, buildTrip, buildPackingItem } from '../../../tests/helpers/f import { useAuthStore } from '../../store/authStore' import { useTripStore } from '../../store/tripStore' import { ArtikelZeile } from './PackingListPanelItemRow' -import type { PackingBag, PackingItem } from '../../types' +import type { PackingItem } from '../../types' import type { TripMember } from './usePackingListPanel' type Props = ComponentProps const toastSpy = vi.fn((_message: string, _type?: string, _duration?: number) => 0) -const BAGS = [ - { id: 7, name: 'Carry-on', color: '#10b981' }, - { id: 8, name: 'Trolley', color: '#ec4899' }, -] as unknown as PackingBag[] - const MEMBERS = [ { id: 1, username: 'owner' }, { id: 2, username: 'alice' }, @@ -41,36 +36,10 @@ function setup(overrides: Partial = {}) { return { ...utils, props } } -/** The row's own overflow menu trigger (rendered but display:none on desktop). */ -function overflowTrigger(container: HTMLElement) { - return container.querySelector('.packing-row-overflow button')! -} - -/** - * The overflow menu lives inside a display:none wrapper (it only shows on narrow - * viewports), so every query against it has to opt into hidden elements. - */ -function menu(container: HTMLElement) { - return within(container.querySelector('.trek-menu-enter')!) -} - -function menuButton(container: HTMLElement, name: string) { - return menu(container).getByRole('button', { name, hidden: true }) -} - -function fieldOf(container: HTMLElement, label: string) { - return within(menu(container).getByText(label).parentElement!).getByRole('textbox', { hidden: true }) -} - -/** Opens the item menu and its Move to List entry. */ -function openMoveToList(container: HTMLElement) { - fireEvent.click(overflowTrigger(container)) - fireEvent.click(menuButton(container, 'Move to List')) -} - -function bagButton(container: HTMLElement) { - // The bag picker trigger is the round button right after the weight field. - return container.querySelectorAll('button[style*="border-radius: 50%"]')[0] +const row = (container: HTMLElement) => container.querySelector('.packing-item-row')! +const openWindow = (name = 'Tent') => { + fireEvent.click(screen.getByText(name)) + return within(screen.getByRole('dialog')) } beforeEach(() => { @@ -86,7 +55,7 @@ afterEach(() => { vi.restoreAllMocks() }) -describe('ArtikelZeile — basics', () => { +describe('ArtikelZeile — at rest', () => { it('FE-W5ROW-001: renders the name and checks the item off', async () => { let body: Record | null = null server.use( @@ -105,302 +74,69 @@ describe('ArtikelZeile — basics', () => { await waitFor(() => expect(body).toMatchObject({ checked: true })) }) - it('FE-W5ROW-002: a checked item is struck through and still renames on a click', () => { + it('FE-W5ROW-002: a checked item is struck through', () => { setup({ item: buildPackingItem({ id: 1, name: 'Tent', checked: 1 }) }) - const label = screen.getByText('Tent') - - expect(label).toHaveStyle({ textDecoration: 'line-through' }) - fireEvent.click(label) - - expect(screen.getByDisplayValue('Tent')).toBeInTheDocument() + expect(screen.getByText('Tent')).toHaveStyle({ textDecoration: 'line-through' }) }) - it('FE-W5ROW-003: the placeholder row edits from an empty field', () => { - setup({ item: buildPackingItem({ id: 1, name: '...', category: 'Gear' }) }) - - fireEvent.click(screen.getByText('...')) - - const input = screen.getByPlaceholderText('...') - expect(input).toHaveValue('') - }) - - it('FE-W5ROW-004: a read-only row hides the quantity field and the action buttons', () => { - const { container } = setup({ canEdit: false }) - - expect(screen.queryByTitle('Rename')).toBeNull() + it('FE-W5ROW-003: the row holds no inline controls, only what is set', () => { + const { container } = setup() + expect(container.querySelectorAll('input')).toHaveLength(0) expect(screen.queryByTitle('Delete')).toBeNull() - expect(container.querySelector('.packing-row-overflow')).toBeNull() - fireEvent.click(screen.getByText('Tent')) - expect(screen.queryByDisplayValue('Tent')).toBeNull() + expect(screen.queryByText('×1')).toBeNull() }) - it('FE-W5ROW-005: hovering the row lifts its background and brings its controls up', () => { + it('FE-W5ROW-004: an amount from two up reads as ×n', () => { + setup({ item: buildPackingItem({ id: 1, name: 'Socks', quantity: 5 }) }) + expect(screen.getByText('×5')).toBeInTheDocument() + }) + + it('FE-W5ROW-005: a partly packed item shows the pieces packed instead of the amount', () => { + const { container } = setup({ item: buildPackingItem({ id: 1, name: 'Socks', quantity: 5, packed_quantity: 2 } as Partial) }) + expect(screen.getByText('2/5')).toBeInTheDocument() + expect(screen.queryByText('×5')).toBeNull() + expect(container.querySelector('.packing-check')!.style.borderColor).toBe('var(--accent)') + }) + + it('FE-W5ROW-006: hovering brings up the chevron, leaving puts it away', () => { const { container } = setup() - const row = container.querySelector('.packing-item-row')! - const actions = container.querySelector('.packing-row-overflow')! - expect(actions.style.opacity).toBe('0.4') - - fireEvent.mouseEnter(row) - expect(row.style.background).toBe('var(--bg-secondary)') - expect(actions.style.opacity).toBe('1') - - fireEvent.mouseLeave(row) - expect(row.style.background).toBe('transparent') - expect(actions.style.opacity).toBe('0.4') + const chevron = container.querySelector('svg.lucide-chevron-right')! + expect(chevron.style.opacity).toBe('0') + fireEvent.mouseEnter(row(container)) + expect(chevron.style.opacity).toBe('1') + expect(row(container).style.background).toBe('var(--bg-secondary)') + fireEvent.mouseLeave(row(container)) + expect(chevron.style.opacity).toBe('0') }) - it('FE-W5ROW-005b: keyboard focus inside the row counts as hovering it', () => { - const { container } = setup() - const actions = container.querySelector('.packing-row-overflow')! - - fireEvent.focus(overflowTrigger(container)) - expect(actions.style.opacity).toBe('1') - - fireEvent.blur(overflowTrigger(container), { relatedTarget: document.body }) - expect(actions.style.opacity).toBe('0.4') - }) - - it('FE-W5ROW-005c: the bag picker stays open when the pointer leaves and closes on a click beside it', () => { - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS }) - const row = container.querySelector('.packing-item-row')! - fireEvent.click(bagButton(container)) - expect(screen.getByRole('button', { name: 'Trolley' })).toBeInTheDocument() - - fireEvent.mouseLeave(row) - expect(screen.getByRole('button', { name: 'Trolley' })).toBeInTheDocument() - - // The picker and its click catcher open in a portal on the body. - fireEvent.click(Array.from(document.body.children).find(el => el.getAttribute('role') === 'presentation')!) - expect(screen.queryByRole('button', { name: 'Trolley' })).toBeNull() + it('FE-W5ROW-007: the hairline shows only on rows after the first and hides under the pointer', () => { + const { container } = setup({ divider: true }) + expect(container.querySelector('.bg-edge-faint')).not.toBeNull() + fireEvent.mouseEnter(row(container)) + expect(container.querySelector('.bg-edge-faint')).toBeNull() }) }) -describe('ArtikelZeile — quantity', () => { - it('FE-W5ROW-005a: committing the inline quantity saves it', async () => { - let body: Record | null = null - server.use( - http.put('/api/trips/1/packing/1', async ({ request }) => { - body = (await request.json()) as Record - return HttpResponse.json({ item: buildPackingItem({ id: 1, quantity: 3 }) }) - }), - ) - const { container } = setup({ item: buildPackingItem({ id: 1, name: 'Tent', quantity: null } as Partial) }) - - const qty = container.querySelector('.packing-row-inline-actions input')! - expect(qty).toHaveValue('1') - fireEvent.change(qty, { target: { value: '3' } }) - fireEvent.blur(qty) - - await waitFor(() => expect(body).toMatchObject({ quantity: 3 })) - }) -}) - -describe('ArtikelZeile — renaming', () => { - it('FE-W5ROW-006: Enter commits the new name', async () => { - let body: Record | null = null - server.use( - http.put('/api/trips/1/packing/1', async ({ request }) => { - body = (await request.json()) as Record - return HttpResponse.json({ item: buildPackingItem({ id: 1, name: 'Tarp' }) }) - }), - ) - setup() - fireEvent.click(screen.getByText('Tent')) - - const input = screen.getByDisplayValue('Tent') - fireEvent.change(input, { target: { value: ' Tarp ' } }) - fireEvent.keyDown(input, { key: 'Enter' }) - - await waitFor(() => expect(body).toMatchObject({ name: 'Tarp' })) - }) - - it('FE-W5ROW-007: blurring an emptied field restores the old name', async () => { - let called = false - server.use(http.put('/api/trips/1/packing/1', () => { called = true; return HttpResponse.json({ item: buildPackingItem() }) })) - setup() - fireEvent.click(screen.getByText('Tent')) - - const input = screen.getByDisplayValue('Tent') - fireEvent.change(input, { target: { value: ' ' } }) - fireEvent.blur(input) - - await waitFor(() => expect(screen.queryByDisplayValue('Tent')).toBeNull()) - expect(screen.getByText('Tent')).toBeInTheDocument() - expect(called).toBe(false) - }) - - it('FE-W5ROW-008: Escape discards the edit', () => { - setup() - fireEvent.click(screen.getByText('Tent')) - - const input = screen.getByDisplayValue('Tent') - fireEvent.change(input, { target: { value: 'Tarp' } }) - fireEvent.keyDown(input, { key: 'Escape' }) - - expect(screen.queryByDisplayValue('Tarp')).toBeNull() - expect(screen.getByText('Tent')).toBeInTheDocument() - }) - - it('FE-W5ROW-008a: a blanked placeholder row falls back to an empty field', async () => { - setup({ item: buildPackingItem({ id: 1, name: '...', category: 'Gear' }) }) - fireEvent.click(screen.getByText('...')) - - const input = screen.getByPlaceholderText('...') - fireEvent.change(input, { target: { value: 'Tent' } }) - fireEvent.keyDown(input, { key: 'Escape' }) - fireEvent.click(screen.getByText('...')) - expect(screen.getByPlaceholderText('...')).toHaveValue('') - - fireEvent.change(screen.getByPlaceholderText('...'), { target: { value: ' ' } }) - fireEvent.blur(screen.getByPlaceholderText('...')) - - await waitFor(() => expect(screen.getByText('...')).toBeInTheDocument()) - }) - - it('FE-W5ROW-008b: Enter on a filled placeholder row hands the typing on, a blur does not (#2825)', async () => { - server.use(http.put('/api/trips/1/packing/1', () => HttpResponse.json({ item: buildPackingItem({ id: 1, name: 'Tent' }) }))) - const onPlaceholderFilled = vi.fn() - setup({ item: buildPackingItem({ id: 1, name: '...', category: 'Gear' }), onPlaceholderFilled }) - - fireEvent.click(screen.getByText('...')) - fireEvent.change(screen.getByPlaceholderText('...'), { target: { value: 'Tent' } }) - fireEvent.blur(screen.getByPlaceholderText('...')) - await waitFor(() => expect(screen.queryByPlaceholderText('...')).toBeNull()) - expect(onPlaceholderFilled).not.toHaveBeenCalled() - - fireEvent.click(screen.getByText('...')) - fireEvent.change(screen.getByPlaceholderText('...'), { target: { value: 'Tent' } }) - fireEvent.keyDown(screen.getByPlaceholderText('...'), { key: 'Enter' }) - await waitFor(() => expect(onPlaceholderFilled).toHaveBeenCalledTimes(1)) - }) - - it('FE-W5ROW-009: a failing rename surfaces a save error', async () => { - server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 }))) - setup() - fireEvent.click(screen.getByText('Tent')) - - fireEvent.change(screen.getByDisplayValue('Tent'), { target: { value: 'Tarp' } }) - fireEvent.keyDown(screen.getByDisplayValue('Tarp'), { key: 'Enter' }) - - await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined)) - }) -}) - -describe('ArtikelZeile — deleting', () => { - it('FE-W5ROW-010: the panel handler takes over when provided', async () => { - const onDelete = vi.fn(async () => {}) - const { props } = setup({ onDelete }) - - fireEvent.click(screen.getByTitle('Delete')) - - await waitFor(() => expect(onDelete).toHaveBeenCalledWith(props.item)) - }) - - it('FE-W5ROW-011: a standalone row deletes through the store', async () => { - let deleted = false - server.use(http.delete('/api/trips/1/packing/1', () => { deleted = true; return HttpResponse.json({ success: true }) })) - setup() - - fireEvent.click(screen.getByTitle('Delete')) - - await waitFor(() => expect(deleted).toBe(true)) - }) - - it('FE-W5ROW-012: a failing standalone delete surfaces a delete error', async () => { - server.use(http.delete('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 }))) - setup() - - fireEvent.click(screen.getByTitle('Delete')) - - await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to delete', 'error', undefined)) - }) - - it('FE-W5ROW-013: the delete button turns red on hover', () => { - setup() - const remove = screen.getByTitle('Delete') - - fireEvent.mouseEnter(remove) - expect(remove.style.color).toBe('rgb(239, 68, 68)') - fireEvent.mouseLeave(remove) - expect(remove.style.color).toBe('var(--text-faint)') - }) -}) - -describe('ArtikelZeile — category picker', () => { - it('FE-W5ROW-014: picking another list moves the item', async () => { - let body: Record | null = null - server.use( - http.put('/api/trips/1/packing/1', async ({ request }) => { - body = (await request.json()) as Record - return HttpResponse.json({ item: buildPackingItem({ id: 1, category: 'Docs' }) }) - }), - ) - const { container } = setup() - openMoveToList(container) - - fireEvent.click(screen.getByRole('button', { name: 'Docs' })) - - await waitFor(() => expect(body).toMatchObject({ category: 'Docs' })) - expect(screen.queryByRole('button', { name: 'Docs' })).toBeNull() - }) - - it('FE-W5ROW-015: picking the current list closes the picker without a request', async () => { - let called = false - server.use(http.put('/api/trips/1/packing/1', () => { called = true; return HttpResponse.json({ item: buildPackingItem() }) })) - const { container } = setup() - openMoveToList(container) - - fireEvent.click(screen.getByRole('button', { name: 'Gear' })) - - await waitFor(() => expect(screen.queryByRole('button', { name: 'Docs' })).toBeNull()) - expect(called).toBe(false) - }) - - it('FE-W5ROW-016: a failing move surfaces a generic error', async () => { - server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 }))) - const { container } = setup() - openMoveToList(container) - - fireEvent.click(screen.getByRole('button', { name: 'Docs' })) - - await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Error', 'error', undefined)) - }) - - it('FE-W5ROW-017: an uncategorized item marks the default list as current', () => { - const { container } = setup({ - item: buildPackingItem({ id: 1, name: 'Soap', category: null }), - categories: ['Other', 'Gear'], - }) - openMoveToList(container) - - expect(screen.getByRole('button', { name: 'Other' })).toHaveStyle({ background: 'var(--bg-tertiary)' }) - expect(screen.getByRole('button', { name: 'Gear' })).not.toHaveStyle({ background: 'var(--bg-tertiary)' }) - }) -}) - -describe('ArtikelZeile — sharing badges', () => { - it('FE-W5ROW-018: an item somebody else brings shows their name in the TREK tooltip', async () => { +describe('ArtikelZeile — badges', () => { + it('FE-W5ROW-008: an item somebody else takes care of shows their name in the tooltip', async () => { setup({ item: buildPackingItem({ id: 1, name: 'Stove', is_private: 1, owner_id: 2, owner_username: 'Bob' } as Partial), currentUserId: 1, }) - const badge = screen.getByLabelText('by Bob') - expect(badge).not.toHaveAttribute('title') fireEvent.mouseEnter(badge) expect(await screen.findByRole('tooltip')).toHaveTextContent('by Bob') }) - it('FE-W5ROW-019: a nameless bringer degrades to an empty name', () => { + it('FE-W5ROW-009: a nameless owner degrades to an empty name', () => { setup({ item: buildPackingItem({ id: 1, name: 'Stove', is_private: 1, owner_id: 2, owner_username: null } as Partial), currentUserId: 1, }) - expect(screen.getByLabelText('by')).toBeInTheDocument() }) - it('FE-W5ROW-020: an item shared by me counts its recipients', async () => { + it('FE-W5ROW-010: an item shared by me counts its recipients', async () => { setup({ item: buildPackingItem({ id: 1, name: 'Stove', is_private: 1, owner_id: 1, @@ -408,13 +144,12 @@ describe('ArtikelZeile — sharing badges', () => { } as unknown as Partial), currentUserId: 1, }) - expect(screen.getByLabelText('shared with 2')).toHaveTextContent('2') fireEvent.mouseEnter(screen.getByLabelText('shared with 2')) expect(await screen.findByRole('tooltip')).toHaveTextContent('shared with 2: alice, bob') }) - it('FE-W5ROW-021: a common item names its bringer and counts co-bringers', async () => { + it('FE-W5ROW-011: a common item shows its bringer and counts the others', async () => { setup({ item: buildPackingItem({ id: 1, name: 'Stove', is_private: 0, owner_username: 'Bob', @@ -422,58 +157,137 @@ describe('ArtikelZeile — sharing badges', () => { } as unknown as Partial), currentUserId: 1, }) - - // The bringer's initial on an avatar, the co-bringers as a "+N" circle; the tooltip - // names everyone, each on a line of their own (#2782). const badge = screen.getByLabelText('brought by Bob, cleo') expect(badge).toHaveTextContent('B+1') fireEvent.mouseEnter(badge) const rows = within(await screen.findByRole('tooltip')).getAllByRole('listitem') - expect(rows).toHaveLength(2) - expect(rows[0]).toHaveTextContent('Bob') - expect(rows[1]).toHaveTextContent('cleo') + expect(rows.map(r => r.textContent)).toEqual(['Bob', 'cleo']) }) - it('FE-W5ROW-022: a bringer without co-bringers shows no counter', () => { + it('FE-W5ROW-012: co-bringers alone still show, without an owner', () => { setup({ - item: buildPackingItem({ id: 1, name: 'Stove', is_private: 0, owner_username: 'Bob' } as Partial), - currentUserId: 1, - }) - - expect(screen.getByLabelText('brought by Bob')).toHaveTextContent(/^B$/) - }) - - it('FE-W5ROW-023: the placeholder row carries no badges and no share control', () => { - setup({ - item: buildPackingItem({ id: 1, name: '...', is_private: 0, owner_username: 'Bob' } as Partial), - currentUserId: 1, - onSetSharing: () => {}, - onClone: () => {}, - onJoin: () => {}, - onLeave: () => {}, - }) - - expect(screen.queryByTitle('brought by Bob')).toBeNull() - expect(screen.queryByTitle('Sharing')).toBeNull() - }) - - it('FE-W5ROW-024: the share control is wired up for an editable item', () => { - const onSetSharing = vi.fn() - const { container } = setup({ - currentUserId: 1, + item: buildPackingItem({ id: 1, name: 'Stove', is_private: 0, owner_id: null, owner_username: null, contributors: [{ user_id: 2, username: 'alice' }] } as unknown as Partial), tripMembers: MEMBERS, - onSetSharing, - onClone: () => {}, - onJoin: () => {}, - onLeave: () => {}, }) + expect(screen.getByLabelText('brought by alice')).toHaveTextContent(/^A$/) + }) - // Sharing lives in the item menu, as a whole line to click. - fireEvent.click(overflowTrigger(container)) - fireEvent.click(menu(container).getByText('Sharing').closest('button')!) - fireEvent.click(screen.getByText(/^Personal$/)) + it('FE-W5ROW-013: a private item shows no bringer faces', () => { + setup({ item: buildPackingItem({ id: 1, name: 'Diary', is_private: 1, owner_id: 1, owner_username: 'owner' } as Partial), currentUserId: 1 }) + expect(screen.queryByLabelText(/brought by/)).toBeNull() + }) +}) - expect(onSetSharing).toHaveBeenCalledWith(1, 'personal', []) +describe('ArtikelZeile — the placeholder of a new list', () => { + it('FE-W5ROW-014: the placeholder row is typed into right away', () => { + setup({ item: buildPackingItem({ id: 1, name: '...', category: 'Gear' }) }) + expect(screen.getByPlaceholderText('...')).toHaveValue('') + expect(screen.queryByRole('button', { name: '...' })).toBeNull() + }) + + it('FE-W5ROW-015: Escape and a blank blur leave the placeholder as it was', async () => { + let saved = false + server.use(http.put('/api/trips/1/packing/1', () => { saved = true; return HttpResponse.json({ item: buildPackingItem({ id: 1 }) }) })) + setup({ item: buildPackingItem({ id: 1, name: '...', category: 'Gear' }) }) + const input = screen.getByPlaceholderText('...') + + fireEvent.change(input, { target: { value: 'Tent' } }) + fireEvent.keyDown(input, { key: 'Escape' }) + expect(input).toHaveValue('') + fireEvent.change(input, { target: { value: ' ' } }) + fireEvent.blur(input) + + await waitFor(() => expect(input).toHaveValue('')) + expect(saved).toBe(false) + }) + + it('FE-W5ROW-016: Enter on a filled placeholder hands the typing on, a blur does not (#2825)', async () => { + server.use(http.put('/api/trips/1/packing/1', () => HttpResponse.json({ item: buildPackingItem({ id: 1, name: 'Tent' }) }))) + const onPlaceholderFilled = vi.fn() + setup({ item: buildPackingItem({ id: 1, name: '...', category: 'Gear' }), onPlaceholderFilled }) + const input = screen.getByPlaceholderText('...') + + fireEvent.change(input, { target: { value: 'Tent' } }) + fireEvent.blur(input) + await waitFor(() => expect(toastSpy).not.toHaveBeenCalled()) + expect(onPlaceholderFilled).not.toHaveBeenCalled() + + fireEvent.change(input, { target: { value: 'Tarp' } }) + fireEvent.keyDown(input, { key: 'Enter' }) + await waitFor(() => expect(onPlaceholderFilled).toHaveBeenCalledTimes(1)) + }) + + it('FE-W5ROW-017: a failing placeholder save surfaces a save error', async () => { + server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 }))) + setup({ item: buildPackingItem({ id: 1, name: '...', category: 'Gear' }) }) + const input = screen.getByPlaceholderText('...') + fireEvent.change(input, { target: { value: 'Tent' } }) + fireEvent.keyDown(input, { key: 'Enter' }) + await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined)) + }) + + it('FE-W5ROW-018: a read-only placeholder just shows its dots', () => { + setup({ item: buildPackingItem({ id: 1, name: '...', category: 'Gear' }), canEdit: false }) + expect(screen.queryByPlaceholderText('...')).toBeNull() + expect(screen.getByText('...')).toBeInTheDocument() + }) +}) + +describe('ArtikelZeile — the item window', () => { + it('FE-W5ROW-019: a click on the name opens the window and the row marks itself', () => { + const { container } = setup() + const trigger = screen.getByRole('button', { name: /Tent/ }) + expect(trigger).toHaveAttribute('aria-expanded', 'false') + + const dialog = openWindow() + expect(dialog.getByDisplayValue('Tent')).toBeInTheDocument() + expect(trigger).toHaveAttribute('aria-expanded', 'true') + expect(row(container).style.boxShadow).toBe('inset 0 0 0 1px var(--border-primary)') + }) + + it('FE-W5ROW-020: the close button, the backdrop and Escape all close it', () => { + setup() + fireEvent.click(openWindow().getByRole('button', { name: 'Close' })) + expect(screen.queryByRole('dialog')).toBeNull() + + openWindow() + fireEvent.click(document.querySelector('[role="presentation"]')!) + expect(screen.queryByRole('dialog')).toBeNull() + + fireEvent.keyDown(openWindow().getByDisplayValue('Tent'), { key: 'Escape' }) + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('FE-W5ROW-021: Delete in the window goes to the panel handler when there is one', async () => { + const onDelete = vi.fn(async () => {}) + const { props } = setup({ onDelete }) + fireEvent.click(openWindow().getByRole('button', { name: 'Delete' })) + await waitFor(() => expect(onDelete).toHaveBeenCalledWith(props.item)) + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('FE-W5ROW-022: a standalone row deletes through the store', async () => { + let deleted = false + server.use(http.delete('/api/trips/1/packing/1', () => { deleted = true; return HttpResponse.json({ success: true }) })) + seedStore(useTripStore, { trip: buildTrip({ id: 1 }), packingItems: [buildPackingItem({ id: 1, name: 'Tent' })] }) + setup() + fireEvent.click(openWindow().getByRole('button', { name: 'Delete' })) + await waitFor(() => expect(deleted).toBe(true)) + }) + + it('FE-W5ROW-023: a failing standalone delete surfaces a delete error', async () => { + server.use(http.delete('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 }))) + seedStore(useTripStore, { trip: buildTrip({ id: 1 }), packingItems: [buildPackingItem({ id: 1, name: 'Tent' })] }) + setup() + fireEvent.click(openWindow().getByRole('button', { name: 'Delete' })) + await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to delete', 'error', undefined)) + }) + + it('FE-W5ROW-024: a read-only window shows the name as text and offers no delete', () => { + setup({ canEdit: false }) + const dialog = openWindow() + expect(dialog.queryByRole('textbox')).toBeNull() + expect(dialog.queryByRole('button', { name: 'Delete' })).toBeNull() }) }) @@ -494,644 +308,52 @@ describe('ArtikelZeile — drag handle', () => { fireEvent.dragStart(handle, { dataTransfer: dt() }) expect(d.onStart).toHaveBeenCalledWith(1) - fireEvent.dragEnd(handle) expect(d.onEnd).toHaveBeenCalled() }) - it('FE-W5ROW-026: dragging over the row marks it as the drop target', () => { + it('FE-W5ROW-026: dragging over the row marks it, dropping reports the target', () => { const d = drag() const { container } = setup({ drag: d }) - const row = container.querySelector('.packing-item-row')! - - fireEvent.dragOver(row, { dataTransfer: dt() }) + fireEvent.dragOver(row(container), { dataTransfer: dt() }) expect(d.onOver).toHaveBeenCalledWith(1) + fireEvent.drop(row(container), { dataTransfer: dt() }) + expect(d.onDrop).toHaveBeenCalledWith(1) }) it('FE-W5ROW-027: leaving the row clears the drop target, but moving inside it does not', () => { const d = drag() const { container } = setup({ drag: d }) - const row = container.querySelector('.packing-item-row')! - const leave = (relatedTarget: Node) => - fireEvent(row, new MouseEvent('dragleave', { bubbles: true, relatedTarget })) + const leave = (relatedTarget: Node) => fireEvent(row(container), new MouseEvent('dragleave', { bubbles: true, relatedTarget })) leave(document.body) expect(d.onOver).toHaveBeenCalledWith(-1) - d.onOver.mockClear() leave(screen.getByText('Tent')) expect(d.onOver).not.toHaveBeenCalled() }) - it('FE-W5ROW-028: dropping on the row reports the target id', () => { - const d = drag() - const { container } = setup({ drag: d }) - - fireEvent.drop(container.querySelector('.packing-item-row')!, { dataTransfer: dt() }) - - expect(d.onDrop).toHaveBeenCalledWith(1) - }) - - it('FE-W5ROW-029: the dragged row fades and the hovered row shows an edge', () => { + it('FE-W5ROW-028: the dragged row fades and the hovered row shows an edge', () => { const { container } = setup({ drag: { ...drag(), isDragging: true, isOver: true } }) - const row = container.querySelector('.packing-item-row')! - - expect(row.style.opacity).toBe('0.4') - expect(row.style.boxShadow).toBe('inset 3px 0 0 0 var(--accent)') + expect(row(container).style.opacity).toBe('0.4') + expect(row(container).style.boxShadow).toBe('inset 3px 0 0 0 var(--accent)') }) - it('FE-W5ROW-030: hovering the row brings the grip to full opacity', () => { + it('FE-W5ROW-029: the grip only shows under the pointer', () => { const { container } = setup({ drag: drag() }) - const row = container.querySelector('.packing-item-row')! const handle = container.querySelector('div[draggable="true"]')! - - expect(handle.style.opacity).toBe('0.35') - fireEvent.mouseEnter(row) + expect(handle.style.opacity).toBe('0') + fireEvent.mouseEnter(row(container)) expect(handle.style.opacity).toBe('1') }) - it('FE-W5ROW-031: a placeholder row is not draggable', () => { - const { container } = setup({ item: buildPackingItem({ id: 1, name: '...' }), drag: drag() }) - + it('FE-W5ROW-030: a placeholder or read-only row is not draggable, a sorted row keeps the grip column', () => { + const { container, unmount } = setup({ item: buildPackingItem({ id: 1, name: '...' }), drag: drag() }) expect(container.querySelector('div[draggable="true"]')).toBeNull() - }) -}) - -describe('ArtikelZeile — weight and bag', () => { - it('FE-W5ROW-032: entering a weight saves it in grams', async () => { - let body: Record | null = null - server.use( - http.put('/api/trips/1/packing/1', async ({ request }) => { - body = (await request.json()) as Record - return HttpResponse.json({ item: buildPackingItem({ id: 1 }) }) - }), - ) - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS }) - - const weightField = container.querySelector('input[placeholder="—"]')! - fireEvent.change(weightField, { target: { value: '450' } }) - fireEvent.blur(weightField) - - await waitFor(() => expect(body).toMatchObject({ weight_grams: 450 })) - }) - - it('FE-W5ROW-033: clearing the weight stores null', async () => { - let body: Record | null = null - server.use( - http.put('/api/trips/1/packing/1', async ({ request }) => { - body = (await request.json()) as Record - return HttpResponse.json({ item: buildPackingItem({ id: 1 }) }) - }), - ) - const { container } = setup({ - item: buildPackingItem({ id: 1, name: 'Tent', weight_grams: 300 } as Partial), - bagTrackingEnabled: true, - }) - - const weightField = container.querySelector('input[placeholder="—"]')! - fireEvent.change(weightField, { target: { value: '' } }) - fireEvent.blur(weightField) - - await waitFor(() => expect(body).toMatchObject({ weight_grams: null })) - }) - - it('FE-W5ROW-034: a failing weight save surfaces a save error', async () => { - server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 }))) - const { container } = setup({ bagTrackingEnabled: true }) - - const weightField = container.querySelector('input[placeholder="—"]')! - fireEvent.change(weightField, { target: { value: '450' } }) - fireEvent.blur(weightField) - - await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined)) - }) - - it('FE-W5ROW-035: a read-only row ignores weight edits and never opens the bag picker', async () => { - let called = false - server.use(http.put('/api/trips/1/packing/1', () => { called = true; return HttpResponse.json({ item: buildPackingItem() }) })) - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS, canEdit: false }) - - const weight = container.querySelector('input[placeholder="—"]')! - expect(weight.readOnly).toBe(true) - fireEvent.change(weight, { target: { value: '450' } }) - fireEvent.blur(weight) - fireEvent.click(bagButton(container)) - - await waitFor(() => expect(screen.queryByRole('button', { name: /Carry-on/ })).toBeNull()) - expect(called).toBe(false) - }) - - it('FE-W5ROW-036: picking a bag assigns it', async () => { - let body: Record | null = null - server.use( - http.put('/api/trips/1/packing/1', async ({ request }) => { - body = (await request.json()) as Record - return HttpResponse.json({ item: buildPackingItem({ id: 1 }) }) - }), - ) - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS }) - fireEvent.click(bagButton(container)) - - fireEvent.click(screen.getByRole('button', { name: 'Trolley' })) - - await waitFor(() => expect(body).toMatchObject({ bag_id: 8 })) - }) - - it('FE-W5ROW-037: a failing bag assign surfaces a save error', async () => { - server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 }))) - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS }) - fireEvent.click(bagButton(container)) - - fireEvent.click(screen.getByRole('button', { name: 'Trolley' })) - - await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined)) - }) - - it('FE-W5ROW-038: only an assigned item offers the Unassigned entry, which clears the bag', async () => { - let body: Record | null = null - server.use( - http.put('/api/trips/1/packing/1', async ({ request }) => { - body = (await request.json()) as Record - return HttpResponse.json({ item: buildPackingItem({ id: 1 }) }) - }), - ) - const unassigned = setup({ bagTrackingEnabled: true, bags: BAGS }) - fireEvent.click(bagButton(unassigned.container)) - expect(screen.queryByRole('button', { name: 'Unassigned' })).toBeNull() - unassigned.unmount() - - const { container } = setup({ - item: buildPackingItem({ id: 1, name: 'Tent', bag_id: 7 } as Partial), - bagTrackingEnabled: true, - bags: BAGS, - }) - fireEvent.click(bagButton(container)) - fireEvent.click(screen.getByRole('button', { name: 'Unassigned' })) - - await waitFor(() => expect(body).toMatchObject({ bag_id: null })) - }) - - it('FE-W5ROW-039: a failing clear surfaces a save error', async () => { - server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 }))) - const { container } = setup({ - item: buildPackingItem({ id: 1, name: 'Tent', bag_id: 7 } as Partial), - bagTrackingEnabled: true, - bags: BAGS, - }) - fireEvent.click(bagButton(container)) - - fireEvent.click(screen.getByRole('button', { name: 'Unassigned' })) - - await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined)) - }) - - it('FE-W5ROW-040: only the unselected bag entries react to hover', () => { - const { container } = setup({ - item: buildPackingItem({ id: 1, name: 'Tent', bag_id: 7 } as Partial), - bagTrackingEnabled: true, - bags: BAGS, - }) - fireEvent.click(bagButton(container)) - const selected = screen.getByRole('button', { name: 'Carry-on' }) - const other = screen.getByRole('button', { name: 'Trolley' }) - - fireEvent.mouseEnter(other) - expect(other.style.background).toBe('var(--bg-tertiary)') - fireEvent.mouseLeave(other) - expect(other.style.background).toBe('none') - - fireEvent.mouseEnter(selected) - fireEvent.mouseLeave(selected) - expect(selected.style.background).toBe('var(--bg-tertiary)') - }) - - it('FE-W5ROW-040a: hovering the selected bag entry leaves it untouched', () => { - const { container } = setup({ - item: buildPackingItem({ id: 1, name: 'Tent', bag_id: 7 } as Partial), - bagTrackingEnabled: true, - bags: BAGS, - }) - fireEvent.click(bagButton(container)) - const selected = screen.getByRole('button', { name: 'Carry-on' }) - - fireEvent.mouseEnter(selected) - expect(selected.style.background).toBe('var(--bg-tertiary)') - fireEvent.mouseLeave(selected) - expect(selected.style.background).toBe('var(--bg-tertiary)') - }) - - it('FE-W5ROW-040b: a bag id the trip no longer knows falls back to the neutral border', () => { - const { container } = setup({ - item: buildPackingItem({ id: 1, name: 'Tent', bag_id: 99 } as Partial), - bagTrackingEnabled: true, - bags: BAGS, - }) - - const trigger = bagButton(container) - expect(trigger.style.border).toBe('2.5px solid var(--border-primary)') - expect(trigger.style.background).toBe('var(--border-primary)30') - }) - - it('FE-W5ROW-041: creating a bag inline assigns it right away', async () => { - const created = { id: 12, name: 'Duffel', color: '#f97316' } as unknown as PackingBag - const onCreateBag = vi.fn(async () => created) - let body: Record | null = null - server.use( - http.put('/api/trips/1/packing/1', async ({ request }) => { - body = (await request.json()) as Record - return HttpResponse.json({ item: buildPackingItem({ id: 1 }) }) - }), - ) - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS, onCreateBag }) - fireEvent.click(bagButton(container)) - fireEvent.click(screen.getByText('Add bag')) - - const input = screen.getByPlaceholderText('Bag name...') - fireEvent.change(input, { target: { value: ' Duffel ' } }) - fireEvent.keyDown(input, { key: 'Enter' }) - - await waitFor(() => expect(onCreateBag).toHaveBeenCalledWith('Duffel')) - await waitFor(() => expect(body).toMatchObject({ bag_id: 12 })) - }) - - it('FE-W5ROW-042: Enter on a blank inline name creates nothing', () => { - const onCreateBag = vi.fn(async () => undefined) - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS, onCreateBag }) - fireEvent.click(bagButton(container)) - fireEvent.click(screen.getByText('Add bag')) - - fireEvent.keyDown(screen.getByPlaceholderText('Bag name...'), { key: 'Enter' }) - - expect(onCreateBag).not.toHaveBeenCalled() - }) - - it('FE-W5ROW-043: Escape cancels the inline bag form', () => { - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS }) - fireEvent.click(bagButton(container)) - fireEvent.click(screen.getByText('Add bag')) - - fireEvent.keyDown(screen.getByPlaceholderText('Bag name...'), { key: 'Escape' }) - - expect(screen.queryByPlaceholderText('Bag name...')).toBeNull() - expect(screen.getByText('Add bag')).toBeInTheDocument() - }) - - it('FE-W5ROW-044: the inline confirm button creates the bag, and is inert while blank', async () => { - const created = { id: 13, name: 'Crate', color: '#f97316' } as unknown as PackingBag - const onCreateBag = vi.fn(async () => created) - server.use(http.put('/api/trips/1/packing/1', () => HttpResponse.json({ item: buildPackingItem({ id: 1 }) }))) - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS, onCreateBag }) - fireEvent.click(bagButton(container)) - fireEvent.click(screen.getByText('Add bag')) - const confirm = screen.getByPlaceholderText('Bag name...').nextElementSibling as HTMLButtonElement - - fireEvent.click(confirm) - expect(onCreateBag).not.toHaveBeenCalled() - - fireEvent.change(screen.getByPlaceholderText('Bag name...'), { target: { value: 'Crate' } }) - fireEvent.click(confirm) - - await waitFor(() => expect(onCreateBag).toHaveBeenCalledWith('Crate')) - }) - - it('FE-W5ROW-045: a rejected bag creation leaves the item unassigned', async () => { - const onCreateBag = vi.fn(async () => undefined) - let called = false - server.use(http.put('/api/trips/1/packing/1', () => { called = true; return HttpResponse.json({ item: buildPackingItem() }) })) - const { container } = setup({ bagTrackingEnabled: true, bags: [], onCreateBag }) - fireEvent.click(bagButton(container)) - fireEvent.click(screen.getByText('Add bag')) - - const input = screen.getByPlaceholderText('Bag name...') - fireEvent.change(input, { target: { value: 'Duffel' } }) - fireEvent.keyDown(input, { key: 'Enter' }) - - await waitFor(() => expect(onCreateBag).toHaveBeenCalled()) - await waitFor(() => expect(screen.queryByPlaceholderText('Bag name...')).toBeNull()) - expect(called).toBe(false) - }) - - it('FE-W5ROW-045a: a failing assign after an inline create surfaces a save error', async () => { - const created = { id: 14, name: 'Duffel', color: '#f97316' } as unknown as PackingBag - const onCreateBag = vi.fn(async () => created) - server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 }))) - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS, onCreateBag }) - fireEvent.click(bagButton(container)) - fireEvent.click(screen.getByText('Add bag')) - - const input = screen.getByPlaceholderText('Bag name...') - fireEvent.change(input, { target: { value: 'Duffel' } }) - fireEvent.keyDown(input, { key: 'Enter' }) - - await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined)) - }) - - it('FE-W5ROW-045b: the confirm button also reports a failing assign', async () => { - const created = { id: 15, name: 'Crate', color: '#f97316' } as unknown as PackingBag - const onCreateBag = vi.fn(async () => created) - server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 }))) - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS, onCreateBag }) - fireEvent.click(bagButton(container)) - fireEvent.click(screen.getByText('Add bag')) - const confirm = screen.getByPlaceholderText('Bag name...').nextElementSibling as HTMLButtonElement - - fireEvent.change(screen.getByPlaceholderText('Bag name...'), { target: { value: 'Crate' } }) - fireEvent.click(confirm) - - await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined)) - }) - - it('FE-W5ROW-045c: the confirm button closes the form when creation is refused', async () => { - const onCreateBag = vi.fn(async () => undefined) - let called = false - server.use(http.put('/api/trips/1/packing/1', () => { called = true; return HttpResponse.json({ item: buildPackingItem() }) })) - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS, onCreateBag }) - fireEvent.click(bagButton(container)) - fireEvent.click(screen.getByText('Add bag')) - const confirm = screen.getByPlaceholderText('Bag name...').nextElementSibling as HTMLButtonElement - - fireEvent.change(screen.getByPlaceholderText('Bag name...'), { target: { value: 'Crate' } }) - fireEvent.click(confirm) - - await waitFor(() => expect(screen.queryByPlaceholderText('Bag name...')).toBeNull()) - expect(called).toBe(false) - }) - - it('FE-W5ROW-046: the Add bag entry highlights on hover', () => { - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS }) - fireEvent.click(bagButton(container)) - const add = screen.getByText('Add bag').closest('button')! - - fireEvent.mouseEnter(add) - expect(add.style.background).toBe('var(--bg-tertiary)') - fireEvent.mouseLeave(add) - expect(add.style.background).toBe('none') - }) -}) - -describe('ArtikelZeile — overflow menu', () => { - it('FE-W5ROW-047: the menu renames and closes', () => { - const { container } = setup() - fireEvent.click(overflowTrigger(container)) - - fireEvent.click(screen.getByText('Rename')) - - expect(screen.getByDisplayValue('Tent')).toBeInTheDocument() - expect(screen.queryByText('Delete')).toBeNull() - }) - - it('FE-W5ROW-048: the menu deletes through the panel handler', async () => { - const onDelete = vi.fn(async () => {}) - const { container, props } = setup({ onDelete }) - fireEvent.click(overflowTrigger(container)) - - fireEvent.click(screen.getByText('Delete')) - - await waitFor(() => expect(onDelete).toHaveBeenCalledWith(props.item)) - }) - - it('FE-W5ROW-049: the scrim closes the menu', () => { - const { container, baseElement } = setup() - fireEvent.click(overflowTrigger(container)) - expect(screen.getByText('Qty')).toBeInTheDocument() - - fireEvent.click(baseElement.querySelector('div[style*="z-index: 1098"]')!) - - expect(screen.queryByText('Qty')).toBeNull() - }) - - it('FE-W5ROW-050: the menu commits a new quantity', async () => { - let body: Record | null = null - server.use( - http.put('/api/trips/1/packing/1', async ({ request }) => { - body = (await request.json()) as Record - return HttpResponse.json({ item: buildPackingItem({ id: 1, quantity: 4 }) }) - }), - ) - const { container } = setup({ item: buildPackingItem({ id: 1, name: 'Tent', quantity: null } as Partial) }) - fireEvent.click(overflowTrigger(container)) - - const qty = fieldOf(container, 'Qty') - fireEvent.change(qty, { target: { value: '4' } }) - fireEvent.blur(qty) - - await waitFor(() => expect(body).toMatchObject({ quantity: 4 })) - }) - - it('FE-W5ROW-051: the menu saves a weight and reassigns the bag', async () => { - const bodies: Record[] = [] - server.use( - http.put('/api/trips/1/packing/1', async ({ request }) => { - bodies.push((await request.json()) as Record) - return HttpResponse.json({ item: buildPackingItem({ id: 1 }) }) - }), - ) - const { container } = setup({ - item: buildPackingItem({ id: 1, name: 'Tent', bag_id: 7 } as Partial), - bagTrackingEnabled: true, - bags: BAGS, - }) - fireEvent.click(overflowTrigger(container)) - - const weight = fieldOf(container, 'Total weight') - fireEvent.change(weight, { target: { value: '900' } }) - fireEvent.blur(weight) - await waitFor(() => expect(bodies[0]).toMatchObject({ weight_grams: 900 })) - - // The first entry mirrors the current bag and clears it when tapped. - fireEvent.click(menu(container).getAllByRole('button', { name: 'Carry-on', hidden: true })[0]) - await waitFor(() => expect(bodies[1]).toMatchObject({ bag_id: null })) - - fireEvent.click(menuButton(container, 'Trolley')) - await waitFor(() => expect(bodies[2]).toMatchObject({ bag_id: 8 })) - }) - - it('FE-W5ROW-052: a failing menu weight or bag change surfaces a save error', async () => { - server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 }))) - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS }) - fireEvent.click(overflowTrigger(container)) - - fireEvent.change(fieldOf(container, 'Total weight'), { target: { value: '900' } }) - fireEvent.blur(fieldOf(container, 'Total weight')) - - await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined)) - - toastSpy.mockClear() - fireEvent.click(menuButton(container, 'Trolley')) - await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined)) - }) - - it('FE-W5ROW-053: an unassigned item shows the Unassigned row without firing a request', async () => { - let called = false - server.use(http.put('/api/trips/1/packing/1', () => { called = true; return HttpResponse.json({ item: buildPackingItem() }) })) - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS }) - fireEvent.click(overflowTrigger(container)) - - fireEvent.click(menuButton(container, 'Unassigned')) - - await waitFor(() => expect(menu(container).getByText('Total weight')).toBeInTheDocument()) - expect(called).toBe(false) - }) - - it('FE-W5ROW-053a: a failing clear from the menu surfaces a save error', async () => { - server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 }))) - const { container } = setup({ - item: buildPackingItem({ id: 1, name: 'Tent', bag_id: 7 } as Partial), - bagTrackingEnabled: true, - bags: BAGS, - }) - fireEvent.click(overflowTrigger(container)) - - fireEvent.click(menu(container).getAllByRole('button', { name: 'Carry-on', hidden: true })[0]) - - await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined)) - }) - - it('FE-W5ROW-053b: clearing the menu weight stores null', async () => { - let body: Record | null = null - server.use( - http.put('/api/trips/1/packing/1', async ({ request }) => { - body = (await request.json()) as Record - return HttpResponse.json({ item: buildPackingItem({ id: 1 }) }) - }), - ) - const { container } = setup({ - item: buildPackingItem({ id: 1, name: 'Tent', weight_grams: 400 } as Partial), - bagTrackingEnabled: true, - bags: BAGS, - }) - fireEvent.click(overflowTrigger(container)) - - fireEvent.change(fieldOf(container, 'Total weight'), { target: { value: '' } }) - fireEvent.blur(fieldOf(container, 'Total weight')) - - await waitFor(() => expect(body).toMatchObject({ weight_grams: null })) - }) - - it('FE-W5ROW-054: the menu list submenu moves the item and can be collapsed again', async () => { - let body: Record | null = null - server.use( - http.put('/api/trips/1/packing/1', async ({ request }) => { - body = (await request.json()) as Record - return HttpResponse.json({ item: buildPackingItem({ id: 1, category: 'Docs' }) }) - }), - ) - const { container } = setup() - fireEvent.click(overflowTrigger(container)) - - fireEvent.click(menuButton(container, 'Move to List')) - expect(menuButton(container, 'Docs')).toBeInTheDocument() - - fireEvent.click(menuButton(container, 'Move to List')) - expect(menu(container).queryByRole('button', { name: 'Docs', hidden: true })).toBeNull() - - fireEvent.click(menuButton(container, 'Move to List')) - fireEvent.click(menuButton(container, 'Docs')) - - await waitFor(() => expect(body).toMatchObject({ category: 'Docs' })) - }) - - it('FE-W5ROW-054a: an uncategorized item marks the default list in the submenu', () => { - const { container } = setup({ - item: buildPackingItem({ id: 1, name: 'Soap', category: null }), - categories: ['Other', 'Gear'], - }) - fireEvent.click(overflowTrigger(container)) - fireEvent.click(menuButton(container, 'Move to List')) - - expect(menuButton(container, 'Other')).toHaveStyle({ background: 'var(--bg-tertiary)' }) - expect(menuButton(container, 'Gear')).not.toHaveStyle({ background: 'var(--bg-tertiary)' }) - }) - - it('FE-W5ROW-055: the menu carries its own share control', () => { - const onSetSharing = vi.fn() - const { container } = setup({ - currentUserId: 1, - tripMembers: MEMBERS, - onSetSharing, - onClone: () => {}, - onJoin: () => {}, - onLeave: () => {}, - }) - fireEvent.click(overflowTrigger(container)) - - fireEvent.click(menu(container).getByText('Sharing').closest('button')!) - fireEvent.click(screen.getByText(/^Personal$/)) - - expect(onSetSharing).toHaveBeenCalledWith(1, 'personal', []) - }) - - it('FE-W5ROW-056: menu entries highlight on hover, the active one stays put', () => { - const { container } = setup({ bagTrackingEnabled: true, bags: BAGS }) - fireEvent.click(overflowTrigger(container)) - fireEvent.click(menuButton(container, 'Move to List')) - // "Gear" is the item's current list, so its submenu entry renders as active. - const active = menuButton(container, 'Gear') - const plain = menuButton(container, 'Carry-on') - const danger = menu(container).getByText('Delete').closest('button')! - - fireEvent.mouseEnter(plain) - expect(plain.style.background).toBe('var(--bg-tertiary)') - fireEvent.mouseLeave(plain) - expect(plain.style.background).toBe('none') - - fireEvent.mouseEnter(active) - fireEvent.mouseLeave(active) - expect(active.style.background).toBe('var(--bg-tertiary)') - - fireEvent.mouseEnter(danger) - expect(danger.style.background).toBe('rgba(239, 68, 68, 0.1)') - }) -}) - -describe('ArtikelZeile — who brings a common item (#3098)', () => { - const handlers = () => ({ onSetSharing: vi.fn(), onClone: vi.fn(), onJoin: vi.fn(), onLeave: vi.fn() }) - - it('FE-W5ROW-057: the item menu lists every member and ticks one on as a bringer', () => { - const h = handlers() - const { container } = setup({ currentUserId: 1, tripMembers: MEMBERS, ...h }) - - fireEvent.click(overflowTrigger(container)) - fireEvent.click(menuButton(container, 'Brought by')) - fireEvent.click(menuButton(container, 'alice')) - - expect(h.onJoin).toHaveBeenCalledWith(1, 2) - expect(h.onLeave).not.toHaveBeenCalled() - }) - - it('FE-W5ROW-058: a ticked bringer, the owner included, comes off again', () => { - const h = handlers() - const { container } = setup({ - item: buildPackingItem({ - id: 1, name: 'Stove', is_private: 0, owner_id: 1, owner_username: 'owner', - contributors: [{ user_id: 2, username: 'alice' }], - } as unknown as Partial), - currentUserId: 1, tripMembers: MEMBERS, ...h, - }) - - fireEvent.click(overflowTrigger(container)) - fireEvent.click(menuButton(container, 'Brought by')) - fireEvent.click(menuButton(container, 'owner')) - fireEvent.click(menuButton(container, 'alice')) - - expect(h.onLeave).toHaveBeenNthCalledWith(1, 1, 1) - expect(h.onLeave).toHaveBeenNthCalledWith(2, 1, 2) - expect(h.onJoin).not.toHaveBeenCalled() - }) - - it('FE-W5ROW-059: a click on the faces opens the menu at the bringers, also when only co-bringers are left', () => { - const { container } = setup({ - item: buildPackingItem({ - id: 1, name: 'Stove', is_private: 0, owner_id: null, owner_username: null, - contributors: [{ user_id: 2, username: 'alice' }], - } as unknown as Partial), - currentUserId: 1, tripMembers: MEMBERS, ...handlers(), - }) - - fireEvent.click(screen.getByRole('button', { name: 'brought by alice' })) - - expect(menuButton(container, 'alice')).toBeInTheDocument() - expect(menuButton(container, 'owner')).toBeInTheDocument() + unmount() + const sorted = setup() + expect(sorted.container.querySelector('div[draggable="true"]')).toBeNull() + expect(sorted.container.querySelector('span[aria-hidden][style*="width: 13px"]')).not.toBeNull() }) }) diff --git a/client/src/components/Packing/PackingListPanelItemRow.tsx b/client/src/components/Packing/PackingListPanelItemRow.tsx index 06ac9cc09..9a7bbafda 100644 --- a/client/src/components/Packing/PackingListPanelItemRow.tsx +++ b/client/src/components/Packing/PackingListPanelItemRow.tsx @@ -1,26 +1,16 @@ import { useRef, useState, type CSSProperties } from 'react' -import { createPortal } from 'react-dom' -import { useAnchoredPosition } from '../../hooks/useAnchoredPosition' import { useTripStore } from '../../store/tripStore' import { useToast } from '../shared/Toast' import { useTranslation } from '../../i18n' -import { - Check, Trash2, Plus, Pencil, Package, GripVertical, UserRound, HandHelping, - MoreHorizontal, ChevronDown, ChevronRight, -} from 'lucide-react' +import { Check, GripVertical, UserRound, HandHelping, ChevronRight } from 'lucide-react' import type { PackingItem, PackingBag } from '../../types' -import { katColor, packedOf } from './packingListPanel.helpers' +import { packedOf } from './packingListPanel.helpers' import { PACKING_PLACEHOLDER_NAME } from './packingListPanel.constants' -import { QuantityInput } from './PackingListPanelQuantityInput' -import { PackedCounter } from './PackingPackedCounter' -import PackingShareControl from './PackingShareControl' -import { PopoverItem } from './PackingPopover' -import { POPOVER, POPOVER_CAPTION, POPOVER_DIVIDER } from './packingPopoverStyles' import type { TripMember } from './usePackingListPanel' -import { WeightInput } from './PackingListPanelWeightInput' import { bringersOf, packingBringerNames } from './packingBringers' import { Tooltip } from '../shared/Tooltip' import { BringerAvatar, BringersCard, MoreBringers } from './PackingBringersCard' +import { PackingItemDetail } from './PackingItemDetail' interface ArtikelZeileProps { item: PackingItem @@ -34,7 +24,7 @@ interface ArtikelZeileProps { bags?: PackingBag[] onCreateBag: (name: string) => Promise canEdit?: boolean - // Three-tier sharing (#858): members + handlers for the per-item share control. + // Three-tier sharing (#858): members + handlers for the item's detail window. tripMembers?: TripMember[] currentUserId?: number onSetSharing?: (id: number, visibility: 'common' | 'personal' | 'shared', recipientIds: number[]) => void @@ -54,50 +44,93 @@ interface ArtikelZeileProps { } } -export function ArtikelZeile({ item, tripId, categories, onCategoryChange: _onCategoryChange, onDelete, onPlaceholderFilled, bagTrackingEnabled, bags = [], onCreateBag, canEdit = true, tripMembers = [], currentUserId, onSetSharing, onClone, onJoin, onLeave, divider = false, drag }: ArtikelZeileProps) { - const isPlaceholder = item.name === PACKING_PLACEHOLDER_NAME - const [editing, setEditing] = useState(false) - const [editName, setEditName] = useState(isPlaceholder ? '' : item.name) - const [hovered, setHovered] = useState(false) - // Keyboard focus anywhere in the row counts as hovering it, so every control - // that only shows on hover is also there for someone tabbing through. - const [focused, setFocused] = useState(false) - const [showBagPicker, setShowBagPicker] = useState(false) - // The picker opens in a portal: inside the category card it was cut off by the card's edge. - const bagBtnRef = useRef(null) - const bagBox = useAnchoredPosition(bagBtnRef, showBagPicker, { estimatedHeight: 260, offset: 6 }) - const [showItemMenu, setShowItemMenu] = useState(false) - const [showMenuCategories, setShowMenuCategories] = useState(false) - const [showMenuBringers, setShowMenuBringers] = useState(false) - const [bagInlineCreate, setBagInlineCreate] = useState(false) - const [bagInlineName, setBagInlineName] = useState('') - const itemMenuBtnRef = useRef(null) - const { togglePackingItem, updatePackingItem, deletePackingItem, setPackedCount } = useTripStore() +const nameStyle = (checked: boolean, placeholder: boolean): CSSProperties => ({ + flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', + fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', fontWeight: 500, textAlign: 'start', + color: checked || placeholder ? 'var(--text-faint)' : 'var(--text-primary)', + textDecoration: checked ? 'line-through' : 'none', + transition: 'color 200ms cubic-bezier(0.23,1,0.32,1)', +}) + +/** The '...' row a new list starts with: typed into right here, so the next item follows (#2825). */ +function PlaceholderField({ item, tripId, onFilled }: Readonly<{ item: PackingItem; tripId: number; onFilled?: () => void }>) { + const [name, setName] = useState('') + const updatePackingItem = useTripStore(s => s.updatePackingItem) const toast = useToast() const { t } = useTranslation() - - // Three-tier sharing display (#858). - const sharedToMe = !!item.is_private && item.owner_id != null && item.owner_id !== currentUserId - const recipients = item.recipients || [] - const sharedByMe = !!item.is_private && item.owner_id === currentUserId && recipients.length > 0 - const canShare = canEdit && !isPlaceholder && !!onSetSharing - // Who brings a Common item is anyone's call on the trip, not just a pledge for - // yourself: the menu lists every member to tick on or off (#3098). - const canPickBringers = canEdit && !isPlaceholder && !item.is_private && tripMembers.length > 0 && !!onJoin && !!onLeave - const isBringer = (userId: number) => item.owner_id === userId || (item.contributors || []).some(c => c.user_id === userId) - const toggleBringer = (userId: number) => (isBringer(userId) ? onLeave!(item.id, userId) : onJoin!(item.id, userId)) - const closeItemMenu = () => { setShowItemMenu(false); setShowMenuCategories(false); setShowMenuBringers(false) } - - const handleToggle = () => togglePackingItem(tripId, item.id, !item.checked) - - const handleSaveName = async (viaEnter = false) => { - if (!editName.trim()) { setEditing(false); setEditName(isPlaceholder ? '' : item.name); return } + const save = async (viaEnter: boolean) => { + if (!name.trim()) { setName(''); return } try { - await updatePackingItem(tripId, item.id, { name: editName.trim() }); setEditing(false) - if (viaEnter && isPlaceholder) onPlaceholderFilled?.() - } - catch { toast.error(t('packing.toast.saveError')) } + await updatePackingItem(tripId, item.id, { name: name.trim() }) + if (viaEnter) onFilled?.() + } catch { toast.error(t('packing.toast.saveError')) } } + return ( + setName(e.target.value)} + onBlur={() => void save(false)} + onKeyDown={e => { if (e.key === 'Enter') void save(true); if (e.key === 'Escape') setName('') }} + className="min-w-0 flex-1 rounded-md border border-edge bg-transparent px-2 py-0.5 font-[inherit] text-content outline-none" + style={{ fontSize: 'calc(13.5px * var(--fs-scale-body, 1))' }} /> + ) +} + +/** What the row says about the item at rest: only what is set, never an empty field. */ +function RowFacts({ item, tripMembers, currentUserId }: Readonly<{ item: PackingItem; tripMembers: TripMember[]; currentUserId?: number }>) { + const { t } = useTranslation() + const quantity = item.quantity || 1 + const packed = packedOf(item) + const partly = !item.checked && packed > 0 + const recipients = item.recipients || [] + const sharedToMe = !!item.is_private && item.owner_id != null && item.owner_id !== currentUserId + const sharedByMe = !!item.is_private && item.owner_id === currentUserId && recipients.length > 0 + const bringers = item.is_private ? [] : bringersOf(item, tripMembers) + return ( + <> + {partly && {packed}/{quantity}} + {!partly && quantity > 1 && ×{quantity}} + {sharedToMe && ( + + + + + + )} + {sharedByMe && ( + r.username).join(', ')}`}> + + {recipients.length} + + + )} + {bringers.length > 0 && ( + }> + + + {bringers.length > 1 && } + + + )} + + ) +} + +/** + * One packing item. At rest it shows its box, its name and only what is set + * (the amount from two up, the pieces packed, who brings it); a click anywhere + * past the box opens the item's window with every choice in it. + */ +export function ArtikelZeile({ item, tripId, categories, onDelete, onPlaceholderFilled, bagTrackingEnabled, bags = [], onCreateBag, canEdit = true, tripMembers = [], currentUserId, onSetSharing, onClone, onJoin, onLeave, divider = false, drag }: ArtikelZeileProps) { + const isPlaceholder = item.name === PACKING_PLACEHOLDER_NAME + const [hovered, setHovered] = useState(false) + const [open, setOpen] = useState(false) + const rowRef = useRef(null) + const togglePackingItem = useTripStore(s => s.togglePackingItem) + const deletePackingItem = useTripStore(s => s.deletePackingItem) + const toast = useToast() + const { t } = useTranslation() const handleDelete = async () => { // The panel routes deletion through onDelete so an emptied custom category @@ -107,84 +140,44 @@ export function ArtikelZeile({ item, tripId, categories, onCategoryChange: _onCa catch { toast.error(t('packing.toast.deleteError')) } } - const handleCatChange = async (cat: string) => { - setShowMenuCategories(false) - setShowItemMenu(false) - if (cat === item.category) return - try { await updatePackingItem(tripId, item.id, { category: cat }) } - catch { toast.error(t('common.error')) } - } - - const saveWeight = async (grams: number | null) => { - try { await updatePackingItem(tripId, item.id, { weight_grams: grams }) } catch { toast.error(t('packing.toast.saveError')) } - } - - const canDrag = canEdit && !isPlaceholder && !!drag - const selectedBag = bags.find(b => b.id === item.bag_id) - const quantity = item.quantity || 1 - // A multi-piece item counts its pieces into the bag (#2296). - const packed = packedOf(item) - const partlyPacked = !item.checked && packed > 0 - const bringers = bringersOf(item, tripMembers) - - // At rest a row reads as what it holds (owner, a quantity above one, a - // weight, the bag) and everything else stays in place but dimmed: nothing - // leaves a hole and nothing jumps. Pointer or focus brings it all up. - const active = hovered || focused || showItemMenu || showBagPicker - const reveal = (visible: boolean): CSSProperties => ({ opacity: visible ? 1 : 0.4, transition: 'opacity 120ms ease' }) - // Quantity and weight read as quiet pills; under the pointer an outline - // shows they can be typed into. - const badge = (visible: boolean): CSSProperties => ({ - ...reveal(visible), background: 'var(--bg-tertiary)', borderRadius: 99, padding: '2px 8px', - borderColor: active ? 'var(--border-primary)' : 'transparent', - }) - - // Shared by both shells of the name: a renameable name is a real button so - // the rename can be reached with the keyboard, everything else is plain text. - const nameStyle: CSSProperties = { - flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', - fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', fontWeight: 500, - cursor: canEdit ? 'text' : 'default', - color: isPlaceholder ? 'var(--text-faint)' : (item.checked ? 'var(--text-faint)' : 'var(--text-primary)'), - transition: 'color 200ms cubic-bezier(0.23,1,0.32,1)', - textDecoration: item.checked ? 'line-through' : 'none', - } + // The drag handlers only when this row can be dragged at all. + const dnd = canEdit && !isPlaceholder ? drag : undefined + const partlyPacked = !item.checked && packedOf(item) > 0 + const active = hovered || open return (
setHovered(true)} onMouseLeave={() => setHovered(false)} - onFocus={() => setFocused(true)} - onBlur={e => { if (!e.currentTarget.contains(e.relatedTarget as Node)) setFocused(false) }} - onDragOver={canDrag ? (e => { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; drag!.onOver(item.id) }) : undefined} - onDragLeave={canDrag ? (e => { if (!e.currentTarget.contains(e.relatedTarget as Node)) drag!.onOver(-1) }) : undefined} - onDrop={canDrag ? (e => { e.preventDefault(); e.stopPropagation(); drag!.onDrop(item.id) }) : undefined} + onDragOver={dnd ? (e => { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; dnd.onOver(item.id) }) : undefined} + onDragLeave={dnd ? (e => { if (!e.currentTarget.contains(e.relatedTarget as Node)) dnd.onOver(-1) }) : undefined} + onDrop={dnd ? (e => { e.preventDefault(); e.stopPropagation(); dnd.onDrop(item.id) }) : undefined} style={{ display: 'flex', alignItems: 'center', gap: 9, - padding: '8px 10px', borderRadius: 10, position: 'relative', - background: hovered ? 'var(--bg-secondary)' : 'transparent', + padding: '8px 10px', borderRadius: 10, position: 'relative', minHeight: 40, + background: active ? 'var(--bg-secondary)' : 'transparent', + boxShadow: drag?.isOver ? 'inset 3px 0 0 0 var(--accent)' : (open ? 'inset 0 0 0 1px var(--border-primary)' : 'none'), opacity: drag?.isDragging ? 0.4 : 1, - boxShadow: drag?.isOver ? 'inset 3px 0 0 0 var(--accent)' : 'none', transition: 'background 0.1s, opacity 0.15s', }} > - {divider && !hovered && } - {canDrag && ( + {divider && !active && } + {dnd && (
{ e.stopPropagation(); e.dataTransfer.effectAllowed = 'move'; drag!.onStart(item.id) }} - onDragEnd={() => drag!.onEnd()} - title="" - style={{ cursor: 'grab', display: 'flex', alignItems: 'center', color: 'var(--text-faint)', flexShrink: 0, opacity: hovered ? 1 : 0.35, transition: 'opacity 0.15s' }} + onDragStart={e => { e.stopPropagation(); e.dataTransfer.effectAllowed = 'move'; dnd.onStart(item.id) }} + onDragEnd={() => dnd.onEnd()} + className="flex shrink-0 cursor-grab items-center text-content-faint transition-opacity" + style={{ opacity: hovered ? 1 : 0 }} >
)} {/* Sorted A-Z there is nothing to drag, but the box keeps its column. */} - {!canDrag && canEdit && !isPlaceholder && } - {/* The phone's box: filled with the accent once packed, an outline until then. */} - - {editing && canEdit ? ( - setEditName(e.target.value)} - onBlur={() => void handleSaveName()} - onKeyDown={e => { if (e.key === 'Enter') void handleSaveName(true); if (e.key === 'Escape') { setEditing(false); setEditName(isPlaceholder ? '' : item.name) } }} - style={{ flex: 1, minWidth: 0, fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', padding: '2px 8px', borderRadius: 6, border: '1px solid var(--border-primary)', outline: 'none', fontFamily: 'inherit' }} - /> - ) : canEdit ? ( - + {isPlaceholder && canEdit ? ( + ) : ( - - {item.name} - - )} - - {/* Sharing badges (#858 three-tier), as compact chips like the phone's - (#1525): the full sentence is the tooltip and the accessible name. */} - {!isPlaceholder && sharedToMe && ( - - - - - - )} - {!isPlaceholder && sharedByMe && ( - r.username).join(', ')}`}> - - {recipients.length} - - - )} - {!isPlaceholder && !item.is_private && bringers.length > 0 && ( - }> - {/* A click on the faces opens the menu right at the bringers (#3098). */} - {canPickBringers ? ( - - ) : ( - - - {bringers.length > 1 && } - - )} - - )} - -
- {canEdit && !isPlaceholder && quantity > 1 && ( - setPackedCount(tripId, item.id, count)} style={reveal(active || partlyPacked)} /> - )} - {/* Quantity */} - {canEdit && updatePackingItem(tripId, item.id, { quantity: qty })} style={badge(active || quantity > 1)} />} - - {/* Weight + Bag (when enabled) */} - {bagTrackingEnabled && ( - <> -
- - g -
-
- - {showBagPicker && bagBox && createPortal( - <> -
{ setShowBagPicker(false); setBagInlineCreate(false); setBagInlineName('') }} /> -
-
{t('packing.bags')}
- {item.bag_id && ( - } label={t('packing.noBag')} - onClick={async () => { setShowBagPicker(false); try { await updatePackingItem(tripId, item.id, { bag_id: null }) } catch { toast.error(t('packing.toast.saveError')) } }} /> - )} - {bags.map(b => ( - } label={b.name} active={item.bag_id === b.id} - onClick={async () => { setShowBagPicker(false); try { await updatePackingItem(tripId, item.id, { bag_id: b.id }) } catch { toast.error(t('packing.toast.saveError')) } }} /> - ))} - {bags.length > 0 &&
} - {bagInlineCreate ? ( -
- setBagInlineName(e.target.value)} - onKeyDown={async e => { - if (e.key === 'Enter' && bagInlineName.trim()) { - const newBag = await onCreateBag(bagInlineName.trim()) - if (newBag) { try { await updatePackingItem(tripId, item.id, { bag_id: newBag.id }) } catch { toast.error(t('packing.toast.saveError')) } } - setBagInlineName(''); setBagInlineCreate(false); setShowBagPicker(false) - } - if (e.key === 'Escape') { setBagInlineCreate(false); setBagInlineName('') } - }} - placeholder={t('packing.bagName')} - style={{ flex: 1, minWidth: 0, padding: '6px 9px', borderRadius: 8, border: '1px solid var(--border-primary)', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontFamily: 'inherit', outline: 'none', color: 'var(--text-primary)', background: 'var(--bg-input)' }} /> - -
- ) : ( - } label={t('packing.addBag')} muted onClick={() => setBagInlineCreate(true)} /> - )} -
- , - document.body, - )} -
- - )} -
- - {/* Deleting stays one click away; moving, sharing and renaming live in the - menu next to it, and a click on the name renames as well. */} - {canEdit && ( -
- -
)} - {canEdit && ( -
- - {showItemMenu && (() => { - const rect = itemMenuBtnRef.current?.getBoundingClientRect() - return ( - <> -
-
- {/* Quantity, weight and bag sit in the row itself on a wide screen. */} -
-
- {t('packing.quantity')} - updatePackingItem(tripId, item.id, { quantity: qty })} /> -
- - {bagTrackingEnabled && ( - <> -
-
- {t('packing.totalWeight')} -
- - g -
-
-
- } label={selectedBag?.name || t('packing.noBag')} onClick={async () => { - if (item.bag_id) { - try { await updatePackingItem(tripId, item.id, { bag_id: null }) } catch { toast.error(t('packing.toast.saveError')) } - } - }} /> - {bags.map(b => ( - } label={b.name} active={item.bag_id === b.id} onClick={async () => { - setShowItemMenu(false) - try { await updatePackingItem(tripId, item.id, { bag_id: b.id }) } catch { toast.error(t('packing.toast.saveError')) } - }} /> - ))} -
- - )} - -
-
- } label={t('packing.changeCategory')} onClick={() => setShowMenuCategories(v => !v)} - trailing={showMenuCategories ? : } /> - {showMenuCategories && ( -
- {categories.map(cat => ( - } label={cat} active={cat === (item.category || t('packing.defaultCategory'))} onClick={() => handleCatChange(cat)} /> - ))} -
- )} - - {canPickBringers && ( - <> - } label={t('packing.bringersTitle')} onClick={() => setShowMenuBringers(v => !v)} - trailing={showMenuBringers ? : } /> - {showMenuBringers && ( -
- {tripMembers.map(m => ( - } label={m.username} active={isBringer(m.id)} onClick={() => toggleBringer(m.id)} /> - ))} -
- )} - - )} - - {canShare && onClone && onJoin && onLeave && ( - setShowItemMenu(false)} - /> - )} - -
- } label={t('common.rename')} onClick={() => { setEditing(true); setShowItemMenu(false) }} /> - } label={t('common.delete')} danger onClick={() => { setShowItemMenu(false); void handleDelete() }} /> -
- - ) - })()} -
+ {open && ( + setOpen(false)} + categories={categories} canEdit={canEdit} bagTrackingEnabled={bagTrackingEnabled} bags={bags} onCreateBag={onCreateBag} + tripMembers={tripMembers} currentUserId={currentUserId} + onSetSharing={onSetSharing} onClone={onClone} onJoin={onJoin} onLeave={onLeave} + onDelete={() => void handleDelete()} + /> )}
) diff --git a/client/src/components/Packing/PackingListPanelQuantityInput.test.tsx b/client/src/components/Packing/PackingListPanelQuantityInput.test.tsx deleted file mode 100644 index 736a36534..000000000 --- a/client/src/components/Packing/PackingListPanelQuantityInput.test.tsx +++ /dev/null @@ -1,47 +0,0 @@ -// FE-COMP-PACKING-082 to FE-COMP-PACKING-083 -import { vi } from 'vitest'; -import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render'; -import { QuantityInput } from './PackingListPanelQuantityInput'; - -describe('QuantityInput', () => { - it('FE-COMP-PACKING-082: selects the current value on focus so typing replaces it', async () => { - render( {}} />); - const input = screen.getByRole('textbox') as HTMLInputElement; - - fireEvent.focus(input); - - await waitFor(() => { - expect(input.selectionStart).toBe(0); - expect(input.selectionEnd).toBe(1); - }); - }); - - it('FE-COMP-PACKING-083: commits the typed quantity on blur', async () => { - const onSave = vi.fn(); - render(); - const input = screen.getByRole('textbox') as HTMLInputElement; - - fireEvent.change(input, { target: { value: '6' } }); - fireEvent.blur(input); - - await waitFor(() => expect(onSave).toHaveBeenCalledWith(6)); - }); - - it('FE-COMP-PACKING-084: #1513 focus-then-type replaces the value instead of appending to it', async () => { - // The end-to-end shape of the bug: with the caret parked at the end, typing 6 over a - // quantity of 1 committed 16. Selecting on focus makes the keystroke overwrite. - const onSave = vi.fn(); - render(); - const input = screen.getByRole('textbox') as HTMLInputElement; - - fireEvent.focus(input); - await waitFor(() => expect(input.selectionEnd).toBe(1)); - - // A selected value means the browser replaces it — simulate the resulting input event. - fireEvent.change(input, { target: { value: '6' } }); - fireEvent.blur(input); - - await waitFor(() => expect(onSave).toHaveBeenCalledWith(6)); - expect(onSave).not.toHaveBeenCalledWith(16); - }); -}); diff --git a/client/src/components/Packing/PackingListPanelQuantityInput.tsx b/client/src/components/Packing/PackingListPanelQuantityInput.tsx deleted file mode 100644 index 7f3197d6b..000000000 --- a/client/src/components/Packing/PackingListPanelQuantityInput.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { useState, useEffect, type CSSProperties } from 'react' -import { NumericInput } from '../shared/NumericInput' - -/** `style` lays over the frame, for a row that wants the field quieter at rest. */ -export function QuantityInput({ value, onSave, style }: { value: number; onSave: (qty: number) => void; style?: CSSProperties }) { - const [local, setLocal] = useState(String(value)) - useEffect(() => setLocal(String(value)), [value]) - - const commit = () => { - const qty = Math.max(1, Math.min(999, Number(local) || 1)) - setLocal(String(qty)) - if (qty !== value) onSave(qty) - } - - return ( -
- { if (e.key === 'Enter') { commit(); (e.target as HTMLInputElement).blur() } }} - style={{ width: 24, border: 'none', outline: 'none', background: 'transparent', fontSize: 'calc(12px * var(--fs-scale-body, 1))', textAlign: 'end', fontFamily: 'inherit', color: 'var(--text-secondary)', padding: 0 }} - /> - x -
- ) -} diff --git a/client/src/components/Packing/PackingListPanelViewTabs.tsx b/client/src/components/Packing/PackingListPanelViewTabs.tsx index 4178b094d..ba3aaef8a 100644 --- a/client/src/components/Packing/PackingListPanelViewTabs.tsx +++ b/client/src/components/Packing/PackingListPanelViewTabs.tsx @@ -1,34 +1,28 @@ -import { Users, UserRound, ArrowDownAZ } from 'lucide-react' +import { Users, UserRound, CheckCheck } from 'lucide-react' import type { PackingState } from './usePackingListPanel' /** - * One tab row: the three-tier view switch (Gemeinsam / Meine Liste, #858) on the - * left, then the all/open/done filter. Each sits in its own tinted track, the way - * the phone shows them, so the row reads as two questions (whose list, which - * state) rather than five pills of equal weight. The A-Z switch keeps to the far - * end in a track of its own: it changes the order, not what is listed. + * One row above the lists: whose list (Gemeinsam / Meine Liste, #858) on the + * left in a tinted track, and how far the packing has come on the right as a + * line of text with a slim bar. Showing packed items and the order live in the + * Lists menu, so the row asks one question and answers one. */ export function PackingViewTabs(S: PackingState) { - const { view, setView, filter, setFilter, sort, setSort, t, items } = S + const { view, setView, t, items, abgehakt, viewTotal, fortschritt } = S const commonCount = items.filter(i => !i.is_private).length const personalCount = items.filter(i => !!i.is_private).length - const track: React.CSSProperties = { - display: 'inline-flex', alignItems: 'center', gap: 2, padding: 3, borderRadius: 999, background: 'var(--bg-tertiary)', - } - const segment = (active: boolean): React.CSSProperties => ({ - display: 'inline-flex', alignItems: 'center', gap: 6, height: 28, padding: '0 13px', borderRadius: 999, - border: 'none', cursor: 'pointer', fontFamily: 'inherit', - fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 600, transition: 'all 0.12s', - background: active ? 'var(--text-primary)' : 'transparent', - color: active ? 'var(--bg-primary)' : 'var(--text-muted)', - boxShadow: active ? '0 1px 2px rgba(0,0,0,0.12)' : 'none', - }) - const viewPill = (id: 'common' | 'personal', icon: React.ReactNode, label: string, count: number) => { const active = view === id return ( - - ) - return ( -
-
+
+
{viewPill('common', , t('packing.viewCommon'), commonCount)} {viewPill('personal', , t('packing.viewPersonal'), personalCount)}
- {items.length > 0 && ( -
- {filterPill('alle', t('packing.filterAll'))} - {filterPill('offen', t('packing.filterOpen'))} - {filterPill('erledigt', t('packing.filterDone'))} -
- )} - {items.length > 0 && ( - // A second click on the active switch goes back to the manual order. -
- + {viewTotal > 0 && ( +
+ {fortschritt === 100 ? ( + {t('packing.allPacked')} + ) : ( + {t('packing.packedCount', { packed: abgehakt, total: viewTotal })} + )} + + +
)}
diff --git a/client/src/components/Packing/PackingListsMenu.test.tsx b/client/src/components/Packing/PackingListsMenu.test.tsx new file mode 100644 index 000000000..8acffb828 --- /dev/null +++ b/client/src/components/Packing/PackingListsMenu.test.tsx @@ -0,0 +1,147 @@ +// FE-PACKLISTSMENU-001 to FE-PACKLISTSMENU-008 +import type { ComponentProps } from 'react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen } from '../../../tests/helpers/render'; +import { useAddonStore } from '../../store/addonStore'; + +const applyProps = vi.fn(); +const exportProps = vi.fn(); +vi.mock('./ApplyTemplateButton', () => ({ + default: (props: { onApplied?: () => void }) => { + applyProps(props); + return ( + + ); + }, +})); +vi.mock('./PackingExportMenu', () => ({ + default: (props: { onChosen?: () => void }) => { + exportProps(props); + return ( + + ); + }, +})); + +import PackingListsMenu from './PackingListsMenu'; + +type Props = ComponentProps; + +function setup(overrides: Partial = {}) { + const props: Props = { + tripId: 4, + view: 'common', + canEdit: true, + isAdmin: true, + hasItems: true, + packedCount: 0, + sort: 'manual', + onSortChange: vi.fn(), + hideDone: false, + onHideDoneChange: vi.fn(), + onImport: vi.fn(), + onSaveTemplate: vi.fn(), + onClearChecked: vi.fn(), + onOpenBags: vi.fn(), + buttonClassName: 'btn', + buttonStyle: {}, + ...overrides, + }; + render(); + const trigger = screen.getByRole('button', { name: 'Show more' }); + return { props, trigger, menu: () => screen.getByRole('menu', { hidden: true }) }; +} + +beforeEach(() => { + vi.clearAllMocks(); + useAddonStore.setState({ bagTracking: false }); +}); + +describe('PackingListsMenu', () => { + it('FE-PACKLISTSMENU-001: the "..." opens and closes the menu, a click beside it closes it too', () => { + const { trigger, menu } = setup(); + expect(menu()).not.toBeVisible(); + fireEvent.click(trigger); + expect(trigger).toHaveAttribute('aria-expanded', 'true'); + expect(menu()).toBeVisible(); + fireEvent.click(document.querySelector('[role="presentation"]')!); + expect(menu()).not.toBeVisible(); + }); + + it('FE-PACKLISTSMENU-002: templates and export sit in it, for the view on screen, and close it once used', () => { + const { trigger, menu } = setup({ view: 'personal' }); + expect(applyProps).toHaveBeenCalledWith( + expect.objectContaining({ tripId: 4, visibility: 'personal', variant: 'menu' }) + ); + expect(exportProps).toHaveBeenCalledWith(expect.objectContaining({ tripId: 4, view: 'personal', variant: 'menu' })); + fireEvent.click(trigger); + fireEvent.click(screen.getByRole('button', { name: 'Apply template' })); + expect(menu()).not.toBeVisible(); + fireEvent.click(trigger); + fireEvent.click(screen.getByRole('button', { name: 'Print or save as PDF' })); + expect(menu()).not.toBeVisible(); + }); + + it('FE-PACKLISTSMENU-003: import and save as template hand over and close the menu', () => { + const { trigger, props, menu } = setup(); + fireEvent.click(trigger); + fireEvent.click(screen.getByRole('button', { name: 'Import' })); + expect(props.onImport).toHaveBeenCalledTimes(1); + expect(menu()).not.toBeVisible(); + fireEvent.click(trigger); + fireEvent.click(screen.getByRole('button', { name: 'Save as template' })); + expect(props.onSaveTemplate).toHaveBeenCalledTimes(1); + }); + + it('FE-PACKLISTSMENU-004: a reader gets no templates, import, save or clean-up', () => { + setup({ canEdit: false, packedCount: 3 }); + expect(applyProps).not.toHaveBeenCalled(); + expect(screen.queryByRole('button', { name: 'Import', hidden: true })).toBeNull(); + expect(screen.queryByRole('button', { name: 'Save as template', hidden: true })).toBeNull(); + expect(screen.queryByRole('button', { name: /checked/, hidden: true })).toBeNull(); + expect(screen.getByRole('button', { name: /Print or save as PDF/, hidden: true })).toBeInTheDocument(); + }); + + it('FE-PACKLISTSMENU-005: save as template is for admins with a list to save', () => { + setup({ isAdmin: false }); + expect(screen.queryByRole('button', { name: 'Save as template', hidden: true })).toBeNull(); + }); + + it('FE-PACKLISTSMENU-006: A to Z and hiding packed items toggle, and show a tick while on', () => { + const { trigger, props } = setup({ sort: 'name', hideDone: true }); + fireEvent.click(trigger); + const sort = screen.getByRole('button', { name: 'A to Z' }); + const hide = screen.getByRole('button', { name: 'Hide packed' }); + expect(sort.querySelector('svg.lucide-check')).not.toBeNull(); + expect(hide.querySelector('svg.lucide-check')).not.toBeNull(); + fireEvent.click(sort); + fireEvent.click(hide); + expect(props.onSortChange).toHaveBeenCalledWith('manual'); + expect(props.onHideDoneChange).toHaveBeenCalledWith(false); + }); + + it('FE-PACKLISTSMENU-007: an empty list offers no order or hiding, and nothing to clear', () => { + setup({ hasItems: false }); + expect(screen.queryByRole('button', { name: 'A to Z', hidden: true })).toBeNull(); + expect(screen.queryByRole('button', { name: 'Hide packed', hidden: true })).toBeNull(); + expect(screen.queryByRole('button', { name: /checked/, hidden: true })).toBeNull(); + }); + + it('FE-PACKLISTSMENU-008: bags come in with bag tracking, the clean-up with packed items', () => { + useAddonStore.setState({ bagTracking: true }); + const { trigger, props } = setup({ sort: 'manual', packedCount: 2 }); + fireEvent.click(trigger); + fireEvent.click(screen.getByRole('button', { name: 'A to Z' })); + expect(props.onSortChange).toHaveBeenCalledWith('name'); + // The order is a switch: the menu stays open for the next choice. + fireEvent.click(screen.getByRole('button', { name: 'Bags' })); + expect(props.onOpenBags).toHaveBeenCalledTimes(1); + fireEvent.click(trigger); + fireEvent.click(screen.getByRole('button', { name: 'Remove 2 checked' })); + expect(props.onClearChecked).toHaveBeenCalledTimes(1); + }); +}); diff --git a/client/src/components/Packing/PackingListsMenu.tsx b/client/src/components/Packing/PackingListsMenu.tsx new file mode 100644 index 000000000..1cd018f09 --- /dev/null +++ b/client/src/components/Packing/PackingListsMenu.tsx @@ -0,0 +1,133 @@ +import { ArrowDownAZ, Check, Download, EyeOff, FolderPlus, Luggage, MoreHorizontal, Trash2 } from 'lucide-react'; +import { useState, type CSSProperties } from 'react'; +import { useTranslation } from '../../i18n'; +import { useAddonStore } from '../../store/addonStore'; +import ApplyTemplateButton from './ApplyTemplateButton'; +import PackingExportMenu from './PackingExportMenu'; +import { PopoverItem } from './PackingPopover'; +import { POPOVER, POPOVER_DIVIDER } from './packingPopoverStyles'; +import type { PackingSort } from './usePackingListPanel'; + +interface PackingListsMenuProps { + tripId: number; + view: 'common' | 'personal'; + canEdit: boolean; + isAdmin: boolean; + hasItems: boolean; + /** Packed items in the view on screen, for the clean-up line. */ + packedCount: number; + sort: PackingSort; + onSortChange: (next: PackingSort) => void; + hideDone: boolean; + onHideDoneChange: (next: boolean) => void; + onImport: () => void; + onSaveTemplate: () => void; + onClearChecked: () => void; + onOpenBags: () => void; + buttonClassName: string; + buttonStyle: CSSProperties; +} + +/** + * Everything the packing list needs now and then, behind one "..." beside Add + * list: templates, import and export, the order, hiding what is packed, the bag + * overview on a screen too narrow for its sidebar, and clearing the packed items. + * The panel stays mounted while closed, so a print preview opened from it lives on. + */ +export default function PackingListsMenu(props: Readonly) { + const { + tripId, + view, + canEdit, + isAdmin, + hasItems, + packedCount, + sort, + onSortChange, + hideDone, + onHideDoneChange, + onImport, + onSaveTemplate, + onClearChecked, + onOpenBags, + buttonClassName, + buttonStyle, + } = props; + const { t } = useTranslation(); + const bagTracking = useAddonStore((s) => s.bagTracking); + const [open, setOpen] = useState(false); + const close = () => setOpen(false); + const run = (action: () => void) => () => { + close(); + action(); + }; + const tick = (on: boolean) => (on ? : null); + + return ( +
+ + {open &&
} +