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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/mosaic-avatar-drag-to-upload.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/mosaic': patch
---

Drop an image onto the profile picture row in `UserProfile` or the logo row in `OrganizationProfile` to upload it. While a file is dragged over the row, the avatar darkens and shows an upload icon. `FileUpload.Dropzone` now ignores drags that carry no files, such as selected text or links.
1 change: 1 addition & 0 deletions packages/mosaic/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ Most problems a feature hits already have a shared answer. Find the row for your
| An organization permission checked with `checkAuthorization` | `ORGANIZATION_PERMISSIONS` (`src/utils/permissions.ts`) |
| A verification code's length or resend cooldown | `CODE_LENGTH`, `CODE_RESEND_SECONDS` (`src/utils/verification.ts`) |
| An avatar or logo file picker and its rejection errors | `AVATAR_UPLOAD`, `AVATAR_REJECTION_ERRORS` (`src/utils/avatar-upload.ts`) |
| Dropping a file onto an avatar or logo row | `AvatarDropzone` (`src/components/avatar-dropzone/`) inside the row's `FileUpload.Root` |
| Siblings that slide when an item is added or removed | `useLayoutAnimation` (`src/primitives/hooks/`) |
| An input that reformats as the user types without moving the caret | `useFormattedInput` (`src/primitives/hooks/`) |
| A panel that animates open and closed to its measured size | `usePanelSize` (`src/primitives/hooks/`) |
Expand Down
19 changes: 19 additions & 0 deletions packages/mosaic/src/__tests__/feature/drag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { act } from '@testing-library/react';

export function dragFilesOver(target: Element, ...files: File[]) {
dispatchDrag(target, 'dragenter', files);
}

export function dropFiles(target: Element, ...files: File[]) {
dispatchDrag(target, 'drop', files);
}

function dispatchDrag(target: Element, type: 'dragenter' | 'drop', files: File[]) {
const dataTransfer = new DataTransfer();
for (const file of files) {
dataTransfer.items.add(file);
}
act(() => {
target.dispatchEvent(new DragEvent(type, { bubbles: true, cancelable: true, dataTransfer }));
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import * as stylex from '@stylexjs/stylex';

export const avatarDropzoneScope = stylex.defineMarker();
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import * as stylex from '@stylexjs/stylex';

import { durationVars, easingVars } from '../../tokens.stylex';
import { avatarDropzoneScope } from './avatar-dropzone.markers.stylex';

export const styles = stylex.create({
overlay: {
inset: 0,
borderRadius: 'inherit',
alignItems: 'center',
backgroundColor: 'color-mix(in oklab, oklch(0 0 0) 50%, transparent)',
color: 'oklch(1 0 0)',
display: 'flex',
justifyContent: 'center',
opacity: {
default: 0,
[stylex.when.ancestor('[data-dragging]', avatarDropzoneScope)]: 1,
},
pointerEvents: 'none',
position: 'absolute',
transitionDuration: {
default: durationVars['--cl-duration-fast'],
[stylex.when.ancestor('[data-dragging]', avatarDropzoneScope)]: durationVars['--cl-duration-base'],
},
transitionProperty: 'opacity',
transitionTimingFunction: {
default: easingVars['--cl-ease-exit'],
[stylex.when.ancestor('[data-dragging]', avatarDropzoneScope)]: easingVars['--cl-ease-enter'],
},
},
});
50 changes: 50 additions & 0 deletions packages/mosaic/src/components/avatar-dropzone/avatar-dropzone.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import * as stylex from '@stylexjs/stylex';
import React from 'react';

import { ArrowUp } from '../../icons/glyphs/arrow-up';
import { FileUpload } from '../../primitives/file-upload';
import type { MosaicComponentProps, MosaicElementProps } from '../../props';
import { mergeStyleProps, themeProps } from '../../props';
import { reset } from '../../styles/reset.styles';
import { Icon } from '../icon';
import { avatarDropzoneScope } from './avatar-dropzone.markers.stylex';
import { styles } from './avatar-dropzone.styles';

export type AvatarDropzoneProps = MosaicComponentProps<'div'>;

const AvatarDropzoneRoot = React.forwardRef<HTMLDivElement, AvatarDropzoneProps>(function MosaicAvatarDropzoneRoot(
{ xstyle, ...rest },
ref,
) {
return (
<FileUpload.Dropzone
ref={ref}
{...mergeStyleProps(themeProps('avatar-dropzone'), stylex.props(avatarDropzoneScope, xstyle), rest)}
/>
);
});

export type AvatarDropzoneOverlayProps = MosaicElementProps<'span'>;

const AvatarDropzoneOverlay = React.forwardRef<HTMLSpanElement, AvatarDropzoneOverlayProps>(
function MosaicAvatarDropzoneOverlay({ xstyle, ...rest }, ref) {
return (
<span
ref={ref}
aria-hidden
{...mergeStyleProps(
themeProps('avatar-dropzone-overlay'),
stylex.props(reset.base, styles.overlay, xstyle),
rest,
)}
>
<Icon glyph={ArrowUp} />
</span>
);
},
);

export const AvatarDropzone = {
Root: AvatarDropzoneRoot,
Overlay: AvatarDropzoneOverlay,
};
2 changes: 2 additions & 0 deletions packages/mosaic/src/components/avatar-dropzone/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { AvatarDropzone } from './avatar-dropzone';
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
export type { AvatarDropzoneOverlayProps, AvatarDropzoneProps } from './avatar-dropzone';
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event';
import { describe, expect, it } from 'vitest';

import { openDialog } from '../../../__tests__/feature/dialog';
import { dragFilesOver, dropFiles } from '../../../__tests__/feature/drag';
import { type FakeFapiSeed, holdRequests, serveFapi } from '../../../__tests__/feature/fake-fapi';
import {
fapiClient,
Expand Down Expand Up @@ -353,6 +354,33 @@ describe('OrganizationProfileGeneralPanel', () => {
expect(await screen.findByRole('button', { name: 'Upload' })).toBeVisible();
});

it('marks the row while a file is dragged over it and uploads the file dropped on it', async () => {
const { fapi } = await renderPanel();
const row = await screen.findByText('Logo');
const file = new File(['image'], 'logo.png', { type: 'image/png' });

dragFilesOver(row, file);
expect(row.closest('[data-dragging]')).not.toBeNull();

dropFiles(row, file);
expect(row.closest('[data-dragging]')).toBeNull();
await waitFor(() => expect(fapi.memberships[0]?.organization.has_image).toBe(true));
});

it('ignores a file dragged over the logo without manage permission', async () => {
await renderPanel(signedIn({ permissions: [] }));
const upload = holdRequests('post', '/v1/organizations/:organizationId/logo');
const row = await screen.findByText('Logo');
const file = new File(['image'], 'logo.png', { type: 'image/png' });

dragFilesOver(row, file);
expect(row.closest('[data-dragging]')).toBeNull();

dropFiles(row, file);
expect(upload.requests).toHaveLength(0);
upload.release();
});

it('localizes an oversized image rejection without sending a request', async () => {
serveFapi(signedIn());
const { container } = await renderWithClerk(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useState } from 'react';
import type { ActionMenuAction } from '../../../components/action-menu';
import { ActionMenu } from '../../../components/action-menu';
import { Avatar } from '../../../components/avatar';
import { AvatarDropzone } from '../../../components/avatar-dropzone';
import { Button } from '../../../components/button';
import { Section } from '../../../components/section';
import { Pen } from '../../../icons/glyphs/pen';
Expand Down Expand Up @@ -52,7 +53,7 @@ export function OrganizationProfileLogoRowView({

return (
<FileUpload.Root
disabled={logo.isPending}
disabled={logo.isPending || !onChange}
aria-busy={logo.isPending || undefined}
{...AVATAR_UPLOAD}
render={<Section.Row />}
Expand All @@ -69,7 +70,7 @@ export function OrganizationProfileLogoRowView({
}
}}
>
<Section.Item>
<AvatarDropzone.Root render={<Section.Item />}>
<Section.Media size='lg'>
<Avatar.Root
shape='square'
Expand All @@ -80,6 +81,7 @@ export function OrganizationProfileLogoRowView({
src={logo.previewUrl ?? imageUrl}
/>
<Avatar.Fallback>{initials}</Avatar.Fallback>
<AvatarDropzone.Overlay />
</Avatar.Root>
</Section.Media>
<Section.Content>
Expand All @@ -91,7 +93,7 @@ export function OrganizationProfileLogoRowView({
hasImage={hasImage}
onRemove={handleRemove}
/>
</Section.Item>
</AvatarDropzone.Root>
<Section.Error>{error}</Section.Error>
</FileUpload.Root>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { describe, expect, it } from 'vitest';

import { dragFilesOver, dropFiles } from '../../../../__tests__/feature/drag';
import {
demandReverificationOnce,
type FakeFapiSeed,
Expand Down Expand Up @@ -149,6 +150,33 @@ describe('the user profile profile section', () => {
expect(screen.getByRole('menuitem', { name: 'Remove avatar' })).toHaveAttribute('data-color', 'negative');
});

it('marks the row while a file is dragged over it and uploads the file dropped on it', async () => {
await renderSection();
const row = screen.getByText('Profile picture');
const file = new File(['x'], 'me.png', { type: 'image/png' });

dragFilesOver(row, file);
expect(row.closest('[data-dragging]')).not.toBeNull();

dropFiles(row, file);
expect(row.closest('[data-dragging]')).toBeNull();
expect(await screen.findByRole('button', { name: 'Manage profile picture' })).toBeInTheDocument();
});

it('turns away a dropped file of the wrong type without uploading it', async () => {
await renderSection();
const upload = holdRequests('post', '/v1/me/profile_image');
const row = screen.getByText('Profile picture');
const file = new File(['x'], 'notes.pdf', { type: 'application/pdf' });

dragFilesOver(row, file);
dropFiles(row, file);

expect(screen.getByRole('alert')).toBeInTheDocument();
expect(upload.requests).toHaveLength(0);
upload.release();
});

it('says why an upload was refused', async () => {
const { actor, container } = await renderSection();
failsWith('/v1/me/profile_image', { code: 'avatar_file_size_exceeded', message: 'Too large' }, 413);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { ActionMenuAction } from '../../../components/action-menu';
import { ActionMenu } from '../../../components/action-menu';
import { Avatar } from '../../../components/avatar';
import { AvatarDropzone } from '../../../components/avatar-dropzone';
import { Button } from '../../../components/button';
import { Section } from '../../../components/section';
import { useMessages } from '../../../localization';
Expand Down Expand Up @@ -36,7 +37,7 @@ export function UserProfilePictureRowView({
return (
<FileUpload.Root
{...AVATAR_UPLOAD}
disabled={isPending}
disabled={isPending || !onChange}
aria-busy={isPending || undefined}
render={<Section.Row />}
onReject={onReject}
Expand All @@ -47,14 +48,15 @@ export function UserProfilePictureRowView({
}
}}
>
<Section.Item>
<AvatarDropzone.Root render={<Section.Item />}>
<Section.Media size='lg'>
<Avatar.Root size='fit'>
<Avatar.Image
alt={name}
src={previewUrl ?? imageUrl}
/>
<Avatar.Fallback>{initials}</Avatar.Fallback>
<AvatarDropzone.Overlay />
</Avatar.Root>
</Section.Media>
<Section.Content>
Expand All @@ -66,7 +68,7 @@ export function UserProfilePictureRowView({
hasImage={hasImage}
onRemove={onRemove}
/>
</Section.Item>
</AvatarDropzone.Root>
<Section.Error>{error}</Section.Error>
</FileUpload.Root>
);
Expand Down
14 changes: 7 additions & 7 deletions packages/mosaic/src/primitives/file-upload/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ added.
| ------------------------ | --------------- | ------------------------------------------------------------------- |
| `FileUpload.Root` | `<div>` | Owns the file state + hidden input, provides context |
| `FileUpload.Trigger` | `<button>` | Opens the native file picker |
| `FileUpload.Dropzone` | `<div>` | Drag-and-drop target; filters dropped files by `accept` |
| `FileUpload.Dropzone` | `<div>` | Drag-and-drop target; ignores non-file drags, filters by `accept` |
| `FileUpload.Item` | `<div>` | Wraps a single selected file, provides item context |
| `FileUpload.ItemPreview` | `<img>` | Image thumbnail for the item's file (renders nothing for non-image) |
| `FileUpload.ItemDelete` | `<button>` | Removes the item's file |
Expand Down Expand Up @@ -152,12 +152,12 @@ standard HTML attributes for their default element.

## Data Attributes

| Attribute | Applies To | Description |
| --------------- | ----------------------------------- | ------------------------------------------- |
| `data-empty` | Root | Present when no files are selected |
| `data-dragging` | Dropzone | Present while a valid drag is over the zone |
| `data-image` | Item | Present when the item's file is an image |
| `data-disabled` | Root, Trigger, Dropzone, ItemDelete | Present when disabled |
| Attribute | Applies To | Description |
| --------------- | ----------------------------------- | ------------------------------------------ |
| `data-empty` | Root | Present when no files are selected |
| `data-dragging` | Dropzone | Present while a file drag is over the zone |
| `data-image` | Item | Present when the item's file is an image |
| `data-disabled` | Root, Trigger, Dropzone, ItemDelete | Present when disabled |

## ARIA

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ export const FileUploadDropzone = React.forwardRef<HTMLDivElement, FileUploadDro
const defaultProps: Record<string, unknown> = {
'aria-disabled': disabled || undefined,
onDragEnter: (event: DragEvent<HTMLDivElement>) => {
if (!carriesFiles(event)) {
return;
}
event.preventDefault();
if (disabled) {
return;
Expand All @@ -30,13 +33,19 @@ export const FileUploadDropzone = React.forwardRef<HTMLDivElement, FileUploadDro
setDragging(true);
},
onDragOver: (event: DragEvent<HTMLDivElement>) => {
if (!carriesFiles(event)) {
return;
}
// Required for the element to be a valid drop target.
event.preventDefault();
if (!disabled) {
event.dataTransfer.dropEffect = 'copy';
}
},
onDragLeave: (event: DragEvent<HTMLDivElement>) => {
if (!carriesFiles(event)) {
return;
}
event.preventDefault();
if (disabled) {
return;
Expand All @@ -48,6 +57,9 @@ export const FileUploadDropzone = React.forwardRef<HTMLDivElement, FileUploadDro
}
},
onDrop: (event: DragEvent<HTMLDivElement>) => {
if (!carriesFiles(event)) {
return;
}
event.preventDefault();
dragDepth.current = 0;
setDragging(false);
Expand All @@ -74,3 +86,7 @@ export const FileUploadDropzone = React.forwardRef<HTMLDivElement, FileUploadDro
});
},
);

function carriesFiles(event: DragEvent<HTMLElement>) {
return Array.from(event.dataTransfer.types).includes('Files');
}
Loading
Loading