make public storage and direct upload optional

This commit is contained in:
Alex Turchyn
2023-07-04 01:58:43 +03:00
parent ff18fef2e3
commit 97b3adf91f
23 changed files with 336 additions and 181 deletions
+2 -1
View File
@@ -51,7 +51,8 @@ window.customElements.define('template-builder', class extends HTMLElement {
this.appElem = document.createElement('div')
this.app = createApp(TemplateBuilder, {
template: reactive(JSON.parse(this.dataset.template))
template: reactive(JSON.parse(this.dataset.template)),
isDirectUpload: this.dataset.isDirectUpload === 'true'
})
this.app.mount(this.appElem)
+55 -41
View File
@@ -9,28 +9,36 @@ export default actionable(targetable(class extends HTMLElement {
]
connectedCallback () {
import('@rails/activestorage')
if (this.dataset.isDirectUpload === 'true') {
import('@rails/activestorage')
}
this.addEventListener('drop', this.onDrop)
this.addEventListener('dragover', (e) => e.preventDefault())
document.addEventListener('turbo:submit-end', this.toggleLoading)
}
disconnectedCallback () {
document.removeEventListener('turbo:submit-end', this.toggleLoading)
}
onDrop (e) {
e.preventDefault()
this.input.files = e.dataTransfer.files
this.uploadFiles(e.dataTransfer.files)
}
onSelectFiles (e) {
e.preventDefault()
this.uploadFiles(this.input.files).then(() => {
this.input.value = ''
})
this.uploadFiles(this.input.files)
}
toggleLoading () {
toggleLoading = () => {
this.loading.classList.toggle('hidden')
this.icon.classList.toggle('hidden')
this.classList.toggle('opacity-50')
@@ -39,50 +47,56 @@ export default actionable(targetable(class extends HTMLElement {
async uploadFiles (files) {
this.toggleLoading()
const { DirectUpload } = await import('@rails/activestorage')
if (this.dataset.isDirectUpload === 'true') {
const { DirectUpload } = await import('@rails/activestorage')
await Promise.all(
Array.from(files).map(async (file) => {
const upload = new DirectUpload(
file,
'/direct_uploads',
this.input
)
await Promise.all(
Array.from(files).map(async (file) => {
const upload = new DirectUpload(
file,
'/direct_uploads',
this.input
)
return new Promise((resolve, reject) => {
upload.create((error, blob) => {
if (error) {
console.error(error)
return new Promise((resolve, reject) => {
upload.create((error, blob) => {
if (error) {
console.error(error)
return reject(error)
} else {
return resolve(blob)
}
return reject(error)
} else {
return resolve(blob)
}
})
}).catch((error) => {
console.error(error)
})
}).catch((error) => {
console.error(error)
})
).then((blobs) => {
if (this.dataset.submitOnUpload) {
this.querySelectorAll('[name="blob_signed_ids[]"]').forEach((e) => e.remove())
}
blobs.forEach((blob) => {
const input = document.createElement('input')
input.type = 'hidden'
input.name = 'blob_signed_ids[]'
input.value = blob.signed_id
this.append(input)
})
if (this.dataset.submitOnUpload) {
this.closest('form').querySelector('button[type="submit"]').click()
}
}).finally(() => {
this.toggleLoading()
})
).then((blobs) => {
if (this.dataset.submitOnUpload) {
this.querySelectorAll('[name="blob_signed_ids[]"]').forEach((e) => e.remove())
}
blobs.forEach((blob) => {
const input = document.createElement('input')
input.type = 'hidden'
input.name = 'blob_signed_ids[]'
input.value = blob.signed_id
this.append(input)
})
} else {
if (this.dataset.submitOnUpload) {
this.closest('form').querySelector('button[type="submit"]').click()
}
}).finally(() => {
this.toggleLoading()
})
}
}
}))
+1
View File
@@ -13,6 +13,7 @@ window.customElements.define('submission-form', class extends HTMLElement {
submitterUuid: this.dataset.submitterUuid,
authenticityToken: this.dataset.authenticityToken,
canSendEmail: this.dataset.canSendEmail === 'true',
isDirectUpload: this.dataset.isDirectUpload === 'true',
values: reactive(JSON.parse(this.dataset.values)),
attachments: reactive(JSON.parse(this.dataset.attachments)),
fields: JSON.parse(this.dataset.fields)
@@ -47,6 +47,8 @@
<FileDropzone
:message="`Upload ${field.name || 'Attachments'}${field.required ? '' : ' (optional)'}`"
:submitter-slug="submitterSlug"
:is-direct-upload="isDirectUpload"
:multiple="true"
@upload="onUpload"
/>
</div>
@@ -77,6 +79,11 @@ export default {
required: false,
default: () => ({})
},
isDirectUpload: {
type: Boolean,
required: true,
default: false
},
modelValue: {
type: Array,
required: false,
+68 -39
View File
@@ -69,6 +69,11 @@ export default {
required: false,
default: '*/*'
},
isDirectUpload: {
type: Boolean,
required: true,
default: false
},
multiple: {
type: Boolean,
required: false,
@@ -87,7 +92,9 @@ export default {
}
},
mounted () {
import('@rails/activestorage')
if (this.isDirectUpload) {
import('@rails/activestorage')
}
},
methods: {
onDropFiles (e) {
@@ -105,50 +112,72 @@ export default {
async uploadFiles (files) {
this.isLoading = true
const { DirectUpload } = await import('@rails/activestorage')
if (this.isDirectUpload) {
const { DirectUpload } = await import('@rails/activestorage')
const blobs = await Promise.all(
Array.from(files).map(async (file) => {
const upload = new DirectUpload(
file,
'/direct_uploads',
this.$refs.input
)
const blobs = await Promise.all(
Array.from(files).map(async (file) => {
const upload = new DirectUpload(
file,
'/direct_uploads',
this.$refs.input
)
return new Promise((resolve, reject) => {
upload.create((error, blob) => {
if (error) {
console.error(error)
return new Promise((resolve, reject) => {
upload.create((error, blob) => {
if (error) {
console.error(error)
return reject(error)
} else {
return resolve(blob)
}
return reject(error)
} else {
return resolve(blob)
}
})
}).catch((error) => {
console.error(error)
})
}).catch((error) => {
console.error(error)
})
})
)
)
return await Promise.all(
blobs.map((blob) => {
return fetch('/api/attachments', {
method: 'POST',
body: JSON.stringify({
name: 'attachments',
blob_signed_id: blob.signed_id,
submitter_slug: this.submitterSlug
}),
headers: { 'Content-Type': 'application/json' }
}).then(resp => resp.json()).then((data) => {
return data
})
})).then((result) => {
this.$emit('upload', result)
}).finally(() => {
this.isLoading = false
})
return await Promise.all(
blobs.map((blob) => {
return fetch('/api/attachments', {
method: 'POST',
body: JSON.stringify({
name: 'attachments',
blob_signed_id: blob.signed_id,
submitter_slug: this.submitterSlug
}),
headers: { 'Content-Type': 'application/json' }
}).then(resp => resp.json()).then((data) => {
return data
})
})).then((result) => {
this.$emit('upload', result)
}).finally(() => {
this.isLoading = false
})
} else {
return await Promise.all(
Array.from(files).map((file) => {
const formData = new FormData()
formData.append('file', file)
formData.append('submitter_slug', this.submitterSlug)
formData.append('name', 'attachments')
return fetch('/api/attachments', {
method: 'POST',
body: formData
}).then(resp => resp.json()).then((data) => {
return data
})
})).then((result) => {
this.$emit('upload', result)
}).finally(() => {
this.isLoading = false
})
}
}
}
}
+8
View File
@@ -201,6 +201,7 @@
v-else-if="currentField.type === 'image'"
v-model="values[currentField.uuid]"
:field="currentField"
:is-direct-upload="isDirectUpload"
:attachments-index="attachmentsIndex"
:submitter-slug="submitterSlug"
@attached="[attachments.push($event), $refs.areas.scrollIntoField(currentField)]"
@@ -210,6 +211,7 @@
ref="currentStep"
v-model="values[currentField.uuid]"
:field="currentField"
:is-direct-upload="isDirectUpload"
:attachments-index="attachmentsIndex"
:submitter-slug="submitterSlug"
@attached="attachments.push($event)"
@@ -217,6 +219,7 @@
<AttachmentStep
v-else-if="currentField.type === 'file'"
v-model="values[currentField.uuid]"
:is-direct-upload="isDirectUpload"
:field="currentField"
:attachments-index="attachmentsIndex"
:submitter-slug="submitterSlug"
@@ -315,6 +318,11 @@ export default {
type: String,
required: true
},
isDirectUpload: {
type: Boolean,
required: true,
default: false
},
values: {
type: Object,
required: false,
@@ -30,6 +30,7 @@
:message="`Upload ${field.name || 'Image'}${field.required ? '' : ' (optional)'}`"
:submitter-slug="submitterSlug"
:accept="'image/*'"
:is-direct-upload="isDirectUpload"
@upload="onImageUpload"
/>
</div>
@@ -50,6 +51,11 @@ export default {
type: Object,
required: true
},
isDirectUpload: {
type: Boolean,
required: true,
default: false
},
submitterSlug: {
type: String,
required: true
@@ -56,6 +56,11 @@ export default {
type: String,
required: true
},
isDirectUpload: {
type: Boolean,
required: true,
default: false
},
attachmentsIndex: {
type: Object,
required: false,
@@ -79,7 +84,10 @@ export default {
this.$refs.canvas.height = this.$refs.canvas.parentNode.clientWidth / 3
})
import('@rails/activestorage')
if (this.isDirectUpload) {
import('@rails/activestorage')
}
const { default: SignaturePad } = await import('signature_pad')
this.pad = new SignaturePad(this.$refs.canvas)
@@ -102,31 +110,49 @@ export default {
return Promise.resolve({})
}
const { DirectUpload } = await import('@rails/activestorage')
return new Promise((resolve) => {
this.$refs.canvas.toBlob((blob) => {
this.$refs.canvas.toBlob(async (blob) => {
const file = new File([blob], 'signature.png', { type: 'image/png' })
new DirectUpload(
file,
'/direct_uploads'
).create((_error, data) => {
fetch('/api/attachments', {
if (this.isDirectUpload) {
const { DirectUpload } = await import('@rails/activestorage')
new DirectUpload(
file,
'/direct_uploads'
).create((_error, data) => {
fetch('/api/attachments', {
method: 'POST',
body: JSON.stringify({
submitter_slug: this.submitterSlug,
blob_signed_id: data.signed_id,
name: 'attachments'
}),
headers: { 'Content-Type': 'application/json' }
}).then((resp) => resp.json()).then((attachment) => {
this.$emit('update:model-value', attachment.uuid)
this.$emit('attached', attachment)
return resolve(attachment)
})
})
} else {
const formData = new FormData()
formData.append('file', file)
formData.append('submitter_slug', this.submitterSlug)
formData.append('name', 'attachments')
return fetch('/api/attachments', {
method: 'POST',
body: JSON.stringify({
submitter_slug: this.submitterSlug,
blob_signed_id: data.signed_id,
name: 'attachments'
}),
headers: { 'Content-Type': 'application/json' }
body: formData
}).then((resp) => resp.json()).then((attachment) => {
this.$emit('update:model-value', attachment.uuid)
this.$emit('attached', attachment)
return resolve(attachment)
})
})
}
}, 'image/png')
})
}
+12 -6
View File
@@ -74,6 +74,7 @@
<Upload
v-if="sortedDocuments.length"
:template-id="template.id"
:is-direct-upload="isDirectUpload"
@success="updateFromUpload"
/>
</div>
@@ -83,12 +84,12 @@
ref="documents"
class="pr-3.5 pl-0.5"
>
<template v-if="!sortedDocuments.length">
<Dropzone
:template-id="template.id"
@success="updateFromUpload"
/>
</template>
<Dropzone
v-if="!sortedDocuments.length"
:template-id="template.id"
:is-direct-upload="isDirectUpload"
@success="updateFromUpload"
/>
<template v-else>
<Document
v-for="document in sortedDocuments"
@@ -194,6 +195,11 @@ export default {
template: {
type: Object,
required: true
},
isDirectUpload: {
type: Boolean,
required: true,
default: false
}
},
data () {
+17 -7
View File
@@ -33,15 +33,20 @@
</div>
</div>
</div>
<input
:id="inputId"
ref="input"
type="file"
<form
ref="form"
class="hidden"
accept="image/*, application/pdf"
multiple
@change="upload"
>
<input
:id="inputId"
ref="input"
type="file"
name="files[]"
accept="image/*, application/pdf"
multiple
@change="upload"
>
</form>
</label>
</div>
</template>
@@ -60,6 +65,11 @@ export default {
templateId: {
type: [Number, String],
required: true
},
isDirectUpload: {
type: Boolean,
required: true,
default: false
}
},
emits: ['success'],
+64 -40
View File
@@ -24,15 +24,20 @@
Add Document
</span>
</label>
<input
:id="inputId"
ref="input"
type="file"
<form
ref="form"
class="hidden"
accept="image/*, application/pdf"
multiple
@change="upload"
>
<input
:id="inputId"
ref="input"
name="files[]"
type="file"
accept="image/*, application/pdf"
multiple
@change="upload"
>
</form>
</div>
</template>
@@ -49,6 +54,11 @@ export default {
templateId: {
type: [Number, String],
required: true
},
isDirectUpload: {
type: Boolean,
required: true,
default: false
}
},
emits: ['success'],
@@ -64,52 +74,66 @@ export default {
}
},
mounted () {
import('@rails/activestorage')
if (this.isDirectUpload) {
import('@rails/activestorage')
}
},
methods: {
async upload () {
this.isLoading = true
const { DirectUpload } = await import('@rails/activestorage')
if (this.isDirectUpload) {
const { DirectUpload } = await import('@rails/activestorage')
const blobs = await Promise.all(
Array.from(this.$refs.input.files).map(async (file) => {
const upload = new DirectUpload(
file,
'/direct_uploads',
this.$refs.input
)
const blobs = await Promise.all(
Array.from(this.$refs.input.files).map(async (file) => {
const upload = new DirectUpload(
file,
'/direct_uploads',
this.$refs.input
)
return new Promise((resolve, reject) => {
upload.create((error, blob) => {
if (error) {
console.error(error)
return new Promise((resolve, reject) => {
upload.create((error, blob) => {
if (error) {
console.error(error)
return reject(error)
} else {
return resolve(blob)
}
return reject(error)
} else {
return resolve(blob)
}
})
}).catch((error) => {
console.error(error)
})
}).catch((error) => {
console.error(error)
})
).finally(() => {
this.isLoading = false
})
).finally(() => {
this.isLoading = false
})
this.isProcessing = true
this.isProcessing = true
fetch(`/api/templates/${this.templateId}/documents`, {
method: 'POST',
body: JSON.stringify({ blobs }),
headers: { 'Content-Type': 'application/json' }
}).then(resp => resp.json()).then((data) => {
this.$emit('success', data)
this.$refs.input.value = ''
}).finally(() => {
this.isProcessing = false
})
fetch(`/api/templates/${this.templateId}/documents`, {
method: 'POST',
body: JSON.stringify({ blobs }),
headers: { 'Content-Type': 'application/json' }
}).then(resp => resp.json()).then((data) => {
this.$emit('success', data)
this.$refs.input.value = ''
}).finally(() => {
this.isProcessing = false
})
} else {
fetch(`/api/templates/${this.templateId}/documents`, {
method: 'POST',
body: new FormData(this.$refs.form)
}).then(resp => resp.json()).then((data) => {
this.$emit('success', data)
this.$refs.input.value = ''
}).finally(() => {
this.isLoading = false
})
}
}
}
}