feat(packing): a calmer packing list, with every item's choices in one window

A row now shows its box, its name and only what is set: the amount from two
up, the pieces packed while packing, and who brings it. A click on the name
opens a small window at the row with the list, amount, pieces packed, weight,
bag, who brings it and who sees it, each as one pill, plus copy and delete,
instead of fields, a bin and menus in menus on every row. Above the lists the
Lists bar keeps Add list and gathers templates, import, export, the order,
hiding packed items, the bags on a narrow screen and the clean-up in one menu;
the progress moves next to the Shared/My list switch. The bag overview stays.

The phone follows the same shape: one "..." sheet for the list's actions, a
sheet per list for its own, a slim row and an item sheet that saves as you go.
Who may change what about an item lives in one module both views read.
This commit is contained in:
Maurice
2026-11-15 12:11:15 +01:00
parent 7bbb5a9f71
commit 5536d29cbf
61 changed files with 3271 additions and 3731 deletions
@@ -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(<ApplyTemplateButton tripId={4} visibility="personal" variant="menu" onApplied={onApplied} />)
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()
})
})
@@ -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<Template[]>([])
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 (
<>
<PopoverItem icon={<Package size={13} />} label={t('packing.applyTemplate')} onClick={() => setOpen(v => !v)}
trailing={open ? <ChevronDown size={13} className="shrink-0 text-content-faint" /> : <ChevronRight size={13} className="shrink-0 text-content-faint" />} />
{open && (
<div className="mb-1 ms-[18px] border-s border-edge-faint ps-1.5">
{templates.map(tmpl => (
<PackingTemplateOption key={tmpl.id} name={tmpl.name} itemCount={tmpl.item_count} onClick={() => { if (!applying) void handleApply(tmpl.id) }} t={t} />
))}
</div>
)}
</>
)
return (
<div ref={dropRef} style={{ position: 'relative' }}>
<button type="button"
@@ -1,4 +1,4 @@
// FE-PACKEXPORTMENU-001 to FE-PACKEXPORTMENU-006
// FE-PACKEXPORTMENU-001 to FE-PACKEXPORTMENU-007
import { beforeEach, describe, expect, it, vi } from 'vitest'
import userEvent from '@testing-library/user-event'
import { fireEvent, render, screen } from '../../../tests/helpers/render'
@@ -99,4 +99,18 @@ describe('PackingPrintPreview', () => {
await user.click(closeButtons[closeButtons.length - 1])
expect(onClose).toHaveBeenCalledTimes(1)
})
it('FE-PACKEXPORTMENU-007: as menu lines it offers the three ways out and reports the choice', async () => {
const user = userEvent.setup()
const onChosen = vi.fn()
render(<PackingExportMenu tripId={7} view="personal" variant="menu" onChosen={onChosen} />)
expect(screen.queryByRole('button', { name: 'Export' })).toBeNull()
await user.click(screen.getByRole('button', { name: 'CSV for import (.csv)' }))
expect(packingExport.exportCsv).toHaveBeenCalledTimes(1)
expect(onChosen).toHaveBeenCalledTimes(1)
await user.click(screen.getByRole('button', { name: 'Print or save as PDF' }))
expect(packingExport.openPrint).toHaveBeenCalledTimes(1)
await user.click(screen.getByRole('button', { name: 'Markdown checklist (.md)' }))
expect(packingExport.exportMarkdown).toHaveBeenCalledTimes(1)
})
})
@@ -3,13 +3,17 @@ import type { LucideIcon } from 'lucide-react'
import { FileSpreadsheet, FileText, Printer, Upload } from 'lucide-react'
import { useTranslation } from '../../i18n'
import PackingPrintPreview from './PackingPrintPreview'
import { PopoverItem } from './PackingPopover'
import { usePackingExport, type PackingView } from './usePackingExport'
interface PackingExportMenuProps {
tripId: number
view: PackingView
style: React.CSSProperties
style?: React.CSSProperties
className?: string
/** 'menu' draws the three ways out as lines of the Lists menu; onChosen closes that menu. */
variant?: 'button' | 'menu'
onChosen?: () => void
}
function MenuItem({ icon: Icon, label, onClick }: { icon: LucideIcon; label: string; onClick: () => void }) {
@@ -31,7 +35,7 @@ function MenuItem({ icon: Icon, label, onClick }: { icon: LucideIcon; label: str
* as PDF, a Markdown checklist, or CSV in the import's own format. Covers the view on
* screen and renders nothing while that view is empty.
*/
export default function PackingExportMenu({ tripId, view, style, className }: PackingExportMenuProps): React.ReactElement | null {
export default function PackingExportMenu({ tripId, view, style, className, variant = 'button', onChosen }: PackingExportMenuProps): React.ReactElement | null {
const { t } = useTranslation()
const packingExport = usePackingExport(tripId, view)
const [open, setOpen] = useState(false)
@@ -55,9 +59,19 @@ export default function PackingExportMenu({ tripId, view, style, className }: Pa
const choose = (action: () => void | Promise<void>) => () => {
setOpen(false)
onChosen?.()
void action()
}
if (variant === 'menu') return (
<>
<PopoverItem icon={<Printer size={13} />} label={t('packing.exportPrint')} onClick={choose(packingExport.openPrint)} />
<PopoverItem icon={<FileText size={13} />} label={t('packing.exportMarkdown')} onClick={choose(packingExport.exportMarkdown)} />
<PopoverItem icon={<FileSpreadsheet size={13} />} label={t('packing.exportCsv')} onClick={choose(packingExport.exportCsv)} />
<PackingPrintPreview html={packingExport.printHtml} title={packingExport.printTitle} onClose={packingExport.closePrint} />
</>
)
return (
// A flex box, so the button stretches to the row height like its neighbours in the header.
<div ref={menuRef} className="relative flex">
@@ -0,0 +1,373 @@
// FE-PACKDETAIL-001 to FE-PACKDETAIL-024
import { http, HttpResponse } from 'msw';
import type { ComponentProps } from 'react';
import { createRef } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildPackingItem, buildTrip, buildUser } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { fireEvent, render, screen, waitFor, within } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useAuthStore } from '../../store/authStore';
import { useTripStore } from '../../store/tripStore';
import type { PackingBag, PackingItem } from '../../types';
import { PackingItemDetail } from './PackingItemDetail';
import type { TripMember } from './usePackingListPanel';
type Props = ComponentProps<typeof PackingItemDetail>;
const toastSpy = vi.fn((_message: string, _type?: string, _duration?: number) => 0);
const MEMBERS = [
{ id: 1, username: 'owner' },
{ id: 2, username: 'alice' },
{ id: 3, username: 'bob', avatar_url: '/uploads/avatars/bob.png' },
] as unknown as TripMember[];
const BAGS = [
{ id: 7, name: 'Carry-on', color: '#10b981' },
{ id: 8, name: 'Trolley', color: '#ec4899' },
] as unknown as PackingBag[];
function setup(overrides: Partial<Props> = {}) {
const anchor = document.createElement('div');
document.body.appendChild(anchor);
const anchorRef = createRef<HTMLElement>() as { current: HTMLElement | null };
anchorRef.current = anchor;
const props: Props = {
item: buildPackingItem({
id: 1,
name: 'Tent',
category: 'Gear',
quantity: 1,
is_private: 0,
owner_id: 1,
owner_username: 'owner',
} as Partial<PackingItem>),
tripId: 1,
anchorRef,
onClose: vi.fn(),
categories: ['Gear', 'Docs'],
canEdit: true,
bags: BAGS,
onCreateBag: vi.fn(async () => undefined),
tripMembers: MEMBERS,
currentUserId: 1,
onSetSharing: vi.fn(),
onClone: vi.fn(),
onJoin: vi.fn(),
onLeave: vi.fn(),
onDelete: vi.fn(),
...overrides,
};
const utils = render(<PackingItemDetail {...props} />);
return { ...utils, props, dialog: within(screen.getByRole('dialog')) };
}
/** Captures the body of the next PUT to item 1. */
function capturePut() {
const box: { body: Record<string, unknown> | null } = { body: null };
server.use(
http.put('/api/trips/1/packing/1', async ({ request }) => {
box.body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ item: buildPackingItem({ id: 1 }) });
})
);
return box;
}
beforeEach(() => {
resetAllStores();
toastSpy.mockClear();
window.__addToast = toastSpy;
seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }), packingItems: [buildPackingItem({ id: 1, name: 'Tent' })] });
});
afterEach(() => {
delete window.__addToast;
vi.restoreAllMocks();
});
describe('PackingItemDetail — name and list', () => {
it('FE-PACKDETAIL-001: renaming saves when the field lets go, Enter included', async () => {
const put = capturePut();
const { dialog } = setup();
const input = dialog.getByRole('textbox', { name: 'Rename' });
input.focus();
fireEvent.change(input, { target: { value: 'Tarp' } });
fireEvent.keyDown(input, { key: 'Enter' });
await waitFor(() => expect(put.body).toMatchObject({ name: 'Tarp' }));
});
it('FE-PACKDETAIL-002: a blank or unchanged name saves nothing', async () => {
const put = capturePut();
const { dialog } = setup();
const input = dialog.getByRole('textbox', { name: 'Rename' });
fireEvent.change(input, { target: { value: ' ' } });
fireEvent.blur(input);
expect(input).toHaveValue('Tent');
fireEvent.blur(input);
await new Promise((r) => setTimeout(r, 20));
expect(put.body).toBeNull();
});
it('FE-PACKDETAIL-003: a failing save surfaces a save error', async () => {
server.use(http.put('/api/trips/1/packing/1', () => new HttpResponse(null, { status: 500 })));
const { dialog } = setup();
const input = dialog.getByRole('textbox', { name: 'Rename' });
fireEvent.change(input, { target: { value: 'Tarp' } });
fireEvent.blur(input);
await waitFor(() => expect(toastSpy).toHaveBeenCalledWith('Failed to save', 'error', undefined));
});
it('FE-PACKDETAIL-004: the List choice moves the item and leaves the current list alone', async () => {
const put = capturePut();
const { dialog } = setup();
const choice = dialog.getByRole('button', { name: /Gear/ });
expect(choice).toHaveAttribute('aria-expanded', 'false');
fireEvent.click(choice);
expect(choice).toHaveAttribute('aria-expanded', 'true');
fireEvent.click(dialog.getAllByRole('button', { name: /Gear/ })[1]);
expect(put.body).toBeNull();
fireEvent.click(dialog.getByRole('button', { name: /Gear/ }));
fireEvent.click(dialog.getByRole('button', { name: /Docs/ }));
await waitFor(() => expect(put.body).toMatchObject({ category: 'Docs' }));
});
it('FE-PACKDETAIL-005: an item without a list sits in the default one', () => {
const { dialog } = setup({ item: buildPackingItem({ id: 1, name: 'Tent', category: null }) });
expect(dialog.getByRole('button', { name: /Other/ })).toBeInTheDocument();
});
});
describe('PackingItemDetail — amounts', () => {
it('FE-PACKDETAIL-006: the amount steps up and down and is typed into', async () => {
const put = capturePut();
const { dialog } = setup({ item: buildPackingItem({ id: 1, name: 'Socks', quantity: 3 }) });
const group = within(dialog.getByRole('group', { name: 'Qty' }));
fireEvent.click(group.getByRole('button', { name: 'One more' }));
await waitFor(() => expect(put.body).toMatchObject({ quantity: 4 }));
fireEvent.click(group.getByRole('button', { name: 'One less' }));
await waitFor(() => expect(put.body).toMatchObject({ quantity: 2 }));
const field = group.getByDisplayValue('3');
fireEvent.focus(field);
fireEvent.change(field, { target: { value: '12' } });
fireEvent.keyDown(field, { key: 'Enter' });
fireEvent.blur(field);
await waitFor(() => expect(put.body).toMatchObject({ quantity: 12 }));
});
it('FE-PACKDETAIL-007: one piece cannot go lower, and a cleared field falls back to one', async () => {
const put = capturePut();
const { dialog } = setup();
const group = within(dialog.getByRole('group', { name: 'Qty' }));
expect(group.getByRole('button', { name: 'One less' })).toBeDisabled();
const field = group.getByDisplayValue('1');
fireEvent.focus(field);
fireEvent.change(field, { target: { value: '' } });
fireEvent.blur(field);
await new Promise((r) => setTimeout(r, 20));
expect(put.body).toBeNull();
expect(field).toHaveValue('1');
});
it('FE-PACKDETAIL-008: several pieces add the packed counter', () => {
const { dialog } = setup({
item: buildPackingItem({ id: 1, name: 'Socks', quantity: 5, packed_quantity: 2 } as Partial<PackingItem>),
});
expect(dialog.getByText('2/5')).toBeInTheDocument();
});
it('FE-PACKDETAIL-009: a single piece and a read-only window show no steppers', () => {
const first = setup();
expect(first.dialog.queryByText(/\/1$/)).toBeNull();
first.unmount();
const ro = setup({ canEdit: false });
expect(ro.dialog.queryByRole('group', { name: 'Qty' })).toBeNull();
expect(ro.dialog.getByRole('button', { name: /Gear/ })).toBeDisabled();
});
it('FE-PACKDETAIL-010: with bag tracking the weight is typed in grams', async () => {
const put = capturePut();
const { dialog } = setup({ bagTrackingEnabled: true });
const weight = dialog.getByPlaceholderText('—');
fireEvent.focus(weight);
fireEvent.change(weight, { target: { value: '450' } });
fireEvent.blur(weight);
await waitFor(() => expect(put.body).toMatchObject({ weight_grams: 450 }));
});
});
describe('PackingItemDetail — bag', () => {
it('FE-PACKDETAIL-011: no bag tracking, no bag or weight lines', () => {
const { dialog } = setup();
expect(dialog.queryByPlaceholderText('—')).toBeNull();
expect(dialog.queryByRole('button', { name: /Unassigned/ })).toBeNull();
});
it('FE-PACKDETAIL-012: picking a bag assigns it, picking the same one does nothing', async () => {
const put = capturePut();
const { dialog } = setup({ bagTrackingEnabled: true });
fireEvent.click(dialog.getByRole('button', { name: /Unassigned/ }));
fireEvent.click(dialog.getAllByRole('button', { name: /Unassigned/ })[1]);
expect(put.body).toBeNull();
fireEvent.click(dialog.getByRole('button', { name: /Unassigned/ }));
fireEvent.click(dialog.getByRole('button', { name: /Trolley/ }));
await waitFor(() => expect(put.body).toMatchObject({ bag_id: 8 }));
});
it('FE-PACKDETAIL-013: an assigned item can be taken out of its bag', async () => {
const put = capturePut();
const { dialog } = setup({
bagTrackingEnabled: true,
item: buildPackingItem({ id: 1, name: 'Tent', bag_id: 7 } as Partial<PackingItem>),
});
fireEvent.click(dialog.getByRole('button', { name: /Carry-on/ }));
fireEvent.click(dialog.getByRole('button', { name: /Unassigned/ }));
await waitFor(() => expect(put.body).toMatchObject({ bag_id: null }));
});
it('FE-PACKDETAIL-014: a new bag is created and assigned, a blank name creates nothing', async () => {
const put = capturePut();
const onCreateBag = vi.fn(async () => ({ id: 20, name: 'Daypack', color: '#6366f1' }) as unknown as PackingBag);
const { dialog } = setup({ bagTrackingEnabled: true, onCreateBag });
fireEvent.click(dialog.getByRole('button', { name: /Unassigned/ }));
const field = dialog.getByRole('textbox', { name: 'Bag name...' });
expect(dialog.getByRole('button', { name: 'Add bag' })).toBeDisabled();
fireEvent.keyDown(field, { key: 'Enter' });
expect(onCreateBag).not.toHaveBeenCalled();
fireEvent.change(field, { target: { value: 'Daypack' } });
fireEvent.click(dialog.getByRole('button', { name: 'Add bag' }));
await waitFor(() => expect(put.body).toMatchObject({ bag_id: 20 }));
expect(onCreateBag).toHaveBeenCalledWith('Daypack');
});
it('FE-PACKDETAIL-015: a bag that could not be created assigns nothing', async () => {
const put = capturePut();
const { dialog } = setup({ bagTrackingEnabled: true });
fireEvent.click(dialog.getByRole('button', { name: /Unassigned/ }));
const field = dialog.getByRole('textbox', { name: 'Bag name...' });
fireEvent.change(field, { target: { value: 'Daypack' } });
fireEvent.keyDown(field, { key: 'Enter' });
await waitFor(() => expect(dialog.queryByRole('textbox', { name: 'Bag name...' })).toBeNull());
expect(put.body).toBeNull();
});
});
describe('PackingItemDetail — who brings it and who sees it', () => {
it('FE-PACKDETAIL-016: the bringer pill opens every traveller, ticked on or off (#3098)', () => {
const { dialog, props } = setup({
item: buildPackingItem({
id: 1,
name: 'Tent',
is_private: 0,
owner_id: 1,
owner_username: 'owner',
contributors: [{ user_id: 3, username: 'bob' }],
} as unknown as Partial<PackingItem>),
});
fireEvent.click(dialog.getByRole('button', { name: /owner, bob/ }));
fireEvent.click(dialog.getByRole('button', { name: 'alice' }));
expect(props.onJoin).toHaveBeenCalledWith(1, 2);
fireEvent.click(dialog.getByRole('button', { name: 'bob' }));
expect(props.onLeave).toHaveBeenCalledWith(1, 3);
fireEvent.click(dialog.getByRole('button', { name: 'owner' }));
expect(props.onLeave).toHaveBeenCalledWith(1, 1);
});
it('FE-PACKDETAIL-017: nobody bringing it yet reads as such', () => {
const { dialog } = setup({
item: buildPackingItem({
id: 1,
name: 'Tent',
is_private: 0,
owner_id: null,
owner_username: null,
} as Partial<PackingItem>),
});
expect(dialog.getByRole('button', { name: /Nobody yet/ })).toBeInTheDocument();
});
it('FE-PACKDETAIL-018: the owner sets who sees the item', () => {
const { dialog, props } = setup();
const group = within(dialog.getByRole('radiogroup', { name: 'Visible to' }));
expect(group.getByRole('radio', { name: 'All' })).toHaveAttribute('aria-checked', 'true');
fireEvent.click(group.getByRole('radio', { name: 'Only me' }));
expect(props.onSetSharing).toHaveBeenCalledWith(1, 'personal', []);
fireEvent.click(group.getByRole('radio', { name: 'Selected' }));
expect(group.getByRole('radio', { name: 'Selected' })).toHaveAttribute('aria-checked', 'true');
fireEvent.click(dialog.getByRole('button', { name: 'alice' }));
expect(props.onSetSharing).toHaveBeenCalledWith(1, 'shared', [2]);
fireEvent.click(group.getByRole('radio', { name: 'All' }));
expect(props.onSetSharing).toHaveBeenLastCalledWith(1, 'common', []);
});
it('FE-PACKDETAIL-019: taking the last person off a shared item makes it personal', () => {
const { dialog, props } = setup({
item: buildPackingItem({
id: 1,
name: 'Diary',
is_private: 1,
owner_id: 1,
recipients: [{ user_id: 2, username: 'alice' }],
} as unknown as Partial<PackingItem>),
});
expect(dialog.getByRole('radio', { name: 'Selected' })).toHaveAttribute('aria-checked', 'true');
// A private item has no bringer pill.
expect(dialog.queryByRole('button', { name: /owner/ })).toBeNull();
fireEvent.click(dialog.getByRole('button', { name: 'alice' }));
expect(props.onSetSharing).toHaveBeenCalledWith(1, 'personal', []);
});
it('FE-PACKDETAIL-020: alone on the trip there is nobody to pick', () => {
const { dialog } = setup({ tripMembers: [MEMBERS[0]] });
fireEvent.click(dialog.getByRole('radio', { name: 'Selected' }));
expect(dialog.getByText('No one else on this trip yet')).toBeInTheDocument();
});
it('FE-PACKDETAIL-021: an item someone else shared with me says whose it is and offers no sharing', () => {
const { dialog } = setup({
item: buildPackingItem({
id: 1,
name: 'Stove',
is_private: 1,
owner_id: 2,
owner_username: 'alice',
} as Partial<PackingItem>),
});
expect(dialog.getByText('by alice')).toBeInTheDocument();
expect(dialog.queryByRole('radiogroup')).toBeNull();
expect(dialog.queryByRole('button', { name: 'Copy to my list' })).toBeNull();
});
it('FE-PACKDETAIL-022: a common item of someone else can be copied to my list', () => {
const { dialog, props } = setup({
item: buildPackingItem({
id: 1,
name: 'Stove',
is_private: 0,
owner_id: 2,
owner_username: 'alice',
} as Partial<PackingItem>),
});
expect(dialog.queryByRole('radiogroup')).toBeNull();
fireEvent.click(dialog.getByRole('button', { name: 'Copy to my list' }));
expect(props.onClone).toHaveBeenCalledWith(1);
expect(props.onClose).toHaveBeenCalled();
});
});
describe('PackingItemDetail — closing and deleting', () => {
it('FE-PACKDETAIL-023: Delete closes the window and hands over', () => {
const { dialog, props } = setup();
fireEvent.click(dialog.getByRole('button', { name: 'Delete' }));
expect(props.onClose).toHaveBeenCalled();
expect(props.onDelete).toHaveBeenCalled();
});
it('FE-PACKDETAIL-024: Escape, the close button and a click beside the window close it', () => {
const { dialog, props } = setup();
fireEvent.keyDown(dialog.getByRole('textbox', { name: 'Rename' }), { key: 'Escape' });
fireEvent.click(dialog.getByRole('button', { name: 'Close' }));
fireEvent.click(document.querySelector('[role="presentation"]')!);
expect(props.onClose).toHaveBeenCalledTimes(3);
});
});
@@ -0,0 +1,602 @@
import { ChevronDown, Copy, Minus, Plus, Trash2, X } from 'lucide-react';
import { useState, type CSSProperties, type ReactNode, type RefObject } from 'react';
import { createPortal } from 'react-dom';
import { useAnchoredPosition } from '../../hooks/useAnchoredPosition';
import { useTranslation } from '../../i18n';
import { useTripStore } from '../../store/tripStore';
import type { PackingBag, PackingItem } from '../../types';
import { NumericInput } from '../shared/NumericInput';
import { useToast } from '../shared/Toast';
import { bringersOf, packingBringerNames } from './packingBringers';
import { BringerAvatar, MoreBringers } from './PackingBringersCard';
import { bringsItem, packingItemAccess, toggledRecipients, type PackingVisibility } from './packingItemAccess';
import { katColor, packedOf } from './packingListPanel.helpers';
import { WeightInput } from './PackingListPanelWeightInput';
import { PackedCounter } from './PackingPackedCounter';
import { PopoverItem } from './PackingPopover';
import { POPOVER, POPOVER_DIVIDER } from './packingPopoverStyles';
import type { TripMember } from './usePackingListPanel';
type ItemPatch = Partial<Pick<PackingItem, 'name' | 'category' | 'quantity' | 'weight_grams' | 'bag_id'>>;
type Save = (data: ItemPatch) => Promise<void>;
export interface PackingItemDetailProps {
item: PackingItem;
tripId: number;
/** The row the window hangs from. */
anchorRef: RefObject<HTMLElement | null>;
onClose: () => void;
categories: string[];
canEdit: boolean;
bagTrackingEnabled?: boolean;
bags: PackingBag[];
onCreateBag: (name: string) => Promise<PackingBag | undefined>;
tripMembers: TripMember[];
currentUserId?: number;
onSetSharing?: (id: number, visibility: PackingVisibility, recipientIds: number[]) => void;
onClone?: (id: number) => void;
onJoin?: (id: number, userId?: number) => void;
onLeave?: (id: number, userId: number) => void;
onDelete: () => void;
}
const WIDTH = 320;
/** Every value of the window sits in the same soft pill: steppers, fields and the choices that open a list. */
const PILL =
'inline-flex h-7 min-w-0 max-w-full items-center gap-1.5 rounded-full bg-surface-tertiary text-caption font-semibold text-content';
const STEP =
'grid size-6 cursor-pointer place-items-center rounded-full border-0 bg-transparent p-0 text-content-muted hover:text-content disabled:cursor-default disabled:opacity-35';
const dotStyle = (color: string | undefined): CSSProperties => ({
width: 8,
height: 8,
borderRadius: '50%',
background: color,
display: 'inline-block',
flexShrink: 0,
});
const avatarOf = (m: TripMember) => ({ name: m.username, avatar: m.avatar_url ?? m.avatar ?? null });
/** One line of the window: what it is on the left, its value on the right. */
function Field({ name, children }: Readonly<{ name: string; children: ReactNode }>) {
return (
<div className="flex min-h-[38px] items-center gap-2.5 px-2.5 py-[3px]">
<span className="w-[92px] shrink-0 text-caption font-medium text-content-muted">{name}</span>
<div className="flex min-w-0 flex-1 items-center justify-end">{children}</div>
</div>
);
}
/** A pill that opens a short list right under its line, like a select would. */
function Choice({
open,
onToggle,
lead,
text,
disabled,
}: Readonly<{ open: boolean; onToggle: () => void; lead?: ReactNode; text: string; disabled: boolean }>) {
return (
<button
type="button"
onClick={onToggle}
disabled={disabled}
aria-expanded={open}
className={`${PILL} border-0 py-0 pe-2 ps-3 font-[inherit] ${disabled ? 'cursor-default pe-3' : 'cursor-pointer'}`}
>
{lead}
<span className="truncate">{text}</span>
{!disabled && (
<ChevronDown
size={13}
className={`shrink-0 text-content-faint transition-transform ${open ? 'rotate-180' : ''}`}
/>
)}
</button>
);
}
/** The short list a Choice opens, set in under its line. */
function ChoiceList({ children }: Readonly<{ children: ReactNode }>) {
return (
<div className="mx-1.5 mb-1 max-h-56 overflow-y-auto rounded-[10px] bg-surface-secondary p-[3px]">{children}</div>
);
}
/** 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<string | null>(null);
const commit = (next: number) => {
const qty = Math.max(1, Math.min(999, next || 1));
setDraft(null);
if (qty !== value) onSave(qty);
};
return (
<div className={`${PILL} px-0.5`} role="group" aria-label={t('packing.quantity')}>
<button
type="button"
className={STEP}
aria-label={t('packing.quantityLess')}
disabled={value <= 1}
onClick={() => commit(value - 1)}
>
<Minus size={12} strokeWidth={2.5} />
</button>
<NumericInput
value={draft ?? String(value)}
onValueChange={setDraft}
onFocus={() => 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"
/>
<button
type="button"
className={STEP}
aria-label={t('packing.quantityMore')}
disabled={value >= 999}
onClick={() => commit(value + 1)}
>
<Plus size={12} strokeWidth={2.5} />
</button>
</div>
);
}
function BagChoice({
item,
bags,
canEdit,
onCreateBag,
save,
}: Readonly<{
item: PackingItem;
bags: PackingBag[];
canEdit: boolean;
onCreateBag: (name: string) => Promise<PackingBag | undefined>;
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 (
<>
<Field name={t('packing.detail.bag')}>
<Choice
open={open}
disabled={!canEdit}
text={selected?.name || t('packing.noBag')}
onToggle={() => setOpen((o) => !o)}
lead={selected ? <span aria-hidden style={dotStyle(selected.color)} /> : undefined}
/>
</Field>
{open && (
<ChoiceList>
<PopoverItem
label={t('packing.noBag')}
active={!item.bag_id}
onClick={() => pick(null)}
icon={
<span className="inline-block size-2 rounded-full border-[1.5px] border-dashed border-content-faint" />
}
/>
{bags.map((b) => (
<PopoverItem
key={b.id}
label={b.name}
active={item.bag_id === b.id}
onClick={() => pick(b.id)}
icon={<span style={dotStyle(b.color)} />}
/>
))}
{/* 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. */}
<div className="flex items-center gap-[9px] rounded-[9px] py-1 pe-1.5 ps-2.5">
<span aria-hidden className="inline-flex w-4 shrink-0 justify-center text-content-faint">
<Plus size={13} />
</span>
<input
value={newBag}
onChange={(e) => 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"
/>
<button
type="button"
aria-label={t('packing.addBag')}
onClick={() => void create()}
disabled={!newBag.trim()}
className={`grid size-6 shrink-0 place-items-center rounded-full border-0 transition-colors ${newBag.trim() ? 'cursor-pointer bg-accent text-accent-text' : 'cursor-default bg-transparent text-content-faint'}`}
>
<Plus size={13} strokeWidth={2.5} />
</button>
</div>
</ChoiceList>
)}
</>
);
}
/** 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 ? (
<span className="-ms-2 inline-flex shrink-0">
<BringerAvatar bringer={faces[0]} />
{faces.length > 1 && <MoreBringers count={faces.length - 1} />}
</span>
) : undefined;
return (
<>
<Field name={t('packing.bringersTitle')}>
<Choice
open={open}
disabled={false}
lead={lead}
text={faces.length > 0 ? packingBringerNames(item) : t('packing.bringersNobody')}
onToggle={() => setOpen((o) => !o)}
/>
</Field>
{open && (
<ChoiceList>
{members.map((m) => {
const on = bringsItem(item, m.id);
return (
<PopoverItem
key={m.id}
label={m.username}
active={on}
icon={<BringerAvatar bringer={avatarOf(m)} />}
onClick={() => (on ? onLeave(item.id, m.id) : onJoin(item.id, m.id))}
/>
);
})}
</ChoiceList>
)}
</>
);
}
/** 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 (
<>
<Field name={t('packing.detail.visibility')}>
<div role="radiogroup" aria-label={t('packing.detail.visibility')} className={`${PILL} gap-0 p-0.5`}>
{options.map((o) => (
<button
type="button"
role="radio"
key={o.id}
aria-checked={shown === o.id}
onClick={() => choose(o.id)}
className={`h-6 cursor-pointer whitespace-nowrap rounded-full border-0 px-2.5 font-[inherit] text-caption font-semibold ${shown === o.id ? 'bg-content text-surface' : 'bg-transparent text-content-muted'}`}
>
{o.label}
</button>
))}
</div>
</Field>
{shown === 'shared' && (
<ChoiceList>
{others.length === 0 ? (
<div className="px-2 py-1.5 text-caption text-content-faint">{t('packing.noOneToShare')}</div>
) : (
others.map((m) => (
<PopoverItem
key={m.id}
label={m.username}
active={recipientIds.includes(m.id)}
onClick={() => toggle(m.id)}
icon={<BringerAvatar bringer={avatarOf(m)} />}
/>
))
)}
</ChoiceList>
)}
</>
);
}
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 (
<div className="flex items-center gap-2 py-1.5 pe-1.5 ps-2.5">
{canEdit ? (
<input
value={name}
onChange={(e) => 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"
/>
) : (
<span className="min-w-0 flex-1 truncate text-body font-bold">{item.name}</span>
)}
<button
type="button"
onClick={onClose}
aria-label={t('common.close')}
className="flex cursor-pointer rounded-md border-0 bg-transparent p-1 text-content-faint hover:text-content"
>
<X size={15} />
</button>
</div>
);
}
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 (
<>
<Field name={t('packing.detail.list')}>
<Choice
open={open}
disabled={!canEdit}
text={category}
onToggle={() => setOpen((o) => !o)}
lead={<span aria-hidden style={dotStyle(katColor(category, categories))} />}
/>
</Field>
{open && (
<ChoiceList>
{categories.map((cat) => (
<PopoverItem
key={cat}
label={cat}
active={cat === category}
icon={<span style={dotStyle(katColor(cat, categories))} />}
onClick={() => {
setOpen(false);
if (cat !== category) void save({ category: cat });
}}
/>
))}
</ChoiceList>
)}
</>
);
}
/** 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 && (
<Field name={t('packing.quantity')}>
<QuantityStepper value={quantity} onSave={(qty) => void save({ quantity: qty })} />
</Field>
)}
{canEdit && quantity > 1 && (
<Field name={t('packing.printPacked')}>
<PackedCounter
packed={packedOf(item)}
quantity={quantity}
onChange={(count) => setPackedCount(tripId, item.id, count)}
style={{ height: 28, padding: '0 2px' }}
/>
</Field>
)}
{bagTrackingEnabled && (
<Field name={t('packing.totalWeight')}>
<div className={`${PILL} px-3`}>
<WeightInput
value={item.weight_grams}
readOnly={!canEdit}
width={52}
onSave={(grams) => save({ weight_grams: grams })}
/>
<span className="text-content-faint">g</span>
</div>
</Field>
)}
</>
);
}
/**
* 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<PackingItemDetailProps>) {
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(
<>
<div role="presentation" className="fixed inset-0 z-[1098]" onClick={onClose} />
<div
role="dialog"
aria-label={item.name}
className="trek-menu-enter fixed z-[1099] overflow-y-auto"
onKeyDown={(e) => {
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
}}
>
<DetailHead key={item.name} item={item} canEdit={canEdit} save={save} onClose={onClose} />
<ListChoice item={item} categories={categories} canEdit={canEdit} save={save} />
<Amounts item={item} tripId={tripId} canEdit={canEdit} bagTrackingEnabled={bagTrackingEnabled} save={save} />
{bagTrackingEnabled && (
<BagChoice item={item} bags={bags} canEdit={canEdit} onCreateBag={onCreateBag} save={save} />
)}
{(bringers || sharing || sharedToMe) && <div style={POPOVER_DIVIDER} />}
{bringers && <Bringers item={item} members={tripMembers} onJoin={bringers.onJoin} onLeave={bringers.onLeave} />}
{sharing && (
<Visibility item={item} members={tripMembers} currentUserId={currentUserId} onSetSharing={sharing} />
)}
{sharedToMe && (
<div className="px-2.5 py-1.5 text-caption text-content-muted">
{t('packing.takenCareOf', { name: item.owner_username || '' })}
</div>
)}
{canEdit && (
<>
<div style={POPOVER_DIVIDER} />
{clone && (
<PopoverItem
icon={<Copy size={13} />}
label={t('packing.cloneToMine')}
onClick={() => {
clone(item.id);
onClose();
}}
/>
)}
<PopoverItem
icon={<Trash2 size={13} />}
label={t('common.delete')}
danger
onClick={() => {
onClose();
onDelete();
}}
/>
</>
)}
</div>
</>,
document.body
);
}
@@ -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(<PackingListPanel tripId={1} items={[item]} />);
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(<PackingListPanel tripId={1} items={items} />);
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(<PackingListPanel tripId={1} items={items} />);
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(<PackingListPanel tripId={1} items={items} />);
await user.click(screen.getByText('Open'));
render(<PackingListPanel tripId={1} items={items} hideDone />);
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(<PackingListPanel tripId={1} items={items} />);
await user.click(screen.getByText('Done'));
render(<PackingListPanel tripId={1} items={items} hideDone={false} />);
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(<PackingListPanel tripId={1} items={items} hideDone />);
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(<PackingListPanel tripId={1} items={items} />);
const { rerender } = render(<PackingListPanel tripId={1} items={items} sort="name" />);
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(<PackingListPanel tripId={1} items={items} sort="manual" />);
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(<PackingListPanel tripId={1} items={items} />);
expect(screen.getByRole('button', { name: 'A to Z' })).toHaveAttribute('aria-pressed', 'true');
const { container } = render(<PackingListPanel tripId={1} items={items} sort="name" />);
// 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(<PackingListPanel tripId={1} items={[item]} />);
// 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(<PackingListPanel tripId={1} items={items} />);
// 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(<PackingListPanel tripId={1} items={items} />);
// 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(<PackingListPanel tripId={1} items={items} />);
// 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(<PackingListPanel tripId={1} items={[item, item2]} />);
// 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<HTMLButtonElement>('.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(<PackingListPanel tripId={1} items={items} />);
// 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<HTMLElement>(':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(<PackingListPanel tripId={1} items={[item]} />);
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(<PackingListPanel tripId={1} items={[item]} />);
@@ -1115,15 +1067,12 @@ describe('PackingListPanel', () => {
return HttpResponse.json({ item: buildPackingItem({ id: 74, category: 'Documents' }) });
})
);
const { container } = render(<PackingListPanel tripId={1} items={[itemA, itemB]} />);
render(<PackingListPanel tripId={1} items={[itemA, itemB]} />);
// Open the first item's menu and its Move to List entry
fireEvent.click(container.querySelector<HTMLButtonElement>('.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<string, unknown> | 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(<PackingListPanel tripId={1} items={items} />);
render(<PackingListPanel tripId={1} items={items} />);
// 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(<PackingListPanel tripId={1} items={[item]} />);
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(<PackingListPanel tripId={1} items={[placeholder]} />);
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(<PackingListPanel tripId={1} inlineHeader={false} items={[buildPackingItem({ id: 91, name: 'Towel', checked: 1 }), buildPackingItem({ id: 92, name: 'Soap' })]} />);
const items = [buildPackingItem({ id: 91, name: 'Towel', checked: 1 }), buildPackingItem({ id: 92, name: 'Soap' })];
const { rerender } = render(<PackingListPanel tripId={1} inlineHeader={false} items={items} clearCheckedSignal={0} />);
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(<PackingListPanel tripId={1} inlineHeader={false} items={items} clearCheckedSignal={1} />);
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(<PackingListPanel tripId={1} inlineHeader={false} items={items} clearCheckedSignal={0} />);
rerender(<PackingListPanel tripId={1} inlineHeader={false} items={items} clearCheckedSignal={1} />);
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(<PackingListPanel tripId={1} inlineHeader={false} items={items} openBagsSignal={0} />);
await waitFor(() => expect(useAddonStore.getState().bagTracking).toBe(true));
const before = (await screen.findAllByText('Main Bag')).length;
rerender(<PackingListPanel tripId={1} inlineHeader={false} items={items} openBagsSignal={1} />);
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 () => {
@@ -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()
})
@@ -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.
<div style={{ ...COMPOSER, gap: 9, margin: '6px 4px 0', paddingBlock: 4, paddingInlineEnd: 4, paddingInlineStart: 27 }}>
<span aria-hidden style={{ width: 20, height: 20, borderRadius: 6, border: '1.5px solid var(--text-faint)', opacity: 0.6, flexShrink: 0 }} />
// 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.
<div style={{ display: 'flex', alignItems: 'center', gap: 9, margin: '6px 4px 0', minHeight: 36, paddingBlock: 4, paddingInlineEnd: 8, paddingInlineStart: 28, borderRadius: 10, background: 'var(--bg-secondary)' }}>
<span aria-hidden style={{ width: 20, height: 20, borderRadius: 6, border: '1.5px solid var(--text-faint)', flexShrink: 0 }} />
<input
ref={addItemRef}
autoFocus
@@ -329,18 +330,16 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
}
if (e.key === 'Escape') { setShowAddItem(false); setNewItemName('') }
}}
onBlur={() => { 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. */}
<button type="button" onClick={() => { void onAddItem(kategorie, newItemName.trim()); setNewItemName(''); setTimeout(() => addItemRef.current?.focus(), 30) }}
disabled={!newItemName.trim()} aria-label={t('common.add')}
style={composerConfirm(!!newItemName.trim())}>
<Plus size={15} strokeWidth={2.5} />
</button>
<button type="button" onClick={() => { setShowAddItem(false); setNewItemName('') }} aria-label={t('common.cancel')}
style={{ width: 28, height: 28, borderRadius: 8, border: 'none', background: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', flexShrink: 0, color: 'var(--text-faint)' }}>
<X size={14} />
className={`grid size-6 shrink-0 place-items-center rounded-full border-0 transition-colors ${newItemName.trim() ? 'cursor-pointer bg-accent text-accent-text' : 'cursor-default bg-transparent text-content-faint'}`}>
<Plus size={13} strokeWidth={2.5} />
</button>
</div>
) : (
@@ -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 (
<div style={{ padding: inlineHeader ? '20px 24px 16px' : '0 0 16px', flexShrink: 0, borderBottom: inlineHeader ? '1px solid rgba(0,0,0,0.06)' : undefined }}>
<div style={{ padding: inlineHeader ? '20px 24px 16px' : 0, flexShrink: 0, borderBottom: inlineHeader ? '1px solid rgba(0,0,0,0.06)' : undefined }}>
<div style={{ display: 'flex', alignItems: inlineHeader ? 'flex-start' : 'center', justifyContent: 'space-between', gap: 14 }}>
{inlineHeader ? (
<div>
@@ -86,7 +86,7 @@ export function PackingHeader(S: PackingState) {
<FolderPlus size={12} /> <span className="hidden sm:inline">{t('packing.saveAsTemplate')}</span>
</button>
)}
{bagTrackingEnabled && (
{inlineHeader && bagTrackingEnabled && (
<button type="button" onClick={() => setShowBagModal(true)} className="xl:!hidden"
style={{
display: 'flex', alignItems: 'center', gap: 5, padding: '5px 11px', borderRadius: 99,
@@ -101,8 +101,9 @@ export function PackingHeader(S: PackingState) {
</div>
</div>
{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.
<div className="hidden sm:block" style={{ marginTop: 14, marginBottom: 2, padding: '14px 18px', borderRadius: 16, background: 'var(--bg-card)', border: '1px solid var(--border-secondary)' }}>
<div className="flex items-center" style={{ gap: 16 }}>
{fortschritt === 100 ? (
@@ -166,17 +167,6 @@ export function PackingHeader(S: PackingState) {
</div>
</div>
{/* Under the Lists bar the clean-up sits with the count it clears. */}
{!inlineHeader && canEdit && abgehakt > 0 && (
<button type="button" onClick={handleClearChecked} style={{
display: 'inline-flex', alignItems: 'center', gap: 5, flexShrink: 0, padding: '5px 11px', borderRadius: 99,
border: 'none', background: 'rgba(239,68,68,0.1)', color: '#ef4444', cursor: 'pointer', fontFamily: 'inherit',
fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600,
}}>
<Trash2 size={13} strokeWidth={2.2} />
{t('packing.clearChecked', { count: abgehakt })}
</button>
)}
</div>
</div>
)}
File diff suppressed because it is too large Load Diff
@@ -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<PackingBag | undefined>
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<HTMLButtonElement>(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<HTMLButtonElement>(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 (
<input type="text" value={name} placeholder="..." onChange={e => 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 && <span className="shrink-0 text-caption font-semibold tabular-nums text-content-muted">{packed}/{quantity}</span>}
{!partly && quantity > 1 && <span className="shrink-0 text-caption font-medium tabular-nums text-content-faint">×{quantity}</span>}
{sharedToMe && (
<Tooltip label={t('packing.takenCareOf', { name: item.owner_username || '' })}>
<span className="packing-row-badge inline-flex size-[22px] shrink-0 items-center justify-center rounded-full text-accent"
aria-label={t('packing.takenCareOf', { name: item.owner_username || '' })}
style={{ background: 'color-mix(in srgb, var(--accent) 12%, transparent)' }}>
<HandHelping size={12} />
</span>
</Tooltip>
)}
{sharedByMe && (
<Tooltip label={`${t('packing.sharedWithCount', { count: recipients.length })}: ${recipients.map(r => r.username).join(', ')}`}>
<span className="packing-row-badge inline-flex h-[22px] shrink-0 items-center gap-[3px] rounded-full bg-surface-tertiary px-[7px] text-caption font-bold text-content-muted"
aria-label={t('packing.sharedWithCount', { count: recipients.length })}>
<UserRound size={11} /> {recipients.length}
</span>
</Tooltip>
)}
{bringers.length > 0 && (
<Tooltip label={t('packing.broughtBy', { name: packingBringerNames(item) })} content={<BringersCard bringers={bringers} />}>
<span className="packing-row-badge inline-flex shrink-0 items-center" aria-label={t('packing.broughtBy', { name: packingBringerNames(item) })}>
<BringerAvatar bringer={bringers[0]} />
{bringers.length > 1 && <MoreBringers count={bringers.length - 1} />}
</span>
</Tooltip>
)}
</>
)
}
/**
* 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<HTMLDivElement>(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 (
<div
ref={rowRef}
className="group packing-item-row"
onMouseEnter={() => 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 && <span aria-hidden className="pointer-events-none absolute inset-x-2.5 top-0 h-px bg-edge-faint" />}
{canDrag && (
{divider && !active && <span aria-hidden className="pointer-events-none absolute inset-x-2.5 top-0 h-px bg-edge-faint" />}
{dnd && (
<div
draggable
onDragStart={e => { 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 }}
>
<GripVertical size={13} />
</div>
)}
{/* Sorted A-Z there is nothing to drag, but the box keeps its column. */}
{!canDrag && canEdit && !isPlaceholder && <span aria-hidden style={{ width: 13, flexShrink: 0 }} />}
{/* The phone's box: filled with the accent once packed, an outline until then. */}
<button type="button" onClick={handleToggle} className="packing-check" aria-pressed={!!item.checked} style={{
{!dnd && canEdit && !isPlaceholder && <span aria-hidden style={{ width: 13, flexShrink: 0 }} />}
<button type="button" onClick={() => void togglePackingItem(tripId, item.id, !item.checked)} className="packing-check" aria-pressed={!!item.checked} style={{
flexShrink: 0, cursor: 'pointer', padding: 0, width: 20, height: 20, borderRadius: 6,
display: 'grid', placeItems: 'center',
border: `1.5px solid ${item.checked || partlyPacked ? 'var(--accent)' : 'var(--text-faint)'}`,
@@ -199,266 +192,25 @@ export function ArtikelZeile({ item, tripId, categories, onCategoryChange: _onCa
}} />
</button>
{editing && canEdit ? (
<input
type="text" value={editName} autoFocus
placeholder={isPlaceholder ? '...' : undefined}
onChange={e => 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 ? (
<button
type="button"
onClick={() => setEditing(true)}
style={{ ...nameStyle, border: 'none', background: 'none', padding: 0, textAlign: 'start', fontFamily: 'inherit' }}
>
{item.name}
</button>
{isPlaceholder && canEdit ? (
<PlaceholderField item={item} tripId={tripId} onFilled={onPlaceholderFilled} />
) : (
<span style={nameStyle}>
{item.name}
</span>
)}
{/* 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 && (
<Tooltip label={t('packing.takenCareOf', { name: item.owner_username || '' })}>
<span className="packing-row-badge" aria-label={t('packing.takenCareOf', { name: item.owner_username || '' })}
style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, width: 22, height: 22, borderRadius: 99, color: 'var(--accent)', background: 'color-mix(in srgb, var(--accent) 12%, transparent)' }}>
<HandHelping size={12} />
</span>
</Tooltip>
)}
{!isPlaceholder && sharedByMe && (
<Tooltip label={`${t('packing.sharedWithCount', { count: recipients.length })}: ${recipients.map(r => r.username).join(', ')}`}>
<span className="packing-row-badge" aria-label={t('packing.sharedWithCount', { count: recipients.length })}
style={{ display: 'inline-flex', alignItems: 'center', gap: 3, flexShrink: 0, height: 22, padding: '0 7px', borderRadius: 99, fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 700, color: 'var(--text-muted)', background: 'var(--bg-tertiary)' }}>
<UserRound size={11} /> {recipients.length}
</span>
</Tooltip>
)}
{!isPlaceholder && !item.is_private && bringers.length > 0 && (
<Tooltip label={t('packing.broughtBy', { name: packingBringerNames(item) })} content={<BringersCard bringers={bringers} />}>
{/* A click on the faces opens the menu right at the bringers (#3098). */}
{canPickBringers ? (
<button type="button" className="packing-row-badge" aria-label={t('packing.broughtBy', { name: packingBringerNames(item) })}
onClick={() => { setShowItemMenu(true); setShowMenuBringers(true) }}
style={{ display: 'inline-flex', alignItems: 'center', flexShrink: 0, border: 'none', background: 'none', padding: 0, cursor: 'pointer' }}>
<BringerAvatar bringer={bringers[0]} />
{bringers.length > 1 && <MoreBringers count={bringers.length - 1} />}
</button>
) : (
<span className="packing-row-badge" aria-label={t('packing.broughtBy', { name: packingBringerNames(item) })}
style={{ display: 'inline-flex', alignItems: 'center', flexShrink: 0 }}>
<BringerAvatar bringer={bringers[0]} />
{bringers.length > 1 && <MoreBringers count={bringers.length - 1} />}
</span>
)}
</Tooltip>
)}
<div className="packing-row-inline-actions" style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
{canEdit && !isPlaceholder && quantity > 1 && (
<PackedCounter packed={packed} quantity={quantity} onChange={count => setPackedCount(tripId, item.id, count)} style={reveal(active || partlyPacked)} />
)}
{/* Quantity */}
{canEdit && <QuantityInput value={quantity} onSave={qty => updatePackingItem(tripId, item.id, { quantity: qty })} style={badge(active || quantity > 1)} />}
{/* Weight + Bag (when enabled) */}
{bagTrackingEnabled && (
<>
<div style={{ display: 'flex', alignItems: 'center', gap: 2, border: '1px solid var(--border-primary)', borderRadius: 8, padding: '3px 6px', background: 'transparent', ...badge(active || item.weight_grams != null) }}>
<WeightInput value={item.weight_grams} readOnly={!canEdit} width={36} onSave={saveWeight} />
<span style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', userSelect: 'none' }}>g</span>
</div>
<div style={{ position: 'relative' }}>
<button type="button"
ref={bagBtnRef}
onClick={() => canEdit && setShowBagPicker(p => !p)}
style={{
width: 22, height: 22, borderRadius: '50%', cursor: canEdit ? 'pointer' : 'default', padding: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
border: item.bag_id ? `2.5px solid ${selectedBag?.color || 'var(--border-primary)'}` : '2px dashed var(--border-primary)',
background: item.bag_id ? `${selectedBag?.color || 'var(--border-primary)'}30` : 'transparent',
opacity: item.bag_id || active ? 1 : 0.45, transition: 'opacity 120ms ease',
}}
>
{!item.bag_id && <Package size={9} className="text-content-faint" />}
</button>
{showBagPicker && bagBox && createPortal(
<>
<div role="presentation" style={{ position: 'fixed', inset: 0, zIndex: 'var(--z-toast)' }} onClick={() => { setShowBagPicker(false); setBagInlineCreate(false); setBagInlineName('') }} />
<div className="trek-menu-enter" style={{
...POPOVER, position: 'fixed', zIndex: 'var(--z-toast)', width: 210, overflowY: 'auto',
top: bagBox.top, bottom: bagBox.bottom, maxHeight: bagBox.maxHeight,
left: Math.max(8, bagBox.left + bagBox.width - 210),
}}>
<div style={POPOVER_CAPTION}>{t('packing.bags')}</div>
{item.bag_id && (
<PopoverItem icon={<span style={{ width: 10, height: 10, borderRadius: '50%', border: '1.5px dashed var(--text-faint)', display: 'inline-block' }} />} 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 => (
<PopoverItem key={b.id} icon={<span style={{ width: 10, height: 10, borderRadius: '50%', background: b.color, display: 'inline-block' }} />} 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 && <div style={POPOVER_DIVIDER} />}
{bagInlineCreate ? (
<div style={{ display: 'flex', gap: 6, padding: 4 }}>
<input autoFocus value={bagInlineName} onChange={e => 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)' }} />
<button type="button" aria-label={t('common.add')} onClick={async () => {
if (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)
}
}}
style={{ width: 30, borderRadius: 8, border: 'none', background: 'var(--accent)', color: 'var(--accent-text)', cursor: 'pointer', display: 'grid', placeItems: 'center', flexShrink: 0, opacity: bagInlineName.trim() ? 1 : 0.35 }}>
<Plus size={13} strokeWidth={2.5} />
</button>
</div>
) : (
<PopoverItem icon={<Plus size={13} />} label={t('packing.addBag')} muted onClick={() => setBagInlineCreate(true)} />
)}
</div>
</>,
document.body,
)}
</div>
</>
)}
</div>
{/* 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 && (
<div className="packing-row-inline-actions" style={{ display: 'flex', gap: 2, alignItems: 'center', flexShrink: 0, ...reveal(active) }}>
<button type="button" onClick={handleDelete} title={t('common.delete')} aria-label={t('common.delete')} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '3px 4px', borderRadius: 6, display: 'flex', color: 'var(--text-faint)' }}
onMouseEnter={e => e.currentTarget.style.color = '#ef4444'} onMouseLeave={e => e.currentTarget.style.color = 'var(--text-faint)'}>
<Trash2 size={13} />
<button type="button" onClick={() => setOpen(true)} aria-haspopup="dialog" aria-expanded={open}
className="flex min-w-0 flex-1 cursor-pointer items-center gap-2.5 rounded-md border-0 bg-transparent p-0 font-[inherit] outline-none [-webkit-tap-highlight-color:transparent] focus-visible:ring-2 focus-visible:ring-accent">
<span style={nameStyle(!!item.checked, isPlaceholder)}>{item.name}</span>
{!isPlaceholder && <RowFacts item={item} tripMembers={tripMembers} currentUserId={currentUserId} />}
<ChevronRight size={14} aria-hidden className="shrink-0 text-content-faint transition-opacity" style={{ opacity: active ? 1 : 0 }} />
</button>
</div>
)}
{canEdit && (
<div className="packing-row-overflow" style={{ display: 'flex', flexShrink: 0, position: 'relative', ...reveal(active) }}>
<button type="button"
ref={itemMenuBtnRef}
onClick={() => (showItemMenu ? closeItemMenu() : setShowItemMenu(true))}
title={t('common.showMore')}
aria-label={t('common.showMore')} aria-expanded={showItemMenu}
style={{ width: 26, height: 26, borderRadius: 7, border: 'none', background: showItemMenu ? 'var(--bg-tertiary)' : 'transparent', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-faint)', padding: 0 }}
>
<MoreHorizontal size={16} />
</button>
{showItemMenu && (() => {
const rect = itemMenuBtnRef.current?.getBoundingClientRect()
return (
<>
<div role="presentation" style={{ position: 'fixed', inset: 0, zIndex: 1098 }} onClick={closeItemMenu} />
<div className="trek-menu-enter" style={{
...POPOVER,
position: 'fixed',
right: rect ? Math.max(8, window.innerWidth - rect.right) : 8,
top: rect ? rect.bottom + 6 : 0,
zIndex: 1099,
width: 'min(240px, calc(100vw - 16px))',
maxHeight: '70vh',
overflowY: 'auto',
}}>
{/* Quantity, weight and bag sit in the row itself on a wide screen. */}
<div className="packing-menu-phone-only">
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '6px 8px' }}>
<span style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0 }}>{t('packing.quantity')}</span>
<QuantityInput value={item.quantity || 1} onSave={qty => updatePackingItem(tripId, item.id, { quantity: qty })} />
</div>
{bagTrackingEnabled && (
<>
<div style={{ height: 1, background: 'var(--bg-tertiary)', margin: '4px 0' }} />
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '6px 8px' }}>
<span style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: 0 }}>{t('packing.totalWeight')}</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 2, border: '1px solid var(--border-primary)', borderRadius: 8, padding: '3px 6px', background: 'transparent' }}>
<WeightInput value={item.weight_grams} readOnly={!canEdit} width={42} onSave={saveWeight} />
<span style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', userSelect: 'none' }}>g</span>
</div>
</div>
<div style={{ padding: '2px 0' }}>
<PopoverItem icon={<Package size={13} />} 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 => (
<PopoverItem key={b.id} icon={<span style={{ width: 10, height: 10, borderRadius: '50%', background: b.color, display: 'inline-block' }} />} 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')) }
}} />
))}
</div>
</>
)}
<div style={POPOVER_DIVIDER} />
</div>
<PopoverItem icon={<span style={{ width: 9, height: 9, borderRadius: '50%', background: katColor(item.category || t('packing.defaultCategory'), categories), display: 'inline-block' }} />} label={t('packing.changeCategory')} onClick={() => setShowMenuCategories(v => !v)}
trailing={showMenuCategories ? <ChevronDown size={13} style={{ color: 'var(--text-faint)', flexShrink: 0 }} /> : <ChevronRight size={13} style={{ color: 'var(--text-faint)', flexShrink: 0 }} />} />
{showMenuCategories && (
<div style={{ marginBlock: '2px 4px', marginInlineStart: 18, paddingInlineStart: 6, borderInlineStart: '1px solid var(--border-faint)' }}>
{categories.map(cat => (
<PopoverItem key={cat} icon={<span style={{ width: 8, height: 8, borderRadius: '50%', background: katColor(cat, categories), display: 'inline-block' }} />} label={cat} active={cat === (item.category || t('packing.defaultCategory'))} onClick={() => handleCatChange(cat)} />
))}
</div>
)}
{canPickBringers && (
<>
<PopoverItem icon={<HandHelping size={13} />} label={t('packing.bringersTitle')} onClick={() => setShowMenuBringers(v => !v)}
trailing={showMenuBringers ? <ChevronDown size={13} style={{ color: 'var(--text-faint)', flexShrink: 0 }} /> : <ChevronRight size={13} style={{ color: 'var(--text-faint)', flexShrink: 0 }} />} />
{showMenuBringers && (
<div style={{ marginBlock: '2px 4px', marginInlineStart: 18, paddingInlineStart: 6, borderInlineStart: '1px solid var(--border-faint)' }}>
{tripMembers.map(m => (
<PopoverItem key={m.id} icon={<BringerAvatar bringer={{ name: m.username, avatar: m.avatar_url ?? m.avatar ?? null }} />} label={m.username} active={isBringer(m.id)} onClick={() => toggleBringer(m.id)} />
))}
</div>
)}
</>
)}
{canShare && onClone && onJoin && onLeave && (
<PackingShareControl
variant="menu"
item={item}
tripMembers={tripMembers}
currentUserId={currentUserId}
onSetSharing={onSetSharing!}
onClone={onClone}
onJoin={onJoin}
onLeave={onLeave}
onAction={() => setShowItemMenu(false)}
/>
)}
<div style={POPOVER_DIVIDER} />
<PopoverItem icon={<Pencil size={13} />} label={t('common.rename')} onClick={() => { setEditing(true); setShowItemMenu(false) }} />
<PopoverItem icon={<Trash2 size={13} />} label={t('common.delete')} danger onClick={() => { setShowItemMenu(false); void handleDelete() }} />
</div>
</>
)
})()}
</div>
{open && (
<PackingItemDetail
item={item} tripId={tripId} anchorRef={rowRef} onClose={() => 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()}
/>
)}
</div>
)
@@ -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(<QuantityInput value={1} onSave={() => {}} />);
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(<QuantityInput value={1} onSave={onSave} />);
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(<QuantityInput value={1} onSave={onSave} />);
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);
});
});
@@ -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 (
<div style={{ display: 'flex', alignItems: 'center', gap: 2, border: '1px solid var(--border-primary)', borderRadius: 8, padding: '3px 6px', background: 'transparent', flexShrink: 0, ...style }}>
<NumericInput
value={local}
onValueChange={setLocal}
onBlur={commit}
onKeyDown={e => { 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 }}
/>
<span style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', fontWeight: 500 }}>x</span>
</div>
)
}
@@ -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 (
<button type="button" onClick={() => setView(id)} style={segment(active)}>
<button type="button" onClick={() => setView(id)} aria-pressed={active} style={{
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',
}}>
{icon}{label}
<span style={{
fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 700, borderRadius: 99, padding: '0 6px',
@@ -39,30 +33,22 @@ export function PackingViewTabs(S: PackingState) {
)
}
const filterPill = (id: string, label: string) => (
<button type="button" key={id} onClick={() => setFilter(id)} style={segment(filter === id)}>{label}</button>
)
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 0 0', flexShrink: 0, flexWrap: 'wrap' }}>
<div style={track}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0 0', flexShrink: 0, flexWrap: 'wrap' }}>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 2, padding: 3, borderRadius: 999, background: 'var(--bg-tertiary)' }}>
{viewPill('common', <Users size={14} />, t('packing.viewCommon'), commonCount)}
{viewPill('personal', <UserRound size={14} />, t('packing.viewPersonal'), personalCount)}
</div>
{items.length > 0 && (
<div style={track}>
{filterPill('alle', t('packing.filterAll'))}
{filterPill('offen', t('packing.filterOpen'))}
{filterPill('erledigt', t('packing.filterDone'))}
</div>
)}
{items.length > 0 && (
// A second click on the active switch goes back to the manual order.
<div role="group" aria-label={t('packing.sortBy')} style={{ ...track, marginInlineStart: 'auto' }}>
<button type="button" aria-pressed={sort === 'name'} title={t('packing.sortByName')}
onClick={() => setSort(sort === 'name' ? 'manual' : 'name')} style={segment(sort === 'name')}>
<ArrowDownAZ size={14} /><span className="hidden sm:inline">{t('packing.sortByName')}</span>
</button>
{viewTotal > 0 && (
<div className="ms-auto inline-flex items-center gap-2.5 text-caption tabular-nums text-content-muted">
{fortschritt === 100 ? (
<span className="inline-flex items-center gap-1.5 font-semibold text-success"><CheckCheck size={14} strokeWidth={2.5} />{t('packing.allPacked')}</span>
) : (
<span>{t('packing.packedCount', { packed: abgehakt, total: viewTotal })}</span>
)}
<span aria-hidden className="h-1.5 w-[120px] overflow-hidden rounded-full bg-surface-tertiary">
<span className={`block h-full rounded-full transition-[width] duration-500 ${fortschritt === 100 ? 'bg-success' : 'bg-accent'}`} style={{ width: `${fortschritt}%` }} />
</span>
</div>
)}
</div>
@@ -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 (
<button type="button" onClick={props.onApplied}>
Apply template
</button>
);
},
}));
vi.mock('./PackingExportMenu', () => ({
default: (props: { onChosen?: () => void }) => {
exportProps(props);
return (
<button type="button" onClick={props.onChosen}>
Print or save as PDF
</button>
);
},
}));
import PackingListsMenu from './PackingListsMenu';
type Props = ComponentProps<typeof PackingListsMenu>;
function setup(overrides: Partial<Props> = {}) {
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(<PackingListsMenu {...props} />);
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);
});
});
@@ -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<PackingListsMenuProps>) {
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 ? <Check size={13} className="shrink-0 text-content-muted" /> : null);
return (
<div className="relative flex">
<button
type="button"
onClick={() => setOpen((v) => !v)}
aria-haspopup="menu"
aria-expanded={open}
aria-label={t('common.showMore')}
title={t('common.showMore')}
className={buttonClassName}
style={buttonStyle}
>
<MoreHorizontal size={14} strokeWidth={2.5} />
</button>
{open && <div role="presentation" className="fixed inset-0 z-[99]" onClick={close} />}
<div
role="menu"
hidden={!open}
className="trek-menu-enter absolute end-0 top-full z-[100] mt-1.5 w-[260px] origin-top-right"
style={POPOVER}
>
{canEdit && <ApplyTemplateButton tripId={tripId} visibility={view} variant="menu" onApplied={close} />}
{canEdit && isAdmin && hasItems && (
<PopoverItem
icon={<FolderPlus size={13} />}
label={t('packing.saveAsTemplate')}
onClick={run(onSaveTemplate)}
/>
)}
{canEdit && <PopoverItem icon={<Download size={13} />} label={t('packing.import')} onClick={run(onImport)} />}
<PackingExportMenu tripId={tripId} view={view} variant="menu" onChosen={close} />
{hasItems && (
<>
<div style={POPOVER_DIVIDER} />
<PopoverItem
icon={<ArrowDownAZ size={13} />}
label={t('packing.sortByName')}
trailing={tick(sort === 'name')}
onClick={() => onSortChange(sort === 'name' ? 'manual' : 'name')}
/>
<PopoverItem
icon={<EyeOff size={13} />}
label={t('packing.hideDone')}
trailing={tick(hideDone)}
onClick={() => onHideDoneChange(!hideDone)}
/>
</>
)}
{bagTracking && (
<div className="xl:hidden">
<PopoverItem icon={<Luggage size={13} />} label={t('packing.bags')} onClick={run(onOpenBags)} />
</div>
)}
{canEdit && packedCount > 0 && (
<>
<div style={POPOVER_DIVIDER} />
<PopoverItem
icon={<Trash2 size={13} />}
label={t('packing.clearChecked', { count: packedCount })}
danger
onClick={run(onClearChecked)}
/>
</>
)}
</div>
</div>
);
}
@@ -1,318 +0,0 @@
// FE-W4PSC-001 to FE-W4PSC-015, FE-W5PSC-001 to FE-W5PSC-009
import { describe, it, expect, vi } from 'vitest'
import type { PackingItem } from '../../types'
import { render, screen, fireEvent } from '../../../tests/helpers/render'
import PackingShareControl from './PackingShareControl'
import type { TripMember } from './usePackingListPanel'
const MEMBERS = [
{ id: 1, username: 'ada' },
{ id: 2, username: 'bob' },
{ id: 3, username: 'cleo' },
] as unknown as TripMember[]
function item(overrides: Partial<PackingItem> = {}): PackingItem {
return { id: 5, name: 'Tent', is_private: 0, owner_id: 1, recipients: [], contributors: [], ...overrides } as unknown as PackingItem
}
function setup(it_: PackingItem, currentUserId = 1) {
const onSetSharing = vi.fn()
const onClone = vi.fn()
const onJoin = vi.fn()
const onLeave = vi.fn()
const utils = render(
<PackingShareControl
item={it_} tripMembers={MEMBERS} currentUserId={currentUserId}
onSetSharing={onSetSharing} onClone={onClone} onJoin={onJoin} onLeave={onLeave}
/>,
)
return { onSetSharing, onClone, onJoin, onLeave, ...utils }
}
describe('PackingShareControl — owner', () => {
it('FE-W4PSC-001: shows the share trigger for the owner of a common item', () => {
setup(item())
expect(screen.getByRole('button', { name: /sharing/i })).toBeInTheDocument()
})
it('FE-W4PSC-002: opening the menu lists both tiers plus every other member', () => {
setup(item())
fireEvent.click(screen.getByRole('button', { name: /sharing/i }))
expect(screen.getByText(/^Shared$/)).toBeInTheDocument()
expect(screen.getByText(/^Personal$/)).toBeInTheDocument()
expect(screen.getByRole('button', { name: /bob/ })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /cleo/ })).toBeInTheDocument()
// Neither the owner nor the current user is offered as a recipient.
expect(screen.queryByRole('button', { name: /ada/ })).toBeNull()
})
it('FE-W4PSC-003: picking Personal reports the tier and closes the menu', () => {
const { onSetSharing } = setup(item())
fireEvent.click(screen.getByRole('button', { name: /sharing/i }))
fireEvent.click(screen.getByText(/^Personal$/))
expect(onSetSharing).toHaveBeenCalledWith(5, 'personal', [])
expect(screen.queryByText(/^Personal$/)).toBeNull()
})
it('FE-W4PSC-004: picking the common tier reports it', () => {
const { onSetSharing } = setup(item({ is_private: 1 } as Partial<PackingItem>))
fireEvent.click(screen.getByRole('button', { name: /sharing/i }))
fireEvent.click(screen.getByText(/^Shared$/))
expect(onSetSharing).toHaveBeenCalledWith(5, 'common', [])
})
it('FE-W4PSC-005: toggling a member on shares the item with them', () => {
const { onSetSharing } = setup(item({ is_private: 1 } as Partial<PackingItem>))
fireEvent.click(screen.getByRole('button', { name: /sharing/i }))
fireEvent.click(screen.getByRole('button', { name: /bob/ }))
expect(onSetSharing).toHaveBeenCalledWith(5, 'shared', [2])
})
it('FE-W4PSC-006: toggling an existing recipient off removes them', () => {
const { onSetSharing } = setup(item({ is_private: 1, recipients: [{ user_id: 2 }, { user_id: 3 }] } as unknown as Partial<PackingItem>))
fireEvent.click(screen.getByRole('button', { name: /sharing/i }))
fireEvent.click(screen.getByRole('button', { name: /bob/ }))
expect(onSetSharing).toHaveBeenCalledWith(5, 'shared', [3])
})
it('FE-W4PSC-007: an item with recipients reads as the shared tier', () => {
setup(item({ is_private: 1, recipients: [{ user_id: 2 }] } as unknown as Partial<PackingItem>))
fireEvent.click(screen.getByRole('button', { name: /sharing/i }))
// The chosen recipient carries the check mark.
expect(screen.getByRole('button', { name: /bob/ }).querySelector('svg')).not.toBeNull()
})
it('FE-W4PSC-008: shows a hint when there is nobody else to share with', () => {
render(
<PackingShareControl
item={item()} tripMembers={[MEMBERS[0]]} currentUserId={1}
onSetSharing={() => {}} onClone={() => {}} onJoin={() => {}} onLeave={() => {}}
/>,
)
fireEvent.click(screen.getByRole('button', { name: /sharing/i }))
expect(screen.getByText(/no one/i)).toBeInTheDocument()
})
it('FE-W4PSC-009: the scrim closes the menu', () => {
const { baseElement } = setup(item())
fireEvent.click(screen.getByRole('button', { name: /sharing/i }))
// The scrim is the portaled full-screen layer that sits just under the menu.
fireEvent.click(baseElement.querySelector('div[style*="z-index: 1099"]')!)
expect(screen.queryByText(/^Personal$/)).toBeNull()
})
it('FE-W4PSC-010: the trigger toggles the menu closed again', () => {
setup(item())
const trigger = screen.getByRole('button', { name: /sharing/i })
fireEvent.click(trigger)
expect(screen.getByText(/^Personal$/)).toBeInTheDocument()
fireEvent.click(trigger)
expect(screen.queryByText(/^Personal$/)).toBeNull()
})
it('FE-W4PSC-011: an unowned item is treated as the current user own', () => {
setup(item({ owner_id: null } as unknown as Partial<PackingItem>), 9)
expect(screen.getByRole('button', { name: /sharing/i })).toBeInTheDocument()
})
})
describe('PackingShareControl — other members', () => {
it('FE-W4PSC-012: a non-owner can pledge to co-bring a common item', () => {
const { onJoin } = setup(item(), 2)
const buttons = screen.getAllByRole('button')
expect(buttons).toHaveLength(2)
fireEvent.click(buttons[0])
expect(onJoin).toHaveBeenCalledWith(5)
})
it('FE-W4PSC-013: a pledged contributor can withdraw again', () => {
const { onLeave } = setup(item({ contributors: [{ user_id: 2 }] } as unknown as Partial<PackingItem>), 2)
fireEvent.click(screen.getAllByRole('button')[0])
expect(onLeave).toHaveBeenCalledWith(5, 2)
})
it('FE-W4PSC-014: a non-owner can clone a common item to their own list', () => {
const { onClone } = setup(item(), 2)
fireEvent.click(screen.getAllByRole('button')[1])
expect(onClone).toHaveBeenCalledWith(5)
})
it('FE-W4PSC-015: a recipient of a shared item gets no controls', () => {
const { container } = setup(item({ is_private: 1, recipients: [{ user_id: 2 }] } as unknown as Partial<PackingItem>), 2)
expect(container).toBeEmptyDOMElement()
})
})
describe('PackingShareControl — hover affordances', () => {
it('FE-W5PSC-001: the trigger of a common item highlights on hover and resets on leave', () => {
setup(item())
const trigger = screen.getByRole('button', { name: /sharing/i })
fireEvent.mouseEnter(trigger)
expect(trigger.style.color).toBe('var(--text-secondary)')
fireEvent.mouseLeave(trigger)
expect(trigger.style.color).toBe('var(--text-faint)')
})
it('FE-W5PSC-002: a non-common item keeps its accent colour while hovered', () => {
setup(item({ is_private: 1 } as Partial<PackingItem>))
const trigger = screen.getByRole('button', { name: /sharing/i })
fireEvent.mouseEnter(trigger)
expect(trigger.style.color).toBe('var(--accent)')
fireEvent.mouseLeave(trigger)
expect(trigger.style.color).toBe('var(--accent)')
})
it('FE-W5PSC-003: the inactive tier row takes a hover background and drops it again', () => {
setup(item())
fireEvent.click(screen.getByRole('button', { name: /sharing/i }))
// The item is Common, so the Personal row is the inactive one.
const personalRow = screen.getByText(/^Personal$/).closest('button')!
fireEvent.mouseEnter(personalRow)
expect(personalRow.style.background).toBe('var(--bg-tertiary)')
fireEvent.mouseLeave(personalRow)
expect(personalRow.style.background).toBe('none')
})
it('FE-W5PSC-004: the active tier row ignores hover', () => {
setup(item())
fireEvent.click(screen.getByRole('button', { name: /sharing/i }))
const commonRow = screen.getByText(/^Shared$/).closest('button')!
const before = commonRow.style.background
fireEvent.mouseEnter(commonRow)
fireEvent.mouseLeave(commonRow)
expect(commonRow.style.background).toBe(before)
})
it('FE-W5PSC-005: a recipient row highlights on hover', () => {
setup(item({ is_private: 1 } as Partial<PackingItem>))
fireEvent.click(screen.getByRole('button', { name: /sharing/i }))
const bob = screen.getByRole('button', { name: /bob/ })
fireEvent.mouseEnter(bob)
expect(bob.style.background).toBe('var(--bg-tertiary)')
fireEvent.mouseLeave(bob)
expect(bob.style.background).toBe('none')
})
it('FE-W5PSC-006: the co-bring button of a non-contributor highlights on hover', () => {
setup(item(), 2)
const pledge = screen.getAllByRole('button')[0]
fireEvent.mouseEnter(pledge)
expect(pledge.style.color).toBe('var(--text-secondary)')
fireEvent.mouseLeave(pledge)
expect(pledge.style.color).toBe('var(--text-faint)')
})
it('FE-W5PSC-007: an already pledged contributor keeps the accent colour while hovered', () => {
setup(item({ contributors: [{ user_id: 2 }] } as unknown as Partial<PackingItem>), 2)
const pledge = screen.getAllByRole('button')[0]
fireEvent.mouseEnter(pledge)
fireEvent.mouseLeave(pledge)
expect(pledge.style.color).toBe('var(--accent)')
})
})
describe('PackingShareControl — optional fields', () => {
it('FE-W5PSC-008: an item without recipients or contributors reads as the common tier', () => {
const bare = { id: 7, name: 'Stove', is_private: 0, owner_id: 1 } as unknown as PackingItem
const onSetSharing = vi.fn()
render(
<PackingShareControl
item={bare} tripMembers={MEMBERS} currentUserId={1}
onSetSharing={onSetSharing} onClone={() => {}} onJoin={() => {}} onLeave={() => {}}
/>,
)
fireEvent.click(screen.getByRole('button', { name: /sharing/i }))
fireEvent.click(screen.getByRole('button', { name: /bob/ }))
expect(onSetSharing).toHaveBeenCalledWith(7, 'shared', [2])
})
it('FE-W5PSC-009: a non-owner without a contributor list can still pledge', () => {
const bare = { id: 8, name: 'Stove', is_private: 0, owner_id: 1 } as unknown as PackingItem
const onJoin = vi.fn()
render(
<PackingShareControl
item={bare} tripMembers={MEMBERS} currentUserId={3}
onSetSharing={() => {}} onClone={() => {}} onJoin={onJoin} onLeave={() => {}}
/>,
)
fireEvent.click(screen.getAllByRole('button')[0])
expect(onJoin).toHaveBeenCalledWith(8)
})
})
describe('PackingShareControl — menu variant', () => {
function setupMenu(it_: PackingItem, currentUserId = 1) {
const handlers = { onSetSharing: vi.fn(), onClone: vi.fn(), onJoin: vi.fn(), onLeave: vi.fn(), onAction: vi.fn() }
render(<PackingShareControl variant="menu" item={it_} tripMembers={MEMBERS} currentUserId={currentUserId} {...handlers} />)
return handlers
}
it('FE-W6PSC-001: the owner gets one whole line naming the current tier', () => {
setupMenu(item())
const line = screen.getByText('Sharing').closest('button')!
expect(line).toHaveTextContent('Shared')
fireEvent.click(line)
expect(screen.getByText(/^Personal$/)).toBeInTheDocument()
})
it('FE-W6PSC-002: someone else pledges or copies from full lines, and the menu closes after', () => {
const h = setupMenu(item({ owner_id: 2 }))
fireEvent.click(screen.getByRole('button', { name: 'I can bring that too' }))
fireEvent.click(screen.getByRole('button', { name: 'Copy to my list' }))
expect(h.onJoin).toHaveBeenCalledWith(5)
expect(h.onClone).toHaveBeenCalledWith(5)
expect(h.onAction).toHaveBeenCalledTimes(2)
})
it('FE-W6PSC-003: a co-bringer takes the pledge back from the same line', () => {
const h = setupMenu(item({ owner_id: 2, contributors: [{ user_id: 1, username: 'ada' }] } as Partial<PackingItem>))
fireEvent.click(screen.getByRole('button', { name: "I'm not bringing it" }))
expect(h.onLeave).toHaveBeenCalledWith(5, 1)
})
})
@@ -1,170 +0,0 @@
import { useState, useRef } from 'react'
import { createPortal } from 'react-dom'
import { Users, UserRound, Share2, Check, Copy, HandHelping } from 'lucide-react'
import { useTranslation } from '../../i18n'
import type { PackingItem } from '../../types'
import type { TripMember } from './usePackingListPanel'
interface Props {
item: PackingItem
tripMembers: TripMember[]
currentUserId?: number
onSetSharing: (id: number, visibility: 'common' | 'personal' | 'shared', recipientIds: number[]) => void
onClone: (id: number) => void
onJoin: (id: number) => void
onLeave: (id: number, userId: number) => void
/**
* 'menu' draws the control as full-width rows for an overflow menu, where the
* whole line is the target instead of a lone icon. `onAction` then closes that
* menu after a pledge or a copy.
*/
variant?: 'icon' | 'menu'
onAction?: () => void
}
/**
* Per-item sharing control for the three-tier packing model (#858). The owner
* (bringer) sets the tier — Common / Personal / Shared with specific people — via
* a dropdown; everyone else can pledge to co-bring a Common item ("I can bring
* that too") or clone it onto their own list.
*/
export default function PackingShareControl({ item, tripMembers, currentUserId, onSetSharing, onClone, onJoin, onLeave, variant = 'icon', onAction }: Props) {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
const [pos, setPos] = useState<{ top: number; right: number } | null>(null)
const btnRef = useRef<HTMLButtonElement>(null)
// The dropdown is portaled to <body> and fixed-positioned from the button so it
// can't be clipped by the packing panel's overflow.
const toggle = () => {
if (open) { setOpen(false); return }
const r = btnRef.current?.getBoundingClientRect()
if (r) setPos({ top: r.bottom + 4, right: window.innerWidth - r.right })
setOpen(true)
}
const isCommon = !item.is_private
const isOwner = item.owner_id == null || item.owner_id === currentUserId
const recipientIds = (item.recipients || []).map(r => r.user_id)
const visibility: 'common' | 'personal' | 'shared' = isCommon ? 'common' : recipientIds.length > 0 ? 'shared' : 'personal'
const iAmContributor = (item.contributors || []).some(c => c.user_id === currentUserId)
const others = tripMembers.filter(m => m.id !== item.owner_id && m.id !== currentUserId)
const toggleRecipient = (uid: number) => {
const next = recipientIds.includes(uid) ? recipientIds.filter(x => x !== uid) : [...recipientIds, uid]
onSetSharing(item.id, 'shared', next)
}
const btn = (onClick: () => void, title: string, active: boolean, node: React.ReactNode) => (
<button type="button" onClick={onClick} title={title}
style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '3px 4px', borderRadius: 6, display: 'flex', color: active ? 'var(--accent)' : 'var(--text-faint)' }}
onMouseEnter={e => { if (!active) e.currentTarget.style.color = 'var(--text-secondary)' }}
onMouseLeave={e => { if (!active) e.currentTarget.style.color = 'var(--text-faint)' }}>
{node}
</button>
)
const pledge = () => (iAmContributor ? onLeave(item.id, currentUserId!) : onJoin(item.id))
const pledgeLabel = iAmContributor ? t('packing.alsoBringingStop') : t('packing.alsoBring')
// Non-owner on a Common item: pledge to co-bring + clone to personal list.
if (!isOwner && isCommon) {
if (variant === 'menu') return (
<>
<MenuRow icon={<HandHelping size={13} />} label={pledgeLabel} active={iAmContributor} onClick={() => { pledge(); onAction?.() }} />
<MenuRow icon={<Copy size={13} />} label={t('packing.cloneToMine')} onClick={() => { onClone(item.id); onAction?.() }} />
</>
)
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 2 }}>
{btn(pledge, pledgeLabel, iAmContributor, <HandHelping size={14} />)}
{btn(() => onClone(item.id), t('packing.cloneToMine'), false, <Copy size={13} />)}
</div>
)
}
// A recipient of a shared item has no controls (it's the owner's responsibility).
if (!isOwner) return null
const tierLabel = visibility === 'common' ? t('packing.viewCommon') : visibility === 'personal' ? t('packing.tierPersonal') : t('packing.tierShared')
return (
<div style={{ display: 'flex' }}>
{variant === 'menu' ? (
<MenuRow buttonRef={btnRef} icon={<Share2 size={13} />} label={t('packing.share')} hint={tierLabel} active={open} onClick={toggle} />
) : (
<button type="button" ref={btnRef} onClick={toggle} title={t('packing.share')}
style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '3px 4px', borderRadius: 6, display: 'flex', color: visibility !== 'common' ? 'var(--accent)' : 'var(--text-faint)' }}
onMouseEnter={e => { if (visibility === 'common') e.currentTarget.style.color = 'var(--text-secondary)' }}
onMouseLeave={e => { if (visibility === 'common') e.currentTarget.style.color = 'var(--text-faint)' }}>
<Share2 size={14} />
</button>
)}
{open && pos && createPortal(
<>
<div role="presentation" style={{ position: 'fixed', inset: 0, zIndex: 1099 }} onClick={() => setOpen(false)} />
<div style={{
position: 'fixed', top: pos.top, right: pos.right, zIndex: 1100,
background: 'var(--bg-card)', border: '1px solid var(--border-primary)', borderRadius: 10,
boxShadow: '0 8px 28px rgba(0,0,0,0.18)', padding: 4, minWidth: 200, maxHeight: '60vh', overflowY: 'auto',
}}>
<Row icon={<Users size={13} />} label={t('packing.viewCommon')} sub={t('packing.tierCommonHint')} active={visibility === 'common'} onClick={() => { onSetSharing(item.id, 'common', []); setOpen(false) }} />
<Row icon={<UserRound size={13} />} label={t('packing.tierPersonal')} sub={t('packing.tierPersonalHint')} active={visibility === 'personal'} onClick={() => { onSetSharing(item.id, 'personal', []); setOpen(false) }} />
<div style={{ height: 1, background: 'var(--bg-tertiary)', margin: '4px 0' }} />
<div style={{ padding: '4px 10px 2px', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 700, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.04em', display: 'flex', alignItems: 'center', gap: 5 }}>
<Share2 size={10} /> {t('packing.tierShared')}
</div>
{others.length === 0 ? (
<div style={{ padding: '4px 10px 6px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)' }}>{t('packing.noOneToShare')}</div>
) : others.map(m => {
const on = recipientIds.includes(m.id)
return (
<button type="button" key={m.id} onClick={() => toggleRecipient(m.id)}
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', padding: '6px 10px', borderRadius: 7, border: 'none', cursor: 'pointer', background: 'none', fontFamily: 'inherit', fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'var(--text-primary)' }}
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-tertiary)'}
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
<span style={{ width: 18, height: 18, borderRadius: '50%', flexShrink: 0, background: `hsl(${(m.username.codePointAt(0) ?? 0) * 37 % 360}, 55%, 55%)`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 'calc(9px * var(--fs-scale-caption, 1))', fontWeight: 700, color: 'white', textTransform: 'uppercase' }}>{m.username[0]}</span>
<span style={{ flex: 1, textAlign: 'start', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.username}</span>
{on && <Check size={13} className="text-content-muted" />}
</button>
)
})}
</div>
</>,
document.body,
)}
</div>
)
}
function Row({ icon, label, sub, active, onClick }: { icon: React.ReactNode; label: string; sub: string; active: boolean; onClick: () => void }) {
return (
<button type="button" onClick={onClick}
style={{ display: 'flex', alignItems: 'flex-start', gap: 8, width: '100%', padding: '7px 10px', borderRadius: 7, border: 'none', cursor: 'pointer', background: active ? 'var(--bg-tertiary)' : 'none', fontFamily: 'inherit', textAlign: 'start' }}
onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--bg-tertiary)' }}
onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'none' }}>
<span style={{ color: active ? 'var(--accent)' : 'var(--text-muted)', marginTop: 1 }}>{icon}</span>
<span style={{ flex: 1, minWidth: 0 }}>
<span style={{ display: 'block', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-primary)' }}>{label}</span>
<span style={{ display: 'block', fontSize: 'calc(10.5px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)' }}>{sub}</span>
</span>
{active && <Check size={13} className="text-content-muted" style={{ marginTop: 2 }} />}
</button>
)
}
/** A full-width line in an overflow menu, shaped like the item menu's own entries. */
function MenuRow({ icon, label, hint, active = false, onClick, buttonRef }: {
icon: React.ReactNode; label: string; hint?: string; active?: boolean; onClick: () => void
buttonRef?: React.Ref<HTMLButtonElement>
}) {
return (
<button type="button" ref={buttonRef} onClick={onClick}
style={{ display: 'flex', alignItems: 'center', gap: 9, width: '100%', padding: '8px 10px', borderRadius: 9, border: 'none', cursor: 'pointer', background: active ? 'var(--bg-tertiary)' : 'none', color: 'var(--text-primary)', fontFamily: 'inherit', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 500, textAlign: 'start' }}
onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--bg-tertiary)' }}
onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'none' }}>
<span style={{ width: 16, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, color: 'var(--text-muted)' }}>{icon}</span>
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span>
{hint && <span style={{ flexShrink: 0, fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)' }}>{hint}</span>}
</button>
)
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest';
import { bringsItem, packingItemAccess, toggledRecipients } from './packingItemAccess';
describe('packingItemAccess', () => {
it('FE-PACKACCESS-001: a common item of mine is mine to share, not to copy', () => {
expect(packingItemAccess({ is_private: 0, owner_id: 1 }, 1)).toMatchObject({
isCommon: true,
isOwner: true,
visibility: 'common',
sharedToMe: false,
canClone: false,
recipientIds: [],
});
});
it("FE-PACKACCESS-002: nobody owning it makes it everyone's to share", () => {
expect(packingItemAccess({ is_private: 0, owner_id: null }, 5).isOwner).toBe(true);
});
it("FE-PACKACCESS-003: someone else's common item can be copied, their private one is theirs", () => {
expect(packingItemAccess({ is_private: 0, owner_id: 2 }, 1)).toMatchObject({ canClone: true, sharedToMe: false });
expect(packingItemAccess({ is_private: 1, owner_id: 2 }, 1)).toMatchObject({
canClone: false,
sharedToMe: true,
visibility: 'personal',
});
});
it('FE-PACKACCESS-004: a private item with people on it is shared', () => {
const access = packingItemAccess({ is_private: 1, owner_id: 1, recipients: [{ user_id: 3, username: 'c' }] }, 1);
expect(access.visibility).toBe('shared');
expect(access.recipientIds).toEqual([3]);
});
it('FE-PACKACCESS-005: the owner and the co-bringers bring it, nobody else', () => {
const item = { owner_id: 1, contributors: [{ user_id: 2, username: 'b', status: 'accepted' }] };
expect(bringsItem(item, 1)).toBe(true);
expect(bringsItem(item, 2)).toBe(true);
expect(bringsItem(item, 3)).toBe(false);
expect(bringsItem({ owner_id: null }, 3)).toBe(false);
});
it('FE-PACKACCESS-006: a tap adds or removes a person, and the last one out leaves it personal', () => {
expect(toggledRecipients([3], 4)).toEqual({ visibility: 'shared', recipientIds: [3, 4] });
expect(toggledRecipients([3, 4], 3)).toEqual({ visibility: 'shared', recipientIds: [4] });
expect(toggledRecipients([3], 3)).toEqual({ visibility: 'personal', recipientIds: [] });
});
});
@@ -0,0 +1,47 @@
import type { PackingItem } from '../../types';
export type PackingVisibility = 'common' | 'personal' | 'shared';
type AccessItem = Pick<PackingItem, 'is_private' | 'owner_id' | 'recipients' | 'contributors'>;
/**
* Who may do what with one packing item, by the three tiers (#858): the owner
* (or anyone, while nobody owns it) sets who sees it, everyone on the trip can
* be put down as bringing a common item (#3098), and a private item shared with
* me is the owner's to look after. The desktop window and the phone sheet both
* read it from here.
*/
export function packingItemAccess(item: AccessItem, currentUserId: number | null | undefined) {
const isCommon = !item.is_private;
const isOwner = item.owner_id == null || item.owner_id === currentUserId;
const recipientIds = (item.recipients || []).map((r) => r.user_id);
const privateTier: PackingVisibility = recipientIds.length > 0 ? 'shared' : 'personal';
const visibility: PackingVisibility = isCommon ? 'common' : privateTier;
return {
isCommon,
isOwner,
recipientIds,
visibility,
/** A private item somebody else owns: shown, but theirs to change. */
sharedToMe: !isCommon && !isOwner,
/** A common item somebody else owns can be copied onto my own list. */
canClone: isCommon && !isOwner,
};
}
/** True when the person brings the item, as its owner or alongside. */
export function bringsItem(item: Pick<PackingItem, 'owner_id' | 'contributors'>, userId: number): boolean {
return item.owner_id === userId || (item.contributors || []).some((c) => c.user_id === userId);
}
/**
* The sharing a tap on one person leads to: on or off the list of people who see
* the item, and with nobody left it falls back to the owner alone.
*/
export function toggledRecipients(
recipientIds: number[],
userId: number
): { visibility: PackingVisibility; recipientIds: number[] } {
const next = recipientIds.includes(userId) ? recipientIds.filter((id) => id !== userId) : [...recipientIds, userId];
return { visibility: next.length ? 'shared' : 'personal', recipientIds: next };
}
@@ -45,6 +45,23 @@ export interface PackingListPanelProps {
// Lifted so an out-of-panel Apply Template button knows the active view (#1565).
view?: 'common' | 'personal'
onViewChange?: (view: 'common' | 'personal') => void
// Set from the Lists menu, which sits outside the panel.
sort?: PackingSort
hideDone?: boolean
clearCheckedSignal?: number
openBagsSignal?: number
}
/** A-Z or the manual order, remembered per browser. */
export function usePackingSortPreference(): [PackingSort, (next: PackingSort) => void] {
const [sort, setSortState] = useState<PackingSort>(() => {
try { return localStorage.getItem(PACKING_SORT_KEY) === 'name' ? 'name' : 'manual' } catch { return 'manual' }
})
const setSort = (next: PackingSort) => {
setSortState(next)
try { localStorage.setItem(PACKING_SORT_KEY, next) } catch { /* storage unavailable: the choice lasts until reload */ }
}
return [sort, setSort]
}
/**
@@ -54,17 +71,14 @@ export interface PackingListPanelProps {
* sections below render header, filters, the grouped list, the bag sidebar/
* modal and the import dialog.
*/
export function usePackingList({ tripId, items, openImportSignal = 0, addCategorySignal = 0, saveTemplateSignal = 0, inlineHeader = true, view: viewProp, onViewChange }: PackingListPanelProps) {
const [filter, setFilter] = useState('alle') // 'alle' | 'offen' | 'erledigt'
export function usePackingList({ tripId, items, openImportSignal = 0, addCategorySignal = 0, saveTemplateSignal = 0, inlineHeader = true, view: viewProp, onViewChange, sort: sortProp, hideDone, clearCheckedSignal = 0, openBagsSignal = 0 }: PackingListPanelProps) {
const [ownFilter, setFilter] = useState('alle') // 'alle' | 'offen' | 'erledigt'
// Under the Lists bar the menu decides whether packed items show.
const filter = hideDone === undefined ? ownFilter : (hideDone ? 'offen' : 'alle')
// A-Z only changes what is shown; the manual order stays stored underneath and
// comes back when the switch is turned off. Remembered per browser.
const [sort, setSortState] = useState<PackingSort>(() => {
try { return localStorage.getItem(PACKING_SORT_KEY) === 'name' ? 'name' : 'manual' } catch { return 'manual' }
})
const setSort = (next: PackingSort) => {
setSortState(next)
try { localStorage.setItem(PACKING_SORT_KEY, next) } catch { /* storage unavailable: the choice lasts until reload */ }
}
// comes back when the switch is turned off.
const [ownSort, setSort] = usePackingSortPreference()
const sort = sortProp ?? ownSort
// Three-tier sharing (#858): 'common' = the group pool (where existing items
// live — non-breaking), 'personal' = my own list (private + shared-to-me).
const [ownView, setOwnView] = useState<'common' | 'personal'>('common')
@@ -136,6 +150,11 @@ export function usePackingList({ tripId, items, openImportSignal = 0, addCategor
if (!confirm(t('packing.confirm.clearChecked', { count: abgehakt }))) return
await clearChecked()
}
const lastClearSignal = useRef(clearCheckedSignal)
useEffect(() => {
if (clearCheckedSignal !== lastClearSignal.current && clearCheckedSignal > 0 && confirm(t('packing.confirm.clearChecked', { count: abgehakt }))) void clearChecked()
lastClearSignal.current = clearCheckedSignal
}, [clearCheckedSignal, abgehakt, clearChecked, t])
// Bag tracking — the global toggle is a packing sub-flag surfaced to every
// authenticated user via the addon store (loaded on app start), not the
@@ -151,6 +170,13 @@ export function usePackingList({ tripId, items, openImportSignal = 0, addCategor
if (!addonsLoaded) loadAddons()
}, [addonsLoaded, loadAddons])
// The Lists menu opens the bag overview on a screen too narrow for its sidebar.
const lastBagsSignal = useRef(openBagsSignal)
useEffect(() => {
if (openBagsSignal !== lastBagsSignal.current && openBagsSignal > 0) setShowBagModal(true)
lastBagsSignal.current = openBagsSignal
}, [openBagsSignal])
const {
bags, unassignedWeightGrams, serverWeightsFresh, tryCreateBag, createBag: handleCreateBagByName,
deleteBag: handleDeleteBag, updateBag: handleUpdateBag, setBagMembers: handleSetBagMembers,