Files
superlist/apps/web/src/lib/items.ts
Jose Selesan db7cdd5585 feat(items): edit an item's quantity by swiping or right-clicking it
The PATCH endpoint now accepts quantity alongside completed (at least one
field is required), and the row shows the quantity only when its leading
number is above one. A small dialog edits it, opened by a left swipe on
touch or by right-clicking the row on desktop.
2026-10-20 15:02:41 -03:00

57 lines
1.8 KiB
TypeScript

import type { ListItem } from '@superlist/shared'
import { isSameLocalDay } from './dates'
export type SplitItems = {
/** Items still to buy, in the API's order (by `order`). */
pending: ListItem[]
/** Items bought during the current local day, most recent first. */
boughtToday: ListItem[]
}
/**
* Splits a list's items into the two groups the UI renders: pending items
* and items bought today. Items bought on a previous local day are dropped
* entirely — they stay `completed` in the database but are only shown on
* the day they were bought.
*/
export function splitItems(items: ListItem[], now: Date): SplitItems {
const pending: ListItem[] = []
const boughtToday: ListItem[] = []
for (const item of items) {
if (!item.completed) {
pending.push(item)
continue
}
// A completed item without `boughtAt` is legacy data with no known
// purchase day, so it is not considered bought today.
if (item.boughtAt && isSameLocalDay(new Date(item.boughtAt), now)) {
boughtToday.push(item)
}
}
boughtToday.sort(
(a, b) => new Date(b.boughtAt ?? 0).getTime() - new Date(a.boughtAt ?? 0).getTime(),
)
return { pending, boughtToday }
}
/**
* The quantity to show at the right of an item's name, or `null` when it must
* stay hidden. Only quantities above one earn their place in the row, so a
* plain "1" does not add noise: the leading number of the string is parsed
* ("2" → 2, "2 kg" → 2, "0,5" → 0.5) and anything without one is hidden.
*/
export function quantityLabel(quantity: string | null): string | null {
if (!quantity) return null
const trimmed = quantity.trim()
const leadingNumber = /^(\d+(?:[.,]\d+)?)/.exec(trimmed)
if (!leadingNumber) return null
return Number.parseFloat(leadingNumber[1].replace(',', '.')) > 1 ? trimmed : null
}