converse-roomslist.js 11.8 KB
Newer Older
1 2 3
// Converse.js (A browser based XMPP chat client)
// http://conversejs.org
//
4
// Copyright (c) 2013-2018, Jan-Carel Brand <jc@opkode.com>
5 6 7 8 9
// Licensed under the Mozilla Public License (MPLv2)

/* This is a non-core Converse.js plugin which shows a list of currently open
 * rooms in the "Rooms Panel" of the ControlBox.
 */
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

import converse from "@converse/headless/converse-core";
import muc from "@converse/headless/converse-muc";
import tpl_rooms_list from "templates/rooms_list.html";
import tpl_rooms_list_item from "templates/rooms_list_item.html"

const { Backbone, Promise, Strophe, b64_sha1, sizzle, _ } = converse.env;
const u = converse.env.utils;


converse.plugins.add('converse-roomslist', {

    /* Optional dependencies are other plugins which might be
     * overridden or relied upon, and therefore need to be loaded before
     * this plugin. They are called "optional" because they might not be
     * available, in which case any overrides applicable to them will be
     * ignored.
     *
     * It's possible however to make optional dependencies non-optional.
     * If the setting "strict_plugin_dependencies" is set to true,
     * an error will be raised if the plugin is not found.
     *
     * NB: These plugins need to have already been loaded via require.js.
     */
    dependencies: ["converse-singleton", "converse-controlbox", "converse-muc", "converse-bookmarks"],

    initialize () {
        /* The initialize function gets called as soon as the plugin is
         * loaded by converse.js's plugin machinery.
39
         */
40 41
        const { _converse } = this,
              { __ } = _converse;
42

43 44 45
        // Promises exposed by this plugin
        _converse.api.promises.add('roomsListInitialized');

46

47
        _converse.OpenRooms = Backbone.Collection.extend({
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
            comparator (room) {
                if (room.get('bookmarked')) {
                    const bookmark = _.head(_converse.bookmarksview.model.where({'jid': room.get('jid')}));
                    return bookmark.get('name');
                } else {
                    return room.get('name');
                }
            },

            initialize () {
                _converse.chatboxes.on('add', this.onChatBoxAdded, this);
                _converse.chatboxes.on('change:hidden', this.onChatBoxChanged, this);
                _converse.chatboxes.on('change:bookmarked', this.onChatBoxChanged, this);
                _converse.chatboxes.on('change:name', this.onChatBoxChanged, this);
                _converse.chatboxes.on('change:num_unread', this.onChatBoxChanged, this);
                _converse.chatboxes.on('change:num_unread_general', this.onChatBoxChanged, this);
                _converse.chatboxes.on('remove', this.onChatBoxRemoved, this);
                this.reset(_.map(_converse.chatboxes.where({'type': 'chatroom'}), 'attributes'));
            },

            onChatBoxAdded (item) {
                if (item.get('type') === 'chatroom') {
                    this.create(item.attributes);
                }
            },
74

75 76 77 78 79
            onChatBoxChanged (item) {
                if (item.get('type') === 'chatroom') {
                    const room =  this.get(item.get('jid'));
                    if (!_.isNil(room)) {
                        room.set(item.attributes);
80
                    }
81 82
                }
            },
83

84 85 86 87
            onChatBoxRemoved (item) {
                if (item.get('type') === 'chatroom') {
                    const room = this.get(item.get('jid'))
                    this.remove(room);
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
        _converse.RoomsList = Backbone.Model.extend({
            defaults: {
                "toggle-state":  _converse.OPENED
            }
        });

        _converse.RoomsListElementView = Backbone.VDOMView.extend({
            events: {
                'click .room-info': 'showRoomDetailsModal'
            },

            initialize () {
                this.model.on('destroy', this.remove, this);
                this.model.on('remove', this.remove, this);
                this.model.on('change:bookmarked', this.render, this);
                this.model.on('change:hidden', this.render, this);
                this.model.on('change:name', this.render, this);
                this.model.on('change:num_unread', this.render, this);
                this.model.on('change:num_unread_general', this.render, this);
            },

            toHTML () {
                return tpl_rooms_list_item(
                    _.extend(this.model.toJSON(), {
                        // XXX: By the time this renders, the _converse.bookmarks
                        // collection should already exist if bookmarks are
                        // supported by the XMPP server. So we can use it
                        // as a check for support (other ways of checking are async).
                        'allow_bookmarks': _converse.allow_bookmarks && _converse.bookmarks,
122
                        'currently_open': _converse.isUniView() && !this.model.get('hidden'),
123 124 125 126 127 128 129 130 131 132 133 134 135 136
                        'info_leave_room': __('Leave this groupchat'),
                        'info_remove_bookmark': __('Unbookmark this groupchat'),
                        'info_add_bookmark': __('Bookmark this groupchat'),
                        'info_title': __('Show more information on this groupchat'),
                        'name': this.getRoomsListElementName(),
                        'open_title': __('Click to open this groupchat')
                    }));
            },

            showRoomDetailsModal (ev) {
                const room = _converse.chatboxes.get(this.model.get('jid'));
                ev.preventDefault();
                if (_.isUndefined(room.room_details_modal)) {
                    room.room_details_modal = new _converse.RoomDetailsModal({'model': room});
137
                }
138 139 140 141 142 143 144 145 146
                room.room_details_modal.show(ev);
            },

            getRoomsListElementName () {
                if (this.model.get('bookmarked') && _converse.bookmarksview) {
                    const bookmark = _.head(_converse.bookmarksview.model.where({'jid': this.model.get('jid')}));
                    return bookmark.get('name');
                } else {
                    return this.model.get('name');
147
                }
148 149
            }
        });
150 151


152 153 154 155 156 157 158 159 160 161 162 163 164
        _converse.RoomsListView = Backbone.OrderedListView.extend({
            tagName: 'div',
            className: 'open-rooms-list list-container rooms-list-container',
            events: {
                'click .add-bookmark': 'addBookmark',
                'click .close-room': 'closeRoom',
                'click .list-toggle': 'toggleRoomsList',
                'click .remove-bookmark': 'removeBookmark',
                'click .open-room': 'openRoom',
            },
            listSelector: '.rooms-list',
            ItemView: _converse.RoomsListElementView,
            subviewIndex: 'jid',
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
            initialize () {
                Backbone.OrderedListView.prototype.initialize.apply(this, arguments);

                this.model.on('add', this.showOrHide, this);
                this.model.on('remove', this.showOrHide, this);

                const storage = _converse.config.get('storage'),
                      id = b64_sha1(`converse.roomslist${_converse.bare_jid}`);

                this.list_model = new _converse.RoomsList({'id': id});
                this.list_model.browserStorage = new Backbone.BrowserStorage[storage](id);
                this.list_model.fetch();
                this.render();
                this.sortAndPositionAllItems();
            },

            render () {
                this.el.innerHTML = tpl_rooms_list({
                    'toggle_state': this.list_model.get('toggle-state'),
                    'desc_rooms': __('Click to toggle the list of open groupchats'),
                    'label_rooms': __('Open Groupchats'),
                    '_converse': _converse
                });
                if (this.list_model.get('toggle-state') !== _converse.OPENED) {
                    this.el.querySelector('.open-rooms-list').classList.add('collapsed');
                }
                this.showOrHide();
                this.insertIntoControlBox();
                return this;
            },

            insertIntoControlBox () {
                const controlboxview = _converse.chatboxviews.get('controlbox');
                if (!_.isUndefined(controlboxview) && !u.rootContains(_converse.root, this.el)) {
                    const el = controlboxview.el.querySelector('.open-rooms-list');
                    if (!_.isNull(el)) {
                        el.parentNode.replaceChild(this.el, el);
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
            },

            hide () {
                u.hideElement(this.el);
            },

            show () {
                u.showElement(this.el);
            },

            openRoom (ev) {
                ev.preventDefault();
                const name = ev.target.textContent;
                const jid = ev.target.getAttribute('data-room-jid');
                const data = {
                    'name': name || Strophe.unescapeNode(Strophe.getNodeFromJid(jid)) || jid
                }
                _converse.api.rooms.open(jid, data);
            },

            closeRoom (ev) {
                ev.preventDefault();
                const name = ev.target.getAttribute('data-room-name');
                const jid = ev.target.getAttribute('data-room-jid');
                if (confirm(__("Are you sure you want to leave the groupchat %1$s?", name))) {
                    // TODO: replace with API call
                    _converse.chatboxviews.get(jid).close();
                }
            },
234

235 236 237 238 239 240 241 242 243 244 245 246 247
            showOrHide (item) {
                if (!this.model.models.length) {
                    u.hideElement(this.el);
                } else {
                    u.showElement(this.el);
                }
            },

            removeBookmark: _converse.removeBookmarkViaEvent,
            addBookmark: _converse.addBookmarkViaEvent,

            toggleRoomsList (ev) {
                if (ev && ev.preventDefault) { ev.preventDefault(); }
JC Brand's avatar
JC Brand committed
248
                const icon_el = ev.target.matches('.fa') ? ev.target : ev.target.querySelector('.fa');
249 250 251 252 253 254 255 256 257 258 259 260 261
                if (icon_el.classList.contains("fa-caret-down")) {
                    u.slideIn(this.el.querySelector('.open-rooms-list')).then(() => {
                        this.list_model.save({'toggle-state': _converse.CLOSED});
                        icon_el.classList.remove("fa-caret-down");
                        icon_el.classList.add("fa-caret-right");
                    });
                } else {
                    u.slideOut(this.el.querySelector('.open-rooms-list')).then(() => {
                        this.list_model.save({'toggle-state': _converse.OPENED});
                        icon_el.classList.remove("fa-caret-right");
                        icon_el.classList.add("fa-caret-down");
                    });
                }
262
            }
263 264 265 266 267 268 269 270 271
        });

        const initRoomsListView = function () {
            const storage = _converse.config.get('storage'),
                  id = b64_sha1(`converse.open-rooms-{_converse.bare_jid}`),
                  model = new _converse.OpenRooms();

            model.browserStorage = new Backbone.BrowserStorage[storage](id);
            _converse.rooms_list_view = new _converse.RoomsListView({'model': model});
272
            _converse.api.emit('roomsListInitialized');
273 274 275
        };

        if (_converse.allow_bookmarks) {
276
            _converse.api.waitUntil('bookmarksInitialized').then(initRoomsListView);
277 278
        } else {
            u.onMultipleEvents([
279
                    {'object': _converse, 'event': 'chatBoxesInitialized'},
280 281
                    {'object': _converse, 'event': 'roomsPanelRendered'}
                ], initRoomsListView);
282
        }
283 284 285 286 287

        _converse.api.listen.on('reconnected', initRoomsListView);
    }
});