Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

7.2 KB
Raw Blame
import { useEffect, useRef, useState } from 'react'
import { Bookmark, Calendar, ChevronDown, ChevronUp, Eye, Pencil, Trash2, MapPin } from 'lucide-react'
import MSheet from '../../../components/MSheet'
import type { MTripSheetsProps } from '../MTripShell'
import { useTranslation } from '../../../../i18n'
import { useAddonStore } from '../../../../store/addonStore'
import { useSaveToCollectionStore } from '../../../../store/saveToCollectionStore'
import { placeToSaveTarget } from '../../../../components/Collections/saveTarget'
import { useTourDayAssignment } from '../../../../components/Tours/useTourDayAssignment'
import { stageKeysOfTour } from '../../../../components/Tours/stages/stageSpread'
import type { Place } from '../../../../types'
import { TileHeader } from './MTripSheetUi'

interface BrowseActionsPayload {
  placeId?: number
  /** True opens the sheet with the day list already expanded (quick-add "+"). */
  dayPicker?: boolean
}

/**
 * Places-pool context menu ('bract', payload { placeId, dayPicker? }): view
 * details, edit, save to collection, assign to a day (full day list) and delete.
 */
export default function MBrowseActionsSheet({ planner, shell }: MTripSheetsProps) {
  const { t, locale } = useTranslation()
  const open = shell.sheet?.id === 'bract'
  const payload = (shell.sheet?.payload ?? {}) as BrowseActionsPayload
  const livePlace = planner.places.find(p => p.id === payload.placeId) ?? null

  const canEditPlaces = planner.can('place_edit', planner.trip)
  const canEditDays = planner.can('day_edit', planner.trip)
  const isTourPlace = (placeId: number) => planner.isTourPlace(placeId)
  const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
  const openSavePicker = useSaveToCollectionStore(s => s.open)

  const [daysOpen, setDaysOpen] = useState(false)
  // A tour goes onto a day by the rules every tour list shares (PR1-18); a place keeps its own way.
  const dayAssignment = useTourDayAssignment({ canAssign: canEditDays, onAssignToDay: planner.handleAssignToDay })
  useEffect(() => { setDaysOpen(open && Boolean(payload.dayPicker)) }, [open, payload.dayPicker])

  // Hold the last place so the card content survives the exit animation.
  const heldRef = useRef<Place | null>(null)
  if (livePlace) heldRef.current = livePlace
  const place = livePlace ?? heldRef.current

  if (!place) {
    return <MSheet open={false} onClose={shell.closeSheet} variant="card" material="glass" />
  }

  const viewDetails = () => {
    shell.closeSheet()
    planner.handlePlaceClick(place.id)
  }

  const editPlace = () => {
    shell.closeSheet()
    planner.openPlaceEditor(place)
  }

  const saveToCollection = () => {
    shell.closeSheet()
    openSavePicker(placeToSaveTarget(place))
  }

  // A multi-day tour can still go from a day that holds it, as stages (MDT-02); the plan asks which way.
  const staged = stageKeysOfTour(planner.tours.find(tour => tour.place_id === place.id)).length > 1
  const tourUnavailableOnDay = (dayId: number) =>
    isTourPlace(place.id) && !dayAssignment.isAvailable(place.id, dayId, staged ? 'stages' : 'whole')

  const assignToDay = async (dayId: number) => {
    const assigned = isTourPlace(place.id)
      ? await dayAssignment.assign(place.id, dayId, staged ? 'ask' : undefined)
      : await planner.handleAssignToDay(place.id, dayId)
    if (assigned !== false) shell.closeSheet()
  }

  const deletePlace = () => {
    shell.closeSheet()
    planner.handleDeletePlace(place.id)
  }

  const rowCls = 'flex w-full items-center gap-3 px-2 py-[11px] text-start text-[0.84375rem] font-medium'

  return (
    <MSheet open={open && !!livePlace} onClose={shell.closeSheet} variant="card" material="glass" ariaLabel={place.name}>
      <div className="flex-none px-[18px] pt-4">
        <TileHeader
          icon={<MapPin size={19} strokeWidth={1.8} />}
          title={place.name}
          sub={place.address || place.description || undefined}
          onClose={shell.closeSheet}
          closeLabel={t('common.close')}
        />
      </div>

      <div className="m-scroll-fade mt-2 min-h-0 flex-1 overflow-y-auto px-[10px] pb-3 pt-[10px]">
        <button type="button" onClick={viewDetails} className={rowCls}>
          <Eye size={16} strokeWidth={2} className="flex-none text-m-muted" />
          {t('mobileTrip.viewDetails')}
        </button>
        {canEditPlaces && !isTourPlace(place.id) && (
          <button type="button" onClick={editPlace} className={rowCls}>
            <Pencil size={16} strokeWidth={2} className="flex-none text-m-muted" />
            {t('common.edit')}
          </button>
        )}
        {collectionsEnabled && !isTourPlace(place.id) && (
          <button type="button" onClick={saveToCollection} className={rowCls}>
            <Bookmark size={16} strokeWidth={2} className="flex-none text-m-muted" />
            {t('inspector.saveToCollection')}
          </button>
        )}
        {canEditDays && planner.days.length > 0 && (
          <>
            <button type="button" onClick={() => setDaysOpen(v => !v)} aria-expanded={daysOpen} className={rowCls}>
              <Calendar size={16} strokeWidth={2} className="flex-none text-m-muted" />
              <span className="flex-1">{t('mobileTrip.addToDayQuestion')}</span>
              {daysOpen
                ? <ChevronUp size={14} strokeWidth={2} className="flex-none text-m-faint" />
                : <ChevronDown size={14} strokeWidth={2} className="flex-none text-m-faint" />}
            </button>
            {daysOpen && (
              <div className="mx-2 mb-1 max-h-[200px] overflow-y-auto rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)]">
                {planner.days.map((d, i) => (
                  <button
                    key={d.id}
                    type="button"
                    disabled={tourUnavailableOnDay(d.id)}
                    onClick={() => { void assignToDay(d.id) }}
                    className={`flex w-full items-center gap-2 px-3 py-[10px] text-start disabled:cursor-default disabled:opacity-40 ${i > 0 ? 'border-t border-[color:var(--m-rowbr)]' : ''}`}
                  >
                    <span className="min-w-0 flex-1 truncate text-[0.78125rem] font-semibold">
                      {/* A day_number of 0 is as unusable as a missing one — both take the row position. */}
                      {d.title || t('planner.dayN', { n: d.day_number || i + 1 })}
                    </span>
                    {d.date && (
                      <span className="flex-none font-geist text-[0.65625rem] font-medium text-m-muted">
                        {new Date(`${d.date.slice(0, 10)}T00:00:00Z`).toLocaleDateString(locale, {
                          weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC',
                        })}
                      </span>
                    )}
                  </button>
                ))}
              </div>
            )}
          </>
        )}
        {canEditPlaces && !isTourPlace(place.id) && (
          <button type="button" onClick={deletePlace} className={`${rowCls} text-[color:var(--m-st-danger)]`}>
            <Trash2 size={16} strokeWidth={2} className="flex-none" />
            {t('common.delete')}
          </button>
        )}
      </div>
    </MSheet>
  )
}