Proyectos de Subversion Moodle

Rev

| 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
 * Allow the user to search for groups.
18
 *
19
 * @module    core_group/comboboxsearch/group
20
 * @copyright 2023 Mathew May <mathew.solutions>
21
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 */
23
import search_combobox from 'core/comboboxsearch/search_combobox';
24
import {groupFetch} from 'core_group/comboboxsearch/repository';
25
import {renderForPromise, replaceNodeContents} from 'core/templates';
26
import {debounce} from 'core/utils';
27
import Notification from 'core/notification';
28
 
29
export default class GroupSearch extends search_combobox {
30
 
31
    courseID;
32
    bannedFilterFields = ['id', 'link', 'groupimageurl'];
33
 
34
    constructor() {
35
        super();
36
        this.selectors = {...this.selectors,
37
            courseid: '[data-region="courseid"]',
38
            placeholder: '.groupsearchdropdown [data-region="searchplaceholder"]',
39
        };
40
        const component = document.querySelector(this.componentSelector());
41
        this.courseID = component.querySelector(this.selectors.courseid).dataset.courseid;
42
        // Override the instance since the body is built outside the constructor for the combobox.
43
        this.instance = component.querySelector(this.selectors.instance).dataset.instance;
44
 
45
        const searchValueElement = this.component.querySelector(`#${this.searchInput.dataset.inputElement}`);
46
        searchValueElement.addEventListener('change', () => {
47
            this.toggleDropdown(); // Otherwise the dropdown stays open when user choose an option using keyboard.
48
 
49
            const valueElement = this.component.querySelector(`#${this.combobox.dataset.inputElement}`);
50
            if (valueElement.value !== searchValueElement.value) {
51
                valueElement.value = searchValueElement.value;
52
                valueElement.dispatchEvent(new Event('change', {bubbles: true}));
53
            }
54
 
55
            searchValueElement.value = '';
56
        });
57
 
58
        this.$component.on('hide.bs.dropdown', () => {
59
            this.searchInput.removeAttribute('aria-activedescendant');
60
 
61
            const listbox = document.querySelector(`#${this.searchInput.getAttribute('aria-controls')}[role="listbox"]`);
62
            listbox.querySelectorAll('.active[role="option"]').forEach(option => {
63
                option.classList.remove('active');
64
            });
65
            listbox.scrollTop = 0;
66
 
67
            // Use setTimeout to make sure the following code is executed after the click event is handled.
68
            setTimeout(() => {
69
                if (this.searchInput.value !== '') {
70
                    this.searchInput.value = '';
71
                    this.searchInput.dispatchEvent(new Event('input', {bubbles: true}));
72
                }
73
            });
74
        });
75
 
76
        this.renderDefault().catch(Notification.exception);
77
    }
78
 
79
    static init() {
80
        return new GroupSearch();
81
    }
82
 
83
    /**
84
     * The overall div that contains the searching widget.
85
     *
86
     * @returns {string}
87
     */
88
    componentSelector() {
89
        return '.group-search';
90
    }
91
 
92
    /**
93
     * The dropdown div that contains the searching widget result space.
94
     *
95
     * @returns {string}
96
     */
97
    dropdownSelector() {
98
        return '.groupsearchdropdown';
99
    }
100
 
101
    /**
102
     * Build the content then replace the node.
103
     */
104
    async renderDropdown() {
105
        const {html, js} = await renderForPromise('core_group/comboboxsearch/resultset', {
106
            groups: this.getMatchedResults(),
107
            hasresults: this.getMatchedResults().length > 0,
108
            instance: this.instance,
109
            searchterm: this.getSearchTerm(),
110
        });
111
        replaceNodeContents(this.selectors.placeholder, html, js);
112
        // Remove aria-activedescendant when the available options change.
113
        this.searchInput.removeAttribute('aria-activedescendant');
114
    }
115
 
116
    /**
117
     * Build the content then replace the node by default we want our form to exist.
118
     */
119
    async renderDefault() {
120
        this.setMatchedResults(await this.filterDataset(await this.getDataset()));
121
        this.filterMatchDataset();
122
 
123
        await this.renderDropdown();
124
 
125
        this.updateNodes();
126
    }
127
 
128
    /**
129
     * Get the data we will be searching against in this component.
130
     *
131
     * @returns {Promise<*>}
132
     */
133
    async fetchDataset() {
134
        return await groupFetch(this.courseID).then((r) => r.groups);
135
    }
136
 
137
    /**
138
     * Dictate to the search component how and what we want to match upon.
139
     *
140
     * @param {Array} filterableData
141
     * @returns {Array} The users that match the given criteria.
142
     */
143
    async filterDataset(filterableData) {
144
        // Sometimes we just want to show everything.
145
        if (this.getPreppedSearchTerm() === '') {
146
            return filterableData;
147
        }
148
        return filterableData.filter((group) => Object.keys(group).some((key) => {
149
            if (group[key] === "" || this.bannedFilterFields.includes(key)) {
150
                return false;
151
            }
152
            return group[key].toString().toLowerCase().includes(this.getPreppedSearchTerm());
153
        }));
154
    }
155
 
156
    /**
157
     * Given we have a subset of the dataset, set the field that we matched upon to inform the end user.
158
     */
159
    filterMatchDataset() {
160
        this.setMatchedResults(
161
            this.getMatchedResults().map((group) => {
162
                return {
163
                    id: group.id,
164
                    name: group.name,
165
                    groupimageurl: group.groupimageurl,
166
                };
167
            })
168
        );
169
    }
170
 
171
    /**
172
     * The handler for when a user interacts with the component.
173
     *
174
     * @param {MouseEvent} e The triggering event that we are working with.
175
     */
176
    async clickHandler(e) {
177
        if (e.target.closest(this.selectors.clearSearch)) {
178
            e.stopPropagation();
179
            // Clear the entered search query in the search bar.
180
            this.searchInput.value = '';
181
            this.setSearchTerms(this.searchInput.value);
182
            this.searchInput.focus();
183
            this.clearSearchButton.classList.add('d-none');
184
            // Display results.
185
            await this.filterrenderpipe();
186
        }
187
    }
188
 
189
    /**
190
     * The handler for when a user changes the value of the component (selects an option from the dropdown).
191
     *
192
     * @param {Event} e The change event.
193
     */
194
    changeHandler(e) {
195
        window.location = this.selectOneLink(e.target.value);
196
    }
197
 
198
    /**
199
     * Override the input event listener for the text input area.
200
     */
201
    registerInputHandlers() {
202
        // Register & handle the text input.
203
        this.searchInput.addEventListener('input', debounce(async() => {
204
            this.setSearchTerms(this.searchInput.value);
205
            // We can also require a set amount of input before search.
206
            if (this.getSearchTerm() === '') {
207
                // Hide the "clear" search button in the search bar.
208
                this.clearSearchButton.classList.add('d-none');
209
            } else {
210
                // Display the "clear" search button in the search bar.
211
                this.clearSearchButton.classList.remove('d-none');
212
            }
213
            // User has given something for us to filter against.
214
            await this.filterrenderpipe();
215
        }, 300));
216
    }
217
 
218
    /**
219
     * Build up the view all link that is dedicated to a particular result.
220
     * We will call this function when a user interacts with the combobox to redirect them to show their results in the page.
221
     *
222
     * @param {Number} groupID The ID of the group selected.
223
     */
224
    selectOneLink(groupID) {
225
        throw new Error(`selectOneLink(${groupID}) must be implemented in ${this.constructor.name}`);
226
    }
227
}