Files

78 lines
2.1 KiB
JavaScript
Raw Permalink Normal View History

2023-05-28 23:20:48 +03:00
import { actionable } from '@github/catalyst/lib/actionable'
import { target, targetable } from '@github/catalyst/lib/targetable'
2026-05-21 14:50:30 +03:00
import { convertImagesInInput } from './convert_upload'
2023-05-28 23:20:48 +03:00
export default actionable(targetable(class extends HTMLElement {
static [target.static] = [
'loading',
2023-06-24 12:27:34 +03:00
'icon',
2025-05-14 00:54:48 +03:00
'input',
'area'
2023-05-28 23:20:48 +03:00
]
connectedCallback () {
this.addEventListener('dragover', (e) => e.preventDefault())
2025-05-14 00:54:48 +03:00
this.addEventListener('drop', this.onDrop)
document.addEventListener('turbo:submit-end', this.toggleLoading)
2025-05-14 00:54:48 +03:00
this.area?.addEventListener('dragover', this.onDragover)
this.area?.addEventListener('dragleave', this.onDragleave)
}
disconnectedCallback () {
2025-05-14 00:54:48 +03:00
this.removeEventListener('drop', this.onDrop)
document.removeEventListener('turbo:submit-end', this.toggleLoading)
2025-05-14 00:54:48 +03:00
this.area?.removeEventListener('dragover', this.onDragover)
this.area?.removeEventListener('dragleave', this.onDragleave)
}
onDragover (e) {
if (e.dataTransfer?.types?.includes('Files')) {
this.style.backgroundColor = '#F7F3F0'
this.classList.remove('border-base-300', 'hover:bg-base-200/30')
2025-05-15 13:59:06 +03:00
this.classList.add('border-base-content/30')
2025-05-14 00:54:48 +03:00
}
}
onDragleave () {
this.style.backgroundColor = null
2025-05-15 13:59:06 +03:00
this.classList.remove('border-base-content/30')
2025-05-14 00:54:48 +03:00
this.classList.add('border-base-300', 'hover:bg-base-200/30')
2023-05-28 23:20:48 +03:00
}
2026-05-21 14:50:30 +03:00
async onDrop (e) {
2023-05-28 23:20:48 +03:00
e.preventDefault()
this.input.files = e.dataTransfer.files
2026-05-21 14:50:30 +03:00
await convertImagesInInput(this.input)
this.uploadFiles(this.input.files)
2023-05-28 23:20:48 +03:00
}
2026-05-21 14:50:30 +03:00
async onSelectFiles (e) {
2023-05-28 23:20:48 +03:00
e.preventDefault()
2026-05-21 14:50:30 +03:00
await convertImagesInInput(this.input)
this.uploadFiles(this.input.files)
2023-05-28 23:20:48 +03:00
}
2023-08-31 01:12:24 +03:00
toggleLoading = (e) => {
2025-02-21 23:56:18 +02:00
if (e && e.target && (!e.target.contains(this) || !e.detail?.formSubmission?.formElement?.contains(this))) {
2023-08-31 01:12:24 +03:00
return
}
2023-06-24 12:27:34 +03:00
this.loading.classList.toggle('hidden')
this.icon.classList.toggle('hidden')
this.classList.toggle('opacity-50')
}
2024-04-06 15:00:30 +03:00
uploadFiles () {
2023-06-24 12:27:34 +03:00
this.toggleLoading()
2024-04-06 15:00:30 +03:00
if (this.dataset.submitOnUpload) {
this.closest('form').querySelector('button[type="submit"]').click()
}
2023-05-28 23:20:48 +03:00
}
}))