Comandos do chatbox com abas

2 participantes

Ver o tópico anterior Ver o tópico seguinte Ir para baixo

Tópico resolvido Comandos do chatbox com abas

Mensagem por Nág Silva 15.05.17 19:58

Detalhes da questão


Endereço do fórum: http://www.rpghogwartsschool.com/forum
Versão do fórum: phpBB3

Descrição


Eu adicionei agora a pouco o chatbox com abas que o Kyo Panda criou. Ai eu testei e gostei, mas desativei o chat geral porque o intuito era separar as conversas e no All as conversas das outras abas ficavam visíveis. Caso é que agora os comandos do chatbox não funcionam e queria saber como faze-los funcionar nas abas, tipo, em tal aba a conversa é limpa e na outra não, sabe? Se nao tiver como fazer, eu desativarei o codigo :/


Última edição por Nág Silva em 17.05.17 17:49, editado 1 vez(es)
avatar

Nág Silva
*

Membro desde : 01/02/2016
Mensagens : 37
Pontos : 74

http://www.rpghogwartsschool.com/forum

Ir para o topo Ir para baixo

Tópico resolvido Re: Comandos do chatbox com abas

Mensagem por Kyo Panda 17.05.17 17:34

Esse script em breve será atualizado (corrigindo o erro descrito), logo você já pode utilizar a versão nova:

Código:
/*globals jQuery, _userdata*/

/**
 * Adds tabs to the chat in which people can choose to talk separately.
 *
 * @author Kyo Panda
 * @see <a href="http://ajuda.forumeiros.com">Fórum dos Fóruns</a>
 * @license MIT
 */
 
 FA = window.FA || {};
 
 FA.Chatbox = FA.Chatbox || {};
 
 FA.Chatbox.Tabs = (function($, config, i18n, style) {
   /**
    * Object initialization
    */
   function Tabs() {
      /**
       * Language variable
       */
      this.lang = {};
      
      /**
       * Regex for translating tab tags in messages
       */
      this.regex = new RegExp('\\[(' + $.map(config.tabs, function(tab) {
         return tab.label;
      }).join('|') + ')\\]');
      
      /**
       * Tabs initialization
       */      
      $.each(config.tabs, function() {
         /**
          * Regex for removing the tags on messages
          */
         this.regex = new RegExp('\\[' + this.label + '\\](\s?)', 'gi');
         
         /**
          * Last message tab, for new messages notification
          */
         this.lastMessage = 0;
      });
      
      /**
       * Override chatbox
       */
      this.overrideChatbox();
   };
   
   /**
    * Translation function
    */
   Tabs.prototype.t = function(text) {
      return this.lang[text] ? this.lang[text] : text;
   };
   
   /**
    * Initialization function
    */   
   Tabs.prototype.init = function() {
      /**
       * User language definition
       */
      this.lang = window._userdata && i18n[_userdata.user_lang] ?
         i18n[_userdata.user_lang] : {}
      ;
      
      /**
       * Tabs creation
       */
      this.build();
      
      /**
       * Override chatbox refresh
       */
      this.overrideChatboxRefresh();
      
      /**
       * Override chatbox send
       */
      this.overrideChatboxSend();
      
      /**
       * Initial refresh
       */
      this.refresh();
   };
   
   /**
    * Refresh data
    */
   Tabs.prototype.refresh = function() {
      if (!this.source) {
         return this.context.chatbox.refresh(this.context.chatbox);
      }
      
      return this.context.chatbox.refresh(this.source);
   };
   
   /**
    * Tabs creation
    */
   Tabs.prototype.build = function() {
      var self = this;
      
      /**
       * Style creation
       */
      $('head', this.context.document)
         .append($('<style>', { text: style }))
      ;
      
      /**
       * Parent HTML creation
       */
      this.$tabs = $('<ul>', { id: 'chatbox_tabs' })
         /**
          * Tab change function
          */
         .on('click', 'li', function() {
            self.change($(this));
         })
         .appendTo($('#chatbox_header', this.context.document))
      ;
      
      /**
       * Tabs HTML creation
       */
      $.each(config.tabs, function(index, item) {
         /**
          * Don't create hidden tabs
          */
         if (item.hidden) {
            return;
         }
         
         /**
          * Tab creation
          */
         var $elem = $('<li>', {
            'text': self.t(item.label),
            'data-index': index,
         });
         
         /**
          * Make tab active
          */
         if (item.active) {
            self.active = item;
            $elem.addClass('active');
         }
         
         /**
          * Hide properties of "all" tab
          */
         if (item.all) {
            $elem.addClass('all');
         }
         
         self.$tabs.append($elem);
      });
   };
   
   /**
    * Tab change function
    */
   Tabs.prototype.change = function($elem) {
      /**
       * Set the active tab
       */
      this.active = config.tabs[~~$elem.data('index')];
      
      /**
       * Display the active tab
       */
      this.$tabs.children('.active').removeClass('active');
      $elem.addClass('active').removeClass('new-message');

      this.refresh();
   };
   
   /**
    * Notification
    */
   Tabs.prototype.notify = function(message) {
      var date = new Date();
      
      this.source.messages.push({
         userId: -10,
         action: 'msg',
         msgColor: 'green',
         date: date.toLocaleDateString(),
         datetime: date.toLocaleTimeString(),
         time: date.getTime(),
         msg: (this.active.all ? '' : '[' + this.active.label + '] ')
            +  message.replace(/^\/sm\s/i, '')
         ,
      });
   };
   
   /**
    * Mark tab with new messages
    */
   Tabs.prototype.setNewMessageStatus = function(tab) {
      var self = this;
      
      this.$tabs.children().each(function() {
         var $this = $(this);
         var text = $this.text();
         
         if (
            tab.label === text
            || self.t(tab.label) === text
         ) {
            $this.addClass('new-message');
            return false;
         }
      });
   };
   
   /**
    * Chatbox override
    */
   Tabs.prototype.overrideChatbox = function() {
      var self = this;
      var insertChatBoxNew = window.insertChatBoxNew;
   
      window.insertChatBox = window.insertChatBoxNew = function() {
         insertChatBoxNew.apply(this, arguments);
         
         var chatbox = $('#frame_chatbox').get(0);         
         
         if (chatbox.readyState === 'complete') {
            self.context = chatbox.contentWindow;
            return self.init();
         }
         
         var onload = chatbox.onload;
         
         chatbox.onload = function(event) {         
            if (onload) {
               onload.apply(this, arguments);
            }
            
            self.context = event.target.contentWindow;
            
            self.init();
         };
      };
   };
   
   /**
    * Override chatbox refresh
    */
   Tabs.prototype.overrideChatboxRefresh = function() {
      var self = this;
      var refresh = this.context.Chatbox.prototype.refresh;
   
      this.context.Chatbox.prototype.refresh = function(data) {
         
         /**
          * Return if no new messages
          */
         if (!data || !data.messages) {
            return refresh.call(this, data);
         }
         
         /**
          * Store the source data
          */
         self.source = JSON.parse(JSON.stringify(data));
         
         /**
          * Remove hidden messages
          */
         data.messages = $.grep(data.messages, function(message) {
            return !config.hidden[message.action];
         });
         
         /**
          * Capture new messages from other tabs
          */
         var hasNewMessages = [];
         var notifyNewMessages = true;
         
         $.each(data.messages, function() {
            var message = this;
            
            $.each(config.tabs, function() {
               if (message.msg.indexOf('[' + this.label + ']') === -1) {
                  return;
               }
               
               if (this.lastMessage < message.time) {
                  if (this.lastMessage === 0) {
                     notifyNewMessages = false;
                  }
                  
                  if (notifyNewMessages) {
                     hasNewMessages.push(this);
                  }
                  
                  this.lastMessage = message.time;                  
               }
            });
         });
         
         /**
          * Display the all tab
          */
         if (self.active.all) {
            $.each(data.messages, function(index, message) {
               message.msg = message.msg.replace(self.regex, function(text, match) {
                  return '[' + self.t(match) + ']';
               });
            });
            
            return refresh.call(this, data);
         }
         
         /**
          * Display the tab messages
          */
         data.messages = $.grep(data.messages, function(message) {
            if (message.action !== 'msg') {
               return true;
            }
            
            if (message.msg.indexOf('[' + self.active.label + ']') !== -1) {
               /**
                * Remove tag from active and translate others
                */
               message.msg = message.msg
                  .replace(self.active.regex, '$1')
                  .replace(self.regex, function(text, match) {
                     return '[' + self.t(match) + ']';
                  })
               ;
               
               self.active.lastMessage = message.time;
               return true;
            }
            
            return false;
         });
         
         /**
          * Notify new messages from other tabs
          */
         $.each($.unique(hasNewMessages), function() {
            if (this.label === self.active.label) {
               return;
            }
            
            self.setNewMessageStatus(this);
         });
         
         refresh.call(this, data);
      };
   };
   
   /**
    * Override chatbox send
    */
   Tabs.prototype.overrideChatboxSend = function() {
      var self = this;
      var send = this.context.Chatbox.prototype.send;
      
      this.context.Chatbox.prototype.send = function() {
         /**
          * Store the send input
          */
         if (!self.$message) {
            self.$message = $('#message', self.context.document);
         }
         
         var value = self.$message.val();         
         
         /**
          * Change tab
          */
         if (value.indexOf('/ct ') === 0) {
            value = $.trim(value.replace(/^\/ct\s/i, ''));
            
            var tabFound = false;
            
            $.each(config.tabs, function(index) {
               
               if (
                  this.label.toLowerCase() === value.toLowerCase()
                  || self.t(this.label).toLowerCase() === value.toLowerCase()
               ) {
                  tabFound = true;
                  
                  var $elem = self.$tabs
                     .children('[data-index="' + index + '"]')
                  ;
                  
                  if ($elem.length) {
                     self.change($elem);                     
                     return false;
                  }
                  
                  self.$tabs.children('.active').removeClass('active');
                  self.active = this;
                  self.refresh();
                  
                  return false;
               }
            });
            
            if (!tabFound) {
               self.notify(self.t('The tab "%s" doesn\'t exists.').replace('%s', value));
            }

            return self.refresh();   
         }
         
         /**
          * Notification command
          */
         if (value.indexOf('/sm ') === 0) {
            self.notify(value);
            return self.refresh();
         }
         
         /**
          * Add the tab tag to the input
          */
         if (!self.active.all && value.indexOf('/') !== 0) {
            value = '[' + self.active.label + '] ' + value;
         }
         
         self.$message.val(value);
         
         send.apply(this, arguments);
      };
   };
   
   return new Tabs();
 } (jQuery,
   /**
    * Configuration
    */
   {   
      /**
       * Tabs configuration
       *  label  : the tab label
       *  all    : if the tab should show all the messages
       *  active : if the tab is active when first opening the chat
       *  hidden : if the tab is hidden
       */
      tabs: [{
         label: 'All',
         all: true,
      }, {
         label: 'General',
         active: true,
      }, {
         label: 'Animes',
      }, {
         label: 'Games',
      }, {
         label: 'Illuminati',
         hidden: true,
      }],
      
      /**
       * Hidden system messages
       *  connect    : hide connection messages
       *  disconnect : hide disconnect messages
       *  timeout    : hide timeout messages
       */
      hidden: {
         connect: true,
         disconnect: true,
         timeout: true,
      },
   },
      
   /**
    * Internationalization settings
    */
   {
      /**
       * Portuguese
       */
      pt: {
         'All': 'Todos',
         'General': 'Geral',
         'Animes': 'Animes',
         'Games': 'Jogos',
         'Illuminati': 'Illuminati',
         'The tab "%s" doesn\'t exists.': 'A aba "%s" não existe.',
      },
   },

   /**
    * Style
    */
   [
      '#chatbox_header {',
      '   position: relative;',
      '}',
      '',
      '#chatbox_tabs {',
      '   position: absolute;',
      '   bottom: 0;',
      '   left: 180px;',
      '   list-style: none;',
      '   padding: 0 0 0 10px;',
      '   margin: 0;',
      '   overflow: hidden;',
      '}',
      '',
      '#chatbox_tabs li {',
      '   float: left;',
      '   height: 24px;',
      '   line-height: 24px;',
      '   margin-right: 10px;',
      '   padding: 0 5px 0 20px;',
      '   border: 1px #fff solid;',
      '   border-radius: 3px 3px 0 0;',
      '   cursor: pointer;',
      '   font-family: Arial, sans-serif;',
      '   color: #fff;',
      '   border-bottom: none;',
      '   position: relative;',
      '}',
      '',
      '#chatbox_tabs li:before {',
      '   content: " ";',
      '   position: absolute;',
      '   top: 50%;',
      '   left: 5px;',
      '   transform: translate(0, -50%);',
      '   background-color: #999;',
      '   width: 10px;',
      '   height: 10px;',
      '   border-radius: 50%;',
      '}',
      '',
      '#chatbox_tabs li.new-message:before {',
      '   background-color: green;',
      '}',
      '',
      '#chatbox_tabs li.all {',
      '   padding-left: 5px;',
      '}',
      '#chatbox_tabs li.all:before {',
      '   display: none;',
      '}',
      '',
      '#chatbox_tabs li.active {',
      '   background-color: #fff;',
      '   color: #333;',
      '}',
   ].join('\n')
));

Nessa parte do script você pode definir as abas:

Código:
      /**
       * Tabs configuration
       *  label  : the tab label
       *  all    : if the tab should show all the messages
       *  active : if the tab is active when first opening the chat
       *  hidden : if the tab is hidden
       */
      tabs: [{
         label: 'All',
         all: true,
      }, {
         label: 'General',
         active: true,
      }, {
         label: 'Animes',
      }, {
         label: 'Games',
      }, {
         label: 'Illuminati',
         hidden: true,
      }],

Sempre seguindo o padrão:

Código:
{
  label: 'Nome da aba',
}

Parâmetros extras podem ser adicionados à aba, que são:

  • all: true, definindo que a aba é a "Todos".
  • active: true, definindo que a aba é a ativa ao abrir o chat.
  • hidden: true, definindo que a aba é oculta.


Para acessar uma aba oculta, é só utilizar o comando: /ct Nome da aba

---

Quanto aos comandos funcionarem por aba, pelo menos em questão do /clear não é possível no momento. O problema é que até podemos limpá-la enquanto a pessoa está no chat, mas no momento que a página for atualizada, as mensagens voltarão, pois não há como apagarmos as mensagens parcialmente do servidor.

Mas é algo a se pensar. Pensativo
Kyo Panda

Kyo Panda
Hiper Membro

Membro desde : 08/01/2012
Mensagens : 4641
Pontos : 5939

https://ajuda.forumeiros.com

Ir para o topo Ir para baixo

Tópico resolvido Re: Comandos do chatbox com abas

Mensagem por Kyo Panda 17.05.17 20:26

Questão marcada como Resolvida ou o Autor solicitou que ela fosse arquivada.
Tópico marcado como Resolvido e movido para Questões resolvidas.
Kyo Panda

Kyo Panda
Hiper Membro

Membro desde : 08/01/2012
Mensagens : 4641
Pontos : 5939

https://ajuda.forumeiros.com

Ir para o topo Ir para baixo

Ver o tópico anterior Ver o tópico seguinte Ir para o topo

- Tópicos semelhantes

Permissões neste sub-fórum
Não podes responder a tópicos