Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Documentation/ComponentPicker/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,12 @@ Components with descriptors today:
| --- | --- | --- |
| `Button` | `Button` | `label`, `tooltip`, `variant`, `tone`, `shape`, `size` |
| `IconButton` | `IconButton` | `tooltip`, `variant`, `tone`, `shape`, `size` |
| `Badge` | `Badge` | `severity`, `size`, `shape` |
| `Chip` | `Chip` | `label`, `removeAriaLabel` |
| `Avatar` | `Avatar` | `label`, `alt`, `size` |
| `Tag` | `Tag` | `severity`, `rounded` |
| `Skeleton` | `Skeleton` | `width`, `height`, `borderRadius`, `circle` |
| `ProgressSpinner` | `ProgressSpinner` | `aria-label` |
| `TextInput` | `TextInput` | `placeholder`, `invalid`, `disabled`, `readOnly`, `type` |
| `TextArea` | `TextArea` | `placeholder`, `rows`, `invalid`, `disabled`, `readOnly` |
| `Dialog` | `Dialog` | `title`, `placement`, `width`, `okLabel`, `cancelLabel` |
Expand Down
56 changes: 34 additions & 22 deletions Source/Chat/ChatConversation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -182,22 +182,24 @@ interface MessageRenderInfo {
showTimestamp: boolean;
}

const hasSameAuthor = (left: ChatMessage, right: ChatMessage): boolean =>
chatIdentifierString(left.authorId) === chatIdentifierString(right.authorId);

const startsAuthorGroup = (message: ChatMessage, previous: ChatMessage | undefined): boolean =>
!previous || !hasSameAuthor(previous, message);

const endsTimestampGroup = (message: ChatMessage, next: ChatMessage | undefined): boolean =>
!next || !hasSameAuthor(next, message) || !sameMinute(timestampOf(message), timestampOf(next));

const computeRenderInfo = (messages: ChatMessage[]): MessageRenderInfo[] =>
messages.map((message, index) => {
const previous = index > 0 ? messages[index - 1] : undefined;
const next = index < messages.length - 1 ? messages[index + 1] : undefined;

const showAuthor =
!previous ||
chatIdentifierString(previous.authorId) !==
chatIdentifierString(message.authorId);
const showTimestamp =
!next ||
chatIdentifierString(next.authorId) !==
chatIdentifierString(message.authorId) ||
!sameMinute(timestampOf(message), timestampOf(next));

return { showAuthor, showTimestamp };
return {
showAuthor: startsAuthorGroup(message, previous),
showTimestamp: endsTimestampGroup(message, next),
};
});

/**
Expand Down Expand Up @@ -236,19 +238,37 @@ const conversationStatusLabel = (
}
};

const showsStatusAlongsideMessages = (status: ChatStatus): boolean =>
status === ChatStatus.Failed || status === ChatStatus.Unauthorized;

const renderConversationStatus = (
messageCount: number,
status: ChatStatus,
labels: ChatConversationLabels | undefined,
) => {
if (messageCount > 0 && status !== ChatStatus.Failed && status !== ChatStatus.Unauthorized) return null;
if (messageCount > 0 && !showsStatusAlongsideMessages(status)) return null;
return (
<p className='cratis-chat-conversation__empty'>
{conversationStatusLabel(status, labels)}
</p>
);
};

const authorFor = (
authorId: ChatIdentifier,
authorOf: ChatConversationProps['authorOf'],
): ChatAuthor => authorOf?.(authorId) ?? {
name: chatIdentifierString(authorId),
kind: ChatAuthorKind.User,
};

const availableActionsFor = <TMessage extends ChatMessage>(
message: TMessage,
actions: ChatMessageAction<TMessage>[] | undefined,
): ChatMessageAction<TMessage>[] => (actions ?? []).filter(
action => action.isAvailable?.(message) ?? true,
);

interface ConversationMessageProps<TMessage extends ChatMessage> extends Pick<ChatConversationProps<TMessage>,
'renderAvatar' | 'renderAuthorName' | 'renderMessageExtra' | 'buildAvatarUrl' | 'labels'> {
message: TMessage;
Expand Down Expand Up @@ -375,12 +395,6 @@ export const ChatConversation = <TMessage extends ChatMessage = ChatMessage>({
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}, [messages, typingAuthors.length]);

const authorFor = (authorId: ChatIdentifier): ChatAuthor =>
authorOf?.(authorId) ?? {
name: chatIdentifierString(authorId),
kind: ChatAuthorKind.User,
};

const send = (text: string, mentioned: MentionCandidate[]) =>
onSendMessage(
text,
Expand All @@ -401,10 +415,8 @@ export const ChatConversation = <TMessage extends ChatMessage = ChatMessage>({
<div className='cratis-chat-conversation__messages' aria-busy={status === ChatStatus.Loading && messages.length > 0 || undefined}>
{renderConversationStatus(messages.length, status, labels)}
{status !== ChatStatus.Unauthorized && messages.map((message, index) => {
const author = authorFor(message.authorId);
const availableActions = (actions ?? []).filter(
(action) => action.isAvailable?.(message) ?? true,
);
const author = authorFor(message.authorId, authorOf);
const availableActions = availableActionsFor(message, actions);
return renderConversationMessage({
message,
author,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright (c) Cratis. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

// @vitest-environment jsdom

import { createElement } from 'react';
import { ChatConversation } from '../ChatConversation';
import type { ChatMessage } from '../ChatMessage';
import { render, unmount, type ConversationInTheDom } from './given/a_conversation_in_the_dom';

const messages: ChatMessage[] = [
{ id: 'message-1', topicId: 'topic-1', authorId: 'author-1', body: 'First example', timestamp: new Date('2026-01-01T10:00:00Z') },
{ id: 'message-2', topicId: 'topic-1', authorId: { toString: () => 'author-1' }, body: 'Second example', timestamp: new Date('2026-01-01T10:00:30Z') },
{ id: 'message-3', topicId: 'topic-1', authorId: 'author-1', body: 'Third example', timestamp: new Date('2026-01-01T10:01:00Z') },
{ id: 'message-4', topicId: 'topic-1', authorId: 'author-2', body: 'Fourth example', timestamp: new Date('2026-01-01T10:01:30Z') },
];

const messageRows = () => Array.from(document.querySelectorAll('.cratis-chat-message'));

describe('when grouping adjacent messages', () => {
let conversation: ConversationInTheDom;

beforeEach(async () => {
conversation = await render(createElement(ChatConversation, {
messages,
onSendMessage: () => {},
}));
});

afterEach(async () => unmount(conversation));

it('should group authors by their string identifiers even across minutes', () => {
messageRows().map(row => row.classList.contains('cratis-chat-message--continuation'))
.should.deep.equal([false, true, true, false]);
});

it('should fall back to the author identifier when no resolver is supplied', () => {
Array.from(document.querySelectorAll('.cratis-chat-message__author-name'))
.map(author => author.textContent).should.deep.equal(['author-1', 'author-2']);
});

it('should show timestamps at minute changes, author changes and the last message', () => {
messageRows().map(row => row.querySelectorAll('.cratis-chat-message__time').length)
.should.deep.equal([0, 1, 1, 1]);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Copyright (c) Cratis. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

import React, { type ReactElement } from 'react';
import { Avatar } from '../../../Display/Avatar';
import { Badge } from '../../../Display/Badge';
import { Chip } from '../../../Display/Chip';
import { ProgressSpinner } from '../../../Display/ProgressSpinner';
import { Skeleton } from '../../../Display/Skeleton';
import { Tag } from '../../../Display/Tag';
import type { PresentationPropertyDescriptor } from '../../../configuration/identity/PresentationPropertyDescriptor';
import type { PresentationPropertyValue } from '../../../configuration/identity/PresentationPropertyValue';

interface DisplayComponentCase {
component: string;
element: ReactElement;
properties: readonly PresentationPropertyDescriptor<Record<string, unknown>>[];
current: Record<string, PresentationPropertyValue>;
preview: Record<string, PresentationPropertyValue>;
read: (element: HTMLElement) => unknown;
rendered: unknown;
previewed: unknown;
}

export const displayComponents: readonly DisplayComponentCase[] = [
{
component: 'Badge',
element: <Badge value={7} severity='info' size='large' shape='circle' />,
properties: [
{ name: 'severity', label: 'Severity', type: 'enum', values: ['secondary', 'info', 'success', 'warn', 'danger', 'contrast'], defaultValue: 'secondary' },
{ name: 'size', label: 'Size', type: 'enum', values: ['small', 'large', 'xlarge'], defaultValue: 'small' },
{ name: 'shape', label: 'Shape', type: 'enum', values: ['circle'] },
],
current: { severity: 'info', size: 'large', shape: 'circle' },
preview: { severity: 'success', size: 'xlarge', shape: undefined },
read: (element) => [element.dataset.severity, element.dataset.size, element.dataset.shape, element.textContent],
rendered: ['info', 'large', 'circle', '7'],
previewed: ['success', 'xlarge', undefined, '7'],
},
{
component: 'Chip',
element: <Chip label='Example Project' removable removeAriaLabel='Remove example' onRemove={() => undefined} />,
properties: [
{ name: 'label', label: 'Label', type: 'string' },
{ name: 'removeAriaLabel', label: 'Remove accessible name', type: 'string', defaultValue: 'Remove' },
],
current: { label: 'Example Project', removeAriaLabel: 'Remove example' },
preview: { label: 'Demo Assistant', removeAriaLabel: 'Remove preview' },
read: (element) => [element.querySelector('[data-cratis-part="label"]')?.textContent, element.querySelector('button')?.getAttribute('aria-label')],
rendered: ['Example Project', 'Remove example'],
previewed: ['Demo Assistant', 'Remove preview'],
},
{
component: 'Avatar',
element: <Avatar label='SU' alt='Sample User' size='large' />,
properties: [
{ name: 'label', label: 'Label', type: 'string' },
{ name: 'alt', label: 'Alternative text', type: 'string', defaultValue: '' },
{ name: 'size', label: 'Size', type: 'enum', values: ['normal', 'large', 'xlarge'], defaultValue: 'normal' },
],
current: { label: 'SU', alt: 'Sample User', size: 'large' },
preview: { label: 'DA', size: 'xlarge' },
read: (element) => [element.textContent, element.dataset.size],
rendered: ['SU', 'large'],
previewed: ['DA', 'xlarge'],
},
{
component: 'Tag',
element: <Tag value='Example status' severity='info' rounded={false} />,
properties: [
{ name: 'severity', label: 'Severity', type: 'enum', values: ['secondary', 'success', 'info', 'warn', 'danger', 'contrast'], defaultValue: 'secondary' },
{ name: 'rounded', label: 'Rounded', type: 'boolean' },
],
current: { severity: 'info', rounded: false },
preview: { severity: 'success', rounded: true },
read: (element) => [element.dataset.severity, element.dataset.rounded, element.textContent],
rendered: ['info', undefined, 'Example status'],
previewed: ['success', 'true', 'Example status'],
},
{
component: 'Skeleton',
element: <Skeleton width='4rem' height='2rem' borderRadius='1px' circle={false} />,
properties: [
{ name: 'width', label: 'Width', type: 'string', defaultValue: '100%' },
{ name: 'height', label: 'Height', type: 'string', defaultValue: '1rem' },
{ name: 'borderRadius', label: 'Border radius', type: 'string' },
{ name: 'circle', label: 'Circle', type: 'boolean' },
],
current: { width: '4rem', height: '2rem', borderRadius: '1px', circle: false },
preview: { width: '6rem', height: '3rem', borderRadius: '2px' },
read: (element) => [element.style.width, element.style.height, element.style.borderRadius, element.dataset.circle],
rendered: ['4rem', '2rem', '1px', undefined],
previewed: ['6rem', '3rem', '2px', undefined],
},
{
component: 'ProgressSpinner',
element: <ProgressSpinner aria-label='Loading example' />,
properties: [
{ name: 'aria-label', label: 'Accessible name', type: 'string', defaultValue: 'Loading' },
],
current: { 'aria-label': 'Loading example' },
preview: { 'aria-label': 'Loading preview' },
read: (element) => element.getAttribute('aria-label'),
rendered: 'Loading example',
previewed: 'Loading preview',
},
];
Loading
Loading