mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 18:34:09 +00:00
refactor(packing): share the packing list logic between desktop and phone
usePackingItemActions, usePackingTemplates and usePackingImport take the item, template and bulk import logic out of usePackingListPanel and MPackingListTab, and the phone listsModel keeps only its priority tokens. When adding to a category the desktop looks for the placeholder in the store and the phone in its rendered items. The desktop toasts on an empty import, the phone runs one import at a time. The effects run in the same order as before.
This commit is contained in:
@@ -6,7 +6,7 @@ import { FIELD_CLS, FormSheetHeader } from '../sheets/PlSheetChrome'
|
||||
import { avatarSrc } from '../../../../utils/avatarSrc'
|
||||
import type { PackingBag, PackingItem, TripMember } from '../../../../types'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
import { formatWeight } from './listsModel'
|
||||
import { formatWeight } from '../../../../components/Packing/packingListModel'
|
||||
import { bagFillPct, bagTotalWeight, countsTowardsMyLoad, unassignedTotalWeight } from '../../../../components/Packing/packingListPanel.helpers'
|
||||
|
||||
export interface MBagsSheetProps {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Eyebrow, FIELD_CLS, FormSheetFooter, FormSheetHeader } from '../sheets/
|
||||
import { avatarSrc } from '../../../../utils/avatarSrc'
|
||||
import type { PackingItem, TripMember } from '../../../../types'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
import { isPackingPlaceholder } from './listsModel'
|
||||
import { isPackingPlaceholder } from '../../../../components/Packing/packingListModel'
|
||||
|
||||
export interface MPackItemSheetProps {
|
||||
planner: TripPlanner
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { useRef } from 'react'
|
||||
import { FileDown } from 'lucide-react'
|
||||
import MSheet from '../../../components/MSheet'
|
||||
import { Eyebrow, FIELD_AREA_CLS, FormSheetFooter, FormSheetHeader } from '../sheets/PlSheetChrome'
|
||||
import { packingApi } from '../../../../api/client'
|
||||
import { useTripStore } from '../../../../store/tripStore'
|
||||
import { parseImportLines } from '../../../../components/Packing/packingListPanel.helpers'
|
||||
import { usePackingImport } from '../../../../components/Packing/usePackingImport'
|
||||
import { PACKING_IMPORT_ACCEPT } from '../../../../components/Packing/packingListPanel.constants'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
|
||||
@@ -16,43 +14,15 @@ export interface MPackingImportSheetProps {
|
||||
|
||||
/**
|
||||
* Bulk packing import (spec 03 §4.2 action-menu "Import"): one item per line,
|
||||
* `Category, Name, Weight(g), Bag, checked` — same parser + endpoint as the
|
||||
* desktop bulk-import modal (`packingListPanel.helpers.parseImportLines` +
|
||||
* `packingApi.bulkImport`), appended straight into the trip store so both
|
||||
* surfaces stay consistent.
|
||||
* `Category, Name, Weight(g), Bag, checked`, run by the same `usePackingImport`
|
||||
* as the desktop bulk-import dialog, which appends the result straight into the
|
||||
* trip store so both surfaces stay consistent.
|
||||
*/
|
||||
export default function MPackingImportSheet({ planner, open, onClose }: MPackingImportSheetProps) {
|
||||
const { t, toast, tripId } = planner
|
||||
const [text, setText] = useState('')
|
||||
const [importing, setImporting] = useState(false)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const parsed = parseImportLines(text)
|
||||
|
||||
const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (!file) return
|
||||
e.target.value = ''
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => { if (typeof reader.result === 'string') setText(reader.result) }
|
||||
reader.readAsText(file)
|
||||
}
|
||||
|
||||
const handleImport = async () => {
|
||||
if (parsed.length === 0 || importing) return
|
||||
setImporting(true)
|
||||
try {
|
||||
const result = await packingApi.bulkImport(tripId, parsed)
|
||||
useTripStore.setState(s => ({ packingItems: [...s.packingItems, ...(result.items || [])] }))
|
||||
toast.success(t('packing.importSuccess', { count: result.count }))
|
||||
setText('')
|
||||
onClose()
|
||||
} catch {
|
||||
toast.error(t('packing.importError'))
|
||||
} finally {
|
||||
setImporting(false)
|
||||
}
|
||||
}
|
||||
const { text, setText, parsed, importing, readFile: handleFile, runImport: handleImport } =
|
||||
usePackingImport({ tripId, t, toast, onImported: onClose, oneAtATime: true })
|
||||
|
||||
return (
|
||||
<MSheet open={open} onClose={onClose} ariaLabel={t('packing.importTitle')}>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useState, useCallback } from 'react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import {
|
||||
Briefcase, Check, CheckCheck, ChevronDown, ChevronUp, HandHelping, Minus,
|
||||
@@ -8,23 +8,21 @@ import {
|
||||
import MDancingTrek from '../../../components/MDancingTrek'
|
||||
import { useAuthStore } from '../../../../store/authStore'
|
||||
import { useAddonStore } from '../../../../store/addonStore'
|
||||
import { useTripStore } from '../../../../store/tripStore'
|
||||
import { packingApi } from '../../../../api/client'
|
||||
import { useNetworkMode } from '../../../../hooks/useNetworkMode'
|
||||
import { useBagTotalsPing } from '../../../../components/Packing/useBagTotalsPing'
|
||||
import type { PackingUpdateBagRequest } from '@trek/shared'
|
||||
import type { PackingBag, PackingItem, TripMember } from '../../../../types'
|
||||
import type { TripPlanner } from '../MTripShell'
|
||||
import MConfirmSheet from '../../settings/MConfirmSheet'
|
||||
import { FIELD_CLS } from '../sheets/PlSheetChrome'
|
||||
import { TabScroller } from './tabChrome'
|
||||
import { katColor, newItemSharing, packedOf } from '../../../../components/Packing/packingListPanel.helpers'
|
||||
import { BAG_COLORS, PACKING_PLACEHOLDER_NAME } from '../../../../components/Packing/packingListPanel.constants'
|
||||
import { katColor, packedOf } from '../../../../components/Packing/packingListPanel.helpers'
|
||||
import {
|
||||
formatWeight, groupPackingItems, isLastCustomItemInCategory, isPackingPlaceholder,
|
||||
formatWeight, groupPackingItems, isPackingPlaceholder,
|
||||
packingCategoryOrder, packingProgress, packingViewItems,
|
||||
type PackingCategoryGroup, type PackingStatusFilter, type PackingView,
|
||||
} from './listsModel'
|
||||
} from '../../../../components/Packing/packingListModel'
|
||||
import { usePackingBags } from '../../../../components/Packing/usePackingBags'
|
||||
import { usePackingTemplates } from '../../../../components/Packing/usePackingTemplates'
|
||||
import { usePackingCategoryAssignees, type CategoryAssignee } from '../../../../components/Packing/usePackingCategoryAssignees'
|
||||
import { usePackingItemActions } from '../../../../components/Packing/usePackingItemActions'
|
||||
import MBagsSheet from './MBagsSheet'
|
||||
import MPackItemSheet from './MPackItemSheet'
|
||||
import MPackingImportSheet from './MPackingImportSheet'
|
||||
@@ -32,8 +30,6 @@ import PackingPrintPreview from '../../../../components/Packing/PackingPrintPrev
|
||||
import { usePackingExport } from '../../../../components/Packing/usePackingExport'
|
||||
|
||||
type ActionView = 'menu' | 'apply' | 'save'
|
||||
interface CategoryAssignee { user_id: number; username: string }
|
||||
interface PackingTemplate { id: number; name: string; item_count: number }
|
||||
|
||||
/**
|
||||
* Packing sub-tab (spec 03 §4.1-4.4): progress card, action menu (remove
|
||||
@@ -59,50 +55,22 @@ export default function MPackingListTab({ planner }: { planner: TripPlanner }) {
|
||||
const [editMode, setEditMode] = useState(false)
|
||||
const [actionsOpen, setActionsOpen] = useState(false)
|
||||
const [actionView, setActionView] = useState<ActionView>('menu')
|
||||
const [saveTemplateName, setSaveTemplateName] = useState('')
|
||||
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({})
|
||||
const [addingCategory, setAddingCategory] = useState(false)
|
||||
const [newCategoryName, setNewCategoryName] = useState('')
|
||||
const [editingItemId, setEditingItemId] = useState<number | null>(null)
|
||||
const [showBagsSheet, setShowBagsSheet] = useState(false)
|
||||
const [showImportSheet, setShowImportSheet] = useState(false)
|
||||
const [confirmClear, setConfirmClear] = useState(false)
|
||||
const [deleteCategoryTarget, setDeleteCategoryTarget] = useState<{ name: string; items: PackingItem[] } | null>(null)
|
||||
|
||||
const [bags, setBags] = useState<PackingBag[]>([])
|
||||
/** Server-summed weight of everything in no bag (#2191); null until first load. */
|
||||
const [unassignedWeightGrams, setUnassignedWeightGrams] = useState<number | null>(null)
|
||||
const [templates, setTemplates] = useState<PackingTemplate[]>([])
|
||||
const [categoryAssignees, setCategoryAssignees] = useState<Record<string, CategoryAssignee[]>>({})
|
||||
|
||||
const reloadBags = useCallback(async () => {
|
||||
if (!bagTrackingEnabled) return
|
||||
try {
|
||||
const r = await packingApi.listBags(tripId)
|
||||
setBags(r.bags || [])
|
||||
setUnassignedWeightGrams(r.unassigned_weight_grams ?? null)
|
||||
} catch {
|
||||
// Offline or a failed read: the sheet falls back to the local sum.
|
||||
}
|
||||
}, [tripId, bagTrackingEnabled])
|
||||
|
||||
useEffect(() => { void reloadBags() }, [reloadBags])
|
||||
|
||||
// Bag weights are server-summed across every member (#2191), so an item this
|
||||
// viewer cannot see still moves them; the server pings the room content-free.
|
||||
useBagTotalsPing(bagTrackingEnabled, reloadBags)
|
||||
|
||||
// Bags have no offline cache, so their totals go stale the moment the device
|
||||
// does; offline the sheet sums what it can see instead (#2191).
|
||||
const { offline } = useNetworkMode()
|
||||
|
||||
useEffect(() => {
|
||||
packingApi.listTemplates(tripId).then(r => setTemplates(r.templates || [])).catch(() => {})
|
||||
}, [tripId])
|
||||
|
||||
useEffect(() => {
|
||||
packingApi.getCategoryAssignees(tripId).then(r => setCategoryAssignees(r.assignees || {})).catch(() => {})
|
||||
}, [tripId])
|
||||
const closeActions = () => {
|
||||
setActionsOpen(false)
|
||||
setActionView('menu')
|
||||
}
|
||||
const { bags, unassignedWeightGrams, serverWeightsFresh, createBag, updateBag, deleteBag, setBagMembers } =
|
||||
usePackingBags({ tripId, bagTrackingEnabled, t, toast })
|
||||
const { templates, applyTemplate, saveTemplateName, setSaveTemplateName, saveAsTemplate } =
|
||||
usePackingTemplates({ tripId, view, t, toast, onApplied: closeActions, onSaved: closeActions })
|
||||
const { categoryAssignees, setAssignees: setCategoryAssigneesFor } = usePackingCategoryAssignees({ tripId, t, toast })
|
||||
|
||||
const defaultCategory = t('packing.defaultCategory')
|
||||
const viewItems = useMemo(() => packingViewItems(items, view), [items, view])
|
||||
@@ -111,57 +79,16 @@ export default function MPackingListTab({ planner }: { planner: TripPlanner }) {
|
||||
const progress = packingProgress(viewItems)
|
||||
const checkedCount = viewItems.filter(i => i.checked).length
|
||||
|
||||
const {
|
||||
addingCategory, setAddingCategory, newCategoryName, setNewCategoryName, addItemToCategory, deleteItem,
|
||||
renameCategoryReporting: renameCategory, deleteCategoryItems, clearChecked, addNewCategory,
|
||||
} = usePackingItemActions({
|
||||
tripId, items, view, currentUserId, categories: categoryOrder, defaultCategory,
|
||||
actions: tripActions, t, toast, placeholderFrom: 'items',
|
||||
})
|
||||
|
||||
const toggleCategory = (cat: string) => setCollapsed(c => ({ ...c, [cat]: !c[cat] }))
|
||||
|
||||
const addItemToCategory = async (category: string, name: string) => {
|
||||
try {
|
||||
const placeholder = items.find(i => i.category === category && isPackingPlaceholder(i))
|
||||
if (placeholder) {
|
||||
await tripActions.updatePackingItem(tripId, placeholder.id, { name })
|
||||
} else {
|
||||
await tripActions.addPackingItem(
|
||||
tripId,
|
||||
// In "my list", shared the way the category's own items all are (#2241).
|
||||
{ name, category, ...newItemSharing(items, category, view, currentUserId) } as Parameters<typeof tripActions.addPackingItem>[1],
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
toast.error(t('packing.toast.addError'))
|
||||
}
|
||||
}
|
||||
|
||||
const deleteItem = async (item: PackingItem) => {
|
||||
try {
|
||||
if (isLastCustomItemInCategory(item, items)) {
|
||||
if (item.checked) await tripActions.togglePackingItem(tripId, item.id, false)
|
||||
await tripActions.updatePackingItem(tripId, item.id, {
|
||||
name: PACKING_PLACEHOLDER_NAME, weight_grams: null, bag_id: null, quantity: 1,
|
||||
})
|
||||
} else {
|
||||
await tripActions.deletePackingItem(tripId, item.id)
|
||||
}
|
||||
} catch {
|
||||
toast.error(t('packing.toast.deleteError'))
|
||||
}
|
||||
}
|
||||
|
||||
const renameCategory = async (oldName: string, newName: string) => {
|
||||
const toUpdate = items.filter(i => (i.category || defaultCategory) === oldName)
|
||||
try {
|
||||
for (const item of toUpdate) await tripActions.updatePackingItem(tripId, item.id, { category: newName })
|
||||
} catch {
|
||||
toast.error(t('packing.toast.renameError'))
|
||||
}
|
||||
}
|
||||
|
||||
const deleteCategoryItems = async (catItems: PackingItem[]) => {
|
||||
let failed = false
|
||||
for (const item of catItems) {
|
||||
try { await tripActions.deletePackingItem(tripId, item.id) } catch { failed = true }
|
||||
}
|
||||
if (failed) toast.error(t('packing.toast.deleteError'))
|
||||
}
|
||||
|
||||
const checkAllInCategory = async (catItems: PackingItem[]) => {
|
||||
try {
|
||||
for (const item of catItems) if (!item.checked) await tripActions.togglePackingItem(tripId, item.id, true)
|
||||
@@ -177,103 +104,6 @@ export default function MPackingListTab({ planner }: { planner: TripPlanner }) {
|
||||
}
|
||||
}
|
||||
|
||||
const addNewCategory = async () => {
|
||||
const trimmed = newCategoryName.trim()
|
||||
if (!trimmed) return
|
||||
let catName = trimmed
|
||||
while (categoryOrder.includes(catName)) catName += ''
|
||||
try {
|
||||
await tripActions.addPackingItem(
|
||||
tripId,
|
||||
{ name: PACKING_PLACEHOLDER_NAME, category: catName, visibility: view === 'personal' ? 'personal' : 'common' } as Parameters<typeof tripActions.addPackingItem>[1],
|
||||
)
|
||||
setNewCategoryName('')
|
||||
setAddingCategory(false)
|
||||
} catch {
|
||||
toast.error(t('packing.toast.addError'))
|
||||
}
|
||||
}
|
||||
|
||||
const clearChecked = async () => {
|
||||
let failed = false
|
||||
for (const item of items.filter(i => i.checked)) {
|
||||
try { await tripActions.deletePackingItem(tripId, item.id) } catch { failed = true }
|
||||
}
|
||||
if (failed) toast.error(t('packing.toast.deleteError'))
|
||||
}
|
||||
|
||||
const createBag = async (name: string): Promise<PackingBag | undefined> => {
|
||||
try {
|
||||
const data = await packingApi.createBag(tripId, { name, color: BAG_COLORS[bags.length % BAG_COLORS.length] })
|
||||
setBags(prev => [...prev, data.bag])
|
||||
return data.bag
|
||||
} catch {
|
||||
toast.error(t('packing.toast.saveError'))
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
const updateBag = async (bagId: number, data: PackingUpdateBagRequest) => {
|
||||
try {
|
||||
const result = await packingApi.updateBag(tripId, bagId, data)
|
||||
setBags(prev => prev.map(b => (b.id === bagId ? { ...b, ...result.bag } : b)))
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
const deleteBag = async (bagId: number) => {
|
||||
try {
|
||||
await packingApi.deleteBag(tripId, bagId)
|
||||
setBags(prev => prev.filter(b => b.id !== bagId))
|
||||
} catch {
|
||||
toast.error(t('packing.toast.deleteError'))
|
||||
}
|
||||
}
|
||||
const setBagMembers = async (bagId: number, userIds: number[]) => {
|
||||
try {
|
||||
const result = await packingApi.setBagMembers(tripId, bagId, userIds)
|
||||
setBags(prev => prev.map(b => (b.id === bagId ? { ...b, members: result.members } : b)))
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const setCategoryAssigneesFor = async (category: string, userIds: number[]) => {
|
||||
try {
|
||||
const data = await packingApi.setCategoryAssignees(tripId, category, userIds)
|
||||
setCategoryAssignees(prev => ({ ...prev, [category]: data.assignees || [] }))
|
||||
} catch {
|
||||
toast.error(t('packing.toast.saveError'))
|
||||
}
|
||||
}
|
||||
|
||||
const applyTemplate = async (templateId: number) => {
|
||||
try {
|
||||
// Land the items in the list the user is looking at — without the
|
||||
// visibility the API defaults to 'common' and they vanish from My list.
|
||||
const data = await packingApi.applyTemplate(tripId, templateId, view)
|
||||
useTripStore.setState(s => ({ packingItems: [...s.packingItems, ...(data.items || [])] }))
|
||||
toast.success(t('packing.templateApplied', { count: data.count }))
|
||||
setActionsOpen(false)
|
||||
setActionView('menu')
|
||||
} catch {
|
||||
toast.error(t('packing.templateError'))
|
||||
}
|
||||
}
|
||||
|
||||
const saveAsTemplate = async () => {
|
||||
if (!saveTemplateName.trim()) return
|
||||
try {
|
||||
await packingApi.saveAsTemplate(tripId, saveTemplateName.trim())
|
||||
toast.success(t('packing.templateSaved'))
|
||||
setSaveTemplateName('')
|
||||
setActionsOpen(false)
|
||||
setActionView('menu')
|
||||
packingApi.listTemplates(tripId).then(r => setTemplates(r.templates || [])).catch(() => {})
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const filterPillCls = (active: boolean) =>
|
||||
`flex-1 whitespace-nowrap rounded-full px-2 py-[6px] text-center text-[0.71875rem] font-semibold ${
|
||||
active ? 'bg-m-act text-m-actfg' : 'bg-[color:var(--m-ic)] text-m-ink'
|
||||
@@ -507,7 +337,7 @@ export default function MPackingListTab({ planner }: { planner: TripPlanner }) {
|
||||
bags={bags}
|
||||
items={items}
|
||||
unassignedWeightGrams={unassignedWeightGrams}
|
||||
serverWeightsFresh={!offline}
|
||||
serverWeightsFresh={serverWeightsFresh}
|
||||
tripMembers={tripMembers}
|
||||
canEdit={canEdit}
|
||||
currentUserId={currentUserId}
|
||||
|
||||
@@ -1,110 +1,12 @@
|
||||
import type { PackingItem } from '../../../../types'
|
||||
import { PACKING_PLACEHOLDER_NAME } from '../../../../components/Packing/packingListPanel.constants'
|
||||
import { STATUS_COLOR } from './tabModel'
|
||||
|
||||
/**
|
||||
* Pure view-model helpers for the Listen tab (Packing + To-do), the real-data
|
||||
* counterpart to the demo's `PACK`/`TODOS` state (spec 03 §4). No React, no
|
||||
* side effects — grouping/filtering/sorting only, mirroring the desktop hooks
|
||||
* (`usePackingListPanel.ts`, `useTodoList.ts`) closely enough that switching a
|
||||
* filter here and there produces the same buckets.
|
||||
* The phone's priority tokens for the Listen tab's to-do list (spec 03 §4.7).
|
||||
* The grouping, filtering and counting behind both lists is shared with the
|
||||
* desktop panels: `components/Packing/packingListModel.ts` and
|
||||
* `components/Todo/todoListModel.ts`.
|
||||
*/
|
||||
|
||||
// ── Packing ──────────────────────────────────────────────────────────────
|
||||
|
||||
export type PackingView = 'common' | 'personal'
|
||||
export type PackingStatusFilter = 'all' | 'open' | 'done'
|
||||
|
||||
/** Three-tier sharing split (#858): Common = group pool, Personal = mine + shared-to-me. */
|
||||
export function packingViewItems(items: PackingItem[], view: PackingView): PackingItem[] {
|
||||
return items.filter(i => (view === 'common' ? !i.is_private : !!i.is_private))
|
||||
}
|
||||
|
||||
/** Category display order = first-appearance order within the active view (stable colours). */
|
||||
export function packingCategoryOrder(viewItems: PackingItem[], defaultCategory: string): string[] {
|
||||
const seen: string[] = []
|
||||
for (const item of viewItems) {
|
||||
const cat = item.category || defaultCategory
|
||||
if (!seen.includes(cat)) seen.push(cat)
|
||||
}
|
||||
return seen
|
||||
}
|
||||
|
||||
export function packingStatusFiltered(items: PackingItem[], status: PackingStatusFilter): PackingItem[] {
|
||||
if (status === 'open') return items.filter(i => !i.checked)
|
||||
if (status === 'done') return items.filter(i => !!i.checked)
|
||||
return items
|
||||
}
|
||||
|
||||
export interface PackingCategoryGroup {
|
||||
category: string
|
||||
items: PackingItem[]
|
||||
}
|
||||
|
||||
/** Groups the view+status filtered items by category, in first-encounter order. */
|
||||
export function groupPackingItems(
|
||||
viewItems: PackingItem[],
|
||||
status: PackingStatusFilter,
|
||||
defaultCategory: string,
|
||||
): PackingCategoryGroup[] {
|
||||
const filtered = packingStatusFiltered(viewItems, status)
|
||||
const order: string[] = []
|
||||
const byCategory = new Map<string, PackingItem[]>()
|
||||
for (const item of filtered) {
|
||||
const cat = item.category || defaultCategory
|
||||
let bucket = byCategory.get(cat)
|
||||
if (!bucket) {
|
||||
bucket = []
|
||||
byCategory.set(cat, bucket)
|
||||
order.push(cat)
|
||||
}
|
||||
bucket.push(item)
|
||||
}
|
||||
return order.map(category => ({ category, items: byCategory.get(category) as PackingItem[] }))
|
||||
}
|
||||
|
||||
export interface PackingProgress {
|
||||
checked: number
|
||||
total: number
|
||||
pct: number
|
||||
}
|
||||
|
||||
export function packingProgress(items: PackingItem[]): PackingProgress {
|
||||
const checked = items.filter(i => i.checked).length
|
||||
const total = items.length
|
||||
return { checked, total, pct: total > 0 ? Math.round((checked / total) * 100) : 0 }
|
||||
}
|
||||
|
||||
/** "232 g" under 1000g, "1.2 kg" at/above — matches the demo's `gFmt` (spec 03 §4.4). */
|
||||
export function formatWeight(grams: number): string {
|
||||
return grams >= 1000 ? `${(grams / 1000).toFixed(1)} kg` : `${Math.round(grams)} g`
|
||||
}
|
||||
|
||||
/** Weight an item contributes to a bag/total: unit weight times quantity. */
|
||||
export function packingItemWeight(item: Pick<PackingItem, 'weight_grams' | 'quantity'>): number {
|
||||
return (item.weight_grams || 0) * (item.quantity || 1)
|
||||
}
|
||||
|
||||
/**
|
||||
* True when deleting `item` would empty its (custom) category — the row
|
||||
* should be reset to the `...` placeholder instead of removed so the
|
||||
* category keeps its position/colour (mirrors usePackingListPanel's
|
||||
* handleDeleteItem, #1289).
|
||||
*/
|
||||
export function isLastCustomItemInCategory(item: PackingItem, allItems: PackingItem[]): boolean {
|
||||
return (
|
||||
!!item.category &&
|
||||
item.name !== PACKING_PLACEHOLDER_NAME &&
|
||||
!allItems.some(i => i.id !== item.id && i.category === item.category)
|
||||
)
|
||||
}
|
||||
|
||||
export function isPackingPlaceholder(item: Pick<PackingItem, 'name'>): boolean {
|
||||
return item.name === PACKING_PLACEHOLDER_NAME
|
||||
}
|
||||
|
||||
// ── To-do ────────────────────────────────────────────────────────────────
|
||||
|
||||
/** P1/P2/P3 colours (spec 03 §4.7) reuse the shared status-dot tokens so priority and status stay one palette. */
|
||||
export const PRIORITY_COLOR: Record<number, string> = {
|
||||
1: STATUS_COLOR.danger,
|
||||
|
||||
Reference in New Issue
Block a user