Skip to content

Commit

Permalink
feat(file-uploader): add drag&drop functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
felipebritor committed Aug 15, 2023
1 parent 7621bf1 commit 2906891
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
44 changes: 43 additions & 1 deletion src/components/CvFileUploader/CvFileUploader.vue
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,16 @@
role="button"
tabindex="0"
data-file-drop-container
:class="[`${carbonPrefix}--file-browse-btn`]"
:class="[
`${carbonPrefix}--file-browse-btn`,
`${carbonPrefix}--file__drop-container`,
{
[`${carbonPrefix}--file__drop-container--drag-over`]: allowDrop,
},
]"
@dragover="onDragEvent"
@dragleave="onDragEvent"
@drop="onDragEvent"
@keydown.enter.prevent="onKeyHit"
@keydown.space.prevent="onKeyHit"
>
Expand Down Expand Up @@ -104,6 +113,7 @@ const props = defineProps({
const fileInput = ref(null);
// Data
const allowDrop = ref(false);
const internalFiles = ref([]);
// Computed
Expand Down Expand Up @@ -184,6 +194,38 @@ function onChange(ev) {
addFiles(ev.target.files);
}
function onDragEvent(evt) {
if (Array.prototype.indexOf.call(evt.dataTransfer.types, 'Files') === -1) {
return;
}
if (evt.type === 'dragleave') {
allowDrop.value = false;
return;
}
if (evt.type === 'dragover') {
evt.preventDefault();
const dropEffect = 'copy';
if (Array.isArray(evt.dataTransfer.types)) {
try {
// IE11 throws a "permission denied" error accessing `.effectAllowed`
evt.dataTransfer.effectAllowed = dropEffect;
} catch (e) {
// ignore
}
}
evt.dataTransfer.dropEffect = dropEffect;
allowDrop.value = true;
}
if (evt.type === 'drop') {
evt.preventDefault();
addFiles(evt.dataTransfer.files);
allowDrop.value = false;
}
}
function onKeyHit() {
fileInput.value.click();
}
Expand Down
23 changes: 23 additions & 0 deletions src/components/CvFileUploader/__tests__/CvFileUploader.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -373,4 +373,27 @@ describe('CvFileUploader', () => {
}
);
});

describe('Drag & Drop', () => {
it('emits change when native input change', async () => {
const dummyFile = new File(['file content'], 'dummy-file.txt', {
type: 'text/plain',
});
const { container, emitted } = render(CvFileUploader);

const dropZone = container.querySelector(
`div.${carbonPrefix}--file-browse-btn`
);
await fireEvent.drop(dropZone, {
dataTransfer: {
files: [dummyFile],
types: ['Files'],
},
});

const emitResult = emitted('update:modelValue').at(0);
expect(emitResult[0]).toHaveLength(1);
expect(emitResult[0][0].file.name).toBe(dummyFile.name);
});
});
});

0 comments on commit 2906891

Please sign in to comment.