-
Notifications
You must be signed in to change notification settings - Fork 93
/
Create.vue
558 lines (498 loc) Β· 14.1 KB
/
Create.vue
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
<!--
- @copyright Copyright (c) 2018 RenΓ© Gieling <github@dartcafe.de>
-
- @author RenΓ© Gieling <github@dartcafe.de>
- @author Nick Gallo
- @author John Molakvoæ <skjnldsv@protonmail.com>
-
- @license AGPL-3.0-or-later
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as
- published by the Free Software Foundation, either version 3 of the
- License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-->
<template>
<NcAppContent v-if="isLoadingForm">
<NcEmptyContent :title="t('forms', 'Loading {title} β¦', { title: form.title })">
<template #icon>
<NcLoadingIcon :size="64" />
</template>
</NcEmptyContent>
</NcAppContent>
<NcAppContent v-else>
<!-- Show results & sidebar button -->
<TopBar :permissions="form?.permissions"
:sidebar-opened="sidebarOpened"
@update:sidebarOpened="onSidebarChange"
@share-form="onShareForm" />
<!-- Forms title & description-->
<header v-click-outside="disableEdit" @click="enableEdit">
<h2>
<label class="hidden-visually" for="form-title">{{ t('forms', 'Form title') }}</label>
<textarea id="form-title"
ref="title"
v-model="form.title"
class="form-title"
rows="1"
dir="auto"
:maxlength="maxStringLengths.formTitle"
:placeholder="t('forms', 'Form title')"
:readonly="!edit"
:required="true"
autofocus
@focus="enableEdit"
@input="onTitleChange" />
</h2>
<template v-if="edit">
<label class="hidden-visually" for="form-desc">
{{ t('forms', 'Description') }}
</label>
<textarea id="form-desc"
ref="description"
class="form-desc form-desc__input"
rows="1"
dir="auto"
:value="form.description"
:placeholder="t('forms', 'Description (formatting using Markdown is supported)')"
:maxlength="maxStringLengths.formDescription"
@blur="disableEdit"
@input="updateDescription" />
</template>
<!-- eslint-disable vue/no-v-html -->
<div v-else
class="form-desc form-desc__output"
dir="auto"
v-html="formDescription" />
<!-- eslint-enable vue/no-v-html -->
<!-- Show expiration message-->
<p v-if="form.expires && form.showExpiration" class="info-message">
{{ expirationMessage }}
</p>
<!-- Generate form information message-->
<p v-if="infoMessage" class="info-message">
{{ infoMessage }}
</p>
</header>
<section>
<!-- Questions list -->
<Draggable v-model="form.questions"
:animation="200"
tag="ul"
handle=".question__drag-handle"
@change="onQuestionOrderChange"
@start="isDragging = true"
@end="isDragging = false">
<Questions :is="answerTypes[question.type].component"
v-for="(question, index) in form.questions"
ref="questions"
:key="question.id"
:answer-type="answerTypes[question.type]"
:index="index + 1"
:max-string-lengths="maxStringLengths"
v-bind.sync="form.questions[index]"
@delete="deleteQuestion(question)" />
</Draggable>
<!-- Add new questions menu -->
<div class="question-menu">
<NcActions ref="questionMenu"
:open.sync="questionMenuOpened"
:menu-title="t('forms', 'Add a question')"
:aria-label="t('forms', 'Add a question')"
:primary="true">
<template #icon>
<NcLoadingIcon v-if="isLoadingQuestions" :size="20" />
<IconPlus v-else :size="20" />
</template>
<NcActionButton v-for="(answer, type) in answerTypesFilter"
:key="answer.label"
:close-after-click="true"
:disabled="isLoadingQuestions"
class="question-menu__question"
@click="addQuestion(type)">
<template #icon>
<Icon :is="answer.icon" :size="20" />
</template>
{{ answer.label }}
</NcActionButton>
</NcActions>
</div>
</section>
</NcAppContent>
</template>
<script>
import { directive as ClickOutside } from 'v-click-outside'
import { generateOcsUrl } from '@nextcloud/router'
import { loadState } from '@nextcloud/initial-state'
import { showError } from '@nextcloud/dialogs'
import { emit } from '@nextcloud/event-bus'
import axios from '@nextcloud/axios'
import moment from '@nextcloud/moment'
import debounce from 'debounce'
import Draggable from 'vuedraggable'
import NcActionButton from '@nextcloud/vue/dist/Components/NcActionButton.js'
import NcActions from '@nextcloud/vue/dist/Components/NcActions.js'
import NcAppContent from '@nextcloud/vue/dist/Components/NcAppContent.js'
import NcEmptyContent from '@nextcloud/vue/dist/Components/NcEmptyContent.js'
import NcLoadingIcon from '@nextcloud/vue/dist/Components/NcLoadingIcon.js'
import IconPlus from 'vue-material-design-icons/Plus.vue'
import answerTypes from '../models/AnswerTypes.js'
import Question from '../components/Questions/Question.vue'
import QuestionLong from '../components/Questions/QuestionLong.vue'
import QuestionMultiple from '../components/Questions/QuestionMultiple.vue'
import QuestionShort from '../components/Questions/QuestionShort.vue'
import TopBar from '../components/TopBar.vue'
import ViewsMixin from '../mixins/ViewsMixin.js'
import logger from '../utils/Logger.js'
import SetWindowTitle from '../utils/SetWindowTitle.js'
import OcsResponse2Data from '../utils/OcsResponse2Data.js'
window.axios = axios
export default {
name: 'Create',
components: {
Draggable,
IconPlus,
NcActionButton,
NcActions,
NcAppContent,
NcEmptyContent,
NcLoadingIcon,
Question,
QuestionLong,
QuestionShort,
QuestionMultiple,
TopBar,
},
directives: {
ClickOutside,
},
mixins: [ViewsMixin],
data() {
return {
answerTypes,
edit: false,
// Various states
isLoadingQuestions: false,
isDragging: false,
maxStringLengths: loadState('forms', 'maxStringLengths'),
questionMenuOpened: false,
}
},
computed: {
hasQuestions() {
return this.form.questions && this.form.questions.length === 0
},
isRequiredUsed() {
return this.form.questions.reduce((isUsed, question) => isUsed || question.isRequired, false)
},
/**
* Check if form is expired
*/
isExpired() {
return this.form.expires && moment().unix() > this.form.expires
},
infoMessage() {
let message = ''
if (this.form.isAnonymous) {
message += t('forms', 'Responses are anonymous.')
}
// On Submit, this is dependent on `isLoggedIn`. Create-view is always logged in and the variable isLoggedIn does not exist.
if (!this.form.isAnonymous && true) {
message += t('forms', 'Responses are connected to your account.')
}
if (this.isRequiredUsed) {
message += ' ' + t('forms', 'An asterisk (*) indicates mandatory questions.')
}
return message
},
expirationMessage() {
const relativeDate = moment(this.form.expires, 'X').fromNow()
if (this.isExpired) {
return t('forms', 'Expired {relativeDate}.', { relativeDate })
}
return t('forms', 'Expires {relativeDate}.', { relativeDate })
},
// Remove properties from answerTypes for create button
answerTypesFilter() {
// Extract property datetime from answerTypes and copy rest to filteredAnswerTypes
const { datetime, ...filteredAnswerTypes } = answerTypes
return filteredAnswerTypes
},
},
watch: {
// Fetch full form on change
hash() {
this.fetchFullForm(this.form.id)
this.initEdit()
},
// Update Window-Title on title change
'form.title'() {
SetWindowTitle(this.formTitle)
},
// resize description if form is loaded
isLoadingForm(value) {
if (!value && this.edit) {
this.resizeTitle()
this.resizeDescription()
}
},
},
mounted() {
this.fetchFullForm(this.form.id)
SetWindowTitle(this.formTitle)
this.initEdit()
},
methods: {
onTitleChange() {
this.resizeTitle()
this.saveTitle()
},
disableEdit() {
// Keep edit if no title set
if (this.form.title) {
this.edit = false
this.$refs.title.style.height = 'auto'
}
},
enableEdit() {
this.edit = true
this.resizeDescription()
this.resizeTitle()
},
initEdit() {
if (this.form.title) {
this.edit = false
} else {
this.edit = true
}
},
/**
* Auto adjust the title height based its scroll height
*/
resizeTitle() {
this.$nextTick(() => {
const textarea = this.$refs.title
textarea.style.cssText = 'height: 0'
// include 2px border
textarea.style.cssText = `height: ${textarea.scrollHeight + 4}px`
})
},
/**
* Auto adjust the description height based on its scroll height
*/
resizeDescription() {
// nextTick to ensure textarea is attached to DOM
this.$nextTick(() => {
const textarea = this.$refs.description
textarea.style.cssText = 'height: 0'
// include 2px border
textarea.style.cssText = `height: ${textarea.scrollHeight + 4}px`
})
},
/**
* Update the description
*
* @param {InputEvent} ev The input event of the textarea
*/
updateDescription({ target }) {
this.form.description = target.value
this.resizeDescription()
this.saveDescription()
},
/**
* Title & description save methods
*/
saveTitle: debounce(async function() {
this.saveFormProperty('title')
}, 200),
saveDescription: debounce(async function() {
this.saveFormProperty('description')
}, 200),
/**
* Add a new question to the current form
*
* @param {string} type the question type, see AnswerTypes
*/
async addQuestion(type) {
const text = ''
this.isLoadingQuestions = true
try {
const response = await axios.post(generateOcsUrl('apps/forms/api/v2.1/question'), {
formId: this.form.id,
type,
text,
})
const question = OcsResponse2Data(response)
// Add newly created question
this.form.questions.push(Object.assign({
text,
type,
answers: [],
}, question))
// Focus newly added question
this.$nextTick(() => {
const lastQuestion = this.$refs.questions[this.$refs.questions.length - 1]
lastQuestion.focus()
})
emit('forms:last-updated:set', this.form.id)
} catch (error) {
logger.error('Error while adding new question', { error })
showError(t('forms', 'There was an error while adding the new question'))
} finally {
this.isLoadingQuestions = false
}
},
/**
* Delete a question
*
* @param {object} question the question to delete
* @param {number} question.id the question id to delete
*/
async deleteQuestion({ id }) {
this.isLoadingQuestions = true
try {
await axios.delete(generateOcsUrl('apps/forms/api/v2.1/question/{id}', { id }))
const index = this.form.questions.findIndex(search => search.id === id)
this.form.questions.splice(index, 1)
emit('forms:last-updated:set', this.form.id)
} catch (error) {
logger.error(`Error while removing question ${id}`, { error })
showError(t('forms', 'There was an error while removing the question'))
} finally {
this.isLoadingQuestions = false
}
},
/**
* Reorder questions on dragEnd
*/
async onQuestionOrderChange() {
this.isLoadingQuestions = true
const newOrder = this.form.questions.map(question => question.id)
try {
await axios.post(generateOcsUrl('apps/forms/api/v2.1/question/reorder'), {
formId: this.form.id,
newOrder,
})
emit('forms:last-updated:set', this.form.id)
} catch (error) {
logger.error('Error while saving form', { error })
showError(t('forms', 'Error while saving form'))
} finally {
this.isLoadingQuestions = false
}
},
/**
* Add question methods
*/
openQuestionMenu() {
// TODO: fix the vue components to allow external click triggers without
// conflicting with the click outside directive
setTimeout(() => {
this.questionMenuOpened = true
this.$nextTick(() => {
this.$refs.questionMenu.focusFirstAction()
})
}, 10)
},
},
}
</script>
<style lang="scss" scoped>
@import '../scssmixins/markdownOutput';
.app-content {
display: flex;
align-items: center;
flex-direction: column;
header,
section {
width: 100%;
max-width: 750px;
}
// Title & description header
header {
display: flex;
flex-direction: column;
margin-block-end: 24px;
margin-inline-start: 56px;
.form-title {
font-size: 28px;
font-weight: bold;
line-height: 34px;
color: var(--color-main-text);
min-height: 36px;
// padding and margin should be aligned with the submit view (but keep the 2px border in mind)
padding-block: 4px;
padding-inline: 14px;
margin-block: 22px 14px;
margin-inline: 0;
width: calc(100% - 56px); // margin of header, needed if screen is < 806px (max-width + margin-left)
overflow: hidden;
text-overflow: ellipsis;
resize: none;
&:read-only {
border-color: transparent;
}
&::placeholder {
font-size: 28px;
}
}
.form-desc,
.info-message {
font-size: 100%;
min-height: unset;
padding-block: 0px 20px;
padding-inline: 16px;
width: calc(100% - 56px);
}
.form-desc {
color: var(--color-text-maxcontrast);
line-height: 22px;
min-height: 47px; // one line (25px padding + 22px text height)
padding-block-start: 5px; // spacing border<>text
margin: 0px;
&__input {
padding-block: 3px 18px; // 2px smaller because of border
padding-inline: 14px;
resize: none;
}
// Styling for rendered Output
&__output {
@include markdown-output;
}
}
.info-message {
margin-block-start: 4px;
resize: none;
color: var(--color-text-maxcontrast);
}
}
// Questions container
section {
position: relative;
display: flex;
flex-direction: column;
margin-block-end: 250px;
.question-menu {
position: sticky;
inset-block-end: 0px;
padding-block-end: 16px;
// Above other menus
z-index: 55;
display: flex;
align-items: center;
align-self: flex-start;
// To align with text
margin-inline-start: 44px;
}
}
}
</style>