Files
TREK/client/src/components/Todo/useTodoList.ts
T
Maurice 0b7cee0b0d feat(mobile): the trip's tabs, administration, collections and the journal use the large screen
On an iPad or an unfolded foldable the list screens kept one phone-wide
column in the middle of the page. They now lay out for the room they have:

- Transports, bookings, polls and tasks put their cards in a grid of as many
  phone-wide columns as the page holds (CardGrid), three on a 13" iPad on
  its side, two upright, one in a narrow Split View.
- Costs: with room for two panes (split size class) the summary (total,
  owe and owed, settle up, final budget, categories) stands in a pane of its
  own beside the expenses, each scrolling on its own (TabPanes). The search
  field sits in the expenses' column again instead of running past it.
- Files: a grid of tiles with each photo's picture; with room for two panes
  the picked file is previewed beside the grid with what it belongs to and
  its actions, the way Files on an iPad does. The signed preview address
  comes through fileRepo.previewUrl.
- Packing: the categories stand in columns, each card whole in its column;
  the action menu drops from its button at a popover's width.
- To-dos: the four smart filters as tiles and the trip's lists in a pane
  beside the tasks, which take the filter's name as their head.
- Collab: the chat stays in view at the trailing edge beside the notes,
  links or polls, and the header switches only the board. The chat keeps its
  place in the tree, so a fold or a rotation into two panes keeps the draft;
  a chat at its newest message stays there when its box changes size. Notes
  stand as a board in columns.
- Administration and settings share a section list beside the page
  (MSectionNav); the stats grid takes four columns.
- Collections: the lists stand in a column beside the places, which take two
  columns, and the head names the list on show.
- Journal: the entries become a feed beside the map, under their days, with
  photo, place and the start of the story, in step with the map like the
  strip of cards it replaces; it fades out under the header.
- The assistant opens as a tall panel at the trailing edge over a dimmed
  page, as Slide Over would, instead of covering the whole screen.
- The rail fits every name: a word too wide for it shrinks the label before
  it is hyphenated, and the admin entry uses its short name.
- The journeys and notifications headers keep to their column.
- The address screen of the native shell sets the photo as a panel beside
  the choices on a large screen on its side.

On a foldable that reports its fold, a leading pane ends at the fold and a
trailing one starts there. Phones keep their layout.
2026-11-07 23:25:12 +01:00

155 lines
6.8 KiB
TypeScript

import { useState, useMemo, useEffect, useRef } from 'react'
import { useTripStore } from '../../store/tripStore'
import { useCanDo } from '../../store/permissionsStore'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import apiClient from '../../api/client'
import { formatDate as fmtDate } from '../../utils/formatters'
import type { TodoItem } from '../../types'
import { localToday } from '../Planner/today'
import {
compareTodoDue, compareTodoPriority, filterTodoItems, filterTodoItemsByCategory, isTodoSmartFilter, sortTodoRows,
todoCategories, todoCategoryOpenCount, todoCounts, type FilterType, type Member, type TodoSmartFilter,
} from './todoListModel'
import { useIsPhone } from '../../mobile/useIsPhone'
/**
* The bucket the list shows: one of the four built-ins, addressed by id, or a
* category, addressed by name, so a category a user called "all" or "done"
* can have its own bucket instead of the built-in one.
*/
export type TodoActiveFilter = { kind: 'smart'; id: TodoSmartFilter } | { kind: 'category'; name: string }
type TodoSort = 'priority' | 'due' | null
export interface TodoViewOptions {
/**
* The phone's row order: done tasks sink to the end and open overdue ones
* float to the top, the sort toggle only breaks ties. The desktop list keeps
* the filtered order and sorts it by the toggle alone.
*/
rankByStatus?: boolean
/**
* Read "today" once when the view mounts, as the phone tab does. The desktop
* list reads it on every render, so its overdue cut-off moves at midnight.
*/
pinToday?: boolean
}
/**
* The to-do view state both views share: the active bucket, the sort toggle,
* "today" and what is derived from them (categories, rows, counts). The
* desktop panel gets it through useTodoList, the phone tab calls it with its
* own options.
*/
export function useTodoView(items: TodoItem[], currentUserId: number | null, options: TodoViewOptions = {}) {
const { rankByStatus = false, pinToday = false } = options
const [active, setActive] = useState<TodoActiveFilter>({ kind: 'smart', id: 'all' })
const [sortBy, setSortBy] = useState<TodoSort>(null)
// due_date is a bare calendar date, so "today" has to be the user's calendar
// day: toISOString() hands over the UTC one and shifts the overdue cut-off.
const [mountDay] = useState(() => localToday())
const today = pinToday ? mountDay : localToday()
const categories = useMemo(() => todoCategories(items), [items])
const rows = useMemo(() => {
const result = active.kind === 'category'
? filterTodoItemsByCategory(items, active.name)
: filterTodoItems(items, active.id, currentUserId, today)
if (rankByStatus) return sortTodoRows(result, sortBy, today)
if (sortBy === 'priority') return [...result].sort(compareTodoPriority)
// Ties keep the manual order, the stable sort leaves them untouched (#2205).
if (sortBy === 'due') return [...result].sort(compareTodoDue)
return result
}, [items, active, currentUserId, today, sortBy, rankByStatus])
const counts = todoCounts(items, currentUserId, today)
// The desktop sidebar addresses every bucket by one string, so a category
// that shares a built-in's id lands on the built-in, as it always has there.
const filter: FilterType = active.kind === 'smart' ? active.id : active.name
const setFilter = (f: FilterType) =>
setActive(isTodoSmartFilter(f) ? { kind: 'smart', id: f } : { kind: 'category', name: f })
// A second press on the active sort goes back to the manual order.
const toggleSort = (key: 'priority' | 'due') => setSortBy(v => (v === key ? null : key))
// Open (non-done) count of a category
const catCount = (cat: string) => todoCategoryOpenCount(items, cat)
return { active, setActive, filter, setFilter, sortBy, toggleSort, today, categories, rows, counts, catCount }
}
/**
* Todo list logic — store actions, member load, the filter/selection/add-new
* view state and the derived buckets (filtered list + counts) + handlers.
* TodoListPanel stays a layout component that renders the sidebar, the rows
* (TodoRow) and the detail/new panes from this state.
*/
export function useTodoList(tripId: number, items: TodoItem[], addItemSignal: number) {
const { addTodoItem, updateTodoItem, deleteTodoItem, toggleTodoItem, reorderTodoItems } = useTripStore()
const trip = useTripStore((s) => s.trip)
const can = useCanDo()
const canEdit = can('packing_edit', trip)
const toast = useToast()
const { t, locale } = useTranslation()
const formatDate = (d: string) => fmtDate(d, locale) || d
const isMobile = useIsPhone()
const [selectedId, setSelectedId] = useState<number | null>(null)
const [isAddingNew, setIsAddingNew] = useState(false)
const lastHandledAddSignal = useRef(addItemSignal)
useEffect(() => {
if (addItemSignal !== lastHandledAddSignal.current && addItemSignal > 0) {
setSelectedId(null)
setIsAddingNew(true)
}
lastHandledAddSignal.current = addItemSignal
}, [addItemSignal])
const [addingCategory, setAddingCategory] = useState(false)
const [newCategoryName, setNewCategoryName] = useState('')
const [members, setMembers] = useState<Member[]>([])
const [currentUserId, setCurrentUserId] = useState<number | null>(null)
useEffect(() => {
apiClient.get(`/trips/${tripId}/members`).then(r => {
const owner = r.data?.owner
const mems = r.data?.members || []
const all = owner ? [owner, ...mems] : mems
setMembers(all)
setCurrentUserId(r.data?.current_user_id || null)
}).catch(() => {})
}, [tripId])
const { filter, setFilter, sortBy, toggleSort, today, categories, rows: filtered, counts, catCount } = useTodoView(items, currentUserId)
const sortByPrio = sortBy === 'priority'
const sortByDue = sortBy === 'due'
const selectedItem = items.find(i => i.id === selectedId) || null
const { total: totalCount, done: doneCount, overdue: overdueCount, my: myCount } = counts
const addCategory = () => {
const name = newCategoryName.trim()
if (!name || categories.includes(name)) { setAddingCategory(false); setNewCategoryName(''); return }
addTodoItem(tripId, { name: t('todo.newItem'), category: name } as any)
.then(() => { setAddingCategory(false); setNewCategoryName(''); setFilter(name) })
.catch(err => toast.error(err instanceof Error ? err.message : t('common.error')))
}
return {
canEdit, t, formatDate, toggleTodoItem, reorderTodoItems,
isMobile, filter, setFilter, selectedId, setSelectedId,
isAddingNew, setIsAddingNew, sortByPrio, sortByDue, toggleSort,
addingCategory, setAddingCategory, newCategoryName, setNewCategoryName,
members, categories, today, filtered, selectedItem,
totalCount, doneCount, overdueCount, myCount,
addCategory, catCount,
// exposed for completeness (DetailPane/NewTaskPane already get their own)
updateTodoItem, deleteTodoItem,
}
}