Files
TREK/client/src/components/Packing/PackingShareControl.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

133 lines
8.1 KiB
TypeScript

import { useState, useRef } from 'react'
import { createPortal } from 'react-dom'
import { Users, UserRound, Share2, Check, Copy, HandHelping } from 'lucide-react'
import { useTranslation } from '../../i18n'
import type { PackingItem } from '../../types'
import type { TripMember } from './usePackingListPanel'
interface Props {
item: PackingItem
tripMembers: TripMember[]
currentUserId?: number
onSetSharing: (id: number, visibility: 'common' | 'personal' | 'shared', recipientIds: number[]) => void
onClone: (id: number) => void
onJoin: (id: number) => void
onLeave: (id: number, userId: number) => void
}
/**
* Per-item sharing control for the three-tier packing model (#858). The owner
* (bringer) sets the tier — Common / Personal / Shared with specific people — via
* a dropdown; everyone else can pledge to co-bring a Common item ("I can bring
* that too") or clone it onto their own list.
*/
export default function PackingShareControl({ item, tripMembers, currentUserId, onSetSharing, onClone, onJoin, onLeave }: Props) {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
const [pos, setPos] = useState<{ top: number; right: number } | null>(null)
const btnRef = useRef<HTMLButtonElement>(null)
// The dropdown is portaled to <body> and fixed-positioned from the button so it
// can't be clipped by the packing panel's overflow.
const toggle = () => {
if (open) { setOpen(false); return }
const r = btnRef.current?.getBoundingClientRect()
if (r) setPos({ top: r.bottom + 4, right: window.innerWidth - r.right })
setOpen(true)
}
const isCommon = !item.is_private
const isOwner = item.owner_id == null || item.owner_id === currentUserId
const recipientIds = (item.recipients || []).map(r => r.user_id)
const visibility: 'common' | 'personal' | 'shared' = isCommon ? 'common' : recipientIds.length > 0 ? 'shared' : 'personal'
const iAmContributor = (item.contributors || []).some(c => c.user_id === currentUserId)
const others = tripMembers.filter(m => m.id !== item.owner_id && m.id !== currentUserId)
const toggleRecipient = (uid: number) => {
const next = recipientIds.includes(uid) ? recipientIds.filter(x => x !== uid) : [...recipientIds, uid]
onSetSharing(item.id, 'shared', next)
}
const btn = (onClick: () => void, title: string, active: boolean, node: React.ReactNode) => (
<button type="button" onClick={onClick} title={title}
style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '3px 4px', borderRadius: 6, display: 'flex', color: active ? 'var(--accent)' : 'var(--text-faint)' }}
onMouseEnter={e => { if (!active) e.currentTarget.style.color = 'var(--text-secondary)' }}
onMouseLeave={e => { if (!active) e.currentTarget.style.color = 'var(--text-faint)' }}>
{node}
</button>
)
// Non-owner on a Common item: pledge to co-bring + clone to personal list.
if (!isOwner && isCommon) {
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 2 }}>
{btn(() => (iAmContributor ? onLeave(item.id, currentUserId!) : onJoin(item.id)),
iAmContributor ? t('packing.alsoBringingStop') : t('packing.alsoBring'), iAmContributor, <HandHelping size={14} />)}
{btn(() => onClone(item.id), t('packing.cloneToMine'), false, <Copy size={13} />)}
</div>
)
}
// A recipient of a shared item has no controls (it's the owner's responsibility).
if (!isOwner) return null
return (
<div style={{ display: 'flex' }}>
<button type="button" ref={btnRef} onClick={toggle} title={t('packing.share')}
style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '3px 4px', borderRadius: 6, display: 'flex', color: visibility !== 'common' ? 'var(--accent)' : 'var(--text-faint)' }}
onMouseEnter={e => { if (visibility === 'common') e.currentTarget.style.color = 'var(--text-secondary)' }}
onMouseLeave={e => { if (visibility === 'common') e.currentTarget.style.color = 'var(--text-faint)' }}>
<Share2 size={14} />
</button>
{open && pos && createPortal(
<>
<div role="presentation" style={{ position: 'fixed', inset: 0, zIndex: 1099 }} onClick={() => setOpen(false)} />
<div style={{
position: 'fixed', top: pos.top, right: pos.right, zIndex: 1100,
background: 'var(--bg-card)', border: '1px solid var(--border-primary)', borderRadius: 10,
boxShadow: '0 8px 28px rgba(0,0,0,0.18)', padding: 4, minWidth: 200, maxHeight: '60vh', overflowY: 'auto',
}}>
<Row icon={<Users size={13} />} label={t('packing.viewCommon')} sub={t('packing.tierCommonHint')} active={visibility === 'common'} onClick={() => { onSetSharing(item.id, 'common', []); setOpen(false) }} />
<Row icon={<UserRound size={13} />} label={t('packing.tierPersonal')} sub={t('packing.tierPersonalHint')} active={visibility === 'personal'} onClick={() => { onSetSharing(item.id, 'personal', []); setOpen(false) }} />
<div style={{ height: 1, background: 'var(--bg-tertiary)', margin: '4px 0' }} />
<div style={{ padding: '4px 10px 2px', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 700, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.04em', display: 'flex', alignItems: 'center', gap: 5 }}>
<Share2 size={10} /> {t('packing.tierShared')}
</div>
{others.length === 0 ? (
<div style={{ padding: '4px 10px 6px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)' }}>{t('packing.noOneToShare')}</div>
) : others.map(m => {
const on = recipientIds.includes(m.id)
return (
<button type="button" key={m.id} onClick={() => toggleRecipient(m.id)}
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', padding: '6px 10px', borderRadius: 7, border: 'none', cursor: 'pointer', background: 'none', fontFamily: 'inherit', fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'var(--text-primary)' }}
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-tertiary)'}
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
<span style={{ width: 18, height: 18, borderRadius: '50%', flexShrink: 0, background: `hsl(${(m.username.codePointAt(0) ?? 0) * 37 % 360}, 55%, 55%)`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 'calc(9px * var(--fs-scale-caption, 1))', fontWeight: 700, color: 'white', textTransform: 'uppercase' }}>{m.username[0]}</span>
<span style={{ flex: 1, textAlign: 'left', overflow: 'hidden', textOverflow: 'ellipsis' }}>{m.username}</span>
{on && <Check size={13} className="text-content-muted" />}
</button>
)
})}
</div>
</>,
document.body,
)}
</div>
)
}
function Row({ icon, label, sub, active, onClick }: { icon: React.ReactNode; label: string; sub: string; active: boolean; onClick: () => void }) {
return (
<button type="button" onClick={onClick}
style={{ display: 'flex', alignItems: 'flex-start', gap: 8, width: '100%', padding: '7px 10px', borderRadius: 7, border: 'none', cursor: 'pointer', background: active ? 'var(--bg-tertiary)' : 'none', fontFamily: 'inherit', textAlign: 'left' }}
onMouseEnter={e => { if (!active) e.currentTarget.style.background = 'var(--bg-tertiary)' }}
onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'none' }}>
<span style={{ color: active ? 'var(--accent)' : 'var(--text-muted)', marginTop: 1 }}>{icon}</span>
<span style={{ flex: 1, minWidth: 0 }}>
<span style={{ display: 'block', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-primary)' }}>{label}</span>
<span style={{ display: 'block', fontSize: 'calc(10.5px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)' }}>{sub}</span>
</span>
{active && <Check size={13} className="text-content-muted" style={{ marginTop: 2 }} />}
</button>
)
}