Icones em ajax

2 participantes

Ir para baixo

Tópico em curso Icones em ajax

Mensagem por Sousaph29 09.09.24 23:01

Detalhes da questão


Endereço do fórum: https://brasilexperiencelife.forumeiros.com/
Versão do fórum: ModernBB

Descrição


Código:
/*globals jQuery, FA, _userdata*/
 
/**
* Alterar o ícone do tópico com AJAX.
*
* @author Luiz
*
* Modificação por RafaelS. restringir botões aos fóruns
* https://ajuda.forumeiros.com/
*
* @version 1.2
* @licence MIT
*/
 
(function($) {
'use strict';
 
var config = [{
  name: 'Resolvido',
  id: 1,
  background: '#1c6b1c',
  allowedGroups: [6, 2, 7],
  forum: 14
  },
  {
  name: 'Em Curso',
  id: 6,
  background: '#daa520',
  allowedGroups: [6, 2, 7],
  forum: 14
  },
  {
  name: 'Importante',
  id: 4,
  background: '#ffb300',
  allowedGroups: [6, 2, 7],
  forum: 14 
  },
  {
  name: 'Aceito',
  id: 9,
  background: '#8c648c',
  allowedGroups: [6, 2, 7],
  forum: 14
  },
  {
  name: 'Recusado',
  id: 2,
  background: '#de5757',
  allowedGroups: [6, 2, 7],
  forum: 14
  },
  {
  name: 'Banido',
  id: 7,
  background: '#ff0000',
  allowedGroups: [6, 2, 7],
  forum: 14
  },
  {           
  name: 'Desbanido',
  id: 8,
  background: '#00a651',
  allowedGroups: [6, 2, 7],
  forum: 14
  },
  {           
  name: 'Tutorial',
  id: 8,
  background: '#8db3ff',
  allowedGroups: [6, 2, 7],
  forum: 14
  },
  {           
  name: 'Regras',
  id: 3,
  background: '#857f7e',
  allowedGroups: [6, 2, 7],    
  forum: 14
  }
 ];
 
window.FA = window.FA || {};
FA.Topic = FA.Topic || {};
 
var MarkIcon;
FA.Topic.MarkIcon = MarkIcon = function(config) {
 var self = this;
 
    self.userConfig = config;
    self.defaults = {
      name: undefined,
      id: undefined,
      background: undefined,
      allowedGroups: [],
      forum: undefined,
    };
 
 self.config = $.extend({}, self.defaults, self.userConfig);
 
 $.each(self.config, function(key, value) {
 if (key === undefined) {
  throw new Error('[Topic Icons] The ' + key + ' key was not specified in the script config.');
 }
 
 if (value === undefined) {
  throw new Error('[Topic Icons] The ' + value + ' value was not specified in the settings.');
 }
 });
};
 
MarkIcon.prototype.init = function() {
 var self = this;
 
 var $post = $('.post[id*="p"]:first, [id*="post-"].post-wrap:first');
 var $link = $post.find('a[href$="mode=editpost"]');
 
 if (!$link.length) {
 return false;
 }
 
  // Verificar se o usuário pertence a um dos grupos permitidos
    if (!self.config.allowedGroups.includes(_userdata.user_level)) {
      return false;
    }
 
 var atual = $('.sub-header-path a:last').attr("href");
 console.log("Forum detection by RafaelS.");
 if (atual.indexOf("f" + this.config.forum + "-") < 0) {
 console.log("O ícone " + this - config.name + " não está disponível no fórum: " + atual);
 return false;
 }
 
 self.messageLink = $link.attr('href');
 
 self.$button = $('<button>', {
 'class': 'fa-mark-icon-button',
 'data-id': self.config.id,
 'text': self.config.name
 });
 
 self.$button
 .css('background-color', self.config.background)
 .on('click', function(event) {
  event.preventDefault();
 
  self.runAjax();
 })
 .insertBefore($post);
 
 self.appendStyles();
};
 
MarkIcon.prototype.runAjax = function() {
 var self = this;
 
 self.changeText('<i class="fa fa-refresh fa-spin"></i> Carregando...');
 
 $.get(self.messageLink)
 .done(function(context) {
  var $form = $('form[action="/post"]', context);
 
  var encode = document.charset.toLowerCase() === 'utf-8' ? window.encodeURIComponent : window.escape;
 
  var formData = $form.serializeArray();
 
  var data = {};
  $.each(formData, function() {
  var obj = this;
 
  data[obj.name] = obj.value;
  });
 
  data.post_icon = self.config.id;
  data.post = 1;
 
  var encoded = $.map(data, function(value, key) {
  return key + '=' + encode(value);
  }).join('&');
 
  $.post(self.messageLink, encoded)
  .done(self.changeText('<i class="fa fa-check"></i> Feito!'))
  .fail(self.error);
 })
 .fail(self.error);
};
 
MarkIcon.prototype.changeText = function(text) {
 var self = this;
 
 self.runAjax = function() {
 return false;
 };
 
 self.$button
 .html(text)
 .prop('disabled', true);
};
 
MarkIcon.prototype.error = function() {
 alert([
 '[Topic Icons] AJAX Error.',
 'Refresh the page and try again.'
 ].join('\n'));
};
 
MarkIcon.prototype.appendStyles = function() {
 $('<style>', {
 'text': [
    '.fa-mark-icon-button {',
    '  padding: 8px 8px 8px 8px;',
    '  border: none;',
    '  color: #fff;',
    '  margin: 10px 0 10px 6px;',
    '  box-shadow: inset 0 0 0 3px rgba(0, 0, 0, 0.08);',
    '  border-radius: 3px;',
    '}'
  ].join('\n')
 }).appendTo('head');
};
 
$(function() {
 $.each(config, function() {
 var self = this;
 
  $(document).ready(function() {
    $.each(config, function(index, iconConfig) {
      var icon = new MarkIcon(iconConfig);
      icon.init();
}(jQuery));


consegui modificar o código óriginal pois eu gostaria de privar para outros grupos os icones, não apénas para mod e admin. gostaria que corrigissem esse código pois ele não funciona, a inteligencia artificial me passou ele assim!

E gostaria que corrigissem também, só posso colocar em um fórum. gostaria que os icones aparecessem todos em quantos fóruns eu quiser!

esse é o código original:
Código:
/*globals jQuery, FA, _userdata*/
 
/**
* Alterar o ícone do tópico com AJAX.
*
* @author Luiz
*
* Modificação por RafaelS. restringir botões aos fóruns
* https://ajuda.forumeiros.com/
*
* @version 1.2
* @licence MIT
*/
 
(function($) {
'use strict';
 
var config = [{
  name: 'Resolvido',
  id: 1,
  background: '#1c6b1c',
  onlyForMod: true,
  forum: 14
  },
  {
  name: 'Em Curso',
  id: 6,
  background: '#daa520',
  onlyForMod: true, 
  forum: 14
  },
  {
  name: 'Importante',
  id: 4,
  background: '#ffb300',
  onlyForMod: true,
  forum: 14 
  },
  {
  name: 'Aceito',
  id: 9,
  background: '#8c648c',
  onlyForMod: true,
  forum: 14
  },
  {
  name: 'Recusado',
  id: 2,
  background: '#de5757',
  onlyForMod: true,
  forum: 14
  },
  {
  name: 'Banido',
  id: 7,
  background: '#ff0000',
  onlyForMod: true,
  forum: 14
  },
  {           
  name: 'Desbanido',
  id: 8,
  background: '#00a651',
  onlyForMod: true,
  forum: 14
  },
  {           
  name: 'Tutorial',
  id: 8,
  background: '#8db3ff',
  onlyForMod: true,
  forum: 14
  },
  {           
  name: 'Regras',
  id: 3,
  background: '#857f7e',
  onlyForMod: true,
  forum: 14
  }
 ];
 
window.FA = window.FA || {};
FA.Topic = FA.Topic || {};
 
var MarkIcon;
FA.Topic.MarkIcon = MarkIcon = function(config) {
 var self = this;
 
 self.userConfig = config;
 self.defaults = {
 name: undefined,
 id: undefined,
 background: undefined,
 onlyForMod: false,
 onlyForAdmin: false,
 forum: undefined,
 };
 
 self.config = $.extend({}, self.defaults, self.userConfig);
 
 $.each(self.config, function(key, value) {
 if (key === undefined) {
  throw new Error('[Topic Icons] The ' + key + ' key was not specified in the script config.');
 }
 
 if (value === undefined) {
  throw new Error('[Topic Icons] The ' + value + ' value was not specified in the settings.');
 }
 });
};
 
MarkIcon.prototype.init = function() {
 var self = this;
 
 var $post = $('.post[id*="p"]:first, [id*="post-"].post-wrap:first');
 var $link = $post.find('a[href$="mode=editpost"]');
 
 if (!$link.length) {
 return false;
 }
 
 if (this.config.onlyForMod && (_userdata.user_level !== 1 && _userdata.user_level !== 2)) {
 return false;
 }
 
 if (this.config.onlyForAdmin && _userdata.user_level !== 1) {
 return false;
 }
 var atual = $('.sub-header-path a:last').attr("href");
 console.log("Forum detection by RafaelS.");
 if (atual.indexOf("f" + this.config.forum + "-") < 0) {
 console.log("O ícone " + this - config.name + " não está disponível no fórum: " + atual);
 return false;
 }
 
 self.messageLink = $link.attr('href');
 
 self.$button = $('<button>', {
 'class': 'fa-mark-icon-button',
 'data-id': self.config.id,
 'text': self.config.name
 });
 
 self.$button
 .css('background-color', self.config.background)
 .on('click', function(event) {
  event.preventDefault();
 
  self.runAjax();
 })
 .insertBefore($post);
 
 self.appendStyles();
};
 
MarkIcon.prototype.runAjax = function() {
 var self = this;
 
 self.changeText('<i class="fa fa-refresh fa-spin"></i> Carregando...');
 
 $.get(self.messageLink)
 .done(function(context) {
  var $form = $('form[action="/post"]', context);
 
  var encode = document.charset.toLowerCase() === 'utf-8' ? window.encodeURIComponent : window.escape;
 
  var formData = $form.serializeArray();
 
  var data = {};
  $.each(formData, function() {
  var obj = this;
 
  data[obj.name] = obj.value;
  });
 
  data.post_icon = self.config.id;
  data.post = 1;
 
  var encoded = $.map(data, function(value, key) {
  return key + '=' + encode(value);
  }).join('&');
 
  $.post(self.messageLink, encoded)
  .done(self.changeText('<i class="fa fa-check"></i> Feito!'))
  .fail(self.error);
 })
 .fail(self.error);
};
 
MarkIcon.prototype.changeText = function(text) {
 var self = this;
 
 self.runAjax = function() {
 return false;
 };
 
 self.$button
 .html(text)
 .prop('disabled', true);
};
 
MarkIcon.prototype.error = function() {
 alert([
 '[Topic Icons] AJAX Error.',
 'Refresh the page and try again.'
 ].join('\n'));
};
 
MarkIcon.prototype.appendStyles = function() {
 $('<style>', {
 'text': [
    '.fa-mark-icon-button {',
    '  padding: 8px 8px 8px 8px;',
    '  border: none;',
    '  color: #fff;',
    '  margin: 10px 0 10px 6px;',
    '  box-shadow: inset 0 0 0 3px rgba(0, 0, 0, 0.08);',
    '  border-radius: 3px;',
    '}'
  ].join('\n')
 }).appendTo('head');
};
 
$(function() {
 $.each(config, function() {
 var self = this;
 
 (new FA.Topic.MarkIcon(self)).init();
 });
});
}(jQuery));
Sousaph29
Sousaph29
***

Membro desde : 16/09/2018
Mensagens : 137
Pontos : 224

https://brasilexperiencelife.forumeiros.com

Ir para o topo Ir para baixo

Tópico em curso Re: Icones em ajax

Mensagem por Sousaph29 11.09.24 23:22

uppppppppppppppppppppppppppppppppppppppppppppppppppppp
Sousaph29
Sousaph29
***

Membro desde : 16/09/2018
Mensagens : 137
Pontos : 224

https://brasilexperiencelife.forumeiros.com

Ir para o topo Ir para baixo

Tópico em curso Re: Icones em ajax

Mensagem por Sousaph29 15.09.24 19:09

Uppppp
Sousaph29
Sousaph29
***

Membro desde : 16/09/2018
Mensagens : 137
Pontos : 224

https://brasilexperiencelife.forumeiros.com

Ir para o topo Ir para baixo

Tópico em curso Re: Icones em ajax

Mensagem por Sousaph29 17.09.24 9:12

Uppppppppppp ajuda ae na moral 😔
Sousaph29
Sousaph29
***

Membro desde : 16/09/2018
Mensagens : 137
Pontos : 224

https://brasilexperiencelife.forumeiros.com

Ir para o topo Ir para baixo

Tópico em curso Re: Icones em ajax

Mensagem por Sousaph29 Ontem à(s) 11:37

up up upup
Sousaph29
Sousaph29
***

Membro desde : 16/09/2018
Mensagens : 137
Pontos : 224

https://brasilexperiencelife.forumeiros.com

Ir para o topo Ir para baixo

Tópico em curso Re: Icones em ajax

Mensagem por Sleep Hoje à(s) 14:57

Boas @'Sousaph29',

Substitui o teu codigo por:
Código:
/*globals jQuery, FA, _userdata*/

/**
* Alterar o ícone do tópico com AJAX.
*
* @author Luiz
* Modificação por RafaelS.
*
* @version 1.3
* @licence MIT
*/

(function($) {
'use strict';

var config = [{
    name: 'Resolvido',
    id: 1,
    background: '#1c6b1c',
    allowedGroups: [6, 2, 7],  // Adicione IDs de grupos aqui
    forums: [14, 15, 16]      // Lista de IDs de fóruns onde o ícone deve aparecer
  },
  {
    name: 'Em Curso',
    id: 6,
    background: '#daa520',
    allowedGroups: [6, 2, 7],
    forums: [14, 15, 16]
  },
  {
    name: 'Importante',
    id: 4,
    background: '#ffb300',
    allowedGroups: [6, 2, 7],
    forums: [14, 15, 16]
  },
  {
    name: 'Aceito',
    id: 9,
    background: '#8c648c',
    allowedGroups: [6, 2, 7],
    forums: [14, 15, 16]
  },
  {
    name: 'Recusado',
    id: 2,
    background: '#de5757',
    allowedGroups: [6, 2, 7],
    forums: [14, 15, 16]
  },
  {
    name: 'Banido',
    id: 7,
    background: '#ff0000',
    allowedGroups: [6, 2, 7],
    forums: [14, 15, 16]
  },
  {         
    name: 'Desbanido',
    id: 8,
    background: '#00a651',
    allowedGroups: [6, 2, 7],
    forums: [14, 15, 16]
  },
  {         
    name: 'Tutorial',
    id: 8,
    background: '#8db3ff',
    allowedGroups: [6, 2, 7],
    forums: [14, 15, 16]
  },
  {         
    name: 'Regras',
    id: 3,
    background: '#857f7e',
    allowedGroups: [6, 2, 7],
    forums: [14, 15, 16]
  }
];

window.FA = window.FA || {};
FA.Topic = FA.Topic || {};

var MarkIcon;
FA.Topic.MarkIcon = MarkIcon = function(config) {
    var self = this;

    self.userConfig = config;
    self.defaults = {
      name: undefined,
      id: undefined,
      background: undefined,
      allowedGroups: [],
      forums: []
    };

    self.config = $.extend({}, self.defaults, self.userConfig);

    $.each(self.config, function(key, value) {
        if (value === undefined) {
            throw new Error('[Topic Icons] O valor da chave ' + key + ' não foi especificado no script.');
        }
    });
};

MarkIcon.prototype.init = function() {
    var self = this;

    var $post = $('.post[id*="p"]:first, [id*="post-"].post-wrap:first');
    var $link = $post.find('a[href$="mode=editpost"]');

    if (!$link.length) {
        return false;
    }

    // Verificar se o usuário pertence a um dos grupos permitidos
    if (!self.config.allowedGroups.includes(_userdata.user_level)) {
        return false;
    }

    var atual = $('.sub-header-path a:last').attr("href");

    console.log("Forum detection by RafaelS.");
    var forumMatch = self.config.forums.some(function(forumId) {
        return atual.indexOf("f" + forumId + "-") >= 0;
    });

    if (!forumMatch) {
        console.log("O ícone " + this.config.name + " não está disponível neste fórum: " + atual);
        return false;
    }

    self.messageLink = $link.attr('href');

    self.$button = $('<button>', {
        'class': 'fa-mark-icon-button',
        'data-id': self.config.id,
        'text': self.config.name
    });

    self.$button
        .css('background-color', self.config.background)
        .on('click', function(event) {
            event.preventDefault();
            self.runAjax();
        })
        .insertBefore($post);

    self.appendStyles();
};

MarkIcon.prototype.runAjax = function() {
    var self = this;

    self.changeText('<i class="fa fa-refresh fa-spin"></i> Carregando...');

    $.get(self.messageLink)
        .done(function(context) {
            var $form = $('form[action="/post"]', context);

            var encode = document.charset.toLowerCase() === 'utf-8' ? window.encodeURIComponent : window.escape;

            var formData = $form.serializeArray();

            var data = {};
            $.each(formData, function() {
                var obj = this;
                data[obj.name] = obj.value;
            });

            data.post_icon = self.config.id;
            data.post = 1;

            var encoded = $.map(data, function(value, key) {
                return key + '=' + encode(value);
            }).join('&');

            $.post(self.messageLink, encoded)
                .done(self.changeText('<i class="fa fa-check"></i> Feito!'))
                .fail(self.error);
        })
        .fail(self.error);
};

MarkIcon.prototype.changeText = function(text) {
    var self = this;

    self.runAjax = function() {
        return false;
    };

    self.$button
        .html(text)
        .prop('disabled', true);
};

MarkIcon.prototype.error = function() {
    alert('[Topic Icons] Erro AJAX. Atualize a página e tente novamente.');
};

MarkIcon.prototype.appendStyles = function() {
    $('<style>', {
        'text': [
            '.fa-mark-icon-button {',
            '  padding: 8px;',
            '  border: none;',
            '  color: #fff;',
            '  margin: 10px 0 10px 6px;',
            '  box-shadow: inset 0 0 0 3px rgba(0, 0, 0, 0.08);',
            '  border-radius: 3px;',
            '}'
        ].join('\n')
    }).appendTo('head');
};

$(function() {
    $.each(config, function() {
        var self = this;
        (new FA.Topic.MarkIcon(self)).init();
    });
});
}(jQuery));

Atenciosamente,
Sleep
Sleep
Sleep
Ajudeiro
Ajudeiro

Membro desde : 10/08/2012
Mensagens : 1112
Pontos : 1343

https://ajuda.forumeiros.com/

Ir para o topo Ir para baixo

Ir para o topo

- Tópicos semelhantes

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