Merge pull request #434 from YunoHost/enh-configpanels-component

Enh config panels integration
This commit is contained in:
Alexandre Aubin 2022-02-01 13:34:05 +01:00 committed by GitHub
commit 403d8a75ed
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 229 additions and 280 deletions

View file

@ -0,0 +1,75 @@
<template>
<b-card no-body>
<b-tabs fill pills card>
<slot name="before" />
<tab-form
v-for="{ name, id, sections, help, serverError } in panels" :key="id"
v-bind="{ name, id: id + '-form', validation: $v.forms[id], serverError }"
@submit.prevent.stop="$emit('submit', id)"
>
<template v-if="help" #disclaimer>
<div class="alert alert-info" v-html="help" />
</template>
<slot :name="id + '-tab-before'" />
<template v-for="section in sections">
<div v-if="isVisible(section.visible, section)" :key="section.id" class="mb-5">
<b-card-title v-if="section.name" title-tag="h3">
{{ section.name }} <small v-if="section.help">{{ section.help }}</small>
</b-card-title>
<template v-for="(field, fname) in section.fields">
<form-field
v-if="isVisible(field.visible, field)" :key="fname"
v-model="forms[id][fname]" v-bind="field" :validation="$v.forms[id][fname]"
/>
</template>
</div>
</template>
<slot :name="id + '-tab-after'" />
</tab-form>
<slot name="default" />
</b-tabs>
</b-card>
</template>
<script>
import { validationMixin } from 'vuelidate'
import { configPanelsFieldIsVisible } from '@/helpers/yunohostArguments'
export default {
name: 'ConfigPanels',
mixins: [validationMixin],
props: {
panels: { type: Array, default: undefined },
forms: { type: Object, default: undefined },
validations: { type: Object, default: undefined }
},
validations () {
const v = this.validations
return v ? { forms: v } : null
},
methods: {
isVisible (expression, field) {
return configPanelsFieldIsVisible(expression, field, this.forms)
}
}
}
</script>
<style lang="scss" scoped>
.card-title {
margin-bottom: 1em;
border-bottom: solid 1px #aaa;
}
</style>

View file

@ -41,7 +41,7 @@ export default {
data () { data () {
return { return {
fallback_loading: this.loading === null && this.fetch !== null ? true : null fallback_loading: this.loading === null && this.queries !== null ? true : null
} }
}, },
@ -57,7 +57,7 @@ export default {
}, },
methods: { methods: {
fetchQueries (triggerLoading = false) { fetchQueries ({ triggerLoading = false } = {}) {
if (triggerLoading) { if (triggerLoading) {
this.fallback_loading = true this.fallback_loading = true
} }

View file

@ -1,5 +1,6 @@
import i18n from '@/i18n' import i18n from '@/i18n'
import store from '@/store' import store from '@/store'
import evaluate from 'simple-evaluate'
import * as validators from '@/helpers/validators' import * as validators from '@/helpers/validators'
import { isObjectLiteral, isEmptyValue, flattenObjectLiteral } from '@/helpers/commons' import { isObjectLiteral, isEmptyValue, flattenObjectLiteral } from '@/helpers/commons'
@ -72,7 +73,7 @@ export function formatYunoHostArgument (arg) {
name: 'InputItem', name: 'InputItem',
props: defaultProps.concat(['autocomplete', 'trim', 'choices']), props: defaultProps.concat(['autocomplete', 'trim', 'choices']),
callback: function () { callback: function () {
if (arg.choices) { if (arg.choices && arg.choices.length) {
arg.type = 'select' arg.type = 'select'
this.name = 'SelectItem' this.name = 'SelectItem'
} }
@ -284,6 +285,83 @@ export function formatYunoHostArguments (args, name = null) {
return { form, fields, validations, errors } return { form, fields, validations, errors }
} }
export function formatYunoHostConfigPanels (data) {
const result = {
panels: [],
forms: {},
validations: {},
errors: {}
}
for (const { id: panelId, name, help, sections } of data.panels) {
const panel = { id: panelId, sections: [] }
result.forms[panelId] = {}
result.validations[panelId] = {}
result.errors[panelId] = {}
if (name) panel.name = formatI18nField(name)
if (help) panel.help = formatI18nField(help)
for (const { id: sectionId, name, help, visible, options } of sections) {
const section = { id: sectionId, visible, isVisible: false }
if (help) section.help = formatI18nField(help)
if (name) section.name = formatI18nField(name)
const { form, fields, validations, errors } = formatYunoHostArguments(options)
// Merge all sections forms to the panel to get a unique form
Object.assign(result.forms[panelId], form)
Object.assign(result.validations[panelId], validations)
Object.assign(result.errors[panelId], errors)
section.fields = fields
panel.sections.push(section)
}
result.panels.push(panel)
}
return result
}
export function configPanelsFieldIsVisible (expression, field, forms) {
if (!expression || !field) return true
const context = {}
const promises = []
for (const args of Object.values(forms)) {
for (const shortname in args) {
if (args[shortname] instanceof File) {
if (expression.includes(shortname)) {
promises.push(pFileReader(args[shortname], context, shortname, false))
}
} else {
context[shortname] = args[shortname]
}
}
}
// Allow to use match(var,regexp) function
const matchRe = new RegExp('match\\(\\s*(\\w+)\\s*,\\s*"([^"]+)"\\s*\\)', 'g')
let i = 0
Promise.all(promises).then(() => {
for (const matched of expression.matchAll(matchRe)) {
i++
const varName = matched[1] + '__re' + i.toString()
context[varName] = new RegExp(matched[2], 'm').test(context[matched[1]])
expression = expression.replace(matched[0], varName)
}
try {
field.isVisible = evaluate(context, expression)
} catch {
field.isVisible = false
}
})
return field.isVisible
}
export function pFileReader (file, output, key, base64 = true) { export function pFileReader (file, output, key, base64 = true) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fr = new FileReader() const fr = new FileReader()
@ -303,6 +381,8 @@ export function pFileReader (file, output, key, base64 = true) {
} }
}) })
} }
/** /**
* Format helper for a form value. * Format helper for a form value.
* Convert Boolean to (1|0) and concatenate adresses. * Convert Boolean to (1|0) and concatenate adresses.

View file

@ -1,53 +1,31 @@
<template> <template>
<view-base :queries="queries" @queries-response="onQueriesResponse" skeleton="card-form-skeleton"> <view-base
<b-card v-if="panels" no-body> :queries="queries" @queries-response="onQueriesResponse"
<b-tabs fill pills card> ref="view" skeleton="card-form-skeleton"
<tab-form >
v-for="{ name, id: id_, sections, help, serverError } in panels" :key="id_" <config-panels v-if="config.panels" v-bind="config" @submit="applyConfig" />
v-bind="{ name, id: id_ + '-form', validation: $v.forms[id_], serverError }"
@submit.prevent="applyConfig(id_)"
>
<template v-if="help" #disclaimer>
<div class="alert alert-info" v-html="help" />
</template>
<template v-for="section in sections"> <b-alert v-else-if="config.panels === null" variant="warning">
<div v-if="isVisible(section.visible, section)" :key="section.id" class="mb-5">
<b-card-title v-if="section.name" title-tag="h3">
{{ section.name }} <small v-if="section.help">{{ section.help }}</small>
</b-card-title>
<template v-for="(field, fname) in section.fields">
<form-field
v-if="isVisible(field.visible, field)" :key="fname"
v-model="forms[id_][fname]" v-bind="field" :validation="$v.forms[id_][fname]"
/>
</template>
</div>
</template>
</tab-form>
</b-tabs>
</b-card>
<!-- if no config panel -->
<b-alert v-else-if="panels === null" variant="warning">
<icon iname="exclamation-triangle" /> {{ $t('app_config_panel_no_panel') }} <icon iname="exclamation-triangle" /> {{ $t('app_config_panel_no_panel') }}
</b-alert> </b-alert>
</view-base> </view-base>
</template> </template>
<script> <script>
import { validationMixin } from 'vuelidate'
import evaluate from 'simple-evaluate'
// FIXME needs test and rework
import api, { objectToParams } from '@/api' import api, { objectToParams } from '@/api'
import { formatI18nField, formatYunoHostArguments, formatFormData, pFileReader } from '@/helpers/yunohostArguments' import {
formatFormData,
formatYunoHostConfigPanels
} from '@/helpers/yunohostArguments'
import ConfigPanels from '@/components/ConfigPanels'
export default { export default {
name: 'AppConfigPanel', name: 'AppConfigPanel',
mixins: [validationMixin], components: {
ConfigPanels
},
props: { props: {
id: { type: String, required: true } id: { type: String, required: true }
@ -56,129 +34,41 @@ export default {
data () { data () {
return { return {
queries: [ queries: [
['GET', `apps/${this.id}/config-panel?full`], ['GET', `apps/${this.id}/config-panel?full`]
['GET', { uri: 'domains' }],
['GET', { uri: 'domains/main', storeKey: 'main_domain' }],
['GET', { uri: 'users' }]
], ],
panels: undefined, config: {}
forms: undefined,
errors: undefined,
validations: null
} }
}, },
validations () {
return this.validations
},
methods: { methods: {
isVisible (expression, field) { onQueriesResponse (config) {
if (!expression || !field) return true if (!config.panels || config.panels.length === 0) {
const context = {} this.config = null
} else {
const promises = [] this.config = formatYunoHostConfigPanels(config)
for (const args of Object.values(this.forms)) {
for (const shortname in args) {
if (args[shortname] instanceof File) {
if (expression.includes(shortname)) {
promises.push(pFileReader(args[shortname], context, shortname, false))
}
} else {
context[shortname] = args[shortname]
}
}
} }
// Allow to use match(var,regexp) function
const matchRe = new RegExp('match\\(\\s*(\\w+)\\s*,\\s*"([^"]+)"\\s*\\)', 'g')
let i = 0
Promise.all(promises).then((value) => {
for (const matched of expression.matchAll(matchRe)) {
i++
const varName = matched[1] + '__re' + i.toString()
context[varName] = new RegExp(matched[2], 'm').test(context[matched[1]])
expression = expression.replace(matched[0], varName)
}
try {
field.isVisible = evaluate(context, expression)
} catch (error) {
field.isVisible = false
}
})
// This value should be updated magically when vuejs will detect isVisible changed
return field.isVisible
}, },
onQueriesResponse (data) { async applyConfig (id_) {
if (!data.panels || data.panels.length === 0) { const formatedData = await formatFormData(
this.panels = null this.config.forms[id_],
return { removeEmpty: false, removeNull: true, multipart: false }
} )
const forms = {} api.put(
const validations_ = {} `apps/${this.id}/config`,
const errors_ = {} { key: id_, args: objectToParams(formatedData) },
const panels_ = [] { key: 'apps.update_config', name: this.id }
for (const { id, name, help, sections } of data.panels) { ).then(response => {
const panel_ = { id, sections: [] } this.$refs.view.fetchQueries({ triggerLoading: true })
if (name) panel_.name = formatI18nField(name) }).catch(err => {
if (help) panel_.help = formatI18nField(help) if (err.name !== 'APIBadRequestError') throw err
forms[id] = {} const panel = this.config.panels.find(({ id }) => id_ === id)
validations_[id] = {} if (err.data.name) {
errors_[id] = {} this.config.errors[id_][err.data.name].message = err.message
for (const { id_, name, help, visible, options } of sections) { } else this.$set(panel, 'serverError', err.message)
const section_ = { id: id_, isVisible: true, visible }
if (help) section_.help = formatI18nField(help)
if (name) section_.name = formatI18nField(name)
const { form, fields, validations, errors } = formatYunoHostArguments(options)
Object.assign(forms[id], form)
Object.assign(validations_[id], validations)
Object.assign(errors_[id], errors)
section_.fields = fields
panel_.sections.push(section_)
}
panels_.push(panel_)
}
this.forms = forms
this.validations = { forms: validations_ }
this.panels = panels_
this.errors = errors_
},
applyConfig (id_) {
formatFormData(this.forms[id_], { removeEmpty: false, removeNull: true, multipart: false }).then((formatedData) => {
const args = objectToParams(formatedData)
api.put(
`apps/${this.id}/config`, { key: id_, args }, { key: 'apps.update_config', name: this.id }
).then(response => {
api.get(
`apps/${this.id}/config-panel?full`, {}, { key: 'apps.get_config', name: this.id }
).then(response => {
this.onQueriesResponse(response)
}).catch(err => {
if (err.name !== 'APIBadRequestError') throw err
const panel = this.panels.find(({ id }) => id_ === id)
this.$set(panel, 'serverError', err.message)
})
}).catch(err => {
if (err.name !== 'APIBadRequestError') throw err
const panel = this.panels.find(({ id }) => id_ === id)
if (err.data.name) {
this.errors[id_][err.data.name].message = err.message
} else this.$set(panel, 'serverError', err.message)
})
}) })
} }
} }
} }
</script> </script>
<style lang="scss" scoped>
h3 {
margin-bottom: 1em;
border-bottom: solid 1px #aaa;
}
</style>

View file

@ -1,55 +1,27 @@
<template> <template>
<view-base :queries="queries" @queries-response="onQueriesResponse" skeleton="card-info-skeleton"> <view-base
<b-tabs pills card vertical> :queries="queries" @queries-response="onQueriesResponse"
<b-tab v-for="{ name, id: id_, sections, help, serverError } in panels" ref="view" skeleton="card-form-skeleton"
:key="id_" >
:title="name" <config-panels v-if="config.panels" v-bind="config" @submit="applyConfig" />
>
<template #title>
<icon iname="wrench" /> {{ name }}
</template>
<card-form
:key="id_"
:title="name" icon="wrench" title-tag="h2"
:validation="$v.forms[id_]" :id="id_ + '-form'" :server-error="serverError"
@submit.prevent="applyConfig(id_)"
>
<template v-if="help" #disclaimer>
<div class="alert alert-info" v-html="help" />
</template>
<template v-for="section in sections">
<div :key="section.id" class="mb-5" v-if="isVisible(section.visible, section)">
<b-card-title v-if="section.name" title-tag="h3">
{{ section.name }} <small v-if="section.help">{{ section.help }}</small>
</b-card-title>
<template v-for="(field, fname) in section.fields">
<form-field :key="fname" v-model="forms[id_][fname]"
:validation="$v.forms[id_][fname]"
v-if="isVisible(field.visible, field)" v-bind="field"
/>
</template>
</div>
</template>
</card-form>
</b-tab>
</b-tabs>
</view-base> </view-base>
</template> </template>
<script> <script>
import { validationMixin } from 'vuelidate'
import evaluate from 'simple-evaluate'
import api, { objectToParams } from '@/api' import api, { objectToParams } from '@/api'
import {
import { formatI18nField, formatYunoHostArguments, formatFormData, pFileReader } from '@/helpers/yunohostArguments' formatFormData,
formatYunoHostConfigPanels
} from '@/helpers/yunohostArguments'
import ConfigPanels from '@/components/ConfigPanels'
export default { export default {
name: 'DomainConfig', name: 'DomainConfig',
mixins: [validationMixin], components: {
ConfigPanels
},
props: { props: {
name: { type: String, required: true } name: { type: String, required: true }
@ -60,101 +32,33 @@ export default {
queries: [ queries: [
['GET', `domains/${this.name}/config?full`] ['GET', `domains/${this.name}/config?full`]
], ],
panels: undefined, config: {}
forms: undefined,
errors: undefined,
validations: null
} }
}, },
validations () {
return this.validations
},
methods: { methods: {
onQueriesResponse (config) { onQueriesResponse (config) {
const forms = {} this.config = formatYunoHostConfigPanels(config)
const validations_ = {}
const errors_ = {}
const panels_ = []
for (const { id, name, help, sections } of config.panels) {
const panel_ = { id, sections: [] }
if (name) panel_.name = formatI18nField(name)
if (help) panel_.help = formatI18nField(help)
forms[id] = {}
validations_[id] = {}
errors_[id] = {}
for (const { id_, name, help, visible, options } of sections) {
const section_ = { id: id_, isVisible: true, visible }
if (help) section_.help = formatI18nField(help)
if (name) section_.name = formatI18nField(name)
const { form, fields, validations, errors } = formatYunoHostArguments(options)
Object.assign(forms[id], form)
Object.assign(validations_[id], validations)
Object.assign(errors_[id], errors)
section_.fields = fields
panel_.sections.push(section_)
}
panels_.push(panel_)
}
this.forms = forms
this.validations = { forms: validations_ }
this.panels = panels_
this.errors = errors_
}, },
isVisible (expression, field) { async applyConfig (id_) {
if (!expression || !field) return true const formatedData = await formatFormData(
const context = {} this.config.forms[id_],
{ removeEmpty: false, removeNull: true, multipart: false }
)
const promises = [] api.put(
for (const args of Object.values(this.forms)) { `domains/${this.name}/config`,
for (const shortname in args) { { key: id_, args: objectToParams(formatedData) },
if (args[shortname] instanceof File) { { key: 'domains.update_config', name: this.name }
if (expression.includes(shortname)) { ).then(() => {
promises.push(pFileReader(args[shortname], context, shortname, false)) this.$refs.view.fetchQueries({ triggerLoading: true })
} }).catch(err => {
} else { if (err.name !== 'APIBadRequestError') throw err
context[shortname] = args[shortname] const panel = this.config.panels.find(({ id }) => id_ === id)
} if (err.data.name) {
} this.config.errors[id_][err.data.name].message = err.message
} } else this.$set(panel, 'serverError', err.message)
// Allow to use match(var,regexp) function
const matchRe = new RegExp('match\\(\\s*(\\w+)\\s*,\\s*"([^"]+)"\\s*\\)', 'g')
let i = 0
Promise.all(promises).then((value) => {
for (const matched of expression.matchAll(matchRe)) {
i++
const varName = matched[1] + '__re' + i.toString()
context[varName] = new RegExp(matched[2], 'm').test(context[matched[1]])
expression = expression.replace(matched[0], varName)
}
try {
field.isVisible = evaluate(context, expression)
} catch (error) {
field.isVisible = false
}
})
// This value should be updated magically when vuejs will detect isVisible changed
return field.isVisible
},
applyConfig (id_) {
formatFormData(this.forms[id_], { removeEmpty: false, removeNull: true, multipart: false }).then((formatedData) => {
const args = objectToParams(formatedData)
api.put(
`domains/${this.name}/config`, { key: id_, args }, { key: 'domains.update_config', name: this.name }
).then(response => {
}).catch(err => {
if (err.name !== 'APIBadRequestError') throw err
const panel = this.panels.find(({ id }) => id_ === id)
if (err.data.name) {
this.errors[id_][err.data.name].message = err.message
} else this.$set(panel, 'serverError', err.message)
})
}) })
} }
} }