aboutsummaryrefslogtreecommitdiff
path: root/resources/assets/javascripts/lib/search.js
blob: 5d39f4371d2e098e907af154ae54d8379d50f89f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
var cache = null;

const Search = {
    lastSearch: null,
    lastSearchFilter: null,
    resultsInCategory: false,
    searchTermLength: 3,

    getCache: function () {
        if (cache === null) {
            let prefix = '';
            if ($('meta[name="studip-cache-prefix"]').length > 0) {
                prefix = $('meta[name="studip-cache-prefix"]').attr('content');
            }
            cache = STUDIP.Cache.getInstance(prefix);
        }
        return cache;
    },

    /**
     * This function starts the actual search via AJAX call.
     *
     * @param {Object} filter object with filter information (e.g. 'category', 'semester', etc.)
     *               that is set by the filter selects in the sidebar.
     */
    doSearch: function (filter) {

        var cache        = STUDIP.Search.getCache();
        var searchterm   = $('#search-input').val().trim() || cache.get('searchterm');
        var hasValue     = searchterm && searchterm.length >= STUDIP.Search.searchTermLength;
        var resultsDiv   = $('#search-results');
        var wrapper      = $('#search');
        const data       = resultsDiv.data();
        const limit      = 100;

        if (searchterm === '') {
            return;
        }

        if (!hasValue) {
            $('#search-term-invalid .searchtermlen').text(STUDIP.Search.searchTermLength);
            $('#search-term-invalid').show();
        } else {
            $('#search-term-invalid').hide();
        }

        if (!hasValue || STUDIP.Search.lastSearch === searchterm
            && JSON.stringify(STUDIP.Search.lastSearchFilter) === JSON.stringify(filter)) {
            return;
        }

        STUDIP.Search.resultsInCategory = false;

        $('#search-no-result').hide();
        $('#reset-search').show();

        STUDIP.Search.resetSearchCategories();
        STUDIP.Search.greyOutSearchCategories();

        cache.set('searchterm', searchterm);
        STUDIP.Search.lastSearch = searchterm;
        STUDIP.Search.lastSearchFilter = filter;

        // Display spinner symbol, user should always see something is happening.
        wrapper.addClass('is-searching');

        // Call AJAX endpoint and get search results.
        $.getJSON(STUDIP.URLHelper.getURL('dispatch.php/globalsearch/find/' + limit), {
            search: searchterm,
            filters: JSON.stringify(filter)
        }).done(function (json) {
            // Trigger searched event (regardless of successful or not)
            $(document).trigger('searched.studip', {
                needle: searchterm,
                category: STUDIP.Search.getActiveCategory()
            });

            resultsDiv.empty();

            // No results found...
            if (!$.isPlainObject(json) || $.isEmptyObject(json)) {
                wrapper.removeClass('is-searching');
                $('#search-no-result .searchterm').text(searchterm);
                $('#search-no-result').show();
                STUDIP.Search.setActiveCategory('show_all_categories');
                return;
            }

            // Iterate over each result category.
            $.each(json, function (name, value) {
                var category = STUDIP.Search.printCategory(name, value, data);
                resultsDiv.append(category);
            });

            if (STUDIP.Search.getActiveCategory()
                && STUDIP.Search.getActiveCategory() !== 'show_all_categories')
            {
                STUDIP.Search.expandCategory(STUDIP.Search.getActiveCategory());
                if (!STUDIP.Search.resultsInCategory) {
                    $('#search-no-result .searchterm').text(searchterm);
                    $('#search-no-result').show();
                }
            }

            wrapper.removeClass('is-searching');
        }).fail(function (xhr, status, error) {
            if (error) {
                window.alert(error);
            }
        });
    },

    printCategory: function (name, value, data) {
        // Create an <article> for category.
        var allResultsText  = data.allResults;
        var category = $(`<article id="search-${name}" class="studip padding-less">`);
        var header = $('<header>').appendTo(category);
        var categoryBodyDiv = $(`<div id="${name}-body">`).appendTo(category);
        var counter = 0;
        var isActive = STUDIP.Search.getActiveCategory() === name;

        if (isActive) {
            STUDIP.Search.resultsInCategory = true;
        }

        // Create header name
        $(`<h1 class="search-category" data-category="${name}">`)
            .append(`<a href="#">${value.name}</a>`)
            .appendTo(header);

        if (value.more) {
            $(`<div id="show-all-categories-${name}" class="search-more-results">`)
                .append(`<a href="#">${allResultsText}</a>`)
                .toggle(isActive)
                .appendTo(header);
        }

        // Process results and create corresponding entries.
        $.each(value.content, function (index, result) {
            STUDIP.Search.printSingleResult(name, data, result, counter, value.fullsearch, categoryBodyDiv);
            counter += 1;
        });

        $(`a#search_category_${name}`)
            .removeClass('no-result')
            .text(`${value.name}  (${counter}${value.plus ? '+' : ''})`)
            .attr('tabindex', '0');

        // We have more search results than shown, provide link to
        // full search if available.
        if (value.more) {
            var footer = $('<footer class="search-more-results">');
            $(`<a id="link_all_results_${name}" href="#">`).text(`alle ${counter} ${value.name} anzeigen`)
                .click(function() {
                    STUDIP.Search.toggleLinkText(name);
                    STUDIP.Search.expandCategory(name);
                    STUDIP.Search.setActiveCategory(name);
                })
                .toggle(!isActive)
                .appendTo(footer);
            $(`<a id="link_results_${name}" href="#">`).text(allResultsText).hide()
                .click(function() {
                    STUDIP.Search.toggleLinkText(name);
                    STUDIP.Search.showAllCategories(name);
                    STUDIP.Search.setActiveCategory(name);
                })
                .toggle(isActive)
                .appendTo(footer);
            footer.appendTo(category);
        }

        return category;
    },

    printSingleResult: function(
        categoryName,
        { resultsPerType, imgAdd, imgRemove },
        result,
        counter,
        fullsearch,
        categoryBodyDiv
    ) {
        var hasSubcourses   = (categoryName === 'GlobalSearchMyCourses' || categoryName === 'GlobalSearchCourses') && result.has_children;

        // Create single result entry.
        var single          = $('<section>');
        var data            = $('<div class="search-result-data">');
        var details         = $('<div class="search-result-details">');
        var information     = $('<div class="search-result-information">');

        if (counter >= resultsPerType) {
            single.addClass('search-extended-result');
        }
        // Which result types should be opened via dialog?
        const openInDialog = ['GlobalSearchFiles', 'GlobalSearchMessages'];
        var dataDialog = (openInDialog.indexOf(categoryName) >= 0 ? dataDialog = 'data-dialog' : dataDialog = '');
        var link = $(`<a href="${result.url}" ${dataDialog}>`)
            .appendTo(single);

        // Optional image...
        if (result.img !== null) {
            $('<div class="search-result-img hidden-tiny-down">')
                .append(`<img src="${result.img}">`)
                .appendTo(link);
        }

        link.append(data);

        // add/remove icon for courses with sub courses
        if (hasSubcourses) {
            // initially show the 'add' icon
            $(`<a href="#" id="show-subcourses-${result.id}" class="search-has-subcourses">`)
                .click(function(e) {
                    STUDIP.Search.showSubcourses(result.id);
                    e.preventDefault();
                })
                .html(imgAdd)
                .appendTo(data);
            // initially hide the 'remove' icon
            $(`<a href="#" id="hide-subcourses-${result.id}" class="search-has-subcourses">`)
                .click(function(e) {
                    STUDIP.Search.hideSubcourses(result.id);
                    e.preventDefault();
                })
                .html(imgRemove)
                .appendTo(data)
                .hide();
        }

        // Name/title
        $('<div class="search-result-title">')
            .html(result.name)
            .appendTo(data);

        if (result.number !== null) {
            $('<div class="search-result-number">')
                .html(result.number)
                .appendTo(details);
        }

        // Details: Descriptional text
        if (result.description !== null) {
            $('<div class="search-result-description">')
                .html(result.description)
                .appendTo(details);
        }

        if (result.dates !== null) {
            $('<div class="search-result-dates">')
                .html(result.dates)
                .appendTo(details);
        }

        data.append(details);

        // Date/Time of entry
        if (result.date !== null) {
            $('<div class="search-result-time">')
                .html(result.date)
                .appendTo(information);
        }

        // Course Admission State as Img
        if (result.admission_state !== null) {
            $('<div class="search-result-admission-state">')
                .html(result.admission_state)
                .appendTo(information);
        }


        // Details: Additional information
        var additional = $('<div class="search-result-additional">');
        if (result.additional !== null) {
            additional.html(result.additional);

            // "Expand" attribute for further, result-related search
            // (e.g. search in course of found forum entry)
            if (result.expand !== null && result.expand !== fullsearch) {
                additional.wrapInner(`<a href="${result.expand}" title="${result.expandtext}">`);
            }
            additional.appendTo(information);
        }

        link.append(information);

        categoryBodyDiv.append(single);

        if (hasSubcourses) {
            $.each(result.children,  function(key, child) {
                var subcourse = STUDIP.Search.printSingleResult(name, data, child, counter, fullsearch, categoryBodyDiv);
                subcourse.addClass('search-is-subcourse');
                subcourse.addClass(`search-subcourse-${result.id}`);
                subcourse.hide();
            });
        }

        return single;
    },

    /**
     * Clear search term and category from the cache,
     * reload the page and reset the active category.
     */
    resetSearch: function () {
        var cache = STUDIP.Search.getCache();
        STUDIP.Search.lastSearch = null;
        cache.remove('searchterm');
        cache.remove('search_category');
        // reload without parameters
        if (location.href.includes('?')) {
            location = location.href.split('?')[0];
        } else {
            location.reload();
        }
        STUDIP.Search.setActiveCategory('show_all_categories');
    },

    /**
     * Show all possible categories in the sidebar without result numbers.
     */
    resetSearchCategories: function () {
        $('a[id^="search_category_"]').each(function () {
            var category = $(this).text();
            if (category.includes('(')) {
                category = category.substr(0, category.indexOf('(') - 1);
                $(this).text(category);
            }
        }).show();
    },

    /**
     * Grey out all categories in the sidebar with no results.
     */
    greyOutSearchCategories: function () {
        $('a[id^="search_category_"]').addClass('no-result').attr('tabindex', '-1');
    },

    /**
     * Hide all select filters in the sidebar.
     */
    hideAllFilters: function () {
        $('div[id$="_filter"]').hide();
    },

    /**
     * Show the select filters for a given category in the sidebar. Default: semester filter.
     *
     * @param {string} category Given category for which specific select filters should be shown.
     */
    showFilter: function (category) {
        var filters = $('#search-results').data('filters');
        STUDIP.Search.hideAllFilters();
        if (filters && filters[category] !== undefined && category != 'show_all_categories') {
            for (let i = 0; i < filters[category].length; i++) {
                $(`#${filters[category][i]}_filter`).show();
            }
        } else if (category === 'show_all_categories') {
            $('#semester_filter').show();
        }
    },

    /**
     * Set the specified category active (highlighted) in the sidebar.
     * <li class="active">
     *
     * @param {string} category Given category which should be highlighted in the sidebar.
     */
    setActiveCategory: function (category) {
        var cache = STUDIP.Search.getCache();
        cache.set('search_category', category);
        // remove all active classes
        $('#show_all_categories').closest('li').removeClass('active');
        $('a[id^="search_category_"]').closest('li').removeClass('active');

        // set clicked class active
        if (category === 'show_all_categories') {
            $('#show_all_categories').closest('li').addClass('active');
        } else {
            $(`#search_category_${category}`).closest('li').addClass('active');
            $(`#search_category_${category}`).attr('tabindex', '0');
        }
        STUDIP.Search.showFilter(category);

        $(document).trigger('search-category-change.studip', {category: category});
    },

    /**
     * Get the current values from the filter selects in the sidebar that are relevant.
     *
     * @return {Object} filter object with the filter values set by the user.
     */
    getFilter: function () {
        var filters = $('#search-results').data('filters');
        var category = STUDIP.Search.getActiveCategory();
        var filter = {category: category};
        if (filters !== undefined) {
            var active_filters = filters[category];
            $('select[id$="_select"]').each(function () {
                var selected = this.id.substr(0, this.id.lastIndexOf('_'));
                if ($.inArray(selected, active_filters) !== -1) {
                    filter[selected] = $('option:selected', this).val();
                }
            });
        }
        return filter;
    },

    /**
     * Set a specific sidebar filter select to the given value.
     *
     * @param {string} filter filter that should be set.
     * @param {string} value value that the filter should be set to.
     */
    setFilter: function (filter, value) {
        $(`#${filter}_select`).val(value);
    },

    /**
     * Reset all sidebar filters except for the semester filter to their default value ('all').
     */
    resetFilters: function () {
        $('select[id$="_select"]').not('#semester_select').val('').change();
    },

    /**
     * Getter for the selected (active) category.
     *
     * @return {string} The active (currently selected) category in the sidebar widget.
     */
    getActiveCategory: function () {
        var cache = STUDIP.Search.getCache();
        return cache.get('search_category');
    },

    /**
     * Toggle the link text for 'show all' results of one category and 'show all categories'
     * with max. 3 results each.
     *
     * @param {string} category Category for which the link text should be toggled
     */
    toggleLinkText: function (category) {
        var visible = $(`a#link_all_results_${category}`).is(':visible');
        $(`a#link_all_results_${category}`).toggle(!visible);
        $(`a#link_results_${category}`).toggle(visible);
        $(`div#show-all-categories-${category}`).toggle(visible);
    },

    /**
     * When clicked on toggle the icon ('+' -> '-' and vice versa)
     * belonging to a parent course which has sub courses.
     *
     * @param {string} id parent course ID with add/remove Icon
     */
    toggleParentCourseIcon: function (id) {
        var visible = $(`a#show-subcourses-${id}`).is(':visible');
        $(`a#show-subcourses-${id}`).toggle(!visible);
        $(`a#hide-subcourses-${id}`).toggle(visible);
    },

    /**
     * Shows all sub courses for a specific parent course.
     *
     * @param {string} id parent course ID with sub courses
     */
    showSubcourses: function (id) {
        STUDIP.Search.toggleParentCourseIcon(id);
        $(`section.search-subcourse-${id}`).show();
    },

    /**
     * Hides all sub courses for a specific parent course.
     *
     * @param {string} id parent course ID with sub courses
     */
    hideSubcourses: function (id) {
        STUDIP.Search.toggleParentCourseIcon(id);
        $(`section.search-subcourse-${id}`).hide();
    },

    /**
     * Expand a single category, showing more results, and hide other categories.
     *
     * @param {string} category Category that should be expanded.
     * @returns {boolean} false
     */
    expandCategory: function (category) {
        // Hide other categories.
        $(`#search-results article:not([id="search-${category}"])`).hide();
        $('#search-no-result').hide();
        // Show all results.
        $(`#search-${category} section.search-extended-result`)
            .removeClass('search-extended-result');
        // Reassign category click to closing extended view.
        var selector = [
            `#search-results article#search-${category} header a`,
            `#link_all_results_${category}`,
            `#link_results_${category}`,
            `#show-all-categories-${category}`
        ].join(',');
        $(selector).off('click').on('click', function () {
            STUDIP.Search.toggleLinkText(category);
            STUDIP.Search.showAllCategories(category);
            return false;
        });
        return false;
    },

    /**
     * Close expanded view of a single category, showing normal view with
     * all categories again.
     *
     * @param {string} currentCategory Category that was previously selected.
     * @return {boolean} false
     */
    showAllCategories: function (currentCategory) {
        var selector = [
            `#search-results article#search-${currentCategory} header a`,
            `#link_all_results_${currentCategory}`,
            `#link_results_${currentCategory}`
        ].join(',');
        $(selector).off('click').on('click', function () {
            STUDIP.Search.toggleLinkText(currentCategory);
            STUDIP.Search.expandCategory(currentCategory);
            STUDIP.Search.setActiveCategory(currentCategory);
            return false;
        });
        var resultCount = $('#search-results').data('results-per-type') - 1;
        $(`#search-${currentCategory} section:gt(${resultCount})`)
            .addClass('search-extended-result');
        $('#search-results').children(`article:not([id="search-${currentCategory}"])`).show();
        STUDIP.Search.setActiveCategory('show_all_categories');
        $('#search-no-result').hide();
        return false;
    },

    /**
     * Show active filters based on active category
     *
     * @param {Object} filter object with filter information (e.g. 'category', 'semester', etc.)
     * @return {boolean} false
     */
    showActiveFilters: function (filter) {
        var container = $('#search-active-filters').find('.filter-items');
        container.empty();
        var emptyFilter = true;
        for ( var item in filter) {
            if (item != 'category') {
                var value = filter[item];
                if (value.trim()) {
                    var name = $(`#${item}_filter .sidebar-widget-header`).text().trim();
                    var value_text = $(`#${item}_select option:selected`).text().trim();
                    var filterItem = $('<button></button>').addClass('button remove-filter').text(name + ': ' + value_text).attr('data-filter-name', item);
                    filterItem.on('click', function () {
                        var filter_name = $(this).data('filter-name');
                        $(`#${filter_name}_select`).val("");
                        $(`#${filter_name}_select`).trigger('change');
                        return false;
                    });
                    container.append(filterItem);
                    emptyFilter = false;
                }
            }
        }
        if (emptyFilter) {
            $('#search-active-filters').hide();
        } else {
            $('#search-active-filters').show();
        }
        return false;
    }
};

export default Search;