Files
baserow/web-frontend/modules/builder/components/dataSource/DataSourceForm.vue

459 lines
15 KiB
Vue

<template>
<div class="data-source-form">
<div class="data-source-form__header">
<div class="data-source-form__header-form">
<FormGroup
:label="$t('dataSourceForm.actionLabel')"
small-label
required
:error-message="getFirstErrorMessage('type')"
>
<GroupedDropdown
v-model="computedType"
class="data-source-form__type-dropdown"
:items="serviceTypeOptions"
:placeholder="$t('dataSourceForm.servicePlaceholder')"
:search-placeholder="$t('dataSourceForm.searchActionPlaceholder')"
:empty-text="$t('dataSourceForm.noActionsFound')"
panel-height="240px"
@disabled-click="onServiceTypeDisabledClick"
/>
<component
:is="deactivatedClickModal[0]"
v-if="deactivatedClickModal !== null"
ref="deactivatedClickModal"
v-bind="deactivatedClickModal[1]"
:name="deactivatedServiceTypeName"
:workspace="builder.workspace"
/>
</FormGroup>
<FormGroup
v-if="!serviceType || serviceType.integrationType"
:label="
integrationIsOptional
? $t('dataSourceForm.authenticationLabel')
: $t('dataSourceForm.integrationLabel')
"
small-label
:required="!integrationIsOptional"
:error-message="getFirstErrorMessage('integration_id')"
>
<IntegrationDropdown
v-model="v$.values.integration_id.$model"
class="data-source-form__integration-dropdown"
:application="builder"
:integrations="availableIntegrations"
:disabled="!v$.values.type.$model"
:integration-type="serviceType?.integrationType"
:none-label="
integrationIsOptional
? $t('dataSourceForm.noAuthentication')
: null
"
:placeholder="
integrationIsOptional
? $t('dataSourceForm.noAuthentication')
: $t('dataSourceForm.integrationPlaceholder')
"
/>
</FormGroup>
<FormGroup
:label="$t('dataSourceForm.nameLabel')"
small-label
required
:error-message="getFirstErrorMessage('name')"
>
<FormInput
v-model="v$.values.name.$model"
class="data-source-form__name-input"
:placeholder="$t('dataSourceForm.namePlaceholder')"
@blur="v$.values.name.$touch()"
/>
</FormGroup>
</div>
</div>
<template v-if="!create && (integration || hasNoIntegration)">
<component
:is="serviceType.formComponent"
ref="subForm"
:application="builder"
:service="dataSource"
:service-type="serviceType"
:default-values="defaultValues"
:context-data="integration?.context_data"
:databases="integration?.context_data?.databases || []"
@values-changed="emitChange($event)"
/>
<DataSourceTestForm
v-if="serviceType.canBeTested"
:data-source="dataSource"
:page="page"
:show-button="!serviceType.hasOwnTestButton"
/>
</template>
</div>
</template>
<script>
import { getDefaultIntegration } from '@baserow/modules/core/utils/integration'
import _ from 'lodash'
import { computed, getCurrentInstance } from 'vue'
import { useVuelidate } from '@vuelidate/core'
import { useDataSourceTest } from '@baserow/modules/builder/composables/useDataSourceTest'
import IntegrationDropdown from '@baserow/modules/core/components/integrations/IntegrationDropdown'
import GroupedDropdown from '@baserow/modules/core/components/GroupedDropdown'
import DataSourceTestForm from '@baserow/modules/builder/components/dataSource/DataSourceTestForm'
import form from '@baserow/modules/core/mixins/form'
import applicationContext from '@baserow/modules/builder/mixins/applicationContext'
import { required, requiredIf, maxLength, helpers } from '@vuelidate/validators'
import { DATA_PROVIDERS_ALLOWED_DATA_SOURCES } from '@baserow/modules/builder/enums'
import { getNextAvailableNameInSequence } from '@baserow/modules/core/utils/string'
export default {
name: 'DataSourceForm',
components: { GroupedDropdown, IntegrationDropdown, DataSourceTestForm },
mixins: [form, applicationContext],
provide() {
return {
dataProvidersAllowed: DATA_PROVIDERS_ALLOWED_DATA_SOURCES,
// Shared by the service form, which can have a Test button of its own,
// and the test form showing the result.
dataSourceTest: this.dataSourceTest,
// Identifies the data source to the filter form, e.g. for Kuma.
serviceFilterTarget: computed(() => ({
kind: 'builder_data_source',
id: this.dataSource?.id,
})),
// The integration chosen in the header, which the service form can
// read before it's saved, and choose, e.g. one it just created.
dataSourceIntegrationId: computed({
get: () => this.values.integration_id,
set: (integrationId) => {
this.v$.values.integration_id.$model = integrationId
},
}),
}
},
props: {
builder: {
type: Object,
required: true,
},
dataSource: {
type: Object,
required: false,
default: () => ({}),
},
page: {
type: Object,
required: true,
},
integrations: {
type: Array,
required: true,
},
create: {
type: Boolean,
required: false,
default: false,
},
},
// The test saved the data source.
emits: ['saved'],
setup(props) {
const instance = getCurrentInstance()
const dataSourceTest = useDataSourceTest({
dataSource: () => props.dataSource,
page: () => props.page,
applicationContext: () => instance.proxy.applicationContext,
beforeTest: () => instance.proxy.saveBeforeTest(),
})
return { v$: useVuelidate({ $lazy: true }), dataSourceTest }
},
data() {
return {
allowedValues: ['name', 'integration_id', 'type'],
values: { name: '', integration_id: null, type: null },
deactivatedClickModal: null,
deactivatedServiceTypeName: '',
}
},
computed: {
computedType: {
get() {
return this.values.type
},
set(newValue) {
this.v$.values.type.$model = newValue
this.v$.values.name.$model = this.suggestedName
const selectedIntegrationIsAvailable = this.availableIntegrations.some(
({ id }) => id === this.v$.values.integration_id.$model
)
if (!selectedIntegrationIsAvailable) {
this.v$.values.integration_id.$model =
this.preselectedIntegration?.id ?? null
}
},
},
preselectedIntegration() {
// An optional integration, like the key of an API, is only ever chosen.
if (this.integrationIsOptional) {
return null
}
return getDefaultIntegration(this.availableIntegrations, this.builder)
},
integration() {
return this.integrations.find(
(integration) => integration.id === this.values.integration_id
)
},
serviceTypes() {
return this.$registry.getOrderedList('service')
},
dataSourceServiceTypes() {
return this.serviceTypes.filter(
({ isDataSource, hiddenInDataSourcePicker }) =>
isDataSource && !hiddenInDataSourcePicker
)
},
serviceType() {
return this.values.type
? this.$registry.get('service', this.values.type)
: null
},
/**
* Whether the selected service type works without an integration, like an
* HTTP request, in which case there's no integration to choose.
*/
hasNoIntegration() {
return Boolean(
this.serviceType &&
(!this.serviceType.integrationType ||
this.serviceType.integrationIsOptional)
)
},
/**
* Whether the selected service type works with or without an integration,
* like an HTTP request that can carry the key of an API.
*/
integrationIsOptional() {
return Boolean(this.serviceType?.integrationIsOptional)
},
existingNames() {
return this.$store.getters['dataSource/getPageDataSources'](this.page)
.filter(({ id }) => this.create || id !== this.defaultValues.id)
.map(({ name }) => name)
},
suggestedName() {
if (!this.serviceType) {
return getNextAvailableNameInSequence(
this.$t('dataSourceForm.defaultName'),
this.existingNames
)
}
return getNextAvailableNameInSequence(
this.serviceType.name,
this.existingNames
)
},
availableIntegrations() {
return this.serviceType?.integrationType
? this.integrations.filter(
({ type }) => type === this.serviceType.integrationType.getType()
)
: []
},
serviceTypesPerIntegration() {
return this.$registry
.getOrderedList('integration')
.map((integrationType) => [
integrationType,
this.dataSourceServiceTypes.filter(
(serviceType) =>
serviceType.integrationType === integrationType &&
!serviceType.integrationIsOptional
),
])
},
/**
* The service types without an integration, or whose integration is
* optional, grouped by their own group (e.g. HTTP), in the order the groups
* first appear.
*/
serviceTypesPerGroup() {
const groups = new Map()
this.dataSourceServiceTypes
.filter(
(serviceType) =>
!serviceType.integrationType || serviceType.integrationIsOptional
)
.forEach((serviceType) => {
const group = serviceType.group
if (!groups.has(group.id)) {
groups.set(group.id, { group, serviceTypes: [] })
}
groups.get(group.id).serviceTypes.push(serviceType)
})
return [...groups.values()]
},
serviceTypeOptions() {
const integrationGroups = this.serviceTypesPerIntegration.map(
([integrationType, serviceTypes]) => ({
id: `integration-${integrationType.getType()}`,
label: integrationType.name,
image: integrationType.image,
icon: integrationType.iconClass,
iconColor: integrationType.iconColor,
children: serviceTypes.map(this.getServiceTypeOption),
})
)
const otherGroups = this.serviceTypesPerGroup.map(
({ group, serviceTypes }) => ({
id: group.id,
label: group.label,
image: group.image,
icon: group.icon,
iconColor: group.iconColor,
children: serviceTypes.map(this.getServiceTypeOption),
})
)
// The menu sorts groups by their order, then by label: the integration
// groups, like Local Baserow, come first.
return [...integrationGroups, ...otherGroups]
.filter(({ children }) => children.length > 0)
.map((group, index) => ({ ...group, order: index }))
},
},
watch: {
availableIntegrations(integrations) {
// The integration request can finish after the user chooses a service.
// Only fill a new source's empty choice; leave existing sources untouched.
if (
this.create &&
this.values.integration_id === null &&
!this.integrationIsOptional
) {
this.v$.values.integration_id.$model =
getDefaultIntegration(integrations, this.builder)?.id ?? null
}
},
},
methods: {
getServiceTypeOption(serviceType) {
return {
id: `service-${serviceType.getType()}`,
label: serviceType.name,
value: serviceType.getType(),
icon: serviceType.icon,
iconColor: serviceType.iconColor,
description: serviceType.description,
disabled: this.isServiceTypeDeactivated(serviceType),
disabledReason: this.getServiceTypeDeactivatedReason(serviceType),
}
},
getFormValues(deep = false) {
const values = Object.assign(
{},
this.values,
this.getChildFormsValues(deep)
)
if (this.$refs.subForm?.getFormValues) {
return { ...values, ...this.$refs.subForm.getFormValues(deep) }
}
return values
},
isFormValid(deep = false) {
const thisFormInvalid = 'v$' in this && this.v$.$invalid
const subFormValid = this.$refs.subForm?.isFormValid
? this.$refs.subForm.isFormValid(deep)
: true
return !thisFormInvalid && this.areChildFormsValid(deep) && subFormValid
},
/**
* The test dispatches the saved data source, so what the form changed is
* saved first. Returns false when the form isn't valid, as there is then
* nothing that can be saved and tested.
*/
async saveBeforeTest() {
if (!this.isFormValid(true)) {
this.touch(true)
return false
}
// Compared the way the modal does when it saves.
const changes = Object.fromEntries(
Object.entries(this.getFormValues(true)).filter(
([key, value]) => !_.isEqual(value, this.dataSource[key])
)
)
if (Object.keys(changes).length) {
await this.$store.dispatch('dataSource/update', {
page: this.page,
dataSourceId: this.dataSource.id,
values: changes,
})
this.$emit('saved')
}
return true
},
getServiceTypeDeactivatedReason(serviceType) {
return (
serviceType.isDeactivatedReason?.({
workspace: this.builder.workspace,
}) || null
)
},
isServiceTypeDeactivated(serviceType) {
return this.getServiceTypeDeactivatedReason(serviceType) !== null
},
onServiceTypeDisabledClick(item) {
this.onServiceTypeClick(this.$registry.get('service', item.value))
},
onServiceTypeClick(serviceType) {
const deactivatedClickModal = serviceType.getDeactivatedClickModal?.({
workspace: this.builder.workspace,
})
if (
deactivatedClickModal === null ||
deactivatedClickModal === undefined
) {
return
}
this.deactivatedClickModal = deactivatedClickModal
this.deactivatedServiceTypeName = serviceType.name
this.$nextTick(() => {
this.$refs.deactivatedClickModal.show()
})
},
},
validations() {
return {
values: {
name: {
required: helpers.withMessage(
this.$t('error.requiredField'),
required
),
maxLength: helpers.withMessage(
this.$t('error.maxLength', { max: 255 }),
maxLength(255)
),
},
integration_id: {
required: helpers.withMessage(
this.$t('error.requiredField'),
requiredIf(() => !this.hasNoIntegration)
),
},
type: {
required: helpers.withMessage(
this.$t('error.requiredField'),
required
),
},
},
}
},
}
</script>