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/wet-ants-kind.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/ui': minor
---

Add drag-to-upload support in AvatarUploader
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ export const OrganizationProfileAvatarUploader = (
/>
<AvatarUploader
{...rest}
rounded={false}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={
<OrganizationAvatar
Expand Down
82 changes: 72 additions & 10 deletions packages/ui/src/elements/AvatarUploader.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ export type AvatarUploaderProps = {
onAvatarChange: (file: File) => Promise<unknown>;
onAvatarRemove?: (() => void) | null;
avatarPreviewPlaceholder?: React.ReactElement | null;
rounded?: boolean;
};

const fileToBase64 = (file: File): Promise<string> => {
Expand All@@ -39,17 +40,21 @@ const validSize = (f: File) => f.size <= MAX_SIZE_BYTES;

export const AvatarUploader = (props: AvatarUploaderProps) => {
const { t } = useLocalizations();
const [showUpload, setShowUpload] = React.useState(false);
const [objectUrl, setObjectUrl] = React.useState<string>();
const [isDraggingOver, setIsDraggingOver] = React.useState(false);
const card = useCardState();
const inputRef = React.useRef<HTMLInputElement | null>(null);
const openDialog = () => inputRef.current?.click();

const { onAvatarChange, onAvatarRemove, title, avatarPreview, avatarPreviewPlaceholder, ...rest } = props;

const toggle = () => {
setShowUpload(!showUpload);
};
const {
onAvatarChange,
onAvatarRemove,
title,
avatarPreview,
avatarPreviewPlaceholder,
rounded = true,
...rest
} = props;

const handleFileDrop = (file: File | null) => {
if (file === null) {
Expand All@@ -60,7 +65,6 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
card.setLoading();
return onAvatarChange(file)
.then(() => {
toggle();
card.setIdle();
})
.catch(err => handleError(err, [], card.setError));
Expand All@@ -69,6 +73,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
const handleRemove = async () => {
card.setLoading();
await handleFileDrop(null);
card.setIdle();
return onAvatarRemove?.();
};

Expand All@@ -90,6 +95,46 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
await handleFileDrop(f);
};

const isFileDrag = (e: React.DragEvent) => e.dataTransfer?.types?.includes('Files') ?? false;

const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(true);
};

const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
};

const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
// Only reset when leaving the container entirely, not when moving between children.
// SAFETY: e.relatedTarget is typed as EventTarget | null, but in drag events it is always
// a DOM Node (or null). Element.contains() requires Node | null; the cast is safe here.
if (e.currentTarget.contains(e.relatedTarget as Node | null)) {
return;
}
setIsDraggingOver(false);
};

const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
if (!isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(false);
if (card.isLoading) {
return;
}
void upload(e.dataTransfer.files?.[0]);
};

const hasExistingImage = !!(avatarPreview.props as { imageUrl?: string })?.imageUrl;
const previewElement = objectUrl
? React.cloneElement(avatarPreview, { imageUrl: objectUrl })
Expand All@@ -108,11 +153,28 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
/>

<Flex
{...rest}
gap={4}
align='center'
{...rest}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
{previewElement}
<Flex
sx={t => ({
borderRadius: isDraggingOver && rounded ? t.radii.$circle : t.radii.$md,
transitionProperty: t.transitionProperty.$common,
transitionDuration: t.transitionDuration.$controls,
transitionTimingFunction: t.transitionTiming.$common,
...(isDraggingOver && {
outline: `${t.borderWidths.$normal} dashed ${t.colors.$primary500}`,
outlineOffset: t.space.$0x5,
}),
})}
>
{previewElement}
</Flex>
<Col gap={1}>
<Flex
elementDescriptor={descriptors.avatarImageActions}
Expand All@@ -127,7 +189,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
onClick={openDialog}
/>

{!!onAvatarRemove && !showUpload && (

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed a bug where the remove button was showing inconsistently

{!!onAvatarRemove && (
<Button
elementDescriptor={descriptors.avatarImageActionsRemove}
localizationKey={localizationKeys('userProfile.profilePage.imageFormDestructiveActionSubtitle')}
Expand Down
197 changes: 197 additions & 0 deletions packages/ui/src/elements/__tests__/AvatarUploader.test.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
import { fireEvent, render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';

import { localizationKeys } from '../../customizables';
import { AvatarUploader, type AvatarUploaderProps } from '../AvatarUploader';
import { useCardState, withCardStateProvider } from '../contexts';

const { createFixtures } = bindCreateFixtures('UserProfile');

const StubPreview = (_props: { imageUrl?: string }) => <span data-testid='avatar-preview' />;

type HarnessProps = Omit<AvatarUploaderProps, 'title' | 'avatarPreview'>;

const Harness = withCardStateProvider((props: HarnessProps) => {
const card = useCardState();
return (
<>
<AvatarUploader
{...props}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={<StubPreview />}
/>
{card.error ? <div data-testid='card-error'>{card.error}</div> : null}
</>
);
});

const makeImageFile = (size = 1024, type = 'image/png') => {
const file = new File([new Uint8Array(size)], 'logo.png', { type });
Object.defineProperty(file, 'size', { value: size });
return file;
};

const makeDataTransfer = (files: File[] = [], types: string[] = ['Files']) =>
({
files,
types,
items: files.map(f => ({ kind: 'file', type: f.type, getAsFile: () => f })),
dropEffect: 'none',
effectAllowed: 'all',
}) as unknown as DataTransfer;

const findFileInput = (container: HTMLElement) => {
const input = container.querySelector<HTMLInputElement>('input[type="file"]');
if (!input) {
throw new Error('Could not find hidden file input');
}
return input;
};

const findDropZone = (container: HTMLElement) => {
// The outer Flex registered with the drop handlers is the file input's next sibling.
const sibling = findFileInput(container).nextElementSibling;
if (!sibling) {
throw new Error('Could not find drop zone element');
}
return sibling as HTMLElement;
};

describe('AvatarUploader', () => {
describe('click-upload', () => {
it('calls onAvatarChange with the selected file', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.change(findFileInput(container), { target: { files: [file] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});
});

describe('drag-and-drop', () => {
it('calls onAvatarChange when a valid image file is dropped', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([file]) });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});

it('rejects unsupported file types', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const pdf = makeImageFile(1024, 'application/pdf');
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([pdf]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file type not supported/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('rejects files exceeding the max size', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const oversized = makeImageFile(11 * 1000 * 1000);
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([oversized]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file size exceeds/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('ignores drops that do not contain files (e.g. text drags)', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), {
dataTransfer: makeDataTransfer([], ['text/plain']),
});

expect(onAvatarChange).not.toHaveBeenCalled();
});
});

describe('remove button', () => {
it('is hidden when onAvatarRemove is not provided', async () => {
const { wrapper } = await createFixtures();
const { queryByRole } = render(<Harness onAvatarChange={vi.fn().mockResolvedValue(undefined)} />, { wrapper });

expect(queryByRole('button', { name: /^remove$/i })).not.toBeInTheDocument();
});

it('stays visible after a successful upload', async () => {
// Regression: previously `showUpload` was toggled inside handleFileDrop and the remove
// button was gated on `!showUpload`, so it disappeared after each successful upload.
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const onAvatarRemove = vi.fn();
const { container, getByRole } = render(
<Harness
onAvatarChange={onAvatarChange}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();

fireEvent.change(findFileInput(container), { target: { files: [makeImageFile()] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledTimes(1));
await waitFor(() => {
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
});
expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();
});

it('invokes onAvatarRemove when clicked', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
});

it('re-enables buttons after remove completes', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
expect(getByRole('button', { name: /upload/i })).not.toBeDisabled();
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
feat(ui): Add drag to upload to AvatarUploader by alexcarpenter · Pull Request #8348 · clerk/javascript · GitHub
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/wet-ants-kind.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/ui': minor
---

Add drag-to-upload support in AvatarUploader
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ export const OrganizationProfileAvatarUploader = (
/>
<AvatarUploader
{...rest}
rounded={false}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={
<OrganizationAvatar
Expand Down
82 changes: 72 additions & 10 deletions packages/ui/src/elements/AvatarUploader.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ export type AvatarUploaderProps = {
onAvatarChange: (file: File) => Promise<unknown>;
onAvatarRemove?: (() => void) | null;
avatarPreviewPlaceholder?: React.ReactElement | null;
rounded?: boolean;
};

const fileToBase64 = (file: File): Promise<string> => {
Expand All@@ -39,17 +40,21 @@ const validSize = (f: File) => f.size <= MAX_SIZE_BYTES;

export const AvatarUploader = (props: AvatarUploaderProps) => {
const { t } = useLocalizations();
const [showUpload, setShowUpload] = React.useState(false);
const [objectUrl, setObjectUrl] = React.useState<string>();
const [isDraggingOver, setIsDraggingOver] = React.useState(false);
const card = useCardState();
const inputRef = React.useRef<HTMLInputElement | null>(null);
const openDialog = () => inputRef.current?.click();

const { onAvatarChange, onAvatarRemove, title, avatarPreview, avatarPreviewPlaceholder, ...rest } = props;

const toggle = () => {
setShowUpload(!showUpload);
};
const {
onAvatarChange,
onAvatarRemove,
title,
avatarPreview,
avatarPreviewPlaceholder,
rounded = true,
...rest
} = props;

const handleFileDrop = (file: File | null) => {
if (file === null) {
Expand All@@ -60,7 +65,6 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
card.setLoading();
return onAvatarChange(file)
.then(() => {
toggle();
card.setIdle();
})
.catch(err => handleError(err, [], card.setError));
Expand All@@ -69,6 +73,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
const handleRemove = async () => {
card.setLoading();
await handleFileDrop(null);
card.setIdle();
return onAvatarRemove?.();
};

Expand All@@ -90,6 +95,46 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
await handleFileDrop(f);
};

const isFileDrag = (e: React.DragEvent) => e.dataTransfer?.types?.includes('Files') ?? false;

const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(true);
};

const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
};

const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
// Only reset when leaving the container entirely, not when moving between children.
// SAFETY: e.relatedTarget is typed as EventTarget | null, but in drag events it is always
// a DOM Node (or null). Element.contains() requires Node | null; the cast is safe here.
if (e.currentTarget.contains(e.relatedTarget as Node | null)) {
return;
}
setIsDraggingOver(false);
};

const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
if (!isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(false);
if (card.isLoading) {
return;
}
void upload(e.dataTransfer.files?.[0]);
};

const hasExistingImage = !!(avatarPreview.props as { imageUrl?: string })?.imageUrl;
const previewElement = objectUrl
? React.cloneElement(avatarPreview, { imageUrl: objectUrl })
Expand All@@ -108,11 +153,28 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
/>

<Flex
{...rest}
gap={4}
align='center'
{...rest}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
{previewElement}
<Flex
sx={t => ({
borderRadius: isDraggingOver && rounded ? t.radii.$circle : t.radii.$md,
transitionProperty: t.transitionProperty.$common,
transitionDuration: t.transitionDuration.$controls,
transitionTimingFunction: t.transitionTiming.$common,
...(isDraggingOver && {
outline: `${t.borderWidths.$normal} dashed ${t.colors.$primary500}`,
outlineOffset: t.space.$0x5,
}),
})}
>
{previewElement}
</Flex>
<Col gap={1}>
<Flex
elementDescriptor={descriptors.avatarImageActions}
Expand All@@ -127,7 +189,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
onClick={openDialog}
/>

{!!onAvatarRemove && !showUpload && (

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed a bug where the remove button was showing inconsistently

{!!onAvatarRemove && (
<Button
elementDescriptor={descriptors.avatarImageActionsRemove}
localizationKey={localizationKeys('userProfile.profilePage.imageFormDestructiveActionSubtitle')}
Expand Down
197 changes: 197 additions & 0 deletions packages/ui/src/elements/__tests__/AvatarUploader.test.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
import { fireEvent, render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';

import { localizationKeys } from '../../customizables';
import { AvatarUploader, type AvatarUploaderProps } from '../AvatarUploader';
import { useCardState, withCardStateProvider } from '../contexts';

const { createFixtures } = bindCreateFixtures('UserProfile');

const StubPreview = (_props: { imageUrl?: string }) => <span data-testid='avatar-preview' />;

type HarnessProps = Omit<AvatarUploaderProps, 'title' | 'avatarPreview'>;

const Harness = withCardStateProvider((props: HarnessProps) => {
const card = useCardState();
return (
<>
<AvatarUploader
{...props}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={<StubPreview />}
/>
{card.error ? <div data-testid='card-error'>{card.error}</div> : null}
</>
);
});

const makeImageFile = (size = 1024, type = 'image/png') => {
const file = new File([new Uint8Array(size)], 'logo.png', { type });
Object.defineProperty(file, 'size', { value: size });
return file;
};

const makeDataTransfer = (files: File[] = [], types: string[] = ['Files']) =>
({
files,
types,
items: files.map(f => ({ kind: 'file', type: f.type, getAsFile: () => f })),
dropEffect: 'none',
effectAllowed: 'all',
}) as unknown as DataTransfer;

const findFileInput = (container: HTMLElement) => {
const input = container.querySelector<HTMLInputElement>('input[type="file"]');
if (!input) {
throw new Error('Could not find hidden file input');
}
return input;
};

const findDropZone = (container: HTMLElement) => {
// The outer Flex registered with the drop handlers is the file input's next sibling.
const sibling = findFileInput(container).nextElementSibling;
if (!sibling) {
throw new Error('Could not find drop zone element');
}
return sibling as HTMLElement;
};

describe('AvatarUploader', () => {
describe('click-upload', () => {
it('calls onAvatarChange with the selected file', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.change(findFileInput(container), { target: { files: [file] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});
});

describe('drag-and-drop', () => {
it('calls onAvatarChange when a valid image file is dropped', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([file]) });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});

it('rejects unsupported file types', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const pdf = makeImageFile(1024, 'application/pdf');
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([pdf]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file type not supported/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('rejects files exceeding the max size', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const oversized = makeImageFile(11 * 1000 * 1000);
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([oversized]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file size exceeds/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('ignores drops that do not contain files (e.g. text drags)', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), {
dataTransfer: makeDataTransfer([], ['text/plain']),
});

expect(onAvatarChange).not.toHaveBeenCalled();
});
});

describe('remove button', () => {
it('is hidden when onAvatarRemove is not provided', async () => {
const { wrapper } = await createFixtures();
const { queryByRole } = render(<Harness onAvatarChange={vi.fn().mockResolvedValue(undefined)} />, { wrapper });

expect(queryByRole('button', { name: /^remove$/i })).not.toBeInTheDocument();
});

it('stays visible after a successful upload', async () => {
// Regression: previously `showUpload` was toggled inside handleFileDrop and the remove
// button was gated on `!showUpload`, so it disappeared after each successful upload.
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const onAvatarRemove = vi.fn();
const { container, getByRole } = render(
<Harness
onAvatarChange={onAvatarChange}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();

fireEvent.change(findFileInput(container), { target: { files: [makeImageFile()] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledTimes(1));
await waitFor(() => {
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
});
expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();
});

it('invokes onAvatarRemove when clicked', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
});

it('re-enables buttons after remove completes', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
expect(getByRole('button', { name: /upload/i })).not.toBeDisabled();
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(ui): Add drag to upload to AvatarUploader by alexcarpenter · Pull Request #8348 · clerk/javascript · GitHub
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/wet-ants-kind.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/ui': minor
---

Add drag-to-upload support in AvatarUploader
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ export const OrganizationProfileAvatarUploader = (
/>
<AvatarUploader
{...rest}
rounded={false}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={
<OrganizationAvatar
Expand Down
82 changes: 72 additions & 10 deletions packages/ui/src/elements/AvatarUploader.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ export type AvatarUploaderProps = {
onAvatarChange: (file: File) => Promise<unknown>;
onAvatarRemove?: (() => void) | null;
avatarPreviewPlaceholder?: React.ReactElement | null;
rounded?: boolean;
};

const fileToBase64 = (file: File): Promise<string> => {
Expand All@@ -39,17 +40,21 @@ const validSize = (f: File) => f.size <= MAX_SIZE_BYTES;

export const AvatarUploader = (props: AvatarUploaderProps) => {
const { t } = useLocalizations();
const [showUpload, setShowUpload] = React.useState(false);
const [objectUrl, setObjectUrl] = React.useState<string>();
const [isDraggingOver, setIsDraggingOver] = React.useState(false);
const card = useCardState();
const inputRef = React.useRef<HTMLInputElement | null>(null);
const openDialog = () => inputRef.current?.click();

const { onAvatarChange, onAvatarRemove, title, avatarPreview, avatarPreviewPlaceholder, ...rest } = props;

const toggle = () => {
setShowUpload(!showUpload);
};
const {
onAvatarChange,
onAvatarRemove,
title,
avatarPreview,
avatarPreviewPlaceholder,
rounded = true,
...rest
} = props;

const handleFileDrop = (file: File | null) => {
if (file === null) {
Expand All@@ -60,7 +65,6 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
card.setLoading();
return onAvatarChange(file)
.then(() => {
toggle();
card.setIdle();
})
.catch(err => handleError(err, [], card.setError));
Expand All@@ -69,6 +73,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
const handleRemove = async () => {
card.setLoading();
await handleFileDrop(null);
card.setIdle();
return onAvatarRemove?.();
};

Expand All@@ -90,6 +95,46 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
await handleFileDrop(f);
};

const isFileDrag = (e: React.DragEvent) => e.dataTransfer?.types?.includes('Files') ?? false;

const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(true);
};

const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
};

const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
// Only reset when leaving the container entirely, not when moving between children.
// SAFETY: e.relatedTarget is typed as EventTarget | null, but in drag events it is always
// a DOM Node (or null). Element.contains() requires Node | null; the cast is safe here.
if (e.currentTarget.contains(e.relatedTarget as Node | null)) {
return;
}
setIsDraggingOver(false);
};

const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
if (!isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(false);
if (card.isLoading) {
return;
}
void upload(e.dataTransfer.files?.[0]);
};

const hasExistingImage = !!(avatarPreview.props as { imageUrl?: string })?.imageUrl;
const previewElement = objectUrl
? React.cloneElement(avatarPreview, { imageUrl: objectUrl })
Expand All@@ -108,11 +153,28 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
/>

<Flex
{...rest}
gap={4}
align='center'
{...rest}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
{previewElement}
<Flex
sx={t => ({
borderRadius: isDraggingOver && rounded ? t.radii.$circle : t.radii.$md,
transitionProperty: t.transitionProperty.$common,
transitionDuration: t.transitionDuration.$controls,
transitionTimingFunction: t.transitionTiming.$common,
...(isDraggingOver && {
outline: `${t.borderWidths.$normal} dashed ${t.colors.$primary500}`,
outlineOffset: t.space.$0x5,
}),
})}
>
{previewElement}
</Flex>
<Col gap={1}>
<Flex
elementDescriptor={descriptors.avatarImageActions}
Expand All@@ -127,7 +189,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
onClick={openDialog}
/>

{!!onAvatarRemove && !showUpload && (

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed a bug where the remove button was showing inconsistently

{!!onAvatarRemove && (
<Button
elementDescriptor={descriptors.avatarImageActionsRemove}
localizationKey={localizationKeys('userProfile.profilePage.imageFormDestructiveActionSubtitle')}
Expand Down
197 changes: 197 additions & 0 deletions packages/ui/src/elements/__tests__/AvatarUploader.test.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
import { fireEvent, render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';

import { localizationKeys } from '../../customizables';
import { AvatarUploader, type AvatarUploaderProps } from '../AvatarUploader';
import { useCardState, withCardStateProvider } from '../contexts';

const { createFixtures } = bindCreateFixtures('UserProfile');

const StubPreview = (_props: { imageUrl?: string }) => <span data-testid='avatar-preview' />;

type HarnessProps = Omit<AvatarUploaderProps, 'title' | 'avatarPreview'>;

const Harness = withCardStateProvider((props: HarnessProps) => {
const card = useCardState();
return (
<>
<AvatarUploader
{...props}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={<StubPreview />}
/>
{card.error ? <div data-testid='card-error'>{card.error}</div> : null}
</>
);
});

const makeImageFile = (size = 1024, type = 'image/png') => {
const file = new File([new Uint8Array(size)], 'logo.png', { type });
Object.defineProperty(file, 'size', { value: size });
return file;
};

const makeDataTransfer = (files: File[] = [], types: string[] = ['Files']) =>
({
files,
types,
items: files.map(f => ({ kind: 'file', type: f.type, getAsFile: () => f })),
dropEffect: 'none',
effectAllowed: 'all',
}) as unknown as DataTransfer;

const findFileInput = (container: HTMLElement) => {
const input = container.querySelector<HTMLInputElement>('input[type="file"]');
if (!input) {
throw new Error('Could not find hidden file input');
}
return input;
};

const findDropZone = (container: HTMLElement) => {
// The outer Flex registered with the drop handlers is the file input's next sibling.
const sibling = findFileInput(container).nextElementSibling;
if (!sibling) {
throw new Error('Could not find drop zone element');
}
return sibling as HTMLElement;
};

describe('AvatarUploader', () => {
describe('click-upload', () => {
it('calls onAvatarChange with the selected file', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.change(findFileInput(container), { target: { files: [file] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});
});

describe('drag-and-drop', () => {
it('calls onAvatarChange when a valid image file is dropped', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([file]) });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});

it('rejects unsupported file types', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const pdf = makeImageFile(1024, 'application/pdf');
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([pdf]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file type not supported/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('rejects files exceeding the max size', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const oversized = makeImageFile(11 * 1000 * 1000);
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([oversized]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file size exceeds/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('ignores drops that do not contain files (e.g. text drags)', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), {
dataTransfer: makeDataTransfer([], ['text/plain']),
});

expect(onAvatarChange).not.toHaveBeenCalled();
});
});

describe('remove button', () => {
it('is hidden when onAvatarRemove is not provided', async () => {
const { wrapper } = await createFixtures();
const { queryByRole } = render(<Harness onAvatarChange={vi.fn().mockResolvedValue(undefined)} />, { wrapper });

expect(queryByRole('button', { name: /^remove$/i })).not.toBeInTheDocument();
});

it('stays visible after a successful upload', async () => {
// Regression: previously `showUpload` was toggled inside handleFileDrop and the remove
// button was gated on `!showUpload`, so it disappeared after each successful upload.
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const onAvatarRemove = vi.fn();
const { container, getByRole } = render(
<Harness
onAvatarChange={onAvatarChange}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();

fireEvent.change(findFileInput(container), { target: { files: [makeImageFile()] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledTimes(1));
await waitFor(() => {
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
});
expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();
});

it('invokes onAvatarRemove when clicked', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
});

it('re-enables buttons after remove completes', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
expect(getByRole('button', { name: /upload/i })).not.toBeDisabled();
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(ui): Add drag to upload to AvatarUploader by alexcarpenter · Pull Request #8348 · clerk/javascript · GitHub
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/wet-ants-kind.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/ui': minor
---

Add drag-to-upload support in AvatarUploader
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ export const OrganizationProfileAvatarUploader = (
/>
<AvatarUploader
{...rest}
rounded={false}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={
<OrganizationAvatar
Expand Down
82 changes: 72 additions & 10 deletions packages/ui/src/elements/AvatarUploader.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ export type AvatarUploaderProps = {
onAvatarChange: (file: File) => Promise<unknown>;
onAvatarRemove?: (() => void) | null;
avatarPreviewPlaceholder?: React.ReactElement | null;
rounded?: boolean;
};

const fileToBase64 = (file: File): Promise<string> => {
Expand All@@ -39,17 +40,21 @@ const validSize = (f: File) => f.size <= MAX_SIZE_BYTES;

export const AvatarUploader = (props: AvatarUploaderProps) => {
const { t } = useLocalizations();
const [showUpload, setShowUpload] = React.useState(false);
const [objectUrl, setObjectUrl] = React.useState<string>();
const [isDraggingOver, setIsDraggingOver] = React.useState(false);
const card = useCardState();
const inputRef = React.useRef<HTMLInputElement | null>(null);
const openDialog = () => inputRef.current?.click();

const { onAvatarChange, onAvatarRemove, title, avatarPreview, avatarPreviewPlaceholder, ...rest } = props;

const toggle = () => {
setShowUpload(!showUpload);
};
const {
onAvatarChange,
onAvatarRemove,
title,
avatarPreview,
avatarPreviewPlaceholder,
rounded = true,
...rest
} = props;

const handleFileDrop = (file: File | null) => {
if (file === null) {
Expand All@@ -60,7 +65,6 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
card.setLoading();
return onAvatarChange(file)
.then(() => {
toggle();
card.setIdle();
})
.catch(err => handleError(err, [], card.setError));
Expand All@@ -69,6 +73,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
const handleRemove = async () => {
card.setLoading();
await handleFileDrop(null);
card.setIdle();
return onAvatarRemove?.();
};

Expand All@@ -90,6 +95,46 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
await handleFileDrop(f);
};

const isFileDrag = (e: React.DragEvent) => e.dataTransfer?.types?.includes('Files') ?? false;

const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(true);
};

const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
};

const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
// Only reset when leaving the container entirely, not when moving between children.
// SAFETY: e.relatedTarget is typed as EventTarget | null, but in drag events it is always
// a DOM Node (or null). Element.contains() requires Node | null; the cast is safe here.
if (e.currentTarget.contains(e.relatedTarget as Node | null)) {
return;
}
setIsDraggingOver(false);
};

const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
if (!isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(false);
if (card.isLoading) {
return;
}
void upload(e.dataTransfer.files?.[0]);
};

const hasExistingImage = !!(avatarPreview.props as { imageUrl?: string })?.imageUrl;
const previewElement = objectUrl
? React.cloneElement(avatarPreview, { imageUrl: objectUrl })
Expand All@@ -108,11 +153,28 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
/>

<Flex
{...rest}
gap={4}
align='center'
{...rest}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
{previewElement}
<Flex
sx={t => ({
borderRadius: isDraggingOver && rounded ? t.radii.$circle : t.radii.$md,
transitionProperty: t.transitionProperty.$common,
transitionDuration: t.transitionDuration.$controls,
transitionTimingFunction: t.transitionTiming.$common,
...(isDraggingOver && {
outline: `${t.borderWidths.$normal} dashed ${t.colors.$primary500}`,
outlineOffset: t.space.$0x5,
}),
})}
>
{previewElement}
</Flex>
<Col gap={1}>
<Flex
elementDescriptor={descriptors.avatarImageActions}
Expand All@@ -127,7 +189,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
onClick={openDialog}
/>

{!!onAvatarRemove && !showUpload && (

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed a bug where the remove button was showing inconsistently

{!!onAvatarRemove && (
<Button
elementDescriptor={descriptors.avatarImageActionsRemove}
localizationKey={localizationKeys('userProfile.profilePage.imageFormDestructiveActionSubtitle')}
Expand Down
197 changes: 197 additions & 0 deletions packages/ui/src/elements/__tests__/AvatarUploader.test.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
import { fireEvent, render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';

import { localizationKeys } from '../../customizables';
import { AvatarUploader, type AvatarUploaderProps } from '../AvatarUploader';
import { useCardState, withCardStateProvider } from '../contexts';

const { createFixtures } = bindCreateFixtures('UserProfile');

const StubPreview = (_props: { imageUrl?: string }) => <span data-testid='avatar-preview' />;

type HarnessProps = Omit<AvatarUploaderProps, 'title' | 'avatarPreview'>;

const Harness = withCardStateProvider((props: HarnessProps) => {
const card = useCardState();
return (
<>
<AvatarUploader
{...props}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={<StubPreview />}
/>
{card.error ? <div data-testid='card-error'>{card.error}</div> : null}
</>
);
});

const makeImageFile = (size = 1024, type = 'image/png') => {
const file = new File([new Uint8Array(size)], 'logo.png', { type });
Object.defineProperty(file, 'size', { value: size });
return file;
};

const makeDataTransfer = (files: File[] = [], types: string[] = ['Files']) =>
({
files,
types,
items: files.map(f => ({ kind: 'file', type: f.type, getAsFile: () => f })),
dropEffect: 'none',
effectAllowed: 'all',
}) as unknown as DataTransfer;

const findFileInput = (container: HTMLElement) => {
const input = container.querySelector<HTMLInputElement>('input[type="file"]');
if (!input) {
throw new Error('Could not find hidden file input');
}
return input;
};

const findDropZone = (container: HTMLElement) => {
// The outer Flex registered with the drop handlers is the file input's next sibling.
const sibling = findFileInput(container).nextElementSibling;
if (!sibling) {
throw new Error('Could not find drop zone element');
}
return sibling as HTMLElement;
};

describe('AvatarUploader', () => {
describe('click-upload', () => {
it('calls onAvatarChange with the selected file', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.change(findFileInput(container), { target: { files: [file] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});
});

describe('drag-and-drop', () => {
it('calls onAvatarChange when a valid image file is dropped', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([file]) });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});

it('rejects unsupported file types', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const pdf = makeImageFile(1024, 'application/pdf');
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([pdf]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file type not supported/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('rejects files exceeding the max size', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const oversized = makeImageFile(11 * 1000 * 1000);
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([oversized]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file size exceeds/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('ignores drops that do not contain files (e.g. text drags)', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), {
dataTransfer: makeDataTransfer([], ['text/plain']),
});

expect(onAvatarChange).not.toHaveBeenCalled();
});
});

describe('remove button', () => {
it('is hidden when onAvatarRemove is not provided', async () => {
const { wrapper } = await createFixtures();
const { queryByRole } = render(<Harness onAvatarChange={vi.fn().mockResolvedValue(undefined)} />, { wrapper });

expect(queryByRole('button', { name: /^remove$/i })).not.toBeInTheDocument();
});

it('stays visible after a successful upload', async () => {
// Regression: previously `showUpload` was toggled inside handleFileDrop and the remove
// button was gated on `!showUpload`, so it disappeared after each successful upload.
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const onAvatarRemove = vi.fn();
const { container, getByRole } = render(
<Harness
onAvatarChange={onAvatarChange}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();

fireEvent.change(findFileInput(container), { target: { files: [makeImageFile()] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledTimes(1));
await waitFor(() => {
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
});
expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();
});

it('invokes onAvatarRemove when clicked', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
});

it('re-enables buttons after remove completes', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
expect(getByRole('button', { name: /upload/i })).not.toBeDisabled();
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' feat(ui): Add drag to upload to AvatarUploader by alexcarpenter · Pull Request #8348 · clerk/javascript · GitHub
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/wet-ants-kind.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/ui': minor
---

Add drag-to-upload support in AvatarUploader
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ export const OrganizationProfileAvatarUploader = (
/>
<AvatarUploader
{...rest}
rounded={false}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={
<OrganizationAvatar
Expand Down
82 changes: 72 additions & 10 deletions packages/ui/src/elements/AvatarUploader.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ export type AvatarUploaderProps = {
onAvatarChange: (file: File) => Promise<unknown>;
onAvatarRemove?: (() => void) | null;
avatarPreviewPlaceholder?: React.ReactElement | null;
rounded?: boolean;
};

const fileToBase64 = (file: File): Promise<string> => {
Expand All@@ -39,17 +40,21 @@ const validSize = (f: File) => f.size <= MAX_SIZE_BYTES;

export const AvatarUploader = (props: AvatarUploaderProps) => {
const { t } = useLocalizations();
const [showUpload, setShowUpload] = React.useState(false);
const [objectUrl, setObjectUrl] = React.useState<string>();
const [isDraggingOver, setIsDraggingOver] = React.useState(false);
const card = useCardState();
const inputRef = React.useRef<HTMLInputElement | null>(null);
const openDialog = () => inputRef.current?.click();

const { onAvatarChange, onAvatarRemove, title, avatarPreview, avatarPreviewPlaceholder, ...rest } = props;

const toggle = () => {
setShowUpload(!showUpload);
};
const {
onAvatarChange,
onAvatarRemove,
title,
avatarPreview,
avatarPreviewPlaceholder,
rounded = true,
...rest
} = props;

const handleFileDrop = (file: File | null) => {
if (file === null) {
Expand All@@ -60,7 +65,6 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
card.setLoading();
return onAvatarChange(file)
.then(() => {
toggle();
card.setIdle();
})
.catch(err => handleError(err, [], card.setError));
Expand All@@ -69,6 +73,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
const handleRemove = async () => {
card.setLoading();
await handleFileDrop(null);
card.setIdle();
return onAvatarRemove?.();
};

Expand All@@ -90,6 +95,46 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
await handleFileDrop(f);
};

const isFileDrag = (e: React.DragEvent) => e.dataTransfer?.types?.includes('Files') ?? false;

const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(true);
};

const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
};

const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
// Only reset when leaving the container entirely, not when moving between children.
// SAFETY: e.relatedTarget is typed as EventTarget | null, but in drag events it is always
// a DOM Node (or null). Element.contains() requires Node | null; the cast is safe here.
if (e.currentTarget.contains(e.relatedTarget as Node | null)) {
return;
}
setIsDraggingOver(false);
};

const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
if (!isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(false);
if (card.isLoading) {
return;
}
void upload(e.dataTransfer.files?.[0]);
};

const hasExistingImage = !!(avatarPreview.props as { imageUrl?: string })?.imageUrl;
const previewElement = objectUrl
? React.cloneElement(avatarPreview, { imageUrl: objectUrl })
Expand All@@ -108,11 +153,28 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
/>

<Flex
{...rest}
gap={4}
align='center'
{...rest}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
{previewElement}
<Flex
sx={t => ({
borderRadius: isDraggingOver && rounded ? t.radii.$circle : t.radii.$md,
transitionProperty: t.transitionProperty.$common,
transitionDuration: t.transitionDuration.$controls,
transitionTimingFunction: t.transitionTiming.$common,
...(isDraggingOver && {
outline: `${t.borderWidths.$normal} dashed ${t.colors.$primary500}`,
outlineOffset: t.space.$0x5,
}),
})}
>
{previewElement}
</Flex>
<Col gap={1}>
<Flex
elementDescriptor={descriptors.avatarImageActions}
Expand All@@ -127,7 +189,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
onClick={openDialog}
/>

{!!onAvatarRemove && !showUpload && (

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed a bug where the remove button was showing inconsistently

{!!onAvatarRemove && (
<Button
elementDescriptor={descriptors.avatarImageActionsRemove}
localizationKey={localizationKeys('userProfile.profilePage.imageFormDestructiveActionSubtitle')}
Expand Down
197 changes: 197 additions & 0 deletions packages/ui/src/elements/__tests__/AvatarUploader.test.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
import { fireEvent, render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';

import { localizationKeys } from '../../customizables';
import { AvatarUploader, type AvatarUploaderProps } from '../AvatarUploader';
import { useCardState, withCardStateProvider } from '../contexts';

const { createFixtures } = bindCreateFixtures('UserProfile');

const StubPreview = (_props: { imageUrl?: string }) => <span data-testid='avatar-preview' />;

type HarnessProps = Omit<AvatarUploaderProps, 'title' | 'avatarPreview'>;

const Harness = withCardStateProvider((props: HarnessProps) => {
const card = useCardState();
return (
<>
<AvatarUploader
{...props}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={<StubPreview />}
/>
{card.error ? <div data-testid='card-error'>{card.error}</div> : null}
</>
);
});

const makeImageFile = (size = 1024, type = 'image/png') => {
const file = new File([new Uint8Array(size)], 'logo.png', { type });
Object.defineProperty(file, 'size', { value: size });
return file;
};

const makeDataTransfer = (files: File[] = [], types: string[] = ['Files']) =>
({
files,
types,
items: files.map(f => ({ kind: 'file', type: f.type, getAsFile: () => f })),
dropEffect: 'none',
effectAllowed: 'all',
}) as unknown as DataTransfer;

const findFileInput = (container: HTMLElement) => {
const input = container.querySelector<HTMLInputElement>('input[type="file"]');
if (!input) {
throw new Error('Could not find hidden file input');
}
return input;
};

const findDropZone = (container: HTMLElement) => {
// The outer Flex registered with the drop handlers is the file input's next sibling.
const sibling = findFileInput(container).nextElementSibling;
if (!sibling) {
throw new Error('Could not find drop zone element');
}
return sibling as HTMLElement;
};

describe('AvatarUploader', () => {
describe('click-upload', () => {
it('calls onAvatarChange with the selected file', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.change(findFileInput(container), { target: { files: [file] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});
});

describe('drag-and-drop', () => {
it('calls onAvatarChange when a valid image file is dropped', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([file]) });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});

it('rejects unsupported file types', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const pdf = makeImageFile(1024, 'application/pdf');
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([pdf]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file type not supported/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('rejects files exceeding the max size', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const oversized = makeImageFile(11 * 1000 * 1000);
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([oversized]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file size exceeds/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('ignores drops that do not contain files (e.g. text drags)', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), {
dataTransfer: makeDataTransfer([], ['text/plain']),
});

expect(onAvatarChange).not.toHaveBeenCalled();
});
});

describe('remove button', () => {
it('is hidden when onAvatarRemove is not provided', async () => {
const { wrapper } = await createFixtures();
const { queryByRole } = render(<Harness onAvatarChange={vi.fn().mockResolvedValue(undefined)} />, { wrapper });

expect(queryByRole('button', { name: /^remove$/i })).not.toBeInTheDocument();
});

it('stays visible after a successful upload', async () => {
// Regression: previously `showUpload` was toggled inside handleFileDrop and the remove
// button was gated on `!showUpload`, so it disappeared after each successful upload.
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const onAvatarRemove = vi.fn();
const { container, getByRole } = render(
<Harness
onAvatarChange={onAvatarChange}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();

fireEvent.change(findFileInput(container), { target: { files: [makeImageFile()] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledTimes(1));
await waitFor(() => {
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
});
expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();
});

it('invokes onAvatarRemove when clicked', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
});

it('re-enables buttons after remove completes', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
expect(getByRole('button', { name: /upload/i })).not.toBeDisabled();
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(ui): Add drag to upload to AvatarUploader by alexcarpenter · Pull Request #8348 · clerk/javascript · GitHub
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/wet-ants-kind.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/ui': minor
---

Add drag-to-upload support in AvatarUploader
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ export const OrganizationProfileAvatarUploader = (
/>
<AvatarUploader
{...rest}
rounded={false}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={
<OrganizationAvatar
Expand Down
82 changes: 72 additions & 10 deletions packages/ui/src/elements/AvatarUploader.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ export type AvatarUploaderProps = {
onAvatarChange: (file: File) => Promise<unknown>;
onAvatarRemove?: (() => void) | null;
avatarPreviewPlaceholder?: React.ReactElement | null;
rounded?: boolean;
};

const fileToBase64 = (file: File): Promise<string> => {
Expand All@@ -39,17 +40,21 @@ const validSize = (f: File) => f.size <= MAX_SIZE_BYTES;

export const AvatarUploader = (props: AvatarUploaderProps) => {
const { t } = useLocalizations();
const [showUpload, setShowUpload] = React.useState(false);
const [objectUrl, setObjectUrl] = React.useState<string>();
const [isDraggingOver, setIsDraggingOver] = React.useState(false);
const card = useCardState();
const inputRef = React.useRef<HTMLInputElement | null>(null);
const openDialog = () => inputRef.current?.click();

const { onAvatarChange, onAvatarRemove, title, avatarPreview, avatarPreviewPlaceholder, ...rest } = props;

const toggle = () => {
setShowUpload(!showUpload);
};
const {
onAvatarChange,
onAvatarRemove,
title,
avatarPreview,
avatarPreviewPlaceholder,
rounded = true,
...rest
} = props;

const handleFileDrop = (file: File | null) => {
if (file === null) {
Expand All@@ -60,7 +65,6 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
card.setLoading();
return onAvatarChange(file)
.then(() => {
toggle();
card.setIdle();
})
.catch(err => handleError(err, [], card.setError));
Expand All@@ -69,6 +73,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
const handleRemove = async () => {
card.setLoading();
await handleFileDrop(null);
card.setIdle();
return onAvatarRemove?.();
};

Expand All@@ -90,6 +95,46 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
await handleFileDrop(f);
};

const isFileDrag = (e: React.DragEvent) => e.dataTransfer?.types?.includes('Files') ?? false;

const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(true);
};

const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
};

const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
// Only reset when leaving the container entirely, not when moving between children.
// SAFETY: e.relatedTarget is typed as EventTarget | null, but in drag events it is always
// a DOM Node (or null). Element.contains() requires Node | null; the cast is safe here.
if (e.currentTarget.contains(e.relatedTarget as Node | null)) {
return;
}
setIsDraggingOver(false);
};

const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
if (!isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(false);
if (card.isLoading) {
return;
}
void upload(e.dataTransfer.files?.[0]);
};

const hasExistingImage = !!(avatarPreview.props as { imageUrl?: string })?.imageUrl;
const previewElement = objectUrl
? React.cloneElement(avatarPreview, { imageUrl: objectUrl })
Expand All@@ -108,11 +153,28 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
/>

<Flex
{...rest}
gap={4}
align='center'
{...rest}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
{previewElement}
<Flex
sx={t => ({
borderRadius: isDraggingOver && rounded ? t.radii.$circle : t.radii.$md,
transitionProperty: t.transitionProperty.$common,
transitionDuration: t.transitionDuration.$controls,
transitionTimingFunction: t.transitionTiming.$common,
...(isDraggingOver && {
outline: `${t.borderWidths.$normal} dashed ${t.colors.$primary500}`,
outlineOffset: t.space.$0x5,
}),
})}
>
{previewElement}
</Flex>
<Col gap={1}>
<Flex
elementDescriptor={descriptors.avatarImageActions}
Expand All@@ -127,7 +189,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
onClick={openDialog}
/>

{!!onAvatarRemove && !showUpload && (

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed a bug where the remove button was showing inconsistently

{!!onAvatarRemove && (
<Button
elementDescriptor={descriptors.avatarImageActionsRemove}
localizationKey={localizationKeys('userProfile.profilePage.imageFormDestructiveActionSubtitle')}
Expand Down
197 changes: 197 additions & 0 deletions packages/ui/src/elements/__tests__/AvatarUploader.test.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
import { fireEvent, render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';

import { localizationKeys } from '../../customizables';
import { AvatarUploader, type AvatarUploaderProps } from '../AvatarUploader';
import { useCardState, withCardStateProvider } from '../contexts';

const { createFixtures } = bindCreateFixtures('UserProfile');

const StubPreview = (_props: { imageUrl?: string }) => <span data-testid='avatar-preview' />;

type HarnessProps = Omit<AvatarUploaderProps, 'title' | 'avatarPreview'>;

const Harness = withCardStateProvider((props: HarnessProps) => {
const card = useCardState();
return (
<>
<AvatarUploader
{...props}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={<StubPreview />}
/>
{card.error ? <div data-testid='card-error'>{card.error}</div> : null}
</>
);
});

const makeImageFile = (size = 1024, type = 'image/png') => {
const file = new File([new Uint8Array(size)], 'logo.png', { type });
Object.defineProperty(file, 'size', { value: size });
return file;
};

const makeDataTransfer = (files: File[] = [], types: string[] = ['Files']) =>
({
files,
types,
items: files.map(f => ({ kind: 'file', type: f.type, getAsFile: () => f })),
dropEffect: 'none',
effectAllowed: 'all',
}) as unknown as DataTransfer;

const findFileInput = (container: HTMLElement) => {
const input = container.querySelector<HTMLInputElement>('input[type="file"]');
if (!input) {
throw new Error('Could not find hidden file input');
}
return input;
};

const findDropZone = (container: HTMLElement) => {
// The outer Flex registered with the drop handlers is the file input's next sibling.
const sibling = findFileInput(container).nextElementSibling;
if (!sibling) {
throw new Error('Could not find drop zone element');
}
return sibling as HTMLElement;
};

describe('AvatarUploader', () => {
describe('click-upload', () => {
it('calls onAvatarChange with the selected file', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.change(findFileInput(container), { target: { files: [file] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});
});

describe('drag-and-drop', () => {
it('calls onAvatarChange when a valid image file is dropped', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([file]) });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});

it('rejects unsupported file types', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const pdf = makeImageFile(1024, 'application/pdf');
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([pdf]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file type not supported/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('rejects files exceeding the max size', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const oversized = makeImageFile(11 * 1000 * 1000);
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([oversized]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file size exceeds/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('ignores drops that do not contain files (e.g. text drags)', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), {
dataTransfer: makeDataTransfer([], ['text/plain']),
});

expect(onAvatarChange).not.toHaveBeenCalled();
});
});

describe('remove button', () => {
it('is hidden when onAvatarRemove is not provided', async () => {
const { wrapper } = await createFixtures();
const { queryByRole } = render(<Harness onAvatarChange={vi.fn().mockResolvedValue(undefined)} />, { wrapper });

expect(queryByRole('button', { name: /^remove$/i })).not.toBeInTheDocument();
});

it('stays visible after a successful upload', async () => {
// Regression: previously `showUpload` was toggled inside handleFileDrop and the remove
// button was gated on `!showUpload`, so it disappeared after each successful upload.
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const onAvatarRemove = vi.fn();
const { container, getByRole } = render(
<Harness
onAvatarChange={onAvatarChange}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();

fireEvent.change(findFileInput(container), { target: { files: [makeImageFile()] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledTimes(1));
await waitFor(() => {
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
});
expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();
});

it('invokes onAvatarRemove when clicked', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
});

it('re-enables buttons after remove completes', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
expect(getByRole('button', { name: /upload/i })).not.toBeDisabled();
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' feat(ui): Add drag to upload to AvatarUploader by alexcarpenter · Pull Request #8348 · clerk/javascript · GitHub
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/wet-ants-kind.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/ui': minor
---

Add drag-to-upload support in AvatarUploader
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ export const OrganizationProfileAvatarUploader = (
/>
<AvatarUploader
{...rest}
rounded={false}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={
<OrganizationAvatar
Expand Down
82 changes: 72 additions & 10 deletions packages/ui/src/elements/AvatarUploader.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ export type AvatarUploaderProps = {
onAvatarChange: (file: File) => Promise<unknown>;
onAvatarRemove?: (() => void) | null;
avatarPreviewPlaceholder?: React.ReactElement | null;
rounded?: boolean;
};

const fileToBase64 = (file: File): Promise<string> => {
Expand All@@ -39,17 +40,21 @@ const validSize = (f: File) => f.size <= MAX_SIZE_BYTES;

export const AvatarUploader = (props: AvatarUploaderProps) => {
const { t } = useLocalizations();
const [showUpload, setShowUpload] = React.useState(false);
const [objectUrl, setObjectUrl] = React.useState<string>();
const [isDraggingOver, setIsDraggingOver] = React.useState(false);
const card = useCardState();
const inputRef = React.useRef<HTMLInputElement | null>(null);
const openDialog = () => inputRef.current?.click();

const { onAvatarChange, onAvatarRemove, title, avatarPreview, avatarPreviewPlaceholder, ...rest } = props;

const toggle = () => {
setShowUpload(!showUpload);
};
const {
onAvatarChange,
onAvatarRemove,
title,
avatarPreview,
avatarPreviewPlaceholder,
rounded = true,
...rest
} = props;

const handleFileDrop = (file: File | null) => {
if (file === null) {
Expand All@@ -60,7 +65,6 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
card.setLoading();
return onAvatarChange(file)
.then(() => {
toggle();
card.setIdle();
})
.catch(err => handleError(err, [], card.setError));
Expand All@@ -69,6 +73,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
const handleRemove = async () => {
card.setLoading();
await handleFileDrop(null);
card.setIdle();
return onAvatarRemove?.();
};

Expand All@@ -90,6 +95,46 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
await handleFileDrop(f);
};

const isFileDrag = (e: React.DragEvent) => e.dataTransfer?.types?.includes('Files') ?? false;

const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(true);
};

const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
};

const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
// Only reset when leaving the container entirely, not when moving between children.
// SAFETY: e.relatedTarget is typed as EventTarget | null, but in drag events it is always
// a DOM Node (or null). Element.contains() requires Node | null; the cast is safe here.
if (e.currentTarget.contains(e.relatedTarget as Node | null)) {
return;
}
setIsDraggingOver(false);
};

const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
if (!isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(false);
if (card.isLoading) {
return;
}
void upload(e.dataTransfer.files?.[0]);
};

const hasExistingImage = !!(avatarPreview.props as { imageUrl?: string })?.imageUrl;
const previewElement = objectUrl
? React.cloneElement(avatarPreview, { imageUrl: objectUrl })
Expand All@@ -108,11 +153,28 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
/>

<Flex
{...rest}
gap={4}
align='center'
{...rest}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
{previewElement}
<Flex
sx={t => ({
borderRadius: isDraggingOver && rounded ? t.radii.$circle : t.radii.$md,
transitionProperty: t.transitionProperty.$common,
transitionDuration: t.transitionDuration.$controls,
transitionTimingFunction: t.transitionTiming.$common,
...(isDraggingOver && {
outline: `${t.borderWidths.$normal} dashed ${t.colors.$primary500}`,
outlineOffset: t.space.$0x5,
}),
})}
>
{previewElement}
</Flex>
<Col gap={1}>
<Flex
elementDescriptor={descriptors.avatarImageActions}
Expand All@@ -127,7 +189,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
onClick={openDialog}
/>

{!!onAvatarRemove && !showUpload && (

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed a bug where the remove button was showing inconsistently

{!!onAvatarRemove && (
<Button
elementDescriptor={descriptors.avatarImageActionsRemove}
localizationKey={localizationKeys('userProfile.profilePage.imageFormDestructiveActionSubtitle')}
Expand Down
197 changes: 197 additions & 0 deletions packages/ui/src/elements/__tests__/AvatarUploader.test.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
import { fireEvent, render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';

import { localizationKeys } from '../../customizables';
import { AvatarUploader, type AvatarUploaderProps } from '../AvatarUploader';
import { useCardState, withCardStateProvider } from '../contexts';

const { createFixtures } = bindCreateFixtures('UserProfile');

const StubPreview = (_props: { imageUrl?: string }) => <span data-testid='avatar-preview' />;

type HarnessProps = Omit<AvatarUploaderProps, 'title' | 'avatarPreview'>;

const Harness = withCardStateProvider((props: HarnessProps) => {
const card = useCardState();
return (
<>
<AvatarUploader
{...props}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={<StubPreview />}
/>
{card.error ? <div data-testid='card-error'>{card.error}</div> : null}
</>
);
});

const makeImageFile = (size = 1024, type = 'image/png') => {
const file = new File([new Uint8Array(size)], 'logo.png', { type });
Object.defineProperty(file, 'size', { value: size });
return file;
};

const makeDataTransfer = (files: File[] = [], types: string[] = ['Files']) =>
({
files,
types,
items: files.map(f => ({ kind: 'file', type: f.type, getAsFile: () => f })),
dropEffect: 'none',
effectAllowed: 'all',
}) as unknown as DataTransfer;

const findFileInput = (container: HTMLElement) => {
const input = container.querySelector<HTMLInputElement>('input[type="file"]');
if (!input) {
throw new Error('Could not find hidden file input');
}
return input;
};

const findDropZone = (container: HTMLElement) => {
// The outer Flex registered with the drop handlers is the file input's next sibling.
const sibling = findFileInput(container).nextElementSibling;
if (!sibling) {
throw new Error('Could not find drop zone element');
}
return sibling as HTMLElement;
};

describe('AvatarUploader', () => {
describe('click-upload', () => {
it('calls onAvatarChange with the selected file', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.change(findFileInput(container), { target: { files: [file] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});
});

describe('drag-and-drop', () => {
it('calls onAvatarChange when a valid image file is dropped', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([file]) });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});

it('rejects unsupported file types', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const pdf = makeImageFile(1024, 'application/pdf');
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([pdf]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file type not supported/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('rejects files exceeding the max size', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const oversized = makeImageFile(11 * 1000 * 1000);
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([oversized]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file size exceeds/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('ignores drops that do not contain files (e.g. text drags)', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), {
dataTransfer: makeDataTransfer([], ['text/plain']),
});

expect(onAvatarChange).not.toHaveBeenCalled();
});
});

describe('remove button', () => {
it('is hidden when onAvatarRemove is not provided', async () => {
const { wrapper } = await createFixtures();
const { queryByRole } = render(<Harness onAvatarChange={vi.fn().mockResolvedValue(undefined)} />, { wrapper });

expect(queryByRole('button', { name: /^remove$/i })).not.toBeInTheDocument();
});

it('stays visible after a successful upload', async () => {
// Regression: previously `showUpload` was toggled inside handleFileDrop and the remove
// button was gated on `!showUpload`, so it disappeared after each successful upload.
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const onAvatarRemove = vi.fn();
const { container, getByRole } = render(
<Harness
onAvatarChange={onAvatarChange}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();

fireEvent.change(findFileInput(container), { target: { files: [makeImageFile()] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledTimes(1));
await waitFor(() => {
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
});
expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();
});

it('invokes onAvatarRemove when clicked', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
});

it('re-enables buttons after remove completes', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
expect(getByRole('button', { name: /upload/i })).not.toBeDisabled();
});
});
});
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); feat(ui): Add drag to upload to AvatarUploader by alexcarpenter · Pull Request #8348 · clerk/javascript · GitHub
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/wet-ants-kind.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
---
'@clerk/ui': minor
---

Add drag-to-upload support in AvatarUploader
Original file line numberDiff line numberDiff line change
Expand Up@@ -28,6 +28,7 @@ export const OrganizationProfileAvatarUploader = (
/>
<AvatarUploader
{...rest}
rounded={false}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={
<OrganizationAvatar
Expand Down
82 changes: 72 additions & 10 deletions packages/ui/src/elements/AvatarUploader.tsx
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ export type AvatarUploaderProps = {
onAvatarChange: (file: File) => Promise<unknown>;
onAvatarRemove?: (() => void) | null;
avatarPreviewPlaceholder?: React.ReactElement | null;
rounded?: boolean;
};

const fileToBase64 = (file: File): Promise<string> => {
Expand All@@ -39,17 +40,21 @@ const validSize = (f: File) => f.size <= MAX_SIZE_BYTES;

export const AvatarUploader = (props: AvatarUploaderProps) => {
const { t } = useLocalizations();
const [showUpload, setShowUpload] = React.useState(false);
const [objectUrl, setObjectUrl] = React.useState<string>();
const [isDraggingOver, setIsDraggingOver] = React.useState(false);
const card = useCardState();
const inputRef = React.useRef<HTMLInputElement | null>(null);
const openDialog = () => inputRef.current?.click();

const { onAvatarChange, onAvatarRemove, title, avatarPreview, avatarPreviewPlaceholder, ...rest } = props;

const toggle = () => {
setShowUpload(!showUpload);
};
const {
onAvatarChange,
onAvatarRemove,
title,
avatarPreview,
avatarPreviewPlaceholder,
rounded = true,
...rest
} = props;

const handleFileDrop = (file: File | null) => {
if (file === null) {
Expand All@@ -60,7 +65,6 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
card.setLoading();
return onAvatarChange(file)
.then(() => {
toggle();
card.setIdle();
})
.catch(err => handleError(err, [], card.setError));
Expand All@@ -69,6 +73,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
const handleRemove = async () => {
card.setLoading();
await handleFileDrop(null);
card.setIdle();
return onAvatarRemove?.();
};

Expand All@@ -90,6 +95,46 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
await handleFileDrop(f);
};

const isFileDrag = (e: React.DragEvent) => e.dataTransfer?.types?.includes('Files') ?? false;

const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(true);
};

const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
if (card.isLoading || !isFileDrag(e)) {
return;
}
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
};

const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
// Only reset when leaving the container entirely, not when moving between children.
// SAFETY: e.relatedTarget is typed as EventTarget | null, but in drag events it is always
// a DOM Node (or null). Element.contains() requires Node | null; the cast is safe here.
if (e.currentTarget.contains(e.relatedTarget as Node | null)) {
return;
}
setIsDraggingOver(false);
};

const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
if (!isFileDrag(e)) {
return;
}
e.preventDefault();
setIsDraggingOver(false);
if (card.isLoading) {
return;
}
void upload(e.dataTransfer.files?.[0]);
};

const hasExistingImage = !!(avatarPreview.props as { imageUrl?: string })?.imageUrl;
const previewElement = objectUrl
? React.cloneElement(avatarPreview, { imageUrl: objectUrl })
Expand All@@ -108,11 +153,28 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
/>

<Flex
{...rest}
gap={4}
align='center'
{...rest}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
{previewElement}
<Flex
sx={t => ({
borderRadius: isDraggingOver && rounded ? t.radii.$circle : t.radii.$md,
transitionProperty: t.transitionProperty.$common,
transitionDuration: t.transitionDuration.$controls,
transitionTimingFunction: t.transitionTiming.$common,
...(isDraggingOver && {
outline: `${t.borderWidths.$normal} dashed ${t.colors.$primary500}`,
outlineOffset: t.space.$0x5,
}),
})}
>
{previewElement}
</Flex>
<Col gap={1}>
<Flex
elementDescriptor={descriptors.avatarImageActions}
Expand All@@ -127,7 +189,7 @@ export const AvatarUploader = (props: AvatarUploaderProps) => {
onClick={openDialog}
/>

{!!onAvatarRemove && !showUpload && (

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed a bug where the remove button was showing inconsistently

{!!onAvatarRemove && (
<Button
elementDescriptor={descriptors.avatarImageActionsRemove}
localizationKey={localizationKeys('userProfile.profilePage.imageFormDestructiveActionSubtitle')}
Expand Down
197 changes: 197 additions & 0 deletions packages/ui/src/elements/__tests__/AvatarUploader.test.tsx
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
import { fireEvent, render, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';

import { localizationKeys } from '../../customizables';
import { AvatarUploader, type AvatarUploaderProps } from '../AvatarUploader';
import { useCardState, withCardStateProvider } from '../contexts';

const { createFixtures } = bindCreateFixtures('UserProfile');

const StubPreview = (_props: { imageUrl?: string }) => <span data-testid='avatar-preview' />;

type HarnessProps = Omit<AvatarUploaderProps, 'title' | 'avatarPreview'>;

const Harness = withCardStateProvider((props: HarnessProps) => {
const card = useCardState();
return (
<>
<AvatarUploader
{...props}
title={localizationKeys('userProfile.profilePage.imageFormTitle')}
avatarPreview={<StubPreview />}
/>
{card.error ? <div data-testid='card-error'>{card.error}</div> : null}
</>
);
});

const makeImageFile = (size = 1024, type = 'image/png') => {
const file = new File([new Uint8Array(size)], 'logo.png', { type });
Object.defineProperty(file, 'size', { value: size });
return file;
};

const makeDataTransfer = (files: File[] = [], types: string[] = ['Files']) =>
({
files,
types,
items: files.map(f => ({ kind: 'file', type: f.type, getAsFile: () => f })),
dropEffect: 'none',
effectAllowed: 'all',
}) as unknown as DataTransfer;

const findFileInput = (container: HTMLElement) => {
const input = container.querySelector<HTMLInputElement>('input[type="file"]');
if (!input) {
throw new Error('Could not find hidden file input');
}
return input;
};

const findDropZone = (container: HTMLElement) => {
// The outer Flex registered with the drop handlers is the file input's next sibling.
const sibling = findFileInput(container).nextElementSibling;
if (!sibling) {
throw new Error('Could not find drop zone element');
}
return sibling as HTMLElement;
};

describe('AvatarUploader', () => {
describe('click-upload', () => {
it('calls onAvatarChange with the selected file', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.change(findFileInput(container), { target: { files: [file] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});
});

describe('drag-and-drop', () => {
it('calls onAvatarChange when a valid image file is dropped', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const file = makeImageFile();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([file]) });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledWith(file));
});

it('rejects unsupported file types', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const pdf = makeImageFile(1024, 'application/pdf');
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([pdf]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file type not supported/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('rejects files exceeding the max size', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const oversized = makeImageFile(11 * 1000 * 1000);
const { container, findByTestId } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), { dataTransfer: makeDataTransfer([oversized]) });

const error = await findByTestId('card-error');
expect(error).toHaveTextContent(/file size exceeds/i);
expect(onAvatarChange).not.toHaveBeenCalled();
});

it('ignores drops that do not contain files (e.g. text drags)', async () => {
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn();
const { container } = render(<Harness onAvatarChange={onAvatarChange} />, { wrapper });

fireEvent.drop(findDropZone(container), {
dataTransfer: makeDataTransfer([], ['text/plain']),
});

expect(onAvatarChange).not.toHaveBeenCalled();
});
});

describe('remove button', () => {
it('is hidden when onAvatarRemove is not provided', async () => {
const { wrapper } = await createFixtures();
const { queryByRole } = render(<Harness onAvatarChange={vi.fn().mockResolvedValue(undefined)} />, { wrapper });

expect(queryByRole('button', { name: /^remove$/i })).not.toBeInTheDocument();
});

it('stays visible after a successful upload', async () => {
// Regression: previously `showUpload` was toggled inside handleFileDrop and the remove
// button was gated on `!showUpload`, so it disappeared after each successful upload.
const { wrapper } = await createFixtures();
const onAvatarChange = vi.fn().mockResolvedValue(undefined);
const onAvatarRemove = vi.fn();
const { container, getByRole } = render(
<Harness
onAvatarChange={onAvatarChange}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();

fireEvent.change(findFileInput(container), { target: { files: [makeImageFile()] } });

await waitFor(() => expect(onAvatarChange).toHaveBeenCalledTimes(1));
await waitFor(() => {
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
});
expect(getByRole('button', { name: /^remove$/i })).toBeInTheDocument();
});

it('invokes onAvatarRemove when clicked', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
});

it('re-enables buttons after remove completes', async () => {
const user = userEvent.setup();
const { wrapper } = await createFixtures();
const onAvatarRemove = vi.fn();
const { getByRole } = render(
<Harness
onAvatarChange={vi.fn().mockResolvedValue(undefined)}
onAvatarRemove={onAvatarRemove}
/>,
{ wrapper },
);

await user.click(getByRole('button', { name: /^remove$/i }));

await waitFor(() => expect(onAvatarRemove).toHaveBeenCalledTimes(1));
expect(getByRole('button', { name: /^remove$/i })).not.toBeDisabled();
expect(getByRole('button', { name: /upload/i })).not.toBeDisabled();
});
});
});
Loading