Files
TREK/client/src/mobile/components/MBottomNav.tsx
T
Maurice 1ad2e92142 fix: make the app keyboard-reachable, and close four DoS-able patterns
The bulk of what SonarQube still had open on the reliability side, read site by
site rather than swept. Two clusters are worth calling out because they are
defects, not lint.

**Four regexes could be made to hang the process.** The worst is
`/.+@.+\..+/` in the forgot-password path: three unbounded `.+` that all
overlap, unanchored, on an endpoint that needs no login and whose schema is a
bare z.string() under a 100kb body cap. A thousand '@' characters had not
finished after 100 seconds — one request pins the event loop, and Node has one.
EMAIL_REGEX in auth.helpers is the same shape on register and profile update
(310ms for 8kb). The two tag strippers over an uploaded KML description and over
Commons metadata took 0.52s on a 16k run of '<'. Each rewrite was proven
equivalent by brute force against the original — millions of strings for the
coordinate patterns, 671,876 for the tag stripper — because a subtly different
regex on a parsing path is worse than the finding.

`<[^>]+>` could not be fixed in the pattern: `[^>]` matches `<` too, so the only
unambiguous form changes what happens to malformed markup. It is now a scan in
common/stripHtmlTags.ts, quirks included — `<>` is left alone, `<a<b>` is one
tag — with the equivalence pinned by a test that compares against the old regex
over every string up to length six.

**And roughly 500 places could only be reached with a mouse.** Clickable divs
became real buttons where the markup allowed (52 of them), took
role + tabIndex + Enter/Space where they had to stay divs, and modal backdrops
took role="presentation" — the honest role, since a backdrop is a mouse shortcut
for a Cancel control that is already in the tab order, and making it a button
plants a nameless full-screen tab stop around its own contents.

Alongside those: `.sort()` calls that now say the order they always had, `{n &&
<X/>}` guards that rendered a literal "0" for a zero-byte file and for a place at
latitude 0, an optimistic budget write that stored a boolean where the contract
and both transports use 0/1, and the Number statics.

sonar-project.properties documents the six that were deliberately left: two wiki
patterns with no overlapping quantifier pair whose "fix" would stop parsing
`[see [1]](url)`, four tar header fields bounded at 12-155 bytes by the format,
two djb2 hashes where the 32-bit wrap is the algorithm, two `| 0` that are also
coercing undefined to 0 on a path where the API sends no user_id, and the MCP
session maps Sonar reads as empty because they are filled from another module.
2026-08-25 19:26:38 +02:00

200 lines
9.8 KiB
TypeScript

import { useEffect, useState } from 'react'
import { useNavigate, useLocation, useMatch } from 'react-router'
import { useSettingsStore } from '../../store/settingsStore'
import { useTranslation } from '../../i18n'
import { ChevronRight, MoreHorizontal, Plus, Search } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { normalizeAppearance } from '@trek/shared'
import { useNavItems, splitMobileNav } from '../../components/Layout/navItems'
import MFab from './MFab'
interface NavItem { to: string; label: string; icon: LucideIcon }
// The centre "+" means something different per context: inside a trip it adds a
// place, on the journey list it starts a journey (deliberate deviation from the
// demo, which reserves the FAB for entries — the list has no journey to add
// into yet), inside a journey it adds an entry, on the atlas it opens the
// country search, on collections it adds a place to the active list —
// everywhere else it creates a new trip. Pages pick the intent up from the
// query params. The result is unused on /vacay: that screen draws its own centre
// FAB, so the dock yields the slot instead (see screenFabSlot below, #1811).
function useCreateAction(): { label: string; run: () => void } {
const navigate = useNavigate()
const { t } = useTranslation()
const inTrip = useMatch('/trips/:id')
const inJourney = useMatch('/journey/:id')
const onJourneyList = useMatch('/journey')
const onAtlas = useMatch('/atlas')
const onCollections = useMatch('/collections')
const inCollection = useMatch('/collections/:id')
if (inTrip) {
// The "+" is context-aware per active tab: Bookings → reservation,
// Transports → transport, Costs → expense. Tabs without a create modal
// (lists / files / collab) fall through to adding a place. #1349
const id = inTrip.params.id
const tripTab = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem(`trip-tab-${id}`) : null
if (tripTab === 'finanzplan') return { label: t('costs.addExpense'), run: () => navigate(`/trips/${id}?create=expense`) }
if (tripTab === 'buchungen') return { label: t('reservations.addManual'), run: () => navigate(`/trips/${id}?create=reservation`) }
if (tripTab === 'transports') return { label: t('transport.addManual'), run: () => navigate(`/trips/${id}?create=transport`) }
return { label: t('places.addPlace'), run: () => navigate(`/trips/${id}?create=place`) }
}
if (inJourney) {
return { label: t('journey.detail.addEntry'), run: () => navigate(`/journey/${inJourney.params.id}?create=entry`) }
}
if (onJourneyList) {
return { label: t('journey.new'), run: () => navigate('/journey?create=1') }
}
if (onAtlas) {
return { label: t('atlas.searchCountry'), run: () => navigate('/atlas?search=1') }
}
if (onCollections || inCollection) {
// Picking a list moves the route to /collections/:id, so the exact match
// alone dropped the "+" through to creating a trip — the one state the
// screen is normally used in (#1930). The handoff keeps the id, otherwise
// adding would land on "All saved" and the sheet would ask for the list the
// user is already looking at.
const path = inCollection ? `/collections/${inCollection.params.id}` : '/collections'
return { label: t('collections.addPlace'), run: () => navigate(`${path}?create=place`) }
}
return { label: t('dashboard.newTrip'), run: () => navigate('/dashboard?create=1') }
}
/**
* Floating glass dock of the mobile shell. Same tab/gating/"+" logic as the
* legacy BottomNav (addons, ?create= contract), redesigned as the demo's icon
* dock: 42px circles, active on the --m-act pill, Journey/Collections and page
* plugins behind the "More" popover, and a context FAB in the middle (search
* on the atlas, disabled logo slot on settings/admin).
*/
export default function MBottomNav() {
const { t } = useTranslation()
const navigate = useNavigate()
const location = useLocation()
const create = useCreateAction()
const [moreOpen, setMoreOpen] = useState(false)
// Close the popover when the route changes underneath it (browser back etc.).
useEffect(() => setMoreOpen(false), [location.pathname])
// The dock split + order is user-configurable (Settings → Appearance → Mobile);
// an un-customised account falls back to the built-in Dashboard + vacay/atlas
// dock with everything else under "More".
const navItems = useNavItems()
const appearance = useSettingsStore(s => s.settings.appearance)
const split = splitMobileNav(navItems, normalizeAppearance(appearance).mobileNav)
const dockItems: NavItem[] = split.bar
const moreItems: NavItem[] = split.more
const isActive = (to: string) =>
to === '/dashboard' ? location.pathname === '/dashboard' : location.pathname.startsWith(to)
const moreActive = moreItems.some(item => isActive(item.to))
// The FAB gives way to a decorative logo slot on screens without an add
// action (settings/admin, demo Z. 1372/1429).
const logoSlot = location.pathname.startsWith('/settings') || location.pathname.startsWith('/admin')
const searchFab = location.pathname.startsWith('/atlas')
// /vacay owns the centre slot itself: MVacay draws its year/edit toggle into
// exactly this 56px circle. The dock keeps the geometry but stays empty there,
// so the generic "+" can never sit underneath as a second, different action:
// not while the lazy screen chunk loads, and not while its data loads (#1811).
const screenFabSlot = location.pathname.startsWith('/vacay')
// Split so the raised centre slot sits dead centre; the More slot always
// closes the right group.
const slotCount = dockItems.length + (moreItems.length > 0 ? 1 : 0)
const splitAt = Math.ceil(slotCount / 2)
const left = dockItems.slice(0, splitAt)
const right = dockItems.slice(splitAt)
const circleCls = (active: boolean) =>
`flex h-[42px] w-[42px] flex-none items-center justify-center rounded-full ${
active ? 'bg-m-act text-m-actfg' : 'text-m-muted'
}`
const renderItem = ({ to, label, icon: Icon }: NavItem) => {
const active = isActive(to)
// Fixed sizes per slot (demo): the dashboard grid is 18/2.1, every other
// slot 21/1.9 — independent of the active state.
const dash = to === '/dashboard'
return (
<button
key={to}
type="button"
onClick={() => navigate(to)}
aria-label={label}
aria-current={active ? 'page' : undefined}
className={circleCls(active)}
>
<Icon size={dash ? 18 : 21} strokeWidth={dash ? 2.1 : 1.9} />
</button>
)
}
return (
<>
{moreOpen && (
// Invisible scrim (the popover sits on the UI without dimming it).
<div className="fixed inset-0 z-[60]" role="presentation" onClick={() => setMoreOpen(false)}>
<div
className="absolute left-4 right-4 flex flex-col gap-2 rounded-[26px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] p-[10px] shadow-[0_-8px_40px_-14px_rgba(0,0,0,.45)] backdrop-blur-[30px] backdrop-saturate-[1.8] bottom-[calc(env(safe-area-inset-bottom,0px)+86px)]"
role="presentation"
onClick={e => e.stopPropagation()}
>
{moreItems.map(({ to, label, icon: Icon }) => (
<button
key={to}
type="button"
onClick={() => { setMoreOpen(false); navigate(to) }}
className="flex items-center gap-[13px] rounded-[18px] bg-[color:var(--m-ic)] px-4 py-[14px] text-left"
>
<span className="flex h-10 w-10 flex-none items-center justify-center rounded-xl bg-[color:var(--m-ic)] text-m-ink">
<Icon size={20} strokeWidth={2} />
</span>
<span className="block min-w-0 flex-1 truncate text-[0.9375rem] font-extrabold text-m-ink">{label}</span>
<ChevronRight size={17} strokeWidth={2} className="flex-none text-m-faint" />
</button>
))}
</div>
</div>
)}
<nav className="fixed left-4 right-4 z-40 flex h-[62px] items-center rounded-[31px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-3 shadow-[0_16px_44px_-14px_rgba(0,0,0,.35)] backdrop-blur-[30px] backdrop-saturate-[1.8] bottom-[calc(env(safe-area-inset-bottom,0px)+12px)]">
<div className="flex min-w-0 flex-1 items-center justify-around">{left.map(renderItem)}</div>
{logoSlot ? (
<span aria-hidden="true" className="mx-2 flex h-14 w-14 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] opacity-70">
<img src="/icons/icon-dark.svg" alt="" className="block h-6 w-6 opacity-75 dark:hidden" />
<img src="/icons/icon-white.svg" alt="" className="hidden h-6 w-6 opacity-75 dark:block" />
</span>
) : screenFabSlot ? (
// Same box as MFab (56px, flex-none, mx-2) so both tab groups keep
// sitting symmetrically around the centre in every dock configuration.
<span aria-hidden="true" className="mx-2 h-14 w-14 flex-none" />
) : (
<MFab onClick={create.run} ariaLabel={create.label} className="mx-2">
{searchFab ? <Search size={24} strokeWidth={2.4} /> : <Plus size={26} strokeWidth={2.4} />}
</MFab>
)}
<div className="flex min-w-0 flex-1 items-center justify-around">
{right.map(renderItem)}
{moreItems.length > 0 && (
<button
type="button"
onClick={() => setMoreOpen(v => !v)}
aria-label={t('mobileNav.more')}
aria-expanded={moreOpen}
aria-current={moreActive ? 'page' : undefined}
className={circleCls(moreActive)}
>
<MoreHorizontal size={21} strokeWidth={1.9} />
</button>
)}
</div>
</nav>
</>
)
}