summaryrefslogtreecommitdiffstats
path: root/grid/src/grid.ts
blob: f263ac76d64cd79115f1870101669bc0c6fef4e8 (plain) (blame)
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
351
352
353
import * as JsSearch from "js-search";

interface GridProps {
    id?: string;
    debug?: boolean;
    data: Array<Object>;
    columns: Array<GridColumn>;
    pageSize?: number;
    search?: SearchConfiguration;
    tableClassName?: string
}

interface GridConfiguration {
    id: string;
    debug: boolean;
    data: Array<Object>;
    columns: Array<GridColumn>;
    pageSize: number;
    search: SearchConfiguration;
    tableClassName: string
}

interface SearchConfiguration {
    dataIds: Array<string | Array<string>>;
}

interface GridColumn {
    dataId?: string | Array<string>;
    columnName: string | Function;
    cellValue?: string | Function | Element;
    width?: string;
    maxWidth?: string;
    minWidth?: string;
}

export default class Grid {
    private readonly canRender: boolean;
    private readonly defaultOptions: GridConfiguration = {
        id: "id",
        debug: false,
        columns: [],
        data: [],
        pageSize: 0,
        tableClassName: "table",
        search: {
            dataIds: [],
        },
    };
    private configuration: GridConfiguration;
    private domElement: Element;
    private searchIndex: JsSearch.Search;
    public currentPage: number = 0;

    constructor(props: GridProps) {
        this.setOptions(props);
        this.validateOptions();
        this.canRender = true;
    }

    private setOptions(props: GridProps = this.defaultOptions): void {
        this.configuration = {} as GridConfiguration;
        this.configuration.columns = [];
        for (const column of props.columns) {
            if (isGridColumn(column)) {
                this.configuration.columns.push(column);
            } else {
                this.log("column is not of type GridColumn: " + JSON.stringify(column));
            }
        }
        this.configuration.data = props.data ?? this.defaultOptions.data;
        this.configuration.id = props.id ?? this.defaultOptions.id;
        this.configuration.debug = props.debug ?? this.defaultOptions.debug;
        this.configuration.pageSize = props.pageSize ?? this.defaultOptions.pageSize;
        this.configuration.tableClassName = props.tableClassName ?? this.defaultOptions.tableClassName;
        this.configuration.search = props.search ?? this.defaultOptions.search;
    }

    private validateOptions(): void {
        if (this.configuration.data.length === undefined) {
            throw new GridError("props.data.length is undefined");
        }
        if (this.configuration.columns.length === undefined || this.configuration.columns.length <= 0) {
            throw new GridError("props.columns.length is undefined or <= 0");
        }
    }

    private renderCurrentPageIndicator(): void {
        if (this.configuration.pageSize <= 0) return;
        this.domElement.querySelectorAll(".pagination .page-item").forEach((el) => {
            if (el.getAttribute("data-page-number") == this.currentPage.toString()) el.classList.add("active");
            else el.classList.remove("active");
        });
    }

    private renderPaginator(): void {
        if (this.configuration.pageSize === 0 || this.configuration.data.length < this.configuration.pageSize) return;
        const nav = document.createElement("nav");
        nav.className = "float-right user-select-none";
        const ul = document.createElement("ul");
        ul.className = "pagination";
        const previousItem = document.createElement("li");
        previousItem.className = "page-item";
        previousItem.onclick = () => this.navigate(this.currentPage - 1);
        const previousLink = document.createElement("span");
        previousLink.style.cursor = "pointer";
        previousLink.className = "page-link";
        previousLink.innerText = "Forrige";
        previousItem.appendChild(previousLink);
        ul.appendChild(previousItem);

        for (let i = 0; i < this.configuration.data.length / this.configuration.pageSize; i++) {
            const item = document.createElement("li");
            item.className = "page-item";
            item.dataset.pageNumber = i.toString();
            item.onclick = () => this.navigate(i);
            const link = document.createElement("span");
            link.className = "page-link";
            link.style.cursor = "pointer";
            link.innerText = (i + 1).toString();
            item.appendChild(link);
            ul.appendChild(item);
        }

        const nextItem = document.createElement("li");
        nextItem.className = "page-item";
        nextItem.onclick = () => this.navigate(this.currentPage + 1);
        const nextLink = document.createElement("span");
        nextLink.style.cursor = "pointer";
        nextLink.className = "page-link";
        nextLink.innerText = "Neste";
        nextItem.appendChild(nextLink);

        ul.appendChild(nextItem);
        nav.appendChild(ul);
        this.domElement.appendChild(nav);
    }

    private renderWrapper(): void {
        const wrapper = document.createElement("table");
        const thead = document.createElement("thead");
        const tbody = document.createElement("tbody");
        wrapper.className = this.configuration.tableClassName;
        wrapper.appendChild(thead);
        wrapper.appendChild(tbody);
        this.domElement.appendChild(wrapper);
    }

    private renderHead(): void {
        const wrapper = this.domElement.querySelector("table thead");
        wrapper.innerHTML = "";
        const row = document.createElement("tr");
        for (const col of this.configuration.columns) {
            const th = document.createElement("th");
            th.innerText = this.asString(col.columnName);
            row.appendChild(th);
        }
        wrapper.appendChild(row);
    }

    // https://github.com/bvaughn/js-search/blob/master/source/getNestedFieldValue.js
    private getNestedFieldValue<T>(object: Object, path: Array<string>): T {
        path = path || [];
        object = object || {};

        let value = object;

        // walk down the property path
        for (let i = 0; i < path.length; i++) {
            value = value[path[i]];
            if (value == null) {
                return null;
            }
        }

        return value as T;
    }

    private renderBody(data: Array<Object> = null, isSearchResult: boolean = false): void {
        let wrapper: Element;
        if (isSearchResult) {
            this.domElement.querySelector("table tbody:not(.search-results)").classList.add("d-none");
            this.domElement.querySelector("table tbody.search-results").classList.remove("d-none");
            wrapper = this.domElement.querySelector("table tbody.search-results");
        } else {
            this.domElement.querySelector("table tbody.search-results")?.classList.add("d-none");
            this.domElement.querySelector("table tbody:not(.search-results)").classList.remove("d-none");
            wrapper = this.domElement.querySelector("table tbody:not(.search-results)");
        }
        wrapper.innerHTML = "";
        let items = data ?? this.configuration.data;
        if (this.configuration.pageSize > 0) {
            items = items.slice(0, this.configuration.pageSize);
        }
        for (const item of items) {
            const row = document.createElement("tr");
            // @ts-ignore
            row.dataset.id = item[this.configuration.id];
            for (const val of this.configuration.columns) {
                const cell = document.createElement("td");
                cell.className = "text-break";
                if (val.width) cell.style.width = val.width;
                if (val.maxWidth) cell.style.maxWidth = val.maxWidth;
                if (val.minWidth) cell.style.minWidth = val.minWidth;

                if (val.cellValue instanceof Function) {
                    const computed = val.cellValue(item);
                    if (computed instanceof Element) cell.appendChild(computed);
                    else if (typeof computed === "string" || typeof computed === "number") cell.innerText = computed as string;
                } else if (Array.isArray(val.dataId)) {
                    cell.innerText = this.getNestedFieldValue(item, val.dataId);
                } else if (typeof val.dataId === "string" && val.dataId.length > 0) {
                    cell.innerText = item[val.dataId];
                } else if (typeof val.cellValue === "string" || typeof val.cellValue === "number") {
                    cell.innerText = val.cellValue;
                } else if (val.cellValue instanceof Element) {
                    cell.appendChild(val.cellValue);
                }
                row.appendChild(cell);
            }
            wrapper.appendChild(row);
        }
    }

    private asString(val: string | Function, callbackData: any = undefined) {
        if (val instanceof Function) {
            return val(callbackData);
        } else {
            return val;
        }
    }

    private static id(): string {
        return Math.random().toString(36).substring(2) + Date.now().toString(36);
    }

    private log(message: any): void {
        if (!this.configuration.debug) return;
        console.log("Grid Debug: " + message);
    }

    private renderSearch() {
        if (this.configuration.search.dataIds.length < 1) return;
        const wrapper = document.createElement("div");
        const searchInput = document.createElement("input");
        searchInput.type = "text";
        searchInput.className = "form-control";
        searchInput.placeholder = "Søk";
        searchInput.oninput = () => this.search(searchInput.value);
        wrapper.appendChild(searchInput);
        this.domElement.appendChild(wrapper);
    }

    private renderSearchResultWrapper() {
        if (this.configuration.search.dataIds.length < 1) return;
        const searchWrapper = document.createElement("tbody");
        searchWrapper.className = "search-results";
        this.domElement.querySelector("table").appendChild(searchWrapper);
    }

    private populateSearchIndex() {
        if (this.configuration.search.dataIds.length < 1) return;
        this.searchIndex = new JsSearch.Search(this.configuration.id);
        this.searchIndex.indexStrategy = new JsSearch.ExactWordIndexStrategy();
        this.configuration.search.dataIds.forEach((id) => this.searchIndex.addIndex(id));
        this.searchIndex.addDocuments(this.configuration.data);
    }

    public search(query: string): void {
        if (this.configuration.search.dataIds.length < 1) return;
        let result = this.searchIndex.search(query);
        if (result.length === 0) {
            this.renderBody(this.configuration.data);
        } else {
            this.renderBody(result, true);
        }
    }

    public navigate(pageNumber: number): void {
        const maxPage = Math.ceil(this.configuration.data.length / this.configuration.pageSize - 1);
        if (this.configuration.pageSize <= 0 || pageNumber < 0 || pageNumber === this.currentPage || pageNumber > maxPage) return;
        this.log("Navigating to page: " + pageNumber);
        const skipCount = this.configuration.pageSize * pageNumber;
        const endIndex =
            this.configuration.data.length < skipCount + this.configuration.pageSize
                ? this.configuration.data.length
                : skipCount + this.configuration.pageSize;
        this.renderBody(this.configuration.data.slice(skipCount, endIndex));
        this.currentPage = pageNumber;
        this.renderCurrentPageIndicator();
    }

    public removeByID(id: string): void {
        // @ts-ignore
        const itemIndex = this.configuration.data.findIndex((c) => c[this.configuration.id] === id);
        if (itemIndex !== -1) {
            delete this.configuration.data[itemIndex];
            this.domElement.querySelector(`tr[data-id="${id}"]`).remove();
        } else {
            this.log("Grid does not contain id: " + id);
        }
    }

    public refresh(data?: Array<Object>) {
        this.renderPaginator();
        this.navigate(0);
        if (data !== undefined) this.configuration.data = data;
        this.renderBody();
        this.populateSearchIndex();
    }

    public render(el: Element): void {
        if (this.canRender) {
            this.log("Grid starting render");
            this.domElement = el;
            this.renderSearch();
            this.populateSearchIndex();
            this.renderWrapper();
            this.renderHead();
            this.renderBody();
            this.renderPaginator();
            this.renderCurrentPageIndicator();
            this.renderSearchResultWrapper();
            this.log("Grid was rendered");
        } else {
            throw new GridError("render is not allowed due to invalid props");
        }
    }
}

class GridError extends Error {
    constructor(message: string) {
        super(message);
        this.name = "GridError";
    }
}

function isArrayOfGridColumn(array: Array<GridColumn> | Array<string>): array is Array<GridColumn> {
    try {
        // @ts-ignore
        return !(array.map((element) => "name" in element).indexOf(false) !== -1);
    } catch (e) {
        return false;
    }
}

function isGridColumn(val: GridColumn | string): val is GridColumn {
    try {
        // @ts-ignore
        return "columnName" in val && ("cellValue" in val || "dataId" in val);
    } catch (e) {
        return false;
    }
}