The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Move ImageInput into Twenty UI (#27039)
Raphaël Bosiaf6c3b4173fc
diff --git a/packages/twenty-docs/docs.json b/packages/twenty-docs/docs.jsonindex f94fceafdf6..9b3127f968c 100644--- a/packages/twenty-docs/docs.json+++ b/packages/twenty-docs/docs.json@@ -635,6 +635,7 @@"ui/components/avatar-group","ui/components/callout","ui/components/command-block",+ "ui/components/image-input","ui/components/inline-banner","ui/components/json-tree","ui/components/menu-items",diff --git a/packages/twenty-docs/navigation/base-structure.json b/packages/twenty-docs/navigation/base-structure.jsonindex ade7466e952..a0fcdcdcb74 100644--- a/packages/twenty-docs/navigation/base-structure.json+++ b/packages/twenty-docs/navigation/base-structure.json@@ -653,6 +653,7 @@"ui/components/avatar-group","ui/components/callout","ui/components/command-block",+ "ui/components/image-input","ui/components/inline-banner","ui/components/json-tree","ui/components/menu-items",diff --git a/packages/twenty-docs/snippets/ui/generated/components/image-input.mdx b/packages/twenty-docs/snippets/ui/generated/components/image-input.mdxnew file mode 100644index 00000000000..4e2aefd80f5--- /dev/null+++ b/packages/twenty-docs/snippets/ui/generated/components/image-input.mdx@@ -0,0 +1,76 @@+{/*+ * _____ _+ *|_ _|_ _____ _ __ | |_ _ _+ * | | \ \ /\ / / _ \ '_ \| __| | | | Auto-generated file+ * | | \ V V / __/ | | | |_| |_| | DO NOT EDIT - changes will be overwritten+ * |_| \_/\_/ \___|_| |_|\__|\__, | Generated by: npx nx generate:ui twenty-docs+ * |___/+ *+ * This file is generated from the documentation data in packages/twenty-ui/generated.+ * To update it, edit the component prop types or design tokens in twenty-ui and run:+ * npx nx generate:ui twenty-docs+ */}++<ParamField body="abortLabel" type="string" default="Abort">+ Label for the Abort action.+</ParamField>++<ParamField body="accept" type="string" default="image/*">+ Native file picker filter. Defaults to image/*. The application validates the selected file.+</ParamField>++<ParamField body="className" type="string">+ Class applied to the root element.+</ParamField>++<ParamField body="disabled" type="boolean" default="false">+ Disables file selection, removal, and abort actions.+</ParamField>++<ParamField body="errorMessage" type="string | null">+ Application error, displayed as an alert and associated with the selection controls.+</ParamField>++<ParamField body="helperText" type="string">+ Application instructions, associated with the selection controls.+</ParamField>++<ParamField body="isUploading" type="boolean" default="false">+ Marks the module busy. Selection and removal controls that would otherwise be enabled stay focusable but unavailable. Shows Abort when onAbort is supplied.+</ParamField>++<ParamField body="onAbort" type="(() => void)">+ Shows an abort action while uploading. It can cancel the first upload before a src exists.+</ParamField>++<ParamField body="onRemove" type="(() => void)">+ Requests removal of the current image. Removal is disabled without this callback or a nonempty src.+</ParamField>++<ParamField body="onUpload" type="((file: File) => void)">+ Receives the selected File. Empty and canceled selections do not call it. Selection is disabled when omitted.+</ParamField>++<ParamField body="ref" type="Ref<HTMLDivElement>">+ Ref to the root element.+</ParamField>++<ParamField body="removeLabel" type="string" default="Remove">+ Label for the Remove action.+</ParamField>++<ParamField body="render" type="ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, {}>">+ Custom root element or render function. Keep a non-interactive root.+</ParamField>++<ParamField body="src" type="string | null">+ Resolved image URL. Empty or failed images show the image placeholder.+</ParamField>++<ParamField body="style" type="CSSProperties">+ Inline style applied to the root element.+</ParamField>++<ParamField body="uploadLabel" type="string" default="Upload">+ Label for the preview and Upload action.+</ParamField>diff --git a/packages/twenty-docs/ui/components/image-input.mdx b/packages/twenty-docs/ui/components/image-input.mdxnew file mode 100644index 00000000000..fae408f4856--- /dev/null+++ b/packages/twenty-docs/ui/components/image-input.mdx@@ -0,0 +1,72 @@+---+title: ImageInput+description: Image selection, preview, and upload actions with application-owned storage.+---++import { StoryEmbed } from '/snippets/ui/StoryEmbed.mdx';+import ImageInputReference from '/snippets/ui/generated/components/image-input.mdx';++`ImageInput` combines an image preview, a native file picker, and upload, remove, or abort actions. Pass a resolved image URL as `src`. Your application validates files, uploads them, saves the resulting URL, and supplies instructions and errors.++<StoryEmbed+ storyId="ui-input-imageinput--with-helper-text"+ title="Image input with an existing image"+ height={180}+/>++```tsx+import { ImageInput, type ImageInputProps } from 'twenty-ui/components';++export const WorkspaceImage = ({+ src,+ onUpload,+ onRemove,+}: Pick<ImageInputProps, 'src' | 'onUpload' | 'onRemove'>) => (+ <ImageInput+ src={src}+ onUpload={onUpload}+ onRemove={onRemove}+ helperText="Choose a square image for your workspace."+ />+);+```++## Selection and preview++The preview and Upload button open the same native file picker. `onUpload` receives the selected `File`. Canceling or returning an empty selection leaves the current image unchanged. The file input clears after selection so the same file can be selected again.++Native file selection and usable `File` contents are not supported in the current front-component sandbox. React and Preact renderer coverage includes previews, action callbacks, and state. Use an ordinary React host for the complete native selection flow.++The `accept` prop defaults to `image/*` and filters the file picker. Validate allowed formats, dimensions, and size in your application. This callback-driven selector does not retain a file for native form submission. Its action buttons use `type="button"`, so they do not submit a surrounding form.++An empty or failed image shows a placeholder. Changing `src` retries the preview, including after an earlier image failed to load. Removal calls `onRemove`; update `src` after your application removes the image.++## Uploading and disabled states++`isUploading` marks the root busy and makes selection and removal unavailable. Controls that were available stay focusable, so keyboard focus is not lost when an upload starts. Supply `onAbort` to replace Upload with Abort during an upload. Abort works before the first image URL exists. The application owns cancellation and sets `isUploading` back to `false` when the upload ends.++`disabled` disables every action. Selection requires `onUpload`. Removal requires both `onRemove` and a nonempty `src`.++<StoryEmbed+ storyId="ui-input-imageinput--uploading"+ title="Image upload with an abort action"+ height={180}+/>++## Labels, instructions, and errors++Supply localized `uploadLabel`, `removeLabel`, and `abortLabel` strings. They default to `Upload`, `Remove`, and `Abort`. The upload label also names the preview button.++`helperText` and `errorMessage` belong to the application. Both describe the selection controls, and errors are announced as alerts. There are no built-in file limits or product instructions.++<StoryEmbed+ storyId="ui-input-imageinput--with-error"+ title="Image input with instructions and an error"+ height={200}+/>++Native div attributes, `className`, `style`, and `ref` apply to the root. Use `render` for root composition and keep that root non-interactive, since the module already contains buttons. Use `dir="rtl"` for right-to-left layout.++## Props++<ImageInputReference />diff --git a/packages/twenty-e2e-testing/lib/pom/helper/uploadImage.ts b/packages/twenty-e2e-testing/lib/pom/helper/uploadImage.tsindex 41493fdc0e1..698f6ff4ab7 100644--- a/packages/twenty-e2e-testing/lib/pom/helper/uploadImage.ts+++ b/packages/twenty-e2e-testing/lib/pom/helper/uploadImage.ts@@ -6,8 +6,13 @@ export class UploadImage {private readonly removeButton: Locator;constructor(public readonly page: Page) {- this.imagePreview = page.locator('.css-6eut39'); //TODO: add attribute to make it independent of theme- this.uploadButton = page.getByRole('button', { name: 'Upload' });+ const uploadButtons = page.getByRole('button', {+ name: 'Upload',+ exact: true,+ });++ this.imagePreview = uploadButtons.filter({ hasNotText: 'Upload' });+ this.uploadButton = uploadButtons.filter({ hasText: 'Upload' });this.removeButton = page.getByRole('button', { name: 'Remove' });}diff --git a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsxindex bcc85aab6eb..d6571a3c831 100644--- a/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/TwentyUiGallery.stories.tsx@@ -1,4 +1,5 @@import { breadcrumbTest } from '@/__stories__/twenty-ui-gallery/utils/breadcrumbTest';+import { imageInputTest } from '@/__stories__/twenty-ui-gallery/utils/imageInputTest';import { jsonTreeTest } from '@/__stories__/twenty-ui-gallery/utils/jsonTreeTest';import { inlineBannerSandboxTest } from '@/__stories__/twenty-ui-gallery/utils/inlineBannerSandboxTest';import { themeTokenTest } from '@/__stories__/twenty-ui-gallery/utils/themeTokenTest';@@ -563,3 +564,15 @@ export const InlineBannerPreactFocusFailure: Story = createGalleryStory({runtime: 'preact',play: inlineBannerSandboxTest,});++export const ImageInputReact: Story = createGalleryStory({+ frontComponentBundleName: 'twenty-ui-image-input',+ runtime: 'react',+ play: imageInputTest,+});++export const ImageInputPreact: Story = createGalleryStory({+ frontComponentBundleName: 'twenty-ui-image-input',+ runtime: 'preact',+ play: imageInputTest,+});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.mdindex 3ee19d64b0d..694e6a97e60 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@@ -17,6 +17,7 @@ requiring them to occur.| --- | --- || `twenty-ui-field-controls` | Field, Input, InputGroup, Textarea || `twenty-ui-display-helpers` | Text |+| `twenty-ui-image-input` | ImageInput || `twenty-ui-list-item` | ListItem || `twenty-ui-tabs` | Tabs || `twenty-ui-popover` | Popover |@@ -51,6 +52,7 @@ No stories are skipped or marked as expected-to-fail by the runner.| Component | Current limitation || --- | --- || Field controls | Forwarded events lack the `nativeEvent` Base UI reads for `composedPath`. Textarea's cloned render element loses its change handler in React. The value report checks the state received by the component after typing. |+| ImageInput | Native file picker activation and usable file contents are unavailable in the sandbox. The fixture checks forwarded file metadata, preview recovery, action callbacks, and supplied error changes. See the [ImageInput documentation](../../../../twenty-docs/ui/components/image-input.mdx). || Tabs | Activation fails on the missing `nativeEvent` for `composedPath` in both runtimes. || Popover, Dialog, AlertDialog | Opening fails while reading pointer contact data from the missing `nativeEvent`. || Menu | Opening fails on the missing `nativeEvent.pointerType` and pointer contact data. |diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-image-input.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-image-input.front-component.tsxnew file mode 100644index 00000000000..ced6f9e47b7--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/twenty-ui-image-input.front-component.tsx@@ -0,0 +1,77 @@+import { useState } from 'react';+import { defineFrontComponent } from 'twenty-sdk/define';+import { ImageInput } from 'twenty-ui/components';+import { Button } from 'twenty-ui/primitives/input';++import { TwentyUiGalleryCard } from '@/__stories__/shared/front-components/twenty-ui-gallery-card';++const IMAGE_SOURCE =+ 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="40" height="40"%3E%3Crect width="40" height="40" fill="royalblue"/%3E%3C/svg%3E';+const INVALID_IMAGE_SOURCE = 'data:image/png;base64,invalid';++const ImageInputExample = () => {+ const [src, setSrc] = useState<string | undefined>(IMAGE_SOURCE);+ const [isUploading, setIsUploading] = useState(false);+ const [disabled, setDisabled] = useState(false);+ const [errorMessage, setErrorMessage] = useState<string | undefined>();+ const [uploads, setUploads] = useState(0);+ const [removals, setRemovals] = useState(0);+ const [aborts, setAborts] = useState(0);+ const [selectedFile, setSelectedFile] = useState('none');++ return (+ <TwentyUiGalleryCard title="ImageInput">+ <ImageInput+ role="group"+ aria-label="Profile image"+ src={src}+ isUploading={isUploading}+ disabled={disabled}+ helperText="Choose an image for your profile."+ errorMessage={errorMessage}+ uploadLabel="Choose profile image"+ removeLabel="Remove profile image"+ abortLabel="Cancel profile upload"+ onUpload={(file) => {+ setUploads((count) => count + 1);+ setSelectedFile(`${file.name}; ${file.type}; ${file.size} bytes`);+ }}+ onRemove={() => {+ setRemovals((count) => count + 1);+ setSrc(undefined);+ }}+ onAbort={() => {+ setAborts((count) => count + 1);+ setIsUploading(false);+ }}+ />+ <Button onClick={() => setSrc(IMAGE_SOURCE)}>Restore image</Button>+ <Button onClick={() => setSrc(INVALID_IMAGE_SOURCE)}>+ Show invalid image+ </Button>+ <Button onClick={() => setIsUploading(true)}>Start upload</Button>+ <Button+ onClick={() => setErrorMessage('The image could not be uploaded.')}+ >+ Show upload error+ </Button>+ <Button onClick={() => setErrorMessage(undefined)}>+ Clear upload error+ </Button>+ <Button onClick={() => setDisabled((value) => !value)}>+ {disabled ? 'Enable image input' : 'Disable image input'}+ </Button>+ <output aria-label="Image actions">+ Uploads: {uploads}; Removals: {removals}; Aborts: {aborts}+ </output>+ <output aria-label="Selected image">{selectedFile}</output>+ </TwentyUiGalleryCard>+ );+};++export default defineFrontComponent({+ universalIdentifier: '4c486527-2e46-4c7d-a0cc-d2f06d9c3a8e',+ name: 'twenty-ui-image-input',+ description: 'Image selection, preview, and actions in the sandbox',+ component: ImageInputExample,+});diff --git a/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/imageInputTest.ts b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/imageInputTest.tsnew file mode 100644index 00000000000..25ba56bc4af--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/twenty-ui-gallery/utils/imageInputTest.ts@@ -0,0 +1,134 @@+import { expect, userEvent, waitFor, within } from 'storybook/test';++import { type TwentyUiGalleryPlayFunction } from '@/__stories__/twenty-ui-gallery/types/TwentyUiGalleryPlayFunction';++export const imageInputTest: TwentyUiGalleryPlayFunction = async ({+ canvasElement,+}) => {+ const canvas = within(canvasElement);+ const imageInput = await canvas.findByLabelText(+ 'Profile image',+ {},+ { timeout: 10000 },+ );+ const input = within(imageInput);+ const actions = canvas.getByLabelText('Image actions');++ await expect(+ input.getByText('Choose an image for your profile.'),+ ).toBeVisible();+ await expect(input.queryByRole('alert')).not.toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Show upload error' }),+ );+ await expect(await input.findByRole('alert')).toHaveTextContent(+ 'The image could not be uploaded.',+ );+ await userEvent.click(+ canvas.getByRole('button', { name: 'Clear upload error' }),+ );+ await waitFor(() =>+ expect(input.queryByRole('alert')).not.toBeInTheDocument(),+ );+ await waitFor(() => {+ expect(input.getByRole('presentation')).toHaveProperty('naturalWidth', 40);+ });++ await userEvent.click(+ canvas.getByRole('button', { name: 'Show invalid image' }),+ );+ await waitFor(() =>+ expect(input.queryByRole('presentation')).not.toBeInTheDocument(),+ );+ await userEvent.click(canvas.getByRole('button', { name: 'Restore image' }));+ await waitFor(() => {+ expect(input.getByRole('presentation')).toHaveProperty('naturalWidth', 40);+ });++ for (const activation of ['pointer', 'Enter', 'Space']) {+ const remove = input.getByRole('button', {+ name: 'Remove profile image',+ });++ await expect(remove).toHaveAttribute('type', 'button');+ if (activation === 'pointer') {+ await userEvent.click(remove);+ }+ if (activation !== 'pointer') {+ remove.focus();+ await userEvent.keyboard(activation === 'Enter' ? '{Enter}' : ' ');+ }+ await waitFor(() => expect(remove).toBeDisabled());+ await expect(input.queryByRole('presentation')).not.toBeInTheDocument();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Restore image' }),+ );+ await waitFor(() => expect(remove).toBeEnabled());+ }+ await expect(actions).toHaveTextContent('Uploads: 0; Removals: 3; Aborts: 0');++ await userEvent.click(+ canvas.getByRole('button', { name: 'Disable image input' }),+ );+ await waitFor(() => {+ for (const button of input.getAllByRole('button')) {+ expect(button).toBeDisabled();+ }+ });+ await userEvent.click(+ input.getByRole('button', { name: 'Remove profile image' }),+ );+ await userEvent.click(+ canvas.getByRole('button', { name: 'Enable image input' }),+ );+ await waitFor(() => {+ for (const button of input.getAllByRole('button')) {+ expect(button).toBeEnabled();+ }+ });+ await expect(actions).toHaveTextContent('Removals: 3');++ await userEvent.click(canvas.getByRole('button', { name: 'Start upload' }));+ const abort = await input.findByRole('button', {+ name: 'Cancel profile upload',+ });++ await expect(abort).toHaveAttribute('type', 'button');+ await expect(abort).toBeEnabled();+ for (const button of input.getAllByRole('button', {+ name: 'Choose profile image',+ })) {+ await expect(button).toHaveAttribute('aria-disabled', 'true');+ }+ await userEvent.click(abort);+ await waitFor(() => expect(actions).toHaveTextContent('Aborts: 1'));+ await userEvent.click(+ input.getByRole('button', { name: 'Remove profile image' }),+ );+ await userEvent.click(canvas.getByRole('button', { name: 'Start upload' }));+ const emptyAbort = await input.findByRole('button', {+ name: 'Cancel profile upload',+ });++ emptyAbort.focus();+ await userEvent.keyboard('{Enter}');+ await waitFor(() => expect(actions).toHaveTextContent('Aborts: 2'));+ await expect(input.queryByRole('presentation')).not.toBeInTheDocument();++ const fileInput = imageInput.querySelector('input[type="file"]');++ if (!(fileInput instanceof HTMLInputElement)) {+ throw new Error('ImageInput must render a native file input');+ }++ await expect(fileInput).toHaveAttribute('accept', 'image/*');+ await expect(fileInput).not.toBeVisible();+ await userEvent.upload(+ fileInput,+ new File(['image'], 'profile.png', { type: 'image/png' }),+ );+ await waitFor(() => expect(actions).toHaveTextContent('Uploads: 1'));+ await expect(canvas.getByLabelText('Selected image')).toHaveTextContent(+ 'profile.png; image/png; 5 bytes',+ );+};diff --git a/packages/twenty-front/src/modules/settings/components/SettingsImageInput.tsx b/packages/twenty-front/src/modules/settings/components/SettingsImageInput.tsxnew file mode 100644index 00000000000..4ceac154c05--- /dev/null+++ b/packages/twenty-front/src/modules/settings/components/SettingsImageInput.tsx@@ -0,0 +1,45 @@+import { useLingui } from '@lingui/react/macro';+import { ImageInput, type ImageInputProps } from 'twenty-ui/components';++import { getAbsoluteImageUrl } from '~/utils/image/getAbsoluteImageUrl';++type SettingsImageInputProps = Pick<+ ImageInputProps,+ | 'onUpload'+ | 'onRemove'+ | 'onAbort'+ | 'isUploading'+ | 'errorMessage'+ | 'disabled'+> & {+ picture: string | null | undefined;+};++export const SettingsImageInput = ({+ picture,+ onUpload,+ onRemove,+ onAbort,+ isUploading,+ errorMessage,+ disabled,+}: SettingsImageInputProps) => {+ const { t } = useLingui();++ return (+ <ImageInput+ onUpload={onUpload}+ onRemove={onRemove}+ onAbort={onAbort}+ isUploading={isUploading}+ errorMessage={errorMessage}+ disabled={disabled}+ src={getAbsoluteImageUrl(picture)}+ accept="image/jpeg, image/png, image/gif"+ uploadLabel={t`Upload`}+ removeLabel={t`Remove`}+ abortLabel={t`Abort`}+ helperText={t`We support your square PNGs, JPEGs and GIFs under 10MB`}+ />+ );+};diff --git a/packages/twenty-front/src/modules/settings/components/__stories__/SettingsImageInput.stories.tsx b/packages/twenty-front/src/modules/settings/components/__stories__/SettingsImageInput.stories.tsxnew file mode 100644index 00000000000..6a52e75676f--- /dev/null+++ b/packages/twenty-front/src/modules/settings/components/__stories__/SettingsImageInput.stories.tsx@@ -0,0 +1,55 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { expect, fn, within } from 'storybook/test';+import { ComponentDecorator } from 'twenty-ui/testing';++import { SettingsImageInput } from '@/settings/components/SettingsImageInput';+import { workspaceLogoUrl } from '~/testing/mock-data/users';++const meta: Meta<typeof SettingsImageInput> = {+ title: 'Modules/Settings/SettingsImageInput',+ component: SettingsImageInput,+ decorators: [ComponentDecorator],+ args: { onUpload: fn(), onRemove: fn() },+};++export default meta;+type Story = StoryObj<typeof SettingsImageInput>;++export const Default: Story = {+ args: { picture: null },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(+ canvas.getByText(+ 'We support your square PNGs, JPEGs and GIFs under 10MB',+ ),+ ).toBeVisible();+ await expect(canvas.getByRole('button', { name: 'Remove' })).toBeDisabled();+ await expect(+ canvasElement.querySelector('input[type="file"]'),+ ).toHaveAttribute('accept', 'image/jpeg, image/png, image/gif');+ },+};++export const WithPicture: Story = {+ args: { picture: workspaceLogoUrl },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(await canvas.findByRole('presentation')).toHaveAttribute(+ 'src',+ workspaceLogoUrl,+ );+ await expect(canvas.getByRole('button', { name: 'Remove' })).toBeEnabled();+ },+};++export const Uploading: Story = {+ args: { picture: workspaceLogoUrl, isUploading: true, onAbort: fn() },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expect(canvas.getByRole('button', { name: 'Abort' })).toBeEnabled();+ },+};diff --git a/packages/twenty-front/src/modules/settings/workspace-member/components/WorkspaceMemberPictureUploader.tsx b/packages/twenty-front/src/modules/settings/workspace-member/components/WorkspaceMemberPictureUploader.tsxindex a317e8fb991..9537db514c3 100644--- a/packages/twenty-front/src/modules/settings/workspace-member/components/WorkspaceMemberPictureUploader.tsx+++ b/packages/twenty-front/src/modules/settings/workspace-member/components/WorkspaceMemberPictureUploader.tsx@@ -5,7 +5,7 @@ import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMembeimport { useUploadWorkspaceMemberProfilePicture } from '@/settings/members/hooks/useUploadWorkspaceMemberProfilePicture';import { useCanEditProfileField } from '@/settings/profile/hooks/useCanEditProfileField';import { useUpdateWorkspaceMemberSettings } from '@/settings/profile/hooks/useUpdateWorkspaceMemberSettings';-import { ImageInput } from '@/ui/input/components/ImageInput';+import { SettingsImageInput } from '@/settings/components/SettingsImageInput';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import { FileFolder } from 'twenty-shared/types';@@ -29,6 +29,7 @@ export const WorkspaceMemberPictureUploader = ({}: WorkspaceMemberPictureUploaderProps) => {const { enqueueToast } = useToast();const [isUploading, setIsUploading] = useState(false);+ const [isRemoving, setIsRemoving] = useState(false);const [errorMessage, setErrorMessage] = useState<string | null>(null);const [uploadController, setUploadController] =useState<AbortController | null>(null);@@ -86,6 +87,10 @@ export const WorkspaceMemberPictureUploader = ({setUploadController(null);setErrorMessage(null);} catch (error) {+ if (controller.signal.aborted) {+ return;+ }+const message =error instanceof Error ? error.message : t`Failed to upload picture`;setErrorMessage(t`An error occurred while uploading the picture.`);@@ -100,7 +105,7 @@ export const WorkspaceMemberPictureUploader = ({return;}- setIsUploading(true);+ setIsRemoving(true);setErrorMessage(null);try {@@ -120,7 +125,7 @@ export const WorkspaceMemberPictureUploader = ({setErrorMessage(t`An error occurred while removing the picture.`);enqueueToast({ variant: 'error', children: message });} finally {- setIsUploading(false);+ setIsRemoving(false);}};@@ -140,12 +145,12 @@ export const WorkspaceMemberPictureUploader = ({avatarUrl ?? (isEditingSelf ? currentWorkspaceMember?.avatarUrl : null);return (- <ImageInput+ <SettingsImageInputpicture={displayAvatarUrl}onUpload={handleUpload}onRemove={handleRemove}- onAbort={handleAbort}- isUploading={isUploading}+ onAbort={isUploading ? handleAbort : undefined}+ isUploading={isUploading || isRemoving}errorMessage={errorMessage}disabled={!canEdit}/>diff --git a/packages/twenty-front/src/modules/settings/workspace/components/WorkspaceLogoUploader.tsx b/packages/twenty-front/src/modules/settings/workspace/components/WorkspaceLogoUploader.tsxindex 3fb1e133284..934e830be9b 100644--- a/packages/twenty-front/src/modules/settings/workspace/components/WorkspaceLogoUploader.tsx+++ b/packages/twenty-front/src/modules/settings/workspace/components/WorkspaceLogoUploader.tsx@@ -1,58 +1,94 @@+import { t } from '@lingui/core/macro';+import { useState } from 'react';+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';-import { ImageInput } from '@/ui/input/components/ImageInput';+import { SettingsImageInput } from '@/settings/components/SettingsImageInput';import { useUploadWorkspaceLogo } from '@/workspace/hooks/useUploadWorkspaceLogo';import { useMutation } from '@apollo/client/react';+import { useToast } from 'twenty-ui/components';import { UpdateWorkspaceDocument } from '~/generated-metadata/graphql';import { isUndefinedOrNull } from '~/utils/isUndefinedOrNull';export const WorkspaceLogoUploader = () => {+ const { enqueueToast } = useToast();const { uploadWorkspaceLogo } = useUploadWorkspaceLogo();const [updateWorkspace] = useMutation(UpdateWorkspaceDocument);const [currentWorkspace, setCurrentWorkspace] = useAtomState(currentWorkspaceState,);+ const [isUploading, setIsUploading] = useState(false);+ const [isRemoving, setIsRemoving] = useState(false);+ const [errorMessage, setErrorMessage] = useState<string | null>(null);const onUpload = async (file: File) => {if (isUndefinedOrNull(file)) {return;}- if (!currentWorkspace?.id) {- throw new Error('Workspace id not found');- }- const uploadedLogo = await uploadWorkspaceLogo(file);+ setIsUploading(true);+ setErrorMessage(null);++ try {+ if (!currentWorkspace?.id) {+ throw new Error(t`Failed to upload picture`);+ }- setCurrentWorkspace({- ...currentWorkspace,- logo: uploadedLogo.url,- });+ const uploadedLogo = await uploadWorkspaceLogo(file);++ setCurrentWorkspace({+ ...currentWorkspace,+ logo: uploadedLogo.url,+ });+ } catch (error) {+ const message =+ error instanceof Error ? error.message : t`Failed to upload picture`;+ setErrorMessage(t`An error occurred while uploading the picture.`);+ enqueueToast({ variant: 'error', children: message });+ } finally {+ setIsUploading(false);+ }};const onRemove = async () => {- if (!currentWorkspace?.id) {- throw new Error('Workspace id not found');- }- await updateWorkspace({- variables: {- input: {- logo: null,+ setIsRemoving(true);+ setErrorMessage(null);++ try {+ if (!currentWorkspace?.id) {+ throw new Error(t`Failed to remove picture`);+ }++ await updateWorkspace({+ variables: {+ input: {+ logo: null,+ },},- },- onCompleted: () => {- setCurrentWorkspace({- ...currentWorkspace,- logo: null,- });- },- });+ onCompleted: () => {+ setCurrentWorkspace({+ ...currentWorkspace,+ logo: null,+ });+ },+ });+ } catch (error) {+ const message =+ error instanceof Error ? error.message : t`Failed to remove picture`;+ setErrorMessage(t`An error occurred while removing the picture.`);+ enqueueToast({ variant: 'error', children: message });+ } finally {+ setIsRemoving(false);+ }};return (- <ImageInput+ <SettingsImageInputpicture={currentWorkspace?.logo}onUpload={onUpload}onRemove={onRemove}+ isUploading={isUploading || isRemoving}+ errorMessage={errorMessage}/>);};diff --git a/packages/twenty-front/src/modules/ui/input/components/ImageInput.tsx b/packages/twenty-front/src/modules/ui/input/components/ImageInput.tsxdeleted file mode 100644index b970fa96cb9..00000000000--- a/packages/twenty-front/src/modules/ui/input/components/ImageInput.tsx+++ /dev/null@@ -1,182 +0,0 @@-import { styled } from '@linaria/react';-import { Trans, useLingui } from '@lingui/react/macro';--import { isNonEmptyString } from '@sniptt/guards';-import React, { useState } from 'react';-import { getImageAbsoluteURI, isDefined } from 'twenty-shared/utils';-import { IconPhotoUp, IconTrash, IconUpload, IconX } from 'twenty-ui/icon';-import { Button } from 'twenty-ui/primitives/input';-import { useTheme, themeCssVariables } from 'twenty-ui/theme';-import { REACT_APP_SERVER_BASE_URL } from '~/config';-const StyledContainer = styled.div`- display: flex;- flex-direction: row;-`;--const StyledPicture = styled.button<{ withPicture: boolean }>`- align-items: center;- background: ${({ disabled }) =>- disabled- ? themeCssVariables.background.secondary- : themeCssVariables.background.transparent.light};- border: 1px solid ${themeCssVariables.border.color.medium};- border-radius: ${themeCssVariables.border.radius.md};- box-sizing: content-box;- color: ${themeCssVariables.font.color.light};- cursor: ${({ disabled }) => (disabled ? 'not-allowed' : 'pointer')};- display: flex;- height: 66px;- justify-content: center;- overflow: hidden;- padding: 0;- transition: background 0.1s ease;-- width: 66px;-- img {- height: 100%;- object-fit: cover;- width: 100%;- }-- &:hover svg {- color: ${themeCssVariables.font.color.tertiary};- }-- &:hover {- background: ${({ withPicture, disabled }) =>- withPicture || disabled- ? 'transparent'- : themeCssVariables.background.transparent.medium};- }-`;--const StyledContent = styled.div`- display: flex;- flex: 1;- flex-direction: column;- gap: ${themeCssVariables.spacing[3]};- justify-content: start;-- margin-left: ${themeCssVariables.spacing[4]};-`;--const StyledButtonContainer = styled.div`- display: flex;- flex-direction: row;-- gap: ${themeCssVariables.spacing[2]};-`;--const StyledText = styled.span`- color: ${themeCssVariables.font.color.light};- font-size: ${themeCssVariables.font.size.xs};-`;--const StyledErrorText = styled.span`- color: ${themeCssVariables.font.color.danger};- font-size: ${themeCssVariables.font.size.xs};- margin-top: ${themeCssVariables.spacing[1]};-`;--const StyledHiddenFileInput = styled.input`- display: none;-`;--type ImageInputProps = Omit<React.ComponentProps<'div'>, 'children'> & {- picture: string | null | undefined;- onUpload?: (file: File) => void;- onRemove?: () => void;- onAbort?: () => void;- isUploading?: boolean;- errorMessage?: string | null;- disabled?: boolean;- className?: string;-};--export const ImageInput = ({- picture,- onUpload,- onRemove,- onAbort,- isUploading = false,- errorMessage,- disabled = false,- className,-}: ImageInputProps) => {- const { t } = useLingui();- const theme = useTheme();- const hiddenFileInput = React.useRef<HTMLInputElement>(null);- const onUploadButtonClick = () => {- hiddenFileInput.current?.click();- };- const [isPictureUrlError, setIsPictureUrlError] = useState(false);-- const pictureURI = isNonEmptyString(picture)- ? getImageAbsoluteURI({- imageUrl: picture,- baseUrl: REACT_APP_SERVER_BASE_URL,- })- : null;-- return (- <StyledContainer className={className}>- <StyledPicture- withPicture={!!pictureURI}- disabled={disabled}- onClick={onUploadButtonClick}- >- {pictureURI && !isPictureUrlError ? (- <img- src={pictureURI}- alt="profile"- onError={() => {- setIsPictureUrlError(true);- }}- />- ) : (- <IconPhotoUp size={theme.icon.size.lg} />- )}- </StyledPicture>- <StyledContent>- <StyledButtonContainer>- <StyledHiddenFileInput- type="file"- ref={hiddenFileInput}- accept="image/jpeg, image/png, image/gif" // to desired specification- onChange={(event) => {- if (isDefined(onUpload) && isDefined(event.target.files)) {- onUpload(event.target.files[0]);- }- }}- />- {isUploading && onAbort ? (- <Button- startIcon={<IconX />}- onClick={onAbort}- disabled={!pictureURI || disabled}- variant="outline"- >{t`Abort`}</Button>- ) : (- <Button- startIcon={<IconUpload />}- onClick={onUploadButtonClick}- disabled={disabled}- variant="outline"- >{t`Upload`}</Button>- )}- <Button- startIcon={<IconTrash />}- onClick={onRemove}- disabled={!pictureURI || disabled}- variant="outline"- >{t`Remove`}</Button>- </StyledButtonContainer>- <StyledText>- <Trans>We support your square PNGs, JPEGs and GIFs under 10MB</Trans>- </StyledText>- {errorMessage && <StyledErrorText>{errorMessage}</StyledErrorText>}- </StyledContent>- </StyledContainer>- );-};diff --git a/packages/twenty-front/src/modules/ui/input/components/__stories__/ImageInput.stories.tsx b/packages/twenty-front/src/modules/ui/input/components/__stories__/ImageInput.stories.tsxdeleted file mode 100644index 2577a016531..00000000000--- a/packages/twenty-front/src/modules/ui/input/components/__stories__/ImageInput.stories.tsx+++ /dev/null@@ -1,21 +0,0 @@-import { type Meta, type StoryObj } from '@storybook/react-vite';--import { workspaceLogoUrl } from '~/testing/mock-data/users';--import { ImageInput } from '@/ui/input/components/ImageInput';-import { ComponentDecorator } from 'twenty-ui/testing';--const meta: Meta<typeof ImageInput> = {- title: 'UI/Input/ImageInput/ImageInput',- component: ImageInput,- decorators: [ComponentDecorator],-};--export default meta;-type Story = StoryObj<typeof ImageInput>;--export const Default: Story = {};--export const WithPicture: Story = { args: { picture: workspaceLogoUrl } };--export const Disabled: Story = { args: { disabled: true } };diff --git a/packages/twenty-shared/src/constants/DocumentationPaths.ts b/packages/twenty-shared/src/constants/DocumentationPaths.tsindex a7fe3004676..d338c77ab83 100644--- a/packages/twenty-shared/src/constants/DocumentationPaths.ts+++ b/packages/twenty-shared/src/constants/DocumentationPaths.ts@@ -135,6 +135,7 @@ export const DOCUMENTATION_PATHS = {UI_COMPONENTS_CODE_EDITOR: '/ui/components/code-editor',UI_COMPONENTS_COMMAND_BLOCK: '/ui/components/command-block',UI_COMPONENTS_DROPDOWN: '/ui/components/dropdown',+ UI_COMPONENTS_IMAGE_INPUT: '/ui/components/image-input',UI_COMPONENTS_INLINE_BANNER: '/ui/components/inline-banner',UI_COMPONENTS_INPUT_ICON_BUTTON: '/ui/components/input/icon-button',UI_COMPONENTS_INPUT_LIGHT_BUTTON: '/ui/components/input/light-button',diff --git a/packages/twenty-ui/docs/components.ts b/packages/twenty-ui/docs/components.tsindex 1b36553643a..887e2b0870d 100644--- a/packages/twenty-ui/docs/components.ts+++ b/packages/twenty-ui/docs/components.ts@@ -11,6 +11,7 @@ import { TOAST_PROVIDER_PROP_DESCRIPTIONS } from './toastProviderPropDescriptionimport { TOASTER_PROP_DESCRIPTIONS } from './toasterPropDescriptions';import { RADIO_PROP_DESCRIPTIONS } from './radioPropDescriptions';import { SEARCH_INPUT_PROP_DESCRIPTIONS } from './searchInputPropDescriptions';+import { IMAGE_INPUT_PROP_DESCRIPTIONS } from './imageInputPropDescriptions';import { ANIMATED_ICON_CROSSFADE_PROP_DESCRIPTIONS } from './animatedIconCrossfadePropDescriptions';import { MENU_ITEM_PROP_DESCRIPTIONS } from './menuItemPropDescriptions';import { MENU_ITEM_AVATAR_PROP_DESCRIPTIONS } from './menuItemAvatarPropDescriptions';@@ -584,6 +585,13 @@ export const DOCUMENTED_COMPONENTS = [slug: 'components/toaster',propDescriptions: TOASTER_PROP_DESCRIPTIONS,},+ {+ name: 'ImageInput',+ source: 'components/input/ImageInput/ImageInput.tsx',+ entryPoint: 'twenty-ui/components',+ slug: 'components/image-input',+ propDescriptions: IMAGE_INPUT_PROP_DESCRIPTIONS,+ },{name: 'SearchInput',source: 'components/input/SearchInput/SearchInput.tsx',diff --git a/packages/twenty-ui/docs/imageInputPropDescriptions.ts b/packages/twenty-ui/docs/imageInputPropDescriptions.tsnew file mode 100644index 00000000000..1cb9ab377b1--- /dev/null+++ b/packages/twenty-ui/docs/imageInputPropDescriptions.ts@@ -0,0 +1,28 @@+import { type ImageInputProps } from '../src/components/input/ImageInput/types/ImageInputProps';++export const IMAGE_INPUT_PROP_DESCRIPTIONS = {+ src: 'Resolved image URL. Empty or failed images show the image placeholder.',+ onUpload:+ 'Receives the selected File. Empty and canceled selections do not call it. Selection is disabled when omitted.',+ onRemove:+ 'Requests removal of the current image. Removal is disabled without this callback or a nonempty src.',+ onAbort:+ 'Shows an abort action while uploading. It can cancel the first upload before a src exists.',+ disabled: 'Disables file selection, removal, and abort actions.',+ isUploading:+ 'Marks the module busy. Selection and removal controls that would otherwise be enabled stay focusable but unavailable. Shows Abort when onAbort is supplied.',+ helperText:+ 'Application instructions, associated with the selection controls.',+ errorMessage:+ 'Application error, displayed as an alert and associated with the selection controls.',+ uploadLabel: 'Label for the preview and Upload action.',+ removeLabel: 'Label for the Remove action.',+ abortLabel: 'Label for the Abort action.',+ accept:+ 'Native file picker filter. Defaults to image/*. The application validates the selected file.',+ render:+ 'Custom root element or render function. Keep a non-interactive root.',+ ref: 'Ref to the root element.',+ className: 'Class applied to the root element.',+ style: 'Inline style applied to the root element.',+} satisfies Partial<Record<keyof ImageInputProps, string>>;diff --git a/packages/twenty-ui/docs/label-ownership.md b/packages/twenty-ui/docs/label-ownership.mdindex 2e39a80ac47..ef100d0c00c 100644--- a/packages/twenty-ui/docs/label-ownership.md+++ b/packages/twenty-ui/docs/label-ownership.md@@ -11,6 +11,7 @@ This covers production exports under components, primitives, and icons, includin| Button, MainButton, LightButton | Children and native accessible attributes. Applications compose upcoming-feature labels with Pill. Loading preserves the supplied name and marks the button busy; its spinner is decorative. Button hints use the shared Shortcut presentation and remain decorative. `shortcutJoinLabel` supplies the sequence join label. || IconButton and LightIconButton | Caller-supplied accessible label and optional tooltip. Native `aria-labelledby` remains available and takes precedence. || SearchInput | Caller-owned placeholder and native accessible name; `filterButtonAriaLabel` defaults to `Filter`. Referenced labels take precedence over explicit labels and placeholder fallback. |+| 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 accepts native accessible names over its interactive fallback of the supplied name or `Avatar`. The visual initial or dash is hidden from assistive technology; the image has empty alternative text. || JsonTree | Callers supply empty string, array, and object labels and expanded/collapsed arrow names. JSON booleans, null, property names, and values are data. |diff --git a/packages/twenty-ui/docs/module-ownership.json b/packages/twenty-ui/docs/module-ownership.jsonindex 1e0c8d14396..8b4fc6e16d4 100644--- a/packages/twenty-ui/docs/module-ownership.json+++ b/packages/twenty-ui/docs/module-ownership.json@@ -51,6 +51,7 @@"CommandBlock","Dropdown","IconButton",+ "ImageInput","InlineBanner","JsonTree","LightButton",diff --git a/packages/twenty-ui/docs/public-exports.json b/packages/twenty-ui/docs/public-exports.jsonindex c4a49269b5d..f3963da4c7f 100644--- a/packages/twenty-ui/docs/public-exports.json+++ b/packages/twenty-ui/docs/public-exports.json@@ -20,6 +20,7 @@"Dropdown": "components/navigation/Dropdown/Dropdown","getIconTileColorShades": "components/data-display/TintedIconTile/utils/getIconTileColorShades","IconButton": "components/input/IconButton/IconButton",+ "ImageInput": "components/input/ImageInput/ImageInput","InlineBanner": "components/feedback/InlineBanner/InlineBanner","JsonTree": "components/data-display/JsonTree/JsonTree","LightButton": "components/input/LightButton/LightButton",@@ -67,6 +68,7 @@"IconButtonProps": "components/input/IconButton/types/IconButtonProps","IconButtonSize": "components/input/IconButton/types/IconButtonSize","IconTileColorShades": "components/data-display/TintedIconTile/utils/getIconTileColorShades",+ "ImageInputProps": "components/input/ImageInput/types/ImageInputProps","InlineBannerButtonProps": "components/feedback/InlineBanner/types/InlineBannerButtonProps","InlineBannerProps": "components/feedback/InlineBanner/types/InlineBannerProps","JsonNodeHighlighting": "components/data-display/JsonTree/types/JsonNodeHighlighting",diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.jsonindex a7ba6f4ca8b..2b5b507c491 100644--- a/packages/twenty-ui/generated/components.docs.json+++ b/packages/twenty-ui/generated/components.docs.json@@ -8633,6 +8633,125 @@}]},+ {+ "name": "ImageInput",+ "entryPoint": "twenty-ui/components",+ "slug": "components/image-input",+ "props": [+ {+ "name": "abortLabel",+ "type": "string",+ "required": false,+ "defaultValue": "Abort",+ "description": "Label for the Abort action."+ },+ {+ "name": "accept",+ "type": "string",+ "required": false,+ "defaultValue": "image/*",+ "description": "Native file picker filter. Defaults to image/*. The application validates the selected file."+ },+ {+ "name": "className",+ "type": "string",+ "required": false,+ "defaultValue": null,+ "description": "Class applied to the root element."+ },+ {+ "name": "disabled",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Disables file selection, removal, and abort actions."+ },+ {+ "name": "errorMessage",+ "type": "string | null",+ "required": false,+ "defaultValue": null,+ "description": "Application error, displayed as an alert and associated with the selection controls."+ },+ {+ "name": "helperText",+ "type": "string",+ "required": false,+ "defaultValue": null,+ "description": "Application instructions, associated with the selection controls."+ },+ {+ "name": "isUploading",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Marks the module busy. Selection and removal controls that would otherwise be enabled stay focusable but unavailable. Shows Abort when onAbort is supplied."+ },+ {+ "name": "onAbort",+ "type": "(() => void)",+ "required": false,+ "defaultValue": null,+ "description": "Shows an abort action while uploading. It can cancel the first upload before a src exists."+ },+ {+ "name": "onRemove",+ "type": "(() => void)",+ "required": false,+ "defaultValue": null,+ "description": "Requests removal of the current image. Removal is disabled without this callback or a nonempty src."+ },+ {+ "name": "onUpload",+ "type": "((file: File) => void)",+ "required": false,+ "defaultValue": null,+ "description": "Receives the selected File. Empty and canceled selections do not call it. Selection is disabled when omitted."+ },+ {+ "name": "ref",+ "type": "Ref<HTMLDivElement>",+ "required": false,+ "defaultValue": null,+ "description": "Ref to the root element."+ },+ {+ "name": "removeLabel",+ "type": "string",+ "required": false,+ "defaultValue": "Remove",+ "description": "Label for the Remove action."+ },+ {+ "name": "render",+ "type": "ReactElement<unknown, string | JSXElementConstructor<any>> | ComponentRenderFn<HTMLProps, {}>",+ "required": false,+ "defaultValue": null,+ "description": "Custom root element or render function. Keep a non-interactive root."+ },+ {+ "name": "src",+ "type": "string | null",+ "required": false,+ "defaultValue": null,+ "description": "Resolved image URL. Empty or failed images show the image placeholder."+ },+ {+ "name": "style",+ "type": "CSSProperties",+ "required": false,+ "defaultValue": null,+ "description": "Inline style applied to the root element."+ },+ {+ "name": "uploadLabel",+ "type": "string",+ "required": false,+ "defaultValue": "Upload",+ "description": "Label for the preview and Upload action."+ }+ ]+ },{"name": "SearchInput","entryPoint": "twenty-ui/components",diff --git a/packages/twenty-ui/src/components/index.ts b/packages/twenty-ui/src/components/index.tsindex 697318ea1ab..28f85df3440 100644--- a/packages/twenty-ui/src/components/index.ts+++ b/packages/twenty-ui/src/components/index.ts@@ -42,6 +42,8 @@ export type { ToasterProps } from './feedback/Toaster/types/ToasterProps';export { IconButton } from './input/IconButton/IconButton';export type { IconButtonProps } from './input/IconButton/types/IconButtonProps';export type { IconButtonSize } from './input/IconButton/types/IconButtonSize';+export { ImageInput } from './input/ImageInput/ImageInput';+export type { ImageInputProps } from './input/ImageInput/types/ImageInputProps';export { LightButton } from './input/LightButton/LightButton';export type { LightButtonProps } from './input/LightButton/types/LightButtonProps';export { LightIconButton } from './input/LightIconButton/LightIconButton';diff --git a/packages/twenty-ui/src/components/input/ImageInput/ImageInput.module.scss b/packages/twenty-ui/src/components/input/ImageInput/ImageInput.module.scssnew file mode 100644index 00000000000..d03cef38215--- /dev/null+++ b/packages/twenty-ui/src/components/input/ImageInput/ImageInput.module.scss@@ -0,0 +1,86 @@+.root {+ display: flex;+ flex-direction: row;+}++.preview {+ @include focus-ring;++ align-items: center;+ background: var(--t-background-transparent-light);+ block-size: 66px;+ border: 1px solid var(--t-border-color-medium);+ border-radius: var(--t-border-radius-md);+ box-sizing: content-box;+ color: var(--t-font-color-light);+ cursor: pointer;+ display: flex;+ flex-shrink: 0;+ inline-size: 66px;+ justify-content: center;+ overflow: hidden;+ padding: 0;+ transition: background 0.1s ease;++ &:disabled,+ &[aria-disabled='true'] {+ background: var(--t-background-secondary);+ cursor: not-allowed;+ }++ &:not(:disabled, [aria-disabled='true']) {+ @include hover-capable {+ &:hover {+ background: var(--t-background-transparent-medium);+ }++ &:has(.image):hover {+ background: transparent;+ }++ &:hover svg {+ color: var(--t-font-color-tertiary);+ }+ }+ }++ @media (prefers-reduced-motion: reduce) {+ transition: none;+ }+}++.fileInput {+ display: none;+}++.image {+ block-size: 100%;+ inline-size: 100%;+ object-fit: cover;+}++.content {+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: var(--t-spacing-3);+ justify-content: start;+ margin-inline-start: var(--t-spacing-4);+}++.actions {+ display: flex;+ flex-direction: row;+ gap: var(--t-spacing-2);+}++.helperText {+ color: var(--t-font-color-light);+ font-size: var(--t-font-size-xs);+}++.errorMessage {+ color: var(--t-font-color-danger);+ font-size: var(--t-font-size-xs);+ margin-block-start: var(--t-spacing-1);+}diff --git a/packages/twenty-ui/src/components/input/ImageInput/ImageInput.module.scss.d.ts b/packages/twenty-ui/src/components/input/ImageInput/ImageInput.module.scss.d.tsnew file mode 100644index 00000000000..5966443740f--- /dev/null+++ b/packages/twenty-ui/src/components/input/ImageInput/ImageInput.module.scss.d.ts@@ -0,0 +1,11 @@+declare const classNames: {+ readonly root: 'root';+ readonly preview: 'preview';+ readonly fileInput: 'fileInput';+ readonly image: 'image';+ readonly content: 'content';+ readonly actions: 'actions';+ readonly helperText: 'helperText';+ readonly errorMessage: 'errorMessage';+};+export default classNames;diff --git a/packages/twenty-ui/src/components/input/ImageInput/ImageInput.tsx b/packages/twenty-ui/src/components/input/ImageInput/ImageInput.tsxnew file mode 100644index 00000000000..eebc9a30a52--- /dev/null+++ b/packages/twenty-ui/src/components/input/ImageInput/ImageInput.tsx@@ -0,0 +1,153 @@+import { useRender } from '@base-ui/react/use-render';+import { isNonEmptyString } from '@sniptt/guards';+import { clsx } from 'clsx';+import { type ChangeEvent, useId, useRef } from 'react';++import { IconTrash, IconUpload, IconX } from '@ui/icon';+import { Button } from '@ui/primitives/input/Button/Button';+import { isDefined } from '@ui/utilities/utils/isDefined';++import styles from './ImageInput.module.scss';+import { ImageInputPreview } from './internal/ImageInputPreview';+import { type ImageInputProps } from './types/ImageInputProps';++export const ImageInput = ({+ src,+ onUpload,+ onRemove,+ onAbort,+ disabled = false,+ isUploading = false,+ helperText,+ errorMessage,+ uploadLabel = 'Upload',+ removeLabel = 'Remove',+ abortLabel = 'Abort',+ accept = 'image/*',+ className,+ render,+ ref,+ ...props+}: ImageInputProps) => {+ const fileInputRef = useRef<HTMLInputElement>(null);+ const descriptionId = useId();+ const helperTextId = `${descriptionId}-helper`;+ const errorMessageId = `${descriptionId}-error`;+ const hasPicture = isNonEmptyString(src);+ const hasHelperText = isNonEmptyString(helperText);+ const hasErrorMessage = isNonEmptyString(errorMessage);+ const isSelectionUnavailable = disabled || !isDefined(onUpload);+ const isRemovalUnavailable = disabled || !hasPicture || !isDefined(onRemove);+ const isUploadDisabled = isSelectionUnavailable || isUploading;+ const isRemoveDisabled = isRemovalUnavailable || isUploading;+ const showAbort = isUploading && isDefined(onAbort);+ const describedBy =+ [hasHelperText && helperTextId, hasErrorMessage && errorMessageId]+ .filter(isNonEmptyString)+ .join(' ') || undefined;++ const openFilePicker = () => {+ if (isUploadDisabled) {+ return;+ }++ fileInputRef.current?.click();+ };++ const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {+ const file = event.currentTarget.files?.[0];++ event.currentTarget.value = '';++ if (isUploadDisabled || !isDefined(file)) {+ return;+ }++ onUpload?.(file);+ };++ return useRender({+ render,+ ref,+ props: {+ ...props,+ className: clsx(styles.root, className),+ 'aria-busy': isUploading || props['aria-busy'],+ children: (+ <>+ <button+ className={styles.preview}+ type="button"+ disabled={isSelectionUnavailable}+ aria-disabled={isUploading || undefined}+ aria-label={uploadLabel}+ aria-describedby={describedBy}+ onClick={openFilePicker}+ >+ <ImageInputPreview key={src} src={src} />+ </button>+ <div className={styles.content}>+ <div className={styles.actions}>+ <input+ ref={fileInputRef}+ className={styles.fileInput}+ type="file"+ accept={accept}+ disabled={isUploadDisabled}+ hidden+ onChange={handleFileChange}+ />+ {showAbort ? (+ <Button+ type="button"+ startIcon={<IconX />}+ onClick={onAbort}+ disabled={disabled}+ variant="outline"+ >+ {abortLabel}+ </Button>+ ) : (+ <Button+ type="button"+ startIcon={<IconUpload />}+ onClick={openFilePicker}+ disabled={isUploadDisabled}+ focusableWhenDisabled={isUploading && !isSelectionUnavailable}+ aria-describedby={describedBy}+ variant="outline"+ >+ {uploadLabel}+ </Button>+ )}+ <Button+ type="button"+ startIcon={<IconTrash />}+ onClick={onRemove}+ disabled={isRemoveDisabled}+ focusableWhenDisabled={isUploading && !isRemovalUnavailable}+ variant="outline"+ >+ {removeLabel}+ </Button>+ </div>+ {hasHelperText && (+ <span className={styles.helperText} id={helperTextId}>+ {helperText}+ </span>+ )}+ {hasErrorMessage && (+ <span+ className={styles.errorMessage}+ id={errorMessageId}+ role="alert"+ >+ {errorMessage}+ </span>+ )}+ </div>+ </>+ ),+ },+ });+};diff --git a/packages/twenty-ui/src/components/input/ImageInput/__stories__/ImageInput.interactions.stories.tsx b/packages/twenty-ui/src/components/input/ImageInput/__stories__/ImageInput.interactions.stories.tsxnew file mode 100644index 00000000000..aef22d8aae3--- /dev/null+++ b/packages/twenty-ui/src/components/input/ImageInput/__stories__/ImageInput.interactions.stories.tsx@@ -0,0 +1,242 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';++import { Button } from '@ui/primitives/input/Button/Button';+import { A11Y_DEFER_COLOR_CONTRAST, ComponentDecorator } from '@ui/testing';+import { isDefined } from '@ui/utilities/utils/isDefined';++import { ImageInput } from '../ImageInput';+import { IMAGE_INPUT_PREVIEW_URL } from './imageInputPreviewUrl';+import { ImageInputPreviewChangesExample } from './ImageInputPreviewChangesExample';++const getFileInput = (canvasElement: HTMLElement) => {+ const fileInput =+ canvasElement.querySelector<HTMLInputElement>('input[type="file"]');++ if (!isDefined(fileInput)) {+ throw new Error('The image selector must contain a file input.');+ }++ return fileInput;+};++const meta: Meta<typeof ImageInput> = {+ title: 'UI/Input/ImageInput/Interactions',+ component: ImageInput,+ tags: ['!autodocs'],+ decorators: [ComponentDecorator],+ parameters: { a11y: A11Y_DEFER_COLOR_CONTRAST },+ args: { onUpload: fn(), onRemove: fn(), onAbort: fn() },+};++export default meta;+type Story = StoryObj<typeof ImageInput>;++export const NativeButtonsInForm: Story = {+ args: { src: IMAGE_INPUT_PREVIEW_URL },+ render: (args) => (+ <form+ aria-label="Workspace image"+ onSubmit={(event) => event.preventDefault()}+ >+ <ImageInput {...args} />+ <Button type="submit">Save workspace</Button>+ </form>+ ),+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const previewButton = canvas.getByRole('presentation').closest('button');+ const uploadButton = canvas.getByText('Upload').closest('button');+ if (!isDefined(previewButton) || !isDefined(uploadButton)) {+ throw new Error('The image selector must provide both upload buttons.');+ }++ const removeButton = canvas.getByRole('button', { name: 'Remove' });+ const fileInput = getFileInput(canvasElement);+ const form = canvas.getByRole('form', { name: 'Workspace image' });+ const onSubmit = fn();+ const onFilePicker = fn((event: Event) => event.preventDefault());+ form.addEventListener('submit', onSubmit);+ fileInput.addEventListener('click', onFilePicker);++ try {+ await userEvent.click(previewButton);+ await expect(onFilePicker).toHaveBeenCalledTimes(1);+ previewButton.focus();+ await userEvent.keyboard('{Enter}');+ await userEvent.keyboard(' ');+ await expect(onFilePicker).toHaveBeenCalledTimes(3);+ await userEvent.click(uploadButton);+ await expect(onFilePicker).toHaveBeenCalledTimes(4);+ await userEvent.click(removeButton);+ removeButton.focus();+ await userEvent.keyboard('{Enter}');+ await expect(args.onRemove).toHaveBeenCalledTimes(2);+ await expect(onSubmit).not.toHaveBeenCalled();+ await expect(args.onUpload).not.toHaveBeenCalled();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Save workspace' }),+ );+ await expect(onSubmit).toHaveBeenCalledOnce();+ } finally {+ form.removeEventListener('submit', onSubmit);+ fileInput.removeEventListener('click', onFilePicker);+ }+ },+};++export const FileSelectionAndRetry: Story = {+ args: { accept: 'image/png' },+ play: async ({ canvasElement, args }) => {+ const fileInput = getFileInput(canvasElement);+ const file = new File(['image'], 'workspace.png', { type: 'image/png' });++ await expect(fileInput).not.toBeVisible();+ await expect(fileInput).toHaveAttribute('accept', 'image/png');+ await expect(fileInput).not.toHaveAttribute('multiple');+ await userEvent.upload(fileInput, file);+ await expect(args.onUpload).toHaveBeenCalledOnce();+ await expect(args.onUpload).toHaveBeenCalledWith(file);+ await expect(fileInput).toHaveValue('');+ await userEvent.upload(fileInput, file);+ await expect(args.onUpload).toHaveBeenCalledTimes(2);+ await expect(args.onUpload).toHaveBeenLastCalledWith(file);+ fileInput.dispatchEvent(new Event('cancel', { bubbles: true }));+ fileInput.dispatchEvent(new Event('change', { bubbles: true }));+ await expect(args.onUpload).toHaveBeenCalledTimes(2);+ },+};++export const Disabled: Story = {+ args: { disabled: true, src: IMAGE_INPUT_PREVIEW_URL },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const fileInput = getFileInput(canvasElement);+ const onFilePicker = fn();+ fileInput.addEventListener('click', onFilePicker);++ try {+ for (const button of canvas.getAllByRole('button')) {+ await expect(button).toBeDisabled();+ await userEvent.click(button);+ }+ await expect(fileInput).toBeDisabled();+ await expect(onFilePicker).not.toHaveBeenCalled();+ await expect(args.onUpload).not.toHaveBeenCalled();+ await expect(args.onRemove).not.toHaveBeenCalled();+ } finally {+ fileInput.removeEventListener('click', onFilePicker);+ }+ },+};++export const UploadingWithoutAbort: Story = {+ args: { isUploading: true, src: IMAGE_INPUT_PREVIEW_URL, onAbort: undefined },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ for (const button of canvas.getAllByRole('button')) {+ await expect(button).toHaveAttribute('aria-disabled', 'true');+ button.focus();+ await expect(button).toHaveFocus();+ await userEvent.click(button);+ }+ await expect(getFileInput(canvasElement)).toBeDisabled();+ await expect(+ canvas.queryByRole('button', { name: 'Abort' }),+ ).not.toBeInTheDocument();+ await expect(args.onUpload).not.toHaveBeenCalled();+ await expect(args.onRemove).not.toHaveBeenCalled();+ },+};++export const AbortFirstUpload: Story = {+ args: { isUploading: true },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);+ const abortButton = canvas.getByRole('button', { name: 'Abort' });++ await expect(+ canvas.getByRole('button', { name: 'Upload' }),+ ).toHaveAttribute('aria-disabled', 'true');+ await expect(canvas.getByRole('button', { name: 'Remove' })).toBeDisabled();+ await expect(abortButton).toBeEnabled();+ abortButton.focus();+ await userEvent.keyboard('{Enter}');+ await expect(args.onAbort).toHaveBeenCalledOnce();+ await expect(args.onUpload).not.toHaveBeenCalled();+ await expect(args.onRemove).not.toHaveBeenCalled();+ },+};++export const DisabledUploadCannotAbort: Story = {+ args: { isUploading: true, disabled: true },+ play: async ({ canvasElement, args }) => {+ const abortButton = within(canvasElement).getByRole('button', {+ name: 'Abort',+ });++ await expect(abortButton).toBeDisabled();+ await userEvent.click(abortButton);+ await expect(args.onAbort).not.toHaveBeenCalled();+ },+};++export const LabelsAndError: Story = {+ args: {+ uploadLabel: 'Choose workspace image',+ removeLabel: 'Delete workspace image',+ helperText: 'Choose an image for your workspace.',+ errorMessage: 'This image exceeds your workspace limit.',+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ for (const button of canvas.getAllByRole('button', {+ name: 'Choose workspace image',+ })) {+ await expect(button).toHaveAccessibleDescription(+ 'Choose an image for your workspace. This image exceeds your workspace limit.',+ );+ }+ await expect(canvas.getByRole('alert')).toHaveTextContent(+ 'This image exceeds your workspace limit.',+ );+ await expect(+ canvas.getByRole('button', { name: 'Delete workspace image' }),+ ).toBeDisabled();+ },+};++export const PreviewFallbackAndRecovery: Story = {+ render: (args) => <ImageInputPreviewChangesExample {...args} />,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const previewButton = canvas.getByRole('presentation').closest('button');++ if (!isDefined(previewButton)) {+ throw new Error('The image preview must provide an upload button.');+ }++ await expect(await canvas.findByRole('presentation')).toBeVisible();+ await expect(previewButton).toBeEnabled();+ await expect(canvas.getByRole('button', { name: 'Remove' })).toBeEnabled();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Break preview' }),+ );+ await waitFor(() =>+ expect(canvas.queryByRole('presentation')).not.toBeInTheDocument(),+ );+ await expect(previewButton).toHaveAccessibleName('Upload');+ await userEvent.click(+ canvas.getByRole('button', { name: 'Restore preview' }),+ );+ await expect(await canvas.findByRole('presentation')).toBeVisible();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Clear preview' }),+ );+ await expect(canvas.queryByRole('presentation')).not.toBeInTheDocument();+ await expect(canvas.getByRole('button', { name: 'Remove' })).toBeDisabled();+ await expect(previewButton).toHaveAccessibleName('Upload');+ },+};diff --git a/packages/twenty-ui/src/components/input/ImageInput/__stories__/ImageInput.stories.tsx b/packages/twenty-ui/src/components/input/ImageInput/__stories__/ImageInput.stories.tsxnew file mode 100644index 00000000000..efdcd7972fb--- /dev/null+++ b/packages/twenty-ui/src/components/input/ImageInput/__stories__/ImageInput.stories.tsx@@ -0,0 +1,59 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { fn } from 'storybook/test';++import { A11Y_DEFER_COLOR_CONTRAST, ComponentDecorator } from '@ui/testing';++import { ImageInput } from '../ImageInput';+import { IMAGE_INPUT_PREVIEW_URL } from './imageInputPreviewUrl';++const meta: Meta<typeof ImageInput> = {+ title: 'UI/Input/ImageInput',+ component: ImageInput,+ args: { onUpload: fn(), onRemove: fn() },+ decorators: [ComponentDecorator],+ parameters: { a11y: A11Y_DEFER_COLOR_CONTRAST },+};++export default meta;+type Story = StoryObj<typeof ImageInput>;++export const Default: Story = {};++export const WithPicture: Story = {+ args: { src: IMAGE_INPUT_PREVIEW_URL },+};++export const WithHelperText: Story = {+ args: {+ src: IMAGE_INPUT_PREVIEW_URL,+ helperText: 'Choose a square image for your workspace.',+ },+};++export const Disabled: Story = {+ args: { disabled: true, src: IMAGE_INPUT_PREVIEW_URL },+};++export const Uploading: Story = {+ args: { isUploading: true, onAbort: fn() },+};++export const WithError: Story = {+ args: {+ helperText: 'Choose a square image for your workspace.',+ errorMessage: 'The image could not be saved. Please try again.',+ },+};++export const Dark: Story = {+ ...WithHelperText,+ globals: { colorScheme: 'dark' },+};++export const RightToLeft: Story = {+ args: {+ src: IMAGE_INPUT_PREVIEW_URL,+ helperText: 'Choose a square image for your workspace.',+ dir: 'rtl',+ },+};diff --git a/packages/twenty-ui/src/components/input/ImageInput/__stories__/ImageInputPreviewChangesExample.tsx b/packages/twenty-ui/src/components/input/ImageInput/__stories__/ImageInputPreviewChangesExample.tsxnew file mode 100644index 00000000000..daa725c7b5e--- /dev/null+++ b/packages/twenty-ui/src/components/input/ImageInput/__stories__/ImageInputPreviewChangesExample.tsx@@ -0,0 +1,24 @@+import { useState } from 'react';++import { Button } from '@ui/primitives/input/Button/Button';++import { ImageInput } from '../ImageInput';+import { type ImageInputProps } from '../types/ImageInputProps';+import { IMAGE_INPUT_PREVIEW_URL } from './imageInputPreviewUrl';++const INVALID_IMAGE_URL = 'data:image/png;base64,invalid';++export const ImageInputPreviewChangesExample = (props: ImageInputProps) => {+ const [src, setSrc] = useState<string | undefined>(IMAGE_INPUT_PREVIEW_URL);++ return (+ <>+ <ImageInput {...props} src={src} />+ <Button onClick={() => setSrc(INVALID_IMAGE_URL)}>Break preview</Button>+ <Button onClick={() => setSrc(IMAGE_INPUT_PREVIEW_URL)}>+ Restore preview+ </Button>+ <Button onClick={() => setSrc(undefined)}>Clear preview</Button>+ </>+ );+};diff --git a/packages/twenty-ui/src/components/input/ImageInput/__stories__/imageInputPreviewUrl.ts b/packages/twenty-ui/src/components/input/ImageInput/__stories__/imageInputPreviewUrl.tsnew file mode 100644index 00000000000..e6e928e6571--- /dev/null+++ b/packages/twenty-ui/src/components/input/ImageInput/__stories__/imageInputPreviewUrl.ts@@ -0,0 +1,5 @@+export const IMAGE_INPUT_PREVIEW_URL =+ 'data:image/svg+xml,' ++ encodeURIComponent(+ '<svg xmlns="http://www.w3.org/2000/svg" width="68" height="68" viewBox="0 0 68 68"><rect width="68" height="68" fill="#232529"/><path d="M16 22h36v8H38v24h-8V30H16z" fill="white"/></svg>',+ );diff --git a/packages/twenty-ui/src/components/input/ImageInput/__tests__/ImageInput.test.tsx b/packages/twenty-ui/src/components/input/ImageInput/__tests__/ImageInput.test.tsxnew file mode 100644index 00000000000..9117d045c4f--- /dev/null+++ b/packages/twenty-ui/src/components/input/ImageInput/__tests__/ImageInput.test.tsx@@ -0,0 +1,9 @@+import { runComponentConformance } from '@test-utilities/conformance/runComponentConformance';++import { ImageInput } from '../ImageInput';++runComponentConformance({+ name: 'ImageInput',+ element: <ImageInput />,+ refInstanceOf: HTMLDivElement,+});diff --git a/packages/twenty-ui/src/components/input/ImageInput/internal/ImageInputPreview.tsx b/packages/twenty-ui/src/components/input/ImageInput/internal/ImageInputPreview.tsxnew file mode 100644index 00000000000..642c064b67e--- /dev/null+++ b/packages/twenty-ui/src/components/input/ImageInput/internal/ImageInputPreview.tsx@@ -0,0 +1,29 @@+import { isNonEmptyString } from '@sniptt/guards';+import { useState } from 'react';++import { IconPhotoUp } from '@ui/icon';+import { useTheme } from '@ui/theme';++import styles from '../ImageInput.module.scss';++type ImageInputPreviewProps = {+ src?: string | null;+};++export const ImageInputPreview = ({ src }: ImageInputPreviewProps) => {+ const theme = useTheme();+ const [hasError, setHasError] = useState(false);++ if (!isNonEmptyString(src) || hasError) {+ return <IconPhotoUp size={theme.icon.size.lg} aria-hidden />;+ }++ return (+ <img+ className={styles.image}+ src={src}+ alt=""+ onError={() => setHasError(true)}+ />+ );+};diff --git a/packages/twenty-ui/src/components/input/ImageInput/types/ImageInputProps.ts b/packages/twenty-ui/src/components/input/ImageInput/types/ImageInputProps.tsnew file mode 100644index 00000000000..4ccdb967af7--- /dev/null+++ b/packages/twenty-ui/src/components/input/ImageInput/types/ImageInputProps.ts@@ -0,0 +1,19 @@+import { type useRender } from '@base-ui/react/use-render';++export type ImageInputProps = Omit<+ useRender.ComponentProps<'div'>,+ 'children' | 'onAbort'+> & {+ src?: string | null;+ onUpload?: (file: File) => void;+ onRemove?: () => void;+ onAbort?: () => void;+ disabled?: boolean;+ isUploading?: boolean;+ helperText?: string;+ errorMessage?: string | null;+ uploadLabel?: string;+ removeLabel?: string;+ abortLabel?: string;+ accept?: string;+};