Skip to content

fix(VFileUpload): filter files based on accepted type if passed (#21150) #21158

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 14 commits into from
Closed
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
44 changes: 29 additions & 15 deletions packages/vuetify/src/components/VFileInput/VFileInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { useProxiedModel } from '@/composables/proxiedModel'
import { computed, nextTick, ref, shallowRef, toRef, watch } from 'vue'
import {
callEvent,
filterFilesByAcceptType,
filterInputAttrs,
genericComponent,
humanReadableFileSize,
Expand Down Expand Up @@ -94,12 +95,29 @@ export const VFileInput = genericComponent<VFileInputSlots>()({

setup (props, { attrs, emit, slots }) {
const { t } = useLocale()
const inputRef = ref<HTMLInputElement>()
const model = useProxiedModel(
props,
'modelValue',
props.modelValue,
val => wrapInArray(val),
val => (!props.multiple && Array.isArray(val)) ? val[0] : val,
(val, event) => {
const acceptType = inputRef?.value?.accept
const newValue = filterFilesByAcceptType(val, acceptType)
if (inputRef.value) {
const dataTransfer = new DataTransfer()
// TODO: From the update of J-Sek this should be for (const file of await handleDrop(e))
for (const file of newValue) {
dataTransfer.items.add(file)
}
inputRef.value.files = dataTransfer.files
const eventType = event?.type
if (eventType && (eventType === 'change' || eventType === 'input')) {
inputRef.value.dispatchEvent(new Event(eventType, { bubbles: true }))
}
}
return !props.multiple && Array.isArray(newValue) ? newValue[0] : newValue
},
)
const { isFocused, focus, blur } = useFocus(props)
const base = computed(() => typeof props.showSize !== 'boolean' ? props.showSize : undefined)
Expand All @@ -121,7 +139,6 @@ export const VFileInput = genericComponent<VFileInputSlots>()({
})
const vInputRef = ref<VInput>()
const vFieldRef = ref<VInput>()
const inputRef = ref<HTMLInputElement>()
const isActive = toRef(() => isFocused.value || props.active)
const isPlainOrUnderlined = computed(() => ['plain', 'underlined'].includes(props.variant))
const isDragging = shallowRef(false)
Expand Down Expand Up @@ -170,15 +187,17 @@ export const VFileInput = genericComponent<VFileInputSlots>()({
e.stopImmediatePropagation()
isDragging.value = false

if (!inputRef.value || !hasFilesOrFolders(e)) return
const files = e.dataTransfer?.files
if (!files || files.length === 0 || !inputRef.value || !hasFilesOrFolders(e)) return

const dataTransfer = new DataTransfer()
for (const file of await handleDrop(e)) {
dataTransfer.items.add(file)
}
model.value = Array.from(files)
}
function onFileInputChange (e: Event) {
const files = (e.target as HTMLInputElement)?.files

inputRef.value.files = dataTransfer.files
inputRef.value.dispatchEvent(new Event('change', { bubbles: true }))
if (!files) return

model.value = Array.from(files)
}

watch(model, newValue => {
Expand Down Expand Up @@ -264,13 +283,8 @@ export const VFileInput = genericComponent<VFileInputSlots>()({

onFocus()
}}
onChange={ e => {
if (!e.target) return

const target = e.target as HTMLInputElement
model.value = [...target.files ?? []]
}}
onDragleave={ onDragleave }
onChange={ onFileInputChange }
onFocus={ onFocus }
onBlur={ blur }
{ ...slotProps }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ describe('VFileInput', () => {
it('should add file', async () => {
const model = ref()
const { element } = render(() => (
<VFileInput v-model={ model.value } />
<VFileInput v-model={ model.value } accept="text/plain" />
))

const input = screen.getByCSS('input')
Expand Down
7 changes: 4 additions & 3 deletions packages/vuetify/src/composables/proxiedModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function useProxiedModel<
prop: Prop,
defaultValue?: Props[Prop],
transformIn: (value?: Props[Prop]) => Inner = (v: any) => v,
transformOut: (value: Inner) => Props[Prop] = (v: any) => v,
transformOut: (value: Inner, event?: Event) => Props[Prop] | Promise<Props[Prop]> = (v: any) => v,
) {
const vm = getCurrentInstance('useProxiedModel')
const internal = ref(props[prop] !== undefined ? props[prop] : defaultValue) as Ref<Props[Prop]>
Expand Down Expand Up @@ -52,8 +52,9 @@ export function useProxiedModel<
const externalValue = props[prop]
return transformIn(isControlled.value ? externalValue : internal.value)
},
set (internalValue) {
const newValue = transformOut(internalValue)
async set (internalValue, event?: Event) {
const transformed = transformOut(internalValue, event)
const newValue = await Promise.resolve(transformed)
const value = toRaw(isControlled.value ? props[prop] : internal.value)
if (value === newValue || transformIn(value) === internalValue) {
return
Expand Down
46 changes: 28 additions & 18 deletions packages/vuetify/src/labs/VFileUpload/VFileUpload.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import { useProxiedModel } from '@/composables/proxiedModel'

// Utilities
import { ref, shallowRef } from 'vue'
import { filterInputAttrs, genericComponent, pick, propsFactory, useRender, wrapInArray } from '@/util'
import { filterFilesByAcceptType, filterInputAttrs, genericComponent, pick, propsFactory, useRender, wrapInArray } from '@/util'

// Types
import type { PropType, VNode } from 'vue'
Expand Down Expand Up @@ -99,19 +99,32 @@ export const VFileUpload = genericComponent<VFileUploadSlots>()({

setup (props, { attrs, slots }) {
const { t } = useLocale()
const { handleDrop, hasFilesOrFolders } = useFileDrop()
const { densityClasses } = useDensity(props)
const inputRef = ref<HTMLInputElement | null>(null)
const model = useProxiedModel(
props,
'modelValue',
props.modelValue,
val => wrapInArray(val),
val => (props.multiple || Array.isArray(props.modelValue)) ? val : val[0],
async (val, e) => {
const acceptType = inputRef?.value?.accept
const newValue = filterFilesByAcceptType(val, acceptType)
if (inputRef.value) {
const dataTransfer = new DataTransfer()
// TODO: From the update of J-Sek this should be for (const file of await handleDrop(e))?
for (const file of newValue) {
dataTransfer.items.add(file)
}
inputRef.value.files = dataTransfer.files
inputRef.value.dispatchEvent(new Event('change', { bubbles: true }))
}
return !props.multiple && Array.isArray(newValue) ? newValue[0] : newValue
}
)

const isDragging = shallowRef(false)
const vSheetRef = ref<InstanceType<typeof VSheet> | null>(null)
const inputRef = ref<HTMLInputElement | null>(null)
const { handleDrop } = useFileDrop()

function onDragover (e: DragEvent) {
e.preventDefault()
Expand All @@ -129,15 +142,10 @@ export const VFileUpload = genericComponent<VFileUploadSlots>()({
e.stopImmediatePropagation()
isDragging.value = false

if (!inputRef.value) return

const dataTransfer = new DataTransfer()
for (const file of await handleDrop(e)) {
dataTransfer.items.add(file)
}
const files = e.dataTransfer?.files ?? []
if (!files || files.length === 0 || !inputRef.value || !hasFilesOrFolders(e)) return

inputRef.value.files = dataTransfer.files
inputRef.value.dispatchEvent(new Event('change', { bubbles: true }))
model.value = Array.from(files)
}

function onClick () {
Expand All @@ -153,6 +161,13 @@ export const VFileUpload = genericComponent<VFileUploadSlots>()({
inputRef.value.value = ''
}

function onFileInputChange (e: Event) {
const files = (e.target as HTMLInputElement)?.files
if (!files) return

model.value = Array.from(files)
}

useRender(() => {
const hasTitle = !!(slots.title || props.title)
const hasIcon = !!(slots.icon || props.icon)
Expand All @@ -168,12 +183,7 @@ export const VFileUpload = genericComponent<VFileUploadSlots>()({
disabled={ props.disabled }
multiple={ props.multiple }
name={ props.name }
onChange={ e => {
if (!e.target) return

const target = e.target as HTMLInputElement
model.value = [...target.files ?? []]
}}
onChange={ onFileInputChange }
{ ...inputAttrs }
/>
)
Expand Down
6 changes: 6 additions & 0 deletions packages/vuetify/src/util/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -811,6 +811,12 @@ export function camelizeProps<T extends Record<string, unknown>> (props: T | nul
return out
}

export function filterFilesByAcceptType (files: null | FileList | File[], acceptType?: string): File[] {
if (!files) return []
if (!acceptType) return Array.from(files)
return Array.from(files).filter(file => file.type === acceptType)

This comment was marked as off-topic.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

File type will be dependent provided from the user, like in the example linked on this PR, but do let me know if it is worthwhile to add the suggestion of copilot thanks!

Copy link
Member

Choose a reason for hiding this comment

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

support for image/png, image/jpeg or wildcards image/*?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

For this one it will depend on the type the that user set if no type was set it will return what was uploaded by default with no restriction.

Copy link
Contributor

Choose a reason for hiding this comment

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

So what happens when user sets accept="image/*" and selects jpeg image with type of image/jpeg that does not strictly match the accept attribute value... the file does not pass out of this function. None of the files get out when the user is using wildcards or even comma-separated list of types.

}

export function onlyDefinedProps (props: Record<string, any>) {
const booleanAttributes = ['checked', 'disabled']
return Object.fromEntries(Object.entries(props)
Expand Down
Loading