All files / src/components/FormField/mixins fieldComponent.ts

100% Statements 21/21
100% Branches 2/2
100% Functions 5/5
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 648x 8x       8x 8x   8x                   8x                 8x 8x 17x                 8x 2x   2x             2x 2x                   8x 1x   8x  
import Vue, { PropType } from 'vue';
import Component, { mixins } from 'vue-class-component';
 
import { Field, FieldValue, FieldOptions } from '../types';
 
import { deepCopy } from '@cnamts/vue-dot/src/helpers/deepCopy';
import { deepRemoveKeys } from '@cnamts/vue-dot/src/helpers/deepRemoveKeys';
 
const Props = Vue.extend({
	props: {
		/** The field to display */
		field: {
			type: Object as PropType<Field>,
			required: true
		}
	}
});
 
const MixinsDeclaration = mixins(Props);
 
/** Share code between field components */
@Component({
	model: {
		prop: 'field',
		event: 'change'
	}
})
export class FieldComponent extends MixinsDeclaration {
	get fieldOptions(): FieldOptions | undefined {
		return this.field.fieldOptions;
	}
 
	/**
	 * Update the v-model by emitting 'change' event
	 *
	 * @param {FieldValue} value The updated field
	 * @returns {void}
	 */
	emitChangeEvent(value: FieldValue): void {
		const fieldOptions = this.fieldOptions ? this.clearErrorMessages(deepCopy(this.fieldOptions)) : undefined;
 
		const updatedField = {
			...this.field,
			fieldOptions,
			value
		};
 
		// Emit in next tick to respect event order
		this.$nextTick(() => {
			this.$emit('change', updatedField);
		});
	}
 
	/**
	 * Clear all ErrorMessages in fieldOptions
	 *
	 * @param {FieldOptions} fieldOptions The field fieldOptions
	 * @returns {FieldOptions} The new field fieldOptions without errorMessages
	 */
	clearErrorMessages(fieldOptions: FieldOptions): FieldOptions {
		return deepRemoveKeys(fieldOptions, 'errorMessages');
	}
}