@gitlab/ui 62.5.2 → 62.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/components/base/form/form_fields/form_field_validator.js +93 -0
- package/dist/components/base/form/form_fields/form_fields.js +213 -0
- package/dist/components/base/form/form_fields/mappers.js +13 -0
- package/dist/components/base/form/form_fields/validators.js +16 -0
- package/dist/index.js +1 -0
- package/dist/utils.js +4 -0
- package/package.json +3 -3
- package/src/components/base/form/form_fields/form_field_validator.spec.js +51 -0
- package/src/components/base/form/form_fields/form_field_validator.vue +59 -0
- package/src/components/base/form/form_fields/form_fields.md +28 -0
- package/src/components/base/form/form_fields/form_fields.spec.js +424 -0
- package/src/components/base/form/form_fields/form_fields.stories.js +102 -0
- package/src/components/base/form/form_fields/form_fields.vue +219 -0
- package/src/components/base/form/form_fields/mappers.js +11 -0
- package/src/components/base/form/form_fields/mappers.spec.js +17 -0
- package/src/components/base/form/form_fields/validators.js +16 -0
- package/src/components/base/form/form_fields/validators.spec.js +29 -0
- package/src/index.js +1 -0
- package/src/utils.js +3 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
# [62.6.0](https://gitlab.com/gitlab-org/gitlab-ui/compare/v62.5.2...v62.6.0) (2023-05-02)
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
### Features
|
|
5
|
+
|
|
6
|
+
* Add gl-form-fields component ([a17bcb6](https://gitlab.com/gitlab-org/gitlab-ui/commit/a17bcb6c8db0444dcd7f5bd799fe681891dbdcc9))
|
|
7
|
+
|
|
1
8
|
## [62.5.2](https://gitlab.com/gitlab-org/gitlab-ui/compare/v62.5.1...v62.5.2) (2023-05-01)
|
|
2
9
|
|
|
3
10
|
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import __vue_normalize__ from 'vue-runtime-helpers/dist/normalize-component.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* FormFieldValidator
|
|
5
|
+
*
|
|
6
|
+
* This is an internal component which is used to watch on specific field/value
|
|
7
|
+
* pairs and emits changes to `invalidFeedback`.
|
|
8
|
+
*
|
|
9
|
+
* **why:** Without this separate component, *any* change to *any* value
|
|
10
|
+
* was causing *all* validators to run. A separate renderless component
|
|
11
|
+
* helps us isolate this logic *and* react only to what we need to.
|
|
12
|
+
*/
|
|
13
|
+
var script = {
|
|
14
|
+
name: 'GlFormFieldValidator',
|
|
15
|
+
props: {
|
|
16
|
+
value: {
|
|
17
|
+
required: true,
|
|
18
|
+
// ESLint requires "validator" or "type". Any kind of value is valid.
|
|
19
|
+
validator: () => true
|
|
20
|
+
},
|
|
21
|
+
validators: {
|
|
22
|
+
type: Array,
|
|
23
|
+
required: false,
|
|
24
|
+
default: () => []
|
|
25
|
+
},
|
|
26
|
+
shouldValidate: {
|
|
27
|
+
type: Boolean,
|
|
28
|
+
required: false,
|
|
29
|
+
default: false
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
computed: {
|
|
33
|
+
invalidFeedback() {
|
|
34
|
+
if (!this.shouldValidate) {
|
|
35
|
+
return '';
|
|
36
|
+
}
|
|
37
|
+
const result = this.validators.reduce((acc, validateFn) => {
|
|
38
|
+
// If we already have an invalid message, let's just use that one.
|
|
39
|
+
if (acc) {
|
|
40
|
+
return acc;
|
|
41
|
+
}
|
|
42
|
+
return validateFn(this.value);
|
|
43
|
+
}, '');
|
|
44
|
+
|
|
45
|
+
// Force falsey string for type consistency.
|
|
46
|
+
return result || '';
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
watch: {
|
|
50
|
+
invalidFeedback(newVal) {
|
|
51
|
+
this.$emit('update', newVal);
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
render() {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/* script */
|
|
60
|
+
const __vue_script__ = script;
|
|
61
|
+
|
|
62
|
+
/* template */
|
|
63
|
+
|
|
64
|
+
/* style */
|
|
65
|
+
const __vue_inject_styles__ = undefined;
|
|
66
|
+
/* scoped */
|
|
67
|
+
const __vue_scope_id__ = undefined;
|
|
68
|
+
/* module identifier */
|
|
69
|
+
const __vue_module_identifier__ = undefined;
|
|
70
|
+
/* functional template */
|
|
71
|
+
const __vue_is_functional_template__ = undefined;
|
|
72
|
+
/* style inject */
|
|
73
|
+
|
|
74
|
+
/* style inject SSR */
|
|
75
|
+
|
|
76
|
+
/* style inject shadow dom */
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
const __vue_component__ = __vue_normalize__(
|
|
81
|
+
{},
|
|
82
|
+
__vue_inject_styles__,
|
|
83
|
+
__vue_script__,
|
|
84
|
+
__vue_scope_id__,
|
|
85
|
+
__vue_is_functional_template__,
|
|
86
|
+
__vue_module_identifier__,
|
|
87
|
+
false,
|
|
88
|
+
undefined,
|
|
89
|
+
undefined,
|
|
90
|
+
undefined
|
|
91
|
+
);
|
|
92
|
+
|
|
93
|
+
export default __vue_component__;
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import isFunction from 'lodash/isFunction';
|
|
2
|
+
import mapValues from 'lodash/mapValues';
|
|
3
|
+
import uniqueId from 'lodash/uniqueId';
|
|
4
|
+
import GlFormGroup from '../form_group/form_group';
|
|
5
|
+
import GlFormInput from '../form_input/form_input';
|
|
6
|
+
import GlFormFieldValidator from './form_field_validator';
|
|
7
|
+
import __vue_normalize__ from 'vue-runtime-helpers/dist/normalize-component.js';
|
|
8
|
+
|
|
9
|
+
var script = {
|
|
10
|
+
name: 'GlFormFields',
|
|
11
|
+
components: {
|
|
12
|
+
GlFormGroup,
|
|
13
|
+
GlFormInput,
|
|
14
|
+
GlFormFieldValidator
|
|
15
|
+
},
|
|
16
|
+
model: {
|
|
17
|
+
prop: 'values',
|
|
18
|
+
event: 'input'
|
|
19
|
+
},
|
|
20
|
+
props: {
|
|
21
|
+
/**
|
|
22
|
+
* Object of keys to FieldDefinitions.
|
|
23
|
+
* The shape of the keys will be the same for `values` and what's emitted by the `input` event.
|
|
24
|
+
*
|
|
25
|
+
* @typedef {object} FieldDefinition
|
|
26
|
+
* @template TValue=string
|
|
27
|
+
* @property {string} label - Label text to show for this field.
|
|
28
|
+
* @property {undefined | Object} inputAttrs - Properties that are passed to the actual input for this field.
|
|
29
|
+
* @property {undefined | function(string): TValue} mapValue - Function that maps the inputted string value to the field's actual value (e.g. a Number).
|
|
30
|
+
* @property {undefined | Array<function(TValue): string | undefined>=} validators - Collection of validator functions.
|
|
31
|
+
*
|
|
32
|
+
* @type {{ [key: string]: FieldDefinition }}
|
|
33
|
+
*/
|
|
34
|
+
fields: {
|
|
35
|
+
type: Object,
|
|
36
|
+
required: true
|
|
37
|
+
},
|
|
38
|
+
/**
|
|
39
|
+
* The current value for each field, by key.
|
|
40
|
+
* Keys should match between `values` and `fields`.
|
|
41
|
+
*/
|
|
42
|
+
values: {
|
|
43
|
+
type: Object,
|
|
44
|
+
required: true
|
|
45
|
+
},
|
|
46
|
+
/**
|
|
47
|
+
* The id of the form element to handle "submit" listening.
|
|
48
|
+
*/
|
|
49
|
+
formId: {
|
|
50
|
+
type: String,
|
|
51
|
+
required: true
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
data() {
|
|
55
|
+
return {
|
|
56
|
+
fieldDirtyStatuses: {},
|
|
57
|
+
fieldValidations: {}
|
|
58
|
+
};
|
|
59
|
+
},
|
|
60
|
+
computed: {
|
|
61
|
+
formElement() {
|
|
62
|
+
return document.getElementById(this.formId);
|
|
63
|
+
},
|
|
64
|
+
fieldValidationProps() {
|
|
65
|
+
return mapValues(this.fields, (_, fieldName) => {
|
|
66
|
+
const invalidFeedback = this.fieldValidations[fieldName] || '';
|
|
67
|
+
return {
|
|
68
|
+
invalidFeedback,
|
|
69
|
+
state: invalidFeedback ? false : null
|
|
70
|
+
};
|
|
71
|
+
});
|
|
72
|
+
},
|
|
73
|
+
fieldValues() {
|
|
74
|
+
return mapValues(this.fields, (_, fieldName) => {
|
|
75
|
+
if (fieldName in this.values) {
|
|
76
|
+
return this.values[fieldName];
|
|
77
|
+
}
|
|
78
|
+
return this.getMappedValue(fieldName, undefined);
|
|
79
|
+
});
|
|
80
|
+
},
|
|
81
|
+
fieldNames() {
|
|
82
|
+
return Object.keys(this.fields);
|
|
83
|
+
},
|
|
84
|
+
fieldsToRender() {
|
|
85
|
+
return mapValues(this.fields, (field, fieldName) => {
|
|
86
|
+
const id = uniqueId('gl-form-field-');
|
|
87
|
+
const scopedSlotName = `input(${fieldName})`;
|
|
88
|
+
const hasScopedSlot = this.$scopedSlots[scopedSlotName];
|
|
89
|
+
const scopedSlotAttrs = hasScopedSlot && {
|
|
90
|
+
value: this.fieldValues[fieldName],
|
|
91
|
+
input: val => this.onFieldInput(fieldName, val),
|
|
92
|
+
blur: () => this.onFieldBlur(fieldName),
|
|
93
|
+
validation: this.fieldValidationProps[fieldName],
|
|
94
|
+
id
|
|
95
|
+
};
|
|
96
|
+
return {
|
|
97
|
+
...field,
|
|
98
|
+
id,
|
|
99
|
+
label: field.label || fieldName,
|
|
100
|
+
scopedSlotName,
|
|
101
|
+
scopedSlotAttrs
|
|
102
|
+
};
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
mounted() {
|
|
107
|
+
var _this$formElement;
|
|
108
|
+
// why: We emit initial values as a convenience so that `v-model="values"` can be easily initialized.
|
|
109
|
+
this.$emit('input', this.fieldValues);
|
|
110
|
+
(_this$formElement = this.formElement) === null || _this$formElement === void 0 ? void 0 : _this$formElement.addEventListener('submit', this.onFormSubmission);
|
|
111
|
+
},
|
|
112
|
+
destroyed() {
|
|
113
|
+
var _this$formElement2;
|
|
114
|
+
(_this$formElement2 = this.formElement) === null || _this$formElement2 === void 0 ? void 0 : _this$formElement2.removeEventListener('submit', this.onFormSubmission);
|
|
115
|
+
},
|
|
116
|
+
methods: {
|
|
117
|
+
setFieldDirty(fieldName) {
|
|
118
|
+
this.$set(this.fieldDirtyStatuses, fieldName, true);
|
|
119
|
+
},
|
|
120
|
+
setAllFieldsDirty() {
|
|
121
|
+
this.fieldNames.forEach(fieldName => this.setFieldDirty(fieldName));
|
|
122
|
+
},
|
|
123
|
+
hasAllFieldsValid() {
|
|
124
|
+
// note: Only check "fieldNames" since "fields" could have changed since the life of "fieldValidations"
|
|
125
|
+
return this.fieldNames.every(fieldName => !this.fieldValidations[fieldName]);
|
|
126
|
+
},
|
|
127
|
+
async checkBeforeSubmission() {
|
|
128
|
+
this.setAllFieldsDirty();
|
|
129
|
+
await this.$nextTick();
|
|
130
|
+
return this.hasAllFieldsValid();
|
|
131
|
+
},
|
|
132
|
+
getMappedValue(fieldName, val) {
|
|
133
|
+
const field = this.fields[fieldName];
|
|
134
|
+
if (isFunction(field === null || field === void 0 ? void 0 : field.mapValue)) {
|
|
135
|
+
return field.mapValue(val);
|
|
136
|
+
}
|
|
137
|
+
return val;
|
|
138
|
+
},
|
|
139
|
+
onFieldValidationUpdate(fieldName, invalidFeedback) {
|
|
140
|
+
this.$set(this.fieldValidations, fieldName, invalidFeedback);
|
|
141
|
+
},
|
|
142
|
+
onFieldBlur(fieldName) {
|
|
143
|
+
this.setFieldDirty(fieldName);
|
|
144
|
+
},
|
|
145
|
+
onFieldInput(fieldName, inputValue) {
|
|
146
|
+
const val = this.getMappedValue(fieldName, inputValue);
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Emitted when any of the form values change. Used by `v-model`.
|
|
150
|
+
*/
|
|
151
|
+
this.$emit('input', {
|
|
152
|
+
...this.values,
|
|
153
|
+
[fieldName]: val
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Emitted when a form input emits the `input` event.
|
|
158
|
+
*/
|
|
159
|
+
this.$emit('input-field', {
|
|
160
|
+
name: fieldName,
|
|
161
|
+
value: val
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
async onFormSubmission(e) {
|
|
165
|
+
e.preventDefault();
|
|
166
|
+
const isValid = await this.checkBeforeSubmission();
|
|
167
|
+
if (isValid) {
|
|
168
|
+
/**
|
|
169
|
+
* Emitted when the form is submitted and all of the form fields are valid.
|
|
170
|
+
*/
|
|
171
|
+
this.$emit('submit', e);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
/* script */
|
|
178
|
+
const __vue_script__ = script;
|
|
179
|
+
|
|
180
|
+
/* template */
|
|
181
|
+
var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',_vm._l((_vm.fieldsToRender),function(field,fieldName){return _c('gl-form-group',{key:fieldName,attrs:{"label":field.label,"label-for":field.id,"invalid-feedback":_vm.fieldValidationProps[fieldName].invalidFeedback,"state":_vm.fieldValidationProps[fieldName].state}},[_c('gl-form-field-validator',{attrs:{"value":_vm.fieldValues[fieldName],"validators":field.validators,"should-validate":_vm.fieldDirtyStatuses[fieldName]},on:{"update":function($event){return _vm.onFieldValidationUpdate(fieldName, $event)}}}),_vm._v(" "),(field.scopedSlotAttrs)?[_vm._t(field.scopedSlotName,null,null,field.scopedSlotAttrs)]:[_c('gl-form-input',_vm._b({attrs:{"id":field.id,"value":_vm.fieldValues[fieldName],"state":_vm.fieldValidationProps[fieldName].state},on:{"input":function($event){return _vm.onFieldInput(fieldName, $event)},"blur":function($event){return _vm.onFieldBlur(fieldName)}}},'gl-form-input',field.inputAttrs,false))]],2)}),1)};
|
|
182
|
+
var __vue_staticRenderFns__ = [];
|
|
183
|
+
|
|
184
|
+
/* style */
|
|
185
|
+
const __vue_inject_styles__ = undefined;
|
|
186
|
+
/* scoped */
|
|
187
|
+
const __vue_scope_id__ = undefined;
|
|
188
|
+
/* module identifier */
|
|
189
|
+
const __vue_module_identifier__ = undefined;
|
|
190
|
+
/* functional template */
|
|
191
|
+
const __vue_is_functional_template__ = false;
|
|
192
|
+
/* style inject */
|
|
193
|
+
|
|
194
|
+
/* style inject SSR */
|
|
195
|
+
|
|
196
|
+
/* style inject shadow dom */
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
const __vue_component__ = __vue_normalize__(
|
|
201
|
+
{ render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ },
|
|
202
|
+
__vue_inject_styles__,
|
|
203
|
+
__vue_script__,
|
|
204
|
+
__vue_scope_id__,
|
|
205
|
+
__vue_is_functional_template__,
|
|
206
|
+
__vue_module_identifier__,
|
|
207
|
+
false,
|
|
208
|
+
undefined,
|
|
209
|
+
undefined,
|
|
210
|
+
undefined
|
|
211
|
+
);
|
|
212
|
+
|
|
213
|
+
export default __vue_component__;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// This contains core mapping behavior (like mapping to native JavaScript types)
|
|
2
|
+
// and**should not** contain domain-specific mappers.
|
|
3
|
+
//
|
|
4
|
+
// ```
|
|
5
|
+
// // Good
|
|
6
|
+
// export const mapToBoolean = ...
|
|
7
|
+
//
|
|
8
|
+
// // Bad
|
|
9
|
+
// export const mapToApolloCacheWidget = ...
|
|
10
|
+
// ```
|
|
11
|
+
const mapToNumber = x => Number(x || 0);
|
|
12
|
+
|
|
13
|
+
export { mapToNumber };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// This contains core validating behavior and **should not** contain
|
|
2
|
+
// domain-specific validations.
|
|
3
|
+
//
|
|
4
|
+
// Look to what's allowed in HTML attributes as a good basis for what belongs here
|
|
5
|
+
//
|
|
6
|
+
// ```
|
|
7
|
+
// // Good
|
|
8
|
+
// export const required = ...
|
|
9
|
+
//
|
|
10
|
+
// // Bad
|
|
11
|
+
// export const projectPathIsUnique = ...
|
|
12
|
+
// ```
|
|
13
|
+
const factory = (failMessage, isValid) => val => !isValid(val) ? failMessage : '';
|
|
14
|
+
const required = failMessage => factory(failMessage, val => val !== '' && val !== null && val !== undefined);
|
|
15
|
+
|
|
16
|
+
export { factory, required };
|
package/dist/index.js
CHANGED
|
@@ -37,6 +37,7 @@ export { default as GlFormRadioGroup } from './components/base/form/form_radio_g
|
|
|
37
37
|
export { default as GlFormSelect } from './components/base/form/form_select/form_select';
|
|
38
38
|
export { default as GlFormTextarea } from './components/base/form/form_textarea/form_textarea';
|
|
39
39
|
export { default as GlFormGroup } from './components/base/form/form_group/form_group';
|
|
40
|
+
export { default as GlFormFields } from './components/base/form/form_fields/form_fields';
|
|
40
41
|
export { default as GlSearchBoxByType } from './components/base/search_box_by_type/search_box_by_type';
|
|
41
42
|
export { default as GlSearchBoxByClick } from './components/base/search_box_by_click/search_box_by_click';
|
|
42
43
|
export { default as GlDropdownItem } from './components/base/dropdown/dropdown_item';
|
package/dist/utils.js
CHANGED
|
@@ -1 +1,5 @@
|
|
|
1
1
|
export { GlBreakpointInstance, breakpoints } from './utils/breakpoints';
|
|
2
|
+
import * as validators from './components/base/form/form_fields/validators';
|
|
3
|
+
export { validators as formValidators };
|
|
4
|
+
import * as mappers from './components/base/form/form_fields/mappers';
|
|
5
|
+
export { mappers as formMappers };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gitlab/ui",
|
|
3
|
-
"version": "62.
|
|
3
|
+
"version": "62.6.0",
|
|
4
4
|
"description": "GitLab UI Components",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -83,8 +83,8 @@
|
|
|
83
83
|
},
|
|
84
84
|
"devDependencies": {
|
|
85
85
|
"@arkweid/lefthook": "0.7.7",
|
|
86
|
-
"@babel/core": "^7.21.
|
|
87
|
-
"@babel/preset-env": "^7.21.
|
|
86
|
+
"@babel/core": "^7.21.5",
|
|
87
|
+
"@babel/preset-env": "^7.21.5",
|
|
88
88
|
"@babel/preset-react": "^7.18.6",
|
|
89
89
|
"@gitlab/eslint-plugin": "19.0.0",
|
|
90
90
|
"@gitlab/fonts": "^1.2.0",
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { mount } from '@vue/test-utils';
|
|
2
|
+
import GlFormFieldValidator from './form_field_validator.vue';
|
|
3
|
+
import { required } from './validators';
|
|
4
|
+
|
|
5
|
+
const TEST_VALUE = 'root';
|
|
6
|
+
const TEST_MESSAGE = 'this is a required field';
|
|
7
|
+
|
|
8
|
+
describe('GlFormFieldValidators', () => {
|
|
9
|
+
let wrapper;
|
|
10
|
+
|
|
11
|
+
const createWrapper = (props = {}) => {
|
|
12
|
+
wrapper = mount(GlFormFieldValidator, {
|
|
13
|
+
propsData: {
|
|
14
|
+
value: TEST_VALUE,
|
|
15
|
+
validators: [required(TEST_MESSAGE)],
|
|
16
|
+
shouldValidate: true,
|
|
17
|
+
...props,
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
it('should call validators with value prop', () => {
|
|
22
|
+
const validators = [jest.fn(), jest.fn(), jest.fn()];
|
|
23
|
+
|
|
24
|
+
createWrapper({ validators });
|
|
25
|
+
|
|
26
|
+
validators.forEach((validator) => expect(validator).toHaveBeenCalledWith(TEST_VALUE));
|
|
27
|
+
});
|
|
28
|
+
it('should not call validators when told not to', () => {
|
|
29
|
+
const validators = [jest.fn(), jest.fn(), jest.fn()];
|
|
30
|
+
|
|
31
|
+
createWrapper({ validators, shouldValidate: false });
|
|
32
|
+
|
|
33
|
+
validators.forEach((validator) => expect(validator).not.toHaveBeenCalledWith(TEST_VALUE));
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('should not render anything ever forever', () => {
|
|
37
|
+
createWrapper();
|
|
38
|
+
|
|
39
|
+
expect(wrapper.html()).toBe('');
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('should emit update with result of validator', async () => {
|
|
43
|
+
createWrapper();
|
|
44
|
+
|
|
45
|
+
expect(wrapper.emitted('update')).toBeUndefined();
|
|
46
|
+
|
|
47
|
+
await wrapper.setProps({ value: '' });
|
|
48
|
+
|
|
49
|
+
expect(wrapper.emitted('update')).toEqual([[TEST_MESSAGE]]);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
<script>
|
|
2
|
+
/**
|
|
3
|
+
* FormFieldValidator
|
|
4
|
+
*
|
|
5
|
+
* This is an internal component which is used to watch on specific field/value
|
|
6
|
+
* pairs and emits changes to `invalidFeedback`.
|
|
7
|
+
*
|
|
8
|
+
* **why:** Without this separate component, *any* change to *any* value
|
|
9
|
+
* was causing *all* validators to run. A separate renderless component
|
|
10
|
+
* helps us isolate this logic *and* react only to what we need to.
|
|
11
|
+
*/
|
|
12
|
+
export default {
|
|
13
|
+
name: 'GlFormFieldValidator',
|
|
14
|
+
props: {
|
|
15
|
+
value: {
|
|
16
|
+
required: true,
|
|
17
|
+
// ESLint requires "validator" or "type". Any kind of value is valid.
|
|
18
|
+
validator: () => true,
|
|
19
|
+
},
|
|
20
|
+
validators: {
|
|
21
|
+
type: Array,
|
|
22
|
+
required: false,
|
|
23
|
+
default: () => [],
|
|
24
|
+
},
|
|
25
|
+
shouldValidate: {
|
|
26
|
+
type: Boolean,
|
|
27
|
+
required: false,
|
|
28
|
+
default: false,
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
computed: {
|
|
32
|
+
invalidFeedback() {
|
|
33
|
+
if (!this.shouldValidate) {
|
|
34
|
+
return '';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const result = this.validators.reduce((acc, validateFn) => {
|
|
38
|
+
// If we already have an invalid message, let's just use that one.
|
|
39
|
+
if (acc) {
|
|
40
|
+
return acc;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return validateFn(this.value);
|
|
44
|
+
}, '');
|
|
45
|
+
|
|
46
|
+
// Force falsey string for type consistency.
|
|
47
|
+
return result || '';
|
|
48
|
+
},
|
|
49
|
+
},
|
|
50
|
+
watch: {
|
|
51
|
+
invalidFeedback(newVal) {
|
|
52
|
+
this.$emit('update', newVal);
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
render() {
|
|
56
|
+
return null;
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
</script>
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
## Usage
|
|
2
|
+
|
|
3
|
+
`GlFormFields` provides form builder functionality for ease of building simple
|
|
4
|
+
forms out of other GitLab UI form components.
|
|
5
|
+
|
|
6
|
+
For a code example, look at the story. It covers usage of `mapValue`, `validators`,
|
|
7
|
+
custom form elements, and `inputAttrs`.
|
|
8
|
+
|
|
9
|
+
## Fields type
|
|
10
|
+
|
|
11
|
+
Each value of `fields` prop is expected to be a `FieldDefinition`. See below for the shape of this type:
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
interface FieldDefinition<TValue> {
|
|
15
|
+
// Label text to show for this field.
|
|
16
|
+
label: string;
|
|
17
|
+
|
|
18
|
+
// Collection of validator functions
|
|
19
|
+
validators?: Array<(value: TValue) => string | undefined>;
|
|
20
|
+
|
|
21
|
+
// Function that maps the inputted string value to the field's actual value
|
|
22
|
+
// (e.g. a Number).
|
|
23
|
+
mapValue?: (input: string) => TValue;
|
|
24
|
+
|
|
25
|
+
// Properties that are passed to the actual input for this field.
|
|
26
|
+
inputAttrs?: {};
|
|
27
|
+
}
|
|
28
|
+
```
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
import cloneDeep from 'lodash/cloneDeep';
|
|
2
|
+
import mapValues from 'lodash/mapValues';
|
|
3
|
+
import { nextTick } from 'vue';
|
|
4
|
+
import { shallowMount } from '@vue/test-utils';
|
|
5
|
+
import GlFormGroup from '../form_group/form_group.vue';
|
|
6
|
+
import GlInput from '../form_input/form_input.vue';
|
|
7
|
+
import GlFormFields from './form_fields.vue';
|
|
8
|
+
import GlFormFieldValidator from './form_field_validator.vue';
|
|
9
|
+
import * as formMappers from './mappers';
|
|
10
|
+
import * as formValidators from './validators';
|
|
11
|
+
|
|
12
|
+
jest.mock('lodash/uniqueId', () => (val) => `${val}testunique`);
|
|
13
|
+
|
|
14
|
+
const TEST_FIELDS = {
|
|
15
|
+
username: {
|
|
16
|
+
label: 'User name',
|
|
17
|
+
validators: [formValidators.required('User name is required')],
|
|
18
|
+
},
|
|
19
|
+
evenCount: {
|
|
20
|
+
label: 'Count',
|
|
21
|
+
mapValue: formMappers.mapToNumber,
|
|
22
|
+
validators: [
|
|
23
|
+
formValidators.factory('Count is required', Boolean),
|
|
24
|
+
(val) => (val % 2 === 1 ? 'Count must be even' : ''),
|
|
25
|
+
],
|
|
26
|
+
inputAttrs: { size: 'xs', type: 'number' },
|
|
27
|
+
},
|
|
28
|
+
allCaps: {
|
|
29
|
+
label: 'All caps (optional)',
|
|
30
|
+
mapValue: (x) => x?.toUpperCase(),
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
const TEST_VALUES = {
|
|
34
|
+
username: 'root',
|
|
35
|
+
evenCount: 8,
|
|
36
|
+
allCaps: '',
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const TEST_FORM_ID = 'test-form-id';
|
|
40
|
+
|
|
41
|
+
describe('GlFormFields', () => {
|
|
42
|
+
let wrapper;
|
|
43
|
+
|
|
44
|
+
// region: factory --------------------------------------------------
|
|
45
|
+
const createComponent = (props = {}, options = {}) => {
|
|
46
|
+
// why: Clone the constant so Vue doesn't turn it reactive
|
|
47
|
+
const fields = cloneDeep(TEST_FIELDS);
|
|
48
|
+
|
|
49
|
+
wrapper = shallowMount(GlFormFields, {
|
|
50
|
+
propsData: {
|
|
51
|
+
fields,
|
|
52
|
+
values: {},
|
|
53
|
+
formId: TEST_FORM_ID,
|
|
54
|
+
...props,
|
|
55
|
+
},
|
|
56
|
+
stubs: {
|
|
57
|
+
GlFormFieldValidator,
|
|
58
|
+
},
|
|
59
|
+
...options,
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// region: finders --------------------------------------------------
|
|
64
|
+
const mapFormGroupToData = (formGroup) => {
|
|
65
|
+
const input = formGroup.findComponent(GlInput);
|
|
66
|
+
|
|
67
|
+
return {
|
|
68
|
+
label: formGroup.attributes('label'),
|
|
69
|
+
state: formGroup.attributes('state'),
|
|
70
|
+
invalidFeedback: formGroup.attributes('invalid-feedback'),
|
|
71
|
+
input: {
|
|
72
|
+
// Ensure that "value" is present even if undefined
|
|
73
|
+
value: input.attributes('value'),
|
|
74
|
+
...input.attributes(),
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
const findFormGroups = () => wrapper.findAllComponents(GlFormGroup).wrappers;
|
|
79
|
+
const findFormGroupsAsData = () => findFormGroups().map(mapFormGroupToData);
|
|
80
|
+
const findFormGroupFromLabel = (label) =>
|
|
81
|
+
wrapper.findAllComponents(GlFormGroup).wrappers.find((x) => x.attributes('label') === label);
|
|
82
|
+
const findInputFromLabel = (label) => findFormGroupFromLabel(label).findComponent(GlInput);
|
|
83
|
+
const findCustomInputFromLabel = (label) =>
|
|
84
|
+
findFormGroupFromLabel(label).find('[data-testid="test-custom-input"]');
|
|
85
|
+
|
|
86
|
+
// region: actions ---------------------------------------------------
|
|
87
|
+
const submitForm = async () => {
|
|
88
|
+
const form = document.getElementById(TEST_FORM_ID);
|
|
89
|
+
|
|
90
|
+
form.requestSubmit();
|
|
91
|
+
|
|
92
|
+
// Submit form waits for a tick
|
|
93
|
+
await nextTick();
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
// region: setup -----------------------------------------------------
|
|
97
|
+
beforeEach(() => {
|
|
98
|
+
document.body.innerHTML = `<form id="${TEST_FORM_ID}"></form>`;
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// region: tests -----------------------------------------------------
|
|
102
|
+
describe('default', () => {
|
|
103
|
+
beforeEach(() => {
|
|
104
|
+
createComponent();
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it('renders form groups for each field', () => {
|
|
108
|
+
expect(findFormGroupsAsData()).toStrictEqual([
|
|
109
|
+
{
|
|
110
|
+
label: TEST_FIELDS.username.label,
|
|
111
|
+
state: undefined,
|
|
112
|
+
invalidFeedback: '',
|
|
113
|
+
input: {
|
|
114
|
+
id: 'gl-form-field-testunique',
|
|
115
|
+
value: undefined,
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
label: TEST_FIELDS.evenCount.label,
|
|
120
|
+
state: undefined,
|
|
121
|
+
invalidFeedback: '',
|
|
122
|
+
input: {
|
|
123
|
+
id: 'gl-form-field-testunique',
|
|
124
|
+
value: '0',
|
|
125
|
+
...TEST_FIELDS.evenCount.inputAttrs,
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
label: TEST_FIELDS.allCaps.label,
|
|
130
|
+
state: undefined,
|
|
131
|
+
invalidFeedback: '',
|
|
132
|
+
input: {
|
|
133
|
+
id: 'gl-form-field-testunique',
|
|
134
|
+
value: undefined,
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
]);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('emits initial values on mount', () => {
|
|
141
|
+
expect(wrapper.emitted('input')).toEqual([
|
|
142
|
+
[
|
|
143
|
+
{
|
|
144
|
+
username: undefined,
|
|
145
|
+
evenCount: 0,
|
|
146
|
+
allCaps: undefined,
|
|
147
|
+
},
|
|
148
|
+
],
|
|
149
|
+
]);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it('does not emit input-field', () => {
|
|
153
|
+
expect(wrapper.emitted('input-field')).toBeUndefined();
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('does not emit submit', () => {
|
|
157
|
+
expect(wrapper.emitted('submit')).toBeUndefined();
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it('on field blur, it updates validation for field', async () => {
|
|
161
|
+
const input = findInputFromLabel(TEST_FIELDS.username.label);
|
|
162
|
+
input.vm.$emit('blur');
|
|
163
|
+
|
|
164
|
+
await nextTick();
|
|
165
|
+
|
|
166
|
+
expect(findFormGroupsAsData()).toMatchObject([
|
|
167
|
+
{
|
|
168
|
+
label: TEST_FIELDS.username.label,
|
|
169
|
+
invalidFeedback: 'User name is required',
|
|
170
|
+
},
|
|
171
|
+
// why: Include others fields to assert that the validation is not run for them
|
|
172
|
+
{
|
|
173
|
+
label: TEST_FIELDS.evenCount.label,
|
|
174
|
+
invalidFeedback: '',
|
|
175
|
+
},
|
|
176
|
+
{
|
|
177
|
+
label: TEST_FIELDS.allCaps.label,
|
|
178
|
+
invalidFeedback: '',
|
|
179
|
+
},
|
|
180
|
+
]);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
describe('on field input', () => {
|
|
184
|
+
beforeEach(() => {
|
|
185
|
+
const input = findInputFromLabel(TEST_FIELDS.username.label);
|
|
186
|
+
input.vm.$emit('input', 'New value');
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it('emits input event', () => {
|
|
190
|
+
expect(wrapper.emitted('input')).toEqual([
|
|
191
|
+
// Initial value we already test here
|
|
192
|
+
expect.anything(),
|
|
193
|
+
// New emitted event
|
|
194
|
+
[
|
|
195
|
+
{
|
|
196
|
+
username: 'New value',
|
|
197
|
+
},
|
|
198
|
+
],
|
|
199
|
+
]);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
it('emits input-field event', () => {
|
|
203
|
+
expect(wrapper.emitted('input-field')).toEqual([
|
|
204
|
+
[
|
|
205
|
+
{
|
|
206
|
+
name: 'username',
|
|
207
|
+
value: 'New value',
|
|
208
|
+
},
|
|
209
|
+
],
|
|
210
|
+
]);
|
|
211
|
+
});
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
describe('when form submits', () => {
|
|
215
|
+
beforeEach(async () => {
|
|
216
|
+
await submitForm();
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it('runs validations', () => {
|
|
220
|
+
expect(findFormGroupsAsData()).toEqual([
|
|
221
|
+
{
|
|
222
|
+
label: TEST_FIELDS.username.label,
|
|
223
|
+
invalidFeedback: 'User name is required',
|
|
224
|
+
state: undefined,
|
|
225
|
+
input: {
|
|
226
|
+
value: undefined,
|
|
227
|
+
id: 'gl-form-field-testunique',
|
|
228
|
+
},
|
|
229
|
+
},
|
|
230
|
+
{
|
|
231
|
+
label: TEST_FIELDS.evenCount.label,
|
|
232
|
+
invalidFeedback: 'Count is required',
|
|
233
|
+
state: undefined,
|
|
234
|
+
input: expect.objectContaining({
|
|
235
|
+
value: '0',
|
|
236
|
+
id: 'gl-form-field-testunique',
|
|
237
|
+
}),
|
|
238
|
+
},
|
|
239
|
+
{
|
|
240
|
+
label: TEST_FIELDS.allCaps.label,
|
|
241
|
+
invalidFeedback: '',
|
|
242
|
+
state: undefined,
|
|
243
|
+
input: {
|
|
244
|
+
value: undefined,
|
|
245
|
+
id: 'gl-form-field-testunique',
|
|
246
|
+
},
|
|
247
|
+
},
|
|
248
|
+
]);
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('does not emit submit', () => {
|
|
252
|
+
expect(wrapper.emitted('submit')).toBeUndefined();
|
|
253
|
+
});
|
|
254
|
+
});
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
// why: Let's test that multiple validators work as expected
|
|
258
|
+
describe('with non-empty but invalid "count"', () => {
|
|
259
|
+
beforeEach(() => {
|
|
260
|
+
createComponent({
|
|
261
|
+
values: {
|
|
262
|
+
evenCount: 7,
|
|
263
|
+
},
|
|
264
|
+
});
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it('on blur, it runs remaining validators for "count" field', async () => {
|
|
268
|
+
const input = findInputFromLabel(TEST_FIELDS.evenCount.label);
|
|
269
|
+
input.vm.$emit('blur');
|
|
270
|
+
|
|
271
|
+
await nextTick();
|
|
272
|
+
|
|
273
|
+
expect(findFormGroupsAsData().find((x) => x.label === TEST_FIELDS.evenCount.label)).toEqual({
|
|
274
|
+
label: TEST_FIELDS.evenCount.label,
|
|
275
|
+
invalidFeedback: 'Count must be even',
|
|
276
|
+
state: undefined,
|
|
277
|
+
input: {
|
|
278
|
+
...TEST_FIELDS.evenCount.inputAttrs,
|
|
279
|
+
id: 'gl-form-field-testunique',
|
|
280
|
+
value: '7',
|
|
281
|
+
},
|
|
282
|
+
});
|
|
283
|
+
});
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
describe('with valid values', () => {
|
|
287
|
+
beforeEach(() => {
|
|
288
|
+
const values = cloneDeep(TEST_VALUES);
|
|
289
|
+
|
|
290
|
+
createComponent({
|
|
291
|
+
values,
|
|
292
|
+
});
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
it('when form submits, emits submit', async () => {
|
|
296
|
+
await submitForm();
|
|
297
|
+
|
|
298
|
+
expect(wrapper.emitted('submit')).toEqual([[expect.any(Event)]]);
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
describe.each`
|
|
302
|
+
fieldName | inputValue | expectedValue
|
|
303
|
+
${'allCaps'} | ${'foo bar'} | ${'FOO BAR'}
|
|
304
|
+
${'evenCount'} | ${'123'} | ${123}
|
|
305
|
+
`(
|
|
306
|
+
'when input ("$fieldName") with mapValue changes',
|
|
307
|
+
({ fieldName, inputValue, expectedValue }) => {
|
|
308
|
+
beforeEach(() => {
|
|
309
|
+
const input = findInputFromLabel(TEST_FIELDS[fieldName].label);
|
|
310
|
+
input.vm.$emit('input', inputValue);
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
it('emits input with mapped value', () => {
|
|
314
|
+
expect(wrapper.emitted('input')).toEqual([
|
|
315
|
+
// Ignore initial inputted value (already tested)
|
|
316
|
+
expect.anything(),
|
|
317
|
+
[
|
|
318
|
+
{
|
|
319
|
+
...TEST_VALUES,
|
|
320
|
+
[fieldName]: expectedValue,
|
|
321
|
+
},
|
|
322
|
+
],
|
|
323
|
+
]);
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
it('emits input-field with mapped value', () => {
|
|
327
|
+
expect(wrapper.emitted('input-field')).toEqual([
|
|
328
|
+
[
|
|
329
|
+
{
|
|
330
|
+
name: fieldName,
|
|
331
|
+
value: expectedValue,
|
|
332
|
+
},
|
|
333
|
+
],
|
|
334
|
+
]);
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
);
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
describe('with scoped slot', () => {
|
|
341
|
+
beforeEach(() => {
|
|
342
|
+
createComponent(
|
|
343
|
+
{
|
|
344
|
+
values: {
|
|
345
|
+
evenCount: 5,
|
|
346
|
+
},
|
|
347
|
+
},
|
|
348
|
+
{
|
|
349
|
+
scopedSlots: {
|
|
350
|
+
'input(evenCount)':
|
|
351
|
+
'<button data-testid="test-custom-input" @click="props.input(props.value + 1)" @blur="props.blur">{{ props.value }}</button>',
|
|
352
|
+
},
|
|
353
|
+
}
|
|
354
|
+
);
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
it('renders scoped slot for field input', () => {
|
|
358
|
+
expect(findInputFromLabel(TEST_FIELDS.evenCount.label).exists()).toBe(false);
|
|
359
|
+
expect(findCustomInputFromLabel(TEST_FIELDS.evenCount.label).exists()).toBe(true);
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
it('passes down "blur" callback', async () => {
|
|
363
|
+
// what: We'll test this by emitting the "blur" we attached in the scopedSlot
|
|
364
|
+
// and asserting that validation was ran.
|
|
365
|
+
expect(
|
|
366
|
+
findFormGroupFromLabel(TEST_FIELDS.evenCount.label).attributes('invalid-feedback')
|
|
367
|
+
).toBe('');
|
|
368
|
+
|
|
369
|
+
findCustomInputFromLabel(TEST_FIELDS.evenCount.label).trigger('blur');
|
|
370
|
+
await nextTick();
|
|
371
|
+
|
|
372
|
+
expect(
|
|
373
|
+
findFormGroupFromLabel(TEST_FIELDS.evenCount.label).attributes('invalid-feedback')
|
|
374
|
+
).toBe('Count must be even');
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
it('passes down "input" callback', () => {
|
|
378
|
+
// what: We'll test this by checking that the input-field event
|
|
379
|
+
// is emitted when triggered by our scoped slot.
|
|
380
|
+
expect(wrapper.emitted('input-field')).toBeUndefined();
|
|
381
|
+
|
|
382
|
+
findCustomInputFromLabel(TEST_FIELDS.evenCount.label).trigger('click');
|
|
383
|
+
|
|
384
|
+
expect(wrapper.emitted('input-field')).toEqual([[{ name: 'evenCount', value: 6 }]]);
|
|
385
|
+
});
|
|
386
|
+
|
|
387
|
+
it('passes down "value"', () => {
|
|
388
|
+
expect(findCustomInputFromLabel(TEST_FIELDS.evenCount.label).text()).toEqual('5');
|
|
389
|
+
});
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
// why: We have to do some manual reactivity to optimize how often we call
|
|
393
|
+
// field validators. Let's test that here.
|
|
394
|
+
describe('validation performance', () => {
|
|
395
|
+
let validationSpy;
|
|
396
|
+
|
|
397
|
+
beforeEach(async () => {
|
|
398
|
+
validationSpy = jest.fn().mockReturnValue('Not valid!');
|
|
399
|
+
|
|
400
|
+
createComponent({
|
|
401
|
+
fields: mapValues(TEST_FIELDS, (field) => ({
|
|
402
|
+
...field,
|
|
403
|
+
validators: [validationSpy],
|
|
404
|
+
})),
|
|
405
|
+
});
|
|
406
|
+
|
|
407
|
+
// Trigger validation on all fields so that the fields are "dirty"
|
|
408
|
+
await submitForm();
|
|
409
|
+
|
|
410
|
+
// Clear validationSpy so we can assert on *new* validation calls
|
|
411
|
+
validationSpy.mockClear();
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
it('when input changes, only triggers validation for changed value', async () => {
|
|
415
|
+
expect(validationSpy).not.toHaveBeenCalled();
|
|
416
|
+
|
|
417
|
+
wrapper.setProps({ values: { username: 'root' } });
|
|
418
|
+
await nextTick();
|
|
419
|
+
|
|
420
|
+
expect(validationSpy).toHaveBeenCalledTimes(1);
|
|
421
|
+
expect(validationSpy).toHaveBeenCalledWith('root');
|
|
422
|
+
});
|
|
423
|
+
});
|
|
424
|
+
});
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import uniqueId from 'lodash/uniqueId';
|
|
2
|
+
import omit from 'lodash/omit';
|
|
3
|
+
import GlModal from '../../modal/modal.vue';
|
|
4
|
+
import GlButton from '../../button/button.vue';
|
|
5
|
+
import GlListbox from '../../new_dropdowns/listbox/listbox.vue';
|
|
6
|
+
import GlFormFields from './form_fields.vue';
|
|
7
|
+
import readme from './form_fields.md';
|
|
8
|
+
import { required } from './validators';
|
|
9
|
+
import { mapToNumber } from './mappers';
|
|
10
|
+
|
|
11
|
+
const Template = () => ({
|
|
12
|
+
ITEMS: ['Pizza', 'Keyboards', 'Guitars', 'Rocket ships'].map((text) => ({ text, value: text })),
|
|
13
|
+
components: { GlFormFields, GlButton, GlModal, GlListbox },
|
|
14
|
+
data() {
|
|
15
|
+
return {
|
|
16
|
+
// why: We declare fields here so that we can test what binding the
|
|
17
|
+
// "confirmPassword" validator to "this.formValues" would act
|
|
18
|
+
// like. In most cases, these can be constant and injected through
|
|
19
|
+
// `$options`.
|
|
20
|
+
fields: {
|
|
21
|
+
USERNAME: {
|
|
22
|
+
label: 'NAME (ALL CAPS)',
|
|
23
|
+
mapValue: (x) => x?.toUpperCase(),
|
|
24
|
+
validators: [required('NAME IS REQUIRED!!!')],
|
|
25
|
+
},
|
|
26
|
+
password: {
|
|
27
|
+
label: 'Password',
|
|
28
|
+
inputAttrs: { type: 'password' },
|
|
29
|
+
validators: [required('Password is required')],
|
|
30
|
+
},
|
|
31
|
+
confirmPassword: {
|
|
32
|
+
label: 'Confirm Password',
|
|
33
|
+
inputAttrs: { type: 'password' },
|
|
34
|
+
validators: [
|
|
35
|
+
required('Confirmed password is required'),
|
|
36
|
+
(confirmValue) =>
|
|
37
|
+
confirmValue !== this.formValues.password ? 'Must match password' : '',
|
|
38
|
+
],
|
|
39
|
+
},
|
|
40
|
+
custom: {
|
|
41
|
+
label: 'Custom input',
|
|
42
|
+
mapValue: mapToNumber,
|
|
43
|
+
validators: [(val) => (val < 1 ? 'Please click this at least once :)' : '')],
|
|
44
|
+
},
|
|
45
|
+
favoriteItem: {
|
|
46
|
+
label: 'Favorite Item (Optional)',
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
formValues: {},
|
|
50
|
+
testFormId: uniqueId('form_fields_story_'),
|
|
51
|
+
};
|
|
52
|
+
},
|
|
53
|
+
computed: {
|
|
54
|
+
values() {
|
|
55
|
+
return omit(this.formValues, ['confirmPassword']);
|
|
56
|
+
},
|
|
57
|
+
valuesJSON() {
|
|
58
|
+
// JSON doesn't allow undefined values
|
|
59
|
+
return JSON.stringify(this.values, (key, value) => (value === undefined ? null : value), 2);
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
methods: {
|
|
63
|
+
onSubmit() {
|
|
64
|
+
this.$refs.modal.show();
|
|
65
|
+
},
|
|
66
|
+
},
|
|
67
|
+
template: `
|
|
68
|
+
<div>
|
|
69
|
+
<h3>Fields</h3>
|
|
70
|
+
<form :id="testFormId" @submit.prevent>
|
|
71
|
+
<gl-form-fields :fields="fields" v-model="formValues" :form-id="testFormId" @submit="onSubmit">
|
|
72
|
+
<template #input(custom)="{ id, value, input, blur }">
|
|
73
|
+
<button :id="id" @click="input(value + 1)" @blur="blur" type="button">{{value}}</button>
|
|
74
|
+
</template>
|
|
75
|
+
<template #input(favoriteItem)="{ id, value, input, blur }">
|
|
76
|
+
<gl-listbox :id="id" :items="$options.ITEMS" :selected="value" @select="input" @hidden="blur" />
|
|
77
|
+
</template>
|
|
78
|
+
</gl-form-fields>
|
|
79
|
+
<gl-button type="submit" category="primary">Submit</gl-button>
|
|
80
|
+
</form>
|
|
81
|
+
<gl-modal ref="modal" modal-id="submission-modal" title="Form submission"><pre>{{ valuesJSON }}</pre></gl-modal>
|
|
82
|
+
</div>
|
|
83
|
+
`,
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
export const Default = Template.bind({});
|
|
87
|
+
|
|
88
|
+
export default {
|
|
89
|
+
title: 'base/form/form-fields',
|
|
90
|
+
component: GlFormFields,
|
|
91
|
+
parameters: {
|
|
92
|
+
knobs: {
|
|
93
|
+
disable: true,
|
|
94
|
+
},
|
|
95
|
+
docs: {
|
|
96
|
+
description: {
|
|
97
|
+
component: readme,
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
argTypes: {},
|
|
102
|
+
};
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
<script>
|
|
2
|
+
import isFunction from 'lodash/isFunction';
|
|
3
|
+
import mapValues from 'lodash/mapValues';
|
|
4
|
+
import uniqueId from 'lodash/uniqueId';
|
|
5
|
+
import GlFormGroup from '../form_group/form_group.vue';
|
|
6
|
+
import GlFormInput from '../form_input/form_input.vue';
|
|
7
|
+
import GlFormFieldValidator from './form_field_validator.vue';
|
|
8
|
+
|
|
9
|
+
export default {
|
|
10
|
+
name: 'GlFormFields',
|
|
11
|
+
components: {
|
|
12
|
+
GlFormGroup,
|
|
13
|
+
GlFormInput,
|
|
14
|
+
GlFormFieldValidator,
|
|
15
|
+
},
|
|
16
|
+
model: {
|
|
17
|
+
prop: 'values',
|
|
18
|
+
event: 'input',
|
|
19
|
+
},
|
|
20
|
+
props: {
|
|
21
|
+
/**
|
|
22
|
+
* Object of keys to FieldDefinitions.
|
|
23
|
+
* The shape of the keys will be the same for `values` and what's emitted by the `input` event.
|
|
24
|
+
*
|
|
25
|
+
* @typedef {object} FieldDefinition
|
|
26
|
+
* @template TValue=string
|
|
27
|
+
* @property {string} label - Label text to show for this field.
|
|
28
|
+
* @property {undefined | Object} inputAttrs - Properties that are passed to the actual input for this field.
|
|
29
|
+
* @property {undefined | function(string): TValue} mapValue - Function that maps the inputted string value to the field's actual value (e.g. a Number).
|
|
30
|
+
* @property {undefined | Array<function(TValue): string | undefined>=} validators - Collection of validator functions.
|
|
31
|
+
*
|
|
32
|
+
* @type {{ [key: string]: FieldDefinition }}
|
|
33
|
+
*/
|
|
34
|
+
fields: {
|
|
35
|
+
type: Object,
|
|
36
|
+
required: true,
|
|
37
|
+
},
|
|
38
|
+
/**
|
|
39
|
+
* The current value for each field, by key.
|
|
40
|
+
* Keys should match between `values` and `fields`.
|
|
41
|
+
*/
|
|
42
|
+
values: {
|
|
43
|
+
type: Object,
|
|
44
|
+
required: true,
|
|
45
|
+
},
|
|
46
|
+
/**
|
|
47
|
+
* The id of the form element to handle "submit" listening.
|
|
48
|
+
*/
|
|
49
|
+
formId: {
|
|
50
|
+
type: String,
|
|
51
|
+
required: true,
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
data() {
|
|
55
|
+
return {
|
|
56
|
+
fieldDirtyStatuses: {},
|
|
57
|
+
fieldValidations: {},
|
|
58
|
+
};
|
|
59
|
+
},
|
|
60
|
+
computed: {
|
|
61
|
+
formElement() {
|
|
62
|
+
return document.getElementById(this.formId);
|
|
63
|
+
},
|
|
64
|
+
fieldValidationProps() {
|
|
65
|
+
return mapValues(this.fields, (_, fieldName) => {
|
|
66
|
+
const invalidFeedback = this.fieldValidations[fieldName] || '';
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
invalidFeedback,
|
|
70
|
+
state: invalidFeedback ? false : null,
|
|
71
|
+
};
|
|
72
|
+
});
|
|
73
|
+
},
|
|
74
|
+
fieldValues() {
|
|
75
|
+
return mapValues(this.fields, (_, fieldName) => {
|
|
76
|
+
if (fieldName in this.values) {
|
|
77
|
+
return this.values[fieldName];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return this.getMappedValue(fieldName, undefined);
|
|
81
|
+
});
|
|
82
|
+
},
|
|
83
|
+
fieldNames() {
|
|
84
|
+
return Object.keys(this.fields);
|
|
85
|
+
},
|
|
86
|
+
fieldsToRender() {
|
|
87
|
+
return mapValues(this.fields, (field, fieldName) => {
|
|
88
|
+
const id = uniqueId('gl-form-field-');
|
|
89
|
+
|
|
90
|
+
const scopedSlotName = `input(${fieldName})`;
|
|
91
|
+
const hasScopedSlot = this.$scopedSlots[scopedSlotName];
|
|
92
|
+
const scopedSlotAttrs = hasScopedSlot && {
|
|
93
|
+
value: this.fieldValues[fieldName],
|
|
94
|
+
input: (val) => this.onFieldInput(fieldName, val),
|
|
95
|
+
blur: () => this.onFieldBlur(fieldName),
|
|
96
|
+
validation: this.fieldValidationProps[fieldName],
|
|
97
|
+
id,
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
return {
|
|
101
|
+
...field,
|
|
102
|
+
id,
|
|
103
|
+
label: field.label || fieldName,
|
|
104
|
+
scopedSlotName,
|
|
105
|
+
scopedSlotAttrs,
|
|
106
|
+
};
|
|
107
|
+
});
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
mounted() {
|
|
111
|
+
// why: We emit initial values as a convenience so that `v-model="values"` can be easily initialized.
|
|
112
|
+
this.$emit('input', this.fieldValues);
|
|
113
|
+
|
|
114
|
+
this.formElement?.addEventListener('submit', this.onFormSubmission);
|
|
115
|
+
},
|
|
116
|
+
destroyed() {
|
|
117
|
+
this.formElement?.removeEventListener('submit', this.onFormSubmission);
|
|
118
|
+
},
|
|
119
|
+
methods: {
|
|
120
|
+
setFieldDirty(fieldName) {
|
|
121
|
+
this.$set(this.fieldDirtyStatuses, fieldName, true);
|
|
122
|
+
},
|
|
123
|
+
setAllFieldsDirty() {
|
|
124
|
+
this.fieldNames.forEach((fieldName) => this.setFieldDirty(fieldName));
|
|
125
|
+
},
|
|
126
|
+
hasAllFieldsValid() {
|
|
127
|
+
// note: Only check "fieldNames" since "fields" could have changed since the life of "fieldValidations"
|
|
128
|
+
return this.fieldNames.every((fieldName) => !this.fieldValidations[fieldName]);
|
|
129
|
+
},
|
|
130
|
+
async checkBeforeSubmission() {
|
|
131
|
+
this.setAllFieldsDirty();
|
|
132
|
+
|
|
133
|
+
await this.$nextTick();
|
|
134
|
+
|
|
135
|
+
return this.hasAllFieldsValid();
|
|
136
|
+
},
|
|
137
|
+
getMappedValue(fieldName, val) {
|
|
138
|
+
const field = this.fields[fieldName];
|
|
139
|
+
|
|
140
|
+
if (isFunction(field?.mapValue)) {
|
|
141
|
+
return field.mapValue(val);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return val;
|
|
145
|
+
},
|
|
146
|
+
onFieldValidationUpdate(fieldName, invalidFeedback) {
|
|
147
|
+
this.$set(this.fieldValidations, fieldName, invalidFeedback);
|
|
148
|
+
},
|
|
149
|
+
onFieldBlur(fieldName) {
|
|
150
|
+
this.setFieldDirty(fieldName);
|
|
151
|
+
},
|
|
152
|
+
onFieldInput(fieldName, inputValue) {
|
|
153
|
+
const val = this.getMappedValue(fieldName, inputValue);
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Emitted when any of the form values change. Used by `v-model`.
|
|
157
|
+
*/
|
|
158
|
+
this.$emit('input', {
|
|
159
|
+
...this.values,
|
|
160
|
+
[fieldName]: val,
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Emitted when a form input emits the `input` event.
|
|
165
|
+
*/
|
|
166
|
+
this.$emit('input-field', {
|
|
167
|
+
name: fieldName,
|
|
168
|
+
value: val,
|
|
169
|
+
});
|
|
170
|
+
},
|
|
171
|
+
async onFormSubmission(e) {
|
|
172
|
+
e.preventDefault();
|
|
173
|
+
|
|
174
|
+
const isValid = await this.checkBeforeSubmission();
|
|
175
|
+
|
|
176
|
+
if (isValid) {
|
|
177
|
+
/**
|
|
178
|
+
* Emitted when the form is submitted and all of the form fields are valid.
|
|
179
|
+
*/
|
|
180
|
+
this.$emit('submit', e);
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
</script>
|
|
186
|
+
|
|
187
|
+
<template>
|
|
188
|
+
<div>
|
|
189
|
+
<gl-form-group
|
|
190
|
+
v-for="(field, fieldName) in fieldsToRender"
|
|
191
|
+
:key="fieldName"
|
|
192
|
+
:label="field.label"
|
|
193
|
+
:label-for="field.id"
|
|
194
|
+
:invalid-feedback="fieldValidationProps[fieldName].invalidFeedback"
|
|
195
|
+
:state="fieldValidationProps[fieldName].state"
|
|
196
|
+
>
|
|
197
|
+
<gl-form-field-validator
|
|
198
|
+
:value="fieldValues[fieldName]"
|
|
199
|
+
:validators="field.validators"
|
|
200
|
+
:should-validate="fieldDirtyStatuses[fieldName]"
|
|
201
|
+
@update="onFieldValidationUpdate(fieldName, $event)"
|
|
202
|
+
/>
|
|
203
|
+
<template v-if="field.scopedSlotAttrs">
|
|
204
|
+
<!-- @slot scoped slot that can be used for components other than `GlFormInput`. The name of the slot is `input(<fieldName>)`. -->
|
|
205
|
+
<slot :name="field.scopedSlotName" v-bind="field.scopedSlotAttrs"></slot>
|
|
206
|
+
</template>
|
|
207
|
+
<template v-else>
|
|
208
|
+
<gl-form-input
|
|
209
|
+
:id="field.id"
|
|
210
|
+
:value="fieldValues[fieldName]"
|
|
211
|
+
:state="fieldValidationProps[fieldName].state"
|
|
212
|
+
v-bind="field.inputAttrs"
|
|
213
|
+
@input="onFieldInput(fieldName, $event)"
|
|
214
|
+
@blur="onFieldBlur(fieldName)"
|
|
215
|
+
/>
|
|
216
|
+
</template>
|
|
217
|
+
</gl-form-group>
|
|
218
|
+
</div>
|
|
219
|
+
</template>
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// This contains core mapping behavior (like mapping to native JavaScript types)
|
|
2
|
+
// and**should not** contain domain-specific mappers.
|
|
3
|
+
//
|
|
4
|
+
// ```
|
|
5
|
+
// // Good
|
|
6
|
+
// export const mapToBoolean = ...
|
|
7
|
+
//
|
|
8
|
+
// // Bad
|
|
9
|
+
// export const mapToApolloCacheWidget = ...
|
|
10
|
+
// ```
|
|
11
|
+
export const mapToNumber = (x) => Number(x || 0);
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { mapToNumber } from './mappers';
|
|
2
|
+
|
|
3
|
+
describe('components/base/form/form_fields/mappers', () => {
|
|
4
|
+
describe('mapToNumber', () => {
|
|
5
|
+
it.each`
|
|
6
|
+
input | output
|
|
7
|
+
${''} | ${0}
|
|
8
|
+
${false} | ${0}
|
|
9
|
+
${{}} | ${Number.NaN}
|
|
10
|
+
${'888'} | ${888}
|
|
11
|
+
${'-5e10'} | ${-50000000000}
|
|
12
|
+
${'55.78'} | ${55.78}
|
|
13
|
+
`('with $input, returns $output', ({ input, output }) => {
|
|
14
|
+
expect(mapToNumber(input)).toBe(output);
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// This contains core validating behavior and **should not** contain
|
|
2
|
+
// domain-specific validations.
|
|
3
|
+
//
|
|
4
|
+
// Look to what's allowed in HTML attributes as a good basis for what belongs here
|
|
5
|
+
//
|
|
6
|
+
// ```
|
|
7
|
+
// // Good
|
|
8
|
+
// export const required = ...
|
|
9
|
+
//
|
|
10
|
+
// // Bad
|
|
11
|
+
// export const projectPathIsUnique = ...
|
|
12
|
+
// ```
|
|
13
|
+
export const factory = (failMessage, isValid) => (val) => !isValid(val) ? failMessage : '';
|
|
14
|
+
|
|
15
|
+
export const required = (failMessage) =>
|
|
16
|
+
factory(failMessage, (val) => val !== '' && val !== null && val !== undefined);
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { required } from './validators';
|
|
2
|
+
|
|
3
|
+
const TEST_FAIL_MESSAGE = 'Yo test failed!';
|
|
4
|
+
|
|
5
|
+
describe('components/base/form/form_fields/validators', () => {
|
|
6
|
+
// note: We used the `factory` to build required, so we implicitly test `factory` heere
|
|
7
|
+
describe('required', () => {
|
|
8
|
+
let validator;
|
|
9
|
+
|
|
10
|
+
beforeEach(() => {
|
|
11
|
+
validator = required(TEST_FAIL_MESSAGE);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it.each`
|
|
15
|
+
input | output
|
|
16
|
+
${''} | ${TEST_FAIL_MESSAGE}
|
|
17
|
+
${null} | ${TEST_FAIL_MESSAGE}
|
|
18
|
+
${undefined} | ${TEST_FAIL_MESSAGE}
|
|
19
|
+
${'123'} | ${''}
|
|
20
|
+
${{}} | ${''}
|
|
21
|
+
${0} | ${''}
|
|
22
|
+
${1} | ${''}
|
|
23
|
+
${true} | ${''}
|
|
24
|
+
${false} | ${''}
|
|
25
|
+
`('with $input, returns $output', ({ input, output }) => {
|
|
26
|
+
expect(validator(input)).toBe(output);
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
});
|
package/src/index.js
CHANGED
|
@@ -44,6 +44,7 @@ export { default as GlFormRadioGroup } from './components/base/form/form_radio_g
|
|
|
44
44
|
export { default as GlFormSelect } from './components/base/form/form_select/form_select.vue';
|
|
45
45
|
export { default as GlFormTextarea } from './components/base/form/form_textarea/form_textarea.vue';
|
|
46
46
|
export { default as GlFormGroup } from './components/base/form/form_group/form_group.vue';
|
|
47
|
+
export { default as GlFormFields } from './components/base/form/form_fields/form_fields.vue';
|
|
47
48
|
export { default as GlSearchBoxByType } from './components/base/search_box_by_type/search_box_by_type.vue';
|
|
48
49
|
export { default as GlSearchBoxByClick } from './components/base/search_box_by_click/search_box_by_click.vue';
|
|
49
50
|
export { default as GlDropdownItem } from './components/base/dropdown/dropdown_item.vue';
|
package/src/utils.js
CHANGED