import { cloneElement, CSSProperties, FormEvent, ReactElement, useEffect, useId, useRef, useState } from 'react' import { createPortal } from 'react-dom' import { ExternalLink, Link2, Pencil, Pin, Plus, Trash2, X } from 'lucide-react' import CollabPanelHead, { HEAD_ACTION } from './CollabPanelHead' import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT } from '../shared/DialogShell' import { EditorField, INPUT } from '../shared/dialogParts' import { useIsPhone } from '../../mobile/useIsPhone' import { collabApi } from '../../api/client' import { addListener, removeListener } from '../../api/websocket' import { useTranslation } from '../../i18n' import { useCanDo } from '../../store/permissionsStore' import { useTripStore } from '../../store/tripStore' import ConfirmDialog from '../shared/ConfirmDialog' import EmptyState from '../shared/EmptyState' import { Tooltip } from '../shared/Tooltip' import { useToast } from '../shared/Toast' import { offlineOr } from '../../utils/needsConnection' const FONT = "var(--font-system)" interface CollabLink { id: number title: string url: string pinned: boolean | number } // The glyph holds the place until a favicon has really arrived: a host that never // answers, or answers with a blank pixel, left the chip with an empty square. function LinkIcon({ url }: { url: string }) { const [state, setState] = useState<'loading' | 'loaded' | 'failed'>('loading') let favicon = '' try { favicon = new URL('/favicon.ico', url).href } catch { /* not a parseable url, fall through to the glyph */ } const loaded = state === 'loaded' return ( ) } /** The part of the address worth a chip's width: the host, without a leading www. */ /** The desktop names a chip's action in the shared tooltip; the phone keeps its plain title. */ function ChipTip({ label, phone, children }: { label: string; phone: boolean; children: ReactElement<{ title?: string }> }) { return phone ? cloneElement(children, { title: label }) : {children} } function hostOf(url: string): string { try { return new URL(url).hostname.replace(/^www\./, '') } catch { return url } } /** * The add and edit form as a modal, like the poll and note panels next to it. * Inline it pushed the list down and gave the panel a second header, which is * what made this tab read as a different app from its four siblings. With a * link handed in it edits that link (#2414): a link used to be delete-and-add * once its title or address needed a correction. */ function LinkModal({ link, onClose, onSave }: { link?: CollabLink; onClose: () => void; onSave: (link: { title: string; url: string }) => Promise }) { const { t } = useTranslation() const [title, setTitle] = useState(link?.title ?? '') const [url, setUrl] = useState(link?.url ?? '') const [busy, setBusy] = useState(false) const isPhone = useIsPhone() const labelId = useId() const valid = title.trim().length > 0 && url.trim().length > 0 const submit = async (event?: FormEvent) => { event?.preventDefault() if (!valid || busy) return setBusy(true) try { await onSave({ title: title.trim(), url: url.trim() }) onClose() } catch { // The caller already said what went wrong; the form stays open with the input in it. } finally { setBusy(false) } } const field: CSSProperties = { width: '100%', boxSizing: 'border-box', padding: '8px 12px', borderRadius: 10, fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))', outline: 'none', border: '1px solid var(--border-primary)', background: 'var(--bg-input)', color: 'var(--text-primary)', } const label: CSSProperties = { fontSize: 'calc(9px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 4, } // The desktop names the link in the head band like every planner dialog. if (!isPhone) return ( } tint={NEUTRAL_TINT} labelId={labelId} onClose={onClose} eyebrow={t(link ? 'collab.links.edit' : 'collab.links.add')} titleInput={{ value: title, onChange: setTitle, label: t('collab.links.titlePlaceholder'), placeholder: t('collab.links.titlePlaceholder'), autoFocus: true, onKeyDown: e => { if (e.key === 'Enter') void submit() }, }} /> )} footer={( {t('collab.links.cancel')} void submit()} disabled={!valid || busy}>{busy ? '...' : t('collab.links.save')} )} > setUrl(e.target.value)} placeholder={t('collab.links.urlPlaceholder')} className={INPUT} /> ) return createPortal(
{ if (e.target === e.currentTarget) onClose() }}>

{t(link ? 'collab.links.edit' : 'collab.links.add')}

setTitle(e.target.value)} placeholder={t('collab.links.titlePlaceholder')} autoFocus style={field} />
setUrl(e.target.value)} placeholder={t('collab.links.urlPlaceholder')} style={field} />
, document.body, ) } export default function CollabLinks({ tripId }: { tripId: number }) { const { t } = useTranslation() const isPhone = useIsPhone() const trip = useTripStore(s => s.trip) const canEdit = useCanDo()('collab_edit', trip) const toast = useToast() const [links, setLinks] = useState([]) const [showForm, setShowForm] = useState(false) const [editing, setEditing] = useState(null) const [pendingDeleteId, setPendingDeleteId] = useState(null) // Both are new objects on every render, so depending on them would reload the // list after each keystroke and drop a link that was just added back out of it. const toastRef = useRef(toast) toastRef.current = toast const tRef = useRef(t) tRef.current = t useEffect(() => { let cancelled = false collabApi.getLinks(tripId) .then(d => { if (!cancelled) setLinks(d.links || []) }) .catch(err => { if (cancelled) return console.error('Failed to load collab links:', err) toastRef.current.error(tRef.current('common.error')) }) return () => { cancelled = true } }, [tripId]) // Live sync, the same shape the notes panel uses. Without it the three // collab:link events the server broadcasts would arrive nowhere and a link // somebody else added would only appear on the next reload. useEffect(() => { if (!tripId) return const handler = (msg: { type?: string; tripId?: number | string; link?: CollabLink; linkId?: number }) => { // The panel is not remounted on a trip change, so an event still in // flight from the trip we just left must not land in this list. if (String(msg?.tripId) !== String(tripId)) return if (msg.type === 'collab:link:created' && msg.link) { setLinks(prev => prev.some(l => l.id === msg.link!.id) ? prev : [msg.link!, ...prev]) } if (msg.type === 'collab:link:updated' && msg.link) { setLinks(prev => prev .map(l => l.id === msg.link!.id ? { ...l, ...msg.link! } : l) .sort((a, b) => Number(b.pinned) - Number(a.pinned))) } if (msg.type === 'collab:link:deleted' && msg.linkId) { setLinks(prev => prev.filter(l => l.id !== msg.linkId)) } } addListener(handler) return () => removeListener(handler) }, [tripId]) // Every write says something when it fails. Silence left the pin looking // unchanged and the delete looking ignored, with an unhandled rejection in // the console as the only trace. const add = async (data: { title: string; url: string }) => { try { const d = await collabApi.createLink(tripId, data) setLinks(v => [d.link, ...v]) } catch (err) { console.error('Failed to add collab link:', err) toast.error(offlineOr(t, t('common.error'))) throw err } } const toggle = async (link: CollabLink) => { try { const d = await collabApi.updateLink(tripId, link.id, { pinned: !link.pinned }) setLinks(v => v.map(x => x.id === link.id ? d.link : x).sort((a, b) => Number(b.pinned) - Number(a.pinned))) } catch (err) { console.error('Failed to pin collab link:', err) toast.error(offlineOr(t, t('common.error'))) } } const edit = async (link: CollabLink, data: { title: string; url: string }) => { try { const d = await collabApi.updateLink(tripId, link.id, data) setLinks(v => v.map(x => x.id === link.id ? d.link : x)) } catch (err) { console.error('Failed to edit collab link:', err) toast.error(offlineOr(t, t('common.error'))) throw err } } const remove = async (id: number) => { try { await collabApi.deleteLink(tripId, id) setLinks(v => v.filter(x => x.id !== id)) } catch (err) { console.error('Failed to delete collab link:', err) toast.error(offlineOr(t, t('common.error'))) } } return (
{/* Header: the desktop's head band; the phone keeps its own */} {!isPhone ? ( setShowForm(true)} className={HEAD_ACTION}> {t('collab.links.add')} )} /> ) : (

{t('collab.tabs.links')}

{canEdit && ( )}
)} {/* Content: one chip per link, two to a row (see .collab-link-chip). The chip is the link, with the host beside the title; the actions sit in its tail. */}
{links.length === 0 ? ( ) : (
{links.map(link => (
{/* Keyed on the address: the icon remembers a favicon that failed, and an edit keeps the chip's id, so a corrected address got the glyph. */} {link.title} {hostOf(link.url)} {canEdit && ( )}
))}
)}
{/* Create and edit modals */} {showForm && setShowForm(false)} onSave={add} />} {editing && setEditing(null)} onSave={data => edit(editing, data)} />} {/* The delete is shared: the link goes for every member, and on the phone the button is a thumb's width from pin. Same guard as the notes panel. */} setPendingDeleteId(null)} onConfirm={() => (pendingDeleteId !== null ? remove(pendingDeleteId) : undefined)} title={t('collab.links.confirmDeleteTitle')} message={t('collab.links.confirmDeleteBody')} />
) }