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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 | 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 2x 11x 11x 2x 11x 2x 11x 11x 11x 11x 45x 45x 45x 644x 45x 11x 13x 13x 11x 11x 11x 11x 11x 11x 11x 4x 4x 11x | /**
* @module module:lib/helpers/utils
* @description General helper utilities used across the library.
* @summary Exposes small, reusable utility functions for window/document access, date handling,
* string manipulation, simple mapping helpers and environment helpers used by UI components
* and services. This module's functions include `getWindow`, `getWindowDocument`, `formatDate`,
* `isValidDate`, `itemMapper`, `dataMapper`, and event helpers like `windowEventEmitter`.
*
* Do not document individual exports here — functions are documented inline.
* @link {@link getWindow}
*/
import { isDevMode } from '@angular/core';
import { InjectableRegistryImp, InjectablesRegistry } from '@decaf-ts/injectable-decorators';
import { Primitives } from '@decaf-ts/decorator-validation';
import { KeyValue, StringOrBoolean, } from '../engine/types';
import { FunctionLike } from '../engine/types';
import { getLogger } from '../for-angular-common.module';
let injectableRegistry: InjectablesRegistry;
/**
* @description Retrieves the singleton instance of the injectables registry
* @summary This function implements the singleton pattern for the InjectablesRegistry.
* It returns the existing registry instance if one exists, or creates a new instance
* if none exists. The registry is used to store and retrieve injectable dependencies
* throughout the application.
*
* @return {InjectablesRegistry} The singleton injectables registry instance
*
* @function getInjectablesRegistry
* @memberOf module:for-angular
*/
export function getInjectablesRegistry(): InjectablesRegistry {
Iif (!injectableRegistry)
injectableRegistry = new InjectableRegistryImp();
return injectableRegistry;
}
/**
* @description Determines if the application is running in development mode
* @summary This function checks whether the application is currently running in a development
* environment. It uses Angular's isDevMode() function and also checks the window context
* and hostname against the provided context parameter. This is useful for enabling
* development-specific features or logging.
*
* @param {string} [context='localhost'] - The context string to check against the current environment
* @return {boolean} True if the application is running in development mode, false otherwise
*
* @function isDevelopmentMode
* @memberOf module:for-angular
*/
export function isDevelopmentMode(context: string = 'localhost'): boolean {
Iif (!context)
return isDevMode();
const win = getWindow();
return (
isDevMode() ||
win?.['env']?.['CONTEXT'].toLowerCase() !== context.toLowerCase() ||
win?.['location']?.hostname?.includes(context)
);
}
/**
* @description Dispatches a custom event to the document window
* @summary This function creates and dispatches a custom event to the browser window.
* It's useful for cross-component communication or for triggering application-wide events.
* The function allows specifying the event name, detail data, and additional event properties.
*
* @param {string} name - The name of the custom event to dispatch
* @param {unknown} detail - The data to include in the event's detail property
* @param {object} [props] - Optional additional properties for the custom event
* @return {void}
*
* @function windowEventEmitter
* @memberOf module:for-angular
*/
export function windowEventEmitter(
name: string,
detail: unknown,
props?: object
): void {
const data = Object.assign(
{
bubbles: true,
composed: true,
cancelable: false,
detail: detail,
},
props || {}
);
(getWindow() as Window).dispatchEvent(new CustomEvent(name, data));
}
/**
* @description Retrieves a property from the window's document object
* @summary This function provides a safe way to access properties on the window's document object.
* It uses the getWindowDocument function to get a reference to the document, then accesses
* the specified property. This is useful for browser environment interactions that need
* to access document properties.
*
* @param {string} key - The name of the property to retrieve from the document object
* @return {any} The value of the specified property, or undefined if the document or property doesn't exist
*
* @function getOnWindowDocument
* @memberOf module:for-angular
*/
export function getOnWindowDocument(key: string): Document | undefined {
const doc = getWindowDocument()?.[key as keyof Document];
return doc instanceof Document ?
doc : undefined;
}
/**
* @description Retrieves the document object from the window
* @summary This function provides a safe way to access the document object from the window.
* It uses the getOnWindow function to retrieve the 'document' property from the window object.
* This is useful for browser environment interactions that need access to the document.
*
* @return {Document | undefined} The window's document object, or undefined if it doesn't exist
*
* @function getWindowDocument
* @memberOf module:for-angular
*/
export function getWindowDocument(): Document | undefined {
return getOnWindow('document') as Document;
}
/**
* @description Retrieves a property from the window object
* @summary This function provides a safe way to access properties on the window object.
* It uses the getWindow function to get a reference to the window, then accesses
* the specified property. This is useful for browser environment interactions that need
* to access window properties or APIs.
*
* @param {string} key - The name of the property to retrieve from the window object
* @return {unknown | undefined} The value of the specified property, or undefined if the window or property doesn't exist
*
* @function getOnWindow
* @memberOf module:for-angular
*/
export function getOnWindow(key: string): unknown | undefined {
return getWindow()?.[key];
}
/**
* @description Sets a property on the window object
* @summary This function provides a way to set properties on the window object.
* It uses the getWindow function to get a reference to the window, then sets
* the specified property to the provided value. This is useful for storing
* global data or functions that need to be accessible across the application.
*
* @param {string} key - The name of the property to set on the window object
* @param {any} value - The value to assign to the property
* @return {void}
*
* @function setOnWindow
* @memberOf module:for-angular
*/
export function setOnWindow(key: string, value: unknown): void {
getWindow()[key] = value;
}
/**
* @description Retrieves the global window object
* @summary This function provides a safe way to access the global window object.
* It uses globalThis to ensure compatibility across different JavaScript environments.
* This is the core function used by other window-related utility functions to
* access the window object.
*
* @return {Window} The global window object
*
* @function getWindow
* @memberOf module:for-angular
*/
export function getWindow(): Window & KeyValue {
return (globalThis as KeyValue)?.['window'] as Window & KeyValue;
}
/**
* @description Retrieves the width of the browser window
* @summary This function provides a convenient way to get the current width of the browser window.
* It uses the getOnWindow function to access the 'innerWidth' property of the window object.
* This is useful for responsive design implementations and viewport-based calculations.
*
* @return {number | undefined} The current width of the browser window in pixels
*
* @function getWindowWidth
* @memberOf module:for-angular
*/
export function getWindowWidth(): number {
return getOnWindow('innerWidth') as number || 0;
}
/**
* @description Checks if a value is not undefined
* @summary This utility function determines whether a given value is not undefined.
* It's a simple wrapper that makes code more readable when checking for defined values.
* The function is particularly useful for checking StringOrBoolean properties that might be undefined.
*
* @param {StringOrBoolean | undefined} prop - The property to check
* @return {boolean} True if the property is not undefined, false otherwise
*
* @function isNotUndefined
* @memberOf module:for-angular
*/
export function isNotUndefined(prop: StringOrBoolean | undefined): boolean {
return (prop !== undefined) as boolean;
}
/**
* @description Generates a locale string from a class name or instance
* @summary This utility function converts a class name or instance into a locale string
* that can be used for internationalization purposes. It handles different input types
* (string, function, or object) and applies formatting rules to generate a consistent
* locale identifier. For short names (less than 3 parts), it reverses the dot-separated
* string. For longer names, it uses the last part as a prefix and joins the rest with
* underscores.
*
* @param {string|FunctionLike|object} instance - The input to generate the locale from (class name, constructor, or instance)
* @param {string} [suffix] - Optional string to append to the instance name before processing
* @return {string} A formatted locale string derived from the input
*
* @function getLocaleFromClassName
* @memberOf module:for-angular
*/
export function getLocaleFromClassName(
instance: string | FunctionLike | KeyValue,
suffix?: string
): string {
Iif (typeof instance !== Primitives.STRING)
instance = (instance as FunctionLike).name || (instance as object)?.constructor?.name;
let name: string | string[] = instance as string;
Iif (suffix)
name = `${instance}${suffix.charAt(0).toUpperCase() + suffix.slice(1)}`;
name = name.replace(/_|-/g, '').replace(/(?:^\w|[A-Z]|\b\w)/g, (word: string, index: number) => {
Iif (index > 1) word = '.' + word;
return word.toLowerCase();
}).split('.');
Iif (name.length < 3)
return name.reverse().join('.');
const preffix = name[name.length - 1];
name.pop();
name = name.join('_');
return `${preffix}.${name}`;
}
/**
* @description Retrieves the current locale language
* @summary This utility function gets the current locale language based on the user's browser settings.
* It provides a consistent way to access the user's language preference throughout the application.
* The function returns the browser's navigator.language value, defaulting to 'en' if not available.
*
* @return {string} The current locale language (e.g., 'en', 'fr')
*
* @function getLocaleLanguage
* @memberOf module:for-angular
*/
export function getLocaleLanguage(): string {
const win = getWindow();
return (win as Window).navigator.language || "en";
// return win?.[WINDOW_KEYS.LANGUAGE_SELECTED] || (win.navigator.language || '').split('-')[0] || "en";
}
/**
* @description Generates a random string or number of specified length
* @summary This utility function creates a random string of a specified length.
* It can generate either alphanumeric strings (including uppercase and lowercase letters)
* or numeric-only strings. This is useful for creating random IDs, temporary passwords,
* or other random identifiers throughout the application.
*
* @param {number} [length=8] - The length of the random value to generate
* @param {boolean} [onlyNumbers=false] - Whether to generate only numeric characters
* @return {string} A randomly generated string of the specified length and character set
*
* @function generateRandomValue
* @memberOf module:for-angular
*/
export function generateRandomValue(length: number = 8, onlyNumbers: boolean = false): string {
const chars = onlyNumbers
? '0123456789'
: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++)
result += chars.charAt(Math.floor(Math.random() * chars.length));
return result;
}
/**
* Converts a string representation of a boolean or a boolean value to a boolean type.
*
* @export
* @param {('true' | 'false' | boolean)} prop - The value to convert. Can be the string 'true', 'false', or a boolean.
* @returns {boolean} The boolean representation of the input value. Returns true if the input is the string 'true' or boolean true, false otherwise.
*/
export function stringToBoolean(prop: 'true' | 'false' | boolean): boolean {
Iif(typeof prop === 'string')
prop = prop.toLowerCase() === 'true' ? true : false;
return prop;
}
/**
* Checks if a value is a valid Date object
*
* @param {(string | Date | number)} date - The value to check. Can be a Date object, a timestamp number, or a date string
* @return {boolean} Returns true if the value is a valid Date object (not NaN), otherwise false
*/
export function isValidDate(date: string | Date | number): boolean {
try {
return (date instanceof Date && !isNaN(date as unknown as number)) || (() => {
const testRegex = new RegExp(/^\d{4}-\d{2}-\d{2}$/).test(date as string)
Iif(typeof date !== Primitives.STRING || !(date as string)?.includes('T') && !testRegex)
return false;
date = (date as string).split('T')[0];
Iif(!new RegExp(/^\d{4}-\d{2}-\d{2}$/).test(date))
return false;
return !!(new Date(date));
})();
} catch(error: unknown) {
getLogger(isValidDate).error(error as Error | string);
return false;
}
}
/**
* Formats a date into a localized string representation
*
* @param {(string | Date | number)} date - The date to format. Can be a Date object, a timestamp number, or a date string
* @param {string} [locale] - The locale to use for formatting. If not provided, the system's locale will be used
* @return {(Date | string)} A formatted date string in the format DD/MM/YYYY according to the specified locale,
* or the original input as a string if the date is invalid
*/
export function formatDate(date: string | Date | number, locale?: string | undefined): Date | string {
Iif(!locale)
locale = getLocaleLanguage();
Iif(typeof date === 'string' || typeof date === 'number')
date = new Date(typeof date === 'string' ? date.replace(/\//g, '-') : date);
Iif(!isValidDate(date))
return `${date}` as string;
const r = date.toLocaleString(locale, {
year: "numeric",
day: "2-digit",
month: '2-digit'
});
return r;
}
/**
* Attempts to parse a date string, Date object, or number into a valid Date object
*
* @param {(string | Date | number)} date - The date to parse. Can be a Date object, a timestamp number,
* or a date string in the format "DD/MM/YYYY HH:MM:SS:MS"
* @return {(Date | null)} A valid Date object if parsing is successful, or null if the date is invalid
* or doesn't match the expected format
*/
export function parseToValidDate(date: string | Date | number): Date | null {
Iif(isValidDate(date))
return date as Date;
Iif(!`${date}`.includes('/'))
return null;
const [dateString, timeString] = (date as string).split(' ');
const [day, month, year] = dateString.split('/').map(Number);
const [hours, minutes, seconds, milliseconds] = timeString.split(':').map(Number);
date = new Date(year, month - 1, day, hours, minutes, seconds, milliseconds);
Iif(!isValidDate(date)) {
console.warn('parseToValidDate - Invalid date format', date);
return null;
}
return date;
}
/**
* Maps an item object using a provided mapper object and optional additional properties.
*
* @param {KeyValue} item - The source object to be mapped.
* @param {KeyValue} mapper - An object that defines the mapping rules. Keys represent the new property names,
* and values represent the path to the corresponding values in the source object.
* @param {KeyValue} [props] - Optional additional properties to be included in the mapped object.
* @returns {KeyValue} A new object with properties mapped according to the mapper object and including any additional properties.
*/
export function itemMapper(item: KeyValue, mapper: KeyValue, props?: KeyValue): KeyValue {
return Object.entries(mapper).reduce((accum: KeyValue, [key, value]) => {
const arrayValue = (value as string).split('.');
if (!value) {
accum[key] = value;
} else {
if (arrayValue.length === 1) {
accum[key] = item?.[value as string] || (value !== key ? value : "");
} else {
let val;
for (const _value of arrayValue)
val = !val
? item[_value]
: (typeof val === 'string' ? JSON.parse(val) : val)[_value];
Iif (isValidDate(new Date(val))) val = `${formatDate(val)}`;
accum[key] = val === null || val === undefined ? value : val;
}
}
return Object.assign({}, props || {}, accum);
}, {});
}
/**
* Maps an array of data objects using a provided mapper object.
*
* @template T - The type of the resulting mapped items.
* @param {any[]} data - The array of data objects to be mapped.
* @param {KeyValue} mapper - An object that defines the mapping rules.
* @param {KeyValue} [props] - Additional properties to be included in the mapped items.
*
* @returns {T[]} - The array of mapped items. If an item in the original array does not have any non-null values after mapping,
* the original item is returned instead.
*/
export function dataMapper<T>(data: T[], mapper: KeyValue, props?: KeyValue): T[] {
Iif (!data || !data.length) return [];
return data.reduce((accum: T[], curr) => {
const item = itemMapper(curr as KeyValue, mapper, props) as T;
const hasValues =
[...new Set(Object.values(item as T[]))].filter((value) => value).length >
0;
accum.push(hasValues ? item : curr);
return accum;
}, []);
}
/**
* @description Removes focus from the currently active DOM element
* @summary This utility function blurs the currently focused element in the document,
* effectively removing focus traps that might prevent proper navigation or keyboard
* interaction. It safely accesses the document's activeElement and calls blur() if
* an element is currently focused. This is useful for accessibility and user experience
* improvements, particularly when closing modals or dialogs.
*
* @return {void}
*
* @function removeFocusTrap
* @memberOf module:for-angular
*/
export function removeFocusTrap(): void {
const doc = getWindowDocument();
Iif(doc?.activeElement)
(doc.activeElement as HTMLElement)?.blur();
}
/**
* @description Cleans and normalizes whitespace in a string value
* @summary This utility function trims leading and trailing whitespace from a string
* and replaces multiple consecutive whitespace characters with a single space.
* Optionally converts the result to lowercase for consistent text processing.
* This is useful for normalizing user input, search terms, or data sanitization.
*
* @param {string} value - The string value to clean and normalize
* @param {boolean} [lowercase=false] - Whether to convert the result to lowercase
* @return {string} The cleaned and normalized string
*
* @function cleanSpaces
* @memberOf module:for-angular
*/
export function cleanSpaces(value: string = "", lowercase: boolean = false): string {
value = `${value}`.trim().replace(/\s+/g, ' ');
return lowercase ? value.toLowerCase() : value;
}
/**
* @description Determines if the user's system is currently in dark mode
* @summary This function checks the user's color scheme preference using the CSS media query
* '(prefers-color-scheme: dark)'. It returns a boolean indicating whether the system is
* currently set to dark mode. This is useful for implementing theme-aware functionality
* and adjusting UI elements based on the user's preferred color scheme.
*
* @return {Promise<boolean>} True if the system is in dark mode, false otherwise
*
* @function isDarkMode
* @memberOf module:for-angular
*/
export async function isDarkMode(): Promise<boolean> {
const {matches} = getWindow().matchMedia('(prefers-color-scheme: dark)');
return matches;
}
|