PageSourceSearch

https://northstar.mv/assets/js/customClasses.js

js northstar.mv collected 2026-09-24 11:07:53 UTC 20,247 bytes, 538 lines download raw bytes

1/**
2 * @Author
3 *  R.M. Kavindu Nimesh
4 * @version
5 *  V1.0.0
6 * @Contents
7 *  [1] => httpRequest
8 *  [2] => Alert
9 *  [3] => dataTable
10 *  [4] => Pagination
11**/
12
13
14class httpRequest {
15    static async json({ route = "", method = "post", data = {}, baseURL = "" }) {
16        return new Promise(resolve => {
17            $.ajax({
18                url: baseURL + route,
19                method: method,
20                data: data,
21                dataType: "json",
22                contentType: "application/json",
23                success: async function (data) {
24                    resolve(data);
25                    return;
26                },
27                error: function (data) {
28                    resolve({ status: false, message: data.statusText });
29                    return;
30                }
31            });
32        });
33    }
34    static async form({ route = "", method = "post", data = new FormData(), baseURL = "" }) {
35        return new Promise(resolve => {
36            $.ajax({
37                url: baseURL + route,
38                method: method,
39                data: data,
40                processData: false,
41                contentType: false,
42                success: async function (data) {
43                    resolve(data);
44                    return;
45                },
46                error: function (data) {
47                    resolve(data);
48                    return;
49                }
50            });
51        });
52    }
53}
54
55class Alert {
56    static error({ title = "error", timer = 2000, position = 'top-end' }) {
57        Swal.fire({
58            position: position,
59            icon: 'error',
60            title: title,
61            showConfirmButton: false,
62            timer: timer
63        });
64    }
65    static success({ title = "success", timer = 2000, position = 'top-end' }) {
66        Swal.fire({
67            position: position,
68            icon: 'success',
69            title: title,
70            showConfirmButton: false,
71            timer: timer
72        });
73    }
74    static confirmBox({
75        title = 'Are you sure?',
76        text = 'You will not be able to undo this action!',
77        confirmButtonText = 'Yes, do it!',
78        cancelButtonText = 'No, cancel!',
79        confirmButtonColor = '#3085d6',
80        cancelButtonColor = '#d33',
81        icon = 'warning'
82    }) {
83        return new Promise(resolve => {
84            Swal.fire({
85                title: title,
86                text: text,
87                icon: icon,
88                showCancelButton: true,
89                confirmButtonColor: confirmButtonColor,
90                cancelButtonColor: cancelButtonColor,
91                confirmButtonText: confirmButtonText,
92                cancelButtonText: cancelButtonText
93            }).then((result) => {
94                if (result.isConfirmed) {
95                    resolve(true);
96                } else {
97                    resolve(false);
98                }
99            });
100        });
101    }
102}
103
104class dataTable {
105
106    static create({
107        headers = [],
108        dataTableDiv = "dataTable",
109        rowsPerPage = 10
110    }) {
111
112        let ths = headers.map(key => `<th>${key}</th>`).join('');
113
114        let dataTable = `${dataTableDiv}_table`;
115        let searchInputId = `${dataTable}_searchInput`;
116        let currentPageId = `${dataTable}_currentPage`;
117        let prevBtnId = `${dataTable}_prevBtn`;
118        let nextBtnId = `${dataTable}_nextBtn`;
119
120        let input = document.createElement("input");
121        input.type = "hidden";
122        input.id = `${dataTable}_input`;
123        input.value = JSON.stringify([]);
124        document.body.appendChild(input)
125
126
127        document.getElementById(dataTableDiv).innerHTML = `
128            <div class="table-filter">
129                <div class="search-box">
130                    <i class="fa-solid fa-magnifying-glass"></i>
131                    <input class="searchbox" type="text" placeholder="Search..." id="${searchInputId}">
132                </div>
133                <div class="">
134                    <select id="${dataTable}_show_count" onchange="${dataTable}_handleSearch()" class="form-select table-select">
135                        <option value="10">10</option>
136                        <option value="20">20</option>
137                        <option value="50">50</option>
138                        <option value="100">100</option>
139                    </select>
140                </div>
141            </div>
142            <div class="responsive-table">
143                <table class="my-2" id="${dataTable}">
144                    <thead class="table-header">${ths}</thead>
145                    <tbody class="table-body">
146                    </tbody>
147                </table>
148            </div>
149            <div class="table-footer d-flex justify-content-between align-items-center">
150                <div class="pt-3 pb-1 px-3">
151                    <nav aria-label="Page navigation example">
152                        <ul class="pagination">
153                            <li class="page-item"><a class="page-link" href="#dataTable" id="${prevBtnId}">Prev</a></li>
154                            <li class="page-item"><a class="page-link" href="#dataTable" id="${currentPageId}">Page 1</a></li>
155                            <li class="page-item"><a class="page-link" href="#dataTable" id="${nextBtnId}">Next</a></li>
156                        </ul>
157                    </nav>
158                </div>
159                <div class="back-to-top">
160                    <a href="#">
161                        <i class="fa-solid fa-chevron-up"></i>
162                    </a>
163                </div>
164            </div>
165            `;
166
167        let show_counts = [10, 20, 50, 100];
168        if (show_counts.includes(rowsPerPage)) {
169            document.getElementById(`${dataTable}_show_count`).value = rowsPerPage;
170        } else {
171            let option = document.createElement("option");
172            option.value = rowsPerPage;
173            option.innerHTML = rowsPerPage;
174            option.selected = true;
175            document.getElementById(`${dataTable}_show_count`).appendChild(option);
176        }
177
178        let script = `
179            const ${dataTable}_tableBody = document.querySelector("#${dataTable} tbody");
180            const ${dataTable}_prevBtn   = document.querySelector("#${prevBtnId}");
181            const ${dataTable}_nextBtn   = document.querySelector("#${nextBtnId}");
182            const ${dataTable}_currentPageSpan = document.querySelector("#${currentPageId}");
183            const ${dataTable}_searchInput = document.querySelector("#${searchInputId}");
184        
185            let ${dataTable}_currentPage = 1;
186            let ${dataTable}_pageStartIndex = 0;
187            let ${dataTable}_pageEndIndex   = ${rowsPerPage};
188        
189            async function ${dataTable}_rendertableRowData(startIndex, endIndex, filteredtableRowData) {
190        
191                ${dataTable}_tableBody.innerHTML = "";
192            
193                if (filteredtableRowData.length < endIndex ) {
194                    endIndex = filteredtableRowData.length;
195                }
196        
197                for (let i = startIndex; i < endIndex; i++) {
198            
199                    const arr = filteredtableRowData[i];
200                    const row = document.createElement("tr");
201            
202                    const includesValue = Object.values(arr).some(value => {
203                    const nameCell = document.createElement("td");
204                    nameCell.innerHTML = value;
205                    row.appendChild(nameCell);
206                    
207                    });
208            
209                    ${dataTable}_tableBody.appendChild(row);
210                }
211
212            }
213        
214        
215            function ${dataTable}_updatePaginationButtons() {
216                ${dataTable}_prevBtn.disabled = ${dataTable}_currentPage === 1;
217                ${dataTable}_nextBtn.disabled = ${dataTable}_currentPage === Math.ceil(JSON.parse(document.getElementById('${dataTable}_input').value).length / parseInt($(\`#${dataTable}_show_count\`).val()));
218                ${dataTable}_currentPageSpan.textContent = \`Page \${${dataTable}_currentPage}\`;
219            }
220
221        
222            function ${dataTable}_goToPreviousPage() {
223                if (${dataTable}_currentPage > 1) {
224                    ${dataTable}_currentPage--;
225                    ${dataTable}_handleSearch((${dataTable}_currentPage - 1) * parseInt($(\`#${dataTable}_show_count\`).val()), ${dataTable}_currentPage * parseInt($(\`#${dataTable}_show_count\`).val()));
226                    ${dataTable}_updatePaginationButtons();
227                }
228            }
229        
230            function ${dataTable}_goToNextPage() {
231                if (${dataTable}_currentPage < Math.ceil(JSON.parse(document.getElementById('${dataTable}_input').value).length / parseInt($(\`#${dataTable}_show_count\`).val()))) {
232                    ${dataTable}_currentPage++;
233                    ${dataTable}_handleSearch((${dataTable}_currentPage - 1) * parseInt($(\`#${dataTable}_show_count\`).val()), ${dataTable}_currentPage * parseInt($(\`#${dataTable}_show_count\`).val()));
234                    ${dataTable}_updatePaginationButtons();
235                }
236            }
237        
238            function ${dataTable}_filtertableRowData(query) {
239
240                const filteredtableRowData = JSON.parse(document.getElementById('${dataTable}_input').value).filter(function(arr) {
241                    const lowerCaseQuery = query.toLowerCase();
242                    return (
243                        Object.values(arr).some(value => {
244                            if (typeof value === 'string') {
245                                const lowerCaseValue = value.toLowerCase();
246                                return lowerCaseValue.includes(lowerCaseQuery);
247                            }
248                            return false;
249                        })
250                    );
251                });
252            
253                return filteredtableRowData;
254            }
255        
256            function ${dataTable}_handleSearch(startIndex, endIndex) {
257                if (endIndex === undefined) {
258                    endIndex = ${dataTable}_pageStartIndex + parseInt($(\`#${dataTable}_show_count\`).val());
259                    startIndex = ${dataTable}_pageStartIndex;
260                } else {
261                    ${dataTable}_pageEndIndex = endIndex;
262                    ${dataTable}_pageStartIndex = startIndex;
263                }
264                const searchQuery = ${dataTable}_searchInput.value;
265                const filteredtableRowData = ${dataTable}_filtertableRowData(searchQuery);
266                ${dataTable}_rendertableRowData(startIndex, endIndex, filteredtableRowData);
267            }
268        
269            ${dataTable}_prevBtn.addEventListener("click", ${dataTable}_goToPreviousPage);
270            ${dataTable}_nextBtn.addEventListener("click", ${dataTable}_goToNextPage);
271        
272            ${dataTable}_searchInput.addEventListener("input", ${dataTable}_handleSearch);
273            ${dataTable}_handleSearch();
274            ${dataTable}_updatePaginationButtons();`;
275        let scriptTag = document.createElement("script");
276        scriptTag.id = `${dataTable}_script`;
277        scriptTag.innerHTML = script;
278
279        document.body.appendChild(scriptTag);
280    };
281
282    static add(
283        {
284            data = [],
285            dataTableDiv = "dataTable",
286        }) {
287
288        document.getElementById(`${dataTableDiv}_table_input`).value = JSON.stringify(data);
289        let script = document.createElement("script");
290        script.innerHTML = `${dataTableDiv}_table_handleSearch()`;
291        script.id = `${dataTableDiv}_callback`
292        document.body.appendChild(script);
293        document.getElementById(`${dataTableDiv}_callback`).remove();
294    }
295}
296
297class Pagination {
298    static async add({
299        paginationId = "pagination",
300        buttonCount = 3,
301        callback = "tableLoad",
302        displayCount = 10
303    }) {
304        // Pagination buttons inner
305        let buttons = '';
306        let await_to_loop = new Promise(resolve => {
307            for (let i = 0; i < buttonCount; i++) {
308                buttons = buttons + `<li onclick="paginationActive(this,${callback}, '${paginationId}');" class="${paginationId}page-item active"><a class="page-link ${paginationId}pageValNo" href="javascript:void(0)">${i + 1}</a></li>`;
309                if (i === buttonCount - 1) {
310                    resolve(true);
311                    return;
312                }
313            }
314        });
315        await await_to_loop;
316        document.getElementById(paginationId).innerHTML = `
317        <nav aria-label="...">
318            <ul class="pagination justify-content-center justify-content-md-start">
319                <li onclick="pagination(-1, '${paginationId}',${callback}, '${buttonCount}');" class="${paginationId}page-item"><a class="page-link prev"
320                        href="javascript:void(0)">Prev</a></li>
321                ${buttons}
322                <li onclick="pagination(+1, '${paginationId}',${callback}, '${buttonCount}');" class="${paginationId}page-item"><a class="page-link next"
323                        href="javascript:void(0)">Next</a></li>
324            </ul>
325        </nav>`;
326        let countInput = document.createElement(`input`);
327        countInput.type = `hidden`;
328        countInput.id = `${paginationId}_count`;
329        countInput.value = displayCount;
330        document.body.appendChild(countInput);
331
332        let pageFirstNoInput = document.createElement(`input`);
333        pageFirstNoInput.type = `hidden`;
334        pageFirstNoInput.id = `${paginationId}_pageFirstNo`;
335        pageFirstNoInput.value = 1;
336        document.body.appendChild(pageFirstNoInput);
337
338        let pageNoInput = document.createElement(`input`);
339        pageNoInput.type = `hidden`;
340        pageNoInput.id = `${paginationId}_pageNo`;
341        pageNoInput.value = 1;
342        document.body.appendChild(pageNoInput);
343
344        let totalCountInput = document.createElement(`input`);
345        totalCountInput.type = `hidden`;
346        totalCountInput.id = `${paginationId}_totalCount`;
347        totalCountInput.value = 200;
348        document.body.appendChild(totalCountInput);
349
350        let script = document.createElement('script');
351        script.innerHTML = `
352        function paginationActive(element, callback, paginationId) {
353            document.getElementsByClassName(\`\${paginationId}page-item page-link-active\`)[0].classList.remove("page-link-active");
354            document.getElementById(\`\${paginationId}_pageNo\`).value = element.querySelector("a").innerHTML;
355            element.classList.add("page-link-active");
356            callback();
357        }
358
359        function pagination(type, paginationId, callback, buttonCount) {
360
361            if ((parseInt(document.getElementById(\`\${paginationId}_totalCount\`).value) / parseInt(document.getElementById(\`\${paginationId}_count\`).value) <= parseInt(document.getElementById(\`\${paginationId}_pageFirstNo\`).value)) && type == 1) {
362                return;
363            }
364            let a = parseInt(document.getElementById(\`\${paginationId}_pageFirstNo\`).value);
365            if (a + type != 0) {
366                for (let i = 0; i < parseInt(buttonCount); i++) {
367                    document.getElementsByClassName(\`\${paginationId}pageValNo\`)[i].innerHTML = a + type + i;
368                }
369                document.getElementById(\`\${paginationId}_pageFirstNo\`).value = a + type;
370                document.getElementById(\`\${paginationId}_pageNo\`).value = parseInt(document.getElementById(\`\${paginationId}_pageNo\`).value) + type;
371                callback()
372            }
373        }
374        `;
375        document.body.appendChild(script);
376
377    }
378}
379
380async function deleteData(tableId = "", resultId = "", callback) {
381    
382    iziToast.show({
383        theme: 'dark',
384        icon: 'fa-solid fa-trash-can',
385        title: 'Are you sure?',
386        message: 'Do you want to delete this customer?',
387        position: 'center',
388        progressBarColor: 'rgb(0, 255, 184)',
389        buttons: [
390            ['<button>Yes</button>', function (instance, toast) {
391
392                $.ajax({
393                    url: "/api/delete",
394                    method: "delete",
395                    data: JSON.stringify({
396                        tableId: tableId,
397                        resultId: resultId
398                    }),
399                    dataType: "json",
400                    contentType: "application/json",
401                    success: async function (data) {
402                        if ( data.status ) {
403
404                            iziToast.success({
405                                timeout: 5000,
406                                icon: 'fa fa-check',
407                                title: 'Done',
408                                message: data.message,
409                            });
410                            
411                            callback()
412                        } else {
413
414                            iziToast.error({
415                                timeout: 5000,
416                                icon: 'fa fa-ban',
417                                title: 'Error',
418                                message: data.message,
419                            });
420
421                        }
422                    },
423                    error: function (data) {
424
425                        iziToast.error({
426                            timeout: 5000,
427                            icon: 'fa fa-ban',
428                            title: 'Error',
429                            message: data.statusText,
430                        });
431
432                    }
433                });
434
435                iziToast.hide({
436                    transitionOut: 'fadeOutUp'
437                }, toast);
438            }, true],
439            ['<button>No</button>', function (instance, toast) {
440                iziToast.hide({
441                    transitionOut: 'fadeOutUp'
442                }, toast);
443            }]
444        ],
445    });
446}
447
448async function statusChange(tableId = "", resultId = "", status, callback) {
449    $.ajax({
450        url: "/api/status",
451        method: "post",
452        data: JSON.stringify({
453            resultId: resultId,
454            tableId: tableId,
455            status: status
456        }),
457        dataType: "json",
458        contentType: "application/json",
459        success: async function (data) {
460            if ( data.status ) {
461
462                iziToast.success({
463                    timeout: 5000,
464                    icon: 'fa fa-check',
465                    title: 'Done',
466                    message: data.message,
467                });
468
469                callback()
470            } else {
471
472                iziToast.error({
473                    timeout: 5000,
474                    icon: 'fa fa-ban',
475                    title: 'Error',
476                    message: data.message,
477                });
478            }
479        },
480        error: function (data) {
481
482            iziToast.error({
483                timeout: 5000,
484                icon: 'fa fa-ban',
485                title: 'Error',
486                message: data.statusText,
487            });
488        }
489    });
490}
491
492class Form {
493
494    static inputFocus(
495        {
496            form,
497            fields = {},
498            callback = "console.log"
499        }
500    ) {
501        let script = document.createElement("script");
502        script.innerHTML = `$("${form} input").keypress(e => {
503            if (e.which === 13) {
504                e.preventDefault();
505                let fields = ${JSON.stringify(fields)};
506                const target = fields[e.currentTarget.id];
507                if (target != undefined) {
508                    if (target) typeof target === "string" ? $(target).focus() : target(); else ${callback}();
509                }
510                
511            }
512        });`;
513        document.body.appendChild(script);
514    }
515
516    static lock(
517        {
518            button = "submit",
519            waiting = "wait..."
520        }
521    ) {
522        $(button).prop("disabled", true);
523        $(button).attr("data-text", $(button).text());
524        $(button).text(waiting);
525
526    }
527
528    static unlock(
529        {
530            button = "submit"
531        }
532    ) {
533        $(button).prop("disabled", false);
534        $(button).text($(button).attr("data-text"));
535        $(button).removeAttr("data-text");
536    }
537
538}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.