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.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
import { useEffect, useRef, useState, type ChangeEvent, type ClipboardEvent } from 'react'
import { Link, Loader2, MoreVertical, Star, Wallet } from 'lucide-react'
import MDancingTrek from '../../../components/MDancingTrek'
import { useTranslation, translateApiError } from '../../../../i18n'
import { fileRepo } from '../../../../repo/fileRepo'
import { openFile } from '../../../../utils/fileDownload'
import { isMedia, isWalletPass, formatSize } from '../../../../components/Files/FileManager.helpers'
import type { TripFile } from '../../../../types'
import { TabScroller } from './tabChrome'
import type { MTabScreenProps } from './tabModel'
import MFileMenuSheet from './MFileMenuSheet'
import MFileLinkSheet from './MFileLinkSheet'
import MFileTrashSheet from './MFileTrashSheet'
import MDocSyncSheet from './MDocSyncSheet'
import { canManageDocSync } from '../../../../components/Files/docsync/useDocSync'
import { filesFromClipboard } from '../../../../components/Files/fileActions'
import { useAuthStore } from '../../../../store/authStore'
import MFileLightbox from './MFileLightbox'
import { FilePreviewPane, FileTile } from './MFilesBoard'
import { useIsSplit, useIsWide } from '../../../../hooks/sizeClass'
import {
FILE_FILTERS, buildFileLinkLabels, formatFileDate, getFileTypeMeta,
matchesFileFilter, sortFilesStarredFirst, type FileFilterId,
} from './filesModel'
/**
* Tab 5 — Dateien. Real `planner.files` (already non-deleted, §7.2), the
* filter grid + starred-first sort from filesModel.ts, and a row per file
* (spec 03 §5.2). Upload and Trash are triggered from the shell's header
* (shell.uploadFilesSignal / shell.openFilesTrashSignal, watched below, same
* pattern as useTodoList.ts's addItemSignal) since those buttons live outside
* this panel. Star/rename-note/link run through fileRepo, so offline they
* wait in the queue; add/delete run through planner.tripActions (§7.3).
*/
export default function MFilesTab({ planner, shell }: MTabScreenProps) {
const { t } = planner
const files = planner.files || []
const [filter, setFilter] = useState<FileFilterId>('all')
const [menuFileId, setMenuFileId] = useState<number | null>(null)
const [linkFileId, setLinkFileId] = useState<number | null>(null)
const currentUser = useAuthStore(st => st.user)
const maxUploadMb = useAuthStore(st => st.maxUploadMb)
const [trashOpen, setTrashOpen] = useState(false)
const [docSyncOpen, setDocSyncOpen] = useState(false)
const [lightboxIndex, setLightboxIndex] = useState<number | null>(null)
const [uploading, setUploading] = useState(false)
// Wide: the files as a grid of tiles. Split: the picked one previewed beside
// the grid (MFilesBoard), so a tap picks a file there instead of opening it.
const wide = useIsWide()
const split = useIsSplit()
const [pickedId, setPickedId] = useState<number | null>(null)
const menuFile = menuFileId != null ? files.find(f => f.id === menuFileId) ?? null : null
const linkFile = linkFileId != null ? files.find(f => f.id === linkFileId) ?? null : null
// ── Upload: the shell's header "Upload" button only increments a signal —
// this panel owns the actual file picker + upload call. ──
const inputRef = useRef<HTMLInputElement>(null)
const lastUploadSignal = useRef(shell.uploadFilesSignal)
useEffect(() => {
if (shell.uploadFilesSignal !== lastUploadSignal.current && shell.uploadFilesSignal > 0) {
inputRef.current?.click()
}
lastUploadSignal.current = shell.uploadFilesSignal
}, [shell.uploadFilesSignal])
const uploadFiles = async (list: File[]) => {
const maxBytes = maxUploadMb * 1024 * 1024
const tooBig = list.filter(f => f.size > maxBytes)
const okFiles = list.filter(f => f.size <= maxBytes)
if (tooBig.length > 0) planner.toast.error(t('files.uploadErrorSize', { max: maxUploadMb }))
if (okFiles.length === 0) return
setUploading(true)
let uploaded = 0
const failures: unknown[] = []
for (const file of okFiles) {
const fd = new FormData()
fd.append('file', file)
try {
await planner.tripActions.addFile(planner.tripId, fd)
uploaded++
} catch (err) {
// One rejected file must not drop the rest of the batch.
failures.push(err)
}
}
setUploading(false)
if (uploaded > 0) planner.toast.success(t('files.uploaded', { count: uploaded }))
if (failures.length > 0) planner.toast.error(translateApiError(t, failures[0], 'files.uploadError'))
}
const onPickFiles = (e: ChangeEvent<HTMLInputElement>) => {
const list = Array.from(e.target.files || [])
e.target.value = ''
if (list.length > 0) void uploadFiles(list)
}
const onPaste = (e: ClipboardEvent<HTMLDivElement>) => {
if (!planner.canUploadFiles) return
const pasted = filesFromClipboard(e.clipboardData)
if (pasted.length > 0) {
e.preventDefault()
void uploadFiles(pasted)
}
}
// ── Trash: same signal pattern as upload. ──
const lastTrashSignal = useRef(shell.openFilesTrashSignal)
useEffect(() => {
if (shell.openFilesTrashSignal !== lastTrashSignal.current && shell.openFilesTrashSignal > 0) {
setTrashOpen(true)
}
lastTrashSignal.current = shell.openFilesTrashSignal
}, [shell.openFilesTrashSignal])
// ── Document sync: same signal pattern again. ──
const lastDocSyncSignal = useRef(shell.openDocSyncSignal)
useEffect(() => {
if (shell.openDocSyncSignal !== lastDocSyncSignal.current && shell.openDocSyncSignal > 0) {
setDocSyncOpen(true)
}
lastDocSyncSignal.current = shell.openDocSyncSignal
}, [shell.openDocSyncSignal])
// ── Star toggle (ungated, §7.6): through fileRepo, then a store refresh. ──
const toggleStar = async (file: TripFile) => {
try {
await fileRepo.toggleStar(planner.tripId, file.id)
planner.tripActions.loadFiles(planner.tripId)
} catch {
planner.toast.error(t('files.toast.starError'))
}
}
const sorted = sortFilesStarredFirst(files)
const visible = sorted.filter(f => matchesFileFilter(f, filter))
const mediaFiles = visible.filter(f => isMedia(f.mime_type))
const openRow = (file: TripFile) => {
if (isMedia(file.mime_type)) {
// Only rows out of `visible` get here, so the file is always in mediaFiles.
setLightboxIndex(mediaFiles.findIndex(f => f.id === file.id))
} else {
// Wallet passes and everything else (PDF/docs) share the same browser-native
// handling as the transport/reservation file chips: openFile() opens PDFs
// inline (SAFE_INLINE_TYPES) and forces a download for anything unsafe
// (incl. .pkpass, so it reaches Apple Wallet, #1447).
openFile(file.url, file.original_name).catch(() => planner.toast.error(t('files.openError')))
}
}
const picked = split ? (visible.find(f => f.id === pickedId) ?? visible[0] ?? null) : null
const visibleFilters = FILE_FILTERS.filter(f => f.id !== 'collab' || files.some(x => x.note_id != null))
const isEmpty = files.length === 0
const body = (
<div onPaste={onPaste} tabIndex={-1} className="flex min-h-full flex-col">
<input ref={inputRef} type="file" multiple className="hidden" onChange={onPickFiles} />
{uploading && (
<div className="mb-2 flex items-center justify-center gap-2 rounded-full bg-[color:var(--m-ic)] px-3 py-[6px] font-geist text-[0.6875rem] font-bold text-m-muted">
<Loader2 size={13} className="animate-spin" />
{t('files.uploading')}
</div>
)}
{isEmpty ? (
<div className="flex flex-1 flex-col items-center justify-center px-8 py-10 text-center">
<MDancingTrek scene="files" className="mb-2" />
<p className="font-geist text-[0.8125rem] font-medium text-m-muted">{t('mobileTrip.filesEmpty')}</p>
</div>
) : (
<>
<div className="grid gap-[6px]" style={{ gridTemplateColumns: `repeat(${visibleFilters.length}, 1fr)` }}>
{visibleFilters.map(f => {
const Icon = f.icon
const active = filter === f.id
const count = files.filter(x => matchesFileFilter(x, f.id)).length
return (
<button
key={f.id}
type="button"
onClick={() => setFilter(f.id)}
className={`rounded-[14px] border px-[2px] pb-[9px] pt-[11px] text-center ${
active
? 'border-[color:var(--m-act)] bg-m-act text-m-actfg'
: 'border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-ink'
}`}
>
<Icon size={15} strokeWidth={2} className="mx-auto" />
<div className="mt-1 truncate font-geist text-[0.5625rem] font-bold">{t(f.labelKey)}</div>
<div className="mt-px font-geist text-[0.5625rem] font-bold opacity-55">{count}</div>
</button>
)
})}
</div>
{visible.length === 0 ? (
<div className="pt-14 text-center font-geist text-[0.8125rem] text-m-faint">{t('mobileTrip.filesEmpty')}</div>
) : wide ? (
<div className="mt-3 grid grid-cols-[repeat(auto-fill,minmax(156px,1fr))] gap-3">
{visible.map(file => (
<FileTile
key={file.id}
file={file}
selected={split ? picked?.id === file.id : undefined}
canStar={planner.can('file_edit', planner.trip)}
onPick={() => (split ? setPickedId(file.id) : openRow(file))}
onStar={() => void toggleStar(file)}
onMenu={() => setMenuFileId(file.id)}
t={t}
/>
))}
</div>
) : (
<div className="flex flex-col">
{visible.map(file => (
<FileRow
key={file.id}
file={file}
planner={planner}
onOpen={() => openRow(file)}
onStar={() => void toggleStar(file)}
onMenu={() => setMenuFileId(file.id)}
/>
))}
</div>
)}
</>
)}
</div>
)
const sheets = (
<>
<MFileMenuSheet
planner={planner}
file={menuFile}
onClose={() => setMenuFileId(null)}
onOpenLinks={f => { setMenuFileId(null); setLinkFileId(f.id) }}
/>
<MFileLinkSheet planner={planner} file={linkFile} onClose={() => setLinkFileId(null)} />
<MFileTrashSheet planner={planner} open={trashOpen} onClose={() => setTrashOpen(false)} />
<MDocSyncSheet
tripId={planner.tripId}
tripTitle={planner.trip?.title}
canManage={canManageDocSync(currentUser, planner.trip)}
open={docSyncOpen}
onClose={() => setDocSyncOpen(false)}
/>
{lightboxIndex != null && mediaFiles.length > 0 && (
<MFileLightbox
files={mediaFiles}
index={Math.min(lightboxIndex, mediaFiles.length - 1)}
onIndexChange={setLightboxIndex}
onClose={() => setLightboxIndex(null)}
t={t}
/>
)}
</>
)
if (split && picked) {
return (
<div className="flex h-full">
<div className="min-h-0 min-w-0 flex-1 overflow-y-auto overflow-x-hidden pb-[calc(var(--bottom-nav-h,84px)+22px)] pe-3 ps-6 pt-[calc(var(--m-safe-top,12px)+58px)]">
{body}
</div>
<aside
aria-label={t('common.preview')}
className="m-pane-trail min-h-0 flex-none overflow-y-auto overflow-x-hidden border-s border-[color:var(--m-rowbr)] px-5 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)]"
>
<FilePreviewPane
file={picked}
planner={planner}
onOpen={() => openRow(picked)}
onStar={() => void toggleStar(picked)}
onLinks={() => setLinkFileId(picked.id)}
onMenu={() => setMenuFileId(picked.id)}
/>
</aside>
{sheets}
</div>
)
}
return (
<TabScroller wide={wide ? 'full' : 'readable'}>
{body}
{sheets}
</TabScroller>
)
}
/** The product's name, the same in every language. */
const APPLE_WALLET = 'Apple Wallet'
function FileRow({ file, planner, onOpen, onStar, onMenu }: {
file: TripFile
planner: MTabScreenProps['planner']
onOpen: () => void
onStar: () => void
onMenu: () => void
}) {
const { t } = planner
const { locale } = useTranslation()
const meta = getFileTypeMeta(file)
const TypeIcon = meta.icon
const linkLabels = buildFileLinkLabels(file, planner.places, planner.reservations, planner.TRANSPORT_TYPES, t)
const starred = !!file.starred
return (
<div className="mt-2 flex items-center gap-[11px] rounded-2xl border border-[color:var(--m-rowbr)] bg-m-sheetop px-[11px] py-[10px]">
<button type="button" onClick={onOpen} className="flex min-w-0 flex-1 items-center gap-[11px] text-start">
<div
className="flex h-[42px] w-[42px] flex-none flex-col items-center justify-center gap-[2px] rounded-[13px]"
style={{ background: `${meta.color}22`, color: meta.color }}
>
<TypeIcon size={15} strokeWidth={2} />
<span className="font-geist text-[0.4375rem] font-extrabold tracking-[.04em]">{meta.label}</span>
</div>
<div className="min-w-0 flex-1">
<div dir="auto" className="truncate text-[0.8125rem] font-bold text-m-ink">{file.original_name}</div>
<div className="mt-1 flex flex-wrap items-center gap-1">
{isWalletPass(file.mime_type, file.original_name) && (
// A tap hands the pass to Apple Wallet (native/wallet.ts), or downloads it into Wallet on the web.
<span className="flex items-center gap-[3px] whitespace-nowrap rounded-full bg-m-act px-[7px] py-[2px] font-geist text-[length:calc(8.5px*var(--fs-scale-caption,1))] font-bold text-m-actfg">
<Wallet size={9} strokeWidth={2.4} aria-hidden="true" />
{APPLE_WALLET}
</span>
)}
{!!file.file_size && (
<span dir="ltr" className="whitespace-nowrap rounded-full bg-[color:var(--m-ic)] px-[7px] py-[2px] font-geist text-[0.53125rem] font-bold text-m-muted">
{formatSize(file.file_size)}
</span>
)}
<span className="whitespace-nowrap rounded-full bg-[color:var(--m-ic)] px-[7px] py-[2px] font-geist text-[0.53125rem] font-bold text-m-muted">
{formatFileDate(file.created_at, locale)}
</span>
{file.uploaded_by_name && (
<span className="flex items-center gap-[3px] rounded-full bg-[color:var(--m-ic)] py-[2px] ps-[3px] pe-[7px]">
<span className="flex h-3 w-3 flex-none items-center justify-center rounded-full bg-m-act font-geist text-[0.40625rem] font-extrabold text-m-actfg">
{file.uploaded_by_name[0]?.toUpperCase()}
</span>
<span dir="auto" className="max-w-[92px] truncate font-geist text-[0.53125rem] font-bold text-m-muted">{file.uploaded_by_name}</span>
</span>
)}
</div>
{linkLabels.length > 0 && (
// One badge per link, the kind beside the name, so two links never run
// together; the last one that does not fit ends in an ellipsis.
<div className="mt-1 flex items-center gap-1 overflow-hidden text-m-faint">
<Link size={9} strokeWidth={2.4} className="flex-none" />
{linkLabels.map((label, i) => (
<span key={i} className="flex min-w-0 flex-none items-center gap-[3px] rounded-full bg-[color:var(--m-ic)] px-[6px] py-px font-geist text-[0.5625rem] font-bold last:flex-initial">
<span className="flex-none uppercase tracking-[.06em]">{label.kind}</span>
{label.name && <span className="min-w-0 truncate text-m-muted">{label.name}</span>}
</span>
))}
</div>
)}
</div>
</button>
{planner.can('file_edit', planner.trip) && <button
type="button"
onClick={e => { e.stopPropagation(); onStar() }}
aria-label={starred ? t('files.unstar') : t('files.star')}
className={`flex h-7 w-7 flex-none items-center justify-center rounded-full ${
starred ? 'bg-m-act text-m-actfg' : 'bg-[color:var(--m-ic)] text-m-muted'
}`}
>
<Star size={13} strokeWidth={2.4} fill={starred ? 'currentColor' : 'none'} />
</button>}
<button
type="button"
onClick={e => { e.stopPropagation(); onMenu() }}
aria-label={t('files.menu')}
className="flex h-7 w-7 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-muted"
>
<MoreVertical size={14} strokeWidth={2} />
</button>
</div>
)
}