1/* global JSINFO */
2
3/**
4 * DokuWiki DataTables Plugins
5 *
6 * Home      http://dokuwiki.org/template:bootstrap3
7 * Author    Giuseppe Di Terlizzi <giuseppe.diterlizzi@gmail.com>
8 * License   GPL 2 (http://www.gnu.org/licenses/gpl.html)
9 * Copyright (C) 2015-2020, Giuseppe Di Terlizzi
10 */
11jQuery(document).ready(function () {
12
13    const WRAP_TABLES_SELECTOR = '.page div.dt-wrapper table';
14    const ALL_TABLES_SELECTOR = '.page table thead';
15
16    /**
17     * Initialize DataTables on the given table
18     *
19     * @param {jQuery} $target_table
20     * @param {object} dt_config DataTable configuration
21     */
22    function init_datatables($target_table, dt_config) {
23        console.debug(dt_config);
24
25        // adjust header rows if requested
26        let headerRows = dt_config.headerRows;
27        if (headerRows) {
28            const $tbody = jQuery('tbody', $target_table);
29
30            // if table heade ismissing, create it
31            let $thead = jQuery('thead', $target_table);
32            if ($thead.length === 0) {
33                $thead = jQuery('<thead>');
34                $target_table.prepend($thead);
35            }
36
37            // move the first rows from tbody to thead
38            headerRows -= $thead.children().length;
39            while (headerRows > 0) {
40                headerRows--;
41                $thead.append($tbody.children().first());
42            }
43        }
44
45        // initialize, unless there are colspans or rowspans
46        if (
47            jQuery('thead > tr', $target_table).length &&
48            !jQuery('tbody', $target_table).find('[rowspan], [colspan]').length
49        ) {
50            $target_table.attr('width', '100%');
51            $target_table.DataTable(dt_config);
52        }
53    }
54
55    // MAIN
56
57    // check if plugin is configured
58    if (!('plugin' in JSINFO) || !('datatables' in JSINFO.plugin)) return;
59
60    // initialize on all tables, unless they have our wrapper (using default config)
61    if (JSINFO.plugin.datatables.enableForAllTables) {
62        jQuery(ALL_TABLES_SELECTOR).each(function () {
63            const $target_table = jQuery(this).parent();
64
65            if (!$target_table.parents('.dt-wrapper').length) {
66                init_datatables($target_table, JSINFO.plugin.datatables.config);
67            }
68        });
69    }
70
71    // initialize on all tables with our wrapper (using default config + wrapper config)
72    const $wrap_tables = jQuery(WRAP_TABLES_SELECTOR);
73    if ($wrap_tables.length) {
74        $wrap_tables.each(function () {
75            const $target_table = jQuery(this);
76            const wrap_config = jQuery(this).parents('.dt-wrapper').data();
77            const dt_config = jQuery.extend(JSINFO.plugin.datatables.config, wrap_config);
78            init_datatables($target_table, dt_config);
79        });
80    }
81});
82