• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IgniteUI / igniteui-angular / 14473610501

15 Apr 2025 03:40PM UTC coverage: 91.612% (+0.01%) from 91.601%
14473610501

Pull #15562

github

web-flow
Merge fad898b4d into 044db8746
Pull Request #15562: feat(h-grid): add support for advanced filtering

13420 of 15695 branches covered (85.5%)

99 of 106 new or added lines in 6 files covered. (93.4%)

1 existing line in 1 file now uncovered.

27011 of 29484 relevant lines covered (91.61%)

34180.89 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

92.22
/projects/igniteui-angular/src/lib/query-builder/query-builder-tree.component.ts
1
import {
2
    AfterViewInit,
3
    EventEmitter,
4
    LOCALE_ID,
5
    Output,
6
    TemplateRef
7
} from '@angular/core';
8
import { getLocaleFirstDayOfWeek, NgTemplateOutlet, NgClass, DatePipe } from '@angular/common';
9
import { Inject } from '@angular/core';
10
import {
11
    Component, Input, ViewChild, ChangeDetectorRef, ViewChildren, QueryList, ElementRef, OnDestroy, HostBinding
12
} from '@angular/core';
13
import { FormsModule } from '@angular/forms';
14
import { Subject } from 'rxjs';
15
import { IgxChipComponent } from '../chips/chip.component';
16
import { IQueryBuilderResourceStrings, QueryBuilderResourceStringsEN } from '../core/i18n/query-builder-resources';
17
import { PlatformUtil, trackByIdentity } from '../core/utils';
18
import { DataType, DataUtil } from '../data-operations/data-util';
19
import { IgxBooleanFilteringOperand, IgxDateFilteringOperand, IgxDateTimeFilteringOperand, IgxNumberFilteringOperand, IgxStringFilteringOperand, IgxTimeFilteringOperand } from '../data-operations/filtering-condition';
20
import { FilteringLogic, IFilteringExpression } from '../data-operations/filtering-expression.interface';
21
import { FilteringExpressionsTree, IExpressionTree, IFilteringExpressionsTree } from '../data-operations/filtering-expressions-tree';
22
import { IgxDatePickerComponent } from '../date-picker/date-picker.component';
23

24
import { IgxButtonDirective } from '../directives/button/button.directive';
25
import { IgxDateTimeEditorDirective } from '../directives/date-time-editor/date-time-editor.directive';
26

27
import { IgxOverlayOutletDirective } from '../directives/toggle/toggle.directive';
28
import { FieldType, EntityType } from '../grids/common/grid.interface';
29
import { IgxSelectComponent } from '../select/select.component';
30
import { HorizontalAlignment, OverlaySettings, VerticalAlignment } from '../services/overlay/utilities';
31
import { AbsoluteScrollStrategy, AutoPositionStrategy, CloseScrollStrategy, ConnectedPositioningStrategy } from '../services/public_api';
32
import { IgxTimePickerComponent } from '../time-picker/time-picker.component';
33
import { IgxPickerToggleComponent, IgxPickerClearComponent } from '../date-common/picker-icons.common';
34
import { IgxInputDirective } from '../directives/input/input.directive';
35
import { IgxInputGroupComponent } from '../input-group/input-group.component';
36
import { IgxSelectItemComponent } from '../select/select-item.component';
37
import { IgxPrefixDirective } from '../directives/prefix/prefix.directive';
38
import { IgxIconComponent } from '../icon/icon.component';
39
import { getCurrentResourceStrings } from '../core/i18n/resources';
40
import { IgxIconButtonDirective } from '../directives/button/icon-button.directive';
41
import { IComboSelectionChangingEventArgs, IgxComboComponent } from "../combo/combo.component";
42
import { IgxComboHeaderDirective } from '../combo/public_api';
43
import { IgxCheckboxComponent } from "../checkbox/checkbox.component";
44
import { IChangeCheckboxEventArgs } from '../checkbox/checkbox-base.directive';
45
import { IgxDialogComponent } from "../dialog/dialog.component";
46
import { ISelectionEventArgs } from '../drop-down/drop-down.common';
47
import { IgxTooltipDirective } from '../directives/tooltip/tooltip.directive';
48
import { IgxTooltipTargetDirective } from '../directives/tooltip/tooltip-target.directive';
49
import { IgxQueryBuilderSearchValueTemplateDirective } from './query-builder.directives';
50
import { IgxQueryBuilderComponent } from './query-builder.component';
51
import { IgxDragIgnoreDirective, IgxDropDirective } from '../directives/drag-drop/drag-drop.directive';
52
import { IgxDropDownComponent } from '../drop-down/drop-down.component';
53
import { IgxDropDownItemComponent } from '../drop-down/drop-down-item.component';
54
import { IgxDropDownItemNavigationDirective } from '../drop-down/drop-down-navigation.directive';
55
import { IgxQueryBuilderDragService } from './query-builder-drag.service';
56
import { isTree } from '../data-operations/expressions-tree-util';
57
import { ExpressionGroupItem, ExpressionItem, ExpressionOperandItem, IgxFieldFormatterPipe } from './query-builder.common';
58

59
const DEFAULT_PIPE_DATE_FORMAT = 'mediumDate';
3✔
60
const DEFAULT_PIPE_TIME_FORMAT = 'mediumTime';
3✔
61
const DEFAULT_PIPE_DATE_TIME_FORMAT = 'medium';
3✔
62
const DEFAULT_PIPE_DIGITS_INFO = '1.0-3';
3✔
63
const DEFAULT_CHIP_FOCUS_DELAY = 50;
3✔
64

65
/** @hidden */
66
@Component({
67
    selector: 'igx-query-builder-tree',
68
    templateUrl: './query-builder-tree.component.html',
69
    host: { 'class': 'igx-query-builder-tree' },
70
    imports: [
71
        DatePipe,
72
        FormsModule,
73
        IgxButtonDirective,
74
        IgxCheckboxComponent,
75
        IgxChipComponent,
76
        IgxComboComponent,
77
        IgxComboHeaderDirective,
78
        IgxDatePickerComponent,
79
        IgxDateTimeEditorDirective,
80
        IgxDialogComponent,
81
        IgxDragIgnoreDirective,
82
        IgxDropDirective,
83
        IgxDropDownComponent,
84
        IgxDropDownItemComponent,
85
        IgxDropDownItemNavigationDirective,
86
        IgxFieldFormatterPipe,
87
        IgxIconButtonDirective,
88
        IgxIconComponent,
89
        IgxInputDirective,
90
        IgxInputGroupComponent,
91
        IgxOverlayOutletDirective,
92
        IgxPickerClearComponent,
93
        IgxPickerToggleComponent,
94
        IgxPrefixDirective,
95
        IgxSelectComponent,
96
        IgxSelectItemComponent,
97
        IgxTimePickerComponent,
98
        IgxTooltipDirective,
99
        IgxTooltipTargetDirective,
100
        NgClass,
101
        NgTemplateOutlet
102
    ],
103
    providers: [
104
        IgxQueryBuilderDragService
105
    ],
106
})
107
export class IgxQueryBuilderTreeComponent implements AfterViewInit, OnDestroy {
3✔
108
    /**
109
     * @hidden @internal
110
     */
111
    public _expressionTree: IExpressionTree;
112

113
    /**
114
     * @hidden @internal
115
     */
116
    public _expressionTreeCopy: IExpressionTree;
117

118
    /**
119
     * @hidden @internal
120
     */
121
    @HostBinding('class') public get getClass() {
122
        return `igx-query-builder-tree--level-${this.level}`;
11,419✔
123
    }
124

125
    /**
126
     * Sets/gets the entities.
127
     */
128
    @Input()
129
    public entities: EntityType[];
130

131
    /**
132
     * Sets/gets the parent query builder component.
133
     */
134
    @Input()
135
    public queryBuilder: IgxQueryBuilderComponent;
136

137
    /**
138
     * Sets/gets the search value template.
139
     */
140
    @Input()
141
    public searchValueTemplate: TemplateRef<IgxQueryBuilderSearchValueTemplateDirective> = null;
297✔
142

143
    /**
144
    * Returns the parent expression operand.
145
    */
146
    @Input()
147
    public get parentExpression(): ExpressionOperandItem {
148
        return this._parentExpression;
153,761✔
149
    }
150

151
    /**
152
     * Sets the parent expression operand.
153
     */
154
    public set parentExpression(value: ExpressionOperandItem) {
155
        this._parentExpression = value;
142✔
156
    }
157

158
    /**
159
    * Returns the fields.
160
    */
161
    public get fields(): FieldType[] {
162
        if (!this._fields && this.isAdvancedFiltering()) {
58,648✔
163
            this._fields = this.entities[0].fields;
63✔
164
        }
165

166
        return this._fields;
58,648✔
167
    }
168

169
    /**
170
     * Sets the fields.
171
     */
172
    @Input()
173
    public set fields(fields: FieldType[]) {
174
        this._fields = fields;
805✔
175
        
176
        this._fields = this._fields?.map(f => ({...f, filters: this.getFilters(f), pipeArgs: this.getPipeArgs(f) }));
3,292✔
177
        
178
        if (!this._fields && this.isAdvancedFiltering()) {
805✔
179
            this._fields = this.entities[0].fields;
1✔
180
        }
181
    }
182

183
    /**
184
    * Returns the expression tree.
185
    */
186
    public get expressionTree(): IExpressionTree {
187
        return this._expressionTree;
6,663✔
188
    }
189

190
    /**
191
     * Sets the expression tree.
192
     */
193
    @Input()
194
    public set expressionTree(expressionTree: IExpressionTree) {
195
        this._expressionTree = expressionTree;
511✔
196
        if (!expressionTree) {
511✔
197
            this._selectedEntity = this.isAdvancedFiltering() && this.entities.length === 1 ? this.entities[0] : null;
163✔
198
            this._selectedReturnFields = this._selectedEntity ? this._selectedEntity.fields?.map(f => f.field) : [];
271✔
199
        }
200

201
        if (!this._preventInit) {
511✔
202
            this.init();
502✔
203
        }
204
    }
205

206
    /**
207
     * Gets the `locale` of the query builder.
208
     * If not set, defaults to application's locale.
209
     */
210
    @Input()
211
    public get locale(): string {
212
        return this._locale;
1,004✔
213
    }
214

215
    /**
216
     * Sets the `locale` of the query builder.
217
     * Expects a valid BCP 47 language tag.
218
     */
219
    public set locale(value: string) {
220
        this._locale = value;
452✔
221
        // if value is invalid, set it back to _localeId
222
        try {
452✔
223
            getLocaleFirstDayOfWeek(this._locale);
452✔
224
        } catch {
225
            this._locale = this._localeId;
101✔
226
        }
227
    }
228

229
    /**
230
     * Sets the resource strings.
231
     * By default it uses EN resources.
232
     */
233
    @Input()
234
    public set resourceStrings(value: IQueryBuilderResourceStrings) {
235
        this._resourceStrings = Object.assign({}, this._resourceStrings, value);
156✔
236
    }
237

238
    /**
239
     * Returns the resource strings.
240
     */
241
    public get resourceStrings(): IQueryBuilderResourceStrings {
242
        return this._resourceStrings;
245,863✔
243
    }
244

245
    /**
246
     * Gets/sets the expected return field.
247
     */
248
    @Input() public expectedReturnField: string = null;
297✔
249

250
    /**
251
     * Event fired as the expression tree is changed.
252
     */
253
    @Output()
254
    public expressionTreeChange = new EventEmitter<IExpressionTree>();
297✔
255

256
    /**
257
     * Event fired if a nested query builder tree is being edited.
258
     */
259
    @Output()
260
    public inEditModeChange = new EventEmitter<ExpressionOperandItem>();
297✔
261

262
    @ViewChild('entitySelect', { read: IgxSelectComponent })
263
    protected entitySelect: IgxSelectComponent;
264

265
    @ViewChild('editingInputs', { read: ElementRef })
266
    private editingInputs: ElementRef;
267

268
    @ViewChild('returnFieldsCombo', { read: IgxComboComponent })
269
    private returnFieldsCombo: IgxComboComponent;
270

271
    @ViewChild('returnFieldSelect', { read: IgxSelectComponent })
272
    protected returnFieldSelect: IgxSelectComponent;
273

274
    @ViewChild('fieldSelect', { read: IgxSelectComponent })
275
    private fieldSelect: IgxSelectComponent;
276

277
    @ViewChild('conditionSelect', { read: IgxSelectComponent })
278
    private conditionSelect: IgxSelectComponent;
279

280
    @ViewChild('searchValueInput', { read: ElementRef })
281
    private searchValueInput: ElementRef;
282

283
    @ViewChild('picker')
284
    private picker: IgxDatePickerComponent | IgxTimePickerComponent;
285

286
    @ViewChild('addRootAndGroupButton', { read: ElementRef })
287
    private addRootAndGroupButton: ElementRef;
288

289
    @ViewChild('addConditionButton', { read: ElementRef })
290
    private addConditionButton: ElementRef;
291

292
    @ViewChild('entityChangeDialog', { read: IgxDialogComponent })
293
    private entityChangeDialog: IgxDialogComponent;
294

295
    @ViewChild('addOptionsDropDown', { read: IgxDropDownComponent })
296
    private addExpressionItemDropDown: IgxDropDownComponent;
297

298
    @ViewChild('groupContextMenuDropDown', { read: IgxDropDownComponent })
299
    private groupContextMenuDropDown: IgxDropDownComponent;
300

301
    /**
302
     * @hidden @internal
303
     */
304
    @ViewChildren(IgxChipComponent, { read: IgxChipComponent })
305
    public expressionsChips: QueryList<IgxChipComponent>;
306

307
    @ViewChild('editingInputsContainer', { read: ElementRef })
308
    protected set editingInputsContainer(value: ElementRef) {
309
        if ((value && !this._editingInputsContainer) ||
812✔
310
            (value && this._editingInputsContainer && this._editingInputsContainer.nativeElement !== value.nativeElement)) {
311
            requestAnimationFrame(() => {
289✔
312
                this.scrollElementIntoView(value.nativeElement);
289✔
313
            });
314
        }
315

316
        this._editingInputsContainer = value;
812✔
317
    }
318

319
    /** @hidden */
320
    protected get editingInputsContainer(): ElementRef {
321
        return this._editingInputsContainer;
×
322
    }
323

324
    @ViewChild('currentGroupButtonsContainer', { read: ElementRef })
325
    protected set currentGroupButtonsContainer(value: ElementRef) {
326
        if ((value && !this._currentGroupButtonsContainer) ||
812✔
327
            (value && this._currentGroupButtonsContainer && this._currentGroupButtonsContainer.nativeElement !== value.nativeElement)) {
328
            requestAnimationFrame(() => {
370✔
329
                this.scrollElementIntoView(value.nativeElement);
370✔
330
            });
331
        }
332

333
        this._currentGroupButtonsContainer = value;
812✔
334
    }
335

336
    /** @hidden */
337
    protected get currentGroupButtonsContainer(): ElementRef {
338
        return this._currentGroupButtonsContainer;
×
339
    }
340

341
    @ViewChild('expressionsContainer')
342
    private expressionsContainer: ElementRef;
343

344
    @ViewChild('overlayOutlet', { read: IgxOverlayOutletDirective, static: true })
345
    private overlayOutlet: IgxOverlayOutletDirective;
346

347
    @ViewChildren(IgxQueryBuilderTreeComponent)
348
    private innerQueries: QueryList<IgxQueryBuilderTreeComponent>;
349

350
    /**
351
     * @hidden @internal
352
     */
353
    public innerQueryNewExpressionTree: IExpressionTree;
354

355
    /**
356
     * @hidden @internal
357
     */
358
    public rootGroup: ExpressionGroupItem;
359

360
    /**
361
     * @hidden @internal
362
     */
363
    public selectedExpressions: ExpressionOperandItem[] = [];
297✔
364

365
    /**
366
     * @hidden @internal
367
     */
368
    public currentGroup: ExpressionGroupItem;
369

370
    /**
371
     * @hidden @internal
372
     */
373
    public contextualGroup: ExpressionGroupItem;
374

375
    /**
376
     * @hidden @internal
377
     */
378
    public filteringLogics;
379

380
    /**
381
     * @hidden @internal
382
     */
383
    public selectedCondition: string;
384

385
    /**
386
     * @hidden @internal
387
     */
388
    public searchValue: { value: any } = { value: null };
297✔
389

390
    /**
391
     * @hidden @internal
392
     */
393
    public pickerOutlet: IgxOverlayOutletDirective | ElementRef;
394

395
    /**
396
     * @hidden @internal
397
     */
398
    public prevFocusedExpression: ExpressionOperandItem;
399

400
    /**
401
     * @hidden @internal
402
     */
403
    public initialOperator = 0;
297✔
404

405
    /**
406
     * @hidden @internal
407
     */
408
    public returnFieldSelectOverlaySettings: OverlaySettings = {
297✔
409
        scrollStrategy: new AbsoluteScrollStrategy(),
410
        modal: false,
411
        closeOnOutsideClick: true
412
    };
413

414
    /**
415
     * @hidden @internal
416
     */
417
    public entitySelectOverlaySettings: OverlaySettings = {
297✔
418
        scrollStrategy: new AbsoluteScrollStrategy(),
419
        modal: false,
420
        closeOnOutsideClick: true
421
    };
422

423
    /**
424
     * @hidden @internal
425
     */
426
    public fieldSelectOverlaySettings: OverlaySettings = {
297✔
427
        scrollStrategy: new AbsoluteScrollStrategy(),
428
        modal: false,
429
        closeOnOutsideClick: true
430
    };
431

432
    /**
433
     * @hidden @internal
434
     */
435
    public conditionSelectOverlaySettings: OverlaySettings = {
297✔
436
        scrollStrategy: new AbsoluteScrollStrategy(),
437
        modal: false,
438
        closeOnOutsideClick: true
439
    };
440

441
    /**
442
     * @hidden @internal
443
     */
444
    public addExpressionDropDownOverlaySettings: OverlaySettings = {
297✔
445
        scrollStrategy: new AbsoluteScrollStrategy(),
446
        modal: false,
447
        closeOnOutsideClick: true
448
    };
449

450
    /**
451
     * @hidden @internal
452
     */
453
    public groupContextMenuDropDownOverlaySettings: OverlaySettings = {
297✔
454
        scrollStrategy: new AbsoluteScrollStrategy(),
455
        modal: false,
456
        closeOnOutsideClick: true
457
    };
458

459
    private destroy$ = new Subject<any>();
297✔
460
    private _timeoutId: any;
461
    private _lastFocusedChipIndex: number;
462
    private _focusDelay = DEFAULT_CHIP_FOCUS_DELAY;
297✔
463
    private _parentExpression: ExpressionOperandItem;
464
    private _selectedEntity: EntityType;
465
    private _selectedReturnFields: string | string[];
466
    private _selectedField: FieldType;
467
    private _editingInputsContainer: ElementRef;
468
    private _currentGroupButtonsContainer: ElementRef;
469
    private _addModeExpression: ExpressionOperandItem;
470
    private _editedExpression: ExpressionOperandItem;
471
    private _preventInit = false;
297✔
472
    private _prevFocusedContainer: ElementRef;
473
    private _expandedExpressions: IFilteringExpression[] = [];
297✔
474
    private _fields: FieldType[];
475
    private _locale;
476
    private _entityNewValue: EntityType;
477
    private _resourceStrings = getCurrentResourceStrings(QueryBuilderResourceStringsEN);
297✔
478

479
    /**
480
     * Returns if the select entity dropdown at the root level is disabled after the initial selection.
481
     */
482
    public get disableEntityChange(): boolean {
483

484
        return !this.parentExpression && this.selectedEntity ? this.queryBuilder.disableEntityChange : false;
12,215✔
485
    }
486

487
    /**
488
     * Returns if the fields combo at the root level is disabled.
489
     */
490
    public get disableReturnFieldsChange(): boolean {
491

492
        return !this.selectedEntity || this.queryBuilder.disableReturnFieldsChange;
5,852✔
493
    }
494

495
    /**
496
     * Returns the current level.
497
     */
498
    public get level(): number {
499
        let parent = this.elRef.nativeElement.parentElement;
11,419✔
500
        let _level = 0;
11,419✔
501
        while (parent) {
11,419✔
502
            if (parent.localName === 'igx-query-builder-tree') {
96,197✔
503
                _level++;
6,177✔
504
            }
505
            parent = parent.parentElement;
96,197✔
506
        }
507
        return _level;
11,419✔
508
    }
509

510
    private _positionSettings = {
297✔
511
        horizontalStartPoint: HorizontalAlignment.Right,
512
        verticalStartPoint: VerticalAlignment.Top
513
    };
514

515
    private _overlaySettings: OverlaySettings = {
297✔
516
        closeOnOutsideClick: false,
517
        modal: false,
518
        positionStrategy: new ConnectedPositioningStrategy(this._positionSettings),
519
        scrollStrategy: new CloseScrollStrategy()
520
    };
521

522
    /** @hidden */
523
    protected isAdvancedFiltering(): boolean {
524
        return (this.entities?.length === 1 && !this.entities[0]?.name) ||
20,864✔
525
            this.entities?.find(e => e.childEntities?.length > 0) !== undefined ||
37,086✔
526
            this.entities !== this.queryBuilder?.entities;
527
    }
528

529
    /** @hidden */
530
    protected isHierarchicalNestedQuery(): boolean {
531
        return this.queryBuilder.entities !== this.entities
14,244✔
532
    }
533

534
    /** @hidden */
535
    protected isSearchValueInputDisabled(): boolean {
536
        return !this.selectedField ||
1,704✔
537
            !this.selectedCondition ||
538
            (this.selectedField &&
539
                (this.selectedField.filters.condition(this.selectedCondition).isUnary ||
540
                    this.selectedField.filters.condition(this.selectedCondition).isNestedQuery));
541
    }
542

543
    constructor(public cdr: ChangeDetectorRef,
297✔
544
        public dragService: IgxQueryBuilderDragService,
297✔
545
        protected platform: PlatformUtil,
297✔
546
        private elRef: ElementRef,
297✔
547
        @Inject(LOCALE_ID) protected _localeId: string) {
297✔
548
        this.locale = this.locale || this._localeId;
297✔
549
        this.dragService.register(this, elRef);
297✔
550
    }
551

552
    /**
553
     * @hidden @internal
554
     */
555
    public ngAfterViewInit(): void {
556
        this._overlaySettings.outlet = this.overlayOutlet;
297✔
557
        this.entitySelectOverlaySettings.outlet = this.overlayOutlet;
297✔
558
        this.fieldSelectOverlaySettings.outlet = this.overlayOutlet;
297✔
559
        this.conditionSelectOverlaySettings.outlet = this.overlayOutlet;
297✔
560
        this.returnFieldSelectOverlaySettings.outlet = this.overlayOutlet;
297✔
561
        this.addExpressionDropDownOverlaySettings.outlet = this.overlayOutlet;
297✔
562
        this.groupContextMenuDropDownOverlaySettings.outlet = this.overlayOutlet;
297✔
563
        
564
        if (this.isAdvancedFiltering() && this.entities?.length === 1) {
297✔
565
            this.selectedEntity = this.entities[0].name;
59✔
566
            if (this._selectedEntity.fields.find(f => f.field === this.expectedReturnField)) {
329✔
567
                this._selectedReturnFields = [this.expectedReturnField];
5✔
568
            }
569
        }
570

571
        // Trigger additional change detection cycle
572
        this.cdr.detectChanges();
297✔
573
    }
574

575
    /**
576
     * @hidden @internal
577
     */
578
    public ngOnDestroy(): void {
579
        this.destroy$.next(true);
297✔
580
        this.destroy$.complete();
297✔
581
    }
582

583
    /**
584
     * @hidden @internal
585
     */
586
    public set selectedEntity(value: string) {
587
        this._selectedEntity = this.entities?.find(el => el.name === value);
59✔
588
    }
589

590
    /**
591
     * @hidden @internal
592
     */
593
    public get selectedEntity(): EntityType {
594
        return this._selectedEntity;
85,180✔
595
    }
596

597
    /**
598
     * @hidden @internal
599
     */
600
    public onEntitySelectChanging(event: ISelectionEventArgs) {
601
        event.cancel = true;
43✔
602
        this._entityNewValue = event.newSelection.value;
43✔
603
        if (event.oldSelection.value && this.queryBuilder.showEntityChangeDialog) {
43✔
604
            this.entityChangeDialog.open();
6✔
605
        } else {
606
            this.onEntityChangeConfirm();
37✔
607
        }
608
    }
609

610
    /**
611
     * @hidden
612
     */
613
    public onShowEntityChangeDialogChange(eventArgs: IChangeCheckboxEventArgs) {
614
        this.queryBuilder.showEntityChangeDialog = !eventArgs.checked;
1✔
615
    }
616

617
    /**
618
     * @hidden
619
     */
620
    public onEntityChangeCancel() {
621
        this.entityChangeDialog.close();
3✔
622
        this.entitySelect.close();
3✔
623
        this._entityNewValue = null;
3✔
624
    }
625

626
    /**
627
     * @hidden
628
     */
629
    public onEntityChangeConfirm() {
630
        if (this._parentExpression) {
39✔
631
            this._expressionTree = this.createExpressionTreeFromGroupItem(this.createExpressionGroupItem(this._expressionTree));
6✔
632
        }
633

634
        this._selectedEntity = this._entityNewValue;
39✔
635
        if (!this._selectedEntity.fields) {
39!
636
            this._selectedEntity.fields = [];
×
637
        }
638
        this.fields = this._entityNewValue ? this._entityNewValue.fields : [];
39!
639

640
        if (this._selectedEntity.fields.find(f => f.field === this.expectedReturnField)) {
150✔
641
            this._selectedReturnFields = [this.expectedReturnField];
6✔
642
        } else {
643
            this._selectedReturnFields = this.parentExpression ? [] : this._entityNewValue.fields?.map(f => f.field);
132!
644
        }
645

646
        if (this._expressionTree) {
39✔
647
            this._expressionTree.entity = this._entityNewValue.name;
5✔
648

649
            this._expressionTree.returnFields = this.fields.length === this._selectedReturnFields.length ? ['*'] : this._selectedReturnFields;
5✔
650

651
            this._expressionTree.filteringOperands = [];
5✔
652

653
            this._editedExpression = null;
5✔
654
            if (!this.parentExpression) {
5✔
655
                this.expressionTreeChange.emit(this._expressionTree);
4✔
656
            }
657

658
            this.rootGroup = null;
5✔
659
            this.currentGroup = this.rootGroup;
5✔
660
        }
661

662
        this._selectedField = null;
39✔
663
        this.selectedCondition = null;
39✔
664
        this.searchValue.value = null;
39✔
665

666
        this.entityChangeDialog.close();
39✔
667
        this.entitySelect.close();
39✔
668

669
        this._entityNewValue = null;
39✔
670
        this.innerQueryNewExpressionTree = null;
39✔
671

672
        this.initExpressionTree(this._selectedEntity.name, this.selectedReturnFields);
39✔
673
    }
674

675
    /**
676
     * @hidden @internal
677
     */
678
    public set selectedReturnFields(value: string[]) {
679
        if (this._selectedReturnFields !== value) {
5✔
680
            this._selectedReturnFields = value;
5✔
681

682
            if (this._expressionTree && !this.parentExpression) {
5✔
683
                this._expressionTree.returnFields = value.length === this.fields.length ? ['*'] : value;
5✔
684
                this.expressionTreeChange.emit(this._expressionTree);
5✔
685
            }
686
        }
687
    }
688

689
    /**
690
     * @hidden @internal
691
     */
692
    public get selectedReturnFields(): string[] {
693
        if (typeof this._selectedReturnFields == 'string') {
51,611!
694
            return [this._selectedReturnFields];
×
695
        }
696
        return this._selectedReturnFields;
51,611✔
697
    }
698

699
    /**
700
     * @hidden @internal
701
     */
702
    public set selectedField(value: FieldType) {
703
        const oldValue = this._selectedField;
207✔
704

705
        if (this._selectedField !== value) {
207✔
706
            this._selectedField = value;
175✔
707
            if (this._selectedField && !this._selectedField.dataType) {
175!
NEW
708
                this._selectedField.filters = this.getFilters(this._selectedField);
×
709
            }
710

711
            this.selectDefaultCondition();
175✔
712
            if (oldValue && this._selectedField && this._selectedField.dataType !== oldValue.dataType) {
175✔
713
                this.searchValue.value = null;
17✔
714
                this.cdr.detectChanges();
17✔
715
            }
716
        }
717
    }
718

719
    /**
720
     * @hidden @internal
721
     */
722
    public get selectedField(): FieldType {
723
        return this._selectedField;
57,814✔
724
    }
725

726
    /**
727
     * @hidden @internal
728
     *
729
     * used by the grid
730
     */
731
    public setPickerOutlet(outlet?: IgxOverlayOutletDirective | ElementRef) {
732
        this.pickerOutlet = outlet;
54✔
733
    }
734

735
    /**
736
     * @hidden @internal
737
     *
738
     * used by the grid
739
     */
740
    public get isContextMenuVisible(): boolean {
741
        return !this.groupContextMenuDropDown.collapsed;
×
742
    }
743

744
    /**
745
     * @hidden @internal
746
     */
747
    public get hasEditedExpression(): boolean {
748
        return this._editedExpression !== undefined && this._editedExpression !== null;
31,287✔
749
    }
750

751
    /**
752
     * @hidden @internal
753
     */
754
    public addCondition(parent: ExpressionGroupItem, afterExpression?: ExpressionOperandItem, isUIInteraction?: boolean) {
755
        this.cancelOperandAdd();
81✔
756

757
        const operandItem = new ExpressionOperandItem({
81✔
758
            fieldName: null,
759
            condition: null,
760
            conditionName: null,
761
            ignoreCase: true,
762
            searchVal: null
763
        }, parent);
764

765
        const groupItem = new ExpressionGroupItem(this.getOperator(null) ?? FilteringLogic.And, parent);
81!
766
        this.contextualGroup = groupItem;
81✔
767
        this.initialOperator = null;
81✔
768

769
        this._lastFocusedChipIndex = this._lastFocusedChipIndex === undefined ? -1 : this._lastFocusedChipIndex;
81✔
770

771
        if (parent) {
81✔
772
            if (afterExpression) {
11✔
773
                const index = parent.children.indexOf(afterExpression);
1✔
774
                parent.children.splice(index + 1, 0, operandItem);
1✔
775
            } else {
776
                parent.children.push(operandItem);
10✔
777
            }
778
            this._lastFocusedChipIndex++;
11✔
779
        } else {
780
            this.rootGroup = groupItem;
70✔
781
            operandItem.parent = groupItem;
70✔
782
            this.rootGroup.children.push(operandItem);
70✔
783
            this._lastFocusedChipIndex = 0;
70✔
784
        }
785

786
        this._focusDelay = 250;
81✔
787

788
        if (isUIInteraction && !afterExpression) {
81✔
789
            this._lastFocusedChipIndex = this.expressionsChips.length;
77✔
790
            this._focusDelay = DEFAULT_CHIP_FOCUS_DELAY;
77✔
791
        }
792

793
        this.enterExpressionEdit(operandItem);
81✔
794
    }
795

796
    /**
797
     * @hidden @internal
798
     */
799
    public addReverseGroup(parent?: ExpressionGroupItem, afterExpression?: ExpressionItem) {
800
        parent = parent ?? this.rootGroup;
3!
801

802
        if (parent.operator === FilteringLogic.And) {
3✔
803
            this.addGroup(FilteringLogic.Or, parent, afterExpression);
2✔
804
        } else {
805
            this.addGroup(FilteringLogic.And, parent, afterExpression);
1✔
806
        }
807
    }
808

809
    /**
810
     * @hidden @internal
811
     */
812
    public endGroup(groupItem: ExpressionGroupItem) {
813
        this.currentGroup = groupItem.parent;
×
814
    }
815

816
    /**
817
     * @hidden @internal
818
     */
819
    public commitExpression() {
820
        this.commitOperandEdit();
46✔
821
        this.focusEditedExpressionChip();
46✔
822
    }
823

824
    /**
825
     * @hidden @internal
826
     */
827
    public discardExpression(expressionItem?: ExpressionOperandItem) {
828
        this.cancelOperandEdit();
11✔
829
        if (expressionItem && expressionItem.expression.fieldName) {
11✔
830
            this.focusEditedExpressionChip();
4✔
831
        }
832
    }
833

834
    /**
835
     * @hidden @internal
836
     */
837
    public commitOperandEdit() {
838
        const actualSearchValue = this.searchValue.value;
61✔
839
        if (this._editedExpression) {
61✔
840
            this._editedExpression.expression.fieldName = this.selectedField.field;
58✔
841
            this._editedExpression.expression.condition = this.selectedField.filters.condition(this.selectedCondition);
58✔
842
            this._editedExpression.expression.conditionName = this.selectedCondition;
58✔
843
            this._editedExpression.expression.searchVal = DataUtil.parseValue(this.selectedField.dataType, actualSearchValue) || actualSearchValue;
58✔
844
            this._editedExpression.fieldLabel = this.selectedField.label
58!
845
                ? this.selectedField.label
846
                : this.selectedField.header
58!
847
                    ? this.selectedField.header
848
                    : this.selectedField.field;
849

850
            const innerQuery = this.innerQueries.filter(q => q.isInEditMode())[0]
58✔
851
            if (innerQuery && this.selectedField?.filters?.condition(this.selectedCondition)?.isNestedQuery) {
58✔
852
                innerQuery.exitEditAddMode();
8✔
853
                this._editedExpression.expression.searchTree = this.getExpressionTreeCopy(innerQuery.expressionTree);
8✔
854
                const returnFields = innerQuery.selectedReturnFields.length > 0 ?
8!
855
                                        innerQuery.selectedReturnFields :
856
                                        [innerQuery.fields[0].field];
857
                this._editedExpression.expression.searchTree.returnFields = returnFields;
8✔
858
            } else {
859
                this._editedExpression.expression.searchTree = null;
50✔
860
            }
861
            this.innerQueryNewExpressionTree = null;
58✔
862

863
            if (this.selectedField.filters.condition(this.selectedCondition)?.isUnary || this.selectedField.filters.condition(this.selectedCondition)?.isNestedQuery) {
58✔
864
                this._editedExpression.expression.searchVal = null;
13✔
865
            }
866

867
            this._editedExpression.inEditMode = false;
58✔
868
            this._editedExpression = null;
58✔
869
        }
870

871
        if (this.selectedReturnFields.length === 0) {
61!
NEW
872
            this.selectedReturnFields = this.fields.map(f => f.field);
×
873
        }
874

875
        this._expressionTree = this.createExpressionTreeFromGroupItem(this.rootGroup, this.selectedEntity?.name, this.selectedReturnFields);
61✔
876
        if (!this.parentExpression) {
61✔
877
            this.expressionTreeChange.emit(this._expressionTree);
51✔
878
        }
879
    }
880

881
    /**
882
     * @hidden @internal
883
     */
884
    public cancelOperandAdd() {
885
        if (this._addModeExpression) {
601!
886
            this._addModeExpression.inAddMode = false;
×
887
            this._addModeExpression = null;
×
888
        }
889
    }
890

891
    /**
892
     * @hidden @internal
893
     */
894
    public deleteItem = (expressionItem: ExpressionItem, skipEmit: boolean = false) => {
297✔
895
        if (!expressionItem.parent) {
48✔
896
            this.rootGroup = null;
15✔
897
            this.currentGroup = null;
15✔
898
            //this._expressionTree = null;
899
            return;
15✔
900
        }
901

902
        if (expressionItem === this.currentGroup) {
33!
903
            this.currentGroup = this.currentGroup.parent;
×
904
        }
905

906
        const children = expressionItem.parent.children;
33✔
907
        const index = children.indexOf(expressionItem);
33✔
908
        children.splice(index, 1);
33✔
909
        const entity = this.expressionTree ? this.expressionTree.entity : null;
33✔
910
        const returnFields = this.expressionTree ? this.expressionTree.returnFields : null;
33✔
911
        this._expressionTree = this.createExpressionTreeFromGroupItem(this.rootGroup, entity, returnFields); // TODO: don't recreate if not necessary
33✔
912

913
        if (!children.length) {
33✔
914
            this.deleteItem(expressionItem.parent, true);
16✔
915
        }
916

917
        if (!this.parentExpression && !skipEmit) {
33✔
918
            this.expressionTreeChange.emit(this._expressionTree);
31✔
919
        }
920
    }
921

922
    /**
923
     * @hidden @internal
924
     */
925
    public cancelOperandEdit() {
926
        if (this.innerQueries) {
529✔
927
            const innerQuery = this.innerQueries.filter(q => q.isInEditMode())[0];
232✔
928
            if (innerQuery) {
232✔
929
                if (innerQuery._editedExpression) {
9✔
930
                    innerQuery.cancelOperandEdit();
1✔
931
                }
932

933
                innerQuery.expressionTree = this.getExpressionTreeCopy(this._editedExpression.expression.searchTree);
9✔
934
                this.innerQueryNewExpressionTree = null;
9✔
935
            }
936
        }
937

938
        if (this._editedExpression) {
529✔
939
            this._editedExpression.inEditMode = false;
30✔
940

941
            if (!this._editedExpression.expression.fieldName) {
30✔
942
                this.deleteItem(this._editedExpression);
16✔
943
            }
944

945
            this._editedExpression = null;
30✔
946
        }
947

948
        if (!this.expressionTree && this.contextualGroup) {
529✔
949
            this.initialOperator = this.contextualGroup.operator;
1✔
950
        }
951
    }
952

953
    /**
954
     * @hidden @internal
955
     */
956
    public operandCanBeCommitted(): boolean {
957
        const innerQuery = this.innerQueries.filter(q => q.isInEditMode())[0];
1,771✔
958
        return this.selectedField && this.selectedCondition &&
1,771✔
959
            (
960
                (
961
                    ((!Array.isArray(this.searchValue.value) && !!this.searchValue.value) || (Array.isArray(this.searchValue.value) && this.searchValue.value.length !== 0)) &&
962
                    !(this.selectedField?.filters?.condition(this.selectedCondition)?.isNestedQuery)
963
                ) ||
964
                (
965
                    this.selectedField?.filters?.condition(this.selectedCondition)?.isNestedQuery && innerQuery && !!innerQuery.expressionTree && innerQuery.selectedReturnFields?.length > 0
966
                ) ||
967
                this.selectedField.filters.condition(this.selectedCondition)?.isUnary
968
            );
969
    }
970
    
971
    /**
972
     * @hidden @internal
973
     */
974
    public canCommitCurrentState(): boolean {
975
        const innerQuery = this.innerQueries.filter(q => q.isInEditMode())[0];
36✔
976
        if (innerQuery) {
36✔
977
            return this.selectedReturnFields?.length > 0 && innerQuery.canCommitCurrentState();
8✔
978
        } else {
979
            return this.selectedReturnFields?.length > 0 &&
28✔
980
                (
981
                    (!this._editedExpression) || // no edited expr
982
                    (this._editedExpression && !this.selectedField) || // empty edited expr
983
                    (this._editedExpression && this.operandCanBeCommitted() === true) // valid edited expr
984
                );
985
        }
986
    }
987

988
    /**
989
     * @hidden @internal
990
     */
991
    public commitCurrentState(): void {
992
        const innerQuery = this.innerQueries.filter(q => q.isInEditMode())[0];
3✔
993
        if (innerQuery) {
3✔
994
            innerQuery.commitCurrentState();
1✔
995
        }
996

997
        if (this._editedExpression) {
3✔
998
            if (this.selectedField) {
3!
999
                this.commitOperandEdit();
3✔
1000
            } else {
1001
                this.deleteItem(this._editedExpression);
×
1002
                this._editedExpression = null;
×
1003
            }
1004
        }
1005
    }
1006

1007
    /**
1008
     * @hidden @internal
1009
     */
1010
    public exitEditAddMode(shouldPreventInit = false) {
47✔
1011
        if (!this._editedExpression) {
239✔
1012
            return;
224✔
1013
        }
1014

1015
        this.exitOperandEdit();
15✔
1016
        this.cancelOperandAdd();
15✔
1017

1018
        if (shouldPreventInit) {
15✔
1019
            this._preventInit = true;
7✔
1020
        }
1021
    }
1022

1023
    /**
1024
     * @hidden @internal
1025
     *
1026
     * used by the grid
1027
     */
1028
    public exitOperandEdit() {
1029
        if (!this._editedExpression) {
35✔
1030
            return;
16✔
1031
        }
1032

1033
        if (this.operandCanBeCommitted()) {
19✔
1034
            this.commitOperandEdit();
9✔
1035
        } else {
1036
            this.cancelOperandEdit();
10✔
1037
        }
1038
    }
1039

1040
    /**
1041
     * @hidden @internal
1042
     */
1043
    public isExpressionGroup(expression: ExpressionItem): boolean {
1044
        return expression instanceof ExpressionGroupItem;
34,557✔
1045
    }
1046

1047
    /**
1048
     * @hidden @internal
1049
     */
1050
    public onExpressionFocus(expressionItem: ExpressionOperandItem) {
1051
        if (this.prevFocusedExpression) {
41✔
1052
            this.prevFocusedExpression.focused = false;
4✔
1053
        }
1054
        expressionItem.focused = true;
41✔
1055
        this.prevFocusedExpression = expressionItem;
41✔
1056
    }
1057

1058
    /**
1059
     * @hidden @internal
1060
     */
1061
    public onExpressionBlur(event, expressionItem: ExpressionOperandItem) {
1062
        if (this._prevFocusedContainer && this._prevFocusedContainer !== event.target.closest('.igx-filter-tree__expression-item')) {
2!
1063
            expressionItem.focused = false;
×
1064
        }
1065
        this._prevFocusedContainer = event.target.closest('.igx-filter-tree__expression-item');
2✔
1066
    }
1067

1068
    /**
1069
     * @hidden @internal
1070
     */
1071
    public onChipRemove(expressionItem: ExpressionItem) {
1072
        this.exitEditAddMode();
5✔
1073
        this.deleteItem(expressionItem);
5✔
1074
    }
1075

1076
    /**
1077
     * @hidden @internal
1078
     */
1079
    public focusChipAfterDrag = (index: number) => {
297✔
1080
        this._lastFocusedChipIndex = index;
11✔
1081
        this.focusEditedExpressionChip();
11✔
1082
    }
1083
    /**
1084
     * @hidden @internal
1085
     */
1086
    public addExpressionBlur() {
1087
        if (this.prevFocusedExpression) {
×
1088
            this.prevFocusedExpression.focused = false;
×
1089
        }
1090
        if (this.addExpressionItemDropDown && !this.addExpressionItemDropDown.collapsed) {
×
1091
            this.addExpressionItemDropDown.close();
×
1092
        }
1093
    }
1094

1095
    /**
1096
     * @hidden @internal
1097
     */
1098
    public onChipClick(expressionItem: ExpressionOperandItem, chip: IgxChipComponent) {
1099
        this.enterExpressionEdit(expressionItem, chip);
55✔
1100
    }
1101

1102
    /**
1103
     * @hidden @internal
1104
     */
1105
    public enterExpressionEdit(expressionItem: ExpressionOperandItem, chip?: IgxChipComponent) {
1106
        this.exitEditAddMode(true);
136✔
1107
        this.cdr.detectChanges();
136✔
1108
        this._lastFocusedChipIndex = chip ? this.expressionsChips.toArray().findIndex(expr => expr === chip) : this._lastFocusedChipIndex;
136✔
1109
        this.enterEditMode(expressionItem);
136✔
1110
    }
1111

1112

1113
    /**
1114
     * @hidden @internal
1115
     */
1116
    public clickExpressionAdd(targetButton: HTMLElement, chip: IgxChipComponent) {
1117
        this.exitEditAddMode(true);
4✔
1118
        this.cdr.detectChanges();
4✔
1119
        this._lastFocusedChipIndex = this.expressionsChips.toArray().findIndex(expr => expr === chip);
22✔
1120
        this.openExpressionAddDialog(targetButton);
4✔
1121
    }
1122

1123
    /**
1124
     * @hidden @internal
1125
     */
1126
    public openExpressionAddDialog(targetButton: HTMLElement) {
1127
        this.addExpressionDropDownOverlaySettings.target = targetButton;
4✔
1128
        this.addExpressionDropDownOverlaySettings.positionStrategy = new ConnectedPositioningStrategy({
4✔
1129
            horizontalDirection: HorizontalAlignment.Right,
1130
            horizontalStartPoint: HorizontalAlignment.Left,
1131
            verticalStartPoint: VerticalAlignment.Bottom
1132
        });
1133

1134
        this.addExpressionItemDropDown.open(this.addExpressionDropDownOverlaySettings);
4✔
1135
    }
1136

1137
    /**
1138
     * @hidden @internal
1139
     */
1140
    public enterExpressionAdd(event: ISelectionEventArgs, expressionItem: ExpressionOperandItem) {
1141
        if (this._addModeExpression) {
1!
1142
            this._addModeExpression.inAddMode = false;
×
1143
        }
1144

1145
        if (this.parentExpression) {
1!
1146
            this.inEditModeChange.emit(this.parentExpression);
×
1147
        }
1148

1149
        const parent = expressionItem.parent ?? this.rootGroup;
1!
1150
        requestAnimationFrame(() => {
1✔
1151
            if (event.newSelection.value === 'addCondition') {
1!
1152
                this.addCondition(parent, expressionItem);
1✔
1153
            } else if (event.newSelection.value === 'addGroup') {
×
1154
                this.addReverseGroup(parent, expressionItem);
×
1155
            }
1156
            expressionItem.inAddMode = true;
1✔
1157
            this._addModeExpression = expressionItem;
1✔
1158
        })
1159
    }
1160

1161
    /**
1162
     * @hidden @internal
1163
     */
1164
    public enterEditMode(expressionItem: ExpressionOperandItem) {
1165
        if (this._editedExpression) {
136!
1166
            this._editedExpression.inEditMode = false;
×
1167
        }
1168

1169
        if (this.parentExpression) {
136✔
1170
            this.inEditModeChange.emit(this.parentExpression);
16✔
1171
        }
1172

1173
        expressionItem.hovered = false;
136✔
1174
        this.fields = this.selectedEntity ? this.selectedEntity.fields : null;
136✔
1175
        this.selectedField =
136✔
1176
            expressionItem.expression.fieldName ?
136✔
1177
                this.fields?.find(field => field.field === expressionItem.expression.fieldName)
89✔
1178
                : null;
1179
        this.selectedCondition =
136✔
1180
            expressionItem.expression.condition ?
136✔
1181
                expressionItem.expression.condition.name :
1182
                null;
1183
        this.searchValue.value = expressionItem.expression.searchVal instanceof Set ?
136✔
1184
            Array.from(expressionItem.expression.searchVal) :
1185
            expressionItem.expression.searchVal;
1186

1187
        expressionItem.inEditMode = true;
136✔
1188
        this._editedExpression = expressionItem;
136✔
1189
        this.cdr.detectChanges();
136✔
1190

1191
        this.entitySelectOverlaySettings.target = this.entitySelect.element;
136✔
1192
        this.entitySelectOverlaySettings.excludeFromOutsideClick = [this.entitySelect.element as HTMLElement];
136✔
1193
        this.entitySelectOverlaySettings.positionStrategy = new AutoPositionStrategy();
136✔
1194

1195
        if (this.returnFieldSelect) {
136✔
1196
            this.returnFieldSelectOverlaySettings.target = this.returnFieldSelect.element;
16✔
1197
            this.returnFieldSelectOverlaySettings.excludeFromOutsideClick = [this.returnFieldSelect.element as HTMLElement];
16✔
1198
            this.returnFieldSelectOverlaySettings.positionStrategy = new AutoPositionStrategy();
16✔
1199
        }
1200
        if (this.fieldSelect) {
136✔
1201
            this.fieldSelectOverlaySettings.target = this.fieldSelect.element;
133✔
1202
            this.fieldSelectOverlaySettings.excludeFromOutsideClick = [this.fieldSelect.element as HTMLElement];
133✔
1203
            this.fieldSelectOverlaySettings.positionStrategy = new AutoPositionStrategy();
133✔
1204
        }
1205
        if (this.conditionSelect) {
136✔
1206
            this.conditionSelectOverlaySettings.target = this.conditionSelect.element;
133✔
1207
            this.conditionSelectOverlaySettings.excludeFromOutsideClick = [this.conditionSelect.element as HTMLElement];
133✔
1208
            this.conditionSelectOverlaySettings.positionStrategy = new AutoPositionStrategy();
133✔
1209
        }
1210

1211
        if (!this.selectedField) {
136✔
1212
            this.fieldSelect.input.nativeElement.focus();
81✔
1213
        } else if (this.selectedField.filters.condition(this.selectedCondition)?.isUnary) {
55✔
1214
            this.conditionSelect?.input.nativeElement.focus();
5✔
1215
        } else {
1216
            const input = this.searchValueInput?.nativeElement || this.picker?.getEditElement();
50✔
1217
            input?.focus();
50✔
1218
        }
1219

1220
        (this.editingInputs?.nativeElement.parentElement as HTMLElement)?.scrollIntoView({ block: "nearest", inline: "nearest" });
136✔
1221
    }
1222

1223
    /**
1224
     * @hidden @internal
1225
     */
1226
    public onConditionSelectChanging(event: ISelectionEventArgs) {
1227
        event.cancel = true;
68✔
1228
        this.selectedCondition = event.newSelection.value;
68✔
1229
        this.conditionSelect.close();
68✔
1230
        this.cdr.detectChanges();
68✔
1231
    }
1232

1233
    /**
1234
     * @hidden @internal
1235
     */
1236
    public onKeyDown(eventArgs: KeyboardEvent) {
1237
        eventArgs.stopPropagation();
×
1238
    }
1239

1240
    /**
1241
     * @hidden @internal
1242
     */
1243
    public onGroupClick(groupContextMenuDropDown: any, targetButton: HTMLButtonElement, groupItem: ExpressionGroupItem) {
1244
        this.exitEditAddMode();
7✔
1245
        this.cdr.detectChanges();
7✔
1246

1247
        this.groupContextMenuDropDown = groupContextMenuDropDown;
7✔
1248
        this.groupContextMenuDropDownOverlaySettings.target = targetButton;
7✔
1249
        this.groupContextMenuDropDownOverlaySettings.positionStrategy = new ConnectedPositioningStrategy({
7✔
1250
            horizontalDirection: HorizontalAlignment.Right,
1251
            horizontalStartPoint: HorizontalAlignment.Left,
1252
            verticalStartPoint: VerticalAlignment.Bottom
1253
        });
1254

1255
        if (groupContextMenuDropDown.collapsed) {
7!
1256
            this.contextualGroup = groupItem;
7✔
1257
            groupContextMenuDropDown.open(this.groupContextMenuDropDownOverlaySettings);
7✔
1258
        } else {
1259
            groupContextMenuDropDown.close();
×
1260
        }
1261
    }
1262

1263
    /**
1264
     * @hidden @internal
1265
     */
1266
    public getOperator(expressionItem: any) {
1267
        // if (!expressionItem && !this.expressionTree && !this.initialOperator) {
1268
        //     this.initialOperator = 0;
1269
        // }
1270

1271
        const operator = expressionItem ?
89,937✔
1272
            expressionItem.operator :
1273
            this.expressionTree ?
3,135✔
1274
                this.expressionTree.operator :
1275
                this.initialOperator;
1276
        return operator;
89,937✔
1277
    }
1278

1279
    /**
1280
     * @hidden @internal
1281
     */
1282
    public getSwitchGroupText(expressionItem: any) {
1283
        const operator = this.getOperator(expressionItem);
14,976✔
1284
        const condition = operator === FilteringLogic.Or ? this.resourceStrings.igx_query_builder_and_label : this.resourceStrings.igx_query_builder_or_label
14,976✔
1285
        return this.resourceStrings.igx_query_builder_switch_group.replace('{0}', condition.toUpperCase());
14,976✔
1286
    }
1287

1288
    /**
1289
     * @hidden @internal
1290
     */
1291
    public onGroupContextMenuDropDownSelectionChanging(event: ISelectionEventArgs) {
1292
        event.cancel = true;
4✔
1293

1294
        if (event.newSelection.value === 'switchCondition') {
4✔
1295
            const newOperator = (!this.expressionTree ? this.initialOperator : (this.contextualGroup ?? this._expressionTree).operator) === 0 ? 1 : 0;
3!
1296
            this.selectFilteringLogic(newOperator);
3✔
1297
        } else if (event.newSelection.value === 'ungroup') {
1✔
1298
            this.ungroup();
1✔
1299
        }
1300

1301
        this.groupContextMenuDropDown.close();
4✔
1302
    }
1303

1304
    /**
1305
     * @hidden @internal
1306
     */
1307
    public ungroup() {
1308
        const selectedGroup = this.contextualGroup;
1✔
1309
        const parent = selectedGroup.parent;
1✔
1310
        if (parent) {
1✔
1311
            const index = parent.children.indexOf(selectedGroup);
1✔
1312
            parent.children.splice(index, 1, ...selectedGroup.children);
1✔
1313

1314
            for (const expr of selectedGroup.children) {
1✔
1315
                expr.parent = parent;
2✔
1316
            }
1317
        }
1318
        this.commitOperandEdit();
1✔
1319
    }
1320

1321
    /**
1322
     * @hidden @internal
1323
     */
1324
    public selectFilteringLogic(index: number) {
1325
        if (!this.expressionTree) {
3!
1326
            this.initialOperator = index;
×
1327
            return;
×
1328
        }
1329

1330
        if (this.contextualGroup) {
3✔
1331
            this.contextualGroup.operator = index as FilteringLogic;
2✔
1332
            this.commitOperandEdit();
2✔
1333
        } else if (this.expressionTree) {
1✔
1334
            this._expressionTree.operator = index as FilteringLogic;
1✔
1335
        }
1336

1337
        this.initialOperator = null;
3✔
1338
    }
1339

1340
    /**
1341
     * @hidden @internal
1342
     */
1343
    public getConditionFriendlyName(name: string): string {
1344
        // As we have an 'In' condition already used in ESF to search in a Set, we add the 'Query' suffix to the newly introduced nested query condition names.
1345
        // So instead of in/notIn we end up with 'inQuery'/'notInQuery', hence removing the suffix from the friendly name.
1346
        return this.resourceStrings[`igx_query_builder_filter_${name?.replace('Query', '')}`] || name;
60,969✔
1347
    }
1348

1349
    /**
1350
     * @hidden @internal
1351
     */
1352
    public isDate(value: any) {
1353
        return value instanceof Date;
20,059✔
1354
    }
1355

1356
    /**
1357
     * @hidden @internal
1358
     */
1359
    public invokeClick(eventArgs: KeyboardEvent) {
1360
        if (!this.dragService.dropGhostExpression && this.platform.isActivationKey(eventArgs)) {
2✔
1361
            eventArgs.preventDefault();
2✔
1362
            (eventArgs.currentTarget as HTMLElement).click();
2✔
1363
        }
1364
    }
1365

1366
    /**
1367
     * @hidden @internal
1368
     */
1369
    public openPicker(args: KeyboardEvent) {
1370
        if (this.platform.isActivationKey(args)) {
×
1371
            args.preventDefault();
×
1372
            this.picker.open();
×
1373
        }
1374
    }
1375

1376
    /**
1377
     * @hidden @internal
1378
     */
1379
    public onOutletPointerDown(event) {
1380
        // This prevents closing the select's dropdown when clicking the scroll
1381
        event.preventDefault();
60✔
1382
    }
1383

1384
    /**
1385
     * @hidden @internal
1386
     */
1387
    public getConditionList(): string[] {
1388
        if (!this.selectedField) return [];
1,725✔
1389

1390
        if (!this.selectedField.filters) {
1,259!
NEW
1391
            this.selectedField.filters = this.getFilters(this.selectedField);
×
1392
        }
1393

1394
        if ((this.isAdvancedFiltering() && !this.entities[0].childEntities) ||
1,259✔
1395
            (this.isHierarchicalNestedQuery() && this.selectedEntity.name && !this.selectedEntity.childEntities)) {
1396
            return this.selectedField.filters.conditionList();
218✔
1397
        }
1398

1399
        return this.selectedField.filters.extendedConditionList();
1,041✔
1400
    }
1401

1402
    /**
1403
     * @hidden @internal
1404
     */
1405
    public getFormatter(field: string) {
1406
        return this.fields?.find(el => el.field === field)?.formatter;
72,346✔
1407
    }
1408

1409
    /**
1410
     * @hidden @internal
1411
     */
1412
    public getFormat(field: string) {
1413
        return this.fields?.find(el => el.field === field).pipeArgs.format;
1,845✔
1414
    }
1415

1416
    /**
1417
     * @hidden @internal
1418
     *
1419
     * used by the grid
1420
     */
1421
    public setAddButtonFocus() {
1422
        if (this.addRootAndGroupButton) {
49!
1423
            this.addRootAndGroupButton.nativeElement.focus();
×
1424
        } else if (this.addConditionButton) {
49✔
1425
            this.addConditionButton.nativeElement.focus();
18✔
1426
        }
1427
    }
1428

1429
    /**
1430
     * @hidden @internal
1431
     */
1432
    public context(expression: ExpressionItem, afterExpression?: ExpressionItem) {
1433
        return {
56,327✔
1434
            $implicit: expression,
1435
            afterExpression
1436
        };
1437
    }
1438

1439
    public formatReturnFields(innerTree: IFilteringExpressionsTree) {
1440
        const returnFields = innerTree.returnFields;
3,642✔
1441
        let text = returnFields.join(', ');
3,642✔
1442
        const innerTreeEntity = this.entities?.find(el => el.name === innerTree.entity);
3,642✔
1443
        if (returnFields.length === innerTreeEntity?.fields.length) {
3,642!
1444
            text = this.resourceStrings.igx_query_builder_all_fields;
×
1445
        } else {
1446
            text = returnFields.join(', ');
3,642✔
1447
            text = text.length > 25 ? text.substring(0, 25) + ' ...' : text;
3,642!
1448
        }
1449
        return text;
3,642✔
1450
    }
1451

1452
    public isInEditMode(): boolean {
1453
        return !this.parentExpression || (this.parentExpression && this.parentExpression.inEditMode);
64,962✔
1454
    }
1455

1456
    public onInEditModeChanged(expressionItem: ExpressionOperandItem) {
1457
        if (!expressionItem.inEditMode) {
16!
1458
            this.enterExpressionEdit(expressionItem);
×
1459
        }
1460
    }
1461

1462
    public getExpressionTreeCopy(expressionTree: IExpressionTree, shouldAssignInnerQueryExprTree?: boolean): IExpressionTree {
1463
        if (!expressionTree) {
321✔
1464
            return null;
290✔
1465
        }
1466

1467
        const exprTreeCopy = new FilteringExpressionsTree(expressionTree.operator, expressionTree.fieldName, expressionTree.entity, expressionTree.returnFields);
31✔
1468
        exprTreeCopy.filteringOperands = [];
31✔
1469

1470
        expressionTree.filteringOperands.forEach(o => isTree(o) ? exprTreeCopy.filteringOperands.push(this.getExpressionTreeCopy(o)) : exprTreeCopy.filteringOperands.push(o));
56!
1471

1472
        if (!this.innerQueryNewExpressionTree && shouldAssignInnerQueryExprTree) {
31✔
1473
            this.innerQueryNewExpressionTree = exprTreeCopy;
18✔
1474
        }
1475

1476
        return exprTreeCopy;
31✔
1477
    }
1478

1479
    public onSelectAllClicked() {
1480
        if (
2✔
1481
            (this._selectedReturnFields.length > 0 && this._selectedReturnFields.length < this._selectedEntity.fields.length) ||
5✔
1482
            this._selectedReturnFields.length == this._selectedEntity.fields.length
1483
        ) {
1484
            this.returnFieldsCombo.deselectAllItems();
1✔
1485
        } else {
1486
            this.returnFieldsCombo.selectAllItems();
1✔
1487
        }
1488
    }
1489

1490
    public onReturnFieldSelectChanging(event: IComboSelectionChangingEventArgs | ISelectionEventArgs) {
1491
        let newSelection = [];
11✔
1492
        if (Array.isArray(event.newSelection)) {
11✔
1493
            newSelection = event.newSelection.map(item => item.field)
11✔
1494
        } else {
1495
            newSelection.push(event.newSelection.value);
6✔
1496
            this._selectedReturnFields = newSelection;
6✔
1497
        }
1498

1499
        this.initExpressionTree(this.selectedEntity.name, newSelection);
11✔
1500
    }
1501

1502
    public initExpressionTree(selectedEntityName: string, selectedReturnFields: string[]) {
1503
        if (!this._expressionTree) {
50✔
1504
            this._expressionTree = this.createExpressionTreeFromGroupItem(new ExpressionGroupItem(FilteringLogic.And, this.rootGroup), selectedEntityName, selectedReturnFields);
34✔
1505
        }
1506

1507
        if (!this.parentExpression) {
50✔
1508
            this.expressionTreeChange.emit(this._expressionTree);
38✔
1509
        }
1510
    }
1511

1512
    public getSearchValueTemplateContext(defaultSearchValueTemplate): any {
1513
        const ctx = {
1,725✔
1514
            $implicit: this.searchValue,
1515
            selectedField: this.selectedField,
1516
            selectedCondition: this.selectedCondition,
1517
            defaultSearchValueTemplate: defaultSearchValueTemplate
1518
        };
1519
        return ctx;
1,725✔
1520
    }
1521

1522
    private getPipeArgs(field: FieldType) {
1523
        let pipeArgs = {...field.pipeArgs};
3,292✔
1524
        if (!pipeArgs) {
3,292!
1525
            pipeArgs = { digitsInfo: DEFAULT_PIPE_DIGITS_INFO };
×
1526
        }
1527

1528
        if (!pipeArgs.format) {
3,292✔
1529
            pipeArgs.format = field.dataType === DataType.Time ?
3,059!
1530
                DEFAULT_PIPE_TIME_FORMAT : field.dataType === DataType.DateTime ?
3,059!
1531
                    DEFAULT_PIPE_DATE_TIME_FORMAT : DEFAULT_PIPE_DATE_FORMAT;
1532
        }
1533
        
1534
        return pipeArgs;
3,292✔
1535
    }
1536

1537
    private selectDefaultCondition() {
1538
        if (this.selectedField && this.selectedField.filters) {
175✔
1539
            this.selectedCondition = this.selectedField.filters.conditionList().indexOf('equals') >= 0 ? 'equals' : this.selectedField.filters.conditionList()[0];
126✔
1540
        }
1541
    }
1542

1543
    private getFilters(field: FieldType) {
1544
        if (!field.filters) {
3,292✔
1545
            switch (field.dataType) {
3,059!
1546
                case DataType.Boolean:
1547
                    return IgxBooleanFilteringOperand.instance();
759✔
1548
                case DataType.Number:
1549
                case DataType.Currency:
1550
                case DataType.Percent:
1551
                    return IgxNumberFilteringOperand.instance();
1,139✔
1552
                case DataType.Date:
1553
                    return IgxDateFilteringOperand.instance();
384✔
1554
                case DataType.Time:
1555
                    return IgxTimeFilteringOperand.instance();
×
1556
                case DataType.DateTime:
1557
                    return IgxDateTimeFilteringOperand.instance();
×
1558
                case DataType.String:
1559
                default:
1560
                    return IgxStringFilteringOperand.instance();
777✔
1561
            }
1562
        } else {
1563
            return field.filters;
233✔
1564
        }
1565
    }
1566

1567

1568
    private addGroup(operator: FilteringLogic, parent?: ExpressionGroupItem, afterExpression?: ExpressionItem) {
1569
        this.cancelOperandAdd();
3✔
1570

1571
        const groupItem = new ExpressionGroupItem(operator, parent);
3✔
1572

1573
        if (parent) {
3!
1574
            if (afterExpression) {
3!
1575
                const index = parent.children.indexOf(afterExpression);
×
1576
                parent.children.splice(index + 1, 0, groupItem);
×
1577
            } else {
1578
                parent.children.push(groupItem);
3✔
1579
            }
1580
        } else {
1581
            this.rootGroup = groupItem;
×
1582
        }
1583

1584
        this.addCondition(groupItem);
3✔
1585
        this.currentGroup = groupItem;
3✔
1586
    }
1587

1588
    private createExpressionGroupItem(expressionTree: IExpressionTree, parent?: ExpressionGroupItem, entityName?: string): ExpressionGroupItem {
1589
        let groupItem: ExpressionGroupItem;
1590
        if (expressionTree) {
855✔
1591
            groupItem = new ExpressionGroupItem(expressionTree.operator, parent);
684✔
1592
            if (!expressionTree.filteringOperands) {
684!
1593
                return groupItem;
×
1594
            }
1595

1596
            for (let i = 0; i < expressionTree.filteringOperands.length; i++) {
684✔
1597
                const expr = expressionTree.filteringOperands[i];
1,493✔
1598

1599
                if (isTree(expr)) {
1,493✔
1600
                    groupItem.children.push(this.createExpressionGroupItem(expr, groupItem, expressionTree.entity));
90✔
1601
                } else {
1602
                    const filteringExpr = expr as IFilteringExpression;
1,403✔
1603
                    const exprCopy: IFilteringExpression = {
1,403✔
1604
                        fieldName: filteringExpr.fieldName,
1605
                        condition: filteringExpr.condition,
1606
                        conditionName: filteringExpr.condition?.name || filteringExpr.conditionName,
1,403!
1607
                        searchVal: filteringExpr.searchVal,
1608
                        searchTree: filteringExpr.searchTree,
1609
                        ignoreCase: filteringExpr.ignoreCase
1610
                    };
1611
                    const operandItem = new ExpressionOperandItem(exprCopy, groupItem);
1,403✔
1612
                    const field = this.fields?.find(el => el.field === filteringExpr.fieldName);
2,025✔
1613
                    operandItem.fieldLabel = field?.label || field?.header || field?.field;
1,403✔
1614
                    if (this._expandedExpressions.filter(e => e.searchTree == operandItem.expression.searchTree).length > 0) {
1,403!
1615
                        operandItem.expanded = true;
×
1616
                    }
1617
                    groupItem.children.push(operandItem);
1,403✔
1618
                }
1619
            }
1620

1621

1622
            if (expressionTree.entity) {
684✔
1623
                entityName = expressionTree.entity;
626✔
1624
            }
1625
            const entity = this.entities?.find(el => el.name === entityName);
981✔
1626
            if (entity) {
684✔
1627
                this.fields = entity.fields;
630✔
1628
            }
1629

1630
            this._selectedEntity = this.entities?.find(el => el.name === entityName);
981✔
1631
            this._selectedReturnFields =
684✔
1632
                !expressionTree.returnFields || expressionTree.returnFields.includes('*') || expressionTree.returnFields.includes('All') || expressionTree.returnFields.length === 0
2,874✔
1633
                    ? this.fields?.map(f => f.field)
1,122✔
1634
                    : this.fields?.filter(f => expressionTree.returnFields.indexOf(f.field) >= 0).map(f => f.field);
1,778✔
1635
        }
1636
        return groupItem;
855✔
1637
    }
1638

1639
    private createExpressionTreeFromGroupItem(groupItem: ExpressionGroupItem, entity?: string, returnFields?: string[]): FilteringExpressionsTree {
1640
        if (!groupItem) {
153✔
1641
            return null;
5✔
1642
        }
1643

1644
        const expressionTree = new FilteringExpressionsTree(groupItem.operator, undefined, entity, returnFields);
148✔
1645

1646
        for (let i = 0; i < groupItem.children.length; i++) {
148✔
1647
            const item = groupItem.children[i];
201✔
1648

1649
            if (item instanceof ExpressionGroupItem) {
201✔
1650
                const subTree = this.createExpressionTreeFromGroupItem((item as ExpressionGroupItem), entity, returnFields);
19✔
1651
                expressionTree.filteringOperands.push(subTree);
19✔
1652
            } else {
1653
                expressionTree.filteringOperands.push((item as ExpressionOperandItem).expression);
182✔
1654
            }
1655
        }
1656

1657
        return expressionTree;
148✔
1658
    }
1659

1660
    private scrollElementIntoView(target: HTMLElement) {
1661
        const container = this.expressionsContainer.nativeElement;
659✔
1662
        const targetOffset = target.offsetTop - container.offsetTop;
659✔
1663
        const delta = 10;
659✔
1664

1665
        if (container.scrollTop + delta > targetOffset) {
659✔
1666
            container.scrollTop = targetOffset - delta;
425✔
1667
        } else if (container.scrollTop + container.clientHeight < targetOffset + target.offsetHeight + delta) {
234✔
1668
            container.scrollTop = targetOffset + target.offsetHeight + delta - container.clientHeight;
229✔
1669
        }
1670
    }
1671

1672
    private focusEditedExpressionChip() {
1673
        if (this._timeoutId) {
61✔
1674
            clearTimeout(this._timeoutId);
5✔
1675
        }
1676

1677
        this._timeoutId = setTimeout(() => {
61✔
1678
            if (this._lastFocusedChipIndex != -1) {
61✔
1679
                //Sort the expression chip list.
1680
                //If there was a recent drag&drop and the tree hasn't rerendered(child query), they will be unordered
1681
                const sortedChips = this.expressionsChips.toArray().sort(function (a, b) {
59✔
1682
                    if (a === b) return 0;
73!
1683
                    if (a.chipArea.nativeElement.compareDocumentPosition(b.chipArea.nativeElement) & 2) {
73✔
1684
                        // b comes before a
1685
                        return 1;
60✔
1686
                    }
1687
                    return -1;
13✔
1688
                });
1689
                const chipElement = sortedChips[this._lastFocusedChipIndex]?.nativeElement;
59✔
1690
                if (chipElement) {
59✔
1691
                    chipElement.focus();
51✔
1692
                }
1693
                this._lastFocusedChipIndex = -1;
59✔
1694
                this._focusDelay = DEFAULT_CHIP_FOCUS_DELAY;
59✔
1695
            }
1696
        }, this._focusDelay);
1697
    }
1698

1699
    private init() {
1700
        this.cancelOperandAdd();
502✔
1701
        this.cancelOperandEdit();
502✔
1702

1703
        // Ignore values of certain properties for the comparison
1704
        const propsToIgnore = ['parent', 'hovered', 'ignoreCase', 'inEditMode', 'inAddMode'];
502✔
1705
        const propsReplacer = function replacer(key, value) {
502✔
1706
            if (propsToIgnore.indexOf(key) >= 0) {
19,541✔
1707
                return undefined;
2,606✔
1708
            } else {
1709
                return value;
16,935✔
1710
            }
1711
        };
1712

1713
        // Skip root being recreated if the same
1714
        const newRootGroup = this.createExpressionGroupItem(this.expressionTree);
502✔
1715
        if (JSON.stringify(this.rootGroup, propsReplacer) !== JSON.stringify(newRootGroup, propsReplacer)) {
502✔
1716
            this.rootGroup = this.createExpressionGroupItem(this.expressionTree);
257✔
1717
            this.currentGroup = this.rootGroup;
257✔
1718
        }
1719

1720
        if (this.rootGroup?.children?.length == 0) {
502✔
1721
            this.rootGroup = null;
40✔
1722
            this.currentGroup = null;
40✔
1723
        }
1724
    }
1725

1726
    /** rootGroup is recreated after clicking Apply, which sets new expressionTree and calls init()*/
1727
    protected trackExpressionItem = trackByIdentity;
297✔
1728
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc