forms/src/views/Create.vue
John Molakvoæ (skjnldsv) df69a7a4a3 Multiple uniques & aria
Signed-off-by: John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
2020-04-24 17:27:49 +02:00

555 lines
12 KiB
Vue

<!--
- @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 GNU AGPL version 3 or any later version
-
- 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/>.
-
-
- UPDATE: Adds Quiz option and takes the input:
- is yet to store input of quizzes and cannot represtent them
- requires quizFormItem.vue (should be added to svn)
-->
<template>
<AppContent v-if="loadingForm">
<EmptyContent icon="icon-loading">
{{ t('forms', 'Loading form “{title}”', { title: form.title }) }}
</EmptyContent>
</AppContent>
<AppContent v-else>
<!-- Show results & sidebar button -->
<TopBar>
<button class="primary" @click="showResults">
<span class="icon-forms-white" role="img" />
{{ t('forms', 'Show results') }}
</button>
<button v-tooltip="t('forms', 'Toggle settings')"
:aria-label="t('forms', 'Toggle settings')"
@click="toggleSidebar">
<span class="icon-settings" role="img" />
</button>
</TopBar>
<!-- Forms title & description-->
<header>
<label class="hidden-visually" for="form-title">{{ t('forms', 'Title') }}</label>
<input
id="form-title"
v-model="form.title"
:minlength="0"
:placeholder="t('forms', 'Title')"
:required="true"
autofocus
type="text"
@click="selectIfUnchanged">
<label class="hidden-visually" for="form-desc">{{ t('forms', 'Description') }}</label>
<textarea
id="form-desc"
ref="description"
v-model="form.description"
:placeholder="t('forms', 'Description')"
@change="autoSizeDescription"
@keydown="autoSizeDescription" />
</header>
<section>
<!-- Add new questions toolbar -->
<div class="question-toolbar" role="toolbar">
<Actions ref="questionMenu"
v-tooltip="t('forms', 'Add a question to this form')"
:aria-label="t('forms', 'Add a question to this form')"
:open.sync="questionMenuOpened"
:default-icon="loadingQuestions ? 'icon-loading-small' : 'icon-add-white'">
<ActionButton v-for="(answer, type) in answerTypes"
:key="answer.label"
:disabled="loadingQuestions"
:icon="answer.icon"
class="question-toolbar__question"
@click="addQuestion(type)">
{{ answer.label }}
</ActionButton>
</Actions>
</div>
<!-- No questions -->
<EmptyContent v-if="hasQuestions">
{{ t('forms', 'This form does not have any questions') }}
<template #desc>
<button class="empty-content__button primary" @click="openQuestionMenu">
<span class="icon-add-white" />
{{ t('forms', 'Add a new one') }}
</button>
</template>
</EmptyContent>
<!-- Questions list -->
<!-- <transitionGroup
v-else
id="form-list"
name="list"
tag="ul"
class="form-table">
<QuizFormItem
v-for="(question, index) in form.questions"
:key="question.id"
:question="question"
:type="question.type"
@addOption="addOption"
@deleteOption="deleteOption"
@deleteQuestion="deleteQuestion(question, index)" />
</transitionGroup> -->
<form @submit.prevent="onSubmit">
<Draggable v-model="questions"
:animation="200"
tag="ul"
@start="dragging = true"
@end="dragging = false">
<Questions :is="answerTypes[question.type].component"
v-for="(question, index) in questions"
:key="question.id"
:model="answerTypes[question.type]"
:index="index + 1"
v-bind.sync="question"
@delete="deleteQuestion" />
</Draggable>
</form>
</section>
</AppContent>
</template>
<script>
import { emit } from '@nextcloud/event-bus'
import { generateUrl } from '@nextcloud/router'
import { showError, showSuccess } from '@nextcloud/dialogs'
import axios from '@nextcloud/axios'
import debounce from 'debounce'
import Draggable from 'vuedraggable'
import ActionButton from '@nextcloud/vue/dist/Components/ActionButton'
import Actions from '@nextcloud/vue/dist/Components/Actions'
import AppContent from '@nextcloud/vue/dist/Components/AppContent'
import answerTypes from '../models/AnswerTypes'
import EmptyContent from '../components/EmptyContent'
import Question from '../components/Questions/Question'
import QuestionLong from '../components/Questions/QuestionLong'
import QuestionShort from '../components/Questions/QuestionShort'
import QuestionMultiple from '../components/Questions/QuestionMultiple'
import QuizFormItem from '../components/quizFormItem'
import TopBar from '../components/TopBar'
import ViewsMixin from '../mixins/ViewsMixin'
window.axios = axios
export default {
name: 'Create',
components: {
ActionButton,
Actions,
AppContent,
Draggable,
EmptyContent,
Question,
QuestionLong,
QuestionShort,
QuestionMultiple,
QuizFormItem,
TopBar,
},
mixins: [ViewsMixin],
data() {
return {
questionMenuOpened: false,
answerTypes,
loadingForm: true,
loadingQuestions: false,
errorForm: false,
questions: [
{
id: 1,
type: 'short',
title: 'How old are you ?',
},
{
id: 2,
type: 'long',
title: 'Your latest best memory ?',
},
{
id: 3,
type: 'multiple',
title: 'Choose an answer ?',
options: ['Answer 1', 'Answer 2', 'Answer 3', 'Answer 4'],
},
{
id: 4,
type: 'multiple_unique',
title: 'Choose an answer ?',
options: ['Answer 1', 'Answer 2', 'Answer 3', 'Answer 4'],
},
],
dragging: false,
}
},
computed: {
title() {
if (this.form.title === '') {
return t('forms', 'Create new form')
} else {
return this.form.title
}
},
hasQuestions() {
return this.form.questions && this.form.questions.length === 0
},
},
watch: {
form: {
deep: true,
handler: function() {
this.debounceWriteForm()
},
},
},
beforeMount() {
this.fetchFullForm(this.form.id)
},
updated() {
this.autoSizeDescription()
},
methods: {
/**
* Fetch the full form data and update parent
*
* @param {number} id the unique form hash
*/
async fetchFullForm(id) {
this.loadingForm = true
console.debug('Loading form', id)
try {
const form = await axios.get(generateUrl('/apps/forms/api/v1/form/{id}', { id }))
this.$emit('update:form', form.data)
} catch (error) {
console.error(error)
this.errorForm = true
} finally {
this.loadingForm = false
}
},
onSubmit() {
this.saveForm()
},
/**
* Add a new question to the current form
*
* @param {string} type the question type, see AnswerTypes
*/
async addQuestion(type) {
const text = t('forms', 'New question')
this.loadingQuestions = true
try {
const response = await axios.post(generateUrl('/apps/forms/api/v1/question'), {
formId: this.form.id,
type,
text,
})
const question = response.data
// Add newly created question
this.form.questions.push(Object.assign({
text,
type,
answers: [],
}, question))
} catch (error) {
console.error(error)
showError(t('forms', 'There was an error while adding the new question'))
} finally {
this.loadingQuestions = false
}
},
async deleteQuestion(question, index) {
await axios.delete(generateUrl('/apps/forms/api/v1/question/{id}', { id: question.id }))
// TODO catch Error
this.form.questions.splice(index, 1)
},
async addOption(item, question) {
const response = await axios.post(generateUrl('/apps/forms/api/v1/option/'), { formId: this.form.id, questionId: question.id, text: item.newOption })
const optionId = response.data
question.options.push({
id: optionId,
text: item.newOption,
})
},
async deleteOption(question, option, index) {
await axios.delete(generateUrl('/apps/forms/api/v1/option/{id}', { id: option.id }))
// TODO catch errors
question.options.splice(index, 1)
},
autoSizeDescription() {
const textarea = this.$refs.description
if (textarea) {
textarea.style.cssText = 'height:auto; padding:0'
textarea.style.cssText = `height: ${textarea.scrollHeight + 20}px`
}
},
debounceSaveForm: debounce(function() {
this.saveForm()
}, 200),
async saveForm() {
try {
await axios.post(OC.generateUrl('apps/forms/write/form'), this.form)
showSuccess(t('forms', '%n successfully saved', 1, this.form.title), { duration: 3000 })
} catch (error) {
showError(t('forms', 'Error on saving form, see console'))
console.error(error)
}
},
/**
* Topbar methods
*/
showResults() {
this.$router.push({
name: 'results',
params: {
hash: this.form.event.hash,
},
})
},
toggleSidebar() {
emit('toggleSidebar')
},
/**
* 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
}, 100)
},
/**
* Select the text in the input if it is still set to 'New form'
* @param {Event} e the click event
*/
selectIfUnchanged(e) {
if (e.target && e.target.value === t('forms', 'New form')) {
e.target.select()
}
},
},
}
</script>
<style lang="scss">
.app-content {
display: flex;
align-items: center;
flex-direction: column;
header,
section {
width: 100%;
max-width: 900px;
}
// Title & description header
header {
display: flex;
flex-direction: column;
margin: 44px;
#form-title,
#form-desc {
width: 100%;
margin: 10px; // aerate the header
padding: 0; // makes alignment and desc height calc easier
border: none;
}
#form-title {
font-size: 2em;
}
#form-desc {
// make sure height calculations are correct
box-sizing: content-box !important;
min-height: 60px;
max-height: 200px;
padding-left: 2px; // align with title (compensate font size diff)
resize: none;
}
}
.empty-content__button {
margin: 5px;
> span {
margin-right: 5px;
cursor: pointer;
opacity: 1;
}
}
// Questions container
section {
position: relative;
display: flex;
flex-direction: column;
margin-bottom: 250px;
.question-toolbar {
position: sticky;
z-index: 50;
top: var(--header-height);
display: flex;
align-items: center;
align-self: flex-end;
width: 44px;
height: var(--top-bar-height);
// make sure this doesn't take any space and appear floating
margin-top: -44px;
.icon-add-white {
opacity: 1;
border-radius: 50%;
// TODO: standardize on components
background-color: var(--color-primary-element);
&:hover,
&:focus,
&:active {
background-color: var(--color-primary-element-light) !important;
}
}
}
}
}
/* Transitions for inserting and removing list items */
.list-enter-active,
.list-leave-active {
transition: all .5s ease;
}
.list-enter,
.list-leave-to {
opacity: 0;
}
.list-move {
transition: transform .5s;
}
#form-item-selector-text {
> input {
width: 100%;
}
}
.form-table {
> li {
display: flex;
overflow: hidden;
align-items: baseline;
min-height: 24px;
padding-right: 8px;
padding-left: 8px;
white-space: nowrap;
border-bottom: 1px solid var(--color-border);
line-height: 24px;
&:active,
&:hover {
transition: var(--background-dark) .3s ease;
background-color: var(--color-background-dark); //$hover-color;
}
> div {
display: flex;
flex-grow: 1;
padding-right: 4px;
white-space: normal;
opacity: .7;
font-size: 1.2em;
&.avatar {
flex-grow: 0;
}
}
> div:nth-last-child(1) {
flex-grow: 0;
flex-shrink: 0;
justify-content: center;
}
}
}
button {
&.button-inline {
border: 0;
background-color: transparent;
}
}
.tab {
display: flex;
flex-wrap: wrap;
}
.selectUnit {
display: flex;
align-items: center;
flex-wrap: nowrap;
> label {
padding-right: 4px;
}
}
#shiftDates {
min-width: 16px;
min-height: 16px;
margin: 0;
padding: 10px;
padding-left: 34px;
text-align: left;
background-repeat: no-repeat;
background-position: 10px center;
}
</style>