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

100% Statements 96/96
100% Branches 32/32
100% Functions 25/25
100% Lines 94/94

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 33194x                 94x           94x   1860x     1860x     1860x     1860x             1860x     1860x     1860x     1860x     1860x           1860x     1860x               1860x                       1860x     1860x     1860x               1860x                 1860x 1860x 1860x 1860x 1860x 1860x 1860x 1860x 1860x 1860x 1860x 1860x 1860x 1860x 1860x 1860x 1860x 1860x 1860x   1860x 2x         1x       2x 1x     1x                       74063x 74063x 1x 74062x 3564x 3564x   74063x         1949x                 3x 5x 2x   3x       3x         1080x 1080x 150x   930x               1x               2x 2x 1x 1x                   2x 2x 1x   1x               6x         356x 356x 356x 6x   356x         2x               256x 103x   256x         23x 1x   23x         2x 2x                 29x                         82x 82x                 60x 60x       2x               2x               2x               2x              
import {
	AccessorManager,
	IAccessorManager,
	IDictionary,
	IKeyMap,
	Metadata,
	Event as ZdEvent,
	KeyMap as ZdKeyMap,
} from '@zeedhi/core';
import { ChildNotFoundError } from './child-not-found';
import { IComponent, IComponentDirectives, IComponentEvents, IComponentInstance } from './interfaces';
 
/**
 * Base class for all Zeedhi components.
 */
export class Component<T extends IComponent = IComponent> implements IComponentInstance {
	// Allow the component to be duplicated without warning.
	public allowDuplicate = false;
 
	// Automatically add focus to input when it's created.
	public autofocus = false;
 
	// Children component structure if the component has children.
	public children: IComponent[] = [];
 
	// All children instances if the component has children
	public childrenInstances: any[] = [];
 
	/**
	 * CSS classes to be added to the DOM element when rendering.
	 * To apply multiple CSS classes use space as separator
	 * (e.g. <samp>\"class1 class2\"</samp>).
	 */
	public cssClass = '';
 
	// Set css in line with cssStyle.
	public cssStyle: string | IDictionary<string> = '';
 
	// Directives registered to the component.
	public directives: IComponentDirectives = {};
 
	// Events registered to the component.
	public events: IComponentEvents = {};
 
	// Controls component visibility.
	public isVisible = true;
 
	// Defines component name.
	public name!: string;
 
	// Applies the dark theme variant to the component.
	public dark = false; // deprecated
 
	// Applies the light theme variant to the component.
	public light = false; // deprecated
 
	// Overwrite the default theme.
	public theme?: string;
 
	/**
	 * Set component height to fill all space available
	 */
	public fillHeight: boolean | string = false;
 
	/**
	 * Parent component instance. This property should be used when is
	 * necessary create dynamic components.
	 */
	public parent?: IComponentInstance;
 
	// Define if the component id.
	public componentId!: number;
 
	// Define component key mapping
	public keyMap: IKeyMap = {};
 
	// Return if component has focus
	public isFocused = false;
 
	// Return if component can receive focus using tab
	public tabStop = true;
 
	// Properties accessors to controller.
	private accessorManager!: IAccessorManager;
 
	// Sets view focus method.
	protected viewFocus?: () => void;
 
	public userProperties: IDictionary<any> = {};
 
	protected props: T;
 
	/**
	 * Creates a new Component.
	 * @param props Components properties
	 */
	constructor(props: T) {
		this.props = { ...props };
		this.accessorManager = new AccessorManager();
		this.parent = props.parent;
		this.name = props.name;
		this.events = ZdEvent.factory(props.events || this.events);
		this.allowDuplicate = this.getInitValue('allowDuplicate', props.allowDuplicate, this.allowDuplicate);
		this.autofocus = this.getInitValue('autofocus', props.autofocus, this.autofocus);
		this.cssClass = this.getInitValue('cssClass', props.cssClass, this.cssClass);
		this.cssStyle = this.getInitValue('cssStyle', props.cssStyle, this.cssStyle);
		this.directives = this.getInitValue('directives', props.directives, this.directives);
		this.isVisible = this.getInitValue('isVisible', props.isVisible, this.isVisible);
		this.dark = this.getInitValue('dark', props.dark, this.dark); // deprecated
		this.light = this.getInitValue('light', props.light, this.light); // deprecated
		this.theme = this.getInitValue('theme', props.theme, this.theme);
		this.tabStop = this.getInitValue('tabStop', props.tabStop, this.tabStop);
		this.children = Array.isArray(props.children) ? props.children : this.children;
		this.keyMap = ZdKeyMap.factory(props.keyMap || this.keyMap);
		this.fillHeight = this.getInitValue('fillHeight', props.fillHeight, this.fillHeight);
		this.userProperties = this.getInitValue('userProperties', props.userProperties, this.userProperties);
 
		for (const directive in this.directives) {
			this.directives[directive] = ZdEvent.factory(this.directives[directive] || {});
		}
	}
 
	public setViewFocus(viewFocus: () => void) {
		this.viewFocus = viewFocus;
	}
 
	public setFocus() {
		if (this.viewFocus) {
			return this.viewFocus();
		}
 
		throw new Error('viewFocus method not assigned');
	}
 
	/**
	 * Retrieves initial value for the attribute and if it is an accessor,
	 * updates props value.
	 * @param name Attribute name
	 * @param value Attribute value
	 * @param defaultValue Attribute default value
	 * @returns Initial value
	 */
	protected getInitValue(name: string, value: any, defaultValue: any) {
		let returnValue = defaultValue;
		if (this.accessorManager.hasAccessor(name)) {
			returnValue = (this as any)[name];
		} else if (typeof value !== 'undefined') {
			returnValue = value;
			this.accessorManager.addProp(name, value);
		}
		return returnValue;
	}
 
	// Creates all accessors based on props value.
	protected createAccessors() {
		this.accessorManager.createAccessors(this);
	}
 
	/**
	 * Creates the accessors defined inside an object recursively
	 * @param obj Object having the accessors
	 * @param path Name of the `obj` property inside the component
	 */
	protected createObjAccessors(obj: any, path: string) {
		for (const key in obj) {
			if (obj[key] instanceof Object) {
				this.createObjAccessors(obj[key], `${path}.${key}`);
			} else {
				this.accessorManager.addProp(`${path}.${key}`, obj[key]);
			}
		}
 
		this.createAccessors();
	}
 
	/** Test and trigger an event */
	public callEvent(eventName: string, args: any) {
		const event = this.events[eventName];
		if (event && typeof event === 'function') {
			return !!event(args);
		}
		return false;
	}
 
	/**
	 * Adds a new child
	 * @param child Child component structure
	 */
	public addChild(child: IComponent) {
		this.children.push(child);
	}
 
	/**
	 * Removes child by name
	 * @param name Child name
	 */
	public removeChild(name: string) {
		const index = this.children.findIndex((child) => child.name === name);
		if (index !== -1) {
			this.children.splice(index, 1);
			this.childrenInstances.splice(index, 1);
		}
	}
 
	/**
	 * Retrieves a child instance by name
	 * @param name Child name
	 * @throws Will throw if child not exists
	 */
	public getChildInstance<T>(name: string): T {
		const child = this.childrenInstances.find((item) => item.name === name);
		if (child) {
			return child;
		}
		throw new ChildNotFoundError(name, this.name);
	}
 
	/**
	 * Adds new child instance
	 * @param instance Child instance
	 */
	public addChildInstance(instance: Component) {
		this.childrenInstances.push(instance);
	}
 
	// Triggered when the component is created.
	public onCreated() {
		this.createAccessors();
		this.componentId = Metadata.addInstance(this, this.allowDuplicate);
		if (this.parent) {
			this.parent.addChildInstance(this);
		}
		this.callEvent('onCreated', { component: this });
	}
 
	// Triggered before component is mounted.
	public onBeforeMount() {
		this.callEvent('onBeforeMount', { component: this });
	}
 
	/**
	 * Triggered when the component is mounted.
	 * @param element Element mounted reference
	 */
	public onMounted(element: any) {
		if (Object.keys(this.keyMap).length) {
			ZdKeyMap.bind(this.keyMap, this, element);
		}
		this.callEvent('onMounted', { element, component: this });
	}
 
	// Triggered before the component is destroyed.
	public onBeforeDestroy() {
		if (Object.keys(this.keyMap).length) {
			ZdKeyMap.unbind(this.keyMap, this);
		}
		this.callEvent('onBeforeDestroy', { component: this });
	}
 
	// Triggered when the component is destroyed.
	public onDestroyed() {
		Metadata.clearInstance(this.name, this.componentId);
		this.callEvent('onDestroyed', { component: this });
	}
 
	/**
	 * Triggered when the component is clicked.
	 * @param event DOM event
	 * @param element Element clicked
	 */
	public click(event?: Event, element?: any) {
		this.callEvent('click', {
			event: event || new MouseEvent('click'),
			element: element,
			component: this,
		});
	}
 
	/**
	 * Triggered when the component is focused.
	 * @param event DOM event
	 * @param element Element focused
	 */
	public focus(event: Event, element: any) {
		this.isFocused = true;
		this.callEvent('focus', { event, element, component: this });
	}
 
	/**
	 * Triggered when the component loses focus.
	 * @param event DOM event
	 * @param element Element that lost the focus
	 */
	public blur(event: Event, element: any) {
		this.isFocused = false;
		this.callEvent('blur', { event, element, component: this });
	}
 
	public mouseenter(event?: Event, element?: any) {
		this.callEvent('mouseenter', {
			event: event || new MouseEvent('mouseenter'),
			element: element,
			component: this,
		});
	}
 
	public mouseleave(event?: Event, element?: any) {
		this.callEvent('mouseleave', {
			event: event || new MouseEvent('mouseleave'),
			element: element,
			component: this,
		});
	}
 
	public mouseout(event?: Event, element?: any) {
		this.callEvent('mouseout', {
			event: event || new MouseEvent('mouseout'),
			element: element,
			component: this,
		});
	}
 
	public mouseover(event?: Event, element?: any) {
		this.callEvent('mouseover', {
			event: event || new MouseEvent('mouseover'),
			element: element,
			component: this,
		});
	}
}