@sankhyalabs/core 2.9.0 → 2.11.0

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.
@@ -33,6 +33,9 @@ export default class DataUnit {
33
33
  private _stateManager: StateManager;
34
34
  private _interceptors: Array<DUActionInterceptor>;
35
35
  private _pageSize: number;
36
+ private _childByName = new Map<string, DataUnit>();
37
+ private _parentDataUnit: DataUnit | undefined;
38
+ private _parentSelectedRecordID: string | undefined;
36
39
 
37
40
  public metadataLoader?: (dataUnit: DataUnit) => Promise<UnitMetadata>;
38
41
  public dataLoader?: (dataUnit: DataUnit, request: LoadDataRequest) => Promise<LoadDataResponse>;
@@ -40,7 +43,7 @@ export default class DataUnit {
40
43
  public removeLoader?: (dataUnit: DataUnit, recordIds: Array<string>) => Promise<Array<string>>;
41
44
  public recordLoader?: (dataUnit: DataUnit, recordIds: Array<string>) => Promise<Array<Record>>;
42
45
 
43
- constructor(name: string) {
46
+ constructor(name: string, parentDataUnit?: DataUnit) {
44
47
  this._name = name;
45
48
  this._pageSize = 0;
46
49
  this._stateManager = new StateManager(
@@ -61,6 +64,9 @@ export default class DataUnit {
61
64
  this._filterProviders = new Map<string, FilterProvider>();
62
65
  this._sortingProvider = undefined;
63
66
  this._interceptors = [];
67
+ this._parentDataUnit = parentDataUnit;
68
+ this._parentDataUnit?.subscribe(this.onDataUnitParentEvent);
69
+
64
70
  }
65
71
 
66
72
  /**
@@ -89,6 +95,26 @@ export default class DataUnit {
89
95
  return descriptor ? convertType(descriptor.dataType, newValue) : newValue;
90
96
  }
91
97
 
98
+ /**
99
+ *
100
+ * Trata as Actions do DataUnit Parent
101
+ *
102
+ *
103
+ */
104
+ private onDataUnitParentEvent = (action: DataUnitAction) => {
105
+ switch(action.type){
106
+ case Action.SELECTION_CHANGED:
107
+ this._parentSelectedRecordID = this._parentDataUnit?.getSelectedRecord()?.__record__id__;
108
+ this.loadData();
109
+ break;
110
+ case Action.DATA_LOADED:
111
+ if(this._parentDataUnit?.getSelectedRecord() == undefined){
112
+ this.clearDataUnit();
113
+ }
114
+ break;
115
+ }
116
+ }
117
+
92
118
  /**
93
119
  *
94
120
  * Obtém chave única para identificação do FilterProvider.
@@ -173,10 +199,20 @@ export default class DataUnit {
173
199
  */
174
200
  public async loadData(quickFilter?: QuickFilter, executionCtx?: ExecutionContext): Promise<LoadDataResponse> {
175
201
 
202
+ if(this._parentDataUnit && !this._parentDataUnit.getSelectedRecord()){
203
+ if(this.records){
204
+ this.clearDataUnit();
205
+ }
206
+ return Promise.resolve({
207
+ records: []
208
+ });
209
+ }
210
+
176
211
  const loadDataRequest: LoadDataRequest = {
177
212
  quickFilter,
178
213
  filters: this.getFilters(),
179
- sort: this.getSort()
214
+ sort: this.getSort(),
215
+ parentRecordId: this._parentSelectedRecordID
180
216
  };
181
217
 
182
218
  if (this._pageSize > 0) {
@@ -552,7 +588,7 @@ export default class DataUnit {
552
588
  *
553
589
  */
554
590
  public addRecord(executionCtx?: ExecutionContext): void {
555
- this.dispatchAction(Action.RECORDS_ADDED, prepareAddedRecordId(this._stateManager, [{}]), executionCtx);
591
+ this.dispatchAction(Action.RECORDS_ADDED, prepareAddedRecordId(this._stateManager, [{}], this._parentSelectedRecordID), executionCtx);
556
592
  }
557
593
 
558
594
  /**
@@ -565,7 +601,7 @@ export default class DataUnit {
565
601
  public copySelected(executionCtx?: ExecutionContext): void {
566
602
  const selectedRecords = this.getSelectedRecords();
567
603
  if (selectedRecords) {
568
- this.dispatchAction(Action.RECORDS_COPIED, prepareCopiedRecord(this._stateManager, selectedRecords), executionCtx);
604
+ this.dispatchAction(Action.RECORDS_COPIED, prepareCopiedRecord(this._stateManager, selectedRecords, this._parentSelectedRecordID), executionCtx);
569
605
  }
570
606
  }
571
607
 
@@ -710,10 +746,34 @@ export default class DataUnit {
710
746
  const selection: Array<string> = this.getSelection();
711
747
  if (selection) {
712
748
  const currentRecords: Array<Record> = this.records;
713
- return currentRecords?.filter(r => selection.includes(r.__record__id__));
749
+ return currentRecords?.filter(record => selection.includes(record.__record__id__));
714
750
  }
715
751
  }
716
752
 
753
+ /**
754
+ *
755
+ * Retorna apenas um registro selecionado no Dataunit
756
+ *
757
+ * @returns - Registro selecionado.
758
+ *
759
+ */
760
+ public getSelectedRecord(): Record | undefined {
761
+ const selection: Array<string> = this.getSelection();
762
+ if(!selection) return;
763
+ return this.records.find(record => (selection as Array<string>).includes(record.__record__id__));
764
+ }
765
+
766
+ /**
767
+ *
768
+ * Limpa todos os registros do DataUnit
769
+ *
770
+ *
771
+ *
772
+ */
773
+ public clearDataUnit(): void {
774
+ this.records = [];
775
+ }
776
+
717
777
  /**
718
778
  *
719
779
  * Seleciona o próximo registro.
@@ -963,6 +1023,19 @@ export default class DataUnit {
963
1023
  });
964
1024
  }
965
1025
 
1026
+ /**
1027
+ *
1028
+ * Cria um dataunit filho.
1029
+ *
1030
+ * @param name - Nome do dataunit filho.
1031
+ *
1032
+ */
1033
+ public getChildDataunit(name:string){
1034
+ const detail: DataUnit = new DataUnit(name, this);
1035
+ this._childByName.set(name, detail);
1036
+ return detail;
1037
+ }
1038
+
966
1039
  /**
967
1040
  *
968
1041
  * Adiciona um novo observer no DataUnit.
@@ -1155,7 +1228,6 @@ export interface QuickFilter {
1155
1228
  fields?: Array<string>;
1156
1229
  }
1157
1230
 
1158
-
1159
1231
  export interface PageResponse {
1160
1232
  limit: number;
1161
1233
  offset: number;
@@ -17,4 +17,7 @@ export interface LoadDataRequest {
17
17
 
18
18
  /** Ordenação dos resultados */
19
19
  sort?: Array<Sort>;
20
+
21
+ /** Info parent */
22
+ parentRecordId?: string | undefined;
20
23
  }
@@ -4,7 +4,7 @@ export interface UnitMetadata{
4
4
  name: string;
5
5
  label: string;
6
6
  fields: Array<FieldDescriptor>;
7
- children?: Array<ChildDescriptor>
7
+ children?: Array<ChildDescriptor>;
8
8
  }
9
9
 
10
10
  export interface ChildDescriptor{
@@ -27,12 +27,22 @@ export const getAddedRecords = (stateManager: StateManager): Array<Record> => {
27
27
  return stateManager.select(AddedRecordsReducer.sliceName, (state: Array<Record>) => state);
28
28
  };
29
29
 
30
- export const prepareAddedRecordId = (stateManager: StateManager, source: Array<any>): Array<Record> => {
31
- let index = (getAddedRecords(stateManager)||[]).length;
32
- return source.map(item=>{return {...item, __record__id__: "NEW_" + (index++)}});
30
+ export const prepareAddedRecordId = (stateManager: StateManager, source: Array<any>, parentRecordId?: string): Array<Record> => {
31
+ let index = (getAddedRecords(stateManager) || []).length;
32
+ return source.map(item => ({
33
+ ...item,
34
+ __record__id__: `NEW_${index++}`,
35
+ ...(parentRecordId && { __parent__record__id__: parentRecordId }),
36
+ }));
33
37
  };
34
38
 
35
- export const prepareCopiedRecord = (stateManager: StateManager, source: Array<Record>): Array<Record> => {
39
+ export const prepareCopiedRecord = (stateManager: StateManager, source: Array<Record>, parentRecordId?: string): Array<Record> => {
36
40
  let index = (getAddedRecords(stateManager)||[]).length;
37
- return source.map(item=>{return {...item, __record__id__: "NEW_" + (index++), __record__source__id__: item.__record__id__, __copy__: true}});
41
+ return source.map(item => ({
42
+ ...item,
43
+ __record__id__: "NEW_" + (index++),
44
+ ...(parentRecordId && { __parent__record__id__: parentRecordId }),
45
+ __record__source__id__: item.__record__id__,
46
+ __copy__: true})
47
+ );
38
48
  };
@@ -1,13 +1,5 @@
1
1
  import { StringUtils } from "./StringUtils.js";
2
2
 
3
- type FilterRecursivelyParams<T> = {
4
- query: string;
5
- list: T[];
6
- fieldName: string;
7
- key: string;
8
- sortAlphabetically?: boolean;
9
- }
10
-
11
3
  /**
12
4
  * `ArrayUtils`: Utilitário com a responsabilidade de manipular Arrays.
13
5
  */
@@ -42,34 +34,6 @@ export default class ArrayUtils {
42
34
  private static normalizeSearchString(original:string ): string{
43
35
  return StringUtils.replaceAccentuatedCharsKeepSymbols(original.toUpperCase());
44
36
  }
45
-
46
- /**
47
- * Filtra um array a partir de um critério textual.
48
- *
49
- * @param {string} options.query - Texto a ser usado no filtro.
50
- * @param {Object[]} options.list - Lista a ser filtrada.
51
- * @param {string} options.fieldName - Nome do campo onde irá ser feito a busca a partir do parâmetro `query`.
52
- * @param {string} options.key - Nome do atributo onde conterá outros atributos filhos.
53
- * @param {boolean} [options.sortAlphabetically=true] - Determina se o resultado deve ser ordenado ou mantido na ordem original. Por padrão ordena.
54
- * @returns - Uma lista recursivamente filtrada e ordenado conforme necessidade..
55
- */
56
- static applyStringFilterRecursively<ListType>({ query, list, fieldName, key, sortAlphabetically = true }: FilterRecursivelyParams<ListType>): ListType[] {
57
- const normalizedArgument = ArrayUtils.normalizeSearchString(query);
58
- const alphabeticalSortingList = sortAlphabetically ? ArrayUtils.sortAlphabetically(list, fieldName) : list;
59
-
60
- const recursiveReducer = (initialList: ListType[], item: any) => {
61
- const itemValue = ArrayUtils.normalizeSearchString(item[fieldName]);
62
- if (itemValue.includes(normalizedArgument)) {
63
- initialList.push(item);
64
- return initialList;
65
- }
66
- item[key] = Array.isArray(item[key]) ? item[key].reduce(recursiveReducer, []) : [];
67
- if (item[key].length) initialList.push({ ...item, [key]: item[key] });
68
- return initialList;
69
- }
70
-
71
- return alphabeticalSortingList.reduce(recursiveReducer, []);
72
- }
73
37
 
74
38
  /**
75
39
  * Ordena valores de um array alfabeticamente.