@guajiritos/general-autocomplete 19.0.1 → 19.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,7 +7,7 @@ import { Injectable, Pipe, signal, EventEmitter, forwardRef, Input, Output, View
7
7
  import * as i6 from '@angular/forms';
8
8
  import { UntypedFormControl, Validators, ReactiveFormsModule, NG_VALUE_ACCESSOR } from '@angular/forms';
9
9
  import * as i10 from '@angular/material/autocomplete';
10
- import { MatAutocompleteModule } from '@angular/material/autocomplete';
10
+ import { MatAutocompleteModule, MatAutocompleteTrigger } from '@angular/material/autocomplete';
11
11
  import * as i8 from '@angular/material/button';
12
12
  import { MatButtonModule } from '@angular/material/button';
13
13
  import * as i4 from '@angular/material/form-field';
@@ -20,7 +20,7 @@ import * as i9 from '@angular/material/progress-spinner';
20
20
  import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
21
21
  import * as i2 from '@ngx-translate/core';
22
22
  import { TranslateModule } from '@ngx-translate/core';
23
- import { debounceTime, finalize } from 'rxjs';
23
+ import { Subject, debounceTime, tap, from, switchMap, finalize } from 'rxjs';
24
24
  import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
25
25
 
26
26
  const GENERAL_DISPLAY_OPTIONS = {
@@ -46,10 +46,10 @@ class UtilsService {
46
46
  return prev ? prev[curr] : null;
47
47
  }, obj || self);
48
48
  }
49
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: UtilsService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
50
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: UtilsService, providedIn: 'root' }); }
49
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: UtilsService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
50
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: UtilsService, providedIn: 'root' }); }
51
51
  }
52
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: UtilsService, decorators: [{
52
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: UtilsService, decorators: [{
53
53
  type: Injectable,
54
54
  args: [{
55
55
  providedIn: 'root'
@@ -78,10 +78,10 @@ class ResolvePropertyPath {
78
78
  });
79
79
  return result;
80
80
  }
81
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: ResolvePropertyPath, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
82
- static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.2.14", ngImport: i0, type: ResolvePropertyPath, isStandalone: true, name: "resolvePropertyPath" }); }
81
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: ResolvePropertyPath, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
82
+ static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.2.12", ngImport: i0, type: ResolvePropertyPath, isStandalone: true, name: "resolvePropertyPath" }); }
83
83
  }
84
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: ResolvePropertyPath, decorators: [{
84
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: ResolvePropertyPath, decorators: [{
85
85
  type: Pipe,
86
86
  args: [{
87
87
  name: 'resolvePropertyPath',
@@ -95,276 +95,491 @@ class GuajiritosGeneralAutocomplete {
95
95
  this._zone = _zone;
96
96
  this._destroyRef = _destroyRef;
97
97
  this.translateService = translateService;
98
- this.wasSelected = false;
99
- this.firstCall = true;
100
- this.selectedElement = null;
98
+ // --- Private Properties ---
99
+ // Indica si la última actualización del input fue por una selección explícita desde el autocomplete
100
+ this._isOptionSelected = false;
101
+ this._clearDataSubject = new Subject();
102
+ this._doFocusSubject = new Subject();
103
+ this._selectedElement = null; // Almacena el objeto completo seleccionado
101
104
  this._url = null;
102
- this.restrictionsFilters = [];
105
+ this._limit = 20;
106
+ this._offset = 0;
107
+ this._restrictionsFilters = [];
108
+ this._lastSearchText = ""; // Almacena el texto usado en la última búsqueda de API
109
+ // --- Public Signals ---
103
110
  this.disabled = signal(false);
104
111
  this.loading = signal(false);
105
112
  this.required = signal(false);
106
113
  this.filteredOptions = signal([]);
107
114
  this.originalOptions = signal([]);
108
115
  this.notAllowedOption = signal(null);
109
- this.component = new UntypedFormControl({ value: null, disabled: false });
110
- /**
111
- * Possible values 'never', 'auto' or 'always'
112
- */
113
- this.floatLabel = 'auto';
114
- this.color = 'accent';
115
- this.appearance = 'outline';
116
- this.subscriptSizing = 'dynamic';
116
+ this.component = new UntypedFormControl({
117
+ value: null,
118
+ disabled: false,
119
+ });
120
+ this.hasMore = signal(true); // Indica si hay más datos para cargar
121
+ // --- Inputs ---
122
+ this.floatLabel = "auto";
123
+ this.color = "accent";
124
+ this.appearance = "outline";
125
+ this.subscriptSizing = "dynamic";
117
126
  this.debounceTimeValue = 300;
118
- this.label = 'Seleccione';
127
+ this.label = "Seleccione";
119
128
  this.showLabel = true;
120
- this.placeholder = 'Seleccione un elemento';
121
- this.field = ['name'];
122
- this.filterString = 'filter[$and][name][$like]';
129
+ this.placeholder = "Seleccione un elemento";
130
+ this.field = ["name"];
131
+ this.filterString = "filter[$and][name][$like]";
123
132
  this.displayOptions = GENERAL_DISPLAY_OPTIONS;
124
133
  this.withoutPaddingBottom = true;
125
134
  this.valueId = false;
126
135
  this.showSuffix = false;
127
136
  this.requireSelection = false;
128
- this.suffixIcon = 'search';
137
+ this.suffixIcon = "search";
129
138
  this.removeProperties = [];
130
- this.modifyResultFn = () => null;
131
- this.SelectElement = new EventEmitter();
139
+ this.modifyResultFn = (options) => options;
140
+ // --- Outputs ---
141
+ this.selectElement = new EventEmitter();
132
142
  this.clearElement = new EventEmitter();
133
- this.propagateChange = (_) => {
134
- };
143
+ // --- ControlValueAccessor methods ---
144
+ this.propagateChange = (_) => { };
135
145
  /**
136
- * Función para mostrar los elementos a seleccionar
137
- *
138
- * @param value - Valor a mostrar
146
+ * Function to display selected elements
139
147
  */
140
148
  this.displayFn = (value) => {
141
- if (value) {
142
- if (typeof value === 'string') {
143
- return value;
149
+ if (!value) {
150
+ return "";
151
+ }
152
+ // Si el valor ya es una cadena, devuélvelo directamente
153
+ if (typeof value === "string") {
154
+ return value;
155
+ }
156
+ let displayText = "";
157
+ const options = this.displayOptions || GENERAL_DISPLAY_OPTIONS;
158
+ options?.firthLabel?.forEach((field) => {
159
+ if (field?.type === DisplayOptionItemType.PATH) {
160
+ displayText +=
161
+ UtilsService.resolvePropertyByPath(value, field?.path) || "";
144
162
  }
145
- let displayText = '';
146
- if (!this.displayOptions) {
147
- this.displayOptions = GENERAL_DISPLAY_OPTIONS;
163
+ else {
164
+ displayText += field?.divider || "";
148
165
  }
149
- this.displayOptions?.firthLabel?.forEach((field) => {
150
- if (field?.type === DisplayOptionItemType.PATH) {
151
- displayText += UtilsService.resolvePropertyByPath(value, field?.path);
152
- }
153
- else {
154
- displayText += field?.divider;
155
- }
156
- });
157
- return displayText;
158
- }
166
+ });
167
+ return displayText;
159
168
  };
160
169
  }
170
+ // --- Setters for Inputs ---
161
171
  set url(data) {
162
172
  if (data) {
163
173
  this._url = data;
164
- this.subscribeComponentChanges();
174
+ // Suscribirse a los cambios del componente una vez que la URL está disponible
175
+ this.subscribeToComponentChanges();
165
176
  }
166
177
  }
167
- set clearData(value) {
168
- this.clearData$ = value;
169
- if (this.clearData$) {
170
- this.clearData$
171
- .pipe(takeUntilDestroyed(this._destroyRef))
172
- .subscribe({
173
- next: () => {
174
- this.component.setValue(null, { emitEvent: false });
175
- this.selectedElement = null;
176
- this.SelectElement.emit(null);
177
- this.filteredOptions.set([]);
178
- this.propagateChange(null);
179
- }
180
- });
178
+ set limit(value) {
179
+ if (value && !isNaN(value)) {
180
+ this._limit = value;
181
181
  }
182
182
  }
183
+ set clearData(value) {
184
+ this._clearDataSubject = value;
185
+ this._clearDataSubject
186
+ .pipe(takeUntilDestroyed(this._destroyRef))
187
+ .subscribe({
188
+ next: () => {
189
+ this.resetAutocompleteState();
190
+ this.component.setValue(null, { emitEvent: false }); // No emitir para evitar ciclo de valueChanges
191
+ this.propagateChange(null);
192
+ this.selectElement.emit(null);
193
+ },
194
+ });
195
+ }
183
196
  set initialValue(value) {
184
- this.component.setValue(value);
197
+ // Si el valor inicial es el mismo que el valor actual del control, no hacer nada para evitar bucles
198
+ if (value === this.component.value) {
199
+ return;
200
+ }
201
+ this._selectedElement = value;
202
+ this._isOptionSelected = !!value; // Marcar como seleccionado si hay un valor inicial
203
+ // Establecer el valor en el formControl sin emitir el evento
204
+ // para evitar que subscribeToComponentChanges reaccione a esta carga inicial.
205
+ this.component.setValue(value, { emitEvent: false });
206
+ // Actualizar _lastSearchText basado en el valor inicial
207
+ if (value) {
208
+ this._lastSearchText = this.displayFn(value);
209
+ console.log("initialValue set: _lastSearchText =", this._lastSearchText);
210
+ }
211
+ else {
212
+ this._lastSearchText = "";
213
+ }
185
214
  }
186
215
  /**
187
- * Añade o elimina restricciones para la búsqueda
188
- *
189
- * @param restrictions - Restricciones para la búsqueda
216
+ * Adds or removes search restrictions
190
217
  */
191
218
  set restrictions(restrictions) {
192
- if (restrictions?.length) {
193
- this.restrictionsFilters = [...restrictions];
194
- }
195
- else {
196
- this.restrictionsFilters = [];
219
+ this._restrictionsFilters = restrictions?.length ? [...restrictions] : [];
220
+ this.resetAutocompleteState();
221
+ // Re-ejecutar búsqueda si el input tiene texto y hay restricciones
222
+ const currentSearchText = this.getAutocompleteSearchText();
223
+ if (currentSearchText) {
224
+ this.getAutocompleteByTextHandler(currentSearchText);
197
225
  }
198
226
  }
199
227
  /**
200
- * Añade o elimina la validación de que el campo sea requerido
201
- *
202
- * @param required - Define si es requerido o no
228
+ * Adds or removes required validation
203
229
  */
204
230
  set isRequired(required) {
205
231
  this.required.set(required);
232
+ const validators = [autocompleteValidator];
206
233
  if (required) {
207
- this.component.setValidators([Validators.required, autocompleteValidator]);
208
- }
209
- else {
210
- this.component.clearValidators();
211
- this.component.setValidators([autocompleteValidator]);
234
+ validators.push(Validators.required);
212
235
  }
236
+ this.component.setValidators(validators);
213
237
  this.component.updateValueAndValidity();
214
238
  }
215
239
  /**
216
- * Define si vamos a realizar una búsqueda al elemento estar en el focus de la aplicación
217
- *
218
- * @param focusSubject - Observable para la subscripción al evento Focus
240
+ * Defines whether to perform a search when the element is in focus
219
241
  */
220
242
  set doFocus(focusSubject) {
221
- this.doFocusSubject$ = focusSubject;
222
- if (this.doFocusSubject$) {
223
- this.doFocusSubject$
224
- .pipe(debounceTime(this.debounceTimeValue), takeUntilDestroyed(this._destroyRef))
225
- .subscribe({
226
- next: () => {
227
- this._zone.run(() => {
228
- setTimeout(() => {
229
- this.inputText?.nativeElement?.focus();
230
- }, 500);
231
- });
232
- }
233
- });
234
- }
243
+ this._doFocusSubject = focusSubject;
244
+ this._doFocusSubject
245
+ .pipe(debounceTime(this.debounceTimeValue), // Retrasar para evitar llamadas excesivas
246
+ takeUntilDestroyed(this._destroyRef))
247
+ .subscribe({
248
+ next: () => {
249
+ this._zone.run(() => {
250
+ setTimeout(() => {
251
+ this.inputText?.nativeElement?.focus();
252
+ // Forzar la apertura del panel y una posible carga si es necesario
253
+ // Simular input para disparar valueChanges, lo que a menudo abre el panel si el texto cambia
254
+ this.inputText?.nativeElement?.dispatchEvent(new Event("input"));
255
+ // Abrir explícitamente el panel usando el MatAutocompleteTrigger
256
+ this.autocompleteTrigger?.openPanel(); // <--- EL CAMBIO ES AQUÍ
257
+ }, 50); // Un pequeño retraso para asegurar el foco y la apertura
258
+ });
259
+ },
260
+ });
235
261
  }
236
262
  set notAllowedElements(element) {
237
263
  if (element) {
238
264
  this.notAllowedOption.set(element);
239
- if (this.originalOptions()?.length) {
240
- this.filteredOptions.set(this.originalOptions()?.filter((option) => JSON.stringify(option) !== JSON.stringify(this.notAllowedOption())));
241
- }
265
+ this.filterOptionsBasedOnNotAllowed();
242
266
  }
243
267
  }
244
268
  /**
245
- * Subscripción a los cambios del input de búsqueda
269
+ * Resets the autocomplete pagination and options state.
270
+ * Centralizes the logic to avoid duplication.
246
271
  */
247
- subscribeComponentChanges() {
272
+ resetAutocompleteState() {
273
+ this._offset = 0;
274
+ this.originalOptions.set([]);
275
+ this.filteredOptions.set([]);
276
+ this.hasMore.set(true);
277
+ // IMPORTANTE: _selectedElement NO se resetea aquí, solo si se borra explícitamente
278
+ // _lastSearchText se actualiza en writeValue y optionSelected
279
+ console.log("Autocomplete state reset (pagination/options).");
280
+ }
281
+ /**
282
+ * Subscription to search input changes
283
+ */
284
+ subscribeToComponentChanges() {
248
285
  this.component.valueChanges
249
- .pipe(debounceTime(this.debounceTimeValue), takeUntilDestroyed(this._destroyRef))
286
+ .pipe(
287
+ // Utiliza tap para observar el valor antes del debounce y el switchMap
288
+ tap((value) => {
289
+ // Si el cambio viene de una selección programática (e.g., this.component.setValue(obj))
290
+ // O de una selección del usuario en el autocomplete, marcamos que no necesitamos buscar.
291
+ if (typeof value === "object" &&
292
+ value !== null &&
293
+ this._isOptionSelected) {
294
+ console.log("Value change detected: Object selected, skipping search.");
295
+ // Resetear la bandera después de procesar
296
+ this._isOptionSelected = false;
297
+ return; // Salir del tap, el debounce/switchMap no se ejecutará para este valor.
298
+ }
299
+ }), debounceTime(this.debounceTimeValue), takeUntilDestroyed(this._destroyRef))
250
300
  .subscribe({
251
- next: () => {
252
- if (!this.firstCall && !this.wasSelected) {
253
- this.getAutocompleteByTextHandler(this.getAutocompleteSearchText());
301
+ next: (value) => {
302
+ const currentSearchText = this.getAutocompleteSearchText();
303
+ // Si el valor actual es un objeto (ya seleccionado), no necesitamos buscar
304
+ // A menos que el texto en el input haya sido modificado por el usuario
305
+ if (typeof value === "object" && value !== null) {
306
+ const displayText = this.displayFn(value);
307
+ if (currentSearchText === displayText &&
308
+ this._selectedElement === value) {
309
+ console.log("Value is selected object and matches display text, skipping search.");
310
+ return;
311
+ }
312
+ }
313
+ // Si el valor del input es un string (el usuario está escribiendo o borró)
314
+ // Y el texto actual es diferente al último texto buscado
315
+ // O si el texto está vacío (para cargar las opciones iniciales si se borra)
316
+ if ((typeof value === "string" &&
317
+ currentSearchText !== this._lastSearchText) ||
318
+ (currentSearchText === "" && this._lastSearchText !== "") // Para cuando el usuario borra todo
319
+ ) {
320
+ this.resetAutocompleteState(); // Reiniciar paginación y opciones
321
+ this._lastSearchText = currentSearchText; // Actualizar el último texto buscado
322
+ console.log("Value changed, initiating new search for:", currentSearchText);
323
+ this.getAutocompleteByTextHandler(currentSearchText);
324
+ }
325
+ else if (currentSearchText === "" && this._lastSearchText === "") {
326
+ // Si el input está vacío y ya lo estaba, y el componente no tiene valor seleccionado,
327
+ // podría ser un buen momento para recargar las opciones iniciales si el panel está abierto
328
+ if (this.matAutocomplete._isOpen &&
329
+ this.originalOptions().length === 0 &&
330
+ !this.loading()) {
331
+ console.log("Input empty, no options, panel open. Loading initial set.");
332
+ this.getAutocompleteByTextHandler("");
333
+ }
334
+ }
335
+ },
336
+ });
337
+ }
338
+ ngAfterViewInit() {
339
+ // Suscribirse a la apertura del panel para añadir el listener de scroll
340
+ this.matAutocomplete.opened
341
+ .pipe(takeUntilDestroyed(this._destroyRef))
342
+ .subscribe(() => {
343
+ if (this.matAutocomplete?.panel) {
344
+ // Asegurarse de que el listener sea removido antes de añadirlo para prevenir duplicados
345
+ this.matAutocomplete.panel.nativeElement.removeEventListener("scroll", this.onScroll.bind(this));
346
+ this.matAutocomplete.panel.nativeElement.addEventListener("scroll", this.onScroll.bind(this));
347
+ // Si el panel se abre y no hay opciones cargadas, o si el input está vacío
348
+ // y no hay una selección activa, cargar las opciones iniciales.
349
+ const currentSearchText = this.getAutocompleteSearchText();
350
+ if (this.originalOptions().length === 0 ||
351
+ (!this._selectedElement && currentSearchText === "")) {
352
+ console.log("Panel opened, loading initial set of options.");
353
+ this.getAutocompleteByTextHandler(currentSearchText);
354
+ }
355
+ }
356
+ });
357
+ // Suscribirse al cierre del panel para remover el listener de scroll y manejar la deselección
358
+ this.matAutocomplete.closed
359
+ .pipe(takeUntilDestroyed(this._destroyRef))
360
+ .subscribe(() => {
361
+ if (this.matAutocomplete?.panel) {
362
+ this.matAutocomplete.panel.nativeElement.removeEventListener("scroll", this.onScroll.bind(this));
363
+ }
364
+ const currentInputValue = this.component.value;
365
+ const currentInputText = this.getAutocompleteSearchText();
366
+ console.log("Autocomplete closed. Current Input Value:", currentInputValue, "Selected Element:", this._selectedElement, "Current Input Text:", currentInputText);
367
+ // Lógica para manejar el borrado del input si no hay una selección válida
368
+ // o si el texto no coincide con el elemento seleccionado.
369
+ if (typeof currentInputValue === "string") {
370
+ // Si el valor del input es un string (el usuario está escribiendo o ha modificado)
371
+ if (this.requireSelection) {
372
+ // Si se requiere selección y el texto no coincide con un elemento seleccionado,
373
+ // o no hay ningún elemento seleccionado, entonces se borra.
374
+ if (!this._selectedElement ||
375
+ currentInputText !== this.displayFn(this._selectedElement)) {
376
+ console.warn("Autocomplete closed: Input cleared because selection is required and no valid match found.");
377
+ this.clearInternalState(); // Usa un método para limpiar
378
+ }
379
+ }
380
+ else {
381
+ // Si NO se requiere selección, pero el usuario ha editado el texto de un elemento previamente seleccionado.
382
+ // En este caso, NO borramos, sino que revertimos al texto del elemento seleccionado si existe.
383
+ if (this._selectedElement &&
384
+ currentInputText !== this.displayFn(this._selectedElement)) {
385
+ console.log("Autocomplete closed: Text edited for a selected item, reverting to original.");
386
+ // Revertir al texto del elemento seleccionado.
387
+ this.component.setValue(this._selectedElement, {
388
+ emitEvent: false,
389
+ });
390
+ this._lastSearchText = this.displayFn(this._selectedElement);
391
+ this.propagateChange(this._selectedElement); // Propagar el valor original si se revierte
392
+ }
393
+ else if (currentInputText === "" && this._selectedElement) {
394
+ // Si el input está vacío pero había un elemento seleccionado, deseleccionar
395
+ console.log("Autocomplete closed: Input cleared by user, deselecting element.");
396
+ this.clearInternalState();
397
+ }
398
+ else if (currentInputText === "" && !this._selectedElement) {
399
+ // Si el input está vacío y no había selección, simplemente asegúrate de que el estado interno refleje esto.
400
+ console.log("Autocomplete closed: Input empty, no selection.");
401
+ this.clearInternalState(); // Asegura el estado
402
+ }
403
+ // Si el texto del input es un string y no se requiere selección,
404
+ // y no hay _selectedElement, asumimos que el usuario quiere el texto libre.
405
+ // No hacemos nada, el texto permanece.
406
+ if (typeof currentInputValue === "string" &&
407
+ !this.requireSelection &&
408
+ !this._selectedElement) {
409
+ // Si no hay un elemento seleccionado pero el usuario escribió algo
410
+ // y no se requiere selección, dejamos el texto tal cual.
411
+ // Aseguramos que _lastSearchText se actualice para evitar re-búsquedas innecesarias.
412
+ this._lastSearchText = currentInputText;
413
+ this.propagateChange(currentInputText);
414
+ }
254
415
  }
255
- this.firstCall = false;
256
- this.wasSelected = false;
257
416
  }
417
+ // Si el valor ya es un objeto (porque se seleccionó), no hacemos nada aquí
418
+ // a menos que el usuario haya borrado manualmente el texto del input.
419
+ // Esa última parte se cubre con la condición currentInputText === ""
258
420
  });
259
421
  }
260
422
  /**
261
- * Búsqueda de los elementos a mostrar en el componente de auto-completamiento
262
- *
263
- * @param text - Texto a buscar
423
+ * Helper method to clear the internal state of the autocomplete.
424
+ */
425
+ clearInternalState() {
426
+ this.component.setValue(null, { emitEvent: false }); // Evitar bucle con valueChanges
427
+ this.propagateChange(null);
428
+ this.selectElement.emit(null);
429
+ this._selectedElement = null;
430
+ this._lastSearchText = "";
431
+ this.resetAutocompleteState(); // Resetear opciones y paginación
432
+ console.log("Internal autocomplete state cleared.");
433
+ }
434
+ /**
435
+ * Searches for elements to display in the autocomplete component.
436
+ * Now supports pagination.
437
+ * @param text - Text to search
264
438
  */
265
439
  getAutocompleteByTextHandler(text) {
440
+ // Si no hay más datos Y ya cargamos algo (offset > 0) Y el texto de búsqueda no ha cambiado,
441
+ // y no estamos actualmente cargando, salir.
442
+ if (!this.hasMore() &&
443
+ this._offset > 0 &&
444
+ text === this._lastSearchText && // Verificar que el texto de búsqueda actual sea el mismo
445
+ !this.loading()) {
446
+ console.log("No more data for current search text, stopping further loads.");
447
+ return;
448
+ }
449
+ if (this.loading()) {
450
+ console.log("Already loading, exiting getAutocompleteByTextHandler.");
451
+ return;
452
+ }
266
453
  this.loading.set(true);
267
- this.propagateChange(null);
268
- this.selectedElement = null;
269
- this.SelectElement.emit(null);
270
- if (!this.serviceConfig) {
271
- this._autocompleteService
272
- .getAutocompleteByText(this._url, text, this.filterString, this.restrictionsFilters, this.removeProperties, this.order, this.bodyRequest)
273
- .then((resp) => {
274
- resp?.pipe(finalize(() => this.loading.set(false))).subscribe({
275
- next: (result) => {
276
- this.originalOptions.set(result?.payload?.data ?? result?.data);
277
- // Modifica los options con una función que se le pase como parámetro
278
- const modifiedOptions = this.modifyResultFn(this.originalOptions());
279
- if (modifiedOptions)
280
- this.filteredOptions.set(modifiedOptions);
281
- if (this.notAllowedOption()) {
282
- this.filteredOptions.set(this.originalOptions()?.filter((option) => JSON.stringify(option) !== JSON.stringify(this.notAllowedOption())));
283
- }
284
- else {
285
- this.filteredOptions.set(this.originalOptions());
286
- }
287
- }
288
- });
289
- });
454
+ const currentOffset = this._offset; // Capturar el offset actual antes de la llamada
455
+ const currentSearchTextForApi = text; // Usar el texto pasado, no el global _lastSearchText
456
+ if (!this._url && !this.serviceConfig) {
457
+ console.warn("Autocomplete: 'url' or 'serviceConfig' input is required.");
458
+ this.loading.set(false);
459
+ this.hasMore.set(false);
460
+ return;
290
461
  }
291
- else {
462
+ let apiCall;
463
+ if (this._url) {
464
+ apiCall = from(this._autocompleteService.getAutocompleteByText(this._url, currentSearchTextForApi, // Usar el texto de búsqueda actual
465
+ this.filterString, this._restrictionsFilters, this.removeProperties, this.order, this.bodyRequest, { limit: this._limit, offset: currentOffset })).pipe(switchMap((innerObservable) => innerObservable));
466
+ }
467
+ else if (this.serviceConfig) {
292
468
  let body = { ...this.serviceConfig };
293
- body[this.serviceConfig.searchProperty] = text;
294
- delete body.service;
295
- this.serviceConfig.service[this.serviceConfig.method](body)
296
- .pipe(takeUntilDestroyed(this._destroyRef), debounceTime(this.debounceTimeValue || 300), finalize(() => this.loading.set(false)))
297
- .subscribe({
298
- next: (result) => {
299
- this.originalOptions.set(result?.payload?.data ?? result?.data);
300
- // Modifica los options con una función que se le pase como parámetro
301
- const modifiedOptions = this.modifyResultFn(this.originalOptions());
302
- if (modifiedOptions)
303
- this.filteredOptions.set(modifiedOptions);
304
- if (this.notAllowedOption()) {
305
- this.filteredOptions.set(this.originalOptions()?.filter((option) => JSON.stringify(option) !== JSON.stringify(this.notAllowedOption())));
306
- }
307
- else {
308
- this.filteredOptions.set(this.originalOptions());
309
- }
310
- },
311
- error: (err) => {
312
- console.log('aki esta el error =>', err);
469
+ body[this.serviceConfig.searchProperty] = currentSearchTextForApi; // Usar el texto de búsqueda actual
470
+ body["limit"] = this._limit;
471
+ body["offset"] = currentOffset;
472
+ apiCall = this.serviceConfig.service[this.serviceConfig.method](body);
473
+ }
474
+ else {
475
+ this.loading.set(false);
476
+ this.hasMore.set(false);
477
+ return;
478
+ }
479
+ // Guardar la posición de scroll antes de la actualización
480
+ let panelScrollTop = 0;
481
+ if (this.matAutocomplete?.panel) {
482
+ panelScrollTop = this.matAutocomplete.panel.nativeElement.scrollTop;
483
+ }
484
+ apiCall
485
+ .pipe(finalize(() => {
486
+ this.loading.set(false);
487
+ }), takeUntilDestroyed(this._destroyRef))
488
+ .subscribe({
489
+ next: (result) => {
490
+ const newData = result?.payload?.data ?? result?.data ?? [];
491
+ console.log("New Data received:", newData.length, "items. Current offset before update:", this._offset);
492
+ this._offset += newData.length; // Actualizar offset con la cantidad de nuevos ítems
493
+ if (newData.length < this._limit) {
494
+ this.hasMore.set(false);
495
+ console.log("No more data, hasMore = false");
313
496
  }
314
- });
497
+ else {
498
+ this.hasMore.set(true);
499
+ console.log("Potentially more data, hasMore = true");
500
+ }
501
+ // Actualizar las opciones originales
502
+ this.originalOptions.update((currentOptions) => {
503
+ const updatedOptions = [...currentOptions, ...newData];
504
+ console.log("Total options after merge:", updatedOptions.length);
505
+ return updatedOptions;
506
+ });
507
+ this.filterOptionsBasedOnNotAllowed();
508
+ // Restaurar la posición de scroll después de que Angular haya actualizado el DOM
509
+ // Esto debe hacerse fuera de la zona de Angular o con un pequeño retardo.
510
+ if (this.matAutocomplete?.panel && panelScrollTop > 0) {
511
+ this._zone.runOutsideAngular(() => {
512
+ setTimeout(() => {
513
+ this.matAutocomplete.panel.nativeElement.scrollTop =
514
+ panelScrollTop;
515
+ console.log("Scroll position restored to:", panelScrollTop);
516
+ }, 0); // Un pequeño retardo para asegurar que el DOM se haya renderizado
517
+ });
518
+ }
519
+ },
520
+ error: (error) => {
521
+ console.error("Error fetching autocomplete data:", error);
522
+ this.loading.set(false);
523
+ this.hasMore.set(false);
524
+ },
525
+ });
526
+ }
527
+ filterOptionsBasedOnNotAllowed() {
528
+ let currentOptions = this.originalOptions();
529
+ const modifiedOptions = this.modifyResultFn(currentOptions);
530
+ if (modifiedOptions !== null && modifiedOptions !== undefined) {
531
+ currentOptions = modifiedOptions;
532
+ }
533
+ if (this.notAllowedOption()) {
534
+ this.filteredOptions.set(currentOptions.filter((option) => JSON.stringify(option) !== JSON.stringify(this.notAllowedOption())));
535
+ }
536
+ else {
537
+ this.filteredOptions.set(currentOptions);
315
538
  }
316
539
  }
317
540
  /**
318
- * Define el texto por el que se va a realizar la búsqueda
319
- *
320
- * @return {string} Texto de la búsqueda
541
+ * Defines the text to be used for the search
321
542
  */
322
543
  getAutocompleteSearchText() {
323
- let text = '';
324
- if (this.component.value) {
325
- if (typeof this.component.value === 'object') {
326
- const componentValue = this.component.value?.[this.field?.[0]];
327
- if (typeof componentValue === 'object') {
328
- let lang = 'es';
329
- if (this.field?.[1]) {
330
- lang = this.field?.[1];
331
- }
332
- text = componentValue?.[lang];
333
- }
334
- }
335
- else if (typeof this.component.value === 'string') {
336
- text = this.component.value;
337
- }
544
+ const value = this.component.value;
545
+ if (typeof value === "object" && value !== null) {
546
+ // Si el valor es un objeto, usa displayFn para obtener el texto
547
+ return this.displayFn(value);
338
548
  }
339
- return text;
549
+ else if (typeof value === "string") {
550
+ return value;
551
+ }
552
+ return "";
340
553
  }
341
554
  registerOnChange(fn) {
342
555
  this.propagateChange = fn;
343
556
  }
344
- registerOnTouched() {
345
- }
557
+ registerOnTouched() { }
346
558
  /**
347
- * Recibe el valor del FormControl
348
- *
349
- * @param value - Valor entrado por FormControl
559
+ * Recibe el valor desde el FormControl externo.
350
560
  */
351
561
  writeValue(value) {
562
+ // Establecer la bandera para indicar que el cambio viene de un setValue programático
563
+ this._isOptionSelected = typeof value === "object" && value !== null;
564
+ this.component.setValue(value, { emitEvent: false }); // No emitir evento para evitar bucles.
565
+ this._selectedElement = value
566
+ ? this.valueId && typeof value === "object"
567
+ ? value?.id
568
+ : value
569
+ : null;
570
+ // Actualizar _lastSearchText basado en el valor que se está escribiendo.
352
571
  if (value) {
353
- this.component.setValue(value, { emitEvent: false });
354
- if (typeof value === 'object' && this.valueId) {
355
- this.selectedElement = value?.id;
356
- }
357
- else {
358
- this.selectedElement = value;
359
- }
572
+ this._lastSearchText = this.displayFn(value);
573
+ console.log("writeValue: Last search text set to:", this._lastSearchText);
360
574
  }
361
575
  else {
362
- this.selectedElement = null;
576
+ this._lastSearchText = "";
577
+ console.log("writeValue: Last search text cleared.");
363
578
  }
364
579
  }
365
580
  setDisabledState(isDisabled) {
366
581
  this.disabled.set(isDisabled);
367
- if (this.disabled()) {
582
+ if (isDisabled) {
368
583
  this.component.disable();
369
584
  }
370
585
  else {
@@ -372,58 +587,105 @@ class GuajiritosGeneralAutocomplete {
372
587
  }
373
588
  }
374
589
  /**
375
- * Acción al limpiar el valor del input
376
- *
377
- * @param trigger
590
+ * Action on clearing the input value
378
591
  */
379
592
  clear(trigger) {
380
593
  this.clearElement.emit(this.component.value);
381
- this.component.setValue(null);
382
- this.selectedElement = null;
383
- this.SelectElement.emit(null);
384
- this.propagateChange(null);
594
+ this.clearInternalState(); // Usa el método auxiliar para limpiar
595
+ // this.component.setValue(null); // Ya se llama dentro de clearInternalState
596
+ // this.propagateChange(null);
597
+ // this.selectElement.emit(null);
598
+ // this._selectedElement = null;
599
+ // this._lastSearchText = "";
385
600
  this._zone.run(() => {
386
601
  setTimeout(() => {
387
- trigger.openPanel();
602
+ trigger.openPanel(); // Reabrir el panel después de borrar
603
+ this.getAutocompleteByTextHandler(""); // Cargar opciones iniciales (o todas) después de borrar
388
604
  }, 100);
389
605
  });
390
606
  }
391
607
  /**
392
- * Acción en el Focus del elemento
608
+ * Action on element Focus
393
609
  */
394
610
  onFocus() {
395
- if (!this.selectedElement) {
396
- this.getAutocompleteByTextHandler(this.getAutocompleteSearchText());
611
+ const currentSearchText = this.getAutocompleteSearchText();
612
+ // Si no hay opciones cargadas O el input está vacío y no hay un elemento seleccionado
613
+ if (this.originalOptions().length === 0 ||
614
+ (currentSearchText === "" && !this._selectedElement)) {
615
+ this.resetAutocompleteState(); // Reiniciar estado antes de una nueva búsqueda
616
+ this._lastSearchText = currentSearchText;
617
+ console.log("On focus, initiating search for:", currentSearchText);
618
+ this.getAutocompleteByTextHandler(currentSearchText);
619
+ }
620
+ else if (this.matAutocomplete._isOpen &&
621
+ currentSearchText === this._lastSearchText) {
622
+ // Si el panel ya está abierto y el texto no ha cambiado, no hacer nada para evitar re-cargas innecesarias.
623
+ // Si el panel no estaba abierto, la apertura de `matAutocomplete.opened` se encargará de la carga.
624
+ console.log("On focus, panel already open with same text, skipping search.");
397
625
  }
398
626
  }
399
627
  optionSelected($event) {
400
- if ($event?.option?.value) {
401
- this.wasSelected = true;
402
- this.selectedElement = $event.option.value;
403
- this.SelectElement.emit($event.option.value);
404
- if (this.valueId) {
405
- this.propagateChange(typeof $event.option.value === 'object' ? $event.option.value?.id : $event.option.value);
628
+ const selectedValue = $event?.option?.value;
629
+ if (selectedValue) {
630
+ this._isOptionSelected = true; // Establecer la bandera de selección
631
+ this._selectedElement = selectedValue;
632
+ this.selectElement.emit(selectedValue);
633
+ if (this.valueId && typeof selectedValue === "object") {
634
+ this.propagateChange(selectedValue?.id);
406
635
  }
407
636
  else {
408
- this.propagateChange($event.option.value);
637
+ this.propagateChange(selectedValue);
409
638
  }
639
+ // Cuando un ítem es seleccionado, actualizar _lastSearchText con su valor de display.
640
+ // Esto es crucial para que el valueChanges no vuelva a disparar una búsqueda para este valor.
641
+ this._lastSearchText = this.displayFn(selectedValue);
642
+ console.log("Option selected. Last search text set to:", this._lastSearchText);
410
643
  }
411
644
  else {
412
- this.propagateChange($event.option.value);
645
+ // Si se deselecciona o selecciona nulo
646
+ // Esto rara vez debería ocurrir si se selecciona una opción válida, pero es un fallback.
647
+ console.log("Option selected is null or undefined, clearing state.");
648
+ this.clearInternalState();
649
+ }
650
+ // Después de la selección, el panel se cierra automáticamente en la mayoría de los casos de MatAutocomplete.
651
+ // this.matAutocomplete.closePanel(); // Descomentar si el panel no se cierra automáticamente
652
+ }
653
+ /**
654
+ * Handles the scroll event in the autocomplete panel to load more data.
655
+ */
656
+ onScroll(event) {
657
+ const element = event.target;
658
+ const scrollPosition = element.scrollTop + element.clientHeight;
659
+ const scrollHeight = element.scrollHeight;
660
+ const threshold = 50; // Pixels before the end to load more
661
+ // console.log("--- Scroll Event ---");
662
+ // console.log("Scroll Top:", element.scrollTop);
663
+ // console.log("Client Height:", element.clientHeight);
664
+ // console.log("Scroll Position (Top + Client):", scrollPosition);
665
+ // console.log("Scroll Height (Total):", scrollHeight);
666
+ // console.log("Remaining distance to bottom:", scrollHeight - scrollPosition);
667
+ // console.log("Is Loading:", this.loading());
668
+ // console.log("Has More:", this.hasMore());
669
+ if (scrollHeight - scrollPosition <= threshold &&
670
+ !this.loading() &&
671
+ this.hasMore()) {
672
+ console.log("Loading more data for infinity scroll...");
673
+ // Usar el texto de búsqueda actual (que puede ser el texto del ítem seleccionado o lo que el usuario escribió)
674
+ this.getAutocompleteByTextHandler(this.getAutocompleteSearchText());
413
675
  }
414
676
  }
415
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: GuajiritosGeneralAutocomplete, deps: [{ token: i1.AutocompleteService }, { token: i0.NgZone }, { token: i0.DestroyRef }, { token: i2.TranslateService }], target: i0.ɵɵFactoryTarget.Component }); }
416
- static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.14", type: GuajiritosGeneralAutocomplete, isStandalone: true, selector: "guajiritos-general-autocomplete", inputs: { floatLabel: "floatLabel", color: "color", appearance: "appearance", subscriptSizing: "subscriptSizing", bodyRequest: "bodyRequest", debounceTimeValue: "debounceTimeValue", detailsTemplate: "detailsTemplate", label: "label", showLabel: "showLabel", placeholder: "placeholder", field: "field", filterString: "filterString", displayOptions: "displayOptions", withoutPaddingBottom: "withoutPaddingBottom", valueId: "valueId", showSuffix: "showSuffix", requireSelection: "requireSelection", order: "order", serviceConfig: "serviceConfig", suffixIcon: "suffixIcon", removeProperties: "removeProperties", modifyResultFn: "modifyResultFn", url: "url", clearData: "clearData", initialValue: "initialValue", restrictions: "restrictions", isRequired: "isRequired", doFocus: "doFocus", notAllowedElements: "notAllowedElements" }, outputs: { SelectElement: "SelectElement", clearElement: "clearElement" }, providers: [
677
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: GuajiritosGeneralAutocomplete, deps: [{ token: i1.AutocompleteService }, { token: i0.NgZone }, { token: i0.DestroyRef }, { token: i2.TranslateService }], target: i0.ɵɵFactoryTarget.Component }); }
678
+ static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.12", type: GuajiritosGeneralAutocomplete, isStandalone: true, selector: "guajiritos-general-autocomplete", inputs: { floatLabel: "floatLabel", color: "color", appearance: "appearance", subscriptSizing: "subscriptSizing", bodyRequest: "bodyRequest", debounceTimeValue: "debounceTimeValue", detailsTemplate: "detailsTemplate", label: "label", showLabel: "showLabel", placeholder: "placeholder", field: "field", filterString: "filterString", displayOptions: "displayOptions", withoutPaddingBottom: "withoutPaddingBottom", valueId: "valueId", showSuffix: "showSuffix", requireSelection: "requireSelection", order: "order", serviceConfig: "serviceConfig", suffixIcon: "suffixIcon", removeProperties: "removeProperties", modifyResultFn: "modifyResultFn", url: "url", limit: "limit", clearData: "clearData", initialValue: "initialValue", restrictions: "restrictions", isRequired: "isRequired", doFocus: "doFocus", notAllowedElements: "notAllowedElements" }, outputs: { selectElement: "selectElement", clearElement: "clearElement" }, providers: [
417
679
  {
418
680
  provide: NG_VALUE_ACCESSOR,
419
681
  useExisting: forwardRef(() => GuajiritosGeneralAutocomplete),
420
- multi: true
421
- }
422
- ], viewQueries: [{ propertyName: "inputText", first: true, predicate: ["inputText"], descendants: true, static: true }], ngImport: i0, template: "<mat-form-field [floatLabel]=\"floatLabel\" class=\"w-100\" [appearance]=\"appearance\" [color]=\"color\"\n [subscriptSizing]=\"subscriptSizing\">\n\n @if (showLabel) {\n <mat-label>{{ label | translate }}</mat-label>\n }\n @if (showSuffix) {\n <mat-icon matSuffix>{{ suffixIcon ?? \"search\" }}</mat-icon>\n }\n <input #inputText #trigger=\"matAutocompleteTrigger\" (focus)=\"onFocus()\" [formControl]=\"component\" type=\"text\"\n [matAutocomplete]=\"autocomplete\" [placeholder]=\"placeholder | translate\" aria-label=\"autocomplete\"\n autocomplete=\"off\" matInput [required]=\"required()\">\n @if (!loading() && component.value) {\n <button (click)=\"clear(trigger)\" [disabled]=\"disabled()\"\n aria-label=\"Clear\" mat-icon-button matSuffix>\n <mat-icon>close</mat-icon>\n </button>\n }\n @if (loading()) {\n <button aria-label=\"search\" mat-icon-button matSuffix>\n <mat-spinner [value]=\"90\" color=\"accent\" diameter=\"25\"></mat-spinner>\n </button>\n }\n <mat-autocomplete #autocomplete=\"matAutocomplete\" [displayWith]=\"displayFn\" [requireSelection]=\"requireSelection\"\n (optionSelected)=\"optionSelected($event)\">\n @for (option of filteredOptions(); track option) {\n <mat-option [value]=\"option\">\n @if (!displayOptions && !detailsTemplate) {\n {{ option?.name | i18n: translateService.currentLang }}\n }\n @if (!detailsTemplate) {\n <div class=\"display-options\">\n <span [ngStyle]=\"{'line-height': displayOptions?.secondLabel ? '16px' : ''}\">\n {{ option | resolvePropertyPath:displayOptions.firthLabel | i18n: translateService.currentLang }}\n </span>\n @if (displayOptions?.secondLabel) {\n <span class=\"mat-caption\">\n {{ option | resolvePropertyPath: displayOptions.secondLabel | i18n: translateService.currentLang }}\n </span>\n }\n </div>\n }\n @if (detailsTemplate) {\n <ng-container *ngTemplateOutlet=\"detailsTemplate;context:{$implicit: option }\"></ng-container>\n }\n </mat-option>\n }\n </mat-autocomplete>\n\n @if (component.invalid) {\n <mat-error>\n {{ 'Este campo es requerido.' | translate }}\n </mat-error>\n }\n</mat-form-field>\n", styles: [".w-100{width:100%}.display-options{display:flex;flex-direction:column;justify-content:flex-start;align-items:flex-start}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i3.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "directive", type: i3.NgStyle, selector: "[ngStyle]", inputs: ["ngStyle"] }, { kind: "ngmodule", type: MatFormFieldModule }, { kind: "component", type: i4.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i4.MatLabel, selector: "mat-label" }, { kind: "directive", type: i4.MatError, selector: "mat-error, [matError]", inputs: ["id"] }, { kind: "directive", type: i4.MatSuffix, selector: "[matSuffix], [matIconSuffix], [matTextSuffix]", inputs: ["matTextSuffix"] }, { kind: "ngmodule", type: TranslateModule }, { kind: "pipe", type: i2.TranslatePipe, name: "translate" }, { kind: "ngmodule", type: MatIconModule }, { kind: "component", type: i5.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i6.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i6.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i6.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "directive", type: i6.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "ngmodule", type: MatInputModule }, { kind: "directive", type: i7.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl], input[matNativeControl], textarea[matNativeControl]", inputs: ["disabled", "id", "placeholder", "name", "required", "type", "errorStateMatcher", "aria-describedby", "value", "readonly", "disabledInteractive"], exportAs: ["matInput"] }, { kind: "ngmodule", type: MatButtonModule }, { kind: "component", type: i8.MatIconButton, selector: "button[mat-icon-button]", exportAs: ["matButton"] }, { kind: "ngmodule", type: MatProgressSpinnerModule }, { kind: "component", type: i9.MatProgressSpinner, selector: "mat-progress-spinner, mat-spinner", inputs: ["color", "mode", "value", "diameter", "strokeWidth"], exportAs: ["matProgressSpinner"] }, { kind: "ngmodule", type: MatAutocompleteModule }, { kind: "component", type: i10.MatAutocomplete, selector: "mat-autocomplete", inputs: ["aria-label", "aria-labelledby", "displayWith", "autoActiveFirstOption", "autoSelectActiveOption", "requireSelection", "panelWidth", "disableRipple", "class", "hideSingleSelectionIndicator"], outputs: ["optionSelected", "opened", "closed", "optionActivated"], exportAs: ["matAutocomplete"] }, { kind: "component", type: i10.MatOption, selector: "mat-option", inputs: ["value", "id", "disabled"], outputs: ["onSelectionChange"], exportAs: ["matOption"] }, { kind: "directive", type: i10.MatAutocompleteTrigger, selector: "input[matAutocomplete], textarea[matAutocomplete]", inputs: ["matAutocomplete", "matAutocompletePosition", "matAutocompleteConnectedTo", "autocomplete", "matAutocompleteDisabled"], exportAs: ["matAutocompleteTrigger"] }, { kind: "pipe", type: I18nPipe, name: "i18n" }, { kind: "pipe", type: ResolvePropertyPath, name: "resolvePropertyPath" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
682
+ multi: true,
683
+ },
684
+ ], viewQueries: [{ propertyName: "inputText", first: true, predicate: ["inputText"], descendants: true, static: true }, { propertyName: "matAutocomplete", first: true, predicate: ["auto"], descendants: true }, { propertyName: "autocompleteTrigger", first: true, predicate: MatAutocompleteTrigger, descendants: true }], ngImport: i0, template: "<mat-form-field [floatLabel]=\"floatLabel\" class=\"w-100\" [appearance]=\"appearance\" [color]=\"color\"\n [subscriptSizing]=\"subscriptSizing\">\n\n @if (showLabel) {\n <mat-label>{{ label | translate }}</mat-label>\n }\n @if (showSuffix) {\n <mat-icon matSuffix>{{ suffixIcon ?? \"search\" }}</mat-icon>\n }\n <input #inputText #trigger=\"matAutocompleteTrigger\" (focus)=\"onFocus()\" [formControl]=\"component\" type=\"text\"\n [matAutocomplete]=\"auto\" [placeholder]=\"placeholder | translate\" aria-label=\"autocomplete\"\n autocomplete=\"off\" matInput [required]=\"required()\">\n @if (!loading() && component.value) {\n <button (click)=\"clear(trigger)\" [disabled]=\"disabled()\"\n aria-label=\"Clear\" mat-icon-button matSuffix>\n <mat-icon>close</mat-icon>\n </button>\n }\n @if (loading()) {\n <button aria-label=\"search\" mat-icon-button matSuffix>\n <mat-spinner [value]=\"90\" color=\"accent\" diameter=\"25\"></mat-spinner>\n </button>\n }\n <mat-autocomplete #auto=\"matAutocomplete\" [displayWith]=\"displayFn\" [requireSelection]=\"requireSelection\"\n (optionSelected)=\"optionSelected($event)\">\n @for (option of filteredOptions(); track option) {\n <mat-option [value]=\"option\">\n @if (!displayOptions && !detailsTemplate) {\n {{ option?.name | i18n: translateService.currentLang }}\n }\n @if (!detailsTemplate) {\n <div class=\"display-options\">\n <span [ngStyle]=\"{'line-height': displayOptions?.secondLabel ? '16px' : ''}\">\n {{ option | resolvePropertyPath:displayOptions.firthLabel | i18n: translateService.currentLang }}\n </span>\n @if (displayOptions?.secondLabel) {\n <span class=\"mat-caption\">\n {{ option | resolvePropertyPath: displayOptions.secondLabel | i18n: translateService.currentLang }}\n </span>\n }\n </div>\n }\n @if (detailsTemplate) {\n <ng-container *ngTemplateOutlet=\"detailsTemplate;context:{$implicit: option }\"></ng-container>\n }\n </mat-option>\n }\n </mat-autocomplete>\n\n @if (component.invalid) {\n <mat-error>\n {{ 'Este campo es requerido.' | translate }}\n </mat-error>\n }\n</mat-form-field>\n", styles: [".w-100{width:100%}.display-options{display:flex;flex-direction:column;justify-content:flex-start;align-items:flex-start}\n"], dependencies: [{ kind: "ngmodule", type: CommonModule }, { kind: "directive", type: i3.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet", "ngTemplateOutletInjector"] }, { kind: "directive", type: i3.NgStyle, selector: "[ngStyle]", inputs: ["ngStyle"] }, { kind: "ngmodule", type: MatFormFieldModule }, { kind: "component", type: i4.MatFormField, selector: "mat-form-field", inputs: ["hideRequiredMarker", "color", "floatLabel", "appearance", "subscriptSizing", "hintLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i4.MatLabel, selector: "mat-label" }, { kind: "directive", type: i4.MatError, selector: "mat-error, [matError]", inputs: ["id"] }, { kind: "directive", type: i4.MatSuffix, selector: "[matSuffix], [matIconSuffix], [matTextSuffix]", inputs: ["matTextSuffix"] }, { kind: "ngmodule", type: TranslateModule }, { kind: "pipe", type: i2.TranslatePipe, name: "translate" }, { kind: "ngmodule", type: MatIconModule }, { kind: "component", type: i5.MatIcon, selector: "mat-icon", inputs: ["color", "inline", "svgIcon", "fontSet", "fontIcon"], exportAs: ["matIcon"] }, { kind: "ngmodule", type: ReactiveFormsModule }, { kind: "directive", type: i6.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i6.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i6.RequiredValidator, selector: ":not([type=checkbox])[required][formControlName],:not([type=checkbox])[required][formControl],:not([type=checkbox])[required][ngModel]", inputs: ["required"] }, { kind: "directive", type: i6.FormControlDirective, selector: "[formControl]", inputs: ["formControl", "disabled", "ngModel"], outputs: ["ngModelChange"], exportAs: ["ngForm"] }, { kind: "ngmodule", type: MatInputModule }, { kind: "directive", type: i7.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl], input[matNativeControl], textarea[matNativeControl]", inputs: ["disabled", "id", "placeholder", "name", "required", "type", "errorStateMatcher", "aria-describedby", "value", "readonly", "disabledInteractive"], exportAs: ["matInput"] }, { kind: "ngmodule", type: MatButtonModule }, { kind: "component", type: i8.MatIconButton, selector: "button[mat-icon-button]", exportAs: ["matButton"] }, { kind: "ngmodule", type: MatProgressSpinnerModule }, { kind: "component", type: i9.MatProgressSpinner, selector: "mat-progress-spinner, mat-spinner", inputs: ["color", "mode", "value", "diameter", "strokeWidth"], exportAs: ["matProgressSpinner"] }, { kind: "ngmodule", type: MatAutocompleteModule }, { kind: "component", type: i10.MatAutocomplete, selector: "mat-autocomplete", inputs: ["aria-label", "aria-labelledby", "displayWith", "autoActiveFirstOption", "autoSelectActiveOption", "requireSelection", "panelWidth", "disableRipple", "class", "hideSingleSelectionIndicator"], outputs: ["optionSelected", "opened", "closed", "optionActivated"], exportAs: ["matAutocomplete"] }, { kind: "component", type: i10.MatOption, selector: "mat-option", inputs: ["value", "id", "disabled"], outputs: ["onSelectionChange"], exportAs: ["matOption"] }, { kind: "directive", type: i10.MatAutocompleteTrigger, selector: "input[matAutocomplete], textarea[matAutocomplete]", inputs: ["matAutocomplete", "matAutocompletePosition", "matAutocompleteConnectedTo", "autocomplete", "matAutocompleteDisabled"], exportAs: ["matAutocompleteTrigger"] }, { kind: "pipe", type: I18nPipe, name: "i18n" }, { kind: "pipe", type: ResolvePropertyPath, name: "resolvePropertyPath" }], changeDetection: i0.ChangeDetectionStrategy.OnPush }); }
423
685
  }
424
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImport: i0, type: GuajiritosGeneralAutocomplete, decorators: [{
686
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.12", ngImport: i0, type: GuajiritosGeneralAutocomplete, decorators: [{
425
687
  type: Component,
426
- args: [{ selector: 'guajiritos-general-autocomplete', changeDetection: ChangeDetectionStrategy.OnPush, imports: [
688
+ args: [{ selector: "guajiritos-general-autocomplete", changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [
427
689
  CommonModule,
428
690
  MatFormFieldModule,
429
691
  TranslateModule,
@@ -434,17 +696,23 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImpo
434
696
  MatProgressSpinnerModule,
435
697
  MatAutocompleteModule,
436
698
  I18nPipe,
437
- ResolvePropertyPath
699
+ ResolvePropertyPath,
438
700
  ], providers: [
439
701
  {
440
702
  provide: NG_VALUE_ACCESSOR,
441
703
  useExisting: forwardRef(() => GuajiritosGeneralAutocomplete),
442
- multi: true
443
- }
444
- ], template: "<mat-form-field [floatLabel]=\"floatLabel\" class=\"w-100\" [appearance]=\"appearance\" [color]=\"color\"\n [subscriptSizing]=\"subscriptSizing\">\n\n @if (showLabel) {\n <mat-label>{{ label | translate }}</mat-label>\n }\n @if (showSuffix) {\n <mat-icon matSuffix>{{ suffixIcon ?? \"search\" }}</mat-icon>\n }\n <input #inputText #trigger=\"matAutocompleteTrigger\" (focus)=\"onFocus()\" [formControl]=\"component\" type=\"text\"\n [matAutocomplete]=\"autocomplete\" [placeholder]=\"placeholder | translate\" aria-label=\"autocomplete\"\n autocomplete=\"off\" matInput [required]=\"required()\">\n @if (!loading() && component.value) {\n <button (click)=\"clear(trigger)\" [disabled]=\"disabled()\"\n aria-label=\"Clear\" mat-icon-button matSuffix>\n <mat-icon>close</mat-icon>\n </button>\n }\n @if (loading()) {\n <button aria-label=\"search\" mat-icon-button matSuffix>\n <mat-spinner [value]=\"90\" color=\"accent\" diameter=\"25\"></mat-spinner>\n </button>\n }\n <mat-autocomplete #autocomplete=\"matAutocomplete\" [displayWith]=\"displayFn\" [requireSelection]=\"requireSelection\"\n (optionSelected)=\"optionSelected($event)\">\n @for (option of filteredOptions(); track option) {\n <mat-option [value]=\"option\">\n @if (!displayOptions && !detailsTemplate) {\n {{ option?.name | i18n: translateService.currentLang }}\n }\n @if (!detailsTemplate) {\n <div class=\"display-options\">\n <span [ngStyle]=\"{'line-height': displayOptions?.secondLabel ? '16px' : ''}\">\n {{ option | resolvePropertyPath:displayOptions.firthLabel | i18n: translateService.currentLang }}\n </span>\n @if (displayOptions?.secondLabel) {\n <span class=\"mat-caption\">\n {{ option | resolvePropertyPath: displayOptions.secondLabel | i18n: translateService.currentLang }}\n </span>\n }\n </div>\n }\n @if (detailsTemplate) {\n <ng-container *ngTemplateOutlet=\"detailsTemplate;context:{$implicit: option }\"></ng-container>\n }\n </mat-option>\n }\n </mat-autocomplete>\n\n @if (component.invalid) {\n <mat-error>\n {{ 'Este campo es requerido.' | translate }}\n </mat-error>\n }\n</mat-form-field>\n", styles: [".w-100{width:100%}.display-options{display:flex;flex-direction:column;justify-content:flex-start;align-items:flex-start}\n"] }]
704
+ multi: true,
705
+ },
706
+ ], template: "<mat-form-field [floatLabel]=\"floatLabel\" class=\"w-100\" [appearance]=\"appearance\" [color]=\"color\"\n [subscriptSizing]=\"subscriptSizing\">\n\n @if (showLabel) {\n <mat-label>{{ label | translate }}</mat-label>\n }\n @if (showSuffix) {\n <mat-icon matSuffix>{{ suffixIcon ?? \"search\" }}</mat-icon>\n }\n <input #inputText #trigger=\"matAutocompleteTrigger\" (focus)=\"onFocus()\" [formControl]=\"component\" type=\"text\"\n [matAutocomplete]=\"auto\" [placeholder]=\"placeholder | translate\" aria-label=\"autocomplete\"\n autocomplete=\"off\" matInput [required]=\"required()\">\n @if (!loading() && component.value) {\n <button (click)=\"clear(trigger)\" [disabled]=\"disabled()\"\n aria-label=\"Clear\" mat-icon-button matSuffix>\n <mat-icon>close</mat-icon>\n </button>\n }\n @if (loading()) {\n <button aria-label=\"search\" mat-icon-button matSuffix>\n <mat-spinner [value]=\"90\" color=\"accent\" diameter=\"25\"></mat-spinner>\n </button>\n }\n <mat-autocomplete #auto=\"matAutocomplete\" [displayWith]=\"displayFn\" [requireSelection]=\"requireSelection\"\n (optionSelected)=\"optionSelected($event)\">\n @for (option of filteredOptions(); track option) {\n <mat-option [value]=\"option\">\n @if (!displayOptions && !detailsTemplate) {\n {{ option?.name | i18n: translateService.currentLang }}\n }\n @if (!detailsTemplate) {\n <div class=\"display-options\">\n <span [ngStyle]=\"{'line-height': displayOptions?.secondLabel ? '16px' : ''}\">\n {{ option | resolvePropertyPath:displayOptions.firthLabel | i18n: translateService.currentLang }}\n </span>\n @if (displayOptions?.secondLabel) {\n <span class=\"mat-caption\">\n {{ option | resolvePropertyPath: displayOptions.secondLabel | i18n: translateService.currentLang }}\n </span>\n }\n </div>\n }\n @if (detailsTemplate) {\n <ng-container *ngTemplateOutlet=\"detailsTemplate;context:{$implicit: option }\"></ng-container>\n }\n </mat-option>\n }\n </mat-autocomplete>\n\n @if (component.invalid) {\n <mat-error>\n {{ 'Este campo es requerido.' | translate }}\n </mat-error>\n }\n</mat-form-field>\n", styles: [".w-100{width:100%}.display-options{display:flex;flex-direction:column;justify-content:flex-start;align-items:flex-start}\n"] }]
445
707
  }], ctorParameters: () => [{ type: i1.AutocompleteService }, { type: i0.NgZone }, { type: i0.DestroyRef }, { type: i2.TranslateService }], propDecorators: { inputText: [{
446
708
  type: ViewChild,
447
- args: ['inputText', { static: true }]
709
+ args: ["inputText", { static: true }]
710
+ }], matAutocomplete: [{
711
+ type: ViewChild,
712
+ args: ["auto"]
713
+ }], autocompleteTrigger: [{
714
+ type: ViewChild,
715
+ args: [MatAutocompleteTrigger]
448
716
  }], floatLabel: [{
449
717
  type: Input
450
718
  }], color: [{
@@ -489,12 +757,14 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImpo
489
757
  type: Input
490
758
  }], modifyResultFn: [{
491
759
  type: Input
492
- }], SelectElement: [{
760
+ }], selectElement: [{
493
761
  type: Output
494
762
  }], clearElement: [{
495
763
  type: Output
496
764
  }], url: [{
497
765
  type: Input
766
+ }], limit: [{
767
+ type: Input
498
768
  }], clearData: [{
499
769
  type: Input
500
770
  }], initialValue: [{
@@ -509,13 +779,17 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.14", ngImpo
509
779
  type: Input
510
780
  }] } });
511
781
  /**
512
- * Validación customizada para la selección de elementos
782
+ * Custom validation for element selection
513
783
  */
514
784
  function autocompleteValidator(control) {
515
- if (control?.value?.constructor !== Object || !control?.value?.id) {
516
- return { invalidSelection: true };
785
+ // Un valor válido es un objeto no nulo que tiene una propiedad 'id'.
786
+ // Esto asegura que realmente se ha seleccionado un objeto del autocomplete, no solo texto libre.
787
+ if (typeof control?.value === "object" &&
788
+ control?.value !== null &&
789
+ "id" in control.value) {
790
+ return null;
517
791
  }
518
- return null;
792
+ return { invalidSelection: true };
519
793
  }
520
794
 
521
795
  /*