feat(packing): print, PDF and Markdown/CSV export of packing lists

The packing list bar gets an export menu next to the import button, both
now icon only. The menu prints the open view as a TREK styled page (trip,
dates, packed count, one card per category, bags), which the browser can
also save as a PDF, and downloads it as a Markdown checklist or as a CSV
in the exact format the import reads, bags included, so a list works as a
personal template without admin rights.

The import now also reads Markdown checklists: headings become
categories, "- [x]" marks an item packed, a "3x" prefix sets the
quantity and a "(200 g)" suffix the weight. The phone action sheet
offers the same exports through the shared usePackingExport hook.

The help center gets an export guide with new pictures, the import guide
and the wiki page describe the Markdown format, in all 27 languages.

Addresses discussions #1420 and #875.
This commit is contained in:
Maurice
2026-09-25 11:31:23 +02:00
parent 2a8071f642
commit 5c312a8497
106 changed files with 2148 additions and 192 deletions
@@ -0,0 +1,100 @@
// FE-PACKEXPORTMENU-001 to FE-PACKEXPORTMENU-006
import { beforeEach, describe, expect, it, vi } from 'vitest'
import userEvent from '@testing-library/user-event'
import { fireEvent, render, screen } from '../../../tests/helpers/render'
import PackingExportMenu from './PackingExportMenu'
import PackingPrintPreview from './PackingPrintPreview'
import type { PackingExport } from './usePackingExport'
const packingExport: PackingExport = {
hasItems: true,
exportMarkdown: vi.fn(),
exportCsv: vi.fn(async () => {}),
openPrint: vi.fn(async () => {}),
printHtml: null,
printTitle: 'Packing List: Lisbon & Porto',
closePrint: vi.fn(),
}
vi.mock('./usePackingExport', () => ({ usePackingExport: () => packingExport }))
const renderMenu = () => render(<PackingExportMenu tripId={7} view="common" className="btn" style={{}} />)
beforeEach(() => {
vi.clearAllMocks()
packingExport.hasItems = true
packingExport.printHtml = null
})
describe('PackingExportMenu', () => {
it('FE-PACKEXPORTMENU-001: renders nothing while the view has no items', () => {
packingExport.hasItems = false
const { container } = renderMenu()
expect(container).toBeEmptyDOMElement()
})
it('FE-PACKEXPORTMENU-002: is an icon button named Export that opens a menu of three ways out', async () => {
const user = userEvent.setup()
renderMenu()
const button = screen.getByRole('button', { name: 'Export' })
expect(button).toHaveAttribute('title', 'Export')
expect(button).toHaveAttribute('aria-expanded', 'false')
await user.click(button)
expect(button).toHaveAttribute('aria-expanded', 'true')
expect(screen.getAllByRole('menuitem').map(i => i.textContent)).toEqual([
'Print or save as PDF', 'Markdown checklist (.md)', 'CSV for import (.csv)',
])
})
it('FE-PACKEXPORTMENU-003: runs the chosen export and closes the menu', async () => {
const user = userEvent.setup()
renderMenu()
for (const [label, action] of [
['Print or save as PDF', packingExport.openPrint],
['Markdown checklist (.md)', packingExport.exportMarkdown],
['CSV for import (.csv)', packingExport.exportCsv],
] as const) {
await user.click(screen.getByRole('button', { name: 'Export' }))
await user.click(screen.getByRole('menuitem', { name: label }))
expect(action).toHaveBeenCalledTimes(1)
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
}
})
it('FE-PACKEXPORTMENU-004: closes on Escape and on a click anywhere else', async () => {
const user = userEvent.setup()
renderMenu()
await user.click(screen.getByRole('button', { name: 'Export' }))
fireEvent.keyDown(document, { key: 'Escape' })
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Export' }))
fireEvent.mouseDown(document.body)
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
})
it('FE-PACKEXPORTMENU-005: keeps the preview open even if the view has been emptied meanwhile', () => {
packingExport.hasItems = false
packingExport.printHtml = '<html><body><h1>Lisbon</h1></body></html>'
renderMenu()
expect(screen.getByTitle('Packing List: Lisbon & Porto')).toBeInTheDocument()
})
})
describe('PackingPrintPreview', () => {
it('FE-PACKEXPORTMENU-006: shows the page in a frame, prints that frame, and closes', async () => {
const user = userEvent.setup()
const onClose = vi.fn()
const { rerender } = render(<PackingPrintPreview html={null} title="Packing List" onClose={onClose} />)
expect(screen.queryByTitle('Packing List')).not.toBeInTheDocument()
rerender(<PackingPrintPreview html="<html><body>List</body></html>" title="Packing List" onClose={onClose} />)
const frame = screen.getByTitle('Packing List') as HTMLIFrameElement
expect(frame.getAttribute('srcdoc')).toBe('<html><body>List</body></html>')
expect(frame.getAttribute('sandbox')).toBe('allow-same-origin allow-modals')
const print = vi.fn()
Object.defineProperty(frame, 'contentWindow', { value: { print }, configurable: true })
await user.click(screen.getByRole('button', { name: 'Print or save as PDF' }))
expect(print).toHaveBeenCalledTimes(1)
await user.click(screen.getByRole('button', { name: 'Close' }))
expect(onClose).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,89 @@
import React, { useEffect, useRef, useState } from 'react'
import type { LucideIcon } from 'lucide-react'
import { FileSpreadsheet, FileText, Printer, Upload } from 'lucide-react'
import { useTranslation } from '../../i18n'
import PackingPrintPreview from './PackingPrintPreview'
import { usePackingExport, type PackingView } from './usePackingExport'
interface PackingExportMenuProps {
tripId: number
view: PackingView
style: React.CSSProperties
className?: string
}
function MenuItem({ icon: Icon, label, onClick }: { icon: LucideIcon; label: string; onClick: () => void }) {
return (
<button
type="button"
role="menuitem"
onClick={onClick}
className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-caption font-medium text-content hover:bg-surface-tertiary"
>
<Icon size={13} className="text-content-faint" />
{label}
</button>
)
}
/**
* The list's way out, beside Import in the Lists header (#875, #1420): print or save
* 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 {
const { t } = useTranslation()
const packingExport = usePackingExport(tripId, view)
const [open, setOpen] = useState(false)
const menuRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!open) return
const onPointer = (e: MouseEvent) => {
if (menuRef.current && !menuRef.current.contains(e.target as Node)) setOpen(false)
}
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false) }
document.addEventListener('mousedown', onPointer)
document.addEventListener('keydown', onKey)
return () => {
document.removeEventListener('mousedown', onPointer)
document.removeEventListener('keydown', onKey)
}
}, [open])
if (!packingExport.hasItems && !packingExport.printHtml) return null
const choose = (action: () => void | Promise<void>) => () => {
setOpen(false)
void action()
}
return (
// A flex box, so the button stretches to the row height like its neighbours in the header.
<div ref={menuRef} className="relative flex">
<button
type="button"
onClick={() => setOpen(v => !v)}
aria-haspopup="menu"
aria-expanded={open}
aria-label={t('packing.export')}
title={t('packing.export')}
className={className ?? 'hover:opacity-[0.88]'}
style={style}
>
<Upload size={14} strokeWidth={2.5} />
</button>
{open && (
<div
role="menu"
className="trek-menu-enter absolute right-0 top-full z-50 mt-1.5 min-w-[220px] origin-top-right rounded-[10px] border border-edge bg-surface-card p-1 shadow-dropdown"
>
<MenuItem icon={Printer} label={t('packing.exportPrint')} onClick={choose(packingExport.openPrint)} />
<MenuItem icon={FileText} label={t('packing.exportMarkdown')} onClick={choose(packingExport.exportMarkdown)} />
<MenuItem icon={FileSpreadsheet} label={t('packing.exportCsv')} onClick={choose(packingExport.exportCsv)} />
</div>
)}
<PackingPrintPreview html={packingExport.printHtml} title={packingExport.printTitle} onClose={packingExport.closePrint} />
</div>
)
}
@@ -546,8 +546,8 @@ describe('PackingListPanel', () => {
const textarea = screen.getByPlaceholderText(/Hygiene, Toothbrush/);
expect(textarea).toBeInTheDocument();
// "Load CSV/TXT" button is present inside the modal
expect(screen.getByText('Load CSV/TXT')).toBeInTheDocument();
// "Load CSV/TXT/MD" button is present inside the modal
expect(screen.getByText('Load CSV/TXT/MD')).toBeInTheDocument();
// Close by clicking backdrop (covers the onClick on the backdrop div)
const modalTitle = screen.getByText('Import Packing List');
@@ -1496,7 +1496,21 @@ describe('PackingListPanel', () => {
await waitFor(() => expect(createBody).toMatchObject({ name: 'New Bag' }));
});
it('FE-COMP-PACKING-069: Load CSV/TXT button clicks the hidden file input', async () => {
it('FE-COMP-PACKING-082: the import dialog explains the Markdown form, takes .md files and counts a pasted checklist (#875)', async () => {
const user = userEvent.setup();
const { container } = render(<PackingListPanel tripId={1} items={[]} />);
await user.click(container.querySelector('svg.lucide-download')!.closest('button')!);
await screen.findByText('Import Packing List');
expect(screen.getByText(/A Markdown list works too/)).toBeInTheDocument();
expect(document.querySelector('input[type="file"]')).toHaveAttribute('accept', '.csv,.txt,.md,.markdown,text/markdown');
fireEvent.change(screen.getByPlaceholderText(/Hygiene, Toothbrush/), {
target: { value: '# Packing List\n## Clothing\n- [x] 3x Socks\n- [ ] Rain jacket (350 g)\nA note' },
});
expect(screen.getByRole('button', { name: 'Import 2' })).toBeInTheDocument();
});
it('FE-COMP-PACKING-069: Load CSV/TXT/MD button clicks the hidden file input', async () => {
const user = userEvent.setup();
const { container } = render(<PackingListPanel tripId={1} items={[]} />);
@@ -1510,8 +1524,8 @@ describe('PackingListPanel', () => {
expect(fileInput).toBeTruthy();
const clickSpy = vi.spyOn(fileInput, 'click').mockImplementation(() => {});
// Click the "Load CSV/TXT" button
await user.click(screen.getByText('Load CSV/TXT'));
// Click the "Load CSV/TXT/MD" button
await user.click(screen.getByText('Load CSV/TXT/MD'));
expect(clickSpy).toHaveBeenCalled();
clickSpy.mockRestore();
@@ -1,6 +1,7 @@
import { createPortal } from 'react-dom'
import { FileDown } from 'lucide-react'
import type { PackingState } from './usePackingListPanel'
import { PACKING_IMPORT_ACCEPT } from './packingListPanel.constants'
export function BulkImportModal(S: PackingState) {
const { setShowImportModal, t, importText, setImportText, csvInputRef, handleCsvFile, handleBulkImport, parseImportLines } = S
@@ -16,7 +17,11 @@ export function BulkImportModal(S: PackingState) {
display: 'flex', flexDirection: 'column', gap: 14,
}}>
<div style={{ fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 600, color: 'var(--text-primary)' }}>{t('packing.importTitle')}</div>
<div style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'var(--text-faint)', lineHeight: 1.5 }}>{t('packing.importHint')}</div>
<div style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'var(--text-faint)', lineHeight: 1.5 }}>
{t('packing.importHint')}
<br />
{t('packing.importHintMarkdown')}
</div>
<div style={{ display: 'flex', border: '1px solid var(--border-primary)', borderRadius: 10, overflow: 'hidden', background: 'var(--bg-input)' }}>
<div style={{
padding: '10px 0', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontFamily: 'monospace', lineHeight: 1.5,
@@ -42,7 +47,7 @@ export function BulkImportModal(S: PackingState) {
</div>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<div>
<input ref={csvInputRef} type="file" accept=".csv,.txt" style={{ display: 'none' }} onChange={handleCsvFile} />
<input ref={csvInputRef} type="file" accept={PACKING_IMPORT_ACCEPT} style={{ display: 'none' }} onChange={handleCsvFile} />
<button type="button" onClick={() => csvInputRef.current?.click()} style={{
display: 'flex', alignItems: 'center', gap: 5, padding: '5px 10px',
border: '1px dashed var(--border-primary)', borderRadius: 8, background: 'none',
@@ -0,0 +1,56 @@
import { useRef } from 'react'
import { Printer } from 'lucide-react'
import Modal from '../shared/Modal'
import { useTranslation } from '../../i18n'
interface PackingPrintPreviewProps {
/** The page to print; the preview is closed while this is null. */
html: string | null
title: string
onClose: () => void
}
/**
* The printable packing list, shown before it goes to the printer (#1420).
*
* Printed from its own frame, so the page that reaches the printer is the list and
* nothing of the planner around it, and "Save as PDF" in the browser's print dialog
* is the PDF export. No script runs inside the frame; printing is started from here.
*/
export default function PackingPrintPreview({ html, title, onClose }: PackingPrintPreviewProps) {
const { t } = useTranslation()
const frameRef = useRef<HTMLIFrameElement>(null)
return (
<Modal
isOpen={html != null}
onClose={onClose}
title={title}
size="3xl"
footer={(
<div className="flex justify-end gap-2">
<button type="button" onClick={onClose} className="rounded-lg border border-edge px-4 py-2 text-body text-content-muted hover:bg-surface-hover">
{t('common.close')}
</button>
<button
type="button"
onClick={() => frameRef.current?.contentWindow?.print()}
className="inline-flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-body font-medium text-accent-text hover:bg-accent-hover"
>
<Printer size={15} strokeWidth={2.2} />
{t('packing.exportPrint')}
</button>
</div>
)}
>
{html != null && (
<iframe
ref={frameRef}
title={title}
srcDoc={html}
sandbox="allow-same-origin allow-modals"
className="block h-[62vh] w-full rounded-lg border border-edge"
/>
)}
</Modal>
)
}
@@ -0,0 +1,161 @@
// FE-PACKEXPORT-001 to FE-PACKEXPORT-011
import { describe, expect, it } from 'vitest'
import type { PackingItem } from '../../types'
import { groupByCategory, packingCsv, packingFileName, packingMarkdown, type PackingBagLookup } from './packingExport'
import { packingPrintHtml, type PackingPrintText } from './packingPrintDocument'
import { parseImportLines } from './packingListPanel.helpers'
import { KAT_COLORS } from './packingListPanel.constants'
let nextId = 1
const item = (over: Partial<PackingItem>): PackingItem => ({
id: nextId++, trip_id: 1, name: 'Item', checked: 0, category: 'Other', sort_order: 0,
weight_grams: null, bag_id: null, quantity: 1, is_private: 0, ...over,
})
const LIST: PackingItem[] = [
item({ name: 'Passport', category: 'Documents', checked: 1, weight_grams: 40, bag_id: 2 }),
item({ name: 'T-Shirts', category: 'Clothing', quantity: 5, weight_grams: 180, bag_id: 1 }),
item({ name: 'Boarding passes', category: 'Documents' }),
item({ name: 'Phone charger (USB-C)', category: 'Electronics', weight_grams: 90, bag_id: 2 }),
item({ name: 'Sunglasses', category: null }),
]
const BAGS: Record<number, { name: string; color: string }> = {
1: { name: 'Suitcase', color: '#f97316' },
2: { name: 'Backpack', color: '#6366f1' },
}
const bag: PackingBagLookup = id => BAGS[id]
const noBag: PackingBagLookup = () => undefined
const TEXT: PackingPrintText = {
eyebrow: 'Packing List · Shared', title: 'Lisbon & Porto', dates: 'Oct 9 – 16, 2026',
itemsLabel: 'Items', packedLabel: 'Packed', weightLabel: 'Total weight', bagsLabel: 'Bags',
uncategorized: 'Other', lang: 'en', origin: 'https://trek.example', fontCss: '@font-face{font-family:Poppins}',
}
describe('groupByCategory', () => {
it('FE-PACKEXPORT-001: keeps list order, groups by category and files a blank one under the fallback', () => {
expect(groupByCategory(LIST, 'Other').map(g => [g.category, g.items.map(i => i.name)])).toEqual([
['Documents', ['Passport', 'Boarding passes']],
['Clothing', ['T-Shirts']],
['Electronics', ['Phone charger (USB-C)']],
['Other', ['Sunglasses']],
])
})
})
describe('packingFileName', () => {
it('FE-PACKEXPORT-002: builds a short ascii slug from the trip title, and a plain name without one', () => {
expect(packingFileName('Lisbon & Porto 2026!', '.md')).toBe('packing-list-lisbon-porto-2026.md')
expect(packingFileName(undefined, '.csv')).toBe('packing-list.csv')
expect(packingFileName('東京', '.csv')).toBe('packing-list.csv')
})
})
describe('packingMarkdown', () => {
it('FE-PACKEXPORT-003: writes a checklist with a heading per category, quantities and weights per piece', () => {
expect(packingMarkdown(LIST, 'Packing List: Lisbon & Porto (Shared)', 'Other')).toBe([
'# Packing List: Lisbon & Porto (Shared)',
'',
'## Documents',
'',
'- [x] Passport (40 g)',
'- [ ] Boarding passes',
'',
'## Clothing',
'',
'- [ ] 5 × T-Shirts (180 g)',
'',
'## Electronics',
'',
'- [ ] Phone charger (USB-C) (90 g)',
'',
'## Other',
'',
'- [ ] Sunglasses',
'',
].join('\n'))
})
it('FE-PACKEXPORT-004: comes back through the import with the same categories, quantities, weights and checkmarks', () => {
const back = parseImportLines(packingMarkdown(LIST, 'Packing List', 'Other'))
expect(back.map(r => [r.category, r.name, r.quantity ?? 1, r.weight_grams ?? null, r.checked])).toEqual([
['Documents', 'Passport', 1, '40', true],
['Documents', 'Boarding passes', 1, null, false],
['Clothing', 'T-Shirts', 5, '180', false],
['Electronics', 'Phone charger (USB-C)', 1, '90', false],
['Other', 'Sunglasses', 1, null, false],
])
})
})
describe('packingCsv', () => {
it('FE-PACKEXPORT-005: writes the import format with bag names and no header row', () => {
expect(packingCsv(LIST, bag)).toBe([
'Documents,Passport,40,Backpack,checked',
'Clothing,5 × T-Shirts,180,Suitcase,',
'Documents,Boarding passes,,,',
'Electronics,Phone charger (USB-C),90,Backpack,',
',Sunglasses,,,',
'',
].join('\n'))
})
it('FE-PACKEXPORT-006: quotes a field with a separator or a quote, and the import reads it back unchanged', () => {
const tricky = [item({ name: '12" tray, round', category: 'Kitchen; camping', bag_id: 9, quantity: 2 })]
const csv = packingCsv(tricky, () => ({ name: 'Box "A"' }))
expect(csv).toBe('"Kitchen; camping","2 × 12"" tray, round",,"Box ""A""",\n')
expect(parseImportLines(csv)[0]).toMatchObject({ category: 'Kitchen; camping', name: '12" tray, round', quantity: 2, bag: 'Box "A"', checked: false })
})
it('FE-PACKEXPORT-007: leaves the bag empty when it is unknown', () => {
expect(packingCsv([LIST[0]], noBag)).toBe('Documents,Passport,40,,checked\n')
})
})
describe('packingPrintHtml', () => {
const html = packingPrintHtml(LIST, TEXT, bag)
it('FE-PACKEXPORT-008: carries the trip, its dates and the numbers of the list in the cover block', () => {
expect(html).toContain('<h1>Lisbon &amp; Porto</h1>')
expect(html).toContain('Oct 9 – 16, 2026')
expect(html).toContain('<b>5</b><span>Items</span>')
expect(html).toContain('<b>1/5</b><span>Packed</span>')
expect(html).toContain('<b>1.0 kg</b><span>Total weight</span>')
expect(html).toContain('<b>2</b><span>Bags</span>')
expect(html).toContain('style="width:20%"')
expect(html).toContain('https://trek.example/logo-light.svg')
expect(html).toContain('@font-face{font-family:Poppins}')
})
it('FE-PACKEXPORT-009: draws a card per category in the app’s colours, with quantity, weight and bag per item', () => {
expect(html).toContain(`style="--c:${KAT_COLORS[0]}"`)
expect(html).toContain('<em>1/2</em>')
expect(html).toMatch(/<li class="done"><span class="box"><svg[^]*?<\/svg><\/span><span class="name">Passport<\/span>/)
expect(html).toContain('<span class="qty">×5</span><span class="weight">900 g</span>')
expect(html).toContain('<i style="background:#f97316"></i>Suitcase')
expect(html).toContain('<b>Backpack</b><span>2 · 130 g</span>')
})
it('FE-PACKEXPORT-010: escapes every text and lets only a plain hex colour into a style', () => {
const hostile = packingPrintHtml(
[item({ name: '<img src=x onerror=alert(1)>', category: '<b>Cat</b>', bag_id: 1 })],
{ ...TEXT, title: '<script>x</script>', dates: null },
() => ({ name: '<i>Bag</i>', color: 'red;background:url(//evil)' }),
)
expect(hostile).not.toContain('<img src=x')
expect(hostile).not.toContain('<script>x')
expect(hostile).toContain('&lt;img src=x onerror=alert(1)&gt;')
expect(hostile).not.toContain('evil')
expect(hostile).toContain('background:#94a3b8')
expect(hostile).not.toContain('class="dates"')
})
it('FE-PACKEXPORT-011: leaves out weight and bags where the list has none', () => {
const bare = packingPrintHtml([item({ name: 'Hat' })], TEXT, noBag)
expect(bare).not.toContain('Total weight')
expect(bare).not.toContain('class="bags"')
expect(bare).toContain('<b>0/1</b><span>Packed</span>')
expect(bare).toContain('style="width:0%"')
})
})
@@ -0,0 +1,80 @@
import type { PackingItem } from '../../types'
/**
* A packing list leaving TREK as a file (#875): as Markdown for a notes app, and as
* CSV in the exact format the import reads. The printable page is its own module,
* packingPrintDocument.ts, built from the same grouping.
*
* Both files follow the order the list shows, so a list that goes out and comes back
* through the import lands in the same categories, with the same quantities, weights
* and checkmarks. Markdown carries everything but the bag (bags belong to one trip);
* CSV carries the bag too.
*/
/** What an export needs to know about a bag: its name, and for the printout its colour. */
export interface PackingBagInfo {
name: string
color?: string | null
}
export type PackingBagLookup = (bagId: number) => PackingBagInfo | undefined
export interface PackingCategoryGroup {
category: string
items: PackingItem[]
}
/** The items under their category, categories in the order their first item appears. */
export function groupByCategory(items: PackingItem[], uncategorized: string): PackingCategoryGroup[] {
const groups = new Map<string, PackingItem[]>()
for (const item of items) {
const category = item.category?.trim() || uncategorized
const group = groups.get(category)
if (group) group.push(item)
else groups.set(category, [item])
}
return [...groups].map(([category, grouped]) => ({ category, items: grouped }))
}
/** "3 × Socks", read back by the import's quantity rule; one is left unsaid. */
const withQuantity = (item: PackingItem): string =>
(item.quantity ?? 1) > 1 ? `${item.quantity} × ${item.name}` : item.name
/** A file name from the trip title: lowercase, ascii-ish, short. */
export function packingFileName(tripTitle: string | undefined, extension: string): string {
const slug = (tripTitle || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40)
return `packing-list${slug ? `-${slug}` : ''}${extension}`
}
/**
* A Markdown checklist: the title as the one top heading, a second-level heading per
* category, and a task-list item per entry with its weight per piece in brackets.
*/
export function packingMarkdown(items: PackingItem[], title: string, uncategorized: string): string {
const lines = [`# ${title}`]
for (const group of groupByCategory(items, uncategorized)) {
lines.push('', `## ${group.category}`, '')
for (const item of group.items) {
const weight = item.weight_grams ? ` (${item.weight_grams} g)` : ''
lines.push(`- [${item.checked ? 'x' : ' '}] ${withQuantity(item)}${weight}`)
}
}
return `${lines.join('\n')}\n`
}
/** One CSV field, quoted when it holds a separator or a quote, a quote doubled inside. */
const csvField = (value: string): string => (/[",;\t\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value)
/**
* The import format, one item per row: Category, Name, Weight, Bag, checked. No header
* row, because the import would read it as an item.
*/
export function packingCsv(items: PackingItem[], bag: PackingBagLookup): string {
const rows = items.map(item => [
item.category?.trim() || '',
withQuantity(item),
item.weight_grams ? String(item.weight_grams) : '',
item.bag_id != null ? bag(item.bag_id)?.name ?? '' : '',
item.checked ? 'checked' : '',
].map(csvField).join(','))
return `${rows.join('\n')}\n`
}
@@ -17,3 +17,6 @@ export const BAG_COLORS = ['#6366f1', '#ec4899', '#f97316', '#10b981', '#06b6d4'
// A category's first item is seeded with this sentinel because the server
// rejects empty names. Treat it as a placeholder in the UI.
export const PACKING_PLACEHOLDER_NAME = '...'
/** What the import's file picker offers: CSV rows, plain text, or a Markdown list (#875). */
export const PACKING_IMPORT_ACCEPT = '.csv,.txt,.md,.markdown,text/markdown'
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { katColor, itemWeight, bagFillPct, bagTotalWeight, countsTowardsMyLoad, parseCsvLine, parseImportLines, unassignedTotalWeight } from './packingListPanel.helpers'
import { katColor, itemWeight, bagFillPct, bagTotalWeight, countsTowardsMyLoad, isMarkdownList, parseCsvLine, parseImportLines, unassignedTotalWeight } from './packingListPanel.helpers'
import { KAT_COLORS } from './packingListPanel.constants'
describe('packingListPanel.helpers', () => {
@@ -127,6 +127,72 @@ describe('packingListPanel.helpers', () => {
expect(rows).toHaveLength(1)
expect(rows[0].name).toBe('Passport')
})
it('reads a leading "3x" as the quantity in CSV rows too, and leaves "4x4 adapter" a name', () => {
expect(parseImportLines('Clothing, 3x Socks, 40')[0]).toMatchObject({ name: 'Socks', quantity: 3, weight_grams: '40' })
expect(parseImportLines('Clothing, 2 × T-Shirts')[0]).toMatchObject({ name: 'T-Shirts', quantity: 2 })
expect(parseImportLines('Car, 4x4 adapter')[0]).toMatchObject({ name: '4x4 adapter' })
expect(parseImportLines('Car, 4x4 adapter')[0].quantity).toBeUndefined()
})
it('keeps a doubled quote inside a quoted field as one quote (#875 CSV export)', () => {
expect(parseCsvLine('Other,"12"" pizza tray, round",,,')).toEqual(['Other', '12" pizza tray, round', '', '', ''])
})
})
describe('parseImportLines with Markdown (#875)', () => {
it('recognises a Markdown list by a heading or a list item, and leaves CSV rows alone', () => {
expect(isMarkdownList('## Clothing\nSocks')).toBe(true)
expect(isMarkdownList('- [ ] Socks')).toBe(true)
expect(isMarkdownList('1. Passport')).toBe(true)
expect(isMarkdownList('Clothing, Socks\nDocuments, Passport')).toBe(false)
})
it('takes the category from the heading above, checkmarks from the box, and ignores everything else', () => {
const rows = parseImportLines([
'# Packing List: Lisbon (Shared)',
'',
'A note that is not an item.',
'## Clothing ##',
'- [x] T-Shirts',
'* [ ] Rain jacket',
'---',
'### Documents',
'1. Passport',
'+ Boarding pass',
].join('\n'))
expect(rows).toEqual([
{ name: 'T-Shirts', category: 'Clothing', weight_grams: undefined, bag: undefined, checked: true },
{ name: 'Rain jacket', category: 'Clothing', weight_grams: undefined, bag: undefined, checked: false },
{ name: 'Passport', category: 'Documents', weight_grams: undefined, bag: undefined, checked: false },
{ name: 'Boarding pass', category: 'Documents', weight_grams: undefined, bag: undefined, checked: false },
])
})
it('reads the export’s quantity and weight back, in g or kg, and keeps other brackets in the name', () => {
const rows = parseImportLines('## Kit\n- [ ] 5 × T-Shirts (180 g)\n- [ ] Tent (1,2 kg)\n- [x] Phone charger (USB-C) (90 g)\n- [ ] Charger (USB-C)')
expect(rows.map(r => [r.name, r.quantity, r.weight_grams, r.checked])).toEqual([
['T-Shirts', 5, '180', false],
['Tent', undefined, '1200', false],
['Phone charger (USB-C)', undefined, '90', true],
['Charger (USB-C)', undefined, undefined, false],
])
})
it('turns links, emphasis and code marks into plain text, and skips an empty checkbox', () => {
const rows = parseImportLines('- [ ] **Sun**screen\n- [ ] [Adapter](https://example.com/adapter) `EU`\n- [ ]\n- [x]')
expect(rows.map(r => r.name)).toEqual(['Sunscreen', 'Adapter EU'])
})
it('puts items before the first heading in no category, so the import files them under Other', () => {
expect(parseImportLines('- Sunglasses\n## Hats\n- Cap').map(r => r.category)).toEqual([undefined, 'Hats'])
})
it('stays linear on hostile input', () => {
const started = performance.now()
parseImportLines(`#${' '.repeat(50_000)}x\n-${' '.repeat(50_000)}\n- [ ] ${'('.repeat(50_000)}`)
expect(performance.now() - started).toBeLessThan(500)
})
})
describe('bagTotalWeight / unassignedTotalWeight (#2191)', () => {
@@ -76,13 +76,16 @@ export const unassignedTotalWeight = (
export const bagFillPct = (bagWeight: number, limitGrams: number | null | undefined, heaviestBagWeight: number): number =>
Math.min(100, Math.round((bagWeight / (limitGrams || Math.max(heaviestBagWeight, 1))) * 100))
// Parse CSV line respecting quoted values (e.g. "Shirt, blue" stays as one field)
// Parse CSV line respecting quoted values (e.g. "Shirt, blue" stays as one field).
// A doubled quote inside a quoted field is a literal one, which is how the CSV
// export writes a name that contains a quote.
export const parseCsvLine = (line: string): string[] => {
const parts: string[] = []
let current = ''
let inQuotes = false
for (let i = 0; i < line.length; i++) {
const ch = line[i]
if (ch === '"' && inQuotes && line[i + 1] === '"') { current += '"'; i++; continue }
if (ch === '"') { inQuotes = !inQuotes; continue }
if (!inQuotes && (ch === ',' || ch === ';' || ch === '\t')) { parts.push(current.trim()); current = ''; continue }
current += ch
@@ -97,21 +100,83 @@ export interface ParsedImportItem {
weight_grams: string | undefined
bag: string | undefined
checked: boolean
/** From a leading "3x" or "3 ×" on the name. Absent means one. */
quantity?: number
}
// "3x Socks", "3 x Socks", "3 × Socks". The space after the x is required, so
// "4x4 adapter" stays a name.
const QUANTITY_PREFIX = /^(\d{1,3})\s*[x×]\s+(\S.*)$/i
/** A name with its quantity prefix split off, the same way for CSV rows and Markdown items. */
export const splitQuantity = (raw: string): { name: string; quantity?: number } => {
const match = QUANTITY_PREFIX.exec(raw.trim())
const quantity = match ? Number(match[1]) : 0
return match && quantity >= 1 ? { name: match[2].trim(), quantity } : { name: raw.trim() }
}
const MD_HEADING = /^#{1,6}\s+(\S.*)$/
const MD_ITEM = /^(?:[-*+]|\d+[.)])\s+(?:\[([ xX])\]\s+)?(\S.*)$/
// The weight the Markdown export writes after a name: "(200 g)" or "(1.2 kg)".
// Only a parenthesis that holds nothing but a weight counts, so "Charger (USB-C)"
// keeps its name.
const MD_WEIGHT = /\((\d+(?:[.,]\d+)?)\s?(g|kg)\)$/i
/** Links, emphasis and code marks as plain text: a list copied from a notes app is full of them. */
const plainMarkdown = (text: string): string =>
text.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/\*\*|__|~~|`/g, '').trim()
/**
* Whether pasted text is a Markdown list rather than CSV rows (#875): any heading or
* list item decides it, the way Obsidian, Notion, GitHub and most notes apps export.
*/
export const isMarkdownList = (text: string): boolean =>
text.split('\n').some(line => MD_HEADING.test(line.trim()) || MD_ITEM.test(line.trim()))
/**
* A Markdown list as import rows. Every heading names the category of the items
* under it, "- [x]" marks an item packed, and anything that is neither heading nor
* list item (a note, a blank line, a rule) is left out.
*/
const parseMarkdownLines = (text: string): ParsedImportItem[] => {
const out: ParsedImportItem[] = []
let category: string | undefined
for (const line of text.split('\n').map(l => l.trim())) {
const heading = MD_HEADING.exec(line)
if (heading) {
// A closing run of hashes ("## Clothing ##") is decoration, not part of the name.
category = plainMarkdown(heading[1].replace(/\s#+$/, '')) || undefined
continue
}
const item = MD_ITEM.exec(line)
// "- [ ]" with nothing after it is an empty checkbox, not an item called "[ ]".
if (!item || /^\[[ xX]\]$/.test(item[2])) continue
let label = plainMarkdown(item[2])
let weight_grams: string | undefined
const weight = MD_WEIGHT.exec(label)
if (weight) {
const grams = Number(weight[1].replace(',', '.')) * (weight[2].toLowerCase() === 'kg' ? 1000 : 1)
weight_grams = String(Math.round(grams))
label = label.slice(0, weight.index).trim()
}
out.push({ ...splitQuantity(label), category, weight_grams, bag: undefined, checked: item[1]?.toLowerCase() === 'x' })
}
return out.filter(i => i.name)
}
export const parseImportLines = (text: string): ParsedImportItem[] => {
if (isMarkdownList(text)) return parseMarkdownLines(text)
return text.split('\n').map(line => line.trim()).filter(Boolean).map(line => {
// Format: Category, Name, Weight (optional), Bag (optional), checked/unchecked (optional)
const parts = parseCsvLine(line)
if (parts.length >= 2) {
const category = parts[0]
const name = parts[1]
const weight_grams = parts[2] || undefined
const bag = parts[3] || undefined
const checked = parts[4]?.toLowerCase() === 'checked' || parts[4] === '1'
return { name, category, weight_grams, bag, checked }
return { ...splitQuantity(parts[1]), category, weight_grams, bag, checked }
}
// Single value = just a name
return { name: parts[0], category: undefined, weight_grams: undefined, bag: undefined, checked: false }
return { ...splitQuantity(parts[0]), category: undefined, weight_grams: undefined, bag: undefined, checked: false }
}).filter(i => i.name)
}
@@ -0,0 +1,181 @@
import { escapeHtml } from '@trek/shared'
import type { PackingItem } from '../../types'
import { formatWeight, packingItemWeight } from '../../mobile/screens/trip/tabs/listsModel'
import { katColor } from './packingListPanel.helpers'
import { groupByCategory, type PackingBagInfo, type PackingBagLookup } from './packingExport'
/*
* The packing list as a standalone page to print or save as PDF (#1420). Like the trip
* PDF it is a document of its own in a srcdoc frame, where the app's CSS variables do
* not reach, so its colours are written out here (the theme lint exempts this file).
*/
export interface PackingPrintText {
/** "Packing List · Shared": what the page is, above the title. */
eyebrow: string
/** The trip's title, or the list's name when the trip has none. */
title: string
/** The trip's dates, already formatted for the reader. */
dates: string | null
itemsLabel: string
packedLabel: string
weightLabel: string
bagsLabel: string
uncategorized: string
lang: string
/** Where the logos are served from; the page is a srcdoc and has no URL of its own. */
origin: string
/** The app's own @font-face rules, so the page prints in Poppins without asking a font CDN. */
fontCss: string
}
// A bag colour lands in a style attribute, so only a plain hex colour gets there.
const HEX_COLOR = /^#(?:[0-9a-f]{3}){1,2}$/i
const BAG_FALLBACK = '#94a3b8'
const bagColor = (info: PackingBagInfo): string =>
info.color && HEX_COLOR.test(info.color) ? info.color : BAG_FALLBACK
const CHECK_SVG =
'<svg viewBox="0 0 12 12" aria-hidden="true"><path d="M2.6 6.3 5 8.6 9.5 3.7" fill="none" stroke="#fff" '
+ 'stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/></svg>'
// The look of the trip PDF: Poppins, a navy cover block, small spaced capitals for labels,
// slate greys. Colour is kept for print on purpose, the categories are told apart by it.
const PRINT_CSS = `
@page { size: A4; margin: 12mm; }
*, *::before, *::after { box-sizing: border-box; }
html { background: #fff; }
body { margin: 0; color: #1e293b; font: 9.5pt/1.4 'Poppins', -apple-system, 'Segoe UI', Roboto, sans-serif; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
@media screen {
html { background: #e2e8f0; }
body { padding: 28px 16px; }
.sheet { max-width: 794px; margin: 0 auto; padding: 12mm; background: #fff; border-radius: 6px; box-shadow: 0 12px 40px rgba(15, 23, 42, 0.16); }
}
.hero { margin-bottom: 18px; padding: 22px 26px 20px; border-radius: 14px; background: #0f172a; color: #fff; break-inside: avoid; }
.hero-top { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
.eyebrow { font-size: 7.5pt; font-weight: 600; letter-spacing: 2px; text-transform: uppercase; color: rgba(255, 255, 255, 0.5); }
.hero-top img { height: 18px; opacity: 0.6; }
h1 { margin: 0; font-size: 24pt; font-weight: 700; line-height: 1.1; letter-spacing: -0.01em; }
.dates { margin-top: 6px; font-size: 9pt; color: rgba(255, 255, 255, 0.55); }
.stats { display: flex; gap: 30px; margin-top: 18px; padding-top: 14px; border-top: 1px solid rgba(255, 255, 255, 0.1); }
.stat b { display: block; font-size: 16pt; font-weight: 700; line-height: 1; }
.stat span { display: block; margin-top: 5px; font-size: 6.5pt; font-weight: 600; letter-spacing: 1px; text-transform: uppercase; color: rgba(255, 255, 255, 0.45); }
.progress { height: 4px; margin-top: 16px; overflow: hidden; border-radius: 99px; background: rgba(255, 255, 255, 0.12); }
.progress i { display: block; height: 100%; border-radius: 99px; background: #fff; }
main { columns: 2; column-gap: 14px; }
.cat { margin: 0 0 14px; padding: 10px 12px 6px; border: 1px solid #e2e8f0; border-radius: 12px; break-inside: avoid; }
.cat h2 { display: flex; align-items: center; gap: 7px; margin: 0 0 4px; font-size: 7.5pt; font-weight: 700; letter-spacing: 1.2px; text-transform: uppercase; color: #0f172a; }
.cat h2 i { flex: none; width: 7px; height: 7px; border-radius: 50%; background: var(--c); }
.cat h2 span { flex: 1; min-width: 0; }
.cat h2 em { padding: 1px 7px; border-radius: 99px; background: #f1f5f9; color: #64748b; font-size: 7pt; font-style: normal; font-weight: 600; letter-spacing: 0; }
ul { margin: 0; padding: 0; list-style: none; }
li { display: flex; align-items: center; gap: 7px; padding: 5px 0; border-top: 1px solid #f1f5f9; break-inside: avoid; }
li:first-child { border-top: 0; }
.box { display: flex; flex: none; align-items: center; justify-content: center; width: 13px; height: 13px; border: 1.5px solid #cbd5e1; border-radius: 4px; }
li.done .box { border-color: #0f172a; background: #0f172a; }
.box svg { width: 9px; height: 9px; }
.name { flex: 1; min-width: 0; font-weight: 500; }
li.done .name { color: #94a3b8; text-decoration: line-through; }
.qty { flex: none; padding: 1px 6px; border-radius: 99px; background: #f1f5f9; color: #475569; font-size: 7pt; font-weight: 600; }
.weight { flex: none; color: #64748b; font-size: 7.5pt; font-variant-numeric: tabular-nums; }
.bag { display: inline-flex; flex: none; align-items: center; gap: 4px; color: #64748b; font-size: 7pt; }
.bag i, .bag-card i { flex: none; width: 6px; height: 6px; border-radius: 50%; }
.bags { margin-top: 4px; break-inside: avoid; }
.bags h3 { margin: 0 0 8px; font-size: 7.5pt; font-weight: 700; letter-spacing: 1.2px; text-transform: uppercase; color: #64748b; }
.bag-list { display: flex; flex-wrap: wrap; gap: 8px; }
.bag-card { display: flex; align-items: center; gap: 7px; padding: 7px 12px; border: 1px solid #e2e8f0; border-radius: 10px; font-size: 8pt; }
.bag-card span { color: #64748b; }
footer { display: flex; align-items: center; justify-content: center; gap: 6px; margin-top: 22px; opacity: 0.35; color: #64748b; font-size: 6.5pt; letter-spacing: 0.5px; }
footer img { height: 9px; }
@media screen and (max-width: 560px) {
body { padding: 12px 8px; }
.sheet { padding: 16px; }
.hero { padding: 18px 18px 16px; }
h1 { font-size: 18pt; }
.stats { flex-wrap: wrap; gap: 14px 22px; }
main { columns: 1; }
}
`
interface BagSummary {
info: PackingBagInfo
count: number
grams: number
}
/** The bags this view's items go into, in the order they first appear, with this view's share of them. */
function bagSummaries(items: PackingItem[], bag: PackingBagLookup): BagSummary[] {
const byId = new Map<number, BagSummary>()
for (const item of items) {
const info = item.bag_id != null ? bag(item.bag_id) : undefined
if (!info || item.bag_id == null) continue
const summary = byId.get(item.bag_id) ?? { info, count: 0, grams: 0 }
summary.count += 1
summary.grams += packingItemWeight(item)
byId.set(item.bag_id, summary)
}
return [...byId.values()]
}
function itemRow(item: PackingItem, bag: PackingBagLookup): string {
const info = item.bag_id != null ? bag(item.bag_id) : undefined
const quantity = (item.quantity ?? 1) > 1 ? `<span class="qty">×${item.quantity}</span>` : ''
const weight = item.weight_grams ? `<span class="weight">${escapeHtml(formatWeight(packingItemWeight(item)))}</span>` : ''
const bagPill = info ? `<span class="bag"><i style="background:${bagColor(info)}"></i>${escapeHtml(info.name)}</span>` : ''
return `<li${item.checked ? ' class="done"' : ''}><span class="box">${item.checked ? CHECK_SVG : ''}</span>`
+ `<span class="name">${escapeHtml(item.name)}</span>${quantity}${weight}${bagPill}</li>`
}
/**
* The list as a page to print or save as PDF, in the look of the trip PDF: a navy cover
* block with the trip, its dates and the list's numbers, then one card per category in
* two columns, each item with a box to tick on paper. A category card never breaks across
* a column or a page, and the bags close the page with what each one holds.
*/
export function packingPrintHtml(items: PackingItem[], text: PackingPrintText, bag: PackingBagLookup): string {
const groups = groupByCategory(items, text.uncategorized)
const categories = groups.map(group => group.category)
const packed = items.filter(item => item.checked).length
const percent = items.length ? Math.round((packed / items.length) * 100) : 0
const total = items.reduce((sum, item) => sum + packingItemWeight(item), 0)
const bags = bagSummaries(items, bag)
const stat = (value: string, label: string) =>
`<div class="stat"><b>${escapeHtml(value)}</b><span>${escapeHtml(label)}</span></div>`
const stats = [
stat(String(items.length), text.itemsLabel),
stat(`${packed}/${items.length}`, text.packedLabel),
total > 0 ? stat(formatWeight(total), text.weightLabel) : '',
bags.length ? stat(String(bags.length), text.bagsLabel) : '',
].join('')
const sections = groups.map(group => {
const done = group.items.filter(item => item.checked).length
return `<section class="cat" style="--c:${katColor(group.category, categories)}">`
+ `<h2><i></i><span>${escapeHtml(group.category)}</span><em>${done}/${group.items.length}</em></h2>`
+ `<ul>${group.items.map(item => itemRow(item, bag)).join('')}</ul></section>`
}).join('')
const bagCards = bags.map(summary =>
`<div class="bag-card"><i style="background:${bagColor(summary.info)}"></i><b>${escapeHtml(summary.info.name)}</b>`
+ `<span>${summary.count} · ${escapeHtml(formatWeight(summary.grams))}</span></div>`).join('')
const bagsHtml = bags.length
? `<div class="bags"><h3>${escapeHtml(text.bagsLabel)}</h3><div class="bag-list">${bagCards}</div></div>`
: ''
const origin = escapeHtml(text.origin)
return `<!doctype html><html lang="${escapeHtml(text.lang)}"><head><meta charset="utf-8"><title>${escapeHtml(text.title)}</title>
<style>${text.fontCss}${PRINT_CSS}</style></head><body><div class="sheet">
<header class="hero">
<div class="hero-top"><span class="eyebrow">${escapeHtml(text.eyebrow)}</span><img src="${origin}/logo-light.svg" alt="TREK"></div>
<h1>${escapeHtml(text.title)}</h1>
${text.dates ? `<div class="dates">${escapeHtml(text.dates)}</div>` : ''}
<div class="stats">${stats}</div>
<div class="progress"><i style="width:${percent}%"></i></div>
</header>
<main>${sections}</main>
${bagsHtml}
<footer><span>made with</span><img src="${origin}/logo-dark.svg" alt="TREK"></footer>
</div></body></html>`
}
@@ -0,0 +1,170 @@
// FE-PACKEXPORTHOOK-001 to FE-PACKEXPORTHOOK-009
import { createElement, type ReactNode } from 'react'
import { act, renderHook, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { PackingItem } from '../../types'
import { TranslationProvider } from '../../i18n/TranslationContext'
import { useAddonStore } from '../../store/addonStore'
import { useTripStore } from '../../store/tripStore'
import { isEffectivelyOffline } from '../../sync/networkMode'
import { downloadBlob } from '../../utils/fileDownload'
import { packingApi } from '../../api/client'
import { appFontFaces, tripDateRange, usePackingExport } from './usePackingExport'
import { PACKING_PLACEHOLDER_NAME } from './packingListPanel.constants'
vi.mock('../../api/client', () => ({ packingApi: { listBags: vi.fn() } }))
vi.mock('../../utils/fileDownload', () => ({ downloadBlob: vi.fn() }))
vi.mock('../../sync/networkMode', async (importOriginal) => ({
...(await importOriginal<typeof import('../../sync/networkMode')>()),
isEffectivelyOffline: vi.fn(() => false),
}))
let nextId = 1
const item = (over: Partial<PackingItem>): PackingItem => ({
id: nextId++, trip_id: 7, name: 'Item', checked: 0, category: 'Clothing', sort_order: 0,
weight_grams: null, bag_id: null, quantity: 1, is_private: 0, ...over,
})
const ITEMS = [
item({ name: 'Socks', quantity: 7, weight_grams: 40, bag_id: 1 }),
item({ name: PACKING_PLACEHOLDER_NAME, category: 'Empty list' }),
item({ name: 'Diary', category: 'Personal', is_private: 1 }),
]
const wrapper = ({ children }: { children: ReactNode }) => createElement(TranslationProvider, null, children)
/** What the last download wrote, as text, with its file name. */
async function lastDownload(): Promise<{ name: string; text: string; type: string }> {
const calls = vi.mocked(downloadBlob).mock.calls
const [blob, name] = calls[calls.length - 1] as [Blob, string]
return { name, text: await blob.text(), type: blob.type }
}
beforeEach(() => {
useTripStore.setState({ trip: { id: 7, title: 'Lisbon & Porto', start_date: '2026-10-09', end_date: '2026-10-16' } as never, packingItems: ITEMS })
useAddonStore.setState({ bagTracking: true })
vi.mocked(isEffectivelyOffline).mockReturnValue(false)
vi.mocked(packingApi.listBags).mockResolvedValue({ bags: [{ id: 1, name: 'Suitcase', color: '#f97316' }] })
})
afterEach(() => {
vi.clearAllMocks()
useTripStore.setState({ trip: null as never, packingItems: [] })
useAddonStore.setState({ bagTracking: false })
})
describe('usePackingExport', () => {
it('FE-PACKEXPORTHOOK-001: exports the Shared view without private items or category placeholders', async () => {
const { result } = renderHook(() => usePackingExport(7, 'common'), { wrapper })
expect(result.current.hasItems).toBe(true)
act(() => result.current.exportMarkdown())
const file = await lastDownload()
expect(file.name).toBe('packing-list-lisbon-porto.md')
expect(file.type).toBe('text/markdown;charset=utf-8')
expect(file.text).toContain('# Packing List: Lisbon & Porto (Shared)')
expect(file.text).toContain('- [ ] 7 × Socks (40 g)')
expect(file.text).not.toContain('Diary')
expect(file.text).not.toContain(PACKING_PLACEHOLDER_NAME)
expect(file.text).not.toContain('Empty list')
})
it('FE-PACKEXPORTHOOK-002: exports My list with only the private items', async () => {
const { result } = renderHook(() => usePackingExport(7, 'personal'), { wrapper })
act(() => result.current.exportMarkdown())
const file = await lastDownload()
expect(file.text).toContain('(My list)')
expect(file.text).toContain('- [ ] Diary')
expect(file.text).not.toContain('Socks')
})
it('FE-PACKEXPORTHOOK-003: writes the bag names into the CSV', async () => {
const { result } = renderHook(() => usePackingExport(7, 'common'), { wrapper })
await act(() => result.current.exportCsv())
const file = await lastDownload()
expect(file.name).toBe('packing-list-lisbon-porto.csv')
expect(file.text).toBe('Clothing,7 × Socks,40,Suitcase,\n')
expect(packingApi.listBags).toHaveBeenCalledWith(7)
})
it('FE-PACKEXPORTHOOK-004: goes without bags offline, with bag tracking off, or when the bags cannot be read', async () => {
vi.mocked(isEffectivelyOffline).mockReturnValue(true)
const { result, rerender } = renderHook(() => usePackingExport(7, 'common'), { wrapper })
await act(() => result.current.exportCsv())
expect((await lastDownload()).text).toBe('Clothing,7 × Socks,40,,\n')
vi.mocked(isEffectivelyOffline).mockReturnValue(false)
act(() => useAddonStore.setState({ bagTracking: false }))
rerender()
await act(() => result.current.exportCsv())
expect((await lastDownload()).text).toBe('Clothing,7 × Socks,40,,\n')
expect(packingApi.listBags).not.toHaveBeenCalled()
act(() => useAddonStore.setState({ bagTracking: true }))
rerender()
vi.mocked(packingApi.listBags).mockRejectedValue(new Error('Network Error'))
await act(() => result.current.exportCsv())
expect((await lastDownload()).text).toBe('Clothing,7 × Socks,40,,\n')
})
it('FE-PACKEXPORTHOOK-005: opens the printable page with the trip, its dates and the list’s labels, and closes it', async () => {
const { result } = renderHook(() => usePackingExport(7, 'common'), { wrapper })
expect(result.current.printHtml).toBeNull()
expect(result.current.printTitle).toBe('Packing List: Lisbon & Porto')
await act(() => result.current.openPrint())
const html = result.current.printHtml ?? ''
expect(html).toContain('<h1>Lisbon &amp; Porto</h1>')
expect(html).toContain('Packing List · Shared')
expect(html).toContain('<span>Items</span>')
expect(html).toContain('<span>Packed</span>')
expect(html).toContain('<i style="background:#f97316"></i>Suitcase')
expect(html).toContain(`${window.location.origin}/logo-light.svg`)
expect(html).toMatch(/Oct\D+9\D+16, 2026/)
act(() => result.current.closePrint())
await waitFor(() => expect(result.current.printHtml).toBeNull())
})
it('FE-PACKEXPORTHOOK-006: has nothing to export for an empty view', () => {
act(() => useTripStore.setState({ packingItems: [item({ name: PACKING_PLACEHOLDER_NAME })] }))
const { result } = renderHook(() => usePackingExport(7, 'common'), { wrapper })
expect(result.current.hasItems).toBe(false)
})
})
describe('tripDateRange', () => {
it('FE-PACKEXPORTHOOK-007: formats one day, a range, or nothing, on the calendar day whatever the offset', () => {
expect(tripDateRange(null, null, 'en')).toBeNull()
expect(tripDateRange('2026-10-09', '2026-10-09', 'en')).toBe('Oct 9, 2026')
expect(tripDateRange('2026-10-09', null, 'de')).toBe('9. Okt. 2026')
expect(tripDateRange('2026-12-30', '2027-01-02', 'en')).toMatch(/Dec 30, 2026\D+Jan 2, 2027/)
})
})
describe('appFontFaces', () => {
it('FE-PACKEXPORTHOOK-008: copies the family’s @font-face rules with absolute urls and skips sheets it may not read', () => {
const fontFace = (cssText: string) => ({ type: CSSRule.FONT_FACE_RULE, cssText })
const doc = {
baseURI: 'https://trek.example/trips/7',
styleSheets: [
{
href: 'https://trek.example/assets/index.css',
cssRules: [
fontFace('@font-face { font-family: Poppins; src: url("./poppins-400.woff2") format("woff2"); }'),
fontFace('@font-face { font-family: Geist; src: url(/geist.woff2); }'),
{ type: CSSRule.STYLE_RULE, cssText: 'body { font-family: Poppins; }' },
],
},
{ href: null, cssRules: [fontFace("@font-face { font-family: 'Poppins'; src: url(/assets/poppins-700.woff2); }")] },
{ href: 'https://cdn.example/x.css', get cssRules(): never { throw new DOMException('blocked', 'SecurityError') } },
],
} as unknown as Document
const css = appFontFaces('Poppins', doc)
expect(css).toContain('url("https://trek.example/assets/poppins-400.woff2")')
expect(css).toContain('url(https://trek.example/assets/poppins-700.woff2)')
expect(css).not.toContain('Geist')
expect(css).not.toContain('body {')
})
it('FE-PACKEXPORTHOOK-009: reads the live document by default without throwing', () => {
expect(typeof appFontFaces('Poppins')).toBe('string')
})
})
@@ -0,0 +1,126 @@
import { useCallback, useMemo, useState } from 'react'
import { packingApi } from '../../api/client'
import { useTranslation } from '../../i18n'
import { packingViewItems, type PackingView } from '../../mobile/screens/trip/tabs/listsModel'
import { useAddonStore } from '../../store/addonStore'
import { useTripStore } from '../../store/tripStore'
import { isEffectivelyOffline } from '../../sync/networkMode'
import { downloadBlob } from '../../utils/fileDownload'
import { PACKING_PLACEHOLDER_NAME } from './packingListPanel.constants'
import { packingCsv, packingFileName, packingMarkdown, type PackingBagLookup } from './packingExport'
import { packingPrintHtml } from './packingPrintDocument'
export type { PackingView }
const noBag: PackingBagLookup = () => undefined
/** The trip's dates as one range in the reader's language, or null for a trip without them. */
export function tripDateRange(start: string | null | undefined, end: string | null | undefined, locale: string): string | null {
if (!start) return null
// Pinned to UTC: a trip date is a calendar day, and the reader's offset must not move it.
const format = new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' })
const from = new Date(`${start}T00:00:00Z`)
if (!end || end === start) return format.format(from)
const to = new Date(`${end}T00:00:00Z`)
const ranged = format as Intl.DateTimeFormat & { formatRange?: (a: Date, b: Date) => string }
return ranged.formatRange ? ranged.formatRange(from, to) : `${format.format(from)} · ${format.format(to)}`
}
/**
* The @font-face rules the app loaded for `family`, with every url made absolute.
*
* The printable page is a srcdoc frame that knows no fonts of its own. Handing it the
* app's rules lets it print in Poppins from the same origin, where the trip PDF still
* asks Google for it.
*/
export function appFontFaces(family: string, doc: Document = document): string {
const rules: string[] = []
for (const sheet of Array.from(doc.styleSheets)) {
let sheetRules: CSSRuleList
try {
sheetRules = sheet.cssRules
} catch {
continue // a cross-origin sheet does not let its rules be read, and has no font of ours
}
const base = sheet.href || doc.baseURI
for (const rule of Array.from(sheetRules)) {
if (rule.type !== CSSRule.FONT_FACE_RULE || !rule.cssText.includes(family)) continue
rules.push(rule.cssText.replace(/url\((["']?)([^"')]+)\1\)/g, (_, quote: string, url: string) =>
`url(${quote}${new URL(url, base).href}${quote})`))
}
}
return rules.join('\n')
}
/**
* Export, CSV and print for the view of the packing list on screen (#875, #1420), for
* the desktop header and the phone's action menu alike.
*
* Exactly what the view shows goes out: the Personal list never takes the group's
* items along, and the Common one never takes anybody's private ones. The placeholder
* rows that keep an empty category on screen are not items and stay behind.
*
* Bags are read when an export runs rather than kept in sync, because only a CSV row
* or the printout needs them; offline, or with bag tracking off, rows go without.
*/
export function usePackingExport(tripId: number | string, view: PackingView) {
const { t, language, locale } = useTranslation()
const trip = useTripStore(s => s.trip)
const allItems = useTripStore(s => s.packingItems)
const bagTracking = useAddonStore(s => s.bagTracking)
const items = useMemo(
() => packingViewItems(allItems, view).filter(item => item.name !== PACKING_PLACEHOLDER_NAME),
[allItems, view],
)
const [printHtml, setPrintHtml] = useState<string | null>(null)
const tripTitle = trip?.title
const listName = view === 'personal' ? t('packing.viewPersonal') : t('packing.viewCommon')
const title = tripTitle ? `${t('packing.title')}: ${tripTitle}` : t('packing.title')
const uncategorized = t('packing.defaultCategory')
const bagLookup = useCallback(async (): Promise<PackingBagLookup> => {
if (!bagTracking || isEffectivelyOffline()) return noBag
try {
const { bags } = await packingApi.listBags(tripId) as { bags?: { id: number; name: string; color?: string | null }[] }
const byId = new Map((bags ?? []).map(bag => [bag.id, { name: bag.name, color: bag.color }]))
return bagId => byId.get(bagId)
} catch {
return noBag
}
}, [bagTracking, tripId])
const download = useCallback((content: string, type: string, extension: string) => {
downloadBlob(new Blob([content], { type: `${type};charset=utf-8` }), packingFileName(tripTitle, extension))
}, [tripTitle])
const exportMarkdown = useCallback(() => {
download(packingMarkdown(items, `${title} (${listName})`, uncategorized), 'text/markdown', '.md')
}, [download, items, title, listName, uncategorized])
const exportCsv = useCallback(async () => {
download(packingCsv(items, await bagLookup()), 'text/csv', '.csv')
}, [download, items, bagLookup])
const openPrint = useCallback(async () => {
setPrintHtml(packingPrintHtml(items, {
eyebrow: `${t('packing.title')} · ${listName}`,
title: tripTitle || t('packing.title'),
dates: tripDateRange(trip?.start_date, trip?.end_date, locale),
itemsLabel: t('packing.printItems'),
packedLabel: t('packing.printPacked'),
weightLabel: t('packing.totalWeight'),
bagsLabel: t('packing.bags'),
uncategorized,
lang: language,
origin: window.location.origin,
fontCss: appFontFaces('Poppins'),
}, await bagLookup()))
}, [items, t, listName, tripTitle, trip?.start_date, trip?.end_date, locale, uncategorized, language, bagLookup])
const closePrint = useCallback(() => setPrintHtml(null), [])
return { hasItems: items.length > 0, exportMarkdown, exportCsv, openPrint, printHtml, printTitle: title, closePrint }
}
export type PackingExport = ReturnType<typeof usePackingExport>