Skip to content

The open alternative to Salesforce, designed for AI.

Simplify Chip content and interaction (#27648)

Raphaël Bosid385e26837c9
diff --git a/packages/twenty-docs/snippets/ui/generated/data-display/chip.mdx b/packages/twenty-docs/snippets/ui/generated/data-display/chip.mdx
index 30049b6fb2a..333dff93bfd 100644
--- a/packages/twenty-docs/snippets/ui/generated/data-display/chip.mdx
+++ b/packages/twenty-docs/snippets/ui/generated/data-display/chip.mdx
@@ -12,54 +12,39 @@
*/}
<ParamField body="alwaysShowTooltip" type="boolean" default="false">
- Shows the string-label tooltip even when the label is not truncated.
+ Shows the content tooltip even when the content is not truncated.
+</ParamField>
+
+<ParamField body="children" type="ReactNode">
+ Caller-owned content. Missing or empty children add no fallback label.
</ParamField>
<ParamField body="clickable" type="boolean" default="isDefined(onClick)">
- Enables hover and pointer styling. Defaults to whether `onClick` is supplied; does not add button semantics by itself.
+ Enables hover and pointer styling. Defaults to whether `onClick` is supplied; does not change the default div or add keyboard behavior.
</ParamField>
<ParamField body="color" type="&quot;primary&quot; | &quot;secondary&quot;" default="primary">
Primary or secondary text color.
</ParamField>
-<ParamField body="disabled" type="boolean" default="false">
- Applies disabled styling and disables activation when `onClick` is supplied.
-</ParamField>
-
-<ParamField body="emptyLabel" type="string" default="Untitled">
- Placeholder shown when children are missing, empty, or false, unless `forceEmptyText` is enabled.
-</ParamField>
-
<ParamField body="endElement" type="ReactNode">
- Content after the label. Avoid interactive content when the chip itself is a button.
+ Content after the label. Avoid interactive content when the chip itself is a button or link.
</ParamField>
<ParamField body="endElementDivider" type="boolean" default="false">
Adds a divider before `endElement` when that slot has content.
</ParamField>
-<ParamField body="forceEmptyText" type="boolean" default="false">
- Suppresses the empty label when children are missing, empty, or false.
-</ParamField>
-
-<ParamField body="isLabelHidden" type="boolean" default="false">
- Hides the label while keeping the start and end elements. Supply an accessible name for an interactive chip.
+<ParamField body="isTooltipMultiline" type="boolean">
+ Preserves line breaks in the tooltip text.
</ParamField>
<ParamField body="maxWidth" type="number">
- Maximum chip width in pixels, used to constrain and truncate the label.
-</ParamField>
-
-<ParamField body="nativeButton" type="boolean" default="true">
- Set to `false` when a clickable chip uses `render` with an element other than a native button.
+ Maximum chip width in pixels, used to constrain the content.
</ParamField>
<ParamField body="render" type="ReactElement&lt;unknown, string | JSXElementConstructor&lt;any&gt;&gt; | ComponentRenderFn&lt;HTMLProps, {}&gt;">
- Allows you to replace the component's HTML element
- with a different tag, or compose it with another component.
-
- Accepts a `ReactElement` or a function that returns the element to render.
+ Replaces the default div. Compose a native button or link explicitly; that owner supplies disabled and native interaction behavior.
</ParamField>
<ParamField body="shape" type="&quot;round&quot; | &quot;square&quot;" default="square">
@@ -74,12 +59,20 @@
Content before the label, such as an avatar or icon.
</ParamField>
-<ParamField body="tooltipLabel" type="string">
- Tooltip content for a string label. Defaults to the label text.
+<ParamField body="tooltipContent" type="string">
+ Tooltip text. Defaults to string children. Supply text explicitly for node content.
+</ParamField>
+
+<ParamField body="tooltipDelay" type="number">
+ Delay in milliseconds before the tooltip opens.
</ParamField>
<ParamField body="tooltipPlace" type="&quot;bottom&quot; | &quot;inline-end&quot; | &quot;inline-start&quot; | &quot;left&quot; | &quot;right&quot; | &quot;top&quot;">
- Position of the string-label tooltip.
+ Position of the content tooltip.
+</ParamField>
+
+<ParamField body="truncate" type="boolean" default="true">
+ Truncates overflowing content with an ellipsis. Defaults to true.
</ParamField>
<ParamField body="variant" type="&quot;ghost&quot; | &quot;soft&quot; | &quot;solid&quot;" default="ghost">
@@ -87,5 +80,5 @@
</ParamField>
<ParamField body="weight" type="&quot;medium&quot; | &quot;regular&quot;" default="regular">
- Font weight of the label.
+ Font weight of the content.
</ParamField>
diff --git a/packages/twenty-docs/ui/primitives/data-display/chip.mdx b/packages/twenty-docs/ui/primitives/data-display/chip.mdx
index 25b0fe5f490..4a58900c300 100644
--- a/packages/twenty-docs/ui/primitives/data-display/chip.mdx
+++ b/packages/twenty-docs/ui/primitives/data-display/chip.mdx
@@ -1,6 +1,6 @@
---
title: Chip
-description: Show a compact record label with optional leading and trailing content.
+description: Show compact caller-owned content with optional leading and trailing slots.
---
import { StoryEmbed } from '/snippets/ui/StoryEmbed.mdx';
@@ -14,7 +14,7 @@ Use `Chip` for compact references to people, records, or files. Use [Tag](/ui/pr
title="Chip example"
/>
-## Record label
+## Content and slots
```tsx
import { Avatar, Chip } from 'twenty-ui/primitives/data-display';
@@ -31,17 +31,26 @@ export const AssigneeChip = () => (
);
```
-Use `startElement` and `endElement` for avatars, icons, or other content. `endElementDivider` adds a separator before the trailing content. The default chip is a `div`; its slots can contain an action when the chip itself is not interactive.
+Children accept text or nodes. `startElement` and `endElement` accept avatars, icons, or other content. `endElementDivider` adds a separator before the trailing content. The default chip is a `div`; its slots can contain a separate action while the chip itself remains presentational.
-## Open a record
+Chip never inserts a label. Supply a translated fallback from your application when needed. Omit children for content made entirely from slots. An interactive chip with only an icon needs a caller-supplied accessible name.
+
+## Buttons and links
```tsx
import { Avatar, Chip } from 'twenty-ui/primitives/data-display';
-type AssigneeActionProps = { onOpenAssignee: () => void };
+type AssigneeActionProps = {
+ onOpenAssignee: () => void;
+ disabled?: boolean;
+};
-export const AssigneeAction = ({ onOpenAssignee }: AssigneeActionProps) => (
+export const AssigneeAction = ({
+ onOpenAssignee,
+ disabled,
+}: AssigneeActionProps) => (
<Chip
+ render={<button type="button" disabled={disabled} />}
onClick={onOpenAssignee}
aria-label="Open Jane's record"
startElement={
@@ -53,25 +62,39 @@ export const AssigneeAction = ({ onOpenAssignee }: AssigneeActionProps) => (
);
```
-`onClick` renders a button with keyboard activation. `clickable` controls hover and pointer styling only; setting it alone does not create a button or add an action. `disabled` prevents activation of the button. Do not nest buttons or links inside an interactive chip.
+Supplying `onClick` keeps the default `div`. Use `render` to compose an explicit native button, anchor, router link, or another appropriate owner. Native attributes, handlers, styles and the root ref reach that owner. A native button supplies keyboard activation and disabled behavior. Chip recognizes native disabled state and `aria-disabled` for appearance; `aria-disabled` alone does not prevent activation.
+
+`clickable` controls hover and pointer appearance and defaults to whether `onClick` is supplied. Set it explicitly for a link without a click handler. Do not nest buttons or links inside a chip that is itself interactive.
+
+```tsx
+import { Chip } from 'twenty-ui/primitives/data-display';
+
+export const DocumentationChip = () => (
+ <Chip render={<a href="https://twenty.com/developers" />} clickable>
+ Documentation
+ </Chip>
+);
+```
-Use `render` to replace the root element. If an `onClick` chip renders a non-button element, set `nativeButton={false}`. When `isLabelHidden` hides the label, give an interactive chip an `aria-label`.
+URL text remains plain text. Intentional links belong in caller content or in the explicit root composition.
-## Width and empty labels
+## Truncation and tooltips
```tsx
import { Chip } from 'twenty-ui/primitives/data-display';
export const FileChip = () => (
- <Chip variant="soft" maxWidth={180}>
+ <Chip variant="soft" maxWidth={180} tooltipPlace="top">
Quarterly customer research.pdf
</Chip>
);
```
-`maxWidth` constrains the chip in pixels. String labels truncate and show their full text in a tooltip on hover. `tooltipLabel` changes the tooltip text; `alwaysShowTooltip` also enables it when the label fits. Keep essential information available without relying on hover.
+`maxWidth` constrains the chip in pixels. Content truncates with an ellipsis by default; `truncate={false}` leaves it unconstrained by truncation. String children supply their own tooltip text. Set `tooltipContent` for custom text or node content, `tooltipDelay` for the opening delay, and `isTooltipMultiline` to preserve line breaks. `alwaysShowTooltip` also enables the tooltip when content fits. These options follow [OverflowingTextWithTooltip](/ui/primitives/typography/overflowing-text-with-tooltip). Keep essential information available without relying on hover.
+
+## Migration
-Missing, empty-string, or `false` children show `emptyLabel`, which defaults to `Untitled`. `forceEmptyText` suppresses that placeholder. `isLabelHidden` hides both the content label and the placeholder while preserving the slots.
+Replace `emptyLabel` with caller-provided fallback children, and replace `forceEmptyText` or `isLabelHidden` with omitted children. Keep translated product fallbacks in the application. Replace `tooltipLabel` with `tooltipContent`. Move `disabled` to the explicit interactive owner and remove `nativeButton`. Add a native button or link through `render` wherever the chip previously relied on `onClick` to choose its element.
## Appearance
diff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
index 7e17eceb8ac..cb0e984ea64 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx
@@ -35,7 +35,6 @@ import {
resetFrontComponentStoryMocks,
} from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
import { type TwentyUiGalleryStory as Story } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryStory';
-import { chipControlsTest } from '@/__stories__/twenty-ui-gallery/utils/displayControlTests';
import { statusControlsTest } from '@/__stories__/twenty-ui-gallery/utils/statusControlsTest';
import { tagControlsTest } from '@/__stories__/twenty-ui-gallery/utils/tagControlsTest';
import { PortalBoundsDecorator } from '@/__stories__/twenty-ui-gallery/components/PortalBoundsDecorator';
@@ -66,6 +65,7 @@ import { avatarImageTest } from '@/__stories__/twenty-ui-gallery/utils/avatarIma
import { avatarControlsTest } from '@/__stories__/twenty-ui-gallery/utils/avatarControlsTest';
import { commandBlockTest } from '@/__stories__/twenty-ui-gallery/utils/commandBlockTest';
import { calloutTest } from '@/__stories__/twenty-ui-gallery/utils/calloutTest';
+import { chipControlsTest } from '@/__stories__/twenty-ui-gallery/utils/chipControlsTest';
import { cardCompositionTest } from '@/__stories__/twenty-ui-gallery/utils/cardCompositionTest';
const meta: Meta<typeof FrontComponentRenderer> = {
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
index 83f716123ca..83d3a0dcf6c 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/README.md
@@ -7,7 +7,7 @@ Preact stories need Preact 11, which passes `ref` to function components as a
regular prop like React 19. Preact 10 hands that ref to the component instance,
so Dropdown-based popups never open there.
The field-controls fixture checks native input/textarea refs and change targets, typed textarea render composition, Field labels and controlled multiline value updates in React and Preact.
-Textarea auto-resize growth and shrinking remain known renderer failures. Geometry reads use cached host snapshots, so resetting inline height and reading scrollHeight in the same turn cannot measure the updated layout. The growth failure also reproduces with main's unchanged Textarea. The fixture pins them with the existing known-failure helper; these assertions do not count as resize acceptance. Standalone Textarea browser checks pass.
+Textarea auto-resize remains a renderer limitation. Geometry reads use cached host snapshots, so resetting inline height and reading scrollHeight in the same turn cannot measure the updated layout. These stale reads can also produce cumulative height growth instead of fitting the current content. The field fixture verifies values, refs, events and accessibility without treating incidental height changes as resize acceptance. Standalone Textarea browser checks pass.
Popover composes Portal, Positioner, Popup, Arrow and Viewport. Its focused React/Preact cases check controlled trigger requests, native attributes, Button render composition, DOM refs and callback reasons. These checks do not establish popup visibility, geometry or dismissal support. The omitted-container popup still requires C04/C05/C07 renderer acceptance.
@@ -226,3 +226,12 @@ levels, description line limits and optional focus, code semantics, native
handlers, refs, and element/callback render composition. Description popup
visibility and dismissal in the sandbox remain part of the existing portal and
geometry acceptance work; standalone Section stories verify those behaviors.
+
+Chip controls check caller-owned empty, fallback and node content, stable default
+elements with native handlers, named icon-only buttons, explicit native button
+and link composition, DOM refs, keyboard activation and disabled owners in both
+runtimes. The same fixtures check intentional link content without automatic
+anchors, truncation and custom multiline tooltip content. Escape dismissal is
+checked from an explicit button owner with a native keyboard handler, which
+relays the event to the worker. General document-listener forwarding remains
+part of the renderer's dismissal work.
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-chip-controls.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-chip-controls.front-component.tsx
index cdc2b8adcc9..8dca696ac92 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-chip-controls.front-component.tsx
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-chip-controls.front-component.tsx
@@ -1,7 +1,8 @@
-import { useState } from 'react';
+import { createElement, useState } from 'react';
import { defineFrontComponent } from 'twenty-sdk/define';
import { Chip } from 'twenty-ui/primitives/data-display';
import { IconStar } from 'twenty-ui/icon';
+import { Text } from 'twenty-ui/primitives/typography';
import { ThemeProvider } from 'twenty-ui/theme';
import 'twenty-ui/style.css';
@@ -9,6 +10,9 @@ import { ComponentGallery } from '../shared/front-components/component-gallery';
const ChipControls = () => {
const [activations, setActivations] = useState(0);
+ const [nativeClicks, setNativeClicks] = useState(0);
+ const [linkFocuses, setLinkFocuses] = useState(0);
+ const [lastKey, setLastKey] = useState('');
const handleClick = () => setActivations((count) => count + 1);
return (
<ThemeProvider colorScheme="light">
@@ -16,26 +20,112 @@ const ChipControls = () => {
title="Chip controls"
entries={[
{
- name: 'Chip',
+ name: 'Chip interaction',
node: (
<>
<Chip
+ render={<button type="button" />}
onClick={handleClick}
+ onKeyDown={(event) => setLastKey(event.key)}
variant="soft"
- startElement={<IconStar />}
+ startElement={<IconStar size={14} aria-hidden />}
+ ref={(element) => {
+ element?.setAttribute('data-ref-target', 'chip-button');
+ }}
>
Open chip
</Chip>
- <Chip onClick={handleClick} disabled>
+ <Chip
+ render={<button type="button" disabled />}
+ onClick={handleClick}
+ >
Disabled chip
</Chip>
- <Chip shape="round">Static chip</Chip>
+ <Chip
+ shape="round"
+ onClick={() => setNativeClicks((count) => count + 1)}
+ data-testid="static-chip"
+ ref={(element) => {
+ element?.setAttribute('data-ref-target', 'chip-div');
+ }}
+ >
+ Static chip
+ </Chip>
+ <Chip
+ render={<button type="button" aria-label="Star record" />}
+ onClick={handleClick}
+ >
+ <IconStar size={14} aria-hidden />
+ </Chip>
+ </>
+ ),
+ },
+ {
+ name: 'Chip content',
+ node: (
+ <>
+ <Chip data-testid="empty-chip" />
+ <Chip>Unnamed record</Chip>
+ <Chip
+ startElement={<Text render={<span />}>Start slot</Text>}
+ endElement={<Text render={<span />}>End slot</Text>}
+ endElementDivider
+ >
+ <Text render={<strong />}>Node content</Text>
+ </Chip>
+ </>
+ ),
+ },
+ {
+ name: 'Chip links',
+ node: (
+ <>
+ <Chip
+ render={(renderProps) =>
+ createElement('a', {
+ ...renderProps,
+ href: '#chip-documentation',
+ 'data-composed': 'chip-link',
+ })
+ }
+ aria-label="Chip documentation"
+ ref={(element) => {
+ element?.setAttribute('data-ref-target', 'chip-link');
+ }}
+ onFocus={() => setLinkFocuses((count) => count + 1)}
+ >
+ https://twenty.com/docs/chip
+ </Chip>
+ <Chip aria-label="Plain chip URL">https://twenty.com</Chip>
+ <Chip>
+ <a href="#chip-content">Caller supplied link</a>
+ </Chip>
+ </>
+ ),
+ },
+ {
+ name: 'Chip truncation',
+ node: (
+ <>
+ <Chip
+ maxWidth={140}
+ tooltipContent={'Caller supplied details\nFull account name'}
+ tooltipDelay={0}
+ tooltipPlace="top"
+ isTooltipMultiline
+ >
+ A long account name that truncates inside a chip
+ </Chip>
+ <Chip truncate={false}>Untruncated chip content</Chip>
</>
),
},
]}
/>
<output aria-label="Activations">{activations}</output>
+ <output aria-label="Native chip clicks">{nativeClicks}</output>
+ <output aria-label="Chip link focuses">{linkFocuses}</output>
+ <output aria-label="Last chip key">{lastKey}</output>
</ThemeProvider>
);
};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/chipControlsTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/chipControlsTest.ts
new file mode 100644
index 00000000000..ac04d489365
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/chipControlsTest.ts
@@ -0,0 +1,119 @@
+import { expect, userEvent, waitFor, within } from 'storybook/test';
+
+import { errorHandler } from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';
+import { INTERACTION_TIMEOUT } from '@/__stories__/shared/test-utils/timeouts';
+import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
+import { galleryRenderTest } from '@/__stories__/twenty-ui-gallery/utils/galleryRenderTests';
+
+const OVERFLOW_LABEL = 'A long account name that truncates inside a chip';
+const TOOLTIP_CONTENT = 'Caller supplied details\nFull account name';
+
+export const chipControlsTest: TwentyUiGalleryPlayFunction = async (
+ context,
+) => {
+ await galleryRenderTest(context);
+ const user = userEvent.setup();
+ const canvas = within(context.canvasElement);
+ const page = within(context.canvasElement.ownerDocument.body);
+
+ const staticChip = canvas.getByTestId('static-chip');
+ expect(staticChip.tagName).toBe('DIV');
+ expect(staticChip).toHaveAttribute('data-ref-target', 'chip-div');
+ expect(staticChip).not.toHaveAttribute('role');
+ expect(staticChip).not.toHaveAttribute('tabindex');
+ await user.click(staticChip);
+ await waitFor(() =>
+ expect(canvas.getByLabelText('Native chip clicks')).toHaveTextContent('1'),
+ );
+ expect(staticChip.tagName).toBe('DIV');
+ expect(canvas.getByTestId('empty-chip').textContent).toBe('');
+ expect(canvas.queryByText('Untitled')).not.toBeInTheDocument();
+ expect(canvas.getByText('Unnamed record')).toBeVisible();
+ expect(canvas.getByText('Start slot')).toBeVisible();
+ expect(canvas.getByText('End slot')).toBeVisible();
+ expect(canvas.getByText('Node content').tagName).toBe('STRONG');
+
+ const button = canvas.getByRole('button', { name: 'Open chip' });
+ expect(button.tagName).toBe('BUTTON');
+ expect(button).toHaveAttribute('type', 'button');
+ expect(button).toHaveAttribute('data-ref-target', 'chip-button');
+ await user.click(button);
+ button.focus();
+ await user.keyboard('{Enter} ');
+ await waitFor(() =>
+ expect(canvas.getByLabelText('Activations')).toHaveTextContent('3'),
+ );
+ expect(button).toHaveFocus();
+ const disabledButton = canvas.getByRole('button', { name: 'Disabled chip' });
+ expect(disabledButton).toBeDisabled();
+ await user.click(disabledButton);
+ expect(canvas.getByLabelText('Activations')).toHaveTextContent('3');
+
+ const iconOnlyButton = canvas.getByRole('button', { name: 'Star record' });
+ expect(iconOnlyButton.textContent).toBe('');
+ button.focus();
+ await user.tab();
+ expect(iconOnlyButton).toHaveFocus();
+ await user.click(iconOnlyButton);
+ await waitFor(() =>
+ expect(canvas.getByLabelText('Activations')).toHaveTextContent('4'),
+ );
+
+ const link = canvas.getByRole('link', { name: 'Chip documentation' });
+ expect(link.tagName).toBe('A');
+ expect(link).toHaveAttribute('href', '#chip-documentation');
+ expect(link).toHaveAttribute('data-composed', 'chip-link');
+ expect(link).toHaveAttribute('data-ref-target', 'chip-link');
+ expect(link.querySelector('a')).toBeNull();
+ link.focus();
+ expect(link).toHaveFocus();
+ await waitFor(() =>
+ expect(canvas.getByLabelText('Chip link focuses')).toHaveTextContent('1'),
+ );
+ expect(canvas.getByLabelText('Plain chip URL').querySelector('a')).toBeNull();
+ expect(
+ canvas.getByRole('link', { name: 'Caller supplied link' }),
+ ).toHaveAttribute('href', '#chip-content');
+ expect(
+ getComputedStyle(canvas.getByText('Untruncated chip content')).textOverflow,
+ ).not.toBe('ellipsis');
+
+ const overflowingLabel = canvas.getByText(OVERFLOW_LABEL);
+ await waitFor(
+ () => {
+ expect(getComputedStyle(overflowingLabel).textOverflow).toBe('ellipsis');
+ expect(overflowingLabel.scrollWidth).toBeGreaterThan(
+ overflowingLabel.clientWidth,
+ );
+ },
+ { timeout: INTERACTION_TIMEOUT },
+ );
+ await waitFor(
+ async () => {
+ await user.unhover(overflowingLabel);
+ await user.hover(overflowingLabel);
+ expect(overflowingLabel).toHaveAttribute('data-content-overflowing');
+ },
+ { timeout: INTERACTION_TIMEOUT },
+ );
+ await user.unhover(overflowingLabel);
+ await user.hover(overflowingLabel);
+ await waitFor(
+ () => {
+ const tooltip = page.getByRole('tooltip');
+ expect(tooltip.textContent).toBe(TOOLTIP_CONTENT);
+ expect(tooltip).toBeVisible();
+ expect(getComputedStyle(tooltip).whiteSpace).toBe('pre-wrap');
+ },
+ { timeout: INTERACTION_TIMEOUT },
+ );
+ button.focus();
+ await user.keyboard('{Escape}');
+ await waitFor(() =>
+ expect(canvas.getByLabelText('Last chip key')).toHaveTextContent('Escape'),
+ );
+ await waitFor(() =>
+ expect(page.queryByRole('tooltip')).not.toBeInTheDocument(),
+ );
+ expect(errorHandler).not.toHaveBeenCalled();
+};
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/displayControlTests.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/displayControlTests.ts
deleted file mode 100644
index c3bdda8127c..00000000000
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/displayControlTests.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { expect, userEvent, waitFor, within } from 'storybook/test';
-
-import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
-import { galleryRenderTest } from '@/__stories__/twenty-ui-gallery/utils/galleryRenderTests';
-
-type CreateDisplayControlTestOptions = {
- buttonName: string;
- disabledButtonName: string;
- staticContent: string;
- checkGallery?: TwentyUiGalleryPlayFunction;
-};
-
-const createDisplayControlTest =
- ({
- buttonName,
- disabledButtonName,
- staticContent,
- checkGallery = galleryRenderTest,
- }: CreateDisplayControlTestOptions): TwentyUiGalleryPlayFunction =>
- async (context) => {
- await checkGallery(context);
- const canvas = within(context.canvasElement);
- await expect(canvas.getByText(staticContent)).toBeVisible();
- const button = canvas.getByRole('button', { name: buttonName });
- await userEvent.click(button);
- await waitFor(() =>
- expect(canvas.getByLabelText('Activations')).toHaveTextContent('1'),
- );
- await userEvent.keyboard('{Enter}');
- await waitFor(() =>
- expect(canvas.getByLabelText('Activations')).toHaveTextContent('2'),
- );
- await userEvent.keyboard(' ');
- await waitFor(() =>
- expect(canvas.getByLabelText('Activations')).toHaveTextContent('3'),
- );
- await expect(button).toHaveFocus();
- const disabledButton = canvas.getByRole('button', {
- name: disabledButtonName,
- });
- await expect(disabledButton).toBeDisabled();
- await userEvent.click(disabledButton);
- await expect(canvas.getByLabelText('Activations')).toHaveTextContent('3');
- };
-
-export const chipControlsTest = createDisplayControlTest({
- buttonName: 'Open chip',
- disabledButtonName: 'Disabled chip',
- staticContent: 'Static chip',
-});
diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/fieldControlsTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/fieldControlsTest.ts
index 6eed3c0787e..d41cb157541 100644
--- a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/fieldControlsTest.ts
+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/fieldControlsTest.ts
@@ -2,7 +2,6 @@ import { errorHandler } from '@/__stories__/shared/test-utils/createFrontCompone
import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';
import { TYPING_DELAY } from '@/__stories__/shared/test-utils/timeouts';
import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';
-import { expectAssertionToKeepFailing } from '@/__stories__/twenty-ui-gallery/utils/expectAssertionToKeepFailing';
import { expect, userEvent, waitFor, within } from 'storybook/test';
export const fieldControlsTest: TwentyUiGalleryPlayFunction = async ({
@@ -63,17 +62,9 @@ export const fieldControlsTest: TwentyUiGalleryPlayFunction = async ({
);
expect(notes.tagName).toBe('TEXTAREA');
expect(notes).toHaveAttribute('data-filled');
- const editedHeight = notes.clientHeight;
await userEvent.click(canvas.getByRole('button', { name: 'Apply notes' }));
await waitFor(() => expect(notes).toHaveValue('First\nSecond\nThird'));
- await expectAssertionToKeepFailing(() =>
- expect(notes.clientHeight).toBeGreaterThan(editedHeight),
- );
- const multilineHeight = notes.clientHeight;
await userEvent.click(canvas.getByRole('button', { name: 'Clear notes' }));
await waitFor(() => expect(notes).toHaveValue(''));
- await expectAssertionToKeepFailing(() =>
- expect(notes.clientHeight).toBeLessThan(multilineHeight),
- );
expect(errorHandler).not.toHaveBeenCalled();
};
diff --git a/packages/twenty-front/src/modules/ai/components/ChatReferenceChip.tsx b/packages/twenty-front/src/modules/ai/components/ChatReferenceChip.tsx
index b04e5690870..8eddd66e57c 100644
--- a/packages/twenty-front/src/modules/ai/components/ChatReferenceChip.tsx
+++ b/packages/twenty-front/src/modules/ai/components/ChatReferenceChip.tsx
@@ -1,5 +1,5 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { LinkChip } from '@/ui/navigation/link/components/LinkChip/LinkChip';
-import { t } from '@lingui/core/macro';
import { useContext } from 'react';
import { isDefined } from 'twenty-shared/utils';
import { Chip } from 'twenty-ui/primitives/data-display';
@@ -22,25 +22,20 @@ export const ChatReferenceChip = ({ reference }: ChatReferenceChipProps) => {
if (!isDefined(target.to) || !isNavigationEnabled) {
return (
- <Chip
- emptyLabel={t`Untitled`}
- variant="soft"
- startElement={target.leftComponent}
- >
- {reference.displayName}
+ <Chip variant="soft" startElement={target.leftComponent}>
+ {getChipLabel(reference.displayName).content}
</Chip>
);
}
return (
<LinkChip
- emptyLabel={t`Untitled`}
to={target.to}
onClick={target.onClick}
variant="soft"
startElement={target.leftComponent}
>
- {reference.displayName}
+ {getChipLabel(reference.displayName).content}
</LinkChip>
);
};
diff --git a/packages/twenty-front/src/modules/ai/components/ToolRecordsWidget.tsx b/packages/twenty-front/src/modules/ai/components/ToolRecordsWidget.tsx
index 803d5222841..970f42dc241 100644
--- a/packages/twenty-front/src/modules/ai/components/ToolRecordsWidget.tsx
+++ b/packages/twenty-front/src/modules/ai/components/ToolRecordsWidget.tsx
@@ -1,3 +1,4 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { styled } from '@linaria/react';
import { useLingui } from '@lingui/react/macro';
@@ -73,7 +74,7 @@ export const ToolRecordsWidget = ({
})}
startElement={isDefined(Icon) ? <Icon size={14} /> : undefined}
>
- {recordReference.displayName}
+ {getChipLabel(recordReference.displayName).content}
</LinkChip>
);
})}
diff --git a/packages/twenty-front/src/modules/ai/components/internal/AgentChatFilePreview.tsx b/packages/twenty-front/src/modules/ai/components/internal/AgentChatFilePreview.tsx
index 38f4bb1a2a5..041b7b760db 100644
--- a/packages/twenty-front/src/modules/ai/components/internal/AgentChatFilePreview.tsx
+++ b/packages/twenty-front/src/modules/ai/components/internal/AgentChatFilePreview.tsx
@@ -1,3 +1,4 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { type AttachmentFileCategory } from '@/activities/files/types/AttachmentFileCategory';
import { getFileType } from '@/activities/files/utils/getFileType';
import { useFileCategoryColors } from '@/file/hooks/useFileCategoryColors';
@@ -14,13 +15,32 @@ import { isDefined } from 'twenty-shared/utils';
import { type IconComponent, IconX } from 'twenty-ui/icon';
import { Chip } from 'twenty-ui/primitives/data-display';
import { Loader } from 'twenty-ui/primitives/feedback';
-import { useTheme } from 'twenty-ui/theme';
+import { OverflowingTextWithTooltip } from 'twenty-ui/primitives/typography';
+import { themeCssVariables, useTheme } from 'twenty-ui/theme';
-const StyledClickableContainer = styled.div<{ clickable: boolean }>`
- cursor: ${({ clickable }: { clickable: boolean }) =>
- clickable ? 'pointer' : 'inherit'};
+const StyledPreviewButton = styled.button`
+ align-items: center;
+ background: transparent;
+ border: 0;
+ border-radius: ${themeCssVariables.border.radius.sm};
+ color: inherit;
+ cursor: pointer;
display: inline-flex;
+ font: inherit;
+ gap: ${themeCssVariables.spacing[1]};
+ max-width: 100%;
min-width: 0;
+ padding: 0;
+ vertical-align: middle;
+
+ &:focus-visible {
+ outline: 2px solid ${themeCssVariables.color.blue};
+ outline-offset: -1px;
+ }
+
+ &:disabled {
+ cursor: inherit;
+ }
`;
export const AgentChatFilePreview = ({
@@ -40,6 +60,8 @@ export const AgentChatFilePreview = ({
const fileName =
file instanceof File ? file.name : (file.filename ?? t`Unknown file`);
+ const { text: displayName, content } = getChipLabel(fileName);
+
const fileUrl = file instanceof File ? undefined : file.url;
const fileId = file instanceof File ? undefined : file.fileId;
@@ -73,9 +95,10 @@ export const AgentChatFilePreview = ({
);
const rightComponent = onRemove ? (
- <div onClick={(e) => e.stopPropagation()}>
+ <div onClick={(event) => event.stopPropagation()}>
<AvatarOrIcon
Icon={IconX}
+ name={t`Remove ${displayName}`}
IconColor={theme.font.color.secondary}
onClick={onRemove}
/>
@@ -86,19 +109,25 @@ export const AgentChatFilePreview = ({
const isClickable = isDefined(fileUrl) && isDefined(fileId);
return (
- <StyledClickableContainer
- clickable={isClickable}
- onClick={isClickable ? handleClick : undefined}
- >
- <Chip
- emptyLabel={t`Untitled`}
- variant="soft"
- startElement={leftComponent}
- endElement={rightComponent}
- endElementDivider={hasRightDivider}
- >
- {fileName}
- </Chip>
- </StyledClickableContainer>
+ <Chip
+ variant="soft"
+ startElement={
+ <StyledPreviewButton
+ type="button"
+ disabled={!isClickable}
+ onClick={handleClick}
+ >
+ {leftComponent}
+ <OverflowingTextWithTooltip
+ render={<span />}
+ text={content}
+ tooltipContent={displayName}
+ style={{ minWidth: 0 }}
+ />
+ </StyledPreviewButton>
+ }
+ endElement={rightComponent}
+ endElementDivider={hasRightDivider}
+ />
);
};
diff --git a/packages/twenty-front/src/modules/ai/components/internal/__stories__/AgentChatFilePreview.interactions.stories.tsx b/packages/twenty-front/src/modules/ai/components/internal/__stories__/AgentChatFilePreview.interactions.stories.tsx
new file mode 100644
index 00000000000..f6ac4dfc7b0
--- /dev/null
+++ b/packages/twenty-front/src/modules/ai/components/internal/__stories__/AgentChatFilePreview.interactions.stories.tsx
@@ -0,0 +1,85 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { expect, fn, userEvent, within } from 'storybook/test';
+import { Button } from 'twenty-ui/primitives/input';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+import { AgentChatFilePreview } from '@/ai/components/internal/AgentChatFilePreview';
+import { filePreviewState } from '@/ui/field/display/states/filePreviewState';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';
+
+const FILE_NAME = 'Quarterly-account-archive-and-final-contract.pdf';
+
+const meta: Meta<typeof AgentChatFilePreview> = {
+ title: 'Modules/AI/AgentChatFilePreview/Interactions',
+ component: AgentChatFilePreview,
+ decorators: [ComponentDecorator, ObjectMetadataItemsDecorator],
+ args: {
+ file: {
+ type: 'file',
+ filename: FILE_NAME,
+ mediaType: 'application/pdf',
+ url: 'https://example.com/contract.pdf',
+ fileId: 'contract-file-id',
+ },
+ onRemove: fn(),
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof AgentChatFilePreview>;
+
+const PreviewStateProbe = () => {
+ const filePreview = useAtomStateValue(filePreviewState);
+
+ return (
+ <output aria-label="File preview">
+ {filePreview?.label ?? 'No preview'}
+ </output>
+ );
+};
+
+export const TruncatedPreviewWithRemoval: Story = {
+ render: (args) => (
+ <>
+ <Button>Before preview</Button>
+ <div style={{ width: 160 }}>
+ <AgentChatFilePreview {...args} />
+ </div>
+ <PreviewStateProbe />
+ </>
+ ),
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ const user = userEvent.setup();
+ const previewButton = await canvas.findByRole('button', {
+ name: FILE_NAME,
+ });
+ const removeButton = canvas.getByRole('button', {
+ name: `Remove ${FILE_NAME}`,
+ });
+ const label = within(previewButton).getByText(FILE_NAME);
+
+ expect(previewButton.querySelector('button')).toBeNull();
+ expect(label.scrollWidth).toBeGreaterThan(label.clientWidth);
+ await user.hover(label);
+ expect(await body.findByRole('tooltip')).toHaveTextContent(FILE_NAME);
+ await user.unhover(label);
+ await user.click(canvas.getByRole('button', { name: 'Before preview' }));
+ await user.tab();
+ expect(previewButton).toHaveFocus();
+ await user.tab();
+ expect(removeButton).toHaveFocus();
+ await user.keyboard('{Enter}');
+ expect(args.onRemove).toHaveBeenCalledTimes(1);
+ expect(
+ canvas.getByRole('status', { name: 'File preview' }),
+ ).toHaveTextContent('No preview');
+ await user.click(previewButton);
+ expect(
+ canvas.getByRole('status', { name: 'File preview' }),
+ ).toHaveTextContent(FILE_NAME);
+ expect(args.onRemove).toHaveBeenCalledTimes(1);
+ },
+};
diff --git a/packages/twenty-front/src/modules/blocknote-editor/blocks/MentionInlineContent.tsx b/packages/twenty-front/src/modules/blocknote-editor/blocks/MentionInlineContent.tsx
index 44e62d350f2..ff5a15fd829 100644
--- a/packages/twenty-front/src/modules/blocknote-editor/blocks/MentionInlineContent.tsx
+++ b/packages/twenty-front/src/modules/blocknote-editor/blocks/MentionInlineContent.tsx
@@ -54,7 +54,7 @@ const LegacyMentionRenderer = ({
return (
<Chip
variant="ghost"
- disabled
+ aria-disabled
style={{ paddingInlineStart: 0 }}
>{t`Unknown object`}</Chip>
);
@@ -64,7 +64,7 @@ const LegacyMentionRenderer = ({
return (
<Chip
variant="ghost"
- disabled
+ aria-disabled
style={{ paddingInlineStart: 0 }}
>{t`Deleted record`}</Chip>
);
diff --git a/packages/twenty-front/src/modules/log-console/components/LogConsoleMemberChip.tsx b/packages/twenty-front/src/modules/log-console/components/LogConsoleMemberChip.tsx
index 2a4346bd735..cc70c7f4feb 100644
--- a/packages/twenty-front/src/modules/log-console/components/LogConsoleMemberChip.tsx
+++ b/packages/twenty-front/src/modules/log-console/components/LogConsoleMemberChip.tsx
@@ -1,4 +1,4 @@
-import { useLingui } from '@lingui/react/macro';
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { isDefined } from 'twenty-shared/utils';
import { Chip } from 'twenty-ui/primitives/data-display';
@@ -14,7 +14,6 @@ type LogConsoleMemberChipProps = {
};
export const LogConsoleMemberChip = (props: LogConsoleMemberChipProps) => {
- const { t } = useLingui();
const member = useLogConsoleMember(props);
if (!isDefined(member)) {
@@ -23,12 +22,11 @@ export const LogConsoleMemberChip = (props: LogConsoleMemberChipProps) => {
return (
<Chip
- emptyLabel={t`Untitled`}
variant="ghost"
startElement={<LogConsoleMemberAvatar member={member} />}
style={{ paddingInlineStart: 0 }}
>
- {member.name ?? ''}
+ {getChipLabel(member.name).content}
</Chip>
);
};
diff --git a/packages/twenty-front/src/modules/mention/components/MentionRecordChip.tsx b/packages/twenty-front/src/modules/mention/components/MentionRecordChip.tsx
index e041a30e4f8..087473fe898 100644
--- a/packages/twenty-front/src/modules/mention/components/MentionRecordChip.tsx
+++ b/packages/twenty-front/src/modules/mention/components/MentionRecordChip.tsx
@@ -1,3 +1,4 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { getLinkToShowPage } from '@/object-metadata/utils/getLinkToShowPage';
import { AvatarOrIcon } from '@/ui/field/display/components/internal/AvatarOrIcon/AvatarOrIcon';
import { LinkChip } from '@/ui/navigation/link/components/LinkChip/LinkChip';
@@ -25,7 +26,7 @@ export const MentionRecordChip = ({
return (
<Chip
variant="ghost"
- disabled
+ aria-disabled
style={{ paddingInlineStart: 0 }}
>{t`Unknown object`}</Chip>
);
@@ -35,7 +36,7 @@ export const MentionRecordChip = ({
return (
<Chip
variant="ghost"
- disabled
+ aria-disabled
style={{ paddingInlineStart: 0 }}
>{t`Deleted record`}</Chip>
);
@@ -47,7 +48,6 @@ export const MentionRecordChip = ({
return (
<LinkChip
- emptyLabel={t`Untitled`}
to={linkToShowPage}
variant="soft"
className={className}
@@ -60,7 +60,7 @@ export const MentionRecordChip = ({
/>
}
>
- {label}
+ {getChipLabel(label).content}
</LinkChip>
);
};
diff --git a/packages/twenty-front/src/modules/object-record/components/RecordChip.tsx b/packages/twenty-front/src/modules/object-record/components/RecordChip.tsx
index f72475fdc34..ecf791bcfee 100644
--- a/packages/twenty-front/src/modules/object-record/components/RecordChip.tsx
+++ b/packages/twenty-front/src/modules/object-record/components/RecordChip.tsx
@@ -1,3 +1,4 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { getLinkToShowPage } from '@/object-metadata/utils/getLinkToShowPage';
import { useRecordChipData } from '@/object-record/hooks/useRecordChipData';
import { useResolveOpenRecordIn } from '@/object-record/record-index/hooks/useResolveOpenRecordIn';
@@ -6,14 +7,13 @@ import { useOpenRecordInSidePanel } from '@/side-panel/hooks/useOpenRecordInSide
import { AvatarOrIcon } from '@/ui/field/display/components/internal/AvatarOrIcon/AvatarOrIcon';
import { LinkChip } from '@/ui/navigation/link/components/LinkChip/LinkChip';
import { type TriggerEventType } from '@/ui/navigation/types/TriggerEventType';
-import { t } from '@lingui/core/macro';
import { type MouseEvent } from 'react';
import { CoreObjectNameSingular, OpenRecordIn } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { Chip, type ChipSize } from 'twenty-ui/primitives/data-display';
import { getAbsoluteImageUrl } from '~/utils/image/getAbsoluteImageUrl';
-export type RecordChipProps = {
+type RecordChipProps = {
objectNameSingular: string;
record: ObjectRecord;
className?: string;
@@ -49,6 +49,8 @@ export const RecordChip = ({
record,
});
+ const { text: label, content } = getChipLabel(recordChipData.name);
+
const { openRecordInSidePanel } = useOpenRecordInSidePanel();
const openRecordIn = useResolveOpenRecordIn(objectNameSingular);
@@ -72,7 +74,6 @@ export const RecordChip = ({
) {
return (
<Chip
- emptyLabel={t`Untitled`}
weight={isBold ? 'medium' : 'regular'}
size={size}
maxWidth={maxWidth}
@@ -90,7 +91,7 @@ export const RecordChip = ({
}
style={{ paddingInlineStart: 0 }}
>
- {recordChipData.name}
+ {isLabelHidden ? undefined : content}
</Chip>
);
}
@@ -99,9 +100,8 @@ export const RecordChip = ({
<LinkChip
size={size}
maxWidth={maxWidth}
- emptyLabel={t`Untitled`}
weight={isBold ? 'medium' : 'regular'}
- isLabelHidden={isLabelHidden}
+ aria-label={isLabelHidden ? label : undefined}
startElement={
isIconHidden ? null : (
<AvatarOrIcon
@@ -120,7 +120,7 @@ export const RecordChip = ({
onClick={handleCustomClick}
triggerEvent={triggerEvent}
>
- {recordChipData.name}
+ {isLabelHidden ? undefined : content}
</LinkChip>
);
};
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/__stories__/perf/ChipFieldDisplay.perf.stories.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/__stories__/perf/ChipFieldDisplay.perf.stories.tsx
index 70dc83a0c9c..a5a5a703f7f 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/__stories__/perf/ChipFieldDisplay.perf.stories.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/display/components/__stories__/perf/ChipFieldDisplay.perf.stories.tsx
@@ -83,7 +83,7 @@ export const Default: Story = {};
export const Performance = getProfilingStory({
componentName: 'ChipFieldDisplay',
- averageThresholdInMs: 0.6,
+ averageThresholdInMs: 1,
numberOfRuns: 20,
numberOfTestsPerRun: 100,
});
diff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FilesFieldMenuItem.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FilesFieldMenuItem.tsx
index e8c6b7596ab..6700c815af2 100644
--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FilesFieldMenuItem.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/FilesFieldMenuItem.tsx
@@ -1,3 +1,4 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { FileIcon } from '@/file/components/FileIcon';
import { type FieldFilesValue } from '@/object-record/record-field/ui/types/FieldMetadata';
import { getFileCategoryFromExtension } from '@/object-record/record-field/ui/utils/getFileCategoryFromExtension';
@@ -40,7 +41,7 @@ export const FilesFieldMenuItem = ({
}
variant="ghost"
>
- {value}
+ {getChipLabel(value).content}
</Chip>
)}
showPrimaryIcon={false}
diff --git a/packages/twenty-front/src/modules/object-record/record-list/components/RecordListRow.tsx b/packages/twenty-front/src/modules/object-record/record-list/components/RecordListRow.tsx
index 6853d1a5528..b58a8e7e7d5 100644
--- a/packages/twenty-front/src/modules/object-record/record-list/components/RecordListRow.tsx
+++ b/packages/twenty-front/src/modules/object-record/record-list/components/RecordListRow.tsx
@@ -226,7 +226,7 @@ export const RecordListRow = ({ recordId, rowRef }: RecordListRowProps) => {
to={linkToRecord}
onClick={openRecord}
triggerEvent="CLICK"
- tooltipLabel={overflowChipTooltipLabel}
+ tooltipContent={overflowChipTooltipLabel}
tooltipPlace={'top'}
alwaysShowTooltip
variant="soft"
@@ -235,7 +235,7 @@ export const RecordListRow = ({ recordId, rowRef }: RecordListRowProps) => {
</LinkChip>
) : (
<Chip
- tooltipLabel={overflowChipTooltipLabel}
+ tooltipContent={overflowChipTooltipLabel}
tooltipPlace={'top'}
alwaysShowTooltip
variant="soft"
diff --git a/packages/twenty-front/src/modules/page-layout/widgets/call-recording-transcript/components/CallRecordingTranscriptEntryListItem.tsx b/packages/twenty-front/src/modules/page-layout/widgets/call-recording-transcript/components/CallRecordingTranscriptEntryListItem.tsx
index d06118ee732..711fcd927c4 100644
--- a/packages/twenty-front/src/modules/page-layout/widgets/call-recording-transcript/components/CallRecordingTranscriptEntryListItem.tsx
+++ b/packages/twenty-front/src/modules/page-layout/widgets/call-recording-transcript/components/CallRecordingTranscriptEntryListItem.tsx
@@ -1,3 +1,4 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { CallRecordingTranscriptEntryWords } from '@/page-layout/widgets/call-recording-transcript/components/CallRecordingTranscriptEntryWords';
import { type CallRecordingTranscriptEntryPlaybackPhase } from '@/page-layout/widgets/call-recording-transcript/types/CallRecordingTranscriptEntryPlaybackPhase';
import { formatCallRecordingTranscriptTimestamp } from '@/page-layout/widgets/call-recording-transcript/utils/formatCallRecordingTranscriptTimestamp';
@@ -136,7 +137,7 @@ export const CallRecordingTranscriptEntryListItem = ({
}
style={{ paddingInlineStart: 0 }}
>
- {speakerName}
+ {getChipLabel(speakerName).content}
</Chip>
{isDefined(formattedStartTimestamp) && (
<StyledTimestamp
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceContent.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceContent.tsx
index 8d14ca3aaa7..3ed865e2d5b 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceContent.tsx
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminWorkspaceContent.tsx
@@ -1,3 +1,4 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { useNumberFormat } from '@/localization/hooks/useNumberFormat';
import { type WorkspaceInfo } from '@/settings/admin-panel/types/WorkspaceInfo';
import { getUpgradeHealthStatusBadge } from '@/settings/admin-panel/utils/getUpgradeHealthStatusBadge';
@@ -75,7 +76,6 @@ export const SettingsAdminWorkspaceContent = ({
label: t`Name`,
value: activeWorkspace?.id ? (
<LinkChip
- emptyLabel={t`Untitled`}
to={getSettingsPath(SettingsPath.AdminPanelWorkspaceDetail, {
workspaceId: activeWorkspace.id,
})}
@@ -89,7 +89,7 @@ export const SettingsAdminWorkspaceContent = ({
/>
}
>
- {activeWorkspace?.name ?? ''}
+ {getChipLabel(activeWorkspace.name).content}
</LinkChip>
) : (
(activeWorkspace?.name ?? '')
diff --git a/packages/twenty-front/src/modules/settings/ai/components/SettingsAiModelHoverCard.tsx b/packages/twenty-front/src/modules/settings/ai/components/SettingsAiModelHoverCard.tsx
index cda2e963277..b1fbd84bc23 100644
--- a/packages/twenty-front/src/modules/settings/ai/components/SettingsAiModelHoverCard.tsx
+++ b/packages/twenty-front/src/modules/settings/ai/components/SettingsAiModelHoverCard.tsx
@@ -1,3 +1,4 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
import { Chip } from 'twenty-ui/primitives/data-display';
@@ -95,7 +96,7 @@ export const SettingsAiModelHoverCard = ({
}
endElement={null}
>
- {model.label}
+ {getChipLabel(model.label).content}
</Chip>
</StyledChipContainer>
),
diff --git a/packages/twenty-front/src/modules/skill-suggestion/components/SkillReferenceChip.tsx b/packages/twenty-front/src/modules/skill-suggestion/components/SkillReferenceChip.tsx
index 136c824d2ec..76b2dbd4d7c 100644
--- a/packages/twenty-front/src/modules/skill-suggestion/components/SkillReferenceChip.tsx
+++ b/packages/twenty-front/src/modules/skill-suggestion/components/SkillReferenceChip.tsx
@@ -1,3 +1,4 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { LinkChip } from '@/ui/navigation/link/components/LinkChip/LinkChip';
import { SettingsPath } from 'twenty-shared/types';
import { getSettingsPath } from 'twenty-shared/utils';
@@ -29,7 +30,7 @@ export const SkillReferenceChip = ({
<Icon size={theme.icon.size.sm} stroke={theme.icon.stroke.sm} />
}
>
- {label}
+ {getChipLabel(label).content}
</LinkChip>
);
};
diff --git a/packages/twenty-front/src/modules/ui/field/display/components/ActorDisplay.tsx b/packages/twenty-front/src/modules/ui/field/display/components/ActorDisplay.tsx
index def38857d3a..850f2cbc06e 100644
--- a/packages/twenty-front/src/modules/ui/field/display/components/ActorDisplay.tsx
+++ b/packages/twenty-front/src/modules/ui/field/display/components/ActorDisplay.tsx
@@ -1,8 +1,8 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { type FieldActorValue } from '@/object-record/record-field/ui/types/FieldMetadata';
import { AvatarOrIcon } from '@/ui/field/display/components/internal/AvatarOrIcon/AvatarOrIcon';
import { getActorSourceIcon } from '@/ui/field/display/utils/getActorSourceIcon';
-import { t } from '@lingui/core/macro';
import { Chip } from 'twenty-ui/primitives/data-display';
import { getAbsoluteImageUrl } from '~/utils/image/getAbsoluteImageUrl';
@@ -21,7 +21,6 @@ export const ActorDisplay = ({
return (
<Chip
- emptyLabel={t`Untitled`}
variant="ghost"
startElement={
<AvatarOrIcon
@@ -34,7 +33,7 @@ export const ActorDisplay = ({
}
style={{ paddingInlineStart: 0 }}
>
- {name ?? ''}
+ {getChipLabel(name).content}
</Chip>
);
};
diff --git a/packages/twenty-front/src/modules/ui/field/display/components/ArrayDisplay.tsx b/packages/twenty-front/src/modules/ui/field/display/components/ArrayDisplay.tsx
index da7e32684d2..dc08bda8cc1 100644
--- a/packages/twenty-front/src/modules/ui/field/display/components/ArrayDisplay.tsx
+++ b/packages/twenty-front/src/modules/ui/field/display/components/ArrayDisplay.tsx
@@ -1,3 +1,4 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { type FieldArrayValue } from '@/object-record/record-field/ui/types/FieldMetadata';
import { OverflowingList } from 'twenty-ui/components/layout';
import { t } from '@lingui/core/macro';
@@ -11,8 +12,8 @@ export const ArrayDisplay = ({ value }: ArrayDisplayProps) => {
return (
<OverflowingList overflowLabel={t`Show all items`}>
{value?.map((item, index) => (
- <Chip key={`${item}-${index}`} variant="soft" emptyLabel={t`Untitled`}>
- {item}
+ <Chip key={`${item}-${index}`} variant="soft">
+ {getChipLabel(item).content}
</Chip>
))}
</OverflowingList>
diff --git a/packages/twenty-front/src/modules/ui/field/display/components/FileChip.tsx b/packages/twenty-front/src/modules/ui/field/display/components/FileChip.tsx
index 9e1a1b85199..08b533cfbf9 100644
--- a/packages/twenty-front/src/modules/ui/field/display/components/FileChip.tsx
+++ b/packages/twenty-front/src/modules/ui/field/display/components/FileChip.tsx
@@ -1,4 +1,3 @@
-import { styled } from '@linaria/react';
import { t } from '@lingui/core/macro';
import { isNonEmptyString } from '@sniptt/guards';
@@ -9,12 +8,6 @@ import { Chip } from 'twenty-ui/primitives/data-display';
const MAX_WIDTH = 120;
-const StyledClickableContainer = styled.div<{ clickable: boolean }>`
- cursor: ${({ clickable }) => (clickable ? 'pointer' : 'inherit')};
- display: inline-flex;
- min-width: 0;
-`;
-
type FileChipProps = {
file: FieldFilesValue;
onClick: (file: FieldFilesValue) => void;
@@ -43,30 +36,41 @@ export const FileChip = ({
onClick?.(file);
};
+ const handleClick = (event: React.MouseEvent): void => {
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (isClickable && event.detail === 0) {
+ onClick(file);
+ }
+ };
+
return (
- <StyledClickableContainer
- clickable={isClickable}
+ <Chip
+ render={
+ forceDisableClick ? undefined : (
+ <button type="button" disabled={isDeleted} />
+ )
+ }
onMouseDown={handleMouseDown}
+ onClick={isClickable ? handleClick : undefined}
+ alwaysShowTooltip={isDeleted}
+ tooltipContent={
+ isDeleted ? t`File no longer exists - ${label}` : undefined
+ }
+ aria-disabled={isDeleted || undefined}
+ maxWidth={MAX_WIDTH}
+ startElement={
+ <FileIcon
+ fileCategory={fileCategory}
+ size="small"
+ thumbnailUrl={isDeleted ? undefined : file.url}
+ />
+ }
+ variant="soft"
+ clickable={isClickable}
>
- <Chip
- alwaysShowTooltip={isDeleted}
- tooltipLabel={
- isDeleted ? t`File no longer exists - ${label}` : undefined
- }
- disabled={isDeleted}
- maxWidth={MAX_WIDTH}
- startElement={
- <FileIcon
- fileCategory={fileCategory}
- size="small"
- thumbnailUrl={isDeleted ? undefined : file.url}
- />
- }
- variant="soft"
- clickable={isClickable}
- >
- {label}
- </Chip>
- </StyledClickableContainer>
+ {label}
+ </Chip>
);
};
diff --git a/packages/twenty-front/src/modules/ui/field/display/components/__stories__/FileChip.interactions.stories.tsx b/packages/twenty-front/src/modules/ui/field/display/components/__stories__/FileChip.interactions.stories.tsx
new file mode 100644
index 00000000000..e82edd2724d
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/field/display/components/__stories__/FileChip.interactions.stories.tsx
@@ -0,0 +1,110 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { type FormEvent } from 'react';
+import { expect, fn, userEvent, within } from 'storybook/test';
+import { FILE_CATEGORIES } from 'twenty-shared/types';
+import { Button } from 'twenty-ui/primitives/input';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+import { FileChip } from '@/ui/field/display/components/FileChip';
+
+const meta: Meta<typeof FileChip> = {
+ title: 'UI/Field/Display/FileChip/Interactions',
+ component: FileChip,
+ decorators: [ComponentDecorator],
+ args: {
+ file: {
+ fileId: 'contract-file-id',
+ label: 'Contract.pdf',
+ extension: 'pdf',
+ fileCategory: FILE_CATEGORIES.TEXT_DOCUMENT,
+ url: 'https://example.com/contract.pdf',
+ },
+ onClick: fn(),
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof FileChip>;
+
+const onParentClick = fn();
+const onFormSubmit = fn((event: FormEvent) => event.preventDefault());
+
+export const NativePreviewButton: Story = {
+ beforeEach: () => {
+ onParentClick.mockClear();
+ onFormSubmit.mockClear();
+ },
+ render: (args) => (
+ <>
+ <Button>Before file</Button>
+ <form onClick={onParentClick} onSubmit={onFormSubmit}>
+ <FileChip {...args} />
+ </form>
+ </>
+ ),
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const user = userEvent.setup();
+ const button = canvas.getByRole('button', { name: 'Contract.pdf' });
+
+ expect(button).toHaveAttribute('type', 'button');
+ await user.click(canvas.getByRole('button', { name: 'Before file' }));
+ await user.tab();
+ expect(button).toHaveFocus();
+ expect(getComputedStyle(button).outlineStyle).toBe('solid');
+ await user.keyboard('{Enter} ');
+ expect(args.onClick).toHaveBeenCalledTimes(2);
+ await user.click(button);
+ expect(args.onClick).toHaveBeenCalledTimes(3);
+ expect(onParentClick).not.toHaveBeenCalled();
+ expect(onFormSubmit).not.toHaveBeenCalled();
+ },
+};
+
+export const DeletedFileIsDisabled: Story = {
+ args: {
+ file: {
+ fileId: 'deleted-file-id',
+ label: 'Deleted contract.pdf',
+ extension: 'pdf',
+ fileCategory: FILE_CATEGORIES.TEXT_DOCUMENT,
+ url: 'https://example.com/contract.pdf',
+ isDeleted: true,
+ },
+ },
+ render: (args) => (
+ <>
+ <Button>Before deleted file</Button>
+ <FileChip {...args} />
+ <Button>After deleted file</Button>
+ </>
+ ),
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const user = userEvent.setup();
+ const button = canvas.getByRole('button', { name: 'Deleted contract.pdf' });
+
+ expect(button).toBeDisabled();
+ await user.click(
+ canvas.getByRole('button', { name: 'Before deleted file' }),
+ );
+ await user.tab();
+ expect(
+ canvas.getByRole('button', { name: 'After deleted file' }),
+ ).toHaveFocus();
+ await user.click(button);
+ expect(args.onClick).not.toHaveBeenCalled();
+ },
+};
+
+export const PresentationalFile: Story = {
+ args: { forceDisableClick: true },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const user = userEvent.setup();
+
+ expect(canvas.queryByRole('button')).not.toBeInTheDocument();
+ await user.click(canvas.getByText('Contract.pdf'));
+ expect(args.onClick).not.toHaveBeenCalled();
+ },
+};
diff --git a/packages/twenty-front/src/modules/ui/field/display/utils/getChipLabel.tsx b/packages/twenty-front/src/modules/ui/field/display/utils/getChipLabel.tsx
new file mode 100644
index 00000000000..158c9588ff1
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/field/display/utils/getChipLabel.tsx
@@ -0,0 +1,24 @@
+import { t } from '@lingui/core/macro';
+import { isNonEmptyString } from '@sniptt/guards';
+import { Text } from 'twenty-ui/primitives/typography';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+export const getChipLabel = (value: string | null | undefined) => {
+ if (isNonEmptyString(value)) {
+ return { text: value, content: value };
+ }
+
+ const text = t`Untitled`;
+
+ return {
+ text,
+ content: (
+ <Text
+ render={<span />}
+ style={{ color: themeCssVariables.font.color.tertiary }}
+ >
+ {text}
+ </Text>
+ ),
+ };
+};
diff --git a/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/LinkChip.tsx b/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/LinkChip.tsx
index c45b0c133eb..797c230c9d7 100644
--- a/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/LinkChip.tsx
+++ b/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/LinkChip.tsx
@@ -14,7 +14,6 @@ const styles = {
vertical-align: middle;
}
& > a {
- max-width: 100%;
min-width: 0;
text-decoration: none;
}
@@ -35,25 +34,35 @@ export const LinkChip = ({
return (
<span className={styles.linkContainer}>
- <Link
- to={to}
- ref={ref}
- onClick={(event) => {
- event.stopPropagation();
- onClickHandler(event);
- }}
- onMouseDown={(event) => {
- onMouseDown?.(event);
- if (!event.defaultPrevented) {
- onMouseDownHandler(event);
- }
- }}
- data-click-outside-id={LINK_CHIP_CLICK_OUTSIDE_ID}
- target={target}
- rel={target === '_blank' ? 'noopener noreferrer' : undefined}
- >
- <Chip clickable {...props} />
- </Link>
+ <Chip
+ clickable
+ {...props}
+ render={
+ <Link
+ to={to}
+ ref={ref}
+ onClick={(event) => {
+ event.stopPropagation();
+ const isKeyboardClick = event.detail === 0;
+
+ if (isKeyboardClick && triggerEvent !== 'CLICK') {
+ onMouseDownHandler(event);
+ }
+
+ onClickHandler(event);
+ }}
+ onMouseDown={(event) => {
+ onMouseDown?.(event);
+ if (!event.defaultPrevented) {
+ onMouseDownHandler(event);
+ }
+ }}
+ data-click-outside-id={LINK_CHIP_CLICK_OUTSIDE_ID}
+ target={target}
+ rel={target === '_blank' ? 'noopener noreferrer' : undefined}
+ />
+ }
+ />
</span>
);
};
diff --git a/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/__stories__/LinkChip.interactions.stories.tsx b/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/__stories__/LinkChip.interactions.stories.tsx
new file mode 100644
index 00000000000..eec72d5505f
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/__stories__/LinkChip.interactions.stories.tsx
@@ -0,0 +1,122 @@
+import { type Meta, type StoryObj } from '@storybook/react-vite';
+import { createRef } from 'react';
+import { MemoryRouter } from 'react-router-dom';
+import { expect, fn, userEvent, within } from 'storybook/test';
+import { IconUser } from 'twenty-ui/icon';
+import { Button } from 'twenty-ui/primitives/input';
+import { ComponentDecorator } from 'twenty-ui/testing';
+
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
+import { LinkChip } from '@/ui/navigation/link/components/LinkChip/LinkChip';
+
+const meta: Meta<typeof LinkChip> = {
+ title: 'UI/Data Display/LinkChip/Interactions',
+ component: LinkChip,
+ decorators: [
+ ComponentDecorator,
+ (Story) => (
+ <MemoryRouter>
+ <Story />
+ </MemoryRouter>
+ ),
+ ],
+};
+
+export default meta;
+type Story = StoryObj<typeof LinkChip>;
+
+const onParentClick = fn();
+const linkRef = createRef<HTMLAnchorElement>();
+const RECORD_NAME =
+ 'A long record name that requires an automatic overflow tooltip';
+
+export const NativeLink: Story = {
+ args: {
+ to: '/records/1',
+ children: 'https://twenty.com',
+ target: '_blank',
+ onClick: fn(),
+ },
+ beforeEach: () => onParentClick.mockClear(),
+ render: (args) => (
+ <>
+ <Button>Before link</Button>
+ <div onClick={onParentClick}>
+ <LinkChip {...args} ref={linkRef} />
+ </div>
+ </>
+ ),
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const user = userEvent.setup();
+ const link = canvas.getByRole('link', { name: 'https://twenty.com' });
+
+ expect(linkRef.current).toBe(link);
+ expect(link.tagName).toBe('A');
+ expect(link).toHaveAttribute('href', '/records/1');
+ expect(link).toHaveAttribute('rel', 'noopener noreferrer');
+ expect(link.querySelector('a')).toBeNull();
+ await user.click(canvas.getByRole('button', { name: 'Before link' }));
+ await user.tab();
+ expect(link).toHaveFocus();
+ expect(getComputedStyle(link).outlineStyle).toBe('solid');
+ await user.keyboard('{Enter}');
+ expect(args.onClick).toHaveBeenCalledTimes(1);
+ await user.click(link);
+ expect(args.onClick).toHaveBeenCalledTimes(2);
+ expect(onParentClick).not.toHaveBeenCalled();
+ },
+};
+
+export const NamedIconOnlyLink: Story = {
+ args: {
+ to: '/records/1',
+ 'aria-label': 'Open record',
+ startElement: <IconUser size={14} aria-hidden />,
+ onClick: fn(),
+ },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const user = userEvent.setup();
+ const link = canvas.getByRole('link', { name: 'Open record' });
+
+ expect(link).toHaveTextContent('');
+ expect(canvas.queryByText('Untitled')).not.toBeInTheDocument();
+ await user.tab();
+ expect(link).toHaveFocus();
+ await user.keyboard('{Enter}');
+ expect(args.onClick).toHaveBeenCalledTimes(1);
+ },
+};
+
+export const ApplicationLabels: Story = {
+ render: () => {
+ const namedLabel = getChipLabel(RECORD_NAME);
+ const emptyLabel = getChipLabel('');
+
+ return (
+ <>
+ <LinkChip to="/records/named" maxWidth={120} tooltipDelay={0}>
+ {namedLabel.content}
+ </LinkChip>
+ <LinkChip to="/records/empty" aria-label={emptyLabel.text}>
+ {emptyLabel.content}
+ </LinkChip>
+ </>
+ );
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const body = within(canvasElement.ownerDocument.body);
+ const user = userEvent.setup();
+ const namedLink = canvas.getByRole('link', { name: RECORD_NAME });
+ const namedLabel = within(namedLink).getByText(RECORD_NAME);
+ const emptyLink = canvas.getByRole('link', { name: 'Untitled' });
+
+ expect(emptyLink).toHaveTextContent('Untitled');
+ expect(namedLabel.scrollWidth).toBeGreaterThan(namedLabel.clientWidth);
+ await user.hover(namedLabel);
+ expect(await body.findByRole('tooltip')).toHaveTextContent(RECORD_NAME);
+ await user.unhover(namedLabel);
+ },
+};
diff --git a/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/__tests__/LinkChip.test.tsx b/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/__tests__/LinkChip.test.tsx
new file mode 100644
index 00000000000..d536c2fd6d7
--- /dev/null
+++ b/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/__tests__/LinkChip.test.tsx
@@ -0,0 +1,85 @@
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { createRef } from 'react';
+import { MemoryRouter, useLocation } from 'react-router-dom';
+import { IconUser } from 'twenty-ui/icon';
+
+import { LinkChip } from '@/ui/navigation/link/components/LinkChip/LinkChip';
+
+const LocationProbe = () => {
+ const { pathname } = useLocation();
+
+ return <div role="status">{pathname}</div>;
+};
+
+describe('LinkChip', () => {
+ it('forwards native attributes and the actual anchor ref without nesting links', () => {
+ const ref = createRef<HTMLAnchorElement>();
+
+ render(
+ <MemoryRouter>
+ <LinkChip
+ to="/records/1"
+ target="_blank"
+ aria-label="Open record"
+ ref={ref}
+ >
+ https://twenty.com
+ </LinkChip>
+ </MemoryRouter>,
+ );
+
+ const link = screen.getByRole('link', { name: 'Open record' });
+
+ expect(ref.current).toBe(link);
+ expect(link).toHaveAttribute('href', '/records/1');
+ expect(link).toHaveAttribute('target', '_blank');
+ expect(link).toHaveAttribute('rel', 'noopener noreferrer');
+ expect(link.querySelector('a')).toBeNull();
+ });
+
+ it('navigates on Enter with the default mouse-down trigger', async () => {
+ const user = userEvent.setup();
+
+ render(
+ <MemoryRouter initialEntries={['/records']}>
+ <LinkChip to="/records/1">Open record</LinkChip>
+ <LocationProbe />
+ </MemoryRouter>,
+ );
+
+ await user.tab();
+ expect(screen.getByRole('link', { name: 'Open record' })).toHaveFocus();
+ await user.keyboard('{Enter}');
+
+ expect(screen.getByRole('status')).toHaveTextContent('/records/1');
+ });
+
+ it('activates an explicitly named icon-only link once per pointer or keyboard action', async () => {
+ const user = userEvent.setup();
+ const onClick = jest.fn();
+ const onParentClick = jest.fn();
+
+ render(
+ <MemoryRouter>
+ <div onClick={onParentClick}>
+ <LinkChip
+ to="/records/1"
+ aria-label="Open record"
+ startElement={<IconUser aria-hidden />}
+ onClick={onClick}
+ />
+ </div>
+ </MemoryRouter>,
+ );
+
+ const link = screen.getByRole('link', { name: 'Open record' });
+
+ await user.tab();
+ await user.keyboard('{Enter}');
+ expect(onClick).toHaveBeenCalledTimes(1);
+ await user.click(link);
+ expect(onClick).toHaveBeenCalledTimes(2);
+ expect(onParentClick).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/types/LinkChipProps.ts b/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/types/LinkChipProps.ts
index 6f9d254a01b..2f706d12457 100644
--- a/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/types/LinkChipProps.ts
+++ b/packages/twenty-front/src/modules/ui/navigation/link/components/LinkChip/types/LinkChipProps.ts
@@ -5,7 +5,7 @@ import { type ChipProps } from 'twenty-ui/primitives/data-display';
export type LinkChipProps = Omit<
ChipProps,
- 'render' | 'ref' | 'onClick' | 'onMouseDown' | 'disabled' | 'nativeButton'
+ 'render' | 'ref' | 'onClick' | 'onMouseDown'
> &
Pick<ComponentPropsWithRef<typeof Link>, 'target' | 'ref'> & {
to: string;
diff --git a/packages/twenty-front/src/modules/validation-rules/components/SettingsValidationRuleFieldChip.tsx b/packages/twenty-front/src/modules/validation-rules/components/SettingsValidationRuleFieldChip.tsx
index 02bd5fb6b91..21f499046ca 100644
--- a/packages/twenty-front/src/modules/validation-rules/components/SettingsValidationRuleFieldChip.tsx
+++ b/packages/twenty-front/src/modules/validation-rules/components/SettingsValidationRuleFieldChip.tsx
@@ -1,3 +1,4 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { styled } from '@linaria/react';
import { useIcons } from 'twenty-ui/icon';
import { Chip } from 'twenty-ui/primitives/data-display';
@@ -32,7 +33,7 @@ export const SettingsValidationRuleFieldChip = ({
title={path}
startElement={<Icon size={theme.icon.size.sm} />}
>
- {label}
+ {getChipLabel(label).content}
</Chip>
</StyledWrapper>
);
diff --git a/packages/twenty-front/src/pages/settings/applications/components/SettingsApplicationRegistrationGeneralInfo.tsx b/packages/twenty-front/src/pages/settings/applications/components/SettingsApplicationRegistrationGeneralInfo.tsx
index 267c8f44af3..5772f96f1fc 100644
--- a/packages/twenty-front/src/pages/settings/applications/components/SettingsApplicationRegistrationGeneralInfo.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/components/SettingsApplicationRegistrationGeneralInfo.tsx
@@ -1,3 +1,4 @@
+import { getChipLabel } from '@/ui/field/display/utils/getChipLabel';
import { useRefetchOnApplicationOperation } from '@/applications/hooks/useRefetchOnApplicationOperation';
import {
SettingsTableCard,
@@ -117,7 +118,7 @@ export const SettingsApplicationRegistrationGeneralInfo = ({
/>
}
>
- {ownerWorkspace.displayName}
+ {getChipLabel(ownerWorkspace.displayName).content}
</Chip>
) : (
<Tag color="orange">{t`Unclaimed`}</Tag>
diff --git a/packages/twenty-ui/docs/chipPropDescriptions.ts b/packages/twenty-ui/docs/chipPropDescriptions.ts
index d46d4503624..9b285590f92 100644
--- a/packages/twenty-ui/docs/chipPropDescriptions.ts
+++ b/packages/twenty-ui/docs/chipPropDescriptions.ts
@@ -1,33 +1,29 @@
import { type ChipProps } from '../src/primitives/data-display/Chip/types/ChipProps';
export const CHIP_PROP_DESCRIPTIONS = {
+ children:
+ 'Caller-owned content. Missing or empty children add no fallback label.',
size: 'Visual size of the chip.',
variant: 'Background treatment of the chip.',
color: 'Primary or secondary text color.',
shape: 'Square or round corners.',
- weight: 'Font weight of the label.',
- disabled:
- 'Applies disabled styling and disables activation when `onClick` is supplied.',
+ weight: 'Font weight of the content.',
clickable:
- 'Enables hover and pointer styling. Defaults to whether `onClick` is supplied; does not add button semantics by itself.',
- nativeButton:
- 'Set to `false` when a clickable chip uses `render` with an element other than a native button.',
+ 'Enables hover and pointer styling. Defaults to whether `onClick` is supplied; does not change the default div or add keyboard behavior.',
startElement: 'Content before the label, such as an avatar or icon.',
endElement:
- 'Content after the label. Avoid interactive content when the chip itself is a button.',
+ 'Content after the label. Avoid interactive content when the chip itself is a button or link.',
endElementDivider:
'Adds a divider before `endElement` when that slot has content.',
- maxWidth:
- 'Maximum chip width in pixels, used to constrain and truncate the label.',
- tooltipLabel:
- 'Tooltip content for a string label. Defaults to the label text.',
- tooltipPlace: 'Position of the string-label tooltip.',
+ maxWidth: 'Maximum chip width in pixels, used to constrain the content.',
+ truncate: 'Truncates overflowing content with an ellipsis. Defaults to true.',
+ tooltipContent:
+ 'Tooltip text. Defaults to string children. Supply text explicitly for node content.',
+ tooltipPlace: 'Position of the content tooltip.',
+ tooltipDelay: 'Delay in milliseconds before the tooltip opens.',
+ isTooltipMultiline: 'Preserves line breaks in the tooltip text.',
alwaysShowTooltip:
- 'Shows the string-label tooltip even when the label is not truncated.',
- isLabelHidden:
- 'Hides the label while keeping the start and end elements. Supply an accessible name for an interactive chip.',
- forceEmptyText:
- 'Suppresses the empty label when children are missing, empty, or false.',
- emptyLabel:
- 'Placeholder shown when children are missing, empty, or false, unless `forceEmptyText` is enabled.',
+ 'Shows the content tooltip even when the content is not truncated.',
+ render:
+ 'Replaces the default div. Compose a native button or link explicitly; that owner supplies disabled and native interaction behavior.',
} satisfies Partial<Record<keyof ChipProps, string>>;
diff --git a/packages/twenty-ui/docs/label-ownership.md b/packages/twenty-ui/docs/label-ownership.md
index 02c8883698b..49fea8a1aa4 100644
--- a/packages/twenty-ui/docs/label-ownership.md
+++ b/packages/twenty-ui/docs/label-ownership.md
@@ -16,7 +16,7 @@ This covers production exports under components, primitives, and icons, includin
| PhoneCountryPicker | Callers supply country labels and the trigger accessible name. The popup takes the trigger name unless a `Dropdown.Title` or an explicit `Dropdown.Content` label names it, and the selected country label describes the trigger. `searchLabel` defaults to `Search`; `emptyLabel` defaults to `No results`. Calling codes are supplied as data without a leading plus sign. |
| ImageInput | `uploadLabel`, `removeLabel`, and `abortLabel` default to `Upload`, `Remove`, and `Abort`. The upload label names the visible upload button and the preview button. Applications supply `helperText` and `errorMessage`, including validation instructions and translated strings. |
| Toast and Toaster | Children, description and action slots, `iconLabel`, `cancelLabel` (default `Cancel`), and `closeLabel` (default `Close`). Toaster accepts native accessible attributes over its `Notifications` region default. |
-| Chip and Avatar | Chip `emptyLabel` defaults to `Untitled`. Avatar's image and default fallback are decorative. `name` supplies the visual initial and colors. Explicit `imageProps.alt` labels the image and default fallback; caller fallback semantics take precedence. Composed buttons and links own their labels and interaction handlers. |
+| Chip and Avatar | Chip content, translated fallbacks and interactive accessible names belong to the caller. Missing children add no label. Avatar's image and default fallback are decorative. `name` supplies the visual initial and colors. Explicit `imageProps.alt` labels the image and default fallback; caller fallback semantics take precedence. Composed buttons and links own their labels and interaction handlers. |
| JsonTree | Callers supply empty string, array, and object labels and expanded/collapsed arrow names. JSON booleans, null, property names, and values are data. |
| ResizeHandle and CodeEditor | ResizeHandle accepts native labels over `Resize`. Hosts supply a contextual label, `aria-controls`, and the focus destination when collapsing a panel removes its handle. CodeEditor exposes `resizeLabel` (default `Resize editor`) and Monaco `options`, including its editor accessible label. The loading indicator adds no text. Monaco owns its internal editor messages. |
| Input, Textarea, Select, Field, Slider, Radio, RadioGroup, Checkbox, Switch, SegmentedControl | Native attributes, compound label/description/error parts, options, and children belong to the caller. Browser validation messages remain browser-owned; Field.Error children or render content can replace them. |
diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.json
index 7525bf6e859..e5fd0ace1fc 100644
--- a/packages/twenty-ui/generated/components.docs.json
+++ b/packages/twenty-ui/generated/components.docs.json
@@ -9481,14 +9481,21 @@
"type": "boolean",
"required": false,
"defaultValue": "false",
- "description": "Shows the string-label tooltip even when the label is not truncated."
+ "description": "Shows the content tooltip even when the content is not truncated."
+ },
+ {
+ "name": "children",
+ "type": "ReactNode",
+ "required": false,
+ "defaultValue": null,
+ "description": "Caller-owned content. Missing or empty children add no fallback label."
},
{
"name": "clickable",
"type": "boolean",
"required": false,
"defaultValue": "isDefined(onClick)",
- "description": "Enables hover and pointer styling. Defaults to whether `onClick` is supplied; does not add button semantics by itself."
+ "description": "Enables hover and pointer styling. Defaults to whether `onClick` is supplied; does not change the default div or add keyboard behavior."
},
{
"name": "color",
@@ -9497,26 +9504,12 @@
"defaultValue": "primary",
"description": "Primary or secondary text color."
},
- {
- "name": "disabled",
- "type": "boolean",
- "required": false,
- "defaultValue": "false",
- "description": "Applies disabled styling and disables activation when `onClick` is supplied."
- },
- {
- "name": "emptyLabel",
- "type": "string",
- "required": false,
- "defaultValue": "Untitled",
- "description": "Placeholder shown when children are missing, empty, or false, unless `forceEmptyText` is enabled."
- },
{
"name": "endElement",
"type": "ReactNode",
"required": false,
"defaultValue": null,
- "description": "Content after the label. Avoid interactive content when the chip itself is a button."
+ "description": "Content after the label. Avoid interactive content when the chip itself is a button or link."
},
{
"name": "endElementDivider",
@@ -9526,39 +9519,25 @@
"description": "Adds a divider before `endElement` when that slot has content."
},
{
- "name": "forceEmptyText",
- "type": "boolean",
- "required": false,
- "defaultValue": "false",
- "description": "Suppresses the empty label when children are missing, empty, or false."
- },
- {
- "name": "isLabelHidden",
+ "name": "isTooltipMultiline",
"type": "boolean",
"required": false,
- "defaultValue": "false",
- "description": "Hides the label while keeping the start and end elements. Supply an accessible name for an interactive chip."
+ "defaultValue": null,
+ "description": "Preserves line breaks in the tooltip text."
},
{
"name": "maxWidth",
"type": "number",
"required": false,
"defaultValue": null,
- "description": "Maximum chip width in pixels, used to constrain and truncate the label."
- },
- {
- "name": "nativeButton",
- "type": "boolean",
- "required": false,
- "defaultValue": "true",
- "description": "Set to `false` when a clickable chip uses `render` with an element other than a native button."
+ "description": "Maximum chip width in pixels, used to constrain the content."
},
{
"name": "render",
"type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, {}>",
"required": false,
"defaultValue": null,
- "description": "Allows you to replace the component's HTML element\nwith a different tag, or compose it with another component.\n\nAccepts a `ReactElement` or a function that returns the element to render."
+ "description": "Replaces the default div. Compose a native button or link explicitly; that owner supplies disabled and native interaction behavior."
},
{
"name": "shape",
@@ -9582,18 +9561,32 @@
"description": "Content before the label, such as an avatar or icon."
},
{
- "name": "tooltipLabel",
+ "name": "tooltipContent",
"type": "string",
"required": false,
"defaultValue": null,
- "description": "Tooltip content for a string label. Defaults to the label text."
+ "description": "Tooltip text. Defaults to string children. Supply text explicitly for node content."
+ },
+ {
+ "name": "tooltipDelay",
+ "type": "number",
+ "required": false,
+ "defaultValue": null,
+ "description": "Delay in milliseconds before the tooltip opens."
},
{
"name": "tooltipPlace",
"type": "\"bottom\" | \"inline-end\" | \"inline-start\" | \"left\" | \"right\" | \"top\"",
"required": false,
"defaultValue": null,
- "description": "Position of the string-label tooltip."
+ "description": "Position of the content tooltip."
+ },
+ {
+ "name": "truncate",
+ "type": "boolean",
+ "required": false,
+ "defaultValue": "true",
+ "description": "Truncates overflowing content with an ellipsis. Defaults to true."
},
{
"name": "variant",
@@ -9607,7 +9600,7 @@
"type": "\"medium\" | \"regular\"",
"required": false,
"defaultValue": "regular",
- "description": "Font weight of the label."
+ "description": "Font weight of the content."
}
]
},
diff --git a/packages/twenty-ui/src/primitives/data-display/Chip/Chip.module.scss b/packages/twenty-ui/src/primitives/data-display/Chip/Chip.module.scss
index 2ac6653ab7e..40d3f88261b 100644
--- a/packages/twenty-ui/src/primitives/data-display/Chip/Chip.module.scss
+++ b/packages/twenty-ui/src/primitives/data-display/Chip/Chip.module.scss
@@ -8,7 +8,6 @@
gap: var(--t-spacing-1);
block-size: var(--t-spacing-3);
max-inline-size: var(--tw-chip-max-width, 100%);
- overflow: hidden;
padding: var(--t-spacing-1) var(--tw-chip-padding);
user-select: none;
font: inherit;
@@ -22,6 +21,9 @@
& > svg {
flex-shrink: 0;
}
+ &[data-truncate] {
+ overflow: hidden;
+ }
&[data-size='md'] {
block-size: var(--t-spacing-4);
}
@@ -40,11 +42,15 @@
&[data-variant='solid'] {
background: var(--t-background-transparent-medium);
}
+ &:disabled,
+ &[aria-disabled='true'],
&[data-disabled] {
color: var(--t-font-color-light);
cursor: not-allowed;
}
- &[data-clickable]:not([data-disabled]) {
+ &[data-clickable]:not(:disabled):not([aria-disabled='true']):not(
+ [data-disabled]
+ ) {
cursor: pointer;
@include hover-capable {
&:hover {
@@ -69,14 +75,6 @@
}
}
-.content {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-.emptyLabel {
- color: var(--t-font-color-tertiary);
-}
.endElementDivider {
align-self: stretch;
border-inline-start: 1px solid var(--t-border-color-light);
diff --git a/packages/twenty-ui/src/primitives/data-display/Chip/Chip.module.scss.d.ts b/packages/twenty-ui/src/primitives/data-display/Chip/Chip.module.scss.d.ts
index de9148e2417..2614dbbb3a6 100644
--- a/packages/twenty-ui/src/primitives/data-display/Chip/Chip.module.scss.d.ts
+++ b/packages/twenty-ui/src/primitives/data-display/Chip/Chip.module.scss.d.ts
@@ -1,7 +1,5 @@
declare const classNames: {
readonly chip: 'chip';
- readonly content: 'content';
- readonly emptyLabel: 'emptyLabel';
readonly endElementDivider: 'endElementDivider';
};
export default classNames;
diff --git a/packages/twenty-ui/src/primitives/data-display/Chip/Chip.tsx b/packages/twenty-ui/src/primitives/data-display/Chip/Chip.tsx
index 1e69c08efc6..1955ec0f206 100644
--- a/packages/twenty-ui/src/primitives/data-display/Chip/Chip.tsx
+++ b/packages/twenty-ui/src/primitives/data-display/Chip/Chip.tsx
@@ -1,5 +1,5 @@
-import { Button as ButtonPrimitive } from '@base-ui/react/button';
import { useRender } from '@base-ui/react/use-render';
+import { isBoolean, isString } from '@sniptt/guards';
import { clsx } from 'clsx';
import { type CSSProperties } from 'react';
@@ -18,20 +18,18 @@ export const Chip = ({
color = 'primary',
shape = 'square',
weight = 'regular',
- disabled = false,
onClick,
clickable = isDefined(onClick),
- nativeButton = true,
startElement,
endElement,
endElementDivider = false,
maxWidth,
- tooltipLabel,
+ truncate = true,
+ tooltipContent,
+ tooltipDelay,
+ isTooltipMultiline,
tooltipPlace,
alwaysShowTooltip = false,
- isLabelHidden = false,
- forceEmptyText = false,
- emptyLabel = 'Untitled',
className,
style,
render,
@@ -39,20 +37,15 @@ export const Chip = ({
...props
}: ChipProps) => {
const hasContent =
- isDefined(children) && children !== '' && children !== false;
+ isDefined(children) && !isBoolean(children) && children !== '';
+ const textProps = isString(children)
+ ? { text: children, tooltipContent }
+ : { text: children ?? false, tooltipContent: tooltipContent ?? '' };
return useRender({
- render: isDefined(onClick) ? (
- <ButtonPrimitive
- render={render}
- disabled={disabled}
- nativeButton={nativeButton}
- />
- ) : (
- render
- ),
+ render,
ref,
- state: { size, variant, color, shape, weight, disabled, clickable },
+ state: { size, variant, color, shape, weight, clickable, truncate },
props: {
...props,
onClick,
@@ -68,24 +61,18 @@ export const Chip = ({
children: (
<>
{startElement}
- {!isLabelHidden &&
- (hasContent ? (
- typeof children === 'string' ? (
- <OverflowingTextWithTooltip
- style={size === 'md' ? MEDIUM_LABEL_STYLE : undefined}
- text={children}
- tooltipContent={tooltipLabel}
- tooltipPlace={tooltipPlace}
- alwaysShowTooltip={alwaysShowTooltip}
- />
- ) : (
- <span className={styles.content}>{children}</span>
- )
- ) : (
- !forceEmptyText && (
- <span className={styles.emptyLabel}>{emptyLabel}</span>
- )
- ))}
+ {hasContent && (
+ <OverflowingTextWithTooltip
+ {...textProps}
+ render={<span />}
+ style={size === 'md' ? MEDIUM_LABEL_STYLE : undefined}
+ truncate={truncate}
+ tooltipDelay={tooltipDelay}
+ isTooltipMultiline={isTooltipMultiline}
+ tooltipPlace={tooltipPlace}
+ alwaysShowTooltip={alwaysShowTooltip}
+ />
+ )}
{isDefined(endElement) && endElement !== false && (
<>
{endElementDivider && (
diff --git a/packages/twenty-ui/src/primitives/data-display/Chip/__stories__/Chip.stories.tsx b/packages/twenty-ui/src/primitives/data-display/Chip/__stories__/Chip.stories.tsx
index 3991e13f6b8..629d6b483e0 100644
--- a/packages/twenty-ui/src/primitives/data-display/Chip/__stories__/Chip.stories.tsx
+++ b/packages/twenty-ui/src/primitives/data-display/Chip/__stories__/Chip.stories.tsx
@@ -3,6 +3,8 @@ import { type Meta, type StoryObj } from '@storybook/react-vite';
import { IconUser, IconX } from '@ui/icon';
import { Avatar } from '@ui/primitives/data-display/Avatar/Avatar';
import { Button } from '@ui/primitives/input/Button/Button';
+import { Text } from '@ui/primitives/typography/Text/Text';
+import { isDefined } from '@ui/utilities/utils/isDefined';
import {
A11Y_DEFER_COLOR_CONTRAST,
@@ -29,17 +31,9 @@ export const Default: Story = {
size: 'sm',
variant: 'soft',
color: 'primary',
- disabled: false,
maxWidth: 200,
},
decorators: [ComponentDecorator],
- play: async ({ canvasElement }) => {
- const canvas = within(canvasElement);
- await expect(canvas.queryByRole('button')).not.toBeInTheDocument();
- await expect(
- getComputedStyle(canvas.getByText('Chip test')).cursor,
- ).not.toBe('pointer');
- },
};
export const WithLeftAvatar: Story = {
@@ -64,10 +58,14 @@ export const WithLeftIcon: Story = {
decorators: [ComponentDecorator],
};
-export const EmptyLabel: Story = {
+export const CallerFallback: Story = {
parameters: { a11y: A11Y_DEFER_COLOR_CONTRAST },
args: {
- children: '',
+ children: (
+ <Text render={<span />} style={{ color: 'var(--t-font-color-tertiary)' }}>
+ Untitled
+ </Text>
+ ),
clickable: true,
variant: 'ghost',
startElement: <Avatar name="?" colorSeed="empty" size="sm" />,
@@ -81,7 +79,6 @@ export const Catalog: CatalogStory<Story, typeof Chip> = {
size: { control: false },
variant: { control: false },
color: { control: false },
- disabled: { control: false },
className: { control: false },
endElement: { control: false },
startElement: { control: false },
@@ -111,7 +108,7 @@ export const Catalog: CatalogStory<Story, typeof Chip> = {
case 'active':
return { className: state };
case 'disabled':
- return { disabled: true };
+ return { render: <button type="button" disabled /> };
default:
return {};
}
@@ -135,7 +132,6 @@ export const WithAvatarCatalog: CatalogStory<Story, typeof Chip> = {
size: { control: false },
variant: { control: false },
color: { control: false },
- disabled: { control: false },
className: { control: false },
endElement: { control: false },
startElement: { control: false },
@@ -165,7 +161,7 @@ export const WithAvatarCatalog: CatalogStory<Story, typeof Chip> = {
case 'active':
return { className: state };
case 'disabled':
- return { disabled: true };
+ return { render: <button type="button" disabled /> };
default:
return {};
}
@@ -198,7 +194,11 @@ export const CatalogDark: typeof Catalog = {
export const PointerAndKeyboard: Story = {
decorators: [ComponentDecorator],
- args: { children: 'Open details', onClick: fn() },
+ args: {
+ children: 'Open details',
+ render: <button type="button" />,
+ onClick: fn(),
+ },
play: async ({ canvasElement, args }) => {
const control = within(canvasElement).getByRole('button', {
name: 'Open details',
@@ -217,7 +217,11 @@ export const PointerAndKeyboard: Story = {
export const Disabled: Story = {
decorators: [ComponentDecorator],
- args: { children: 'Unavailable', disabled: true, onClick: fn() },
+ args: {
+ children: 'Unavailable',
+ render: <button type="button" disabled />,
+ onClick: fn(),
+ },
play: async ({ canvasElement, args }) => {
const control = within(canvasElement).getByRole('button', {
name: 'Unavailable',
@@ -246,3 +250,95 @@ export const ContentAndSlots: Story = {
await userEvent.click(canvas.getByRole('button', { name: 'Remove' }));
},
};
+
+export const StableDefault: Story = {
+ decorators: [ComponentDecorator],
+ args: { children: 'Presentational chip', onClick: fn() },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const chip = canvas.getByText('Presentational chip').parentElement;
+ await expect(chip?.tagName).toBe('DIV');
+ await expect(canvas.queryByRole('button')).not.toBeInTheDocument();
+ await userEvent.click(canvas.getByText('Presentational chip'));
+ await expect(args.onClick).toHaveBeenCalledTimes(1);
+ },
+};
+
+export const IconOnly: Story = {
+ decorators: [ComponentDecorator],
+ args: {
+ render: <button type="button" />,
+ 'aria-label': 'Open profile',
+ startElement: <IconUser size={14} aria-hidden />,
+ onClick: fn(),
+ },
+ play: async ({ canvasElement, args }) => {
+ const canvas = within(canvasElement);
+ const control = canvas.getByRole('button', { name: 'Open profile' });
+ await expect(canvas.queryByText('Untitled')).not.toBeInTheDocument();
+ control.focus();
+ await userEvent.keyboard('{Enter}');
+ await expect(args.onClick).toHaveBeenCalledTimes(1);
+ await expect(control).toHaveFocus();
+ },
+};
+
+export const ExplicitLink: Story = {
+ decorators: [ComponentDecorator],
+ args: {
+ render: <a href="#chip-link" aria-label="https://twenty.com" />,
+ children: 'https://twenty.com',
+ clickable: true,
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const link = canvas.getByRole('link', { name: 'https://twenty.com' });
+ await expect(link).toHaveAttribute('href', '#chip-link');
+ await expect(link.querySelector('a')).toBeNull();
+ link.focus();
+ await expect(link).toHaveFocus();
+ },
+};
+
+export const TruncationAndTooltip: Story = {
+ decorators: [ComponentDecorator],
+ args: {
+ children: <strong>Quarterly customer research findings.pdf</strong>,
+ variant: 'soft',
+ maxWidth: 150,
+ tooltipContent: 'Research findings\nPDF document',
+ tooltipDelay: 0,
+ isTooltipMultiline: true,
+ tooltipPlace: 'top',
+ },
+ play: async ({ canvasElement }) => {
+ const content = within(canvasElement).getByText(
+ 'Quarterly customer research findings.pdf',
+ ).parentElement;
+ if (!isDefined(content)) {
+ throw new Error('Chip content must have a text container');
+ }
+ await expect(content.scrollWidth).toBeGreaterThan(content.clientWidth);
+ await expect(getComputedStyle(content).textOverflow).toBe('ellipsis');
+ await userEvent.hover(content);
+ await expect(
+ await within(document.body).findByRole('tooltip'),
+ ).toHaveTextContent('Research findings PDF document');
+ await userEvent.unhover(content);
+ await userEvent.keyboard('{Escape}');
+ },
+};
+
+export const WithoutTruncation: Story = {
+ decorators: [ComponentDecorator],
+ args: { children: 'Unconstrained content', truncate: false },
+ play: async ({ canvasElement }) => {
+ const content = within(canvasElement).getByText('Unconstrained content');
+ await expect(getComputedStyle(content).textOverflow).not.toBe('ellipsis');
+ const chip = content.parentElement;
+ if (!isDefined(chip)) {
+ throw new Error('Chip content must have a root');
+ }
+ await expect(getComputedStyle(chip).overflow).not.toBe('hidden');
+ },
+};
diff --git a/packages/twenty-ui/src/primitives/data-display/Chip/__tests__/Chip.test.tsx b/packages/twenty-ui/src/primitives/data-display/Chip/__tests__/Chip.test.tsx
index a189987f8d5..a45dbe6f971 100644
--- a/packages/twenty-ui/src/primitives/data-display/Chip/__tests__/Chip.test.tsx
+++ b/packages/twenty-ui/src/primitives/data-display/Chip/__tests__/Chip.test.tsx
@@ -1,3 +1,7 @@
+import { render, screen } from '@testing-library/react';
+import { createRef } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
import { runComponentConformance } from '@test-utilities/conformance/runComponentConformance';
import { Chip } from '../Chip';
@@ -9,3 +13,99 @@ runComponentConformance({
ownClassName: styles.chip,
refInstanceOf: HTMLDivElement,
});
+
+describe('Chip content and composition', () => {
+ it('keeps the default element when a click handler is supplied', () => {
+ render(
+ <Chip onClick={vi.fn()} data-testid="chip">
+ Label
+ </Chip>,
+ );
+
+ expect(screen.getByTestId('chip').tagName).toBe('DIV');
+ expect(screen.queryByRole('button')).not.toBeInTheDocument();
+ expect(screen.getByTestId('chip')).not.toHaveAttribute('tabindex');
+ });
+
+ it('adds no label for omitted, empty or boolean content', () => {
+ render(
+ <>
+ <Chip data-testid="empty-chip" />
+ <Chip data-testid="empty-chip">{null}</Chip>
+ <Chip data-testid="empty-chip">{false}</Chip>
+ <Chip data-testid="empty-chip">{true}</Chip>
+ <Chip data-testid="empty-chip">{''}</Chip>
+ </>,
+ );
+
+ for (const chip of screen.getAllByTestId('empty-chip')) {
+ expect(chip).toBeEmptyDOMElement();
+ }
+ expect(screen.queryByText('Untitled')).not.toBeInTheDocument();
+ });
+
+ it('preserves caller fallbacks, zero, rich content and both slots', () => {
+ render(
+ <>
+ <Chip>Caller fallback</Chip>
+ <Chip>{0}</Chip>
+ <Chip
+ startElement={<span>Start</span>}
+ endElement={<span>End</span>}
+ endElementDivider
+ >
+ <strong>Rich content</strong>
+ </Chip>
+ </>,
+ );
+
+ expect(screen.getByText('Caller fallback')).toBeVisible();
+ expect(screen.getByText('0')).toBeVisible();
+ expect(screen.getByText('Start')).toBeVisible();
+ expect(screen.getByText('Rich content').tagName).toBe('STRONG');
+ expect(screen.getByText('End')).toBeVisible();
+ });
+
+ it('targets the explicit link with native props and a DOM ref without linkifying its text', () => {
+ const ref = createRef<HTMLDivElement>();
+ render(
+ <Chip
+ ref={ref}
+ render={
+ <a
+ href="https://twenty.com"
+ target="_blank"
+ aria-label="Open Twenty"
+ />
+ }
+ aria-label="Open Twenty"
+ title="Documentation"
+ data-owner="caller"
+ >
+ https://twenty.com
+ </Chip>,
+ );
+
+ const link = screen.getByRole('link', { name: 'Open Twenty' });
+ expect(ref.current).toBe(link);
+ expect(link).toHaveAttribute('href', 'https://twenty.com');
+ expect(link).toHaveAttribute('target', '_blank');
+ expect(link).toHaveAttribute('title', 'Documentation');
+ expect(link).toHaveAttribute('data-owner', 'caller');
+ expect(link.querySelector('a')).toBeNull();
+ });
+
+ it('renders intentional links supplied as content once', () => {
+ render(
+ <Chip>
+ <a href="https://twenty.com">Documentation</a>
+ </Chip>,
+ );
+
+ expect(screen.getAllByRole('link')).toHaveLength(1);
+ expect(screen.getByRole('link', { name: 'Documentation' })).toHaveAttribute(
+ 'href',
+ 'https://twenty.com',
+ );
+ });
+});
diff --git a/packages/twenty-ui/src/primitives/data-display/Chip/types/ChipProps.ts b/packages/twenty-ui/src/primitives/data-display/Chip/types/ChipProps.ts
index 2db116fcf98..eb1307ae5d5 100644
--- a/packages/twenty-ui/src/primitives/data-display/Chip/types/ChipProps.ts
+++ b/packages/twenty-ui/src/primitives/data-display/Chip/types/ChipProps.ts
@@ -1,28 +1,29 @@
import { type useRender } from '@base-ui/react/use-render';
import { type ReactNode } from 'react';
-import { type TooltipSide } from '@ui/primitives/surfaces/Tooltip/types/TooltipSide';
+import { type OverflowingTextWithTooltipProps } from '@ui/primitives/typography/OverflowingTextWithTooltip/types/OverflowingTextWithTooltipProps';
import { type ChipSize } from './ChipSize';
import { type ChipVariant } from './ChipVariant';
-export type ChipProps = Omit<useRender.ComponentProps<'div'>, 'color'> & {
- size?: ChipSize;
- variant?: ChipVariant;
- color?: 'primary' | 'secondary';
- shape?: 'square' | 'round';
- weight?: 'regular' | 'medium';
- disabled?: boolean;
- clickable?: boolean;
- nativeButton?: boolean;
- startElement?: ReactNode;
- endElement?: ReactNode;
- endElementDivider?: boolean;
- maxWidth?: number;
- tooltipLabel?: string;
- tooltipPlace?: TooltipSide;
- alwaysShowTooltip?: boolean;
- isLabelHidden?: boolean;
- forceEmptyText?: boolean;
- emptyLabel?: string;
-};
+export type ChipProps = Omit<useRender.ComponentProps<'div'>, 'color'> &
+ Pick<
+ OverflowingTextWithTooltipProps,
+ | 'truncate'
+ | 'tooltipContent'
+ | 'tooltipDelay'
+ | 'tooltipPlace'
+ | 'isTooltipMultiline'
+ | 'alwaysShowTooltip'
+ > & {
+ size?: ChipSize;
+ variant?: ChipVariant;
+ color?: 'primary' | 'secondary';
+ shape?: 'square' | 'round';
+ weight?: 'regular' | 'medium';
+ clickable?: boolean;
+ startElement?: ReactNode;
+ endElement?: ReactNode;
+ endElementDivider?: boolean;
+ maxWidth?: number;
+ };