All files / src/lib/components/searchbar searchbar.component.ts

64.51% Statements 40/62
0% Branches 0/14
20% Functions 2/10
66.1% Lines 39/59

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 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564                    3x               3x 3x 3x   3x   3x 3x 3x                                           3x                                                 1x                         1x                         1x                           1x                   1x                   1x                   1x                   1x                   1x                                   1x                                     1x                   1x                   1x                   1x                   1x                   1x                                   1x                   1x                   1x                   1x                   1x                   1x                                             1x                     1x 1x                                                                 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                          
/**
 * @module module:lib/components/searchbar/searchbar.component
 * @description Searchbar component module.
 * @summary Exposes `SearchbarComponent` providing a configurable search input with
 * debouncing, clear/cancel handling and optional global window events. Use this
 * component to add search UI across lists and pages.
 *
 * @link {@link SearchbarComponent}
 */
 
import {
  Component,
  EventEmitter,
  HostListener,
  Input,
  OnInit,
  Output,
} from '@angular/core';
import { IonSearchbar } from '@ionic/angular/standalone';
import * as allIcons from 'ionicons/icons';
import { addIcons } from 'ionicons';
import { AutocompleteTypes, PredefinedColors } from '@ionic/core';
import { NgxComponentDirective } from '../../engine/NgxComponentDirective';
import { StringOrBoolean } from '../../engine/types';
import { windowEventEmitter } from '../../utils/helpers';
import { stringToBoolean } from '../../utils/helpers';
import { TranslatePipe } from '@ngx-translate/core';
 
/**
 * @description Searchbar component for Angular applications.
 * @summary The SearchbarComponent provides a highly customizable search input field with comprehensive
 * options for appearance, behavior, and interaction patterns. It extends NgxBaseComponentDirective to inherit
 * common functionality and implements OnInit for proper lifecycle management. This component features
 * debounced input handling, window event integration, visibility controls, and extensive styling options.
 * It's designed to be flexible and adaptable to different search requirements within modern web applications.
 *
 * @class SearchbarComponent
 * @extends {NgxBaseComponentDirective}
 * @implements {OnInit}
 * @memberOf SearchbarComponent
 */
@Component({
  selector: 'ngx-decaf-searchbar',
  templateUrl: './searchbar.component.html',
  styleUrls: ['./searchbar.component.scss'],
  standalone: true,
  imports: [TranslatePipe, IonSearchbar],
})
export class SearchbarComponent
  extends NgxComponentDirective
  implements OnInit
{
  /**
   * @description The mode of the searchbar.
   * @summary Determines the visual style of the searchbar, either iOS or Material Design.
   * @type {"ios" | "md" | undefined}
   * @default "ios"
   */
  // @Input()
  // override mode: "ios" | "md" | undefined = "md";
 
  /**
   * @description The autocomplete attribute for the searchbar input.
   * @summary Specifies whether the browser should enable autocomplete for the input field.
   * This controls the browser's built-in autocomplete functionality, helping users by
   * suggesting previously entered values or common inputs. Setting to 'off' disables
   * this feature for privacy or security reasons.
   *
   * @type {AutocompleteTypes | undefined}
   * @default "off"
   * @memberOf SearchbarComponent
   */
  @Input()
  autocomplete: AutocompleteTypes | undefined = 'off';
 
  /**
   * @description The autocorrect attribute for the searchbar input.
   * @summary Controls whether the browser should enable autocorrect functionality for the input field.
   * When enabled, the browser will automatically correct spelling mistakes as the user types.
   * This is typically disabled for search fields to preserve the user's exact search terms.
   *
   * @type {"on" | "off"}
   * @default "off"
   * @memberOf SearchbarComponent
   */
  @Input()
  autocorrect: 'on' | 'off' = 'off';
 
  /**
   * @description Whether the searchbar should animate.
   * @summary Controls the animation behavior of the searchbar during appearance and disappearance transitions.
   * When enabled, the searchbar will use smooth animations for state changes, providing a more
   * polished user experience. This affects transitions like showing/hiding the component.
   *
   * @type {StringOrBoolean}
   * @default true
   * @memberOf SearchbarComponent
   */
  @Input()
  animated: StringOrBoolean = true;
 
  /**
   * @description The text for the cancel button.
   * @summary Specifies the localized text to be displayed on the cancel button of the searchbar.
   * This text appears when the cancel button is visible and provides users with a clear
   * indication of how to dismiss the search interface. The text can be customized for
   * different languages and cultural contexts.
   *
   * @type {string}
   * @default "Cancel"
   * @memberOf SearchbarComponent
   */
  @Input()
  buttonCancelText: string = 'Cancel';
 
  /**
   * @description The icon to use for the clear button.
   * @summary Specifies the icon to be displayed for the clear button of the searchbar.
   * @type {string | undefined}
   * @default undefined
   * @memberOf SearchbarComponent
   */
  @Input()
  clearIcon: string | undefined = undefined;
 
  /**
   * @description The color of the searchbar.
   * @summary Specifies the color theme to be applied to the searchbar.
   * @type {string | undefined}
   * @default undefined
   * @memberOf SearchbarComponent
   */
  @Input()
  color: string | undefined = undefined;
 
  /**
   * @description The amount of time, in milliseconds, to wait to trigger the `ionChange` event after each keystroke.
   * @summary Controls the debounce time for the search input to reduce the frequency of event emissions.
   * @type {number}
   * @default 500
   * @memberOf SearchbarComponent
   */
  @Input()
  debounce: number = 500;
 
  /**
   * @description Whether the searchbar is disabled.
   * @summary Controls whether the searchbar is interactive or not.
   * @type {StringOrBoolean}
   * @default false
   * @memberOf SearchbarComponent
   */
  @Input()
  disabled: StringOrBoolean = false;
 
  /**
   * @description A hint to the browser for which enter key to display.
   * @summary Specifies the type of action that will be performed when the enter key is pressed.
   * @type {"search" | "enter" | "done" | "go" | "next" | "previous" | "send" | undefined}
   * @default "enter"
   * @memberOf SearchbarComponent
   */
  @Input()
  enterkeyhint:
    | 'search'
    | 'enter'
    | 'done'
    | 'go'
    | 'next'
    | 'previous'
    | 'send'
    | undefined = 'enter';
 
  /**
   * @description The input mode for the searchbar.
   * @summary Specifies the type of data that might be entered by the user while editing the element or its contents.
   * @type {"text" | "search" | "none" | "email" | "tel" | "url" | "numeric" | "decimal" | undefined}
   * @default 'search'
   * @memberOf SearchbarComponent
   */
  @Input()
  inputmode:
    | 'text'
    | 'search'
    | 'none'
    | 'email'
    | 'tel'
    | 'url'
    | 'numeric'
    | 'decimal'
    | undefined = 'search';
 
  /**
   * @description The placeholder for the searchbar input.
   * @summary Specifies the placeholder text to be displayed in the searchbar when it's empty.
   * @type {string}
   * @default "Search"
   * @memberOf SearchbarComponent
   */
  @Input()
  placeholder: string = 'Search';
 
  /**
   * @description The icon to use for the search button.
   * @summary Specifies the icon to be displayed for the search button of the searchbar.
   * @type {string | undefined}
   * @default "search-outline"
   * @memberOf SearchbarComponent
   */
  @Input()
  searchIcon: string | undefined = 'search-outline';
 
  /**
   * @description When to show the cancel button.
   * @summary Controls the visibility of the cancel button in different states of the searchbar.
   * @type {"always" | "focus" | "never"}
   * @default "never"
   * @memberOf SearchbarComponent
   */
  @Input()
  showCancelButton: 'always' | 'focus' | 'never' = 'never';
 
  /**
   * @description When to show the clear button.
   * @summary Controls the visibility of the clear button in different states of the searchbar.
   * @type {"always" | "focus" | "never"}
   * @default "focus"
   * @memberOf SearchbarComponent
   */
  @Input()
  showClearButton: 'always' | 'focus' | 'never' = 'focus';
 
  /**
   * @description Whether to enable spellcheck on the searchbar input.
   * @summary Controls whether the browser's spellcheck feature is enabled for the searchbar input.
   * @type {boolean}
   * @default false
   * @memberOf SearchbarComponent
   */
  @Input()
  spellcheck: boolean = false;
 
  /**
   * @description The type of input to use for the searchbar.
   * @summary Specifies the type of control to display for the searchbar input.
   * @type {"number" | "text" | "search" | "email" | "password" | "tel" | "url" | undefined}
   * @default "search"
   * @memberOf SearchbarComponent
   */
  @Input()
  type:
    | 'number'
    | 'text'
    | 'search'
    | 'email'
    | 'password'
    | 'tel'
    | 'url'
    | undefined = 'search';
 
  /**
   * @description The value of the searchbar input.
   * @summary Specifies the current value of the searchbar input.
   * @type {null | string | undefined}
   * @default ""
   * @memberOf SearchbarComponent
   */
  @Input()
  override value: null | string | undefined = '';
 
  /**
   * @description The keys to use for querying.
   * @summary Specifies the keys to be used when performing a search query.
   * @type {string | string[]}
   * @default "name"
   * @memberOf SearchbarComponent
   */
  @Input()
  queryKeys: string | string[] = 'name';
 
  /**
   * @description Whether the searchbar is visible.
   * @summary Controls the visibility of the searchbar component.
   * @type {StringOrBoolean}
   * @default false
   * @memberOf SearchbarComponent
   */
  @Input()
  isVisible: StringOrBoolean = false;
 
  /**
   * @description Whether to wrap the searchbar in a container.
   * @summary Controls whether the searchbar is wrapped in an additional container element.
   * @type {StringOrBoolean}
   * @default false
   * @memberOf SearchbarComponent
   */
  @Input()
  wrapper: StringOrBoolean = false;
 
  /**
   * @description The color of the wrapper.
   * @summary Specifies the color theme to be applied to the wrapper container, if present.
   * @type {PredefinedColors}
   * @default "primary"
   * @memberOf SearchbarComponent
   */
  @Input()
  wrapperColor: PredefinedColors = 'primary';
 
  /**
   * @description Whether to emit events to the window.
   * @summary Controls whether search events should be emitted as window events.
   * @type {StringOrBoolean}
   * @default true
   * @memberOf SearchbarComponent
   */
  @Input()
  emitEventToWindow: StringOrBoolean = true;
 
  /**
   * @description The current value of the searchbar.
   * @summary Stores the current value of the searchbar input for internal state management and processing.
   * This property is used to track the search term throughout the component's lifecycle and
   * coordinate between different event handlers and methods.
   *
   * @type {string | undefined}
   * @memberOf SearchbarComponent
   */
  currentValue: string | undefined;
 
  /**
   * @description Event emitter for search events.
   * @summary Emits search events when the user interacts with the searchbar, providing a reactive
   * interface for parent components to respond to search actions. This event is triggered by
   * various user interactions including typing, clearing, and explicit search actions.
   *
   * @type {EventEmitter<string>}
   * @memberOf SearchbarComponent
   */
  @Output()
  searchEvent: EventEmitter<string> = new EventEmitter<string>();
 
  /**
   * @description Creates an instance of SearchbarComponent.
   * @summary Initializes the SearchbarComponent with all necessary dependencies and configurations.
   * During initialization, it adds all available Ionicons to the application's icon registry,
   * ensuring that search and clear icons are available for use throughout the component's lifecycle.
   *
   * @memberOf SearchbarComponent
   */
  constructor() {
    super('SearchbarComponent');
    addIcons(allIcons);
  }
 
  /**
   * @description Initializes the component after Angular first displays the data-bound properties.
   * @summary Performs essential component initialization by converting string-based boolean inputs
   * to proper boolean values using the stringToBoolean utility. This ensures that all boolean
   * properties work correctly regardless of how they were passed from parent components or templates.
   *
   * @return {void}
   *
   * @mermaid
   * sequenceDiagram
   *   participant A as Angular Lifecycle
   *   participant S as SearchbarComponent
   *   participant U as Utility Functions
   *
   *   A->>S: ngOnInit()
   *   S->>U: stringToBoolean(emitEventToWindow)
   *   U-->>S: boolean value
   *   S->>U: stringToBoolean(wrapper)
   *   U-->>S: boolean value
   *   S->>U: stringToBoolean(isVisible)
   *   U-->>S: boolean value
   *   S->>U: stringToBoolean(disabled)
   *   U-->>S: boolean value
   *   S->>U: stringToBoolean(animated)
   *   U-->>S: boolean value
   *   Note over S: Component ready for interaction
   *
   * @memberOf SearchbarComponent
   */
  ngOnInit(): void {
    this.emitEventToWindow = stringToBoolean(this.emitEventToWindow);
    this.wrapper = stringToBoolean(this.wrapper);
    this.isVisible = stringToBoolean(this.isVisible);
    this.disabled = stringToBoolean(this.disabled);
    this.animated = stringToBoolean(this.animated);
  }
 
  /**
   * @description Handles the visibility toggle of the searchbar component.
   * @summary Listens for global window events to toggle the visibility state of the searchbar.
   * When the searchbar becomes visible, it automatically focuses on the input field after a brief
   * delay to ensure smooth animation completion. This provides a seamless user experience for
   * search activation through keyboard shortcuts or programmatic triggers.
   *
   * @param {CustomEvent} event - The custom event triggering the visibility toggle (unused but required by HostListener)
   * @return {void}
   *
   * @mermaid
   * sequenceDiagram
   *   participant W as Window
   *   participant S as SearchbarComponent
   *   participant E as DOM Element
   *
   *   W->>S: toggleSearchbarVisibility event
   *   S->>S: handleToggleVisibility()
   *   S->>S: Toggle isVisible state
   *   alt isVisible is true AND component exists
   *     S->>S: setTimeout(125ms)
   *     S->>E: setFocus() on ion-searchbar
   *   end
   *
   * @memberOf SearchbarComponent
   */
  @HostListener('window:toggleSearchbarVisibility', ['$event'])
  handleToggleVisibility(): void {
    this.isVisible = !this.isVisible;
    Iif (this.isVisible && !!this.component.nativeElement) {
      setTimeout(() => {
        (this.component.nativeElement as HTMLIonSearchbarElement).setFocus();
      }, 125);
    }
  }
 
  /**
   * @description Triggers a manual search event with the current searchbar value.
   * @summary Retrieves the current value from the searchbar's native element and emits it as a search event.
   * This method provides a programmatic way to trigger search functionality, useful for external
   * components or keyboard shortcuts that need to execute search without user interaction with the searchbar itself.
   *
   * @return {void}
   * @memberOf SearchbarComponent
   */
  search(): void {
    const element = this.component.nativeElement as HTMLIonSearchbarElement;
    this.searchEvent.emit(element.value || undefined);
  }
 
  /**
   * @description Handles value changes in the searchbar input field.
   * @summary Processes change events from the Ionic searchbar component and extracts the new value
   * to emit as a search event. This method is triggered when the user finishes editing the searchbar
   * value, providing a way to react to completed input changes rather than real-time typing.
   *
   * @param {CustomEvent} event - The change event from the Ionic searchbar containing the new value
   * @return {void}
   * @memberOf SearchbarComponent
   */
  handleChange(event: CustomEvent): void {
    const value = event?.detail?.value;
    Iif (value === this.currentValue) return;
    this.currentValue = value ?? undefined;
    this.emitEvent(this.currentValue);
  }
 
  /**
   * @description Handles clearing of the searchbar input field.
   * @summary Emits an undefined value as a search event when the searchbar is cleared by the user.
   * This method is typically triggered when the user clicks the clear button or uses other
   * clear mechanisms, signaling that the search should be reset or cleared.
   *
   * @return {void}
   * @memberOf SearchbarComponent
   */
  handleClear(): void {
    this.currentValue = undefined;
    this.emitEvent(this.currentValue);
  }
 
  /**
   * @description Handles real-time input events on the searchbar.
   * @summary Processes input events as the user types, providing immediate feedback for search functionality.
   * This method implements smart clearing behavior - if the input becomes empty, it automatically
   * triggers the clear handler. Otherwise, it emits the current value for real-time search suggestions
   * or filtering. This enables responsive search experiences with debounced event handling.
   *
   * @param {CustomEvent} event - The input event from the Ionic searchbar containing the current value
   * @return {void}
   *
   * @mermaid
   * sequenceDiagram
   *   participant U as User
   *   participant S as SearchbarComponent
   *   participant E as Event System
   *
   *   U->>S: Type in searchbar
   *   S->>S: handleInput(event)
   *   S->>S: Extract value from event
   *   alt value is empty or null
   *     S->>S: handleClear()
   *     S->>E: Emit undefined
   *   else value has content
   *     S->>S: emitEvent(value)
   *     S->>E: Emit search value
   *   end
   *
   * @memberOf SearchbarComponent
   */
  handleInput(event: CustomEvent): void {
    const value = event?.detail?.value?.length ? event.detail.value : undefined;
 
    Iif (value === this.currentValue) return;
    this.currentValue = value ?? undefined;
    this.emitEvent(this.currentValue);
  }
 
  /**
   * @description Handles blur events on the searchbar.
   * @summary Currently an empty method, can be implemented for specific blur behavior.
   * @param {CustomEvent} event - The blur event from the searchbar
   * @return {void}
   */
  // handleBlur(event: CustomEvent): void {}
 
  /**
   * @description Emits search events through multiple channels.
   * @summary Orchestrates the emission of search events both as component output events and optionally
   * as global window events. This dual-channel approach enables both direct parent-child communication
   * and application-wide event broadcasting, supporting flexible integration patterns and loose coupling
   * between components that need to respond to search actions.
   *
   * @param {string | undefined} value - The search value to emit across all configured channels
   * @return {void}
   *
   * @mermaid
   * sequenceDiagram
   *   participant S as SearchbarComponent
   *   participant P as Parent Component
   *   participant W as Window Event System
   *
   *   S->>S: emitEvent(value)
   *   S->>P: searchEvent.emit(value)
   *   alt emitEventToWindow is true
   *     S->>W: windowEventEmitter('searchbarEvent', {value})
   *   end
   *
   * @memberOf SearchbarComponent
   */
  emitEvent(value: string | undefined): void {
    this.searchEvent.emit(value);
    Iif (this.emitEventToWindow)
      windowEventEmitter('searchbarEvent', { value: value });
  }
 
  /**
   * @description Prevents default behavior of DOM events.
   * @summary Utility method to prevent unwanted default actions on DOM events, such as form submissions
   * or navigation triggers. This is commonly used in event handlers where the default browser behavior
   * would interfere with the component's custom logic or user experience design.
   *
   * @param {Event} event - The DOM event whose default behavior should be prevented
   * @return {void}
   * @memberOf SearchbarComponent
   */
  preventChange(event: Event): void {
    event.preventDefault();
  }
}