feat(packing): sort the packing list A to Z

A switch at the end of the list's tab row shows every list's items in name
order, so checking whether something is already on the list no longer means
reading all of it. The order follows the reader's language (accents beside
their letter, "Shirt 2" before "Shirt 10") and the empty list stand-in stays
at the bottom.

Sorting only changes what is shown: the manual order stays stored and comes
back with a second click. While sorted the drag grips step aside, the box
keeps its column, and the choice is remembered per browser.
This commit is contained in:
Maurice
2026-09-29 20:25:25 +02:00
parent 6f61b66c5c
commit 272df55cd4
35 changed files with 176 additions and 14 deletions
@@ -236,6 +236,44 @@ describe('PackingListPanel', () => {
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();
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 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);
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');
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');
expect(container.querySelector('[draggable="true"]')).toBeNull();
});
it('FE-COMP-PACKING-023: inline edit item name via pencil icon calls PUT', async () => {
const user = userEvent.setup();
const item = buildPackingItem({ id: 42, name: 'Sunscreen', category: 'Toiletries' });
@@ -35,6 +35,9 @@ interface KategorieGruppeProps {
// order is global, so a within-category drag is mapped back onto the full list.
allItems: PackingItem[]
onReorder: (orderedIds: number[]) => void
// Off while the list is shown A-Z: a drop there would move an item in an order
// the reader cannot see.
reorderable?: boolean
// Three-tier sharing (#858) — threaded down to each item's share control.
currentUserId?: number
onSetSharing?: (id: number, visibility: 'common' | 'personal' | 'shared', recipientIds: number[]) => void
@@ -43,7 +46,7 @@ interface KategorieGruppeProps {
onLeave?: (id: number, userId: number) => void
}
export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRename, onDeleteAll, onDeleteItem, onAddItem, assignees, tripMembers, onSetAssignees, bagTrackingEnabled, bags, onCreateBag, canEdit = true, allItems, onReorder, currentUserId, onSetSharing, onClone, onJoin, onLeave }: KategorieGruppeProps) {
export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRename, onDeleteAll, onDeleteItem, onAddItem, assignees, tripMembers, onSetAssignees, bagTrackingEnabled, bags, onCreateBag, canEdit = true, allItems, onReorder, reorderable = true, currentUserId, onSetSharing, onClone, onJoin, onLeave }: KategorieGruppeProps) {
const [offen, setOffen] = useState(true)
const [dragId, setDragId] = useState<number | null>(null)
const [overId, setOverId] = useState<number | null>(null)
@@ -280,7 +283,7 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
<React.Fragment key={item.id}>
<ArtikelZeile item={item} tripId={tripId} categories={allCategories} onCategoryChange={() => {}} onDelete={onDeleteItem} bagTrackingEnabled={bagTrackingEnabled} bags={bags} onCreateBag={onCreateBag} canEdit={canEdit} divider={index > 0}
tripMembers={tripMembers} currentUserId={currentUserId} onSetSharing={onSetSharing} onClone={onClone} onJoin={onJoin} onLeave={onLeave}
drag={canEdit ? {
drag={canEdit && reorderable ? {
isDragging: dragId === item.id,
isOver: overId === item.id && dragId !== null && dragId !== item.id,
onStart: (id) => { setDragId(id); setOverId(null) },
@@ -161,6 +161,8 @@ export function ArtikelZeile({ item, tripId, categories, onCategoryChange: _onCa
<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={{
flexShrink: 0, cursor: 'pointer', padding: 0, width: 20, height: 20, borderRadius: 6,
@@ -7,7 +7,7 @@ export function PackingList(S: PackingState) {
items, gruppiert, t, tripId, allCategories, handleRenameCategory, handleDeleteCategory, handleDeleteItem,
handleAddItemToCategory, categoryAssignees, tripMembers, handleSetAssignees,
bagTrackingEnabled, bags, handleCreateBagByName, canEdit, reorderPackingItems,
currentUserId, handleSetSharing, handleCloneItem, handleJoinItem, handleLeaveItem,
currentUserId, handleSetSharing, handleCloneItem, handleJoinItem, handleLeaveItem, sort,
} = S
return (
<div style={{ flex: 1, overflowY: 'auto', padding: '10px 0 16px' }}>
@@ -39,6 +39,7 @@ export function PackingList(S: PackingState) {
canEdit={canEdit}
allItems={items}
onReorder={(orderedIds) => reorderPackingItems(tripId, orderedIds)}
reorderable={sort === 'manual'}
currentUserId={currentUserId}
onSetSharing={handleSetSharing}
onClone={handleCloneItem}
@@ -1,14 +1,15 @@
import { Users, UserRound } from 'lucide-react'
import { Users, UserRound, ArrowDownAZ } from 'lucide-react'
import type { PackingState } from './usePackingListPanel'
/**
* One tab row: the three-tier view switch (Gemeinsam / Meine Liste, #858) on the
* left, and the all/open/done filter on the right. 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.
* 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.
*/
export function PackingViewTabs(S: PackingState) {
const { view, setView, filter, setFilter, t, items } = S
const { view, setView, filter, setFilter, sort, setSort, t, items } = S
const commonCount = items.filter(i => !i.is_private).length
const personalCount = items.filter(i => !!i.is_private).length
@@ -55,6 +56,15 @@ export function PackingViewTabs(S: PackingState) {
{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, marginLeft: '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>
</div>
)}
</div>
)
}
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { katColor, itemWeight, bagFillPct, bagTotalWeight, countsTowardsMyLoad, isMarkdownList, parseCsvLine, parseImportLines, unassignedTotalWeight } from './packingListPanel.helpers'
import { katColor, itemWeight, bagFillPct, bagTotalWeight, countsTowardsMyLoad, isMarkdownList, parseCsvLine, parseImportLines, sortItemsByName, unassignedTotalWeight } from './packingListPanel.helpers'
import { KAT_COLORS } from './packingListPanel.constants'
describe('packingListPanel.helpers', () => {
@@ -219,4 +219,26 @@ describe('packingListPanel.helpers', () => {
expect(unassignedTotalWeight(undefined, [])).toBe(0)
})
})
describe('sortItemsByName', () => {
const names = (items: { name: string }[]) => items.map(i => i.name)
it('orders by name, ignoring case and accents the way the language does', () => {
const items = [{ name: 'shirt' }, { name: 'Éponge' }, { name: 'adapter' }, { name: 'Zahnbürste' }, { name: 'Bag' }]
expect(names(sortItemsByName(items, 'en'))).toEqual(['adapter', 'Bag', 'Éponge', 'shirt', 'Zahnbürste'])
})
it('reads numbers as numbers', () => {
expect(names(sortItemsByName([{ name: 'Shirt 10' }, { name: 'Shirt 2' }], 'en'))).toEqual(['Shirt 2', 'Shirt 10'])
})
it('keeps the placeholder of an empty list at the bottom', () => {
expect(names(sortItemsByName([{ name: '...' }, { name: 'Zip bag' }, { name: 'Adapter' }], 'en'))).toEqual(['Adapter', 'Zip bag', '...'])
})
it('leaves the array it was given in its manual order', () => {
const items = [{ name: 'b' }, { name: 'a' }]
sortItemsByName(items, 'en')
expect(names(items)).toEqual(['b', 'a'])
})
})
})
@@ -1,4 +1,4 @@
import { KAT_COLORS } from './packingListPanel.constants'
import { KAT_COLORS, PACKING_PLACEHOLDER_NAME } from './packingListPanel.constants'
// Stable color assignment: category name → index via simple hash
export function katColor(kat: string, allCategories?: string[]): string {
@@ -180,3 +180,19 @@ export const parseImportLines = (text: string): ParsedImportItem[] => {
return { ...splitQuantity(parts[0]), category: undefined, weight_grams: undefined, bag: undefined, checked: false }
}).filter(i => i.name)
}
/**
* One list's items in name order, for the A-Z view. Compared the way the reader's
* language sorts (accents next to their letter, "Shirt 2" before "Shirt 10"), and
* the '...' stand-in of an empty list stays at the bottom where it always sits.
* Returns a new array; the stored manual order is left alone.
*/
export function sortItemsByName<T extends { name: string }>(items: T[], locale?: string): T[] {
const collator = new Intl.Collator(locale, { sensitivity: 'base', numeric: true })
return [...items].sort((a, b) => {
const pa = a.name === PACKING_PLACEHOLDER_NAME
const pb = b.name === PACKING_PLACEHOLDER_NAME
if (pa !== pb) return pa ? 1 : -1
return collator.compare(a.name.trim(), b.name.trim())
})
}
@@ -11,7 +11,11 @@ import { useNetworkMode } from '../../hooks/useNetworkMode'
import { useBagTotalsPing } from './useBagTotalsPing'
import type { PackingItem, PackingBag } from '../../types'
import { BAG_COLORS, PACKING_PLACEHOLDER_NAME } from './packingListPanel.constants'
import { parseImportLines } from './packingListPanel.helpers'
import { parseImportLines, sortItemsByName } from './packingListPanel.helpers'
const PACKING_SORT_KEY = 'trek:packing-sort'
export type PackingSort = 'manual' | 'name'
export interface TripMember {
id: number
@@ -50,6 +54,15 @@ export interface PackingListPanelProps {
*/
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'
// 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 */ }
}
// 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')
@@ -65,7 +78,7 @@ export function usePackingList({ tripId, items, openImportSignal = 0, addCategor
const isAdmin = useAuthStore((s) => s.user?.role === 'admin')
const currentUserId = useAuthStore((s) => s.user?.id)
const toast = useToast()
const { t } = useTranslation()
const { t, locale } = useTranslation()
// Trip members & category assignees
const [tripMembers, setTripMembers] = useState<TripMember[]>([])
@@ -120,8 +133,11 @@ export function usePackingList({ tripId, items, openImportSignal = 0, addCategor
if (!groups[kat]) groups[kat] = []
groups[kat].push(item)
}
if (sort === 'name') {
for (const kat of Object.keys(groups)) groups[kat] = sortItemsByName(groups[kat], locale)
}
return groups
}, [viewItems, filter, t])
}, [viewItems, filter, sort, locale, t])
const abgehakt = viewItems.filter(i => i.checked).length
const fortschritt = viewItems.length > 0 ? Math.round((abgehakt / viewItems.length) * 100) : 0
@@ -399,7 +415,7 @@ export function usePackingList({ tripId, items, openImportSignal = 0, addCategor
view, setView, currentUserId,
handleSetSharing, handleCloneItem, handleJoinItem, handleLeaveItem,
tripId, items, inlineHeader, t, canEdit, isAdmin, font, reorderPackingItems,
filter, setFilter, addingCategory, setAddingCategory, newCatName, setNewCatName,
filter, setFilter, sort, setSort, addingCategory, setAddingCategory, newCatName, setNewCatName,
tripMembers, categoryAssignees, handleSetAssignees, allCategories, gruppiert, abgehakt, fortschritt,
handleAddItemToCategory, handleAddNewCategory, handleRenameCategory, handleDeleteCategory, handleDeleteItem, handleClearChecked,
bagTrackingEnabled, bags, unassignedWeightGrams, serverWeightsFresh, newBagName, setNewBagName, showAddBag, setShowAddBag, showBagModal, setShowBagModal,