Add simplified Form component to Create vue

This commit is contained in:
Bubka 2020-01-20 17:16:08 +01:00
parent a0d6c9ace7
commit 540a4368f1
5 changed files with 459 additions and 26 deletions

View File

@ -0,0 +1,21 @@
<template>
<p class="help is-danger" v-if="form.errors.has(field)" v-html="form.errors.get(field)" />
</template>
<script>
export default {
name: 'field-error',
props: {
form: {
type: Object,
required: true
},
field: {
type: String,
required: true
}
}
}
</script>

272
resources/js/components/Form.js vendored Normal file
View File

@ -0,0 +1,272 @@
import Errors from './FormErrors'
// import { deepCopy } from './util'
class Form {
/**
* Create a new form instance.
*
* @param {Object} data
*/
constructor (data = {}) {
this.isBusy = false
// this.successful = false
this.errors = new Errors()
// this.originalData = deepCopy(data)
Object.assign(this, data)
}
/**
* Fill form data.
*
* @param {Object} data
*/
fill (data) {
this.keys().forEach(key => {
this[key] = data[key]
})
}
/**
* Get the form data.
*
* @return {Object}
*/
data () {
return this.keys().reduce((data, key) => (
{ ...data, [key]: this[key] }
), {})
}
/**
* Get the form data keys.
*
* @return {Array}
*/
keys () {
return Object.keys(this)
.filter(key => !Form.ignore.includes(key))
}
/**
* Start processing the form.
*/
startProcessing () {
this.errors.clear()
this.isBusy = true
// this.successful = false
}
/**
* Finish processing the form.
*/
finishProcessing () {
this.isBusy = false
// this.successful = true
}
/**
* Clear the form errors.
*/
clear () {
this.errors.clear()
// this.successful = false
}
/**
* Reset the form fields.
*/
// reset () {
// Object.keys(this)
// .filter(key => !Form.ignore.includes(key))
// .forEach(key => {
// this[key] = deepCopy(this.originalData[key])
// })
// }
/**
* Submit the form via a GET request.
*
* @param {String} url
* @param {Object} config (axios config)
* @return {Promise}
*/
get (url, config = {}) {
return this.submit('get', url, config)
}
/**
* Submit the form via a POST request.
*
* @param {String} url
* @param {Object} config (axios config)
* @return {Promise}
*/
post (url, config = {}) {
return this.submit('post', url, config)
}
/**
* Submit the form via a PATCH request.
*
* @param {String} url
* @param {Object} config (axios config)
* @return {Promise}
*/
patch (url, config = {}) {
return this.submit('patch', url, config)
}
/**
* Submit the form via a PUT request.
*
* @param {String} url
* @param {Object} config (axios config)
* @return {Promise}
*/
put (url, config = {}) {
return this.submit('put', url, config)
}
/**
* Submit the form via a DELETE request.
*
* @param {String} url
* @param {Object} config (axios config)
* @return {Promise}
*/
delete (url, config = {}) {
return this.submit('delete', url, config)
}
/**
* Submit the form data via an HTTP request.
*
* @param {String} method (get, post, patch, put)
* @param {String} url
* @param {Object} config (axios config)
* @return {Promise}
*/
submit (method, url, config = {}) {
this.startProcessing()
const data = method === 'get'
? { params: this.data() }
: this.data()
return new Promise((resolve, reject) => {
// (Form.axios || axios).request({ url: this.route(url), method, data, ...config })
axios.request({ url: this.route(url), method, data, ...config })
.then(response => {
this.finishProcessing()
resolve(response)
})
.catch(error => {
this.isBusy = false
if (error.response) {
this.errors.set(this.extractErrors(error.response))
}
reject(error)
})
})
}
/**
* Submit the form data via an HTTP request.
*
* @param {String} method (get, post, patch, put)
* @param {String} url
* @param {Object} config (axios config)
* @return {Promise}
*/
upload (url, formData, config = {}) {
this.startProcessing()
return new Promise((resolve, reject) => {
// (Form.axios || axios).request({ url: this.route(url), method, data, ...config })
axios.request({ url: this.route(url), method: 'post', data: formData, header: {'Content-Type' : 'multipart/form-data'} })
.then(response => {
this.finishProcessing()
resolve(response)
})
.catch(error => {
this.isBusy = false
if (error.response) {
this.errors.set(this.extractErrors(error.response))
}
reject(error)
})
})
}
/**
* Extract the errors from the response object.
*
* @param {Object} response
* @return {Object}
*/
extractErrors (response) {
if (!response.data || typeof response.data !== 'object') {
return { error: Form.errorMessage }
}
if (response.data.errors) {
return { ...response.data.errors }
}
if (response.data.message) {
return { error: response.data.message }
}
return { ...response.data }
}
/**
* Get a named route.
*
* @param {String} name
* @return {Object} parameters
* @return {String}
*/
route (name, parameters = {}) {
let url = name
if (Form.routes.hasOwnProperty(name)) {
url = decodeURI(Form.routes[name])
}
if (typeof parameters !== 'object') {
parameters = { id: parameters }
}
Object.keys(parameters).forEach(key => {
url = url.replace(`{${key}}`, parameters[key])
})
return url
}
/**
* Clear errors on keydown.
*
* @param {KeyboardEvent} event
*/
onKeydown (event) {
if (event.target.name) {
this.errors.clear(event.target.name)
}
}
}
Form.routes = {}
Form.errorMessage = 'Something went wrong. Please try again.'
Form.ignore = ['isBusy', /*'successful', 'errors',*/ 'originalData']
export default Form

141
resources/js/components/FormErrors.js vendored Normal file
View File

@ -0,0 +1,141 @@
export default class Errors {
/**
* Create a new error bag instance.
*/
constructor () {
this.errors = {}
}
/**
* Set the errors object or field error messages.
*
* @param {Object|String} field
* @param {Array|String|undefined} messages
*/
set (field, messages) {
if (typeof field === 'object') {
this.errors = field
} else {
this.set({ ...this.errors, [field]: arrayWrap(messages) })
}
}
/**
* Get all the errors.
*
* @return {Object}
*/
all () {
return this.errors
}
/**
* Determine if there is an error for the given field.
*
* @param {String} field
* @return {Boolean}
*/
has (field) {
return this.errors.hasOwnProperty(field)
}
/**
* Determine if there are any errors for the given fields.
*
* @param {...String} fields
* @return {Boolean}
*/
hasAny (...fields) {
return fields.some(field => this.has(field))
}
/**
* Determine if there are any errors.
*
* @return {Boolean}
*/
any () {
return Object.keys(this.errors).length > 0
}
/**
* Get the first error message for the given field.
*
* @param String} field
* @return {String|undefined}
*/
get (field) {
if (this.has(field)) {
return this.getAll(field)[0]
}
}
/**
* Get all the error messages for the given field.
*
* @param {String} field
* @return {Array}
*/
getAll (field) {
return arrayWrap(this.errors[field] || [])
}
/**
* Get the error message for the given fields.
*
* @param {...String} fields
* @return {Array}
*/
only (...fields) {
const messages = []
fields.forEach(field => {
const message = this.get(field)
if (message) {
messages.push(message)
}
})
return messages
}
/**
* Get all the errors in a flat array.
*
* @return {Array}
*/
flatten () {
return Object.values(this.errors).reduce((a, b) => a.concat(b), [])
}
/**
* Clear one or all error fields.
*
* @param {String|undefined} field
*/
clear (field) {
const errors = {}
if (field) {
Object.keys(this.errors).forEach(key => {
if (key !== field) {
errors[key] = this.errors[key]
}
})
}
this.set(errors)
}
}
/**
* If the given value is not an array, wrap it in one.
*
* @param {Any} value
* @return {Array}
*/
function arrayWrap (value) {
return Array.isArray(value) ? value : [value]
}

View File

@ -1,9 +1,11 @@
import Vue from 'vue'
import Button from './Button'
import FieldError from './FieldError'
// Components that are registered globaly.
[
Button,
FieldError,
].forEach(Component => {
Vue.component(Component.name, Component)
})

View File

@ -3,7 +3,7 @@
<div class="columns is-mobile is-centered">
<div class="column is-two-thirds-tablet is-half-desktop is-one-third-widescreen is-one-quarter-fullhd">
<h1 class="title">{{ $t('twofaccounts.forms.new_account') }}</h1>
<form @submit.prevent="createAccount">
<form @submit.prevent="createAccount" @keydown="form.onKeydown($event)">
<div class="field">
<div class="file is-dark is-boxed">
<label class="file-label" :title="$t('twofaccounts.forms.use_qrcode.title')">
@ -17,20 +17,20 @@
</label>
</div>
</div>
<p class="help is-danger help-for-file" v-if="validationErrors.qrcode">{{ validationErrors.qrcode.toString() }}</p>
<field-error :form="form" field="qrcode" class="help-for-file" />
<div class="field">
<label class="label">{{ $t('twofaccounts.service') }}</label>
<div class="control">
<input class="input" type="text" :placeholder="$t('twofaccounts.forms.service.placeholder')" v-model="twofaccount.service" autofocus />
</div>
<p class="help is-danger" v-if="validationErrors.service">{{ validationErrors.service.toString() }}</p>
<field-error :form="form" field="service" />
</div>
<div class="field">
<label class="label">{{ $t('twofaccounts.account') }}</label>
<div class="control">
<input class="input" type="text" :placeholder="$t('twofaccounts.forms.account.placeholder')" v-model="twofaccount.account" />
</div>
<p class="help is-danger" v-if="validationErrors.account">{{ validationErrors.account.toString() }}</p>
<field-error :form="form" field="account" />
</div>
<div class="field" style="margin-bottom: 0.5rem;">
<label class="label">{{ $t('twofaccounts.forms.totp_uri') }}</label>
@ -54,7 +54,7 @@
</a>
</div>
</div>
<p class="help is-danger help-for-file" v-if="validationErrors.uri">{{ validationErrors.uri.toString() }}</p>
<field-error :form="form" field="uri" class="help-for-file" />
<div class="field">
<label class="label">{{ $t('twofaccounts.icon') }}</label>
<div class="file is-dark">
@ -73,10 +73,10 @@
</span>
</div>
</div>
<p class="help is-danger help-for-file" v-if="validationErrors.icon">{{ validationErrors.icon.toString() }}</p>
<field-error :form="form" field="icon" class="help-for-file" />
<div class="field is-grouped">
<div class="control">
<button type="submit" class="button is-link">{{ $t('twofaccounts.forms.create') }}</button>
<button type="submit" class="button is-link" :disabled="form.busy" >{{ $t('twofaccounts.forms.create') }}</button>
</div>
<div class="control">
<button class="button is-text" @click="cancelCreation">{{ $t('commons.cancel') }}</button>
@ -89,6 +89,9 @@
</template>
<script>
import Form from './../../components/Form'
export default {
data() {
return {
@ -100,7 +103,14 @@
},
uriIsLocked: true,
tempIcon: '',
validationErrors: {}
validationErrors: {},
form: new Form({
service: '',
account: '',
uri: '',
icon: '',
qrcode: null
})
}
},
@ -110,7 +120,7 @@
// set current temp icon as account icon
this.twofaccount.icon = this.tempIcon
axios.post('/api/twofaccounts', this.twofaccount)
this.form.post('/api/twofaccounts', this.twofaccount)
.then(response => {
this.$router.push({name: 'accounts', params: { InitialEditMode: false }});
})
@ -140,13 +150,7 @@
imgdata.append('qrcode', this.$refs.qrcodeInput.files[0]);
let config = {
header : {
'Content-Type' : 'multipart/form-data',
}
}
axios.post('/api/qrcode/decode', imgdata, config)
this.form.upload('/api/qrcode/decode', imgdata)
.then(response => {
this.twofaccount = response.data;
this.validationErrors['qrcode'] = '';
@ -173,13 +177,7 @@
imgdata.append('icon', this.$refs.iconInput.files[0]);
let config = {
header : {
'Content-Type' : 'multipart/form-data',
}
}
axios.post('/api/icon/upload', imgdata, config)
this.form.upload('/api/icon/upload', imgdata)
.then(response => {
this.tempIcon = response.data;
this.validationErrors['icon'] = '';
@ -196,7 +194,6 @@
},
deleteIcon(event) {
if(this.tempIcon) {
axios.delete('/api/icon/delete/' + this.tempIcon)
this.tempIcon = ''