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
 * Controls the message drawer.
18
 *
19
 * @module     core_message/message_drawer
20
 * @copyright  2018 Ryan Wyllie <ryan@moodle.com>
21
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 */
23
define(
24
[
25
    'jquery',
26
    'core/custom_interaction_events',
27
    'core/pubsub',
28
    'core_message/message_drawer_view_contact',
29
    'core_message/message_drawer_view_contacts',
30
    'core_message/message_drawer_view_conversation',
31
    'core_message/message_drawer_view_group_info',
32
    'core_message/message_drawer_view_overview',
33
    'core_message/message_drawer_view_search',
34
    'core_message/message_drawer_view_settings',
35
    'core_message/message_drawer_router',
36
    'core_message/message_drawer_routes',
37
    'core_message/message_drawer_events',
38
    'core_message/message_drawer_helper',
39
    'core/pending',
40
    'core/drawer',
1441 ariadna 41
    'core/toast',
42
    'core/str',
43
    'core/config',
44
    'core/ajax',
45
    'core/local/aria/focuslock',
46
    'core/modal_backdrop',
47
    'core/templates',
48
    'core/local/aria/selectors',
1 efrain 49
],
50
function(
51
    $,
52
    CustomEvents,
53
    PubSub,
54
    ViewContact,
55
    ViewContacts,
56
    ViewConversation,
57
    ViewGroupInfo,
58
    ViewOverview,
59
    ViewSearch,
60
    ViewSettings,
61
    Router,
62
    Routes,
63
    Events,
64
    Helper,
65
    Pending,
1441 ariadna 66
    Drawer,
67
    Toast,
68
    Str,
69
    Config,
70
    Ajax,
71
    FocusLock,
72
    ModalBackdrop,
73
    Templates,
74
    AriaSelectors,
1 efrain 75
) {
76
 
77
    var SELECTORS = {
78
        DRAWER: '[data-region="right-hand-drawer"]',
79
        PANEL_BODY_CONTAINER: '[data-region="panel-body-container"]',
80
        PANEL_HEADER_CONTAINER: '[data-region="panel-header-container"]',
81
        VIEW_CONTACT: '[data-region="view-contact"]',
82
        VIEW_CONTACTS: '[data-region="view-contacts"]',
83
        VIEW_CONVERSATION: '[data-region="view-conversation"]',
1441 ariadna 84
        VIEW_CONVERSATION_WITH_ID: '[data-region="view-conversation"][data-conversation-id]',
85
        VIEW_CONVERSATION_WITH_USER: '[data-region="view-conversation"][data-other-user-id]',
1 efrain 86
        VIEW_GROUP_INFO: '[data-region="view-group-info"]',
87
        VIEW_OVERVIEW: '[data-region="view-overview"]',
88
        VIEW_SEARCH: '[data-region="view-search"]',
89
        VIEW_SETTINGS: '[data-region="view-settings"]',
90
        ROUTES: '[data-route]',
91
        ROUTES_BACK: '[data-route-back]',
92
        HEADER_CONTAINER: '[data-region="header-container"]',
93
        BODY_CONTAINER: '[data-region="body-container"]',
94
        FOOTER_CONTAINER: '[data-region="footer-container"]',
1441 ariadna 95
        CLOSE_BUTTON: '[data-action="closedrawer"]',
96
        MESSAGE_INDEX: '[data-region="message-index"]',
97
        MESSAGE_TEXT_AREA: '[data-region="send-message-txt"]',
1 efrain 98
    };
99
 
100
    /**
101
     * Get elements for route.
102
     *
103
     * @param {String} namespace Unique identifier for the Routes
104
     * @param {Object} root The message drawer container.
105
     * @param {string} selector The route container.
106
     *
107
     * @return {array} elements Found route container objects.
108
     */
109
    var getParametersForRoute = function(namespace, root, selector) {
110
 
111
        var header = root.find(SELECTORS.HEADER_CONTAINER).find(selector);
112
        if (!header.length) {
113
            header = root.find(SELECTORS.PANEL_HEADER_CONTAINER).find(selector);
114
        }
115
        var body = root.find(SELECTORS.BODY_CONTAINER).find(selector);
116
        if (!body.length) {
117
            body = root.find(SELECTORS.PANEL_BODY_CONTAINER).find(selector);
118
        }
119
        var footer = root.find(SELECTORS.FOOTER_CONTAINER).find(selector);
120
 
121
        return [
122
            namespace,
123
            header.length ? header : null,
124
            body.length ? body : null,
125
            footer.length ? footer : null
126
        ];
127
    };
128
 
129
    var routes = [
130
        [Routes.VIEW_CONTACT, SELECTORS.VIEW_CONTACT, ViewContact.show, ViewContact.description],
131
        [Routes.VIEW_CONTACTS, SELECTORS.VIEW_CONTACTS, ViewContacts.show, ViewContacts.description],
132
        [Routes.VIEW_CONVERSATION, SELECTORS.VIEW_CONVERSATION, ViewConversation.show, ViewConversation.description],
133
        [Routes.VIEW_GROUP_INFO, SELECTORS.VIEW_GROUP_INFO, ViewGroupInfo.show, ViewGroupInfo.description],
134
        [Routes.VIEW_OVERVIEW, SELECTORS.VIEW_OVERVIEW, ViewOverview.show, ViewOverview.description],
135
        [Routes.VIEW_SEARCH, SELECTORS.VIEW_SEARCH, ViewSearch.show, ViewSearch.description],
136
        [Routes.VIEW_SETTINGS, SELECTORS.VIEW_SETTINGS, ViewSettings.show, ViewSettings.description]
137
    ];
138
 
139
    /**
140
     * Create routes.
141
     *
142
     * @param {String} namespace Unique identifier for the Routes
143
     * @param {Object} root The message drawer container.
144
     */
145
    var createRoutes = function(namespace, root) {
146
        routes.forEach(function(route) {
147
            Router.add(namespace, route[0], getParametersForRoute(namespace, root, route[1]), route[2], route[3]);
148
        });
149
    };
150
 
1441 ariadna 151
    let backdropPromise = null;
152
 
1 efrain 153
    /**
1441 ariadna 154
     * Set the focus on the drawer.
155
     *
156
     * This method also creates or destroy any necessary backdrop zone and focus trap.
157
     *
158
     * @param {Object} root The message drawer container.
159
     * @param {Boolean} hasFocus Whether the drawer has focus or not.
160
     */
161
    var setFocus = function(root, hasFocus) {
162
        var drawerRoot = Drawer.getDrawerRoot(root);
163
        if (!drawerRoot.length) {
164
            return;
165
        }
166
        if (!backdropPromise) {
167
            backdropPromise = Templates.render('core/modal_backdrop', {})
168
                .then(html => new ModalBackdrop(html));
169
        }
170
        const backdropWithAdjustments = backdropPromise.then(modalBackdrop => {
171
            const messageDrawerZIndex = window.getComputedStyle(drawerRoot[0]).zIndex;
172
            if (messageDrawerZIndex) {
173
                modalBackdrop.setZIndex(messageDrawerZIndex - 1);
174
            }
175
            modalBackdrop.getAttachmentPoint().get(0).addEventListener('click', e => {
176
                PubSub.publish(Events.HIDE, {});
177
                e.preventDefault();
178
            });
179
            return modalBackdrop;
180
        });
181
        if (hasFocus) {
182
            FocusLock.trapFocus(root[0]);
183
            // eslint-disable-next-line promise/catch-or-return
184
            backdropWithAdjustments.then(modalBackdrop => {
185
                if (modalBackdrop) {
186
                    modalBackdrop.show();
187
                    const pageWrapper = document.getElementById('page');
188
                    pageWrapper.style.overflow = 'hidden';
189
                    // Set the focus on the close button so when we press enter, it closes the drawer as it did before
190
                    var closeButton = root.find(SELECTORS.CLOSE_BUTTON);
191
                    if (closeButton.length) {
192
                        closeButton.focus();
193
                    }
194
                }
195
                return modalBackdrop;
196
            });
197
        } else {
198
            // eslint-disable-next-line promise/catch-or-return
199
            backdropWithAdjustments.then(modalBackdrop => {
200
                if (modalBackdrop) {
201
                    FocusLock.untrapFocus();
202
                    var button = $(SELECTORS.DRAWER).attr('data-origin');
203
                    if (button) {
204
                        $('#' + button).focus();
205
                    }
206
                    modalBackdrop.hide();
207
                    const pageWrapper = document.getElementById('page');
208
                    pageWrapper.style.overflow = 'visible';
209
                }
210
                return modalBackdrop;
211
            });
212
        }
213
    };
214
    /**
1 efrain 215
     * Show the message drawer.
216
     *
217
     * @param {string} namespace The route namespace.
218
     * @param {Object} root The message drawer container.
219
     */
220
    var show = function(namespace, root) {
221
        if (!root.attr('data-shown')) {
222
            Router.go(namespace, Routes.VIEW_OVERVIEW);
223
            root.attr('data-shown', true);
224
        }
225
 
226
        var drawerRoot = Drawer.getDrawerRoot(root);
227
        if (drawerRoot.length) {
1441 ariadna 228
            setFocus(root, true);
1 efrain 229
            Drawer.show(drawerRoot);
230
        }
231
    };
232
 
233
    /**
234
     * Hide the message drawer.
235
     *
236
     * @param {Object} root The message drawer container.
237
     */
238
    var hide = function(root) {
239
        var drawerRoot = Drawer.getDrawerRoot(root);
240
        if (drawerRoot.length) {
1441 ariadna 241
            setFocus(root, false);
1 efrain 242
            Drawer.hide(drawerRoot);
243
        }
244
    };
245
 
246
    /**
247
     * Check if the drawer is visible.
248
     *
249
     * @param {Object} root The message drawer container.
250
     * @return {boolean}
251
     */
252
    var isVisible = function(root) {
253
        var drawerRoot = Drawer.getDrawerRoot(root);
254
        if (drawerRoot.length) {
255
            return Drawer.isVisible(drawerRoot);
256
        }
257
        return true;
258
    };
259
 
260
    /**
261
     * Set Jump from button
262
     *
263
     * @param {String} buttonid The originating button id
264
     */
265
    var setJumpFrom = function(buttonid) {
266
        $(SELECTORS.DRAWER).attr('data-origin', buttonid);
267
    };
268
 
269
    /**
1441 ariadna 270
     * Store an unsent message.
271
     *
272
     * Don't store this if the user has already seen the unsent message.
273
     * This avoids spamming and ensures the user is only reminded once per unsent message.
274
     * If the unsent message is sent, this attribute is removed and notification is possible again (see sendMessage).
275
     */
276
    const storeUnsentMessage = async() => {
277
        const messageTextArea = document.querySelector(SELECTORS.MESSAGE_TEXT_AREA);
278
 
279
        if (messageTextArea.value.trim().length > 0 && !messageTextArea.hasAttribute('data-unsent-message-viewed')) {
280
 
281
            let message = messageTextArea.value;
282
            let conversationid = 0;
283
            let otheruserid = 0;
284
 
285
            // We don't always have a conversation to link the unsent message to, so let's check for that.
286
            const conversationId = document.querySelector(SELECTORS.VIEW_CONVERSATION_WITH_ID);
287
            if (conversationId) {
288
                const conversationWithId = messageTextArea.closest(SELECTORS.VIEW_CONVERSATION_WITH_ID);
289
                conversationid = conversationWithId.getAttribute('data-conversation-id');
290
            }
291
            // Store the 'other' user id if it is there. This can be used to create conversations.
292
            const conversationUser = document.querySelector(SELECTORS.VIEW_CONVERSATION_WITH_USER);
293
            if (conversationUser) {
294
                const conversationWithUser = messageTextArea.closest(SELECTORS.VIEW_CONVERSATION_WITH_USER);
295
                otheruserid = conversationWithUser.getAttribute('data-other-user-id');
296
            }
297
 
298
            setStoredUnsentMessage(message, conversationid, otheruserid);
299
        }
300
    };
301
 
302
    /**
303
     * Get the stored unsent message from the session via web service.
304
     *
305
     * @returns {Promise}
306
     */
307
    const getStoredUnsentMessage = () => Ajax.call([{
308
        methodname: 'core_message_get_unsent_message',
309
        args: {}
310
    }])[0];
311
 
312
    /**
313
     * Set the unsent message value in the session via web service.
314
     *
315
     * SendBeacon is used here because this is called on 'beforeunload'.
316
     *
317
     * @param {string} message The message string.
318
     * @param {number} conversationid The conversation id.
319
     * @param {number} otheruserid The other user id.
320
     * @returns {Promise}
321
     */
322
    const setStoredUnsentMessage = (message, conversationid, otheruserid) => {
323
        const method = 'core_message_set_unsent_message';
324
        const requestUrl = new URL(`${Config.wwwroot}/lib/ajax/service.php`);
325
        requestUrl.searchParams.set('sesskey', Config.sesskey);
326
        requestUrl.searchParams.set('info', method);
327
 
328
        navigator.sendBeacon(requestUrl, JSON.stringify([{
329
            index: 0,
330
            methodname: method,
331
            args: {
332
                message: message,
333
                conversationid: conversationid,
334
                otheruserid: otheruserid,
335
            }
336
        }]));
337
    };
338
 
339
    /**
340
     * Check for an unsent message.
341
     *
342
     * @param {String} uniqueId Unique identifier for the Routes.
343
     * @param {Object} root The message drawer container.
344
     */
345
    const getUnsentMessage = async(uniqueId, root) => {
346
        let type;
347
        let messageRoot;
348
 
349
        // We need to check if we are on the message/index page.
350
        // This logic is needed to handle the two message widgets here and ensure we are targetting the right one.
351
        const messageIndex = document.querySelector(SELECTORS.MESSAGE_INDEX);
352
        if (messageIndex !== null) {
353
            type = 'index';
354
            messageRoot = document.getElementById(`message-index-${uniqueId}`);
355
            if (!messageRoot) {
356
                // This is not the correct widget.
357
                return;
358
            }
359
 
360
        } else {
361
            type = 'drawer';
362
            messageRoot = document.getElementById(`message-drawer-${uniqueId}`);
363
        }
364
 
365
        const storedMessage = await getStoredUnsentMessage();
366
        const messageTextArea = messageRoot.querySelector(SELECTORS.MESSAGE_TEXT_AREA);
367
        if (storedMessage.message && messageTextArea !== null) {
368
            showUnsentMessage(messageTextArea, storedMessage, type, uniqueId, root);
369
        }
370
    };
371
 
372
    /**
373
     * Show an unsent message.
374
     *
375
     * There are two message widgets on the message/index page.
376
     * Because of that, we need to try and target the correct widget.
377
     *
378
     * @param {String} textArea The textarea element.
379
     * @param {Object} stored The stored message content.
380
     * @param {String} type Is this from the drawer or index page?
381
     * @param {String} uniqueId Unique identifier for the Routes.
382
     * @param {Object} root The message drawer container.
383
     */
384
    const showUnsentMessage = (textArea, stored, type, uniqueId, root) => {
385
        // The user has already been notified.
386
        if (textArea.hasAttribute('data-unsent-message-viewed')) {
387
            return;
388
        }
389
 
390
        // Depending on the type, show the conversation with the data we have available.
391
        // A conversation can be continued if there is a conversationid.
392
        // If the user was messaging a new non-contact, we won't have a conversationid yet.
393
        // In that case, we use the otheruserid value to start a conversation with them.
394
        switch (type) {
395
            case 'index':
396
                // Show the conversation in the main panel on the message/index page.
397
                if (stored.conversationid) {
398
                    Router.go(uniqueId, Routes.VIEW_CONVERSATION, stored.conversationid, 'frompanel');
399
                // There was no conversation id, let's get a conversation going using the user id.
400
                } else if (stored.otheruserid) {
401
                    Router.go(uniqueId, Routes.VIEW_CONVERSATION, null, 'create', stored.otheruserid);
402
                }
403
                break;
404
 
405
            case 'drawer':
406
                // Open the drawer and show the conversation.
407
                if (stored.conversationid) {
408
                    let args = {
409
                        conversationid: stored.conversationid
410
                    };
411
                    Helper.showConversation(args);
412
                // There was no conversation id, let's get a conversation going using the user id.
413
                } else if (stored.otheruserid) {
414
                    show(uniqueId, root);
415
                    Router.go(uniqueId, Routes.VIEW_CONVERSATION, null, 'create', stored.otheruserid);
416
                }
417
                break;
418
        }
419
 
420
        // Populate the text area.
421
        textArea.value = stored.message;
422
        textArea.setAttribute('data-unsent-message-viewed', 1);
423
 
424
        // Notify the user.
425
        Toast.add(Str.get_string('unsentmessagenotification', 'core_message'));
426
    };
427
 
428
    /**
1 efrain 429
     * Listen to and handle events for routing, showing and hiding the message drawer.
430
     *
431
     * @param {string} namespace The route namespace.
432
     * @param {Object} root The message drawer container.
433
     * @param {bool} alwaysVisible Is this messaging app always shown?
434
     */
435
    var registerEventListeners = function(namespace, root, alwaysVisible) {
1441 ariadna 436
        CustomEvents.define(root, [CustomEvents.events.activate, CustomEvents.events.escape]);
1 efrain 437
        var paramRegex = /^data-route-param-?(\d*)$/;
438
 
439
        root.on(CustomEvents.events.activate, SELECTORS.ROUTES, function(e, data) {
440
            var element = $(e.target).closest(SELECTORS.ROUTES);
441
            var route = element.attr('data-route');
442
            var attributes = [];
443
 
444
            for (var i = 0; i < element[0].attributes.length; i++) {
445
                attributes.push(element[0].attributes[i]);
446
            }
447
 
448
            var paramAttributes = attributes.filter(function(attribute) {
449
                var name = attribute.nodeName;
450
                var match = paramRegex.test(name);
451
                return match;
452
            });
453
            paramAttributes.sort(function(a, b) {
454
                var aParts = paramRegex.exec(a.nodeName);
455
                var bParts = paramRegex.exec(b.nodeName);
456
                var aIndex = aParts.length > 1 ? aParts[1] : 0;
457
                var bIndex = bParts.length > 1 ? bParts[1] : 0;
458
 
459
                if (aIndex < bIndex) {
460
                    return -1;
461
                } else if (bIndex < aIndex) {
462
                    return 1;
463
                } else {
464
                    return 0;
465
                }
466
            });
467
 
468
            var params = paramAttributes.map(function(attribute) {
469
                return attribute.nodeValue;
470
            });
471
 
472
            var routeParams = [namespace, route].concat(params);
473
 
474
            Router.go.apply(null, routeParams);
475
 
476
            data.originalEvent.preventDefault();
477
        });
478
 
479
        root.on(CustomEvents.events.activate, SELECTORS.ROUTES_BACK, function(e, data) {
480
            Router.back(namespace);
481
 
482
            data.originalEvent.preventDefault();
483
        });
484
 
1441 ariadna 485
        // Close the message drawer if the drawer is visible and the click happened outside the drawer and the toggle button.
486
        $(document).on(CustomEvents.events.activate, e => {
487
            var drawer = $(e.target).closest(SELECTORS.DRAWER);
488
            var toggleButtonId = $(SELECTORS.DRAWER)?.attr('data-origin');
489
            var toggleButton = '';
490
            if (toggleButtonId !== undefined && toggleButtonId) {
491
                toggleButton = $(e.target).closest("#" + toggleButtonId);
492
            }
493
 
494
            if (!drawer.length && !toggleButton.length && isVisible(root)) {
495
                // Determine if the element that was clicked is focusable.
496
                var focusableElement = $(e.target).closest(AriaSelectors.elements.focusable);
497
                if (focusableElement.length) {
498
                    // We need to move the focus to the clicked element after the drawer is hidden,
499
                    // so we need to clear the `data-origin` attribute first.
500
                    $(SELECTORS.DRAWER).attr('data-origin', '');
501
                }
502
                // Hide the drawer.
503
                hide(root);
504
                // Move the focus to the clicked element if it is focusable.
505
                if (focusableElement.length) {
506
                    focusableElement.focus();
507
                }
508
            }
509
        });
510
 
1 efrain 511
        // These are theme-specific to help us fix random behat fails.
512
        // These events target those events defined in BS3 and BS4 onwards.
1441 ariadna 513
        root[0].querySelectorAll('.collapse').forEach((collapse) => {
514
            collapse.addEventListener('hide.bs.collapse', (e) => {
515
                var pendingPromise = new Pending();
516
                e.target.addEventListener('hidden.bs.collapse', function() {
517
                    pendingPromise.resolve();
518
                }, {once: true});
1 efrain 519
            });
520
        });
521
 
1441 ariadna 522
        root[0].querySelectorAll('.collapse').forEach((collapse) => {
523
            collapse.addEventListener('show.bs.collapse', (e) => {
524
                var pendingPromise = new Pending();
525
                e.target.addEventListener('shown.bs.collapse', function() {
526
                    pendingPromise.resolve();
527
                }, {once: true});
1 efrain 528
            });
529
        });
530
 
531
        $(SELECTORS.JUMPTO).focus(function() {
532
            var firstInput = root.find(SELECTORS.CLOSE_BUTTON);
533
            if (firstInput.length) {
534
                firstInput.focus();
535
            } else {
536
                $(SELECTORS.HEADER_CONTAINER).find(SELECTORS.ROUTES_BACK).focus();
537
            }
538
        });
539
 
540
        $(SELECTORS.DRAWER).focus(function() {
541
            var button = $(this).attr('data-origin');
542
            if (button) {
543
                $('#' + button).focus();
544
            }
545
        });
546
 
547
        if (!alwaysVisible) {
548
            PubSub.subscribe(Events.SHOW, function() {
549
                show(namespace, root);
550
            });
551
 
552
            PubSub.subscribe(Events.HIDE, function() {
553
                hide(root);
554
            });
555
 
556
            PubSub.subscribe(Events.TOGGLE_VISIBILITY, function(buttonid) {
1441 ariadna 557
                const buttonElement = document.getElementById(buttonid);
1 efrain 558
                if (isVisible(root)) {
559
                    hide(root);
1441 ariadna 560
                    buttonElement?.setAttribute('aria-expanded', false);
1 efrain 561
                    $(SELECTORS.JUMPTO).attr('tabindex', -1);
562
                } else {
563
                    show(namespace, root);
1441 ariadna 564
                    buttonElement?.setAttribute('aria-expanded', true);
1 efrain 565
                    setJumpFrom(buttonid);
566
                    $(SELECTORS.JUMPTO).attr('tabindex', 0);
567
                }
568
            });
1441 ariadna 569
            root.on(CustomEvents.events.escape, function() {
570
                PubSub.publish(Events.HIDE, {});
571
            });
1 efrain 572
        }
573
 
574
        PubSub.subscribe(Events.SHOW_CONVERSATION, function(args) {
575
            setJumpFrom(args.buttonid);
576
            show(namespace, root);
577
            Router.go(namespace, Routes.VIEW_CONVERSATION, args.conversationid);
578
        });
579
 
580
        var closebutton = root.find(SELECTORS.CLOSE_BUTTON);
581
        closebutton.on(CustomEvents.events.activate, function(e, data) {
582
            data.originalEvent.preventDefault();
1441 ariadna 583
            setFocus(root, false);
1 efrain 584
            var button = $(SELECTORS.DRAWER).attr('data-origin');
585
            if (button) {
586
                $('#' + button).focus();
587
            }
1441 ariadna 588
            PubSub.publish(Events.TOGGLE_VISIBILITY, button);
1 efrain 589
        });
590
 
591
        PubSub.subscribe(Events.CREATE_CONVERSATION_WITH_USER, function(args) {
592
            setJumpFrom(args.buttonid);
593
            show(namespace, root);
594
            Router.go(namespace, Routes.VIEW_CONVERSATION, null, 'create', args.userid);
595
        });
596
 
597
        PubSub.subscribe(Events.SHOW_SETTINGS, function() {
598
            show(namespace, root);
599
            Router.go(namespace, Routes.VIEW_SETTINGS);
600
        });
601
 
602
        PubSub.subscribe(Events.PREFERENCES_UPDATED, function(preferences) {
603
            var filteredPreferences = preferences.filter(function(preference) {
604
                return preference.type == 'message_entertosend';
605
            });
606
            var enterToSendPreference = filteredPreferences.length ? filteredPreferences[0] : null;
607
 
608
            if (enterToSendPreference) {
609
                var viewConversationFooter = root.find(SELECTORS.FOOTER_CONTAINER).find(SELECTORS.VIEW_CONVERSATION);
610
                viewConversationFooter.attr('data-enter-to-send', enterToSendPreference.value);
611
            }
612
        });
1441 ariadna 613
 
614
        // If our textarea is modified, remove the attribute which indicates the user has seen the unsent message notification.
615
        // This will allow the user to be notified again.
616
        const textArea = document.querySelector(SELECTORS.MESSAGE_TEXT_AREA);
617
        if (textArea) {
618
            textArea.addEventListener('keyup', function() {
619
                textArea.removeAttribute('data-unsent-message-viewed');
620
            });
621
        }
622
 
623
        // Catch any unsent messages and store them.
624
        window.addEventListener('beforeunload', storeUnsentMessage);
1 efrain 625
    };
626
 
627
    /**
628
     * Initialise the message drawer.
629
     *
630
     * @param {Object} root The message drawer container.
631
     * @param {String} uniqueId Unique identifier for the Routes
632
     * @param {bool} alwaysVisible Should we show the app now, or wait for the user?
633
     * @param {Object} route
634
     */
635
    var init = function(root, uniqueId, alwaysVisible, route) {
636
        root = $(root);
637
        createRoutes(uniqueId, root);
638
        registerEventListeners(uniqueId, root, alwaysVisible);
639
 
640
        if (alwaysVisible) {
641
            show(uniqueId, root);
642
 
643
            if (route) {
644
                var routeParams = route.params || [];
645
                routeParams = [uniqueId, route.path].concat(routeParams);
646
                Router.go.apply(null, routeParams);
647
            }
648
        }
649
 
650
        // Mark the drawer as ready.
651
        Helper.markDrawerReady();
1441 ariadna 652
 
653
        // Get and show any unsent message.
654
        getUnsentMessage(uniqueId, root);
1 efrain 655
    };
656
 
657
    return {
658
        init: init,
659
    };
660
});