Proyectos de Subversion Moodle

Rev

Ir a la última revisión | | 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 learners.
18
 *
19
 * @module    core_user/comboboxsearch/user
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 {getStrings} from 'core/str';
25
import {renderForPromise, replaceNodeContents} from 'core/templates';
26
import $ from 'jquery';
27
 
28
export default class UserSearch extends search_combobox {
29
 
30
    courseID;
31
    groupID;
32
 
33
    // A map of user profile field names that is human-readable.
34
    profilestringmap = null;
35
 
36
    constructor() {
37
        super();
38
        // Register a couple of events onto the document since we need to check if they are moving off the component.
39
        ['click', 'focus'].forEach(eventType => {
40
            // Since we are handling dropdowns manually, ensure we can close it when moving off.
41
            document.addEventListener(eventType, e => {
42
                if (this.searchDropdown.classList.contains('show') && !this.combobox.contains(e.target)) {
43
                    this.toggleDropdown();
44
                }
45
            }, true);
46
        });
47
 
48
        // Register keyboard events.
49
        this.component.addEventListener('keydown', this.keyHandler.bind(this));
50
 
51
        // Define our standard lookups.
52
        this.selectors = {...this.selectors,
53
            courseid: '[data-region="courseid"]',
54
            groupid: '[data-region="groupid"]',
55
            resetPageButton: '[data-action="resetpage"]',
56
        };
57
 
58
        this.courseID = this.component.querySelector(this.selectors.courseid).dataset.courseid;
59
        this.groupID = document.querySelector(this.selectors.groupid)?.dataset?.groupid;
60
        this.instance = this.component.querySelector(this.selectors.instance).dataset.instance;
61
 
62
        // We need to render some content by default for ARIA purposes.
63
        this.renderDefault();
64
    }
65
 
66
    static init() {
67
        return new UserSearch();
68
    }
69
 
70
    /**
71
     * The overall div that contains the searching widget.
72
     *
73
     * @returns {string}
74
     */
75
    componentSelector() {
76
        return '.user-search';
77
    }
78
 
79
    /**
80
     * The dropdown div that contains the searching widget result space.
81
     *
82
     * @returns {string}
83
     */
84
    dropdownSelector() {
85
        return '.usersearchdropdown';
86
    }
87
 
88
    /**
89
     * Build the content then replace the node.
90
     */
91
    async renderDropdown() {
92
        const {html, js} = await renderForPromise('core_user/comboboxsearch/resultset', {
93
            users: this.getMatchedResults().slice(0, 5),
94
            hasresults: this.getMatchedResults().length > 0,
95
            instance: this.instance,
96
            matches: this.getMatchedResults().length,
97
            searchterm: this.getSearchTerm(),
98
            selectall: this.selectAllResultsLink(),
99
        });
100
        replaceNodeContents(this.getHTMLElements().searchDropdown, html, js);
101
        // Remove aria-activedescendant when the available options change.
102
        this.searchInput.removeAttribute('aria-activedescendant');
103
    }
104
 
105
    /**
106
     * Build the content then replace the node by default we want our form to exist.
107
     */
108
    async renderDefault() {
109
        this.setMatchedResults(await this.filterDataset(await this.getDataset()));
110
        this.filterMatchDataset();
111
 
112
        await this.renderDropdown();
113
    }
114
 
115
    /**
116
     * Get the data we will be searching against in this component.
117
     *
118
     * @returns {Promise<*>}
119
     */
120
    fetchDataset() {
121
        throw new Error(`fetchDataset() must be implemented in ${this.constructor.name}`);
122
    }
123
 
124
    /**
125
     * Dictate to the search component how and what we want to match upon.
126
     *
127
     * @param {Array} filterableData
128
     * @returns {Array} The users that match the given criteria.
129
     */
130
    async filterDataset(filterableData) {
131
        if (this.getPreppedSearchTerm()) {
132
            const stringMap = await this.getStringMap();
133
            return filterableData.filter((user) => Object.keys(user).some((key) => {
134
                if (user[key] === "" || user[key] === null || !stringMap.get(key)) {
135
                    return false;
136
                }
137
                return user[key].toString().toLowerCase().includes(this.getPreppedSearchTerm());
138
            }));
139
        } else {
140
            return [];
141
        }
142
    }
143
 
144
    /**
145
     * Given we have a subset of the dataset, set the field that we matched upon to inform the end user.
146
     *
147
     * @returns {Array} The results with the matched fields inserted.
148
     */
149
    async filterMatchDataset() {
150
        const stringMap = await this.getStringMap();
151
        this.setMatchedResults(
152
            this.getMatchedResults().map((user) => {
153
                for (const [key, value] of Object.entries(user)) {
154
                    // Sometimes users have null values in their profile fields.
155
                    if (value === null) {
156
                        continue;
157
                    }
158
 
159
                    const valueString = value.toString().toLowerCase();
160
                    const preppedSearchTerm = this.getPreppedSearchTerm();
161
                    const searchTerm = this.getSearchTerm();
162
 
163
                    // Ensure we match only on expected keys.
164
                    const matchingFieldName = stringMap.get(key);
165
                    if (matchingFieldName && valueString.includes(preppedSearchTerm)) {
166
                        user.matchingFieldName = matchingFieldName;
167
 
168
                        // Safely prepare our matching results.
169
                        const escapedValueString = valueString.replace(/</g, '&lt;');
170
                        const escapedMatchingField = escapedValueString.replace(
171
                            preppedSearchTerm.replace(/</g, '&lt;'),
172
                            `<span class="font-weight-bold">${searchTerm.replace(/</g, '&lt;')}</span>`
173
                        );
174
 
175
                        user.matchingField = `${escapedMatchingField} (${user.email})`;
176
                        break;
177
                    }
178
                }
179
                return user;
180
            })
181
        );
182
    }
183
 
184
    /**
185
     * The handler for when a user changes the value of the component (selects an option from the dropdown).
186
     *
187
     * @param {Event} e The change event.
188
     */
189
    changeHandler(e) {
190
        this.toggleDropdown(); // Otherwise the dropdown stays open when user choose an option using keyboard.
191
 
192
        if (e.target.value === '0') {
193
            window.location = this.selectAllResultsLink();
194
        } else {
195
            window.location = this.selectOneLink(e.target.value);
196
        }
197
    }
198
 
199
    /**
200
     * The handler for when a user presses a key within the component.
201
     *
202
     * @param {KeyboardEvent} e The triggering event that we are working with.
203
     */
204
    keyHandler(e) {
205
        // Switch the key presses to handle keyboard nav.
206
        switch (e.key) {
207
            case 'ArrowUp':
208
            case 'ArrowDown':
209
                if (
210
                    this.getSearchTerm() !== ''
211
                    && !this.searchDropdown.classList.contains('show')
212
                    && e.target.contains(this.combobox)
213
                ) {
214
                    this.renderAndShow();
215
                }
216
                break;
217
            case 'Enter':
218
            case ' ':
219
                if (e.target.closest(this.selectors.resetPageButton)) {
220
                    e.stopPropagation();
221
                    window.location = e.target.closest(this.selectors.resetPageButton).href;
222
                    break;
223
                }
224
                break;
225
            case 'Escape':
226
                this.toggleDropdown();
227
                this.searchInput.focus({preventScroll: true});
228
                break;
229
        }
230
    }
231
 
232
    /**
233
     * When called, hide or show the users dropdown.
234
     *
235
     * @param {Boolean} on Flag to toggle hiding or showing values.
236
     */
237
    toggleDropdown(on = false) {
238
        if (on) {
239
            this.searchDropdown.classList.add('show');
240
            $(this.searchDropdown).show();
241
            this.getHTMLElements().searchInput.setAttribute('aria-expanded', 'true');
242
            this.searchInput.focus({preventScroll: true});
243
        } else {
244
            this.searchDropdown.classList.remove('show');
245
            $(this.searchDropdown).hide();
246
 
247
            // As we are manually handling the dropdown, we need to do some housekeeping manually.
248
            this.getHTMLElements().searchInput.setAttribute('aria-expanded', 'false');
249
            this.searchInput.removeAttribute('aria-activedescendant');
250
            this.searchDropdown.querySelectorAll('.active[role="option"]').forEach(option => {
251
                option.classList.remove('active');
252
            });
253
        }
254
    }
255
 
256
    /**
257
     * Build up the view all link.
258
     */
259
    selectAllResultsLink() {
260
        throw new Error(`selectAllResultsLink() must be implemented in ${this.constructor.name}`);
261
    }
262
 
263
    /**
264
     * Build up the view all link that is dedicated to a particular result.
265
     * We will call this function when a user interacts with the combobox to redirect them to show their results in the page.
266
     *
267
     * @param {Number} userID The ID of the user selected.
268
     */
269
    selectOneLink(userID) {
270
        throw new Error(`selectOneLink(${userID}) must be implemented in ${this.constructor.name}`);
271
    }
272
 
273
    /**
274
     * Given the set of profile fields we can possibly search, fetch their strings,
275
     * so we can report to screen readers the field that matched.
276
     *
277
     * @returns {Promise<void>}
278
     */
279
    getStringMap() {
280
        if (!this.profilestringmap) {
281
            const requiredStrings = [
282
                'username',
283
                'fullname',
284
                'firstname',
285
                'lastname',
286
                'email',
287
                'city',
288
                'country',
289
                'department',
290
                'institution',
291
                'idnumber',
292
                'phone1',
293
                'phone2',
294
            ];
295
            this.profilestringmap = getStrings(requiredStrings.map((key) => ({key})))
296
                .then((stringArray) => new Map(
297
                    requiredStrings.map((key, index) => ([key, stringArray[index]]))
298
                ));
299
        }
300
        return this.profilestringmap;
301
    }
302
}