aboutsummaryrefslogtreecommitdiff
path: root/resources/vue/components/responsive/ResponsiveNavigation.vue
blob: 70e46a7311c97e6b910f168ba2d265e69de9c6ae (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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
<template>
    <div role="navigation" ref="container" id="responsive-navigation-container" v-if="menuNeeded">
        <div class="responsive-navigation-header">
            <transition name="slide" appear>
                <button id="responsive-navigation-button" class="styleless"
                        :aria-label="showMenu
                            ? $gettext('Navigation schließen')
                            : $gettext('Navigation öffnen')"
                        @click.prevent="toggleMenu"
                        @keydown.prevent.space="toggleMenu"
                        @keydown.prevent.enter="toggleMenu">
                    <studip-icon shape="hamburger" role="info_alt"
                                 :alt="showMenu ? $gettext('Navigation schließen') : $gettext('Navigation öffnen')"
                                 :size="iconSize" :class="showMenu ? 'menu-open' : 'menu-closed'">
                    </studip-icon>
                </button>
            </transition>
        </div>
        <transition name="appear" appear>
            <nav v-show="showMenu" id="responsive-navigation-items" class="responsive" ref="navigation"
                 :aria-expanded="showMenu">
                <header v-if="me.username !== 'nobody'">
                    <template v-if="!avatarMenuOpen">
                        <section class="profile-info">
                            <div class="profile-pic">
                                <img :src="me.avatar"
                                     @click.prevent="toggleAvatarMenu"
                                     :title="$gettext('Profilnavigation öffnen')"
                                     :aria-label="$gettext('Profilnavigation öffnen')">
                            </div>
                            <div class="profile-data">
                                <div>{{ me.fullname }}</div>
                                <div>{{ me.email }} ({{ me.perm }})</div>
                            </div>
                        </section>
                        <section class="open-avatarmenu">
                            <button class="styleless" ref="openAvatarmenu"
                                    @keydown.prevent.enter="toggleAvatarMenu"
                                    @keydown.prevent.space="toggleAvatarMenu"
                                    @click.prevent="toggleAvatarMenu"
                                    :title="$gettext('Profilnavigation öffnen')"
                                    :aria-label="$gettext('Profilnavigation öffnen')">
                                <studip-icon shape="arr_1right" role="info_alt" :size="iconSize" alt=""></studip-icon>
                            </button>
                        </section>
                    </template>
                    <template v-else>
                        <focus-trap :active="true" :return-focus-on-deactivate="true"
                                    :click-outside-deactivates="true">
                            <div>
                                <div class="close-avatarmenu">
                                    <button class="styleless" ref="closeAvatarmenu"
                                            @keydown.prevent.enter="toggleAvatarMenu"
                                            @keydown.prevent.space="toggleAvatarMenu"
                                            @click="toggleAvatarMenu"
                                            :title="$gettext('Profilnavigation schließen')"
                                            :aria-label="$gettext('Profilnavigation schließen')">
                                        <studip-icon shape="arr_1left" role="info_alt" :size="iconSize"></studip-icon>
                                    </button>
                                </div>
                                <ul class="avatar-navigation">
                                    <navigation-item v-for="(item, index) in avatarNavigation.children" :key="index"
                                                     :item="item"></navigation-item>
                                </ul>
                            </div>
                        </focus-trap>
                    </template>
                </header>
                <ul class="main-navigation">
                    <li v-if="currentParent != null" class="navigation-item navigation-up">
                        <div class="navigation-title" :title="$gettext('Zum Start')"
                             :aria-label="$gettext('Zum Start')">
                            <button class="styleless" @click="moveTo('/')" @keydown.prevent.enter="moveTo('/')"
                                    @keydown.prevent.space="moveTo('/')">
                                <div class="navigation-icon">
                                    <studip-icon shape="arr_2up" role="info_alt" :size="iconSize - 4"></studip-icon>
                                </div>
                                <div class="navigation-text">
                                    {{ $gettext('Start') }}
                                </div>
                            </button>
                        </div>
                    </li>
                    <li v-if="currentParent != null" class="navigation-item navigation-current">
                        <div class="navigation-title">
                            <button class="styleless"
                                    @click="moveTo(currentParent.path)"
                                    @keydown.prevent.enter="moveTo(currentParent.path)"
                                    @keydown.prevent.space="moveTo(currentParent.path)"
                                    :title="$gettext('Eine Ebene höher')"
                                    :aria-label="$gettext('Eine Ebene höher')">
                                <div class="navigation-icon">
                                    <studip-icon shape="arr_1left" role="info_alt" :size="iconSize - 4"></studip-icon>
                                </div>
                                <div class="navigation-text">
                                    {{ $gettext('Eine Ebene höher') }}
                                </div>
                            </button>
                        </div>
                    </li>
                    <navigation-item v-for="(item, index) in currentNavigation.children" :key="index"
                                     :item="item" :active="item.active"></navigation-item>
                </ul>
            </nav>
        </transition>
        <responsive-content-bar v-if="(isResponsive || isFullscreen) && !isFocusMode"
                                :has-sidebar="hasSidebar" :title="contentbarTitle" :aria-label="contentbarTitle"
                                ref="contentbar"></responsive-content-bar>
        <responsive-skip-links v-if="(isResponsive || isFullscreen) && hasSkiplinks" :links="skipLinks"></responsive-skip-links>
    </div>
</template>

<script>
import NavigationItem from './NavigationItem.vue';
import StudipIcon from '../StudipIcon.vue';
import ResponsiveContentBar from './ResponsiveContentBar.vue';
import ResponsiveSkipLinks from './ResponsiveSkipLinks.vue';
import { FocusTrap } from 'focus-trap-vue';

export default {
    name: 'ResponsiveNavigation',
    components: { ResponsiveContentBar, StudipIcon, NavigationItem, ResponsiveSkipLinks, FocusTrap },
    props: {
        me: {
            type: Object,
            required: true
        },
        context: {
            type: String,
            default: ''
        },
        hasSidebar: {
            type: Boolean,
            default: true
        },
        navigation: {
            type: Object,
            required: true,
        }
    },
    data() {
        let studipNavigation = this.sanitizeNavigation(this.navigation);

        return {
            studipNavigation,
            isResponsive: false,
            isFullscreen: false,
            isFocusMode: false,
            headerMagic: false,
            iconSize: 28,
            showMenu: false,
            activeItem: this.navigation.activated.at(-1) ?? 'start',
            currentNavigation: this.findItem(this.navigation.activated.at(0) ?? 'start', studipNavigation)
                ?? studipNavigation,
            initialNavigation: {},
            initialTitle: '',
            isAdmin: ['root','admin'].includes(this.me.perm),
            courses: [],
            avatarNavigation: studipNavigation.avatar,
            avatarMenuOpen: false,
            classObserver: null,
            dialogObserver: null,
            hasSkiplinks: document.querySelector('#skiplink_list') !== null,
            hasContentbar: false,
            contentbarTitle: ''
        }
    },
    computed: {
        // Current navigation title, supplemented by context title if available
        currentTitle() {
            return this.context !== '' && this.currentNavigation.path.indexOf('my_courses/') !== -1 ?
                this.context : '';
        },
        // The parent element of the current navigation item
        currentParent() {
            return this.currentNavigation.parent
                 ? this.findItem(this.currentNavigation.parent, this.studipNavigation)
                 : null;
        },
        /*
         * Is the responsive navigation menu needed (because we are in responsive or fullscreen mode)?
         */
        menuNeeded() {
            return !this.isFocusMode
                && (this.isResponsive || this.isFullscreen || this.headerMagic);
        },

        skipLinks() {
            let links = [
                { url: '#responsive-navigation-button', label: this.$gettext('Hauptnavigation') }
            ];

            if (this.isFullscreen) {
                if (this.hasSidebar) {
                    let name = '';
                    if (document.getElementById('sidebar').classList.contains('responsive-show')) {
                        name = this.$gettext('Sidebar ausblenden');
                    } else {
                        name = this.$gettext('Sidebar anzeigen');
                    }
                    links.push({ url: '#toggle-sidebar', label: name });
                }
            }

            return links;
        }
    },
    methods: {
        /**
         * Find a navigation item specified by given path in the given navigation structure
         * @param path
         * @param navigation
         * @returns {{parent: null, path: string, visible: boolean, children, icon: null, active: boolean, title, url}|null}
         */
        findItem(path, navigation) {
            // Some "pseudo" navigation directly at root level.
            if (path === '/' || path === 'start') {
                return {
                    active: true,
                    children: navigation,
                    icon: null,
                    parent: null,
                    path: '/',
                    title: navigation.start.title,
                    url: navigation.start.url,
                    visible: true
                };
            } else {
                // Found requested item at current level.
                if (navigation[path]) {
                    return navigation[path];
                } else {
                    // Special handling for first navigation level, we have no "children" attribute here.
                    if (navigation.start) {

                        let found = null;
                        for (const sub in navigation) {
                            found = this.findItem(path, navigation[sub]);
                            if (found) {
                                break;
                            }
                        }
                        return found;

                    } else if (navigation.children) {

                        // Found requested item as child of current one.
                        if (navigation.children[path]) {
                            return navigation.children[path];

                            // Recurse deeper.
                        } else {

                            let found = null;
                            for (const sub in navigation.children) {
                                found = this.findItem(path, navigation.children[sub]);
                                if (found) {
                                    break;
                                }
                            }
                            return found;

                        }
                    // No children left to search through, we are doomed.
                    } else {
                        return null;
                    }

                }
            }
        },
        /**
         * Open or close the navigation menu
         */
        toggleMenu() {
            this.showMenu = !this.showMenu;

            if (!this.showMenu && this.avatarMenuOpen) {
                this.toggleAvatarMenu();
            }

            this.$nextTick(() => {
                if (this.showMenu && !this.headerMagic) {
                    this.currentNavigation = this.initialNavigation;

                    if (this.isResponsive) {
                        this.$refs.navigation.style.height = (document.documentElement.clientHeight - 42) + 'px';
                    }
                    document.getElementById('header-links').style.display = 'none';
                } else {
                    document.getElementById('header-links').style.display = null;
                }
            })
        },
        /**
         * Turn compact navigation mode on or off
         * @param state
         */
        setCompactNavigation(state) {
            const sidebar = document.getElementById('sidebar');
            const cache = STUDIP.Cache.getInstance('responsive.');

            if (state) {
                if (this.hasContentbar) {
                    document.getElementById('responsive-toggle-focusmode').style.display = 'block';
                }
                document.documentElement.classList.add('fullscreen-mode');
                cache.set('fullscreen-mode', true);

                const siteTitle = document.getElementById('site-title');
                if (siteTitle) {
                    siteTitle.dataset.originalTitle = siteTitle.textContent.trim();
                    siteTitle.textContent = this.initialTitle;
                }

                sidebar.ariaHidden = 'true';

            } else {
                document.documentElement.classList.remove('fullscreen-mode');
                sidebar?.classList.remove('responsive-show', 'fullscreen-mode');
                this.showMenu = false;
                cache.remove('fullscreen-mode');
                document.getElementById('responsive-toggle-focusmode').style.display = 'none';
                document.body.classList.remove('fullscreen-sidebar-shown');
                document.body.style.display = '';

                const siteTitle = document.getElementById('site-title');
                if (siteTitle.dataset.originalTitle) {
                    siteTitle.textContent = siteTitle.dataset.originalTitle.trim();
                }

                sidebar.ariaHidden = '';
            }

            this.isFullscreen = state;

            if (!this.isResponsive) {
                this.moveHelpbar();
            }
        },
        getUrl(url) {
            return STUDIP.URLHelper.getURL(url, {}, true);
        },
        /**
         * Move to another item in navigation structure, specified by path
         * @param path
         */
        moveTo(path) {
            this.avatarMenuOpen = false;
            this.currentNavigation =
                this.findItem(path ? path : '/', this.studipNavigation) ?? this.studipNavigation;
            this.$nextTick(() => {
                const current = document.querySelector('.navigation-current')
                    ? document.querySelector('.navigation-current .navigation-title button')
                    : document.querySelector('.navigation-item .navigation-title a');
                current.focus();
            })
        },
        /**
         * Relocate the helpbar icon to another DOM location
         * as it is part of top bar in responsive view.
         */
        moveHelpbar() {
            let tag = 'div';
            let target = '.tabs_wrapper';
            let before = '#non-responsive-toggle-fullscreen';
            if (this.isFullscreen || this.isResponsive) {
                tag = 'li';
                target = '#header-links ul';
                before = '#responsive-toggle-fullscreen';
            }

            let helpBar = document.createElement(tag);
            const realHelpBar = document.querySelector('.helpbar-container');

            const helpbarIcon = document.querySelector('#helpbar_icon');

            if (helpbarIcon) {
                const realIcon = helpbarIcon.querySelector('img.icon-shape-question-circle');
                realIcon.src = (this.isFullscreen || this.isResponsive)
                             ? realIcon.src.replace('blue', 'white')
                             : realIcon.src.replace('white', 'blue');

                helpBar.appendChild(helpbarIcon);
                helpBar.appendChild(document.querySelector('div.helpbar'));
                helpBar.classList.add('helpbar-container');
                document.querySelector(target).insertBefore(helpBar, document.querySelector(before));
                realHelpBar.remove();
            }
        },
        /**
         * Show or hide avatar navigation menu.
         */
        toggleAvatarMenu() {
            this.avatarMenuOpen = !this.avatarMenuOpen;

            // Focus first menu entry.
            if (this.avatarMenuOpen) {
                this.$nextTick(() => {
                    document.querySelector('.avatar-navigation .navigation-item .navigation-title a').focus();
                });
            }
        },
        onChangeViewMode(tagName, classes) {
            const classList = classes.split(' ');

            switch (tagName) {
                // watch for "consuming_mode" or "fixed" class changes
                case 'BODY':
                    if (classList.includes('consuming_mode')) {
                        this.isFocusMode = true;
                        STUDIP.eventBus.emit('consuming-mode-enabled');
                        this.setCompactNavigation(false);
                    } else {
                        this.isFocusMode = false;
                        STUDIP.eventBus.emit('consuming-mode-disabled');
                    }
                    if (classList.includes('fixed')) {
                        this.headerMagic = true;
                        STUDIP.eventBus.emit('header-magic-enabled');
                    } else {
                        this.headerMagic = false;
                        this.showMenu = false;
                        STUDIP.eventBus.emit('header-magic-disabled');
                    }
                    break;
                // Watch for "responsive-display" and "fullscreen-mode" class changes
                case 'HTML':
                    if (classList.includes('responsive-display')) {
                        this.isResponsive = true;

                        if (classList.includes('fullscreen-mode')) {
                            this.setCompactNavigation(false);
                        }

                        STUDIP.eventBus.emit('responsive-display-enabled');
                        this.$nextTick(() => {
                            this.moveHelpbar();
                        })
                    } else {
                        this.isResponsive = false;
                        STUDIP.eventBus.emit('responsive-display-disabled');
                        this.$nextTick(() => {
                            this.moveHelpbar();
                        })
                    }

                    if (classList.includes('fullscreen-mode')) {
                        this.isFullscreen = true;

                        STUDIP.eventBus.emit('fullscreen-enabled');
                    } else {
                        this.isFullscreen = false;
                        STUDIP.eventBus.emit('fullscreen-disabled');
                    }
                    break;
                case 'HEADER':
                    this.isFocusMode = classList.includes('cw-ribbon-consume');
            }
        },
        sanitizeNavigation(navigation) {
            const cache = STUDIP.Cache.getInstance('responsive.');

            // No navigation object was sent, read from cache
            if (navigation.navigation === undefined) {
                return cache.get('navigation');
            }

            // Navigation object was sent, store in cache
            cache.set('navigation', navigation.navigation);
            STUDIP.Cookie.set('responsive-navigation-hash', navigation.hash);

            return navigation.navigation;
        },
        captureOutsideClick(target) {
            if (this.showMenu && target !== null) {
                if (!this.$refs.container.contains(target)) {
                    this.toggleMenu();
                }
            }
        }
    },
    watch: {
        showMenu(newState) {
            if (newState) {
                // Click outside navigation menu should close it.
                document.addEventListener('click', event => {
                    this.captureOutsideClick(event.target);
                }, true);
            } else {
                document.removeEventListener('click', this.captureOutsideClick(null), true)
            }
        }
    },
    mounted() {
        const cache = STUDIP.Cache.getInstance('responsive.');
        const fullscreen = cache.get('fullscreen-mode') ?? false;
        const fullscreenDocument = document.documentElement.classList.contains('fullscreen-mode');

        if (document.documentElement.classList.contains('responsive-display')) {
            this.isResponsive = true;
        }

        this.isFullscreen = !this.isResponsive && (fullscreenDocument || fullscreen);
        if (this.isFullscreen && !fullscreenDocument) {
            this.setCompactNavigation(true);
        }
        // Re-structure some DOM elements
        this.$nextTick(() => {
            if (this.isResponsive || (this.isFullscreen && !this.isFocusMode)) {
                this.moveHelpbar();

                this.contentbarTitle = document.querySelector('.sidebar-image .sidebar-title')?.textContent;
                const siteTitle = document.getElementById('site-title');
                if (siteTitle) {
                    siteTitle.dataset.originalTitle = siteTitle.textContent.trim();
                    siteTitle.textContent = this.initialTitle;
                }
            }
        });

        // Pressing escape should close an open navigation.
        window.addEventListener('keydown', event => {
            if (event.key === 'Escape' && this.showMenu) {
                this.toggleMenu();
            }
        });

        this.initialNavigation = this.currentNavigation;
        this.initialTitle = this.initialNavigation.title;

        this.globalOn('responsive-navigation-move-to', path => {
            this.moveTo(path);
        });

        // Listen to changes in fullscreen setting
        this.globalOn('toggle-compact-navigation', value => {
            this.setCompactNavigation(value);
        });

        /*
         * Use an observer for html and body in order to check
         * whether we move into consuming mode or leave responsive mode.
         */
        this.classObserver = new MutationObserver(mutations => {
            for (const m of mutations) {
                const newValue = m.target.getAttribute(m.attributeName);
                this.onChangeViewMode(m.target.tagName, newValue);
            }
        });

        // Observe <html> for class changes.
        this.classObserver.observe(document.documentElement, {
            attributes: true,
            attributeOldValue : false,
            attributeFilter: ['class']
        });

        // Observe <body> for class changes.
        this.classObserver.observe(document.body, {
            attributes: true,
            attributeOldValue : false,
            attributeFilter: ['class']
        });

        // Check for closed dialog, re-mounting the Vue component.
        this.dialogObserver = new MutationObserver(mutations => {
            if (mutations[0].removedNodes.length > 0 &&
                    mutations[0].removedNodes[0].classList.contains('ui-widget-overlay')) {
                document.getElementById('responsive-menu').replaceChildren(this.$el);
            }
        });

        this.dialogObserver.observe(document.body, {
            childList: true
        });

        this.globalOn('has-contentbar', value => {
            this.hasContentbar = value;
            if (value && this.isFullscreen) {
                document.getElementById('responsive-toggle-focusmode').style.display = 'block';
            }
        });

        // Observe courseware contentbar for consuming mode.
        this.globalOn('courseware-contentbar-mounted', element => {
            if (this.isFullscreen) {
                document.getElementById('responsive-toggle-focusmode').style.display = 'block';
            }
            this.classObserver.observe(element.$el.querySelector('header.cw-ribbon'), {
                attributes: true,
                attributeOldValue : false,
                attributeFilter: ['class']
            })
        });
    },
    beforeDestroy() {
        this.classObserver.disconnect();
        this.dialogObserver.disconnect();
        document.getElementById('header-links').style.display = null;
        STUDIP.eventBus.off('responsive-navigation-move-to');
        STUDIP.eventBus.off('toggle-compact-navigation');
        STUDIP.eventBus.off('has-contentbar');
        STUDIP.eventBus.off('courseware-contentbar-mounted');
    }
}
</script>

<style lang="scss">
.slide-enter-active,
.slide-leave-active {
    transition: all var(--transition-duration) ease;
}

.slide-enter-to,
.slide-leave-from,
.slide-leave {
    margin-left: -3px;
}

.slide-enter,
.slide-enter-from,
.slide-leave-to {
    margin-left: -50px;
}

.appear-enter-active,
.appear-leave-active {
    transition: opacity var(--transition-duration) ease;
}

.appear-leave,
.appear-leave-from,
.appear-enter-to {
    opacity: 1;
}

.appear-enter,
.appear-enter-from,
.appear-leave-to {
    opacity: 0;
}
</style>