shile4

shile4 

графика, дизайн, верстка

Blog contains AI content

12subscribers

27posts

Showcase and bundles

6
A bundle is a collection, compilation, playlist, or catalog of posts that saves you from searching through the blog and lets you buy the entire content series in a single click.
goals1
$0 of $12.8 raised
на кофеек

Аватар пользователя рядом с ником в цитате

Скрипт выводит актуальный аватар пользователя рядом с ником в цитате 
После установки и первого запуска может быть баг (Множит реакции, рекламу или другие блоки. Профиксить пока не вышло. Баг выстреливает не везде) (помогает принудительная перегрузка страницы (Command + Shift + R на мак, Ctrl + Shift + R на винде).  
- Аватар подтягивает из страницы пользователей.
- Гостям аватар не подставляет.
- С никами на русском тоже работает.  
- Лучше вставлять в хтмл низ после всех скриптов.
- Работает со скриптом "Ссылка на авторский пост в цитате //  Alex_63"
- Не работает со скриптом в котором фигурирует кнопка  "Перейти к сообщению" в цитате. 
- свой аватар для тех пользователей, у которых его нет ( просто меняете ссылку в var CUSTOM_AVATAR = 'https://forumavatars.ru/img/avatars/000f/09/5e/2416-1770827957.jpg'; на свою)
<!-- аватар цитируемого пользователя в цитате -->
<script>
// --- Форсированная перезагрузка один раз --- //
if (!sessionStorage.getItem('forum_script_force_refresh')) {
sessionStorage.setItem('forum_script_force_refresh', '1');
location.reload();
}
// --- url кастомной заглушки --- //
var CUSTOM_AVATAR = 'https://forumavatars.ru/img/avatars/000f/09/5e/2416-1770827957.jpg'; // <-- Место для своей заглушки
var DEFAULT_RUSFF = 'https://forumavatars.ru/i/default_avatar.jpg';
// --- Кодировка win1251 (для никнеймов) --- //
function encodeWin1251(str) {
var arr = [];
for (var i = 0; i < str.length; i++) {
var code = str.charCodeAt(i);
if (code >= 0x410 && code <= 0x44F) arr.push('%' + (code - 848).toString(16));
else if (code == 0x401) arr.push('%A8');
else if (code == 0x451) arr.push('%B8');
else if (code < 128) arr.push(escape(str.charAt(i)));
else arr.push(str.charAt(i));
}
return arr.join('');
}
// --- Аватары в цитатах --- //
function insertAvatars(context) {
$(context).find('.quote-box > cite').not('[data-avatar-processed]').each(function() {
var $cite = $(this);
$cite.attr('data-avatar-processed', '1');
if ($cite.find('.quote-avatar-block').length) return;
var username = '';
var $a = $cite.find('a.qc-post-link');
if ($a.length) {
username = $a.text();
} else {
username = $cite.text();
}
username = username.replace(/\s*написал\(а\)?:?\s*$/i, '').trim();
username = username.replace(/\s+/g, ' ').trim();
if (!username) return;
var insertBeforeElem = $a.length ? $a : $cite.contents().eq(0);
var k = 'ava_actualized_' + username;
var fromCache = localStorage.getItem(k);
function putAvatar(url) {
// ЕСЛИ url == дефолт рсфф, то СТАВИМ твою заглушку!
if (url == DEFAULT_RUSFF) url = CUSTOM_AVATAR;
if ($cite.find('.quote-avatar-block').length) return;
var $avatar = $('<span class="quote-avatar-block"><span class="quote-avatar-img"></span></span>');
$avatar.find('.quote-avatar-img').css('background-image', 'url(' + url + ')');
$avatar.insertBefore(insertBeforeElem);
}
if (fromCache) {
if (fromCache === "null") return;
putAvatar(fromCache);
return;
}
$.get('/userlist.php?username=' + encodeWin1251(username))
.done(function(html) {
var dom = $('<div>').html(html);
var notfound = dom.find('.usertable td.tcl').filter(function () {
return $(this).text().indexOf('ничего не найдено') !== -1;
}).length > 0;
if (notfound) {
localStorage.setItem(k, "null");
return;
}
var url = '';
var em = dom.find('em.user-avatar');
if (em.length) {
var av = em.find('.avatar-image');
if (av.length) {
var bg = av.css('background-image');
var urlMatch = bg && bg.match(/url\(["']?(.+?)["']?\)/);
if (urlMatch && urlMatch[1]) url = urlMatch[1];
}
}
// Если нет своего аватара, url будет равен дефолтному rusff
if (!url) url = DEFAULT_RUSFF;
localStorage.setItem(k, url);
putAvatar(url);
})
.fail(function () {
localStorage.setItem(k, "null");
});
});
}
// --- Вставка реакций с защитой от дублей --- //
function ensureUniqueReactionsRoot(context) {
$(context).find('.post-body').not('[data-reactions-processed]').each(function () {
var $block = $(this);
$block.attr('data-reactions-processed', '1');
var $roots = $block.children('.reactions-root');
if ($roots.length > 1) $roots.not(':first').remove();
if ($block.children('.reactions-root').length === 0) {
$('<div class="reactions-root"></div>').appendTo($block);
}
});
}
// --- Инициализация --- //
$(function () {
insertAvatars(document);
ensureUniqueReactionsRoot(document);
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
mutation.addedNodes.forEach(function (node) {
if (node.nodeType !== 1) return;
if (node.classList && node.classList.contains('post-body')) {
ensureUniqueReactionsRoot(node);
} else if ($(node).find('.post-body').length) {
ensureUniqueReactionsRoot(node);
}
if (node.classList && node.classList.contains('quote-box')) {
insertAvatars(node);
} else if ($(node).find('.quote-box').length) {
insertAvatars(node);
}
});
});
});
observer.observe(document.body, { childList: true, subtree: true });
});
</script>
И настройка стиля (можно под скриптом в хтмл низ) или в свой стиль в цвета (тогда <style> и </style> удалить)
<style>
.quote-avatar-block {
margin-right: 8px;
display: inline-block;
vertical-align: middle;
}
.quote-avatar-img {
display: inline-block;
width: 32px;
height: 32px;
border-radius: 50%;
background-size: cover;
background-position: center;
}
</style>
Go up