Repository navigation
Expand file tree
/
Copy pathQuestionFile.vue
More file actions
618 lines (552 loc) Β· 16 KB
/
Copy pathQuestionFile.vue
File metadata and controls
618 lines (552 loc) Β· 16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
<!--
- SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
- SPDX-License-Identifier: AGPL-3.0-or-later
-->
<template>
<Question
ref="rootElement"
v-bind="questionProps"
:titlePlaceholder="answerType.titlePlaceholder"
:warningInvalid="answerType.warningInvalid"
:errorMessage="errorMessage"
v-on="commonListeners">
<template #actions>
<template v-if="!allowedFileTypesDialogOpened">
<NcActionButton isMenu @click="allowedFileTypesDialogOpened = true">
<template #icon>
<NcIconSvgWrapper :svg="IconFileDocumentAlert" />
</template>
{{ allowedFileTypesLabel }}
</NcActionButton>
<NcActionInput
type="number"
:modelValue="maxAllowedFilesCount"
labelOutside
:label="t('forms', 'Maximum number of files')"
:showTrailingButton="false"
@update:modelValue="onMaxAllowedFilesCountInput" />
<NcActionInput
type="number"
:modelValue="maxFileSizeValue"
labelOutside
:showTrailingButton="false"
:label="t('forms', 'Maximum file size')"
@update:modelValue="onMaxFileSizeValueInput" />
<NcActionInput
type="multiselect"
:modelValue="maxFileSizeUnit"
:options="availableUnits"
:aria-label-combobox="t('forms', 'File size unit')"
required
:clearable="false"
:searchable="false"
@update:modelValue="onMaxFileSizeUnitInput" />
</template>
<template v-else>
<NcActionSeparator />
<NcActionButton @click="allowedFileTypesDialogOpened = false">
<template #icon>
<NcIconSvgWrapper :svg="IconChevronLeft" />
</template>
{{ t('forms', 'Allow only specific file types') }}
</NcActionButton>
<NcActionCheckbox
v-for="({ label: fileTypeLabel }, fileType) in fileTypes"
:key="fileType"
:modelValue="allowedFileTypes.includes(fileType)"
:value="fileType"
class="file-type-checkbox"
@update:modelValue="onAllowedFileTypesChange(fileType, $event)">
{{ fileTypeLabel }}
</NcActionCheckbox>
<NcActionInput
key="allowed-file-extensions-multiselect"
:label="t('forms', 'Custom file extensions')"
:aria-label-combobox="t('forms', 'Custom file extensions')"
type="multiselect"
multiple
taggable
:modelValue="allowedFileExtensions"
@option:created="onAllowedFileExtensionsAdded"
@option:deselected="onAllowedFileExtensionsDeleted" />
<NcActionSeparator />
</template>
</template>
<div class="question__content">
<ul>
<NcListItem
v-for="uploadedFile of uploadedFiles"
:key="uploadedFile.uploadedFileId"
:name="uploadedFile.fileName"
compact>
<template #icon>
<NcIconSvgWrapper :svg="IconFile" />
</template>
<template #actions>
<NcActionButton
@click="
onDeleteUploadedFile(uploadedFile.uploadedFileId)
">
<template #icon>
<NcIconSvgWrapper :svg="IconDelete" />
</template>
{{ t('forms', 'Delete') }}
</NcActionButton>
</template>
</NcListItem>
<li v-if="fileLoading" class="question__loading">
<NcLoadingIcon v-show="fileLoading" />
{{ t('forms', 'UploadingΒ β¦') }}
</li>
<li v-else-if="uploadedFiles.length < maxAllowedFilesCount">
<div
class="question__input-wrapper"
role="group"
:aria-labelledby="titleId"
:aria-describedby="description ? descriptionId : undefined"
:aria-errormessage="hasError ? errorId : undefined"
:aria-invalid="hasError ? 'true' : undefined">
<label>
{{ t('forms', 'Add new file as answer') }}
<input
ref="fileInput"
class="hidden-visually"
type="file"
:required="isRequired && values.length === 0"
:disabled="!readOnly"
:multiple="maxAllowedFilesCount > 1"
:name="name || undefined"
:accept="
accept.length ? accept.join(',') : undefined
"
@invalid.prevent="validate"
@input="onFileInput" />
</label>
<NcButton
:aria-label="uploadButtonLabel"
:disabled="
!readOnly || values.length >= maxAllowedFilesCount
"
variant="tertiary-no-background"
@click="toggleFileInput">
<template #icon>
<NcIconSvgWrapper
v-if="maxAllowedFilesCount > 1"
:svg="IconUploadMultiple" />
<NcIconSvgWrapper v-else :svg="IconUpload" />
</template>
</NcButton>
</div>
</li>
</ul>
</div>
<template #insert>
<slot name="insert" />
</template>
</Question>
</template>
<script lang="ts">
import IconChevronLeft from '@material-symbols/svg-400/outlined/chevron_left.svg?raw'
import IconDelete from '@material-symbols/svg-400/outlined/delete.svg?raw'
import IconFile from '@material-symbols/svg-400/outlined/draft.svg?raw'
import IconFileDocumentAlert from '@material-symbols/svg-400/outlined/quick_reference.svg?raw'
import IconUpload from '@material-symbols/svg-400/outlined/upload.svg?raw'
import IconUploadMultiple from '@material-symbols/svg-400/outlined/upload_file.svg?raw'
import axios from '@nextcloud/axios'
import { showError } from '@nextcloud/dialogs'
import { formatFileSize } from '@nextcloud/files'
import { loadState } from '@nextcloud/initial-state'
import { n, t } from '@nextcloud/l10n'
import { generateOcsUrl } from '@nextcloud/router'
import { computed, defineComponent, onMounted, ref } from 'vue'
import NcActionButton from '@nextcloud/vue/components/NcActionButton'
import NcActionCheckbox from '@nextcloud/vue/components/NcActionCheckbox'
import NcActionInput from '@nextcloud/vue/components/NcActionInput'
import NcActionSeparator from '@nextcloud/vue/components/NcActionSeparator'
import NcButton from '@nextcloud/vue/components/NcButton'
import NcIconSvgWrapper from '@nextcloud/vue/components/NcIconSvgWrapper'
import NcListItem from '@nextcloud/vue/components/NcListItem'
import NcLoadingIcon from '@nextcloud/vue/components/NcLoadingIcon'
import Question from './Question.vue'
import {
QUESTION_EMITS,
QUESTION_PROPS,
useQuestion,
} from '../../composables/useQuestion.ts'
import fileTypes from '../../models/FileTypes.ts'
import logger from '../../utils/Logger.ts'
import OcsResponse2Data from '../../utils/OcsResponse2Data.ts'
const formsAppName = 'forms'
/**
* A constant object representing file size units in bytes.
*
* @example
* ```typescript
* const kilobytes = FILE_SIZE_UNITS.kb; // 1024
* const megabytes = FILE_SIZE_UNITS.mb; // 1048576
* const gigabytes = FILE_SIZE_UNITS.gb; // 1073741824
* ```
*/
const FILE_SIZE_UNITS = {
kb: 1024,
mb: 1024 ** 2,
gb: 1024 ** 3,
}
type FileSizeUnit = keyof typeof FILE_SIZE_UNITS
type UploadedFileValue = {
fileName: string
uploadedFileId: number | string
}
type QuestionFileExtraSettings = {
allowedFileExtensions?: string[]
allowedFileTypes?: string[]
maxAllowedFilesCount?: number
maxFileSize?: number
}
export default defineComponent({
name: 'QuestionFile',
components: {
NcIconSvgWrapper,
NcActionButton,
NcActionCheckbox,
NcActionInput,
NcActionSeparator,
NcButton,
NcListItem,
NcLoadingIcon,
Question,
},
props: QUESTION_PROPS,
emits: [...QUESTION_EMITS, 'update:values'],
setup(props, { emit }) {
const rootElement = ref<{ $el?: HTMLElement } | null>(null)
const question = useQuestion(props, { emit, rootElement })
const values = computed<UploadedFileValue[]>(() => {
return props.values as UploadedFileValue[]
})
const extraSettings = computed<QuestionFileExtraSettings>(() => {
return (
(props.extraSettings as QuestionFileExtraSettings | undefined) ?? {}
)
})
const fileInput = ref<HTMLInputElement | null>(null)
const fileLoading = ref(false)
const maxFileSizeUnit = ref<FileSizeUnit>(
Object.keys(FILE_SIZE_UNITS)[0] as FileSizeUnit,
)
const maxFileSizeValue = ref(0)
const allowedFileTypesDialogOpened = ref(false)
const availableUnits = computed<FileSizeUnit[]>(() => {
return Object.keys(FILE_SIZE_UNITS) as FileSizeUnit[]
})
const uploadedFiles = computed<UploadedFileValue[]>(() => {
return values.value
})
const maxAllowedFilesCount = computed<number>(() => {
return extraSettings.value.maxAllowedFilesCount ?? 1
})
const uploadButtonLabel = computed<string>(() => {
return n(
'forms',
'Upload a file',
'Upload files',
maxAllowedFilesCount.value,
)
})
const allowedFileExtensions = computed<string[]>(() => {
return extraSettings.value.allowedFileExtensions ?? []
})
const allowedFileTypes = computed<string[]>(() => {
return extraSettings.value.allowedFileTypes ?? []
})
const allowedFileTypesLabel = computed<string>(() => {
const allowedFileTypeLabels: string[] = []
if (extraSettings.value.allowedFileTypes?.length) {
allowedFileTypeLabels.push(
...extraSettings.value.allowedFileTypes.map(
(type: string) => fileTypes[type].label,
),
)
}
if (extraSettings.value.allowedFileExtensions?.length) {
allowedFileTypeLabels.push(
...extraSettings.value.allowedFileExtensions,
)
}
if (allowedFileTypeLabels.length) {
return t('forms', 'Allowed file types: {fileTypes}.', {
fileTypes: allowedFileTypeLabels.join(', '),
})
}
return t('forms', 'All file types are allowed.')
})
onMounted(() => {
if (extraSettings.value.maxFileSize) {
const maxFileSize = extraSettings.value.maxFileSize
Object.keys(FILE_SIZE_UNITS).forEach((unit) => {
const typedUnit = unit as FileSizeUnit
if (maxFileSize > FILE_SIZE_UNITS[typedUnit]) {
maxFileSizeUnit.value = typedUnit
}
})
maxFileSizeValue.value =
maxFileSize / FILE_SIZE_UNITS[maxFileSizeUnit.value]
}
})
const toggleFileInput = (): void => {
;(fileInput.value as HTMLInputElement | undefined)?.click()
}
const onFileInput = async (): Promise<void> => {
const currentInput = fileInput.value
if (!currentInput?.files) {
return
}
const formData = new FormData()
let fileInvalid = false
;[...currentInput.files].forEach((file) => {
formData.append('files[]', file)
if (
extraSettings.value.maxFileSize
&& extraSettings.value.maxFileSize > 0
&& file.size > extraSettings.value.maxFileSize
) {
showError(
t(
'forms',
'The file {fileName} is too large. The maximum file size is {maxFileSize}.',
{
fileName: file.name,
maxFileSize: formatFileSize(
extraSettings.value.maxFileSize,
),
},
),
)
fileInvalid = true
}
})
if (fileInvalid) {
return
}
formData.append(
'shareHash',
String(loadState(formsAppName, 'shareHash', null) ?? ''),
)
const url = generateOcsUrl(
'apps/forms/api/v3/forms/{id}/submissions/files/{questionId}',
{
id: props.formId,
questionId: props.id,
},
)
let response
try {
fileLoading.value = true
response = await axios.post(url, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
})
} catch (error) {
logger.error('Error while submitting the form', { error })
showError(
t(
'forms',
'There was an error during submitting the file: {message}.',
{
message:
(
error as {
response?: {
data?: {
ocs?: {
meta?: {
message?: string
}
}
}
}
}
).response?.data?.ocs?.meta?.message ?? '',
},
),
)
return
} finally {
fileLoading.value = false
currentInput.value = ''
}
emit('update:values', [
...values.value,
...(OcsResponse2Data(response) as UploadedFileValue[]),
])
}
const onMaxAllowedFilesCountInput = (
maxAllowedFilesCountValue: number | string,
): void => {
question.onExtraSettingsChange({
maxAllowedFilesCount: parseInt(
String(maxAllowedFilesCountValue),
10,
),
})
}
const onMaxFileSizeValueInput = (
newMaxFileSizeValue: number | string,
): void => {
maxFileSizeValue.value = Number(newMaxFileSizeValue)
const maxFileSize = Math.round(
Number(newMaxFileSizeValue) * FILE_SIZE_UNITS[maxFileSizeUnit.value],
)
question.onExtraSettingsChange({ maxFileSize })
}
const onMaxFileSizeUnitInput = (newMaxFileSizeUnit: FileSizeUnit): void => {
maxFileSizeUnit.value = newMaxFileSizeUnit
const maxFileSize = Math.round(
maxFileSizeValue.value * FILE_SIZE_UNITS[newMaxFileSizeUnit],
)
question.onExtraSettingsChange({ maxFileSize })
}
const onAllowedFileTypesChange = (
fileType: string,
allowed: boolean,
): void => {
let allowedFileTypesList = extraSettings.value.allowedFileTypes ?? []
if (allowed) {
allowedFileTypesList.push(fileType)
} else {
allowedFileTypesList = allowedFileTypesList.filter(
(type) => type !== fileType,
)
}
question.onExtraSettingsChange({
allowedFileTypes: allowedFileTypesList,
})
}
const onAllowedFileExtensionsAdded = (fileExtension: string): void => {
const allowedFileExtensionsList =
extraSettings.value.allowedFileExtensions ?? []
allowedFileExtensionsList.push(fileExtension)
question.onExtraSettingsChange({
allowedFileExtensions: allowedFileExtensionsList,
})
}
const onAllowedFileExtensionsDeleted = (fileExtension: string): void => {
let allowedFileExtensionsList =
extraSettings.value.allowedFileExtensions ?? []
allowedFileExtensionsList = allowedFileExtensionsList.filter(
(extension) => extension !== fileExtension,
)
question.onExtraSettingsChange({
allowedFileExtensions: allowedFileExtensionsList,
})
}
const onDeleteUploadedFile = (uploadedFileId: number | string): void => {
const remainingValues = values.value.filter(
(value) => value.uploadedFileId !== uploadedFileId,
)
emit('update:values', remainingValues)
}
const validate = async (): Promise<boolean> => {
if (fileLoading.value) {
question.errorMessage.value = t(
'forms',
'Please wait until the file has been uploaded.',
)
return false
}
if (props.isRequired && uploadedFiles.value.length === 0) {
question.errorMessage.value = t(
'forms',
'You must answer this question',
)
return false
}
question.errorMessage.value = null
return true
}
return {
...question,
rootElement,
values,
IconChevronLeft,
IconDelete,
IconFile,
IconFileDocumentAlert,
IconUpload,
IconUploadMultiple,
t,
fileInput,
fileTypes,
fileLoading,
maxFileSizeUnit,
maxFileSizeValue,
allowedFileTypesDialogOpened,
availableUnits,
uploadedFiles,
maxAllowedFilesCount,
uploadButtonLabel,
allowedFileExtensions,
allowedFileTypes,
allowedFileTypesLabel,
toggleFileInput,
onFileInput,
onMaxAllowedFilesCountInput,
onMaxFileSizeValueInput,
onMaxFileSizeUnitInput,
onAllowedFileTypesChange,
onAllowedFileExtensionsAdded,
onAllowedFileExtensionsDeleted,
onDeleteUploadedFile,
validate,
}
},
})
</script>
<style scoped lang="scss">
.file-type-checkbox {
margin-inline-start: 30px;
}
.question {
&--editable {
.question__input-wrapper {
margin-inline-start: -13px;
}
}
&__loading {
display: flex;
justify-content: center;
width: 300px;
}
&__input-wrapper {
--focus-offset: calc(
(var(--border-width-input-focused, 2px) - var(--border-width-input, 2px))
);
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-between;
border: var(--border-width-input, 2px) solid var(--color-border-dark);
border-radius: var(--border-radius-element, var(--border-radius-large));
padding-inline: calc(3 * var(--default-grid-baseline)) var(--focus-offset);
padding-block: var(--focus-offset);
height: var(--default-clickable-area);
width: 100%;
max-width: 300px;
label {
color: var(--color-text-maxcontrast);
&:has(input:disabled) {
cursor: default;
}
}
&:hover,
&:focus-within {
border-color: var(--color-main-text);
border-width: var(--border-width-input-focused, 2px);
padding-block: 0;
padding-inline: calc(
3 * var(--default-grid-baseline) - var(--focus-offset)
)
0;
}
}
}
</style>