@smallpearl/ngx-helper 0.33.28 → 0.33.29

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.
@@ -1,7 +1,12 @@
1
1
  import * as i1 from '@angular/common/http';
2
- import { HttpContextToken, HttpContext, HttpParams, HttpClient } from '@angular/common/http';
2
+ import { HttpContext, HttpClient, HttpParams, HttpContextToken } from '@angular/common/http';
3
3
  import * as i0 from '@angular/core';
4
- import { InjectionToken, inject, input, computed, signal, viewChild, ViewContainerRef, Component, ChangeDetectionStrategy, viewChildren, EventEmitter, effect, ContentChildren, Output, ChangeDetectorRef } from '@angular/core';
4
+ import { input, signal, computed, inject, ChangeDetectorRef, Component, InjectionToken, viewChild, ViewContainerRef, ChangeDetectionStrategy, viewChildren, EventEmitter, effect, ContentChildren, Output } from '@angular/core';
5
+ import * as i4$1 from '@jsverse/transloco';
6
+ import { TranslocoService, TranslocoModule, provideTranslocoScope } from '@jsverse/transloco';
7
+ import { setServerErrorsAsFormErrors } from '@smallpearl/ngx-helper/forms';
8
+ import { Subscription, Observable, map, tap, of, switchMap, firstValueFrom, catchError, EMPTY, throwError } from 'rxjs';
9
+ import { sideloadToComposite } from '@smallpearl/ngx-helper/sideload';
5
10
  import * as i4 from '@angular/common';
6
11
  import { CommonModule } from '@angular/common';
7
12
  import * as i2 from '@angular/material/button';
@@ -21,26 +26,12 @@ import { MatIconModule } from '@angular/material/icon';
21
26
  import * as i8 from '@angular/material/menu';
22
27
  import { MatMenuModule } from '@angular/material/menu';
23
28
  import * as i3$1 from '@angular/platform-browser';
24
- import * as i4$1 from '@jsverse/transloco';
25
- import { TranslocoService, TranslocoModule, provideTranslocoScope } from '@jsverse/transloco';
26
29
  import * as i11 from 'angular-split';
27
30
  import { AngularSplitModule } from 'angular-split';
28
31
  import { startCase, clone } from 'lodash';
29
32
  import { plural } from 'pluralize';
30
- import { Observable, of, Subscription, tap, switchMap, firstValueFrom, map, catchError, EMPTY, throwError } from 'rxjs';
31
33
  import * as i1$1 from '@angular/material/toolbar';
32
34
  import { MatToolbarModule } from '@angular/material/toolbar';
33
- import { setServerErrorsAsFormErrors } from '@smallpearl/ngx-helper/forms';
34
- import { sideloadToComposite } from '@smallpearl/ngx-helper/sideload';
35
-
36
- const SP_MAT_ENTITY_CRUD_HTTP_CONTEXT = new HttpContextToken(() => ({
37
- entityName: '',
38
- entityNamePlural: '',
39
- endpoint: '',
40
- op: undefined,
41
- }));
42
-
43
- const SP_MAT_ENTITY_CRUD_CONFIG = new InjectionToken('SPMatEntityCrudConfig');
44
35
 
45
36
  /**
46
37
  * Converts array of HttpContextToken key, value pairs to HttpContext
@@ -67,75 +58,452 @@ function convertHttpContextInputToHttpContext(context, reqContext) {
67
58
  return context;
68
59
  }
69
60
 
70
- function defaultCrudResponseParser(entityName, idKey, method, // 'create' | 'retrieve' | 'update' | 'delete',
71
- resp) {
72
- // If the response is an object with a property '<idKey>', return it as
73
- // TEntity.
74
- if (resp.hasOwnProperty(idKey)) {
75
- return resp;
76
- }
77
- // If the response has an object indexed at '<entityName>' and it has
78
- // the property '<idKey>', return it as TEntity.
79
- if (resp.hasOwnProperty(entityName)) {
80
- const obj = resp[entityName];
81
- if (obj.hasOwnProperty(idKey)) {
82
- return obj;
83
- }
84
- }
85
- // Return undefined, indicating that we could't parse the response.
86
- return undefined;
87
- }
88
- const DefaultSPMatEntityCrudConfig = {
89
- crudOpResponseParser: defaultCrudResponseParser
90
- };
91
61
  /**
92
- * To be called from an object constructor as it internally calls Angular's
93
- * inject() API.
94
- * @param userConfig
95
- * @returns
62
+ * This is a convenience base class that clients can derive from to implement
63
+ * their CRUD form component. Particularly this class registers the change
64
+ * detection hook which will be called when the user attempts to close the
65
+ * form's parent container pane via the Close button on the top right.
66
+ *
67
+ * This button behaves like a Cancel button in a desktop app and therefore if
68
+ * the user has entered any data in the form's controls, (determined by
69
+ * checking form.touched), then a 'Lose Changes' prompt is displayed allowing
70
+ * the user to cancel the closure.
71
+ *
72
+ * The `@Component` decorator is fake to keep the VSCode angular linter quiet.
73
+ *
74
+ * This class can be used in two modes:
75
+ *
76
+ * I. SPMatEntityCrudComponent mode
77
+ * This mode relies on a bridge interface that implements the
78
+ * SPMatEntityCrudCreateEditBridge interface to perform the entity
79
+ * load/create/update operations. This is the intended mode when the
80
+ * component is used as a part of the SPMatEntityCrudComponent to
81
+ * create/update an entity. This mode requires the following properties
82
+ * to be set:
83
+ * - entity: TEntity | TEntity[IdKey] | undefined (for create)
84
+ * - bridge: SPMatEntityCrudCreateEditBridge
85
+ *
86
+ * II. Standalone mode
87
+ * This mode does not rely on the bridge interface and the component
88
+ * itself performs the entity load/create/update operations.
89
+ * This mode requires the following properties to be set:
90
+ * - entity: TEntity | TEntity[IdKey] | undefined (for create)
91
+ * - baseUrl: string - Base URL for CRUD operations. This URL does not
92
+ * include the entity id. The entity id will be appended to this URL
93
+ * for entity load and update operations. For create operation, this
94
+ * URL is used as is.
95
+ * - entityName: string - Name of the entity, used to parse sideloaded
96
+ * entity responses.
97
+ * - httpReqContext?: HttpContextInput - Optional HTTP context to be
98
+ * passed to the HTTP requests. For instance, if your app has a HTTP
99
+ * interceptor that adds authentication tokens to the requests based
100
+ * on a HttpContextToken, then you can pass that token here.
101
+ *
102
+ * I. SPMatEntityCrudComponent mode:
103
+ *
104
+ * 1. Declare a FormGroup<> type as
105
+ *
106
+ * ```
107
+ * type MyForm = FormGroup<{
108
+ * name: FormControl<string>;
109
+ * type: FormControl<string>;
110
+ * notes: FormControl<string>;
111
+ * }>;
112
+ * ```
113
+ *
114
+ * 2. Derive your form's component class from this and implement the
115
+ * createForm() method returing the FormGroup<> instance that matches
116
+ * the FormGroup concrete type above.
117
+ *
118
+ * ```
119
+ * class MyFormComponent extends SPMatEntityCrudFormBase<MyForm, MyEntity> {
120
+ * constructor() {
121
+ * super()
122
+ * }
123
+ * createForm() {
124
+ * return new FormGroup([...])
125
+ * }
126
+ * }
127
+ * ```
128
+ *
129
+ * 3. If your form's value requires manipulation before being sent to the
130
+ * server, override `getFormValue()` method and do it there before returning
131
+ * the modified values.
132
+ *
133
+ * 4. Wire up the form in the template as below
134
+ *
135
+ * ```html
136
+ * @if (loadEntity$ | async) {
137
+ * <form [formGroup]='form'.. (ngSubmit)="onSubmit()">
138
+ * <button type="submit">Submit</button>
139
+ * </form>
140
+ * } @else {
141
+ * <div>Loading...</div>
142
+ * }
143
+ * ```
144
+ *
145
+ * Here `loadEntity$` is an Observable<boolean> that upon emission of `true`
146
+ * indicates that the entity has been loaded from server (in case of edit)
147
+ * and the form is ready to be displayed. Note that if the full entity was
148
+ * passed in the `entity` input property, then no server load is necessary
149
+ * and the form will be created immediately.
150
+ *
151
+ * 5. In the parent component that hosts the SPMatEntityCrudComponent, set
152
+ * the `entity` and `bridge` input properties of this component to
153
+ * appropriate values. For instance, if your form component has the
154
+ * selector `app-my-entity-form`, then the parent component's template
155
+ * will have:
156
+ *
157
+ * ```html
158
+ * <sp-mat-entity-crud
159
+ * ...
160
+ * createEditFormTemplate="entityFormTemplate"
161
+ * ></sp-mat-entity-crud>
162
+ * <ng-template #entityFormTemplate let-data="data">
163
+ * <app-my-entity-form
164
+ * [entity]="data.entity"
165
+ * [bridge]="data.bridge"
166
+ * ></app-my-entity-form>
167
+ * </ng-template>
168
+ * ```
169
+ *
170
+ * II. Standalone mode
171
+ *
172
+ * 1..4. Same as above, except set the required `bridge` input to `undefined`.
173
+ * 5. Initialize the component's inputs `baseUrl` and `entityName` with the
174
+ * appropriate values. If you would like to pass additional HTTP context to
175
+ * the HTTP requests, then set the `httpReqContext` input as well.
176
+ * If the entity uses an id key other than 'id', then set the `idKey` input
177
+ * to the appropriate id key name.
178
+ * 6. If you want to retrieve the created/updated entity after the create/update
179
+ * operation, override the `onPostCreate()` and/or `onPostUpdate()` methods
180
+ * respectively.
96
181
  */
97
- function getEntityCrudConfig() {
98
- const userCrudConfig = inject(SP_MAT_ENTITY_CRUD_CONFIG, {
99
- optional: true,
100
- });
101
- return {
102
- ...DefaultSPMatEntityCrudConfig,
103
- ...(userCrudConfig ?? {}),
104
- };
105
- }
106
-
107
- class FormViewHostComponent {
108
- entityCrudComponentBase = input.required();
109
- clientViewTemplate = input(null);
110
- _itemLabel = computed(() => {
111
- const label = this.entityCrudComponentBase().getItemLabel();
112
- return label instanceof Observable ? label : of(label);
113
- });
114
- _itemLabelPlural = computed(() => {
115
- const label = this.entityCrudComponentBase().getItemLabelPlural();
116
- return label instanceof Observable ? label : of(label);
117
- });
118
- entity = signal(undefined);
119
- title = signal(undefined);
120
- params = signal(undefined);
121
- clientFormView;
122
- vc = viewChild('clientFormContainer', { read: ViewContainerRef });
123
- config;
182
+ class SPMatEntityCrudFormBase {
183
+ entity = input.required();
184
+ bridge = input.required();
185
+ params = input();
186
+ // --- BEGIN inputs used when `bridge` input is undefined
187
+ // Entity name, which is used to parse sideloaded entity responses
188
+ entityName = input();
189
+ // Base CRUD URL, which is the GET-list-of-entities/POST-to-create
190
+ // URL. Update URL will be derived from this ias `baseUrl()/${TEntity[IdKey]}`
191
+ baseUrl = input();
192
+ // Additional request context to be passed to the request
193
+ httpReqContext = input();
194
+ // ID key, defaults to 'id'
195
+ idKey = input('id');
196
+ // -- END inputs used when `bridge` input is undefined
197
+ // IMPLEMENTATION
198
+ loadEntity$;
199
+ _entity = signal(undefined);
124
200
  sub$ = new Subscription();
201
+ // Store for internal form signal. form() is computed from this.
202
+ _form = signal(undefined);
203
+ // Force typecast to TFormGroup so that we can use it in the template
204
+ // without having to use the non-nullable operator ! with every reference
205
+ // of form(). In any case the form() signal is always set in ngOnInit()
206
+ // method after the form is created. And if form() is not set, then there
207
+ // will be errors while loading the form in the template.
208
+ form = computed(() => this._form());
125
209
  transloco = inject(TranslocoService);
126
- constructor() {
127
- this.config = getEntityCrudConfig();
210
+ cdr = inject(ChangeDetectorRef);
211
+ http = inject(HttpClient);
212
+ canCancelEdit = () => {
213
+ return this._canCancelEdit();
214
+ };
215
+ _canCancelEdit() {
216
+ const form = this._form();
217
+ if (form && form.touched) {
218
+ return window.confirm(this.transloco.translate('spMatEntityCrud.loseChangesConfirm'));
219
+ }
220
+ return true;
221
+ }
222
+ ngOnInit() {
223
+ // validate inputs. Either bridge or (baseUrl and entityName) must be
224
+ // defined.
225
+ if (!this.bridge() && (!this.baseUrl() || !this.entityName())) {
226
+ throw new Error('SPMatEntityCrudFormBase: baseUrl and entityName inputs must be defined in standalone mode.');
227
+ }
228
+ this.loadEntity$ = (typeof this.entity() === 'object' || this.entity() === undefined
229
+ ? new Observable((subscriber) => {
230
+ subscriber.next(this.entity());
231
+ subscriber.complete();
232
+ })
233
+ : this.load(this.entity())).pipe(map((resp) => {
234
+ const compositeEntity = this.getEntityFromLoadResponse(resp);
235
+ this._entity.set(compositeEntity);
236
+ this._form.set(this.createForm(compositeEntity));
237
+ const bridge = this.bridge();
238
+ if (bridge && bridge.registerCanCancelEditCallback) {
239
+ bridge.registerCanCancelEditCallback(this.canCancelEdit);
240
+ }
241
+ return true;
242
+ }));
128
243
  }
129
- ngOnInit() { }
130
244
  ngOnDestroy() {
131
245
  this.sub$.unsubscribe();
132
246
  }
133
- show(entity, params) {
134
- this.entity.set(entity);
135
- if (params && params?.title) {
136
- this.title.set(params.title instanceof Observable ? params.title : of(params.title));
137
- }
138
- else {
247
+ /**
248
+ * Additional parameters for loading the entity, in case this.entity() value
249
+ * is of type TEntity[IdKey].
250
+ * @returns
251
+ */
252
+ getLoadEntityParams() {
253
+ return '';
254
+ }
255
+ /**
256
+ * Return the TEntity object from the response returned by the
257
+ * load() method. Typically entity load returns the actual
258
+ * entity object itself. In some cases, where response is sideloaded, the
259
+ * default implementation here uses the `sideloadToComposite()` utility to
260
+ * extract the entity from the response after merging (inplace) the
261
+ * sideloaded data into a composite.
262
+ *
263
+ * If you have a different response shape, or if your sideloaded object
264
+ * response requires custom custom `sideloadDataMap`, override this method
265
+ * and implement your custom logic to extract the TEntity object from the
266
+ * response.
267
+ * @param resp
268
+ * @returns
269
+ */
270
+ getEntityFromLoadResponse(resp) {
271
+ if (!resp || typeof resp !== 'object') {
272
+ return undefined;
273
+ }
274
+ const entityName = this.entityName();
275
+ if (resp.hasOwnProperty(this.getIdKey())) {
276
+ return resp;
277
+ }
278
+ else if (entityName && resp.hasOwnProperty(entityName)) {
279
+ // const sideloadDataMap = this.sideloadDataMap();
280
+ return sideloadToComposite(resp, this.entityName(), this.getIdKey());
281
+ }
282
+ return undefined;
283
+ }
284
+ /**
285
+ * Override to customize the id key name if it's not 'id'
286
+ * @returns The name of the unique identifier key that will be used to
287
+ * extract the entity's id for UPDATE operation.
288
+ */
289
+ getIdKey() {
290
+ const bridge = this.bridge();
291
+ if (bridge) {
292
+ return bridge.getIdKey();
293
+ }
294
+ return this.idKey();
295
+ }
296
+ /**
297
+ * Return the form's value to be sent to server as Create/Update CRUD
298
+ * operation data.
299
+ * @returns
300
+ */
301
+ getFormValue() {
302
+ const form = this.form();
303
+ return form ? form.value : undefined;
304
+ }
305
+ onSubmit() {
306
+ const value = this.getFormValue();
307
+ const obs = !this._entity()
308
+ ? this.create(value)
309
+ : this.update(this._entity()[this.getIdKey()], value);
310
+ this.sub$.add(obs
311
+ ?.pipe(tap(entity => this._entity() ? this.onPostUpdate(entity) : this.onPostCreate(entity)), setServerErrorsAsFormErrors(this._form(), this.cdr))
312
+ .subscribe());
313
+ }
314
+ onPostCreate(entity) {
315
+ /* empty */
316
+ }
317
+ onPostUpdate(entity) {
318
+ /* empty */
319
+ }
320
+ /**
321
+ * Loads the entity if `this.entity()` is of type TEntity[IdKey]. If `bridge`
322
+ * input is defined, then it's `loadEntity()` method is used to load the
323
+ * entity. Otherwise, then this method attempts to load the entity using
324
+ * HTTP GET from the URL derived from `baseUrl` input.
325
+ * @param entityId
326
+ * @param params
327
+ * @returns
328
+ */
329
+ load(entityId) {
330
+ const bridge = this.bridge();
331
+ const params = this.getLoadEntityParams();
332
+ if (bridge) {
333
+ return bridge.loadEntity(entityId, params);
334
+ }
335
+ // Try to load using baseUrl.
336
+ if (!this.baseUrl()) {
337
+ console.warn(`SPMatEntityCrudFormBase.load: No bridge defined, baseUrl input is undefined. Returning undefined.`);
338
+ return new Observable((subscriber) => {
339
+ subscriber.next(undefined);
340
+ subscriber.complete();
341
+ });
342
+ }
343
+ const url = this.getEntityUrl(entityId);
344
+ return this.http
345
+ .get(this.getEntityUrl(entityId), {
346
+ params: typeof params === 'string'
347
+ ? new HttpParams({ fromString: params })
348
+ : params,
349
+ context: this.getRequestContext(),
350
+ })
351
+ .pipe(map((resp) => this.getEntityFromLoadResponse(resp)));
352
+ }
353
+ /**
354
+ * Create a new entity using the bridge if defined, otherwise using HTTP
355
+ * POST to the `baseUrl`.
356
+ * @param values
357
+ * @returns
358
+ */
359
+ create(values) {
360
+ const bridge = this.bridge();
361
+ if (bridge) {
362
+ return bridge.create(values);
363
+ }
364
+ const url = this.baseUrl();
365
+ if (!url) {
366
+ console.warn('SPMatEntityCrudFormBase.create: Cannot create entity as neither bridge nor baseUrl inputs are provided.');
367
+ return of(undefined);
368
+ }
369
+ return this.http
370
+ .post(url, values, { context: this.getRequestContext() })
371
+ .pipe(map((resp) => this.getEntityFromLoadResponse(resp)));
372
+ }
373
+ /**
374
+ * Update an existing entity using the bridge if defined, otherwise using HTTP
375
+ * PATCH to the URL derived from `baseUrl` and the entity id.
376
+ * @param id
377
+ * @param values
378
+ * @returns
379
+ */
380
+ update(id, values) {
381
+ const bridge = this.bridge();
382
+ if (bridge) {
383
+ return bridge.update(id, values);
384
+ }
385
+ const url = this.baseUrl();
386
+ if (!url) {
387
+ console.warn('SPMatEntityCrudFormBase.update: Cannot update entity as neither bridge nor baseUrl inputs are provided.');
388
+ return of(undefined);
389
+ }
390
+ return this.http
391
+ .patch(this.getEntityUrl(id), values, {
392
+ context: this.getRequestContext(),
393
+ })
394
+ .pipe(map((resp) => this.getEntityFromLoadResponse(resp)));
395
+ }
396
+ getEntityUrl(entityId) {
397
+ const bridge = this.bridge();
398
+ if (bridge) {
399
+ return bridge.getEntityUrl(entityId);
400
+ }
401
+ const baseUrl = this.baseUrl();
402
+ if (baseUrl) {
403
+ const urlParts = baseUrl.split('?');
404
+ return `${urlParts[0]}${String(entityId)}/${urlParts[1] ? '?' + urlParts[1] : ''}`;
405
+ }
406
+ console.warn('SPMatEntityCrudFormBase.getEntityUrl: Cannot determine entity URL as neither baseUrl nor bridge inputs are provided.');
407
+ return '';
408
+ }
409
+ getRequestContext() {
410
+ let context = new HttpContext();
411
+ const httpReqContext = this.httpReqContext();
412
+ if (httpReqContext) {
413
+ context = convertHttpContextInputToHttpContext(context, httpReqContext);
414
+ }
415
+ return context;
416
+ }
417
+ /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.6", ngImport: i0, type: SPMatEntityCrudFormBase, deps: [], target: i0.ɵɵFactoryTarget.Component });
418
+ /** @nocollapse */ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "19.1.6", type: SPMatEntityCrudFormBase, isStandalone: false, selector: "_#_sp-mat-entity-crud-form-base_#_", inputs: { entity: { classPropertyName: "entity", publicName: "entity", isSignal: true, isRequired: true, transformFunction: null }, bridge: { classPropertyName: "bridge", publicName: "bridge", isSignal: true, isRequired: true, transformFunction: null }, params: { classPropertyName: "params", publicName: "params", isSignal: true, isRequired: false, transformFunction: null }, entityName: { classPropertyName: "entityName", publicName: "entityName", isSignal: true, isRequired: false, transformFunction: null }, baseUrl: { classPropertyName: "baseUrl", publicName: "baseUrl", isSignal: true, isRequired: false, transformFunction: null }, httpReqContext: { classPropertyName: "httpReqContext", publicName: "httpReqContext", isSignal: true, isRequired: false, transformFunction: null }, idKey: { classPropertyName: "idKey", publicName: "idKey", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0, template: ``, isInline: true });
419
+ }
420
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.6", ngImport: i0, type: SPMatEntityCrudFormBase, decorators: [{
421
+ type: Component,
422
+ args: [{
423
+ selector: '_#_sp-mat-entity-crud-form-base_#_',
424
+ template: ``,
425
+ standalone: false,
426
+ }]
427
+ }] });
428
+
429
+ const SP_MAT_ENTITY_CRUD_HTTP_CONTEXT = new HttpContextToken(() => ({
430
+ entityName: '',
431
+ entityNamePlural: '',
432
+ endpoint: '',
433
+ op: undefined,
434
+ }));
435
+
436
+ const SP_MAT_ENTITY_CRUD_CONFIG = new InjectionToken('SPMatEntityCrudConfig');
437
+
438
+ function defaultCrudResponseParser(entityName, idKey, method, // 'create' | 'retrieve' | 'update' | 'delete',
439
+ resp) {
440
+ // If the response is an object with a property '<idKey>', return it as
441
+ // TEntity.
442
+ if (resp.hasOwnProperty(idKey)) {
443
+ return resp;
444
+ }
445
+ // If the response has an object indexed at '<entityName>' and it has
446
+ // the property '<idKey>', return it as TEntity.
447
+ if (resp.hasOwnProperty(entityName)) {
448
+ const obj = resp[entityName];
449
+ if (obj.hasOwnProperty(idKey)) {
450
+ return obj;
451
+ }
452
+ }
453
+ // Return undefined, indicating that we could't parse the response.
454
+ return undefined;
455
+ }
456
+ const DefaultSPMatEntityCrudConfig = {
457
+ crudOpResponseParser: defaultCrudResponseParser
458
+ };
459
+ /**
460
+ * To be called from an object constructor as it internally calls Angular's
461
+ * inject() API.
462
+ * @param userConfig
463
+ * @returns
464
+ */
465
+ function getEntityCrudConfig() {
466
+ const userCrudConfig = inject(SP_MAT_ENTITY_CRUD_CONFIG, {
467
+ optional: true,
468
+ });
469
+ return {
470
+ ...DefaultSPMatEntityCrudConfig,
471
+ ...(userCrudConfig ?? {}),
472
+ };
473
+ }
474
+
475
+ class FormViewHostComponent {
476
+ entityCrudComponentBase = input.required();
477
+ clientViewTemplate = input(null);
478
+ _itemLabel = computed(() => {
479
+ const label = this.entityCrudComponentBase().getItemLabel();
480
+ return label instanceof Observable ? label : of(label);
481
+ });
482
+ _itemLabelPlural = computed(() => {
483
+ const label = this.entityCrudComponentBase().getItemLabelPlural();
484
+ return label instanceof Observable ? label : of(label);
485
+ });
486
+ entity = signal(undefined);
487
+ title = signal(undefined);
488
+ params = signal(undefined);
489
+ clientFormView;
490
+ vc = viewChild('clientFormContainer', { read: ViewContainerRef });
491
+ config;
492
+ sub$ = new Subscription();
493
+ transloco = inject(TranslocoService);
494
+ constructor() {
495
+ this.config = getEntityCrudConfig();
496
+ }
497
+ ngOnInit() { }
498
+ ngOnDestroy() {
499
+ this.sub$.unsubscribe();
500
+ }
501
+ show(entity, params) {
502
+ this.entity.set(entity);
503
+ if (params && params?.title) {
504
+ this.title.set(params.title instanceof Observable ? params.title : of(params.title));
505
+ }
506
+ else {
139
507
  // this.title.set(entity ? this.config.i18n.editItemLabel(this.itemLabel()) : this.config.i18n.newItemLabel(this.itemLabel()));
140
508
  // this.title.set(
141
509
  // this.transloco.translate(entity ? 'editItem' : 'newItem', {
@@ -1713,376 +2081,9 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.6", ngImpor
1713
2081
  `, changeDetection: ChangeDetectionStrategy.OnPush, styles: [".preview-wrapper{display:flex;flex-direction:column;height:100%!important;width:100%!important}mat-toolbar{background-color:var(--mat-sys-surface-variant)}.spacer{flex:1 1 auto}.preview-content{padding:.4em;flex-grow:1;overflow:scroll}\n"] }]
1714
2082
  }] });
1715
2083
 
1716
- /**
1717
- * This is a convenience base class that clients can derive from to implement
1718
- * their CRUD form component. Particularly this class registers the change
1719
- * detection hook which will be called when the user attempts to close the
1720
- * form's parent container pane via the Close button on the top right.
1721
- *
1722
- * This button behaves like a Cancel button in a desktop app and therefore if
1723
- * the user has entered any data in the form's controls, (determined by
1724
- * checking form.touched), then a 'Lose Changes' prompt is displayed allowing
1725
- * the user to cancel the closure.
1726
- *
1727
- * The `@Component` decorator is fake to keep the VSCode angular linter quiet.
1728
- *
1729
- * This class can be used in two modes:
1730
- *
1731
- * I. SPMatEntityCrudComponent mode
1732
- * This mode relies on a bridge interface that implements the
1733
- * SPMatEntityCrudCreateEditBridge interface to perform the entity
1734
- * load/create/update operations. This is the intended mode when the
1735
- * component is used as a part of the SPMatEntityCrudComponent to
1736
- * create/update an entity. This mode requires the following properties
1737
- * to be set:
1738
- * - entity: TEntity | TEntity[IdKey] | undefined (for create)
1739
- * - bridge: SPMatEntityCrudCreateEditBridge
1740
- *
1741
- * II. Standalone mode
1742
- * This mode does not rely on the bridge interface and the component
1743
- * itself performs the entity load/create/update operations.
1744
- * This mode requires the following properties to be set:
1745
- * - entity: TEntity | TEntity[IdKey] | undefined (for create)
1746
- * - baseUrl: string - Base URL for CRUD operations. This URL does not
1747
- * include the entity id. The entity id will be appended to this URL
1748
- * for entity load and update operations. For create operation, this
1749
- * URL is used as is.
1750
- * - entityName: string - Name of the entity, used to parse sideloaded
1751
- * entity responses.
1752
- * - httpReqContext?: HttpContextInput - Optional HTTP context to be
1753
- * passed to the HTTP requests. For instance, if your app has a HTTP
1754
- * interceptor that adds authentication tokens to the requests based
1755
- * on a HttpContextToken, then you can pass that token here.
1756
- *
1757
- * I. SPMatEntityCrudComponent mode:
1758
- *
1759
- * 1. Declare a FormGroup<> type as
1760
- *
1761
- * ```
1762
- * type MyForm = FormGroup<{
1763
- * name: FormControl<string>;
1764
- * type: FormControl<string>;
1765
- * notes: FormControl<string>;
1766
- * }>;
1767
- * ```
1768
- *
1769
- * 2. Derive your form's component class from this and implement the
1770
- * createForm() method returing the FormGroup<> instance that matches
1771
- * the FormGroup concrete type above.
1772
- *
1773
- * ```
1774
- * class MyFormComponent extends SPMatEntityCrudFormBase<MyForm, MyEntity> {
1775
- * constructor() {
1776
- * super()
1777
- * }
1778
- * createForm() {
1779
- * return new FormGroup([...])
1780
- * }
1781
- * }
1782
- * ```
1783
- *
1784
- * 3. If your form's value requires manipulation before being sent to the
1785
- * server, override `getFormValue()` method and do it there before returning
1786
- * the modified values.
1787
- *
1788
- * 4. Wire up the form in the template as below
1789
- *
1790
- * ```html
1791
- * @if (loadEntity$ | async) {
1792
- * <form [formGroup]='form'.. (ngSubmit)="onSubmit()">
1793
- * <button type="submit">Submit</button>
1794
- * </form>
1795
- * } @else {
1796
- * <div>Loading...</div>
1797
- * }
1798
- * ```
1799
- *
1800
- * Here `loadEntity$` is an Observable<boolean> that upon emission of `true`
1801
- * indicates that the entity has been loaded from server (in case of edit)
1802
- * and the form is ready to be displayed. Note that if the full entity was
1803
- * passed in the `entity` input property, then no server load is necessary
1804
- * and the form will be created immediately.
1805
- *
1806
- * 5. In the parent component that hosts the SPMatEntityCrudComponent, set
1807
- * the `entity` and `bridge` input properties of this component to
1808
- * appropriate values. For instance, if your form component has the
1809
- * selector `app-my-entity-form`, then the parent component's template
1810
- * will have:
1811
- *
1812
- * ```html
1813
- * <sp-mat-entity-crud
1814
- * ...
1815
- * createEditFormTemplate="entityFormTemplate"
1816
- * ></sp-mat-entity-crud>
1817
- * <ng-template #entityFormTemplate let-data="data">
1818
- * <app-my-entity-form
1819
- * [entity]="data.entity"
1820
- * [bridge]="data.bridge"
1821
- * ></app-my-entity-form>
1822
- * </ng-template>
1823
- * ```
1824
- *
1825
- * II. Standalone mode
1826
- *
1827
- * 1..4. Same as above, except set the required `bridge` input to `undefined`.
1828
- * 5. Initialize the component's inputs `baseUrl` and `entityName` with the
1829
- * appropriate values. If you would like to pass additional HTTP context to
1830
- * the HTTP requests, then set the `httpReqContext` input as well.
1831
- * If the entity uses an id key other than 'id', then set the `idKey` input
1832
- * to the appropriate id key name.
1833
- * 6. If you want to retrieve the created/updated entity after the create/update
1834
- * operation, override the `onPostCreate()` and/or `onPostUpdate()` methods
1835
- * respectively.
1836
- */
1837
- class SPMatEntityCrudFormBase {
1838
- entity = input.required();
1839
- bridge = input.required();
1840
- params = input();
1841
- // --- BEGIN inputs used when `bridge` input is undefined
1842
- // Entity name, which is used to parse sideloaded entity responses
1843
- entityName = input();
1844
- // Base CRUD URL, which is the GET-list-of-entities/POST-to-create
1845
- // URL. Update URL will be derived from this ias `baseUrl()/${TEntity[IdKey]}`
1846
- baseUrl = input();
1847
- // Additional request context to be passed to the request
1848
- httpReqContext = input();
1849
- // ID key, defaults to 'id'
1850
- idKey = input('id');
1851
- // -- END inputs used when `bridge` input is undefined
1852
- // IMPLEMENTATION
1853
- loadEntity$;
1854
- _entity = signal(undefined);
1855
- sub$ = new Subscription();
1856
- // Store for internal form signal. form() is computed from this.
1857
- _form = signal(undefined);
1858
- // Force typecast to TFormGroup so that we can use it in the template
1859
- // without having to use the non-nullable operator ! with every reference
1860
- // of form(). In any case the form() signal is always set in ngOnInit()
1861
- // method after the form is created. And if form() is not set, then there
1862
- // will be errors while loading the form in the template.
1863
- form = computed(() => this._form());
1864
- transloco = inject(TranslocoService);
1865
- cdr = inject(ChangeDetectorRef);
1866
- http = inject(HttpClient);
1867
- canCancelEdit = () => {
1868
- return this._canCancelEdit();
1869
- };
1870
- _canCancelEdit() {
1871
- const form = this._form();
1872
- if (form && form.touched) {
1873
- return window.confirm(this.transloco.translate('spMatEntityCrud.loseChangesConfirm'));
1874
- }
1875
- return true;
1876
- }
1877
- ngOnInit() {
1878
- // validate inputs. Either bridge or (baseUrl and entityName) must be
1879
- // defined.
1880
- if (!this.bridge() && (!this.baseUrl() || !this.entityName())) {
1881
- throw new Error('SPMatEntityCrudFormBase: baseUrl and entityName inputs must be defined in standalone mode.');
1882
- }
1883
- this.loadEntity$ = (typeof this.entity() === 'object' || this.entity() === undefined
1884
- ? new Observable((subscriber) => {
1885
- subscriber.next(this.entity());
1886
- subscriber.complete();
1887
- })
1888
- : this.load(this.entity())).pipe(map((resp) => {
1889
- const compositeEntity = this.getEntityFromLoadResponse(resp);
1890
- this._entity.set(compositeEntity);
1891
- this._form.set(this.createForm(compositeEntity));
1892
- const bridge = this.bridge();
1893
- if (bridge && bridge.registerCanCancelEditCallback) {
1894
- bridge.registerCanCancelEditCallback(this.canCancelEdit);
1895
- }
1896
- return true;
1897
- }));
1898
- }
1899
- ngOnDestroy() {
1900
- this.sub$.unsubscribe();
1901
- }
1902
- /**
1903
- * Additional parameters for loading the entity, in case this.entity() value
1904
- * is of type TEntity[IdKey].
1905
- * @returns
1906
- */
1907
- getLoadEntityParams() {
1908
- return '';
1909
- }
1910
- /**
1911
- * Return the TEntity object from the response returned by the
1912
- * load() method. Typically entity load returns the actual
1913
- * entity object itself. In some cases, where response is sideloaded, the
1914
- * default implementation here uses the `sideloadToComposite()` utility to
1915
- * extract the entity from the response after merging (inplace) the
1916
- * sideloaded data into a composite.
1917
- *
1918
- * If you have a different response shape, or if your sideloaded object
1919
- * response requires custom custom `sideloadDataMap`, override this method
1920
- * and implement your custom logic to extract the TEntity object from the
1921
- * response.
1922
- * @param resp
1923
- * @returns
1924
- */
1925
- getEntityFromLoadResponse(resp) {
1926
- if (!resp || typeof resp !== 'object') {
1927
- return undefined;
1928
- }
1929
- const entityName = this.entityName();
1930
- if (resp.hasOwnProperty(this.getIdKey())) {
1931
- return resp;
1932
- }
1933
- else if (entityName && resp.hasOwnProperty(entityName)) {
1934
- // const sideloadDataMap = this.sideloadDataMap();
1935
- return sideloadToComposite(resp, this.entityName(), this.getIdKey());
1936
- }
1937
- return undefined;
1938
- }
1939
- /**
1940
- * Override to customize the id key name if it's not 'id'
1941
- * @returns The name of the unique identifier key that will be used to
1942
- * extract the entity's id for UPDATE operation.
1943
- */
1944
- getIdKey() {
1945
- const bridge = this.bridge();
1946
- if (bridge) {
1947
- return bridge.getIdKey();
1948
- }
1949
- return this.idKey();
1950
- }
1951
- /**
1952
- * Return the form's value to be sent to server as Create/Update CRUD
1953
- * operation data.
1954
- * @returns
1955
- */
1956
- getFormValue() {
1957
- const form = this.form();
1958
- return form ? form.value : undefined;
1959
- }
1960
- onSubmit() {
1961
- const value = this.getFormValue();
1962
- const obs = !this._entity()
1963
- ? this.create(value)
1964
- : this.update(this._entity()[this.getIdKey()], value);
1965
- this.sub$.add(obs
1966
- ?.pipe(tap(entity => this._entity() ? this.onPostUpdate(entity) : this.onPostCreate(entity)), setServerErrorsAsFormErrors(this._form(), this.cdr))
1967
- .subscribe());
1968
- }
1969
- onPostCreate(entity) {
1970
- /* empty */
1971
- }
1972
- onPostUpdate(entity) {
1973
- /* empty */
1974
- }
1975
- /**
1976
- * Loads the entity if `this.entity()` is of type TEntity[IdKey]. If `bridge`
1977
- * input is defined, then it's `loadEntity()` method is used to load the
1978
- * entity. Otherwise, then this method attempts to load the entity using
1979
- * HTTP GET from the URL derived from `baseUrl` input.
1980
- * @param entityId
1981
- * @param params
1982
- * @returns
1983
- */
1984
- load(entityId) {
1985
- const bridge = this.bridge();
1986
- const params = this.getLoadEntityParams();
1987
- if (bridge) {
1988
- return bridge.loadEntity(entityId, params);
1989
- }
1990
- // Try to load using baseUrl.
1991
- if (!this.baseUrl()) {
1992
- console.warn(`SPMatEntityCrudFormBase.load: No bridge defined, baseUrl input is undefined. Returning undefined.`);
1993
- return new Observable((subscriber) => {
1994
- subscriber.next(undefined);
1995
- subscriber.complete();
1996
- });
1997
- }
1998
- let context = new HttpContext();
1999
- if (this.httpReqContext()) {
2000
- context = convertHttpContextInputToHttpContext(context, this.httpReqContext());
2001
- }
2002
- const url = this.getEntityUrl(entityId);
2003
- return this.http
2004
- .get(this.getEntityUrl(entityId), {
2005
- params: typeof params === 'string'
2006
- ? new HttpParams({ fromString: params })
2007
- : params,
2008
- context: context,
2009
- })
2010
- .pipe(map((resp) => this.getEntityFromLoadResponse(resp)));
2011
- }
2012
- /**
2013
- * Create a new entity using the bridge if defined, otherwise using HTTP
2014
- * POST to the `baseUrl`.
2015
- * @param values
2016
- * @returns
2017
- */
2018
- create(values) {
2019
- const bridge = this.bridge();
2020
- if (bridge) {
2021
- return bridge.create(values);
2022
- }
2023
- const url = this.baseUrl();
2024
- if (!url) {
2025
- console.warn('SPMatEntityCrudFormBase.create: Cannot create entity as neither bridge nor baseUrl inputs are provided.');
2026
- return of(undefined);
2027
- }
2028
- const httpReqContext = this.httpReqContext();
2029
- let context = new HttpContext();
2030
- if (httpReqContext) {
2031
- context = convertHttpContextInputToHttpContext(context, httpReqContext);
2032
- }
2033
- return this.http
2034
- .post(url, values, { context: context })
2035
- .pipe(map((resp) => this.getEntityFromLoadResponse(resp)));
2036
- }
2037
- /**
2038
- * Update an existing entity using the bridge if defined, otherwise using HTTP
2039
- * PATCH to the URL derived from `baseUrl` and the entity id.
2040
- * @param id
2041
- * @param values
2042
- * @returns
2043
- */
2044
- update(id, values) {
2045
- const bridge = this.bridge();
2046
- if (bridge) {
2047
- return bridge.update(id, values);
2048
- }
2049
- const url = this.baseUrl();
2050
- if (!url) {
2051
- console.warn('SPMatEntityCrudFormBase.update: Cannot update entity as neither bridge nor baseUrl inputs are provided.');
2052
- return of(undefined);
2053
- }
2054
- return this.http
2055
- .patch(this.getEntityUrl(id), values)
2056
- .pipe(map((resp) => this.getEntityFromLoadResponse(resp)));
2057
- }
2058
- getEntityUrl(entityId) {
2059
- const bridge = this.bridge();
2060
- if (bridge) {
2061
- return bridge.getEntityUrl(entityId);
2062
- }
2063
- const baseUrl = this.baseUrl();
2064
- if (baseUrl) {
2065
- const urlParts = baseUrl.split('?');
2066
- return `${urlParts[0]}${String(entityId)}/${urlParts[1] ? '?' + urlParts[1] : ''}`;
2067
- }
2068
- console.warn('SPMatEntityCrudFormBase.getEntityUrl: Cannot determine entity URL as neither baseUrl nor bridge inputs are provided.');
2069
- return '';
2070
- }
2071
- /** @nocollapse */ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.6", ngImport: i0, type: SPMatEntityCrudFormBase, deps: [], target: i0.ɵɵFactoryTarget.Component });
2072
- /** @nocollapse */ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "19.1.6", type: SPMatEntityCrudFormBase, isStandalone: false, selector: "_#_sp-mat-entity-crud-form-base_#_", inputs: { entity: { classPropertyName: "entity", publicName: "entity", isSignal: true, isRequired: true, transformFunction: null }, bridge: { classPropertyName: "bridge", publicName: "bridge", isSignal: true, isRequired: true, transformFunction: null }, params: { classPropertyName: "params", publicName: "params", isSignal: true, isRequired: false, transformFunction: null }, entityName: { classPropertyName: "entityName", publicName: "entityName", isSignal: true, isRequired: false, transformFunction: null }, baseUrl: { classPropertyName: "baseUrl", publicName: "baseUrl", isSignal: true, isRequired: false, transformFunction: null }, httpReqContext: { classPropertyName: "httpReqContext", publicName: "httpReqContext", isSignal: true, isRequired: false, transformFunction: null }, idKey: { classPropertyName: "idKey", publicName: "idKey", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0, template: ``, isInline: true });
2073
- }
2074
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.6", ngImport: i0, type: SPMatEntityCrudFormBase, decorators: [{
2075
- type: Component,
2076
- args: [{
2077
- selector: '_#_sp-mat-entity-crud-form-base_#_',
2078
- template: ``,
2079
- standalone: false,
2080
- }]
2081
- }] });
2082
-
2083
2084
  /**
2084
2085
  * Generated bundle index. Do not edit.
2085
2086
  */
2086
2087
 
2087
- export { SPMatEntityCrudComponent, SPMatEntityCrudFormBase, SPMatEntityCrudPreviewPaneComponent, SP_MAT_ENTITY_CRUD_CONFIG, SP_MAT_ENTITY_CRUD_HTTP_CONTEXT };
2088
+ export { SPMatEntityCrudComponent, SPMatEntityCrudFormBase, SPMatEntityCrudPreviewPaneComponent, SP_MAT_ENTITY_CRUD_CONFIG, SP_MAT_ENTITY_CRUD_HTTP_CONTEXT, convertHttpContextInputToHttpContext };
2088
2089
  //# sourceMappingURL=smallpearl-ngx-helper-mat-entity-crud.mjs.map