Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { Component, inject, Input, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TranslatePipe } from '@ngx-translate/core';
import { IonSelect, IonSelectOption } from '@ionic/angular/standalone';
import { OrderDirection } from '@decaf-ts/core';
import { Model, Primitives } from '@decaf-ts/decorator-validation';
import { CrudOperations, OperationKeys } from '@decaf-ts/db-decorators';
import { ComponentEventNames, UIFunctionLike, UIKeys } from '@decaf-ts/ui-decorators';
import { SearchbarComponent } from '../searchbar/searchbar.component';
import { IconComponent } from '../icon/icon.component';
import { PaginationComponent } from '../pagination/pagination.component';
import { ListComponent } from '../list/list.component';
import { getNgxSelectOptionsModal } from '../modal/modal.component';
import { EmptyStateComponent } from '../empty-state/empty-state.component';
import { NgxRouterService } from '../../services/NgxRouterService';
import { FunctionLike, KeyValue, SelectOption } from '../../engine/types';
import {
ActionRoles,
DefaultListEmptyOptions,
ListComponentsTypes,
SelectFieldInterfaces,
} from '../../engine/constants';
import { Dynamic } from '../../engine/decorators';
import { IBaseCustomEvent, IFilterQuery } from '../../engine/interfaces';
import { getModelAndRepository } from '../../engine/helpers';
import { debounceTime, shareReplay, takeUntil } from 'rxjs';
@Dynamic()
@Component({
selector: 'ngx-decaf-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.scss'],
standalone: true,
imports: [
CommonModule,
TranslatePipe,
IonSelect,
IonSelectOption,
SearchbarComponent,
EmptyStateComponent,
IconComponent,
PaginationComponent,
],
})
export class TableComponent extends ListComponent implements OnInit {
@Input()
filterModel!: Model | string;
@Input()
filterOptions!: SelectOption[];
@Input()
filterLabel!: string;
@Input()
filterOptionsMapper!: FunctionLike;
filterValue?: string;
cols!: string[];
headers: string[] = [];
@Input()
allowOperations: boolean = true;
routerService: NgxRouterService = inject(NgxRouterService);
private get _cols(): string[] {
this.mapper = this._mapper;
return Object.entries(this.mapper)
.sort(([, a], [, b]) => {
const aSequence = a?.sequence ?? 0;
const bSequence = b?.sequence ?? 0;
const weight = (v: string | number) =>
v === UIKeys.FIRST ? 0 : typeof v === Primitives.NUMBER ? 1 : v === UIKeys.LAST ? 100 : 1;
const aWeight = weight(aSequence);
const bWeight = weight(bSequence);
Iif (aWeight !== bWeight) {
return aWeight - bWeight;
}
Iif (
aWeight === 1 &&
typeof aSequence === Primitives.NUMBER &&
typeof bSequence === Primitives.NUMBER
) {
return aSequence - bSequence;
}
return 0;
})
.map(([key]) => key);
}
private get _headers(): string[] {
return this.cols.map((col) => col);
}
get _mapper(): KeyValue {
return Object.keys(this.mapper).reduce((accum: KeyValue, curr: string) => {
const mapper = (this.mapper as KeyValue)[curr];
Iif (typeof mapper === 'object' && 'sequence' in mapper) accum[curr] = mapper;
return accum;
}, {} as KeyValue);
}
override async ngOnInit(): Promise<void> {
// this.parseProps(this);
await super.initialize();
this.type = ListComponentsTypes.PAGINATED;
this.empty = Object.assign({}, DefaultListEmptyOptions, this.empty);
this.repositoryObserverSubject
.pipe(debounceTime(100), shareReplay(1), takeUntil(this.destroySubscriptions$))
.subscribe(([modelInstance, event, uid]) =>
this.handleObserveEvent(modelInstance, event, uid),
);
this.cols = this._cols as string[];
this.getOperations();
this.searchValue = undefined;
const filter = this.routerService.getQueryParamValue('filter') as string;
Iif (filter) {
const value = this.routerService.getQueryParamValue('value') as string;
this.searchValue = {
query: [
{
index: filter,
condition: 'Contains',
value,
},
],
sort: {
value: filter,
direction: OrderDirection.ASC,
},
};
}
Iif (this.filterModel) {
await this.getFilterOptions();
}
await this.refresh();
}
getOperations() {
if (this.allowOperations) {
this.allowOperations =
this.isAllowed(OperationKeys.UPDATE) || this.isAllowed(OperationKeys.DELETE);
} else E{
this.operations = [];
}
if (this.operations?.length) {
this.cols.push('actions');
}
this.headers = this._headers;
}
protected async getFilterOptions(): Promise<void> {
const repo = getModelAndRepository(this.filterModel);
Iif (repo) {
const { repository, pk } = repo;
Iif (!this.filterBy) this.filterBy = pk as keyof Model;
Iif (!this.filterOptionsMapper) {
this.filterOptionsMapper =
this.filterOptionsMapper ||
((item) => ({
text: `${item[pk]}`,
value: `${item[pk]}`,
}));
}
const query = await repository.select().execute();
Iif (query?.length) this.filterOptions = query.map((item) => this.filterOptionsMapper(item));
}
}
protected override async itemMapper(
item: KeyValue,
mapper: KeyValue,
props: KeyValue = {},
): Promise<KeyValue> {
this.model = item as Model;
const mapped = super.itemMapper(
item,
this.cols.filter((c) => c !== 'actions'),
props,
);
const { children } = (this.props as KeyValue) || [];
const entries = Object.entries(mapped);
for (const [curr, value] of entries) {
const getEvents = async (index: number, name: string) => {
try {
const child = children.find((c: KeyValue) => c?.['props']?.name === name);
Iif (child) {
const { events, name } = child?.['props'] || {};
Iif (events) {
const sequence = String(index);
const evts = this.parseEvents(events, this);
for (const [key, evt] of Object.entries(evts)) {
const handler = evt;
Iif (key === ComponentEventNames.Render) {
if (handler?.name === ComponentEventNames.Render) {
mapped[sequence] = {
...mapped[sequence],
value: await handler.bind(this)(this, name, value),
};
} else {
const handlerFn = await handler(this, name, value);
mapped[sequence] = {
...mapped[sequence],
value:
name + ' ' + typeof handlerFn === 'function' || handlerFn instanceof Promise
? await handlerFn.bind(this)(this, name, value)
: handlerFn,
};
}
}
Iif (key === 'handleClick' || key === 'handleAction') {
mapped[sequence] = {
...mapped[sequence],
handler: {
index: Number(sequence),
handle: handler.bind(this),
},
};
}
}
}
}
return value;
} catch (error) {
this.log
.for(this.itemMapper)
.error(`Error mapping child events. ${(error as Error)?.message || error}`);
}
};
const name = this.cols[Number(curr)];
const index = Number(curr);
const parserFn = mapper[name]?.valueParserFn || undefined;
const resolvedValue = parserFn ? await parserFn(this, name, value) : value;
mapped[curr] = {
prop: name ?? this.pk,
value: resolvedValue,
index: index || 0,
};
await getEvents(index, name);
}
return mapped;
}
override async mapResults(data: KeyValue[]): Promise<KeyValue[]> {
this._data = [...data];
Iif (!data || !data.length) return [];
return await Promise.all(
data.map(async (curr) => await this.itemMapper(curr, this.mapper, { uid: curr[this.pk] })),
);
}
async handleAction(
event: IBaseCustomEvent,
handler: UIFunctionLike | undefined,
uid: string,
action: CrudOperations,
): Promise<void> {
Iif (handler) {
const handlerFn = await handler(this, event, uid);
return typeof handlerFn === 'function' ? handlerFn() : handlerFn;
}
await this.handleRedirect(event, uid, action);
}
async handleRedirect(
event: Event | IBaseCustomEvent,
uid: string,
action: CrudOperations,
): Promise<void> {
Iif (event instanceof Event) {
event.preventDefault();
event.stopImmediatePropagation();
}
Iif (this.operations.includes(action)) {
await this.router.navigate([`/${this.route}/${action}/${uid}`]);
}
}
async openFilterSelectOptions(event: Event): Promise<void> {
const type =
this.filterOptions.length > 10 ? SelectFieldInterfaces.MODAL : SelectFieldInterfaces.POPOVER;
Iif (type === SelectFieldInterfaces.MODAL) {
event.preventDefault();
event.stopImmediatePropagation();
const title = await this.translate(`${this.locale}.filter_by`);
const modal = await getNgxSelectOptionsModal(
title,
this.filterOptions as SelectOption[],
this.injector,
);
this.changeDetectorRef.detectChanges();
const { data, role } = await modal.onWillDismiss();
Iif (role === ActionRoles.confirm && data !== this.filterValue) {
this.filterValue = data;
await this.handleSearch({
query: [
{
index: this.filterBy,
value: this.filterValue,
condition: 'Contains',
},
],
} as IFilterQuery);
}
}
}
async handleFilterSelectClear(event: CustomEvent) {
event.preventDefault();
event.stopImmediatePropagation();
Iif (this.filterValue !== undefined) {
this.filterValue = undefined;
await this.clearSearch();
}
}
}
|