Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/**
17
 * Dynamic Tabs UI element with AJAX loading of tabs content
18
 *
19
 * @module      core/dynamic_tabs
20
 * @copyright   2021 David Matamoros <davidmc@moodle.com> based on code from Marina Glancy
21
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 */
23
 
24
import $ from 'jquery';
25
import Templates from 'core/templates';
26
import {addIconToContainer} from 'core/loadingicon';
27
import Notification from 'core/notification';
1441 ariadna 28
import {prependPageTitle} from 'core/page_title';
1 efrain 29
import Pending from 'core/pending';
1441 ariadna 30
import {getString} from 'core/str';
1 efrain 31
import {getContent} from 'core/local/repository/dynamic_tabs';
32
import {isAnyWatchedFormDirty, resetAllFormDirtyStates} from 'core_form/changechecker';
33
 
34
const SELECTORS = {
35
    dynamicTabs: '.dynamictabs',
36
    activeTab: '.dynamictabs .nav-link.active',
1441 ariadna 37
    allActiveTabs: '.dynamictabs .nav-link[data-bs-toggle="tab"]:not(.disabled)',
1 efrain 38
    tabContent: '.dynamictabs .tab-pane [data-tab-content]',
1441 ariadna 39
    tabToggle: 'a[data-bs-toggle="tab"]',
1 efrain 40
    tabPane: '.dynamictabs .tab-pane',
41
};
42
 
43
SELECTORS.forTabName = tabName => `.dynamictabs [data-tab-content="${tabName}"]`;
1441 ariadna 44
SELECTORS.forTabId = tabName => `.dynamictabs [data-bs-toggle="tab"][href="#${tabName}"]`;
1 efrain 45
 
1441 ariadna 46
let watchedFormDirtyNotification = false;
47
 
1 efrain 48
/**
49
 * Initialises the tabs view on the page (only one tabs view per page is supported)
50
 */
51
export const init = () => {
1441 ariadna 52
    const tabToggles = document.querySelectorAll(SELECTORS.tabToggle);
53
    tabToggles.forEach(tabToggle => {
54
        // Listen to click, warn user if they are navigating away with unsaved form changes.
55
        tabToggle.addEventListener('show.bs.tab', (event) => {
56
            if (isAnyWatchedFormDirty()) {
57
                event.preventDefault();
58
                event.stopPropagation();
1 efrain 59
 
1441 ariadna 60
                // Prevent double execution of event listener.
61
                if (!watchedFormDirtyNotification) {
62
                    watchedFormDirtyNotification = true;
1 efrain 63
 
1441 ariadna 64
                    Notification.saveCancelPromise(
65
                        getString('changesmade'),
66
                        getString('changesmadereallygoaway'),
67
                        getString('confirm'),
68
                        {triggerElement: tabToggle}
69
                    ).then(() => {
70
                        // Reset form dirty state on confirmation, re-trigger the event.
71
                        resetAllFormDirtyStates();
72
                        tabToggle.dispatchEvent(new Event('click', {bubbles: true}));
73
                        return;
74
                    }).catch(() => {
75
                        // User cancelled the dialogue.
76
                    }).finally(() => {
77
                        watchedFormDirtyNotification = false;
78
                    });
79
                }
1 efrain 80
 
1441 ariadna 81
                return;
82
            }
1 efrain 83
 
84
            // Clean content from previous tab.
85
            const previousTabName = getActiveTabName();
86
            if (previousTabName) {
87
                const previousTab = document.querySelector(SELECTORS.forTabName(previousTabName));
88
                previousTab.textContent = '';
89
            }
1441 ariadna 90
        });
91
 
92
        tabToggle.addEventListener('shown.bs.tab', () => {
93
            const tabPane = document.getElementById(tabToggle.getAttribute('href').replace(/^#/, ''));
94
            if (tabPane) {
95
                loadTab(tabPane.id);
1 efrain 96
            }
97
        });
1441 ariadna 98
    });
1 efrain 99
 
100
    if (!openTabFromHash()) {
101
        const tabs = document.querySelector(SELECTORS.allActiveTabs);
102
        if (tabs) {
103
            openTab(tabs.getAttribute('aria-controls'));
104
        } else {
105
            // We may hide tabs if there is only one available, just load the contents of the first tab.
106
            const tabPane = document.querySelector(SELECTORS.tabPane);
107
            if (tabPane) {
108
                tabPane.classList.add('active', 'show');
109
                loadTab(tabPane.getAttribute('id'));
110
            }
111
        }
112
    }
113
};
114
 
115
/**
116
 * Returns id/name of the currently active tab
117
 *
118
 * @return {String|null}
119
 */
120
const getActiveTabName = () => {
121
    const element = document.querySelector(SELECTORS.activeTab);
122
    return element?.getAttribute('aria-controls') || null;
123
};
124
 
125
/**
126
 * Returns the id/name of the first tab
127
 *
128
 * @return {String|null}
129
 */
130
const getFirstTabName = () => {
131
    const element = document.querySelector(SELECTORS.tabContent);
132
    return element?.dataset.tabContent || null;
133
};
134
 
135
/**
136
 * Loads contents of a tab using an AJAX request
137
 *
138
 * @param {String} tabName
139
 */
140
const loadTab = (tabName) => {
141
    // If tabName is not specified find the active tab, or if is not defined, the first available tab.
142
    tabName = tabName ?? getActiveTabName() ?? getFirstTabName();
143
    const tab = document.querySelector(SELECTORS.forTabName(tabName));
144
    if (!tab) {
145
        return;
146
    }
147
 
148
    const pendingPromise = new Pending('core/dynamic_tabs:loadTab:' + tabName);
149
 
1441 ariadna 150
    const tabLabelledBy = document.getElementById(tab.getAttribute('aria-labelledby'));
151
    prependPageTitle(tabLabelledBy.innerText);
152
 
1 efrain 153
    addIconToContainer(tab)
154
    .then(() => {
155
        let tabArgs = {...tab.dataset};
156
        delete tabArgs.tabClass;
157
        delete tabArgs.tabContent;
158
        return getContent(tab.dataset.tabClass, JSON.stringify(tabArgs));
159
    })
160
    .then(response => Promise.all([
161
        $.parseHTML(response.javascript, null, true).map(node => node.innerHTML).join("\n"),
162
        Templates.renderForPromise(response.template, JSON.parse(response.content)),
163
    ]))
164
    .then(([responseJs, {html, js}]) => Templates.replaceNodeContents(tab, html, js + responseJs))
165
    .then(() => pendingPromise.resolve())
166
    .catch(Notification.exception);
167
};
168
 
169
/**
170
 * Return the tab given the tab name
171
 *
172
 * @param {String} tabName
173
 * @return {HTMLElement}
174
 */
175
const getTab = (tabName) => {
176
    return document.querySelector(SELECTORS.forTabId(tabName));
177
};
178
 
179
/**
180
 * Return the tab pane given the tab name
181
 *
182
 * @param {String} tabName
183
 * @return {HTMLElement}
184
 */
185
const getTabPane = (tabName) => {
186
    return document.getElementById(tabName);
187
};
188
 
189
/**
190
 * Open the tab on page load. If this script loads before theme_boost/tab we need to open tab ourselves
191
 *
192
 * @param {String} tabName
193
 * @return {Boolean}
194
 */
195
const openTab = (tabName) => {
196
    const tab = getTab(tabName);
197
    if (!tab) {
198
        return false;
199
    }
200
 
201
    loadTab(tabName);
202
    tab.classList.add('active');
203
    getTabPane(tabName).classList.add('active', 'show');
204
    return true;
205
};
206
 
207
/**
208
 * If there is a location hash that is the same as the tab name - open this tab.
209
 *
210
 * @return {Boolean}
211
 */
212
const openTabFromHash = () => {
213
    const hash = document.location.hash;
214
    if (hash.match(/^#\w+$/g)) {
215
        return openTab(hash.replace(/^#/g, ''));
216
    }
217
 
218
    return false;
219
};