feat(assistant): chat, note and poll cards drawn like the Collab tab

This commit is contained in:
Maurice
2026-10-22 15:50:51 +02:00
parent b4e188fbfc
commit 6e92c2777c
63 changed files with 5147 additions and 251 deletions
@@ -0,0 +1,202 @@
import type { ReactNode } from 'react';
import { bubbleRadius } from './collabModel';
/**
* The pieces a message of the trip chat is drawn with, shared by the Collab
* tab and the assistant chat's cards so a message looks the same in both:
* the bubble with its tail and the quote it answers, the face beside it, the
* name over a group, the day between groups, the floating reactions and the
* time under the last message. Each piece only draws; what it does on a
* click or a hover stays with the caller.
*/
/** A face beside the last message of a group: the picture, else the first letter. */
export function ChatAvatar({ name, src, size = 28 }: { name: string; src: string | null; size?: number }) {
if (src) {
return <img src={src} alt="" style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover' }} />;
}
return (
<div
style={{
width: size,
height: size,
borderRadius: '50%',
background: 'var(--bg-tertiary)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 'calc(11px * var(--fs-scale-caption, 1))',
fontWeight: 700,
color: 'var(--text-muted)',
}}
>
{(name || '?').charAt(0).toUpperCase()}
</div>
);
}
/** "Today", "Yesterday" or a date between two groups of messages. */
export function ChatDateSeparator({ label }: { label: string }) {
return (
<div style={{ display: 'flex', justifyContent: 'center', padding: '14px 0 6px' }}>
<span
style={{
fontSize: 'calc(10px * var(--fs-scale-caption, 1))',
fontWeight: 600,
color: 'var(--text-faint)',
background: 'var(--bg-card)',
padding: '3px 12px',
borderRadius: 99,
letterSpacing: 0.3,
textTransform: 'uppercase',
}}
>
{label}
</span>
</div>
);
}
/** The name over the first message of someone else's group. */
export function ChatSenderName({ children }: { children: ReactNode }) {
return (
<span
style={{
fontSize: 'calc(10px * var(--fs-scale-caption, 1))',
fontWeight: 600,
color: 'var(--text-faint)',
marginBottom: 2,
paddingInlineStart: 4,
}}
>
{children}
</span>
);
}
/** One to three emoji alone, drawn large without a bubble. */
export function ChatBigEmoji({ children }: { children: ReactNode }) {
return (
<div style={{ fontSize: 'calc(40px * var(--fs-scale-title, 1))', lineHeight: 1.2, padding: '2px 0' }}>
{children}
</div>
);
}
/**
* The bubble: the user's own in the accent with its tail on their side, the
* others as cards on the tinted panel; the tail only on the last message of
* a group. A reply carries the quote of the message it answers on top.
*/
export function ChatBubble({
own,
lastInGroup,
reply,
text,
children,
}: {
own: boolean;
lastInGroup: boolean;
reply: { name: string; text: string } | null;
/** The message's words. */
text: ReactNode;
/** What comes under the words: images, a link preview. */
children?: ReactNode;
}) {
return (
<div
style={{
// Own messages in the accent, the others as cards on the tinted panel.
background: own ? 'var(--accent)' : 'var(--bg-card)',
color: own ? 'var(--accent-text)' : 'var(--text-primary)',
border: own ? 'none' : '1px solid var(--border-faint)',
...bubbleRadius(own, lastInGroup),
padding: reply ? '4px 4px 8px 4px' : '8px 14px',
fontSize: 'calc(14px * var(--fs-scale-body, 1))',
lineHeight: 1.4,
wordBreak: 'break-word',
whiteSpace: 'pre-wrap',
}}
>
{reply && (
<div
style={{
padding: '5px 10px',
marginBottom: 4,
borderRadius: 12,
background: own ? 'color-mix(in srgb, var(--accent-text) 15%, transparent)' : 'var(--bg-secondary)',
fontSize: 'calc(12px * var(--fs-scale-body, 1))',
lineHeight: 1.3,
}}
>
<div
style={{
fontWeight: 600,
fontSize: 'calc(11px * var(--fs-scale-caption, 1))',
opacity: 0.7,
marginBottom: 1,
}}
>
{reply.name}
</div>
<div style={{ opacity: 0.8, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{reply.text}
</div>
</div>
)}
{reply ? <div style={{ padding: '0 10px 4px' }}>{text}</div> : text}
{children}
</div>
);
}
/** The reactions floating under a bubble, on its side, in one pill. */
export function ChatReactions({ own, children }: { own: boolean; children: ReactNode }) {
return (
<div
style={{
display: 'flex',
gap: 3,
marginTop: -6,
marginBottom: 4,
justifyContent: own ? 'flex-end' : 'flex-start',
paddingInlineStart: own ? 0 : 8,
paddingInlineEnd: own ? 8 : 0,
position: 'relative',
zIndex: 1,
}}
>
<div
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 2,
padding: '3px 6px',
borderRadius: 99,
background: 'var(--bg-card)',
boxShadow: '0 1px 6px rgba(0,0,0,0.12)',
border: '1px solid var(--border-faint)',
}}
>
{children}
</div>
</div>
);
}
/** The time under the last message of a group, or what stands in its place. */
export function ChatTime({ children }: { children: ReactNode }) {
return (
<span
style={{
fontSize: 'calc(9px * var(--fs-scale-caption, 1))',
color: 'var(--text-faint)',
marginTop: 2,
padding: '0 4px',
}}
>
{children}
</span>
);
}
@@ -1,19 +1,28 @@
import type { ReactNode } from 'react'
import { URL_REGEX } from './CollabChat.constants'
/* ── Message Text with clickable URLs ── */
interface MessageTextProps {
text: string
/** Links read as underlined words that open nothing, as in the assistant chat's copy of a message. */
plain?: boolean
}
export function MessageText({ text }: MessageTextProps) {
export function MessageText({ text, plain = false }: MessageTextProps) {
const parts = text.split(URL_REGEX)
const urls = text.match(URL_REGEX) || []
const result = []
const result: ReactNode[] = []
parts.forEach((part, i) => {
if (part) result.push(part)
if (urls[i]) result.push(
<a key={i} href={urls[i]} target="_blank" rel="noopener noreferrer" style={{ color: 'inherit', textDecoration: 'underline', textUnderlineOffset: 2, opacity: 0.85 }}>
{urls[i]}
const url = urls[i]
if (url && plain) result.push(
<span key={i} style={{ textDecoration: 'underline', textUnderlineOffset: 2, opacity: 0.85, overflowWrap: 'anywhere' }}>
{url}
</span>
)
else if (url) result.push(
<a key={i} href={url} target="_blank" rel="noopener noreferrer" style={{ color: 'inherit', textDecoration: 'underline', textUnderlineOffset: 2, opacity: 0.85 }}>
{url}
</a>
)
})
@@ -4,6 +4,7 @@ import { Tooltip } from '../shared/Tooltip'
import { URL_REGEX } from './CollabChat.constants'
import { formatChatClockTime, formatChatDateSeparator, isFromAssistant, shouldShowChatDateSeparator } from './collabModel'
import CollabAssistantBadge from './CollabAssistantBadge'
import { ChatAvatar, ChatBigEmoji, ChatBubble, ChatDateSeparator, ChatReactions, ChatSenderName, ChatTime } from './CollabChatBubble'
import { MessageText } from './CollabChatMessageText'
import { CollabChatAttachment } from './CollabChatAttachment'
import { LinkPreview } from './CollabChatLinkPreview'
@@ -52,13 +53,7 @@ export function ChatMessages(props: any) {
if (msg._deleted) {
return (
<React.Fragment key={msg.id}>
{showDate && (
<div style={{ display: 'flex', justifyContent: 'center', padding: '14px 0 6px' }}>
<span style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)', background: 'var(--bg-card)', padding: '3px 12px', borderRadius: 99, letterSpacing: 0.3, textTransform: 'uppercase' }}>
{formatChatDateSeparator(msg.created_at, t)}
</span>
</div>
)}
{showDate && <ChatDateSeparator label={formatChatDateSeparator(msg.created_at, t)} />}
<div style={{ display: 'flex', justifyContent: 'center', padding: '4px 0' }}>
<span style={{ display: 'inline-flex', gap: 6, fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', fontStyle: 'italic' }}>
<span>{msg.username} {t('collab.chat.deletedMessage') || 'deleted a message'}</span>
@@ -69,27 +64,10 @@ export function ChatMessages(props: any) {
)
}
// Bubble border radius — iMessage style tails
const tail = isLastInGroup ? 4 : 18
const br = {
borderStartStartRadius: 18, borderStartEndRadius: 18,
borderEndEndRadius: own ? tail : 18, borderEndStartRadius: own ? 18 : tail,
}
return (
<React.Fragment key={msg.id}>
{/* Date separator */}
{showDate && (
<div style={{ display: 'flex', justifyContent: 'center', padding: '14px 0 6px' }}>
<span style={{
fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)',
background: 'var(--bg-card)', padding: '3px 12px', borderRadius: 99,
letterSpacing: 0.3, textTransform: 'uppercase',
}}>
{formatChatDateSeparator(msg.created_at, t)}
</span>
</div>
)}
{showDate && <ChatDateSeparator label={formatChatDateSeparator(msg.created_at, t)} />}
<div style={{
display: 'flex', alignItems: own ? 'flex-end' : 'flex-start',
@@ -102,29 +80,13 @@ export function ChatMessages(props: any) {
{/* Avatar slot for others */}
{!own && (
<div style={{ width: 28, flexShrink: 0, alignSelf: 'flex-end' }}>
{showAvatar && (
msg.user_avatar ? (
<img src={msg.user_avatar} alt="" style={{ width: 28, height: 28, borderRadius: '50%', objectFit: 'cover' }} />
) : (
<div style={{
width: 28, height: 28, borderRadius: '50%', background: 'var(--bg-tertiary)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700, color: 'var(--text-muted)',
}}>
{(msg.username || '?')[0].toUpperCase()}
</div>
)
)}
{showAvatar && <ChatAvatar name={msg.username} src={msg.user_avatar || null} />}
</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', alignItems: own ? 'flex-end' : 'flex-start', maxWidth: '78%', minWidth: 0 }}>
{/* Username for others at group start */}
{!own && isNewGroup && (
<span style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)', marginBottom: 2, paddingInlineStart: 4 }}>
{msg.username}
</span>
)}
{!own && isNewGroup && <ChatSenderName>{msg.username}</ChatSenderName>}
{isFromAssistant(msg) && (
<span className="mb-0.5 ps-1">
<CollabAssistantBadge name={msg.username} />
@@ -149,41 +111,19 @@ export function ChatMessages(props: any) {
}}
>
{bigEmoji ? (
<div style={{ fontSize: 'calc(40px * var(--fs-scale-title, 1))', lineHeight: 1.2, padding: '2px 0' }}>
{msg.text}
</div>
<ChatBigEmoji>{msg.text}</ChatBigEmoji>
) : (
<div style={{
// Own messages in the accent, the others as cards on the tinted panel.
background: own ? 'var(--accent)' : 'var(--bg-card)',
color: own ? 'var(--accent-text)' : 'var(--text-primary)',
border: own ? 'none' : '1px solid var(--border-faint)',
...br, padding: hasReply ? '4px 4px 8px 4px' : '8px 14px',
fontSize: 'calc(14px * var(--fs-scale-body, 1))', lineHeight: 1.4, wordBreak: 'break-word', whiteSpace: 'pre-wrap',
}}>
{/* Inline reply quote */}
{hasReply && (
<div style={{
padding: '5px 10px', marginBottom: 4, borderRadius: 12,
background: own ? 'color-mix(in srgb, var(--accent-text) 15%, transparent)' : 'var(--bg-secondary)',
fontSize: 'calc(12px * var(--fs-scale-body, 1))', lineHeight: 1.3,
}}>
<div style={{ fontWeight: 600, fontSize: 'calc(11px * var(--fs-scale-caption, 1))', opacity: 0.7, marginBottom: 1 }}>
{msg.reply_username || ''}
</div>
<div style={{ opacity: 0.8, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{(msg.reply_text || '').slice(0, 80)}
</div>
</div>
)}
{hasReply ? (
<div style={{ padding: '0 10px 4px' }}><MessageText text={msg.text} /></div>
) : <MessageText text={msg.text} />}
<ChatBubble
own={own}
lastInGroup={isLastInGroup}
reply={hasReply ? { name: msg.reply_username || '', text: (msg.reply_text || '').slice(0, 80) } : null}
text={<MessageText text={msg.text} />}
>
{msg.attachments?.map((attachment: any) => <CollabChatAttachment key={attachment.id} attachment={attachment} />)}
{(msg.text.match(URL_REGEX) || []).slice(0, 1).map(url => (
<LinkPreview key={url} url={url} tripId={tripId} own={own} onLoad={() => { if (isAtBottom.current) setTimeout(() => scrollToBottom('smooth'), 50) }} />
))}
</div>
</ChatBubble>
)}
{/* Hover actions: above the reactions of the message before, which reach into this row */}
@@ -228,30 +168,15 @@ export function ChatMessages(props: any) {
{/* Reactions — iMessage style floating badge */}
{msg.reactions?.length > 0 && (
<div style={{
display: 'flex', gap: 3, marginTop: -6, marginBottom: 4,
justifyContent: own ? 'flex-end' : 'flex-start',
paddingInlineStart: own ? 0 : 8, paddingInlineEnd: own ? 8 : 0,
position: 'relative', zIndex: 1,
}}>
<div style={{
display: 'inline-flex', alignItems: 'center', gap: 2, padding: '3px 6px',
borderRadius: 99, background: 'var(--bg-card)',
boxShadow: '0 1px 6px rgba(0,0,0,0.12)', border: '1px solid var(--border-faint)',
}}>
{msg.reactions.map(r => (
<ReactionBadge key={r.emoji} reaction={r} currentUserId={currentUser.id} onReact={() => { if (canEdit) handleReact(msg.id, r.emoji) }} />
))}
</div>
</div>
<ChatReactions own={own}>
{msg.reactions.map(r => (
<ReactionBadge key={r.emoji} reaction={r} currentUserId={currentUser.id} onReact={() => { if (canEdit) handleReact(msg.id, r.emoji) }} />
))}
</ChatReactions>
)}
{/* Timestamp — only on last message of group */}
{isLastInGroup && (
<span style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', marginTop: 2, padding: '0 4px' }}>
{formatChatClockTime(msg.created_at, is12h)}
</span>
)}
{isLastInGroup && <ChatTime>{formatChatClockTime(msg.created_at, is12h)}</ChatTime>}
</div>
</div>
</React.Fragment>
@@ -0,0 +1,58 @@
import { Pin } from 'lucide-react';
import type { ReactNode } from 'react';
import { fs } from '../Planner/bookings/bookingParts';
import { tintOf } from '../Planner/planParts';
import { Tooltip } from '../shared/Tooltip';
/**
* The head band of a shared note, tinted by its category's colour: the
* category as a dot (its name in the tooltip), the title, a pin when it is
* pinned and whatever the caller puts at the end (the note card's link, menu
* and author). The Collab tab and the assistant chat's note cards draw it.
*/
export function NoteHeadBand({
title,
color,
category,
pinned,
bordered,
trailing,
titleClassName = '',
}: {
title: ReactNode;
/** The category's colour, already checked. */
color: string;
category: string | null;
pinned: boolean;
/** A line under the band, when a body follows. */
bordered: boolean;
trailing?: ReactNode;
/** Extra classes for the title (struck through for a note about to go). */
titleClassName?: string;
}) {
return (
<div
className={`flex items-center gap-2 py-1.5 ps-3 pe-1.5 ${bordered ? 'border-b border-edge-faint' : ''}`}
style={{ background: tintOf(color) }}
>
{/* The category is only its colour here; the name is in the tooltip and the filter above. */}
{category && (
<Tooltip label={category}>
<span
role="img"
aria-label={category}
data-testid="note-category-dot"
className="h-2.5 w-2.5 flex-none rounded-full"
style={{ background: color }}
/>
</Tooltip>
)}
<span className={`min-w-0 flex-1 truncate font-bold text-content ${titleClassName}`} style={fs(13, 'body')}>
{title}
</span>
{pinned && <Pin size={12} strokeWidth={2.2} className="flex-none" style={{ color }} />}
{trailing}
</div>
);
}
@@ -11,6 +11,7 @@ import { ContextMenu, useContextMenu } from '../shared/ContextMenu'
import { Eyebrow, fs } from '../Planner/bookings/bookingParts'
import { AuthedImg } from './CollabNotesAuthedImg'
import { UserAvatar } from './CollabNotesUserAvatar'
import { NoteHeadBand } from './CollabNoteHead'
import type { CollabNote, NoteFile } from './CollabNotes.types'
import type { User } from '../../types'
@@ -77,15 +78,7 @@ export function NoteCard({ note, canEdit, onUpdate, onDelete, onEdit, onView, on
// A pinned note keeps its category colour on the frame, the way a selected booking card does.
style={{ borderColor: note.pinned ? `color-mix(in srgb, ${color} 45%, transparent)` : 'var(--border-faint)' }}
>
<div className={`flex items-center gap-2 py-1.5 ps-3 pe-1.5 ${hasBody ? 'border-b border-edge-faint' : ''}`} style={{ background: `color-mix(in srgb, ${color} 11%, transparent)` }}>
{/* The category is only its colour here; the name is in the tooltip and the filter above. */}
{note.category && (
<Tooltip label={note.category}>
<span role="img" aria-label={note.category} data-testid="note-category-dot" className="h-2.5 w-2.5 flex-none rounded-full" style={{ background: color }} />
</Tooltip>
)}
<span className="min-w-0 flex-1 truncate font-bold text-content" style={fs(13, 'body')}>{note.title}</span>
{!!note.pinned && <Pin size={12} strokeWidth={2.2} className="flex-none" style={{ color }} />}
<NoteHeadBand title={note.title} color={color} category={note.category || null} pinned={!!note.pinned} bordered={hasBody} trailing={<>
{/* The link rides in the title row as one round button; the host is in its tooltip. */}
{note.website && (
<Tooltip label={websiteHref ? linkHost(websiteHref) : note.website}>
@@ -111,7 +104,7 @@ export function NoteCard({ note, canEdit, onUpdate, onDelete, onEdit, onView, on
<Tooltip label={author.username}>
<span role="img" aria-label={author.username} className="flex flex-none"><UserAvatar user={author} size={20} /></span>
</Tooltip>
</div>
</>} />
{hasBody && (
<div className="flex flex-1 flex-col gap-2 px-3 pb-2.5 pt-2">
@@ -0,0 +1,105 @@
/**
* FE-COLLAB-PARTS-001 to FE-COLLAB-PARTS-005
*
* The pieces the Collab tab and the assistant chat's cards draw a message, a
* poll option and a note's head band with: the bubble's sides, tail and
* quote, the face or its letter, the option as a button or a row with its
* results and a held vote, the tinted band with its dot and pin, and links
* that read as words where they must not open.
*/
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { ChatAvatar, ChatBubble, ChatDateSeparator, ChatReactions, ChatTime } from './CollabChatBubble';
import { MessageText } from './CollabChatMessageText';
import { NoteHeadBand } from './CollabNoteHead';
import { PollChip, PollOptionRow } from './CollabPollOption';
describe('the Collab pieces', () => {
it('FE-COLLAB-PARTS-001: a bubble takes its side colour, its tail on the last of a run and the quote it answers', () => {
const { rerender } = render(<ChatBubble own lastInGroup reply={null} text="mine" />);
const own = screen.getByText('mine');
expect(own.getAttribute('style')).toContain('background: var(--accent)');
expect(own.getAttribute('style')).toContain('border-end-end-radius: 4px');
rerender(<ChatBubble own={false} lastInGroup={false} reply={{ name: 'Anna', text: 'Train?' }} text="yours" />);
const quoted = screen.getByText('yours');
expect(quoted.parentElement?.getAttribute('style')).toContain('background: var(--bg-card)');
expect(screen.getByText('Anna')).toBeInTheDocument();
expect(screen.getByText('Train?')).toBeInTheDocument();
});
it('FE-COLLAB-PARTS-002: a face is the picture, else the first letter; day, reactions and time draw their children', () => {
const { container, rerender } = render(<ChatAvatar name="jon" src={null} size={24} />);
expect(screen.getByText('J').getAttribute('style')).toContain('width: 24px');
rerender(<ChatAvatar name="jon" src="/uploads/avatars/jon.png" />);
expect(container.querySelector('img')?.getAttribute('src')).toBe('/uploads/avatars/jon.png');
rerender(
<>
<ChatDateSeparator label="Today" />
<ChatReactions own>
<span>❤️</span>
</ChatReactions>
<ChatTime>09:12</ChatTime>
</>
);
expect(screen.getByText('Today')).toBeInTheDocument();
expect(screen.getByText('❤️').parentElement?.parentElement?.getAttribute('style')).toContain('flex-end');
expect(screen.getByText('09:12')).toBeInTheDocument();
});
it('FE-COLLAB-PARTS-003: links open in a new tab in the chat and read as words where they must not open', () => {
const { container, rerender } = render(<MessageText text="see https://a.example/x now" />);
expect(container.querySelector('a')?.getAttribute('href')).toBe('https://a.example/x');
rerender(<MessageText text="see https://a.example/x now" plain />);
expect(container.querySelector('a')).toBeNull();
expect(screen.getByText('https://a.example/x').tagName).toBe('SPAN');
});
it('FE-COLLAB-PARTS-004: an option votes as a button, shows as a row, and marks a held vote', () => {
const onClick = vi.fn();
const voters = [{ key: 7, name: 'anna', src: null }];
const { rerender } = render(
<PollOptionRow
text="Pizza"
pct={50}
mine={false}
winner={false}
showResults={false}
voters={voters}
onClick={onClick}
/>
);
fireEvent.click(screen.getByRole('button'));
expect(onClick).toHaveBeenCalled();
expect(screen.queryByText('50%')).toBeNull();
rerender(
<PollOptionRow
as="div"
text="Pizza"
pct={50}
mine
winner={false}
showResults
voters={voters}
pending={{ label: 'Your vote' }}
/>
);
expect(screen.queryByRole('button')).toBeNull();
expect(screen.getByText('50%')).toBeInTheDocument();
expect(screen.getByText('Your vote').className).toContain('sr-only');
expect(screen.getByText('Pizza').closest('div')?.className).toContain('border-dashed');
render(<PollChip tone="info">New</PollChip>);
expect(screen.getByText('New').className).toContain('text-info');
});
it("FE-COLLAB-PARTS-005: a note's band shows its category as a dot, its title and its pin", () => {
const { container } = render(
<NoteHeadBand title="Food" color="#10b981" category="Ideas" pinned bordered trailing={<span>end</span>} />
);
expect(screen.getByTestId('note-category-dot').style.background).toBe('rgb(16, 185, 129)');
expect(screen.getByText('Food')).toBeInTheDocument();
expect(screen.getByText('end')).toBeInTheDocument();
expect(container.querySelector('.lucide-pin')).not.toBeNull();
expect(container.firstElementChild?.className).toContain('border-b');
});
});
@@ -0,0 +1,161 @@
import { Check } from 'lucide-react';
import type { ReactNode } from 'react';
import { fs } from '../shared/DialogShell';
import { Tooltip } from '../shared/Tooltip';
/**
* The pieces a poll of the trip is drawn with, shared by the Collab tab and
* the assistant chat's poll cards: an option with its bar, its check, its
* voters and its share, a voter's face and a fact on the poll's head band.
* An option is a button where it can be voted for and a plain row where it
* only shows; a vote the assistant holds marks its option with a dashed
* frame until it is decided.
*/
/** A voter as an option shows them: a name and the picture TREK serves, if any. */
interface PollVoterFace {
key: string | number;
name: string;
src: string | null;
}
/** One voter's face; faces after the first overlap the one before. */
function VoterChip({ name, src, offset }: { name: string; src: string | null; offset: boolean }) {
return (
<Tooltip label={name || '?'}>
<span
className="grid h-[18px] w-[18px] flex-none place-items-center overflow-hidden rounded-full border-[1.5px] border-surface-card bg-surface-tertiary font-bold text-content-muted"
style={{ ...fs(7), marginInlineStart: offset ? -5 : 0 }}
>
{src ? (
<img src={src} alt={name} className="h-full w-full object-cover" />
) : (
(name || '?').charAt(0).toUpperCase()
)}
</span>
</Tooltip>
);
}
/** A fact about the poll on its head band, set like the type chip on a booking card. */
export function PollChip({
icon,
tone = 'muted',
children,
}: {
icon?: ReactNode;
tone?: 'muted' | 'warning' | 'info';
children: ReactNode;
}) {
const color = tone === 'warning' ? 'text-warning' : tone === 'info' ? 'text-info' : 'text-content-muted';
return (
<span
className={`inline-flex flex-none items-center gap-1 rounded-full border border-edge-faint bg-surface-card px-2 py-[2px] font-geist font-bold uppercase tracking-[.06em] ${color}`}
style={fs(9.5)}
>
{icon}
{children}
</span>
);
}
interface PollOptionRowProps {
text: string;
/** Its share of all votes, which the bar draws. */
pct: number;
/** The signed-in user voted for it. */
mine: boolean;
/** The poll ended and it has the most votes. */
winner: boolean;
/** Shares and voters show once the user voted or the poll ended. */
showResults: boolean;
voters: readonly PollVoterFace[];
/** A button to vote with, or a row that only shows. */
as?: 'button' | 'div';
/** A vote waiting for its decision: the frame is dashed, and says so to a screen reader. */
pending?: { label: string } | null;
disabled?: boolean;
onClick?: () => void;
}
/** One option of a poll, as the Collab tab draws it. */
export function PollOptionRow({
text,
pct,
mine,
winner,
showResults,
voters,
as = 'button',
pending = null,
disabled = false,
onClick,
}: PollOptionRowProps) {
const frame = pending
? 'border-dashed border-accent'
: mine
? 'border-accent'
: 'border-edge-faint enabled:hover:border-edge';
const body = (
<>
{/* The bar behind it: the user's choice in the accent, the winner in green. */}
<span
aria-hidden="true"
className="absolute inset-y-0 start-0 transition-[width] duration-500"
style={{
width: `${pct}%`,
background: mine
? 'color-mix(in srgb, var(--accent) 12%, transparent)'
: winner
? 'var(--success-soft)'
: 'var(--bg-tertiary)',
}}
/>
<span
className={`relative grid h-5 w-5 flex-none place-items-center rounded-full border-2 transition-colors ${mine ? 'border-accent bg-accent text-accent-text' : 'border-edge bg-surface-card'}`}
>
{mine && <Check size={11} strokeWidth={3} />}
</span>
{/* Plain text, but a long or multiline option wraps instead of being clipped (#2177). */}
<span
className="relative z-[1] text-content"
style={{
flex: 1,
minWidth: 0,
whiteSpace: 'pre-wrap',
overflowWrap: 'anywhere',
wordBreak: 'break-word',
lineHeight: 1.35,
...fs(13, 'body'),
fontWeight: mine || winner ? 600 : 400,
}}
>
{text}
</span>
{voters.length > 0 && showResults && (
<span className="relative z-[1] flex">
{voters.slice(0, 3).map((voter, index) => (
<VoterChip key={voter.key} name={voter.name} src={voter.src} offset={index > 0} />
))}
</span>
)}
{pending && <span className="sr-only">{pending.label}</span>}
{showResults && (
<span
className={`relative z-[1] min-w-[32px] text-end font-geist font-bold tabular-nums ${mine ? 'text-content' : 'text-content-muted'}`}
style={fs(12, 'body')}
>
{pct}%
</span>
)}
</>
);
const look = `relative flex w-full items-start gap-2.5 overflow-hidden rounded-[10px] border bg-surface-secondary px-3 py-2.5 text-start transition-colors disabled:cursor-default ${frame}`;
if (as === 'div') return <div className={look}>{body}</div>;
return (
<button type="button" onClick={onClick} disabled={disabled} className={look}>
{body}
</button>
);
}
+12 -75
View File
@@ -1,7 +1,8 @@
import React, { useState, useCallback, useId } from 'react'
import { Plus, Trash2, X, Check, BarChart3, Lock, Clock } from 'lucide-react'
import { Plus, Trash2, X, BarChart3, Lock, Clock } from 'lucide-react'
import { RoundAction } from '../Planner/bookings/bookingParts'
import CollabPanelHead, { HEAD_ACTION } from './CollabPanelHead'
import { PollChip, PollOptionRow } from './CollabPollOption'
import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell'
import { AddRowButton, EditorField, TEXTAREA } from '../shared/dialogParts'
import { Tooltip } from '../shared/Tooltip'
@@ -19,12 +20,6 @@ import type { CollabPollCreateRequest } from '@trek/shared'
import { useCollabPolls } from './useCollabPolls'
import { hasUserVoted, isPollActive, pollMaxVoteCount, splitPolls, totalPollVotes, type CollabPollData } from './collabModel'
interface PollVoter {
user_id: number
username: string
avatar_url: string | null
}
const FONT = "var(--font-system)"
// Block styling for the markdown question (#2177). Tailwind's preflight resets
@@ -156,33 +151,6 @@ function CreatePollModal({ onClose, onCreate, t }: CreatePollModalProps) {
)
}
// ── Voter Chip ───────────────────────────────────────────────────────────────
interface VoterChipProps {
voter: PollVoter
offset: boolean
}
function VoterChip({ voter, offset }: VoterChipProps) {
return (
<Tooltip label={voter.username || '?'}>
<span className="grid h-[18px] w-[18px] flex-none place-items-center overflow-hidden rounded-full border-[1.5px] border-surface-card bg-surface-tertiary font-bold text-content-muted"
style={{ ...fs(7), marginInlineStart: offset ? -5 : 0 }}>
{voter.avatar_url ? <img src={voter.avatar_url} alt={voter.username || ''} className="h-full w-full object-cover" /> : (voter.username || '?')[0].toUpperCase()}
</span>
</Tooltip>
)
}
/** A fact about the poll on its head band, set like the type chip on a booking card. */
function PollChip({ icon, tone = 'muted', children }: { icon?: React.ReactNode; tone?: 'muted' | 'warning'; children: React.ReactNode }) {
return (
<span className={`inline-flex flex-none items-center gap-1 rounded-full border border-edge-faint bg-surface-card px-2 py-[2px] font-geist font-bold uppercase tracking-[.06em] ${tone === 'warning' ? 'text-warning' : 'text-content-muted'}`} style={fs(9.5)}>
{icon}
{children}
</span>
)
}
// ── Poll Card ────────────────────────────────────────────────────────────────
interface PollCardProps {
poll: CollabPollData
@@ -238,48 +206,17 @@ function PollCard({ poll, currentUser, canEdit, onVote, onClose, onDelete, t }:
const isWinner = isClosed && count > 0 && count === topCount
return (
<button type="button" key={idx} onClick={() => onVote(poll.id, idx)}
<PollOptionRow
key={idx}
text={typeof opt === 'string' ? opt : opt.text}
pct={pct}
mine={myVote}
winner={isWinner}
showResults={hasVoted || isClosed}
voters={(opt.voters || []).map((v, vi) => ({ key: v.user_id || vi, name: v.username || '?', src: v.avatar_url }))}
disabled={isClosed}
className={`relative flex w-full items-start gap-2.5 overflow-hidden rounded-[10px] border bg-surface-secondary px-3 py-2.5 text-start transition-colors disabled:cursor-default ${myVote ? 'border-accent' : 'border-edge-faint enabled:hover:border-edge'}`}
>
{/* Progress bar background */}
<span aria-hidden="true" className="absolute inset-y-0 left-0 transition-[width] duration-500"
style={{
width: `${pct}%`,
background: myVote ? 'color-mix(in srgb, var(--accent) 12%, transparent)' : isWinner ? 'var(--success-soft)' : 'var(--bg-tertiary)',
}} />
{/* Check circle */}
<span className={`relative grid h-5 w-5 flex-none place-items-center rounded-full border-2 transition-colors ${myVote ? 'border-accent bg-accent text-accent-text' : 'border-edge bg-surface-card'}`}>
{myVote && <Check size={11} strokeWidth={3} />}
</span>
{/* Label — options stay plain text, but long or multiline ones
must wrap instead of being clipped by the button's
overflow:hidden (#2177) */}
<span className="relative z-[1] text-content" style={{
flex: 1, minWidth: 0, whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', wordBreak: 'break-word',
lineHeight: 1.35, ...fs(13, 'body'), fontWeight: myVote || isWinner ? 600 : 400,
}}>
{typeof opt === 'string' ? opt : opt.text}
</span>
{/* Voter avatars */}
{(opt.voters || []).length > 0 && (hasVoted || isClosed) && (
<span className="relative z-[1] flex">
{(opt.voters || []).slice(0, 3).map((v, vi) => (
<VoterChip key={v.user_id || vi} voter={v} offset={vi > 0} />
))}
</span>
)}
{/* Percentage */}
{(hasVoted || isClosed) && (
<span className={`relative z-[1] min-w-[32px] text-end font-geist font-bold tabular-nums ${myVote ? 'text-content' : 'text-content-muted'}`} style={fs(12, 'body')}>
{pct}%
</span>
)}
</button>
onClick={() => onVote(poll.id, idx)}
/>
)
})}
</div>
@@ -72,6 +72,20 @@ export const OTHER_BUBBLE_RADIUS = {
borderEndStartRadius: 16,
} as const;
/** The corners of a desktop chat bubble: round all over, with the tail (a tight
* corner on the sender's side) only on the last message of a group. Logical
* corners, so the tail follows the row in a right-to-left language. The Collab
* tab and the assistant's chat card draw with it. */
export function bubbleRadius(own: boolean, lastInGroup: boolean) {
const tail = lastInGroup ? 4 : 18;
return {
borderStartStartRadius: 18,
borderStartEndRadius: 18,
borderEndEndRadius: own ? tail : 18,
borderEndStartRadius: own ? 18 : tail,
};
}
// SQLite stores UTC without a 'Z' suffix — append one so JS parses it as UTC
// rather than local time.
export function parseUtcDate(iso: string): Date {