All files / src/components/zd-form form.ts

100% Statements 92/92
100% Branches 25/25
100% Functions 27/27
100% Lines 81/81

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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331  93x             93x                                           33x           33x           33x           33x           33x           33x                                                             33x   33x                                               78x       3x 6x 2x   4x                 1x 2x                 6x 6x 6x 18x   1x                     1x           33x   33x   33x     3x   3x 3x 3x     3x 1x     2x 2x     1x       3x   3x 3x 3x     3x 1x     2x 2x     1x                 2x 2x   2x 7x 3x 3x   2x 2x 2x     4x 3x 3x   2x 2x 2x     1x     2x       4x   3x   1x             3x 3x 4x 4x   3x             14x 2x   12x                             2x             1x                 2x               1x 1x       2x               2x 1x     1x      
import { IDictionary } from '@zeedhi/core';
import { ComponentRender } from '../zd-component/component-render';
import { Input } from '../zd-input/input';
import { IForm, IFormComponent, IFormEvents, IFormGrid } from './interfaces';
 
/**
 * Base class for Form component.
 */
export class Form extends ComponentRender implements IForm {
	/**
	 * Children component structure if the component has children.
	 */
	public declare children: IFormComponent[];
 
	/**
	 * Applies the align-items css property.
	 * Available options are start, center, end, space-between, space-around and stretch.
	 */
	public align?: string;
 
	/**
	 * Applies the justify-content css property.
	 * Available options are start, center, end, space-between and space-around.
	 */
	public justify?: string;
 
	/**
	 * Defines the component height. Possible values for this property can be
	 * <samp>'auto', '100%', '400px' or 400</samp>
	 */
	public height: string | number = 'auto';
 
	/**
	 * Defines the component min height. Possible values for this property can be
	 * <samp>'auto', '100%', '400px' or 400</samp>
	 */
	public minHeight: string | number = 'auto';
 
	/**
	 * Defines the component max height. Possible values for this property can be
	 * <samp>'auto', '100%', '400px' or 400</samp>
	 */
	public maxHeight: string | number = 'none';
 
	/**
	 * Defines the component width. Possible values for this property can be
	 * <samp>'auto', '100%', '400px' or 400</samp>
	 */
	public width: string | number = '100%';
 
	/**
	 * Defines the component min width. Possible values for this property can be
	 * <samp>'auto', '100%', '400px' or 400</samp>
	 */
	public minWidth: string | number = 'auto';
 
	/**
	 * Defines the component max height. Possible values for this property can be
	 * <samp>'auto', '100%', '400px' or 400</samp>
	 */
	public maxWidth: string | number = 'none';
 
	/**
	 * Defines form events.
	 */
	public declare events: IFormEvents;
 
	/**
	 * Optional validation method assigned by view layer.
	 */
	private viewValidate?: () => Promise<{
		valid: boolean;
		errors: {
			id: string | number;
			errorMessages: string[];
		}[];
	}>;
 
	/**
	 * Optional submit method.
	 */
	public submitFunction?: () => void;
 
	/**
	 * Reset validation method assigned by view layer.
	 */
	private viewResetValidation?: () => void;
 
	/**
	 * Children components that are Inputs.
	 */
	private inputs: IDictionary<Input> = {};
 
	private internalValue: IDictionary = {};
 
	/* istanbul ignore next */
	/**
	 * Creates a new Form.
	 * @param props Form properties
	 */
	constructor(props: IForm) {
		super(props);
		this.align = this.getInitValue('align', props.align, this.align);
		this.justify = this.getInitValue('justify', props.justify, this.justify);
		this.height = this.getInitValue('height', props.height, this.height);
		this.minHeight = this.getInitValue('minHeight', props.minHeight, this.minHeight);
		this.maxHeight = this.getInitValue('maxHeight', props.maxHeight, this.maxHeight);
		this.width = this.getInitValue('width', props.width, this.width);
		this.minWidth = this.getInitValue('minWidth', props.minWidth, this.minWidth);
		this.maxWidth = this.getInitValue('maxWidth', props.maxWidth, this.maxWidth);
		this.internalValue = this.getInitValue('value', props.value, this.value);
	}
 
	/**
	 * Form value.
	 */
	get value() {
		return this.internalValue;
	}
 
	set value(value: IDictionary) {
		Object.keys(value).forEach((key) => {
			if (this.inputs[key]) {
				this.inputs[key].value = value[key];
			} else {
				this.internalValue[key] = value[key];
			}
		});
	}
 
	/**
	 * Clear all form inputs
	 */
	public clearForm() {
		Object.keys(this.value).forEach((item) => {
			this.value[item] = null;
		});
	}
 
	/**
	 * Saves input instance and defines property on form value.
	 * @param component Children component
	 */
	public registerInput(component: Input) {
		this.inputs[component.name] = component;
		component.value = this.value[component.name] || component.value;
		Object.defineProperty(this.value, component.name, {
			get: () => component.value,
			set: (value: any) => {
				component.value = value;
			},
			enumerable: true,
			configurable: true,
		});
	}
 
	/**
	 * Children props without grid system.
	 */
	get childrenProps() {
		return this.children.map(({ grid, ...otherAttrs }) => otherAttrs);
	}
 
	/**
	 * Checks if the value matches a col value (1, 2, ... 12) or auto
	 */
	private matchColumn = (value: string) => (!Number.isNaN(Number(value)) || value === 'auto');
 
	private breakpoints = ['lg', 'md', 'sm', 'xl', 'xxl'] as const;
 
	private matchBreakpoint = (value: string): value is typeof this.breakpoints[number] => (this.breakpoints.includes(value as any))
 
	private handleColClass(cssClass: string): { key: keyof IFormGrid, value: string } | null {
		const dataString = cssClass.replace('zd-col-', '');
 
		const splittedData = dataString.split('-');
		const firstData = splittedData[0];
		const secondData = splittedData[1];
 
		// in this case the class is zd-col-{n} or zd-col-auto
		if (this.matchColumn(firstData)) {
			return { key: 'cols', value: firstData };
		}
 
		const matchWithBreakpoints = this.matchBreakpoint(firstData) && this.matchColumn(secondData);
		if (!matchWithBreakpoints) return null;
 
		// in this case the class is zd-col-{breakpoint}-{n} or zd-col-{breakpoint}-auto
		return { key: firstData, value: secondData };
	}
 
	private handleOffsetClass(cssClass: string): { key: keyof IFormGrid, value: string } | null {
		const dataString = cssClass.replace('zd-offset-', '');
 
		const splittedData = dataString.split('-');
		const firstData = splittedData[0];
		const secondData = splittedData[1];
 
		// in this case the class is zd-offset-{n} or zd-offset-auto
		if (this.matchColumn(firstData)) {
			return { key: 'offset', value: firstData };
		}
 
		const matchWithBreakpoints = this.matchBreakpoint(firstData) && this.matchColumn(secondData);
		if (!matchWithBreakpoints) return null;
 
		// in this case the class is zd-offset-{breakpoint}-{n} or zd-offset-{breakpoint}-auto
		return { key: `offset-${firstData}`, value: secondData };
	}
 
	/**
	 * This method searches in a css class string to find classes related to grid cols \
	 * Parses all of the grid cols classes found to form grid object entries, for example
	 * the following class: 'zd-col-sm-12 zd-col-md-6' will become { sm: '12', md: '6' }
	 */
	private parseGridClasses(classes: string) {
		const classesArray = classes.split(' ');
		const gridObject: IFormGrid = {};
 
		classesArray.forEach((cssClass) => {
			if (cssClass.startsWith('zd-col-')) {
				const result = this.handleColClass(cssClass);
				if (!result) return;
 
				const { key, value } = result;
				gridObject[key] = value;
				return;
			}
 
			if (cssClass.startsWith('zd-offset-')) {
				const result = this.handleOffsetClass(cssClass);
				if (!result) return;
 
				const { key, value } = result;
				gridObject[key] = value;
				return;
			}
 
			return;
		});
 
		return gridObject;
	}
 
	private getChildGrid(child: IFormComponent) {
		if (child.grid && Object.keys(child.grid).length > 0) return child.grid;
 
		if (child.cssClass) return this.parseGridClasses(child.cssClass);
 
		return {};
	}
 
	/**
	 * Grid system for each child.
	 */
	get childrenGrid() {
		const childrenGrid: IDictionary<IFormGrid> = {};
		this.children.forEach((child) => {
			const grid = this.getChildGrid(child);
			childrenGrid[child.name] = { cols: '3', ...grid };
		});
		return childrenGrid;
	}
 
	/**
	 * Validates form.
	 */
	public validate() {
		if (this.viewValidate) {
			return this.viewValidate();
		}
		return Promise.resolve({ valid: Object.values(this.inputs).every((input) => input.isValid()) });
	}
 
	/**
	 * Sets view validation method.
	 */
	public setViewValidate(
		viewValidate: () => Promise<{
			valid: boolean;
			errors: {
				id: string | number;
				errorMessages: string[];
			}[];
		}>,
	) {
		this.viewValidate = viewValidate;
	}
 
	/**
	 * Sets view reset validation method.
	 */
	public setViewResetValidation(viewResetValidation: () => void) {
		this.viewResetValidation = viewResetValidation;
	}
 
	/**
	 * Triggered when form is submitted and it's valid.
	 * @param event DOM Event
	 * @param element Form component
	 */
	public callSubmitEvent(event: Event, element: any) {
		this.callEvent('submit', { event, element, component: this });
	}
 
	/**
	 * Triggered when the component is mounted.
	 * @param element Element mounted reference
	 */
	public onMounted(element: any) {
		super.onMounted(element);
		this.submitFunction = (element as any).requestSubmit?.bind(element);
	}
 
	public submit() {
		if (this.submitFunction) this.submitFunction();
	}
 
	/**
	 * Reset all form validation errors.
	 * @throws Will throw if viewResetValidation is undefined
	 */
	public resetValidation() {
		if (this.viewResetValidation) {
			return this.viewResetValidation();
		}
 
		throw new Error('viewResetValidation method not assigned');
	}
}