forked from nextcloud/forms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnswerInput.vue
More file actions
570 lines (497 loc) Β· 12.6 KB
/
Copy pathAnswerInput.vue
File metadata and controls
570 lines (497 loc) Β· 12.6 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
<!--
- SPDX-FileCopyrightText: 2020 John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
- SPDX-License-Identifier: AGPL-3.0-or-later
-->
<template>
<li class="question__item" @focusout="handleTabbing">
<div
:is="pseudoIcon"
v-if="!isDropdown"
class="question__item__pseudoInput" />
<input
ref="input"
v-model="localText"
:aria-label="ariaLabel"
:placeholder="placeholder"
class="question__input"
:class="{ 'question__input--shifted': !isDropdown }"
:maxlength="maxOptionLength"
type="text"
dir="auto"
@input="debounceOnInput"
@keydown.delete="deleteEntry"
@keydown.enter.prevent="onEnter"
@compositionstart="onCompositionStart"
@compositionend="onCompositionEnd" />
<!-- Actions for reordering and deleting the option -->
<div v-if="!answer.local" class="option__actions">
<NcActions
:id="optionDragMenuId"
:container="`#${optionDragMenuId}`"
:aria-label="t('forms', 'Move option actions')"
class="option__drag-handle"
variant="tertiary-no-background">
<template #icon>
<IconDragIndicator :size="20" />
</template>
<NcActionButton
ref="buttonOptionUp"
:disabled="index === 0"
@click="onMoveUp">
<template #icon>
<IconArrowUp :size="20" />
</template>
{{ t('forms', 'Move option up') }}
</NcActionButton>
<NcActionButton
ref="buttonOptionDown"
:disabled="index === maxIndex"
@click="onMoveDown">
<template #icon>
<IconArrowDown :size="20" />
</template>
{{ t('forms', 'Move option down') }}
</NcActionButton>
</NcActions>
<NcButton
:aria-label="t('forms', 'Delete answer')"
variant="tertiary"
@click="deleteEntry">
<template #icon>
<IconDelete :size="20" />
</template>
</NcButton>
</div>
<div v-else class="option__actions">
<NcButton
:aria-label="t('forms', 'Add a new answer option')"
variant="tertiary"
:disabled="isIMEComposing || !canCreateLocalAnswer"
@click="createLocalAnswer">
<template #icon>
<IconPlus :size="20" />
</template>
</NcButton>
</div>
</li>
</template>
<script>
import axios from '@nextcloud/axios'
import { showError } from '@nextcloud/dialogs'
import { generateOcsUrl } from '@nextcloud/router'
import debounce from 'debounce'
import PQueue from 'p-queue'
import NcActionButton from '@nextcloud/vue/components/NcActionButton'
import NcActions from '@nextcloud/vue/components/NcActions'
import NcButton from '@nextcloud/vue/components/NcButton'
import IconArrowDown from 'vue-material-design-icons/ArrowDown.vue'
import IconArrowUp from 'vue-material-design-icons/ArrowUp.vue'
import IconCheckboxBlankOutline from 'vue-material-design-icons/CheckboxBlankOutline.vue'
import IconPlus from 'vue-material-design-icons/Plus.vue'
import IconRadioboxBlank from 'vue-material-design-icons/RadioboxBlank.vue'
import IconTableColumn from 'vue-material-design-icons/TableColumn.vue'
import IconTableRow from 'vue-material-design-icons/TableRow.vue'
import IconDelete from 'vue-material-design-icons/TrashCanOutline.vue'
import IconDragIndicator from '../Icons/IconDragIndicator.vue'
import { INPUT_DEBOUNCE_MS, OptionType } from '../../models/Constants.ts'
import logger from '../../utils/Logger.js'
import OcsResponse2Data from '../../utils/OcsResponse2Data.js'
export default {
name: 'AnswerInput',
components: {
IconArrowDown,
IconArrowUp,
IconCheckboxBlankOutline,
IconDelete,
IconDragIndicator,
IconPlus,
IconRadioboxBlank,
IconTableColumn,
IconTableRow,
NcActions,
NcActionButton,
NcButton,
},
props: {
answer: {
type: Object,
required: true,
},
index: {
type: Number,
required: true,
},
formId: {
type: Number,
required: true,
},
isUnique: {
type: Boolean,
required: true,
},
isDropdown: {
type: Boolean,
default: false,
},
maxIndex: {
type: Number,
required: true,
},
maxOptionLength: {
type: Number,
required: true,
},
optionType: {
type: String,
required: true,
},
},
emits: [
'tabbed-out',
'create-answer',
'update:answer',
'focus-next',
'delete',
'move-down',
'move-up',
],
data() {
return {
queue: null,
debounceOnInput: null,
isIMEComposing: false,
localText: this.answer?.text ?? '',
}
},
computed: {
canCreateLocalAnswer() {
if (this.answer.local) {
return !!this.localText?.trim()
}
return !!this.answer.text?.trim()
},
ariaLabel() {
if (this.answer.local) {
if (this.optionType === OptionType.Column) {
return t('forms', 'Add a new column')
}
if (this.optionType === OptionType.Row) {
return t('forms', 'Add a new row')
}
return t('forms', 'Add a new answer option')
}
if (this.optionType === OptionType.Column) {
return t('forms', 'The text of column {index}', {
index: this.index + 1,
})
}
if (this.optionType === OptionType.Row) {
return t('forms', 'The text of row {index}', {})
}
return t('forms', 'The text of option {index}', {
index: this.index + 1,
})
},
optionDragMenuId() {
return `q${this.answer.questionId}o${this.answer.id}o${this.optionType}__drag_menu`
},
placeholder() {
if (this.answer.local) {
if (this.optionType === OptionType.Column) {
return t('forms', 'Add a new column')
}
if (this.optionType === OptionType.Row) {
return t('forms', 'Add a new row')
}
return t('forms', 'Add a new answer option')
}
if (this.optionType === OptionType.Column) {
return t('forms', 'Column number {index}', { index: this.index + 1 })
}
if (this.optionType === OptionType.Row) {
return t('forms', 'Row number {index}', { index: this.index + 1 })
}
return t('forms', 'Answer number {index}', { index: this.index + 1 })
},
pseudoIcon() {
if (this.answer.local) {
return IconPlus
}
if (this.optionType === OptionType.Column) {
return IconTableColumn
}
if (this.optionType === OptionType.Row) {
return IconTableRow
}
return this.isUnique ? IconRadioboxBlank : IconCheckboxBlankOutline
},
},
watch: {
// Keep localText in sync when the parent replaces/updates the answer prop
answer: {
handler(newVal) {
this.localText = newVal?.text ?? ''
},
deep: true,
},
},
created() {
this.queue = new PQueue({ concurrency: 1 })
// As data instead of method, to have a separate debounce per AnswerInput
this.debounceOnInput = debounce((event) => {
return this.queue.add(() => this.onInput(event))
}, INPUT_DEBOUNCE_MS)
},
methods: {
handleTabbing() {
this.$emit('tabbed-out', this.optionType)
},
/**
* Focus the input
*/
focus() {
this.$refs.input?.focus()
},
/**
* Option changed, processing the data
*
* @param {InputEvent} event The input event that triggered adding a new entry
*/
async onInput({ target, isComposing }) {
if (this.answer.local) {
this.localText = target.value
return
}
if (!isComposing && !this.isIMEComposing && target.value !== '') {
// clone answer
const answer = { ...this.answer }
answer.text = this.$refs.input.value
await this.updateAnswer(answer)
// Forward changes, but use current answer.text to avoid erasing
// any in-between changes while updating the answer
answer.text = this.$refs.input.value
this.$emit('update:answer', this.index, answer)
}
},
/**
* Handle Enter key: create local answer or move focus
*
* @param {KeyboardEvent} e the keydown event
*/
onEnter(e) {
if (this.answer.local) {
this.createLocalAnswer(e)
return
}
this.focusNextInput(e)
},
/**
* Create a new local answer option from the current input
*
* @param {Event} e the triggering event
*/
async createLocalAnswer(e) {
if (this.isIMEComposing || e?.isComposing) {
return
}
const value = this.localText ?? ''
if (!value.trim()) {
return
}
const answer = { ...this.answer }
answer.text = value
// Dispatched for creation. Marked as synced
this.$set(this.answer, 'local', false)
const newAnswer = await this.createAnswer(answer)
// Forward changes, but use current answer.text to avoid erasing
// any in-between changes while creating the answer
newAnswer.text = this.$refs.input.value
this.localText = ''
this.$emit('create-answer', this.index, newAnswer)
},
/**
* Request a new answer
*
* @param {Event} e the triggering event
*/
focusNextInput(e) {
if (this.isIMEComposing || e?.isComposing) {
return
}
if (this.index <= this.maxIndex) {
this.$emit('focus-next', this.index, this.optionType)
}
},
/**
* Emit a delete request for this answer
* when pressing the delete key on an empty input
*
* @param {Event} e the event
*/
async deleteEntry(e) {
if (this.isIMEComposing || e?.isComposing) {
return
}
if (this.answer.local) {
return
}
if (e.type !== 'click' && this.$refs.input.value.length !== 0) {
return
}
// Dismiss delete key action
e.preventDefault()
// do this in queue to prevent race conditions between PATCH and DELETE
this.queue.add(() => {
this.$emit('delete', this.answer)
// Prevent any patch requests
this.queue.pause()
this.queue.clear()
})
},
/**
* Create an unsynced answer to the server
*
* @param {object} answer the answer to sync
* @return {object} answer
*/
async createAnswer(answer) {
try {
const response = await axios.post(
generateOcsUrl(
'apps/forms/api/v3/forms/{id}/questions/{questionId}/options',
{
id: this.formId,
questionId: answer.questionId,
},
),
{
optionTexts: [answer.text],
optionType: answer.optionType,
},
)
logger.debug('Created answer', { answer })
// Was synced once, this is now up to date with the server
delete answer.local
return OcsResponse2Data(response)[0]
} catch (error) {
logger.error('Error while saving answer', { answer, error })
showError(t('forms', 'Error while saving the answer'))
}
return answer
},
/**
* Save to the server, only do it after 500ms
* of no change
*
* @param {object} answer the answer to sync
*/
async updateAnswer(answer) {
try {
await axios.patch(
generateOcsUrl(
'apps/forms/api/v3/forms/{id}/questions/{questionId}/options/{optionId}',
{
id: this.formId,
questionId: answer.questionId,
optionId: answer.id,
},
),
{
keyValuePairs: {
text: answer.text,
},
},
)
logger.debug('Updated answer', { answer })
} catch (error) {
logger.error('Error while saving answer', { answer, error })
showError(t('forms', 'Error while saving the answer'))
}
},
/**
* Reorder option but keep focus on the button
*/
onMoveDown() {
this.$emit('move-down')
this.focusButton(
this.index < this.maxIndex - 1
? 'buttonOptionDown'
: 'buttonOptionUp',
)
},
onMoveUp() {
this.$emit('move-up')
this.focusButton(this.index > 1 ? 'buttonOptionUp' : 'buttonOptionDown')
},
focusButton(refName) {
this.$nextTick(() => this.$refs[refName].$el.focus())
},
/**
* Handle composition start event for IME inputs
*/
onCompositionStart() {
this.isIMEComposing = true
},
/**
* Handle composition end event for IME inputs
*
* @param {CompositionEvent} event The input event that triggered adding a new entry
*/
onCompositionEnd({ target, isComposing }) {
this.isIMEComposing = false
if (!isComposing) {
this.onInput({ target, isComposing })
}
},
},
}
</script>
<style lang="scss" scoped>
.question__item {
position: relative;
display: inline-flex;
min-height: var(--default-clickable-area);
width: 100%;
&__pseudoInput {
color: var(--color-primary-element);
margin-inline-start: -2px;
z-index: 1;
}
.option__actions {
display: flex;
position: absolute;
gap: var(--default-grid-baseline);
inset-inline-end: 12px;
height: 100%;
}
.option__drag-handle,
.drag-indicator-icon {
color: var(--color-text-maxcontrast);
cursor: grab;
margin-block: auto;
&:hover,
&:focus,
&:focus-within {
color: var(--color-main-text);
}
&:active {
cursor: grabbing;
}
> * {
cursor: grab;
}
}
.question__input {
width: calc(100% - var(--default-clickable-area));
position: relative;
inset-inline-start: -12px;
margin-inline-end: -12px !important;
&--shifted {
inset-inline-start: calc(-1 * var(--default-clickable-area));
padding-inline-start: calc(
var(--default-clickable-area) + var(--default-grid-baseline)
) !important;
}
}
}
</style>