summaryrefslogtreecommitdiffstats
path: root/sdnr/wt/odlux/framework/src/components/material-table/utilities.ts
blob: f9015493f4ccf348bcf99c4c29bf9cfdbf7b90c1 (plain)
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/**
 * ============LICENSE_START========================================================================
 * ONAP : ccsdk feature sdnr wt odlux
 * =================================================================================================
 * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
 * =================================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 * ============LICENSE_END==========================================================================
 */
import { Action, IActionHandler } from '../../flux/action';
import { Dispatch } from '../../flux/store';

import { AddErrorInfoAction } from '../../actions/errorActions';
import { IApplicationStoreState } from '../../store/applicationStore';

export const RowDisabled = Symbol("RowDisabled");
import { DataCallback } from ".";

export interface IExternalTableState<TData> {
  order: 'asc' | 'desc';
  orderBy: string | null;
  selected: any[] | null;
  hiddenColumns: string[]
  rows: (TData & { [RowDisabled]?: boolean })[];
  total: number;
  page: number;
  rowsPerPage: number;
  loading: boolean;
  showFilter: boolean;
  filter: { [property: string]: string };
  preFilter: { [property: string]: string };
}

export type ExternalMethodes<TData> = {
  reloadAction: (dispatch: Dispatch, getAppState: () => IApplicationStoreState) => Promise<void | AddErrorInfoAction>;
  createActions: (dispatch: Dispatch, skipRefresh?: boolean) => {
    onRefresh: () => void;
    onHandleRequestSort: (orderBy: string) => void;
    onHandleExplicitRequestSort: (property: string, sortOrder: "asc" | "desc") => void;
    onToggleFilter: (refresh?: boolean | undefined) => void;
    onFilterChanged: (property: string, filterTerm: string) => void;
    onHandleChangePage: (page: number) => void;
    onHandleChangeRowsPerPage: (rowsPerPage: number | null) => void;
    onHideColumns: (columnName: string[]) => void;
    onShowColumns: (columnName: string[]) => void;
  },
 createPreActions: (dispatch: Dispatch, skipRefresh?: boolean) => {
  onPreFilterChanged: (preFilter: {
      [key: string]: string;
  }) => void;
 };
 createProperties: (state: IApplicationStoreState) => IExternalTableState<TData>;
 actionHandler: IActionHandler<IExternalTableState<TData>, Action>;
}


/** Create an actionHandler and actions for external table states. */
export function createExternal<TData>(callback: DataCallback<TData>, selectState: (appState: IApplicationStoreState) => IExternalTableState<TData>) : ExternalMethodes<TData> ;
export function createExternal<TData>(callback: DataCallback<TData>, selectState: (appState: IApplicationStoreState) => IExternalTableState<TData>, disableRow: (data: TData) => boolean) : ExternalMethodes<TData>;
export function createExternal<TData>(callback: DataCallback<TData>, selectState: (appState: IApplicationStoreState) => IExternalTableState<TData>, disableRow?: (data: TData) => boolean) : ExternalMethodes<TData> {

  //#region Actions
  abstract class TableAction extends Action { }


  class RequestSortAction extends TableAction {
    constructor(public orderBy: string) {
      super();
    }
  }

  class RequestExplicitSortAction extends TableAction {
    constructor(public propertyName: string, public sortOrder: "asc" | "desc") {
      super();
    }
  }

  class SetSelectedAction extends TableAction {
    constructor(public selected: TData[] | null) {
      super();
    }
  }

  class SetPageAction extends TableAction {
    constructor(public page: number) {
      super();
    }
  }

  class SetRowsPerPageAction extends TableAction {
    constructor(public rowsPerPage: number) {
      super();
    }
  }

  class SetPreFilterChangedAction extends TableAction {
    constructor(public preFilter: { [key: string]: string }) {
      super();
    }
  }

  class SetFilterChangedAction extends TableAction {
    constructor(public filter: { [key: string]: string }) {
      super();
    }
  }

  class SetShowFilterAction extends TableAction {
    constructor(public show: boolean) {
      super();
    }
  }

  class RefreshAction extends TableAction {
    constructor() {
      super();
    }
  }

  class SetResultAction extends TableAction {
    constructor(public result: { page: number, total: number, rows: TData[] }) {
      super();
    }
  }

  class HideColumnsAction extends TableAction{
    constructor(public property: string[]){
      super();
    }
  }

  class ShowColumnsAction extends TableAction{
    constructor(public property: string[]){
      super();
    }
  }

  // #endregion

  //#region Action Handler
  const externalTableStateInit: IExternalTableState<TData> = {
    order: 'asc',
    orderBy: null,
    selected: null,
    hiddenColumns:[],
    rows: [],
    total: 0,
    page: 0,
    rowsPerPage: 10,
    loading: false,
    showFilter: false,
    filter: {},
    preFilter: {}
  };

  const externalTableStateActionHandler: IActionHandler<IExternalTableState<TData>> = (state = externalTableStateInit, action) => {
    if (!(action instanceof TableAction)) return state;
    if (action instanceof RefreshAction) {
      state = {
        ...state,
        loading: true
      }
    } else if (action instanceof SetResultAction) {
      state = {
        ...state,
        loading: false,
        rows: disableRow 
          ? action.result.rows.map((row: TData) => ({...row, [RowDisabled]: disableRow(row) })) 
          : action.result.rows,
        total: action.result.total,
        page: action.result.page,
      }
    } else if (action instanceof RequestSortAction) {
      state = {
        ...state,
        loading: true,
        orderBy: state.orderBy === action.orderBy && state.order === 'desc' ? null : action.orderBy,
        order: state.orderBy === action.orderBy && state.order === 'asc' ? 'desc' : 'asc',
      }
    } else if (action instanceof RequestExplicitSortAction) {
      state = {
        ...state,
        loading: true,
        orderBy: action.propertyName,
        order: action.sortOrder
      }
    }
    else if (action instanceof SetShowFilterAction) {
      state = {
        ...state,
        loading: true,
        showFilter: action.show
      }
    } else if (action instanceof SetPreFilterChangedAction) {
      state = {
        ...state,
        loading: true,
        preFilter: action.preFilter
      }
    } else if (action instanceof SetFilterChangedAction) {
      state = {
        ...state,
        loading: true,
        filter: action.filter
      }
    } else if (action instanceof SetPageAction) {
      state = {
        ...state,
        loading: true,
        page: action.page
      }
    } else if (action instanceof SetRowsPerPageAction) {
      state = {
        ...state,
        loading: true,
        rowsPerPage: action.rowsPerPage
      }
    }
    else if (action instanceof HideColumnsAction){
      
      //merge arrays, remove duplicates
      const newArray = [...new Set([...state.hiddenColumns, ...action.property])]
      state = {...state, hiddenColumns: newArray};
    }
    else if(action instanceof ShowColumnsAction){

      const newArray = state.hiddenColumns.filter(el=> !action.property.includes(el));
      state = {...state, hiddenColumns: newArray};
    }

    return state;
  }

  //const createTableAction(tableAction)

  //#endregion
  const reloadAction = (dispatch: Dispatch, getAppState: () => IApplicationStoreState) => {
    dispatch(new RefreshAction());
    const ownState = selectState(getAppState());
    const filter = { ...ownState.preFilter, ...(ownState.showFilter && ownState.filter || {}) };
    return Promise.resolve(callback(ownState.page, ownState.rowsPerPage, ownState.orderBy, ownState.order, filter)).then(result => {

      if (ownState.page > 0 && ownState.rowsPerPage * ownState.page > result.total) { //if result is smaller than the currently shown page, new search and repaginate

        let newPage = Math.floor(result.total / ownState.rowsPerPage);

        Promise.resolve(callback(newPage, ownState.rowsPerPage, ownState.orderBy, ownState.order, filter)).then(result1 => {
          dispatch(new SetResultAction(result1));
        });


      } else {
        dispatch(new SetResultAction(result));
      }


    }).catch(error => dispatch(new AddErrorInfoAction(error)));
  };

  const createPreActions = (dispatch: Dispatch, skipRefresh: boolean = false) => {
    return {
      onPreFilterChanged: (preFilter: { [key: string]: string }) => {
        dispatch(new SetPreFilterChangedAction(preFilter));
        (!skipRefresh) && dispatch(reloadAction);
      }
    };
  }

  const createActions = (dispatch: Dispatch, skipRefresh: boolean = false) => {
    return {
      onRefresh: () => {
        dispatch(reloadAction);
      },
      onHandleRequestSort: (orderBy: string) => {
        dispatch((dispatch: Dispatch) => {
          dispatch(new RequestSortAction(orderBy));
          (!skipRefresh) && dispatch(reloadAction);
        });
      },
      onHandleExplicitRequestSort: (property: string, sortOrder: "asc" | "desc") => {
        dispatch((dispatch: Dispatch) => {
          dispatch(new RequestExplicitSortAction(property, sortOrder));
          (!skipRefresh) && dispatch(reloadAction);
        });
      },
      onToggleFilter: (refresh?: boolean) => {
        dispatch((dispatch: Dispatch, getAppState: () => IApplicationStoreState) => {
          const { showFilter } = selectState(getAppState());
          dispatch(new SetShowFilterAction(!showFilter));
          if (!skipRefresh && (refresh === undefined || refresh))
            dispatch(reloadAction);
        });
      },
      onFilterChanged: (property: string, filterTerm: string) => {
        dispatch((dispatch: Dispatch, getAppState: () => IApplicationStoreState) => {
          let { filter } = selectState(getAppState());
          filter = { ...filter, [property]: filterTerm };
          dispatch(new SetFilterChangedAction(filter));
          (!skipRefresh) && dispatch(reloadAction);
        });
      },
      onHandleChangePage: (page: number) => {
        dispatch((dispatch: Dispatch) => {
          dispatch(new SetPageAction(page));
          (!skipRefresh) && dispatch(reloadAction);
        });
      },
      onHandleChangeRowsPerPage: (rowsPerPage: number | null) => {
        dispatch((dispatch: Dispatch) => {
          dispatch(new SetRowsPerPageAction(rowsPerPage || 10));
          (!skipRefresh) && dispatch(reloadAction);
        });
      },
      onHideColumns: (columnName: string[]) =>{
        dispatch((dispatch: Dispatch) => {
          dispatch(new HideColumnsAction(columnName));
        })
      },
      onShowColumns: (columnName: string[]) =>{
        dispatch((dispatch: Dispatch) => {
          dispatch(new ShowColumnsAction(columnName));
        })
      }
      // selected:
    };
  };

  const createProperties = (state: IApplicationStoreState) => {
    return {
      ...selectState(state)
    }
  }

  return {
    reloadAction: reloadAction,
    createActions: createActions,
    createProperties: createProperties,
    createPreActions: createPreActions,
    actionHandler: externalTableStateActionHandler,
  }
}