Здесь делается вжух 🪄

дуэт недели:

Doran Basu x Christian de Clare

постописцы недели:

Xie Lian Aotsuki Eito Severus Snape Sumino Takumi Margaery Tyrell

Asaba Harumasa writes:

Есть те, кто прямо как ты, Хуго: цепляются за маски, стараются держать их на лице безукоризненно и очень грустят, когда те трещат. Никогда не думал о том, что все твои глупые детские выходки уже давно предсказали на много ходов вперёд? Так думал, правда? И как тебе в подушку после плакалось? Ну убьёшь ты его, и что тогда? Что тогда, после смерти? Смерть ведь только начало. Ты ведёшь за руку создание, для которого маска — единственное возможное лицо. Догадываешься, почему? Да, потому что у существ вроде этой грязной твари «лица» нет и быть не может. А ты ведёшься, прямо как ребёнок. А ведь взрослым себя считаешь! Ну вот кто, кто, скажи мне, совершит такую глупость и подойдёт к этой мерзкой образине добровольно? Знаешь, другой ты был умнее хотя бы отчасти и не назвал этому монстру своего имени.

Настроить вид
Шрифт в постах
Яркость фона
Акцентный шрифт
up
down

Promise, not command

Информация о пользователе

Привет, Гость! Войдите или зарегистрируйтесь.


Вы здесь » Promise, not command » THE PERKS OF BEING A WALLFLOWER » *вздох*


*вздох*

Сообщений 1 страница 2 из 2

1

Код:
<!--HTML-->
<link rel="stylesheet" type="text/css" href="https://forumstatic.ru/files/001c/11/e3/52754.css" />

<div id="modao_fd-wrapper">
  <div class="modao_fd-header">
    <img src="https://forumstatic.ru/files/001c/11/e3/43424.svg" class="modao_fd-bg1">
    <img src="https://forumstatic.ru/files/001c/11/e3/32877.png" class="modao_fd-bg2">
  </div>
  <div class="modao_fd-cast">
  </div>
  <div class="modao_fd-events">
    <div class="modao_fd-bg3"></div>
    <ul class="modao_fd-list">
      <li>
        <span>событие/дата</span>
          <a href="ссылка">название эпизода</a>
          <p>Тут чота будет</p>
      </li>
      <li>
        <span>событие/дата</span>
          <p>Тут тоже</p>
      </li>
    </ul>
  </div>
</div>


<script>
(function(){
    const ids = [5, 3, 4, 2];
    const getUrl = id => `${location.origin}/profile.php?id=${id}`;
    
    const i=setInterval(()=>{const c=document.querySelector(".modao_fd-cast");if(!c)return;clearInterval(i),Promise.all(ids.map(d=>fetch(getUrl(d)).then(r=>r.text()).then(h=>({id:d,name:new DOMParser().parseFromString(h,"text/html").querySelector("#profile-name").textContent.trim()})))).then(d=>{d.sort((a,b)=>a.name.localeCompare(b.name)),c.innerHTML=d.map(p=>`<a href="${getUrl(p.id)}" target="_blank"><span>${p.name}</span><i class="modao-ico profile-ico"></i></a>`).join("")})},100);
})();
</script>

hide-autor2

0

2

/*
* jQuery Reveal Plugin 1.0 - Упрощенная версия
* Берем только контент из поста
*/

(function($) {

    $(document).on('click', 'a[data-reveal-id]', function(e) {
        e.preventDefault();
        var modalLocation = $(this).attr('data-reveal-id');
        $('#'+modalLocation).reveal($(this).data());
    });

    $.fn.reveal = function(options) {
       
        var defaults = { 
            animation: 'fadeAndPop',
            animationspeed: 300,
            closeonbackgroundclick: true,
            dismissmodalclass: 'close-reveal-modal'
        };
       
        var options = $.extend({}, defaults, options);
   
        return this.each(function() {
       
            var modal = $(this),
                topMeasure  = parseInt(modal.css('top')),
                topOffset = modal.height() + topMeasure,
                locked = false,
                modalBG = $('.reveal-modal-bg');

            if(modalBG.length == 0) {
                modalBG = $('<div class="reveal-modal-bg" />').insertAfter(modal);
            }           
     
            modal.on('reveal:open', function () {
                modalBG.off('click.modalEvent');
                $('.' + options.dismissmodalclass).off('click.modalEvent');
                if(!locked) {
                    lockModal();
                    if(options.animation == "fadeAndPop") {
                        modal.css({'top': $(document).scrollTop()-topOffset, 'opacity' : 0, 'visibility' : 'visible'});
                        modalBG.fadeIn(options.animationspeed/2);
                        modal.delay(options.animationspeed/2).animate({
                            "top": $(document).scrollTop()+topMeasure + 'px',
                            "opacity" : 1
                        }, options.animationspeed,unlockModal());                   
                    }
                    if(options.animation == "fade") {
                        modal.css({'opacity' : 0, 'visibility' : 'visible', 'top': $(document).scrollTop()+topMeasure});
                        modalBG.fadeIn(options.animationspeed/2);
                        modal.delay(options.animationspeed/2).animate({
                            "opacity" : 1
                        }, options.animationspeed,unlockModal());                   
                    }
                    if(options.animation == "none") {
                        modal.css({'visibility' : 'visible', 'top':$(document).scrollTop()+topMeasure});
                        modalBG.css({"display":"block"});   
                        unlockModal()               
                    }
                }
                modal.off('reveal:open');
            });     

            modal.on('reveal:close', function () {
                if(!locked) {
                    lockModal();
                    if(options.animation == "fadeAndPop") {
                        modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
                        modal.animate({
                            "top":  $(document).scrollTop()-topOffset + 'px',
                            "opacity" : 0
                        }, options.animationspeed/2, function() {
                            modal.css({'top':topMeasure, 'opacity' : 1, 'visibility' : 'hidden'});
                            unlockModal();
                        });                   
                    }   
                    if(options.animation == "fade") {
                        modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
                        modal.animate({
                            "opacity" : 0
                        }, options.animationspeed, function() {
                            modal.css({'opacity' : 1, 'visibility' : 'hidden', 'top' : topMeasure});
                            unlockModal();
                        });                   
                    }   
                    if(options.animation == "none") {
                        modal.css({'visibility' : 'hidden', 'top' : topMeasure});
                        modalBG.css({'display' : 'none'});   
                    }       
                }
                modal.off('reveal:close');
            });     
       
            modal.trigger('reveal:open')
           
            var closeButton = $('.' + options.dismissmodalclass).on('click.modalEvent', function () {
                modal.trigger('reveal:close')
            });
           
            if(options.closeonbackgroundclick) {
                modalBG.css({"cursor":"pointer"})
                modalBG.on('click.modalEvent', function () {
                    modal.trigger('reveal:close')
                });
            }
            $('body').on('keyup', function(e) {
                if(e.which===27){ modal.trigger('reveal:close'); }
            });
           
            function unlockModal() {
                locked = false;
            }
            function lockModal() {
                locked = true;
            }   
           
        });
    };
})(jQuery);

/*---------------------------
СКРИПТ: берем HTML из поста по его ID
Используем логику из того скрипта, но для одного поста
----------------------------*/

// Основная функция загрузки контента
function loadPostContent(postId) {
    console.log('Загрузка поста #' + postId);
   
    // Показываем загрузку
    $('.modal_wrap').html('<div class="loading">Загрузка...</div>');
   
    // 1. Сначала ищем пост на текущей странице (быстро)
    var $post = $('#p' + postId);
   
    if ($post.length > 0) {
        console.log('Пост найден локально');
        var postContent = $post.find('.post-content').html();
       
        if (postContent && postContent.trim() !== '') {
            $('.modal_wrap').html(postContent);
            updateEditLink($post);
            return;
        }
    }
   
    // 2. Поста нет на странице - ищем через AJAX
    console.log('Пост не найден локально, ищем через AJAX');
    findPostById(postId);
}

// Поиск поста по ID через AJAX
// Используем подход из того скрипта, но ищем конкретный пост
function findPostById(postId) {
    // Мы не знаем тему, поэтому пробуем разные подходы
   
    // Подход 1: Прямой URL к посту (часто работает на форумах)
    var url1 = '/viewtopic.php?pid=' + postId + '#p' + postId;
   
    // Подход 2: Попробуем найти тему через поиск
    var url2 = '/search.php?action=findpost&pid=' + postId;
   
    // Подход 3: Если есть API - используем его
    var apiUrl = '/api.php?method=post.get&post_id=' + postId + '&format=json';
   
    // Пробуем последовательно
    tryFindPost(postId, [
        { type: 'direct', url: url1 },
        { type: 'search', url: url2 },
        { type: 'api', url: apiUrl }
    ], 0);
}

// Рекурсивно пробуем разные методы поиска
function tryFindPost(postId, methods, index) {
    if (index >= methods.length) {
        $('.modal_wrap').html('<div class="error">Не удалось найти пост #' + postId + '</div>');
        return;
    }
   
    var method = methods[index];
    console.log('Пробуем метод', method.type, ':', method.url);
   
    $.ajax({
        url: method.url,
        cache: true,
        dataType: method.type === 'api' ? 'json' : 'html',
        timeout: 10000,
        success: function(data) {
            console.log('Успешный ответ от', method.type);
           
            if (method.type === 'api') {
                // Обработка API ответа
                handleApiResponse(data, postId);
            } else {
                // Обработка HTML ответа
                handleHtmlResponse(data, postId, method.type);
            }
        },
        error: function(xhr, status, error) {
            console.log('Ошибка метода', method.type, ':', error);
            // Пробуем следующий метод
            tryFindPost(postId, methods, index + 1);
        }
    });
}

// Обработка HTML ответа (из viewtopic.php или search.php)
function handleHtmlResponse(html, postId, methodType) {
    var $response = $(html);
   
    // Ищем пост по ID
    var $post = $response.find('#p' + postId);
   
    // Если не нашли напрямую, возможно пост - это вся страница
    if ($post.length === 0) {
        $post = $response.filter('#p' + postId);
    }
   
    // Если нашли в search.php, может быть редирект на тему
    if ($post.length === 0 && methodType === 'search') {
        // Ищем ссылку на тему
        var topicLink = $response.find('a[href*="viewtopic.php?id="]').first();
        if (topicLink.length) {
            var href = topicLink.attr('href');
            var topicId = href.match(/viewtopic\.php\?id=(\d+)/)[1];
            if (topicId) {
                // Грузим тему и ищем пост в ней
                loadTopicAndFindPost(topicId, postId);
                return;
            }
        }
    }
   
    if ($post.length > 0) {
        var postContent = $post.find('.post-content').html();
       
        if (postContent && postContent.trim() !== '') {
            $('.modal_wrap').html(postContent);
            updateEditLink($post);
        } else {
            $('.modal_wrap').html('<div class="error">Контент поста пустой</div>');
        }
    } else {
        // Показываем ошибку с предложением открыть вручную
        showPostNotFound(postId);
    }
}

// Обработка API ответа
function handleApiResponse(data, postId) {
    if (data && data.success && data.data && data.data.length > 0) {
        var postData = data.data[0];
        var content = postData.message || postData.content || '';
       
        if (content) {
            $('.modal_wrap').html(content);
            updateEditLinkFromApi(postId);
        } else {
            $('.modal_wrap').html('<div class="error">API вернул пустой контент</div>');
        }
    } else {
        $('.modal_wrap').html('<div class="error">Пост не найден через API</div>');
    }
}

// Загрузка темы и поиск поста в ней
function loadTopicAndFindPost(topicId, postId) {
    console.log('Загружаем тему #' + topicId + ' для поиска поста #' + postId);
   
    $.ajax({
        url: '/viewtopic.php?id=' + topicId,
        cache: true,
        dataType: 'html',
        success: function(html) {
            var $response = $(html);
            var $post = $response.find('#p' + postId);
           
            if ($post.length > 0) {
                var postContent = $post.find('.post-content').html();
                $('.modal_wrap').html(postContent);
                updateEditLink($post);
            } else {
                $('.modal_wrap').html('<div class="error">Пост не найден в теме #' + topicId + '</div>');
            }
        },
        error: function() {
            $('.modal_wrap').html('<div class="error">Ошибка загрузки темы</div>');
        }
    });
}

// Показ сообщения "не найден" со ссылкой
function showPostNotFound(postId) {
    $('.modal_wrap').html(`
        <div class="post-not-found">
            <h3>Пост #${postId} не найден</h3>
            <p>Попробуйте открыть пост напрямую:</p>
            <p><a href="/viewtopic.php?pid=${postId}" target="_blank" class="button">
                Открыть пост #${postId}
            </a></p>
            <p><small>Или пост мог быть удален</small></p>
        </div>
    `);
}

// Обновление ссылки редактирования
function updateEditLink($post) {
    var editLink = $post.find('.pl-edit a').attr('href');
    if (editLink) {
        var editBtn = document.querySelector('.edit-reveal-modal');
        if (editBtn) {
            editBtn.href = editLink;
            editBtn.style.display = 'inline-block';
        }
    }
}

// Обновление ссылки редактирования для API
function updateEditLinkFromApi(postId) {
    var editBtn = document.querySelector('.edit-reveal-modal');
    if (editBtn) {
        editBtn.href = '/edit.php?id=' + postId;
        editBtn.style.display = 'inline-block';
    }
}

// Обработчик кликов по ссылкам с data-post-id
$(document).ready(function() {
    // Клик по ссылкам с data-post-id
    $(document).on('click', '[data-post-id]', function(e) {
        if ($(this).hasClass('modal-link') || $(this).data('post-id')) {
            e.preventDefault();
            var postId = $(this).data('post-id');
            loadPostContent(postId);
            $('#character').reveal();
        }
    });
   
    // Оставляем старый обработчик для совместимости
    $(".modal-link").click(function(e) {
        e.preventDefault();
        var postId = $(this).attr('id') || $(this).data('post-id');
        if (postId) {
            loadPostContent(postId);
            $('#character').reveal();
        }
    });
});

// Добавляем стили
$(document).ready(function() {
    var styles = `
    .loading, .error, .post-not-found {
        text-align: center;
        padding: 40px;
        font-size: 16px;
    }
    .post-not-found .button {
        display: inline-block;
        padding: 10px 20px;
        background: #8c2b2b;
        color: white;
        text-decoration: none;
        border-radius: 3px;
        margin: 10px 0;
    }
    .post-not-found .button:hover {
        background: #a03535;
    }
    `;
   
    $('<style>').text(styles).appendTo('head');
});

0


Вы здесь » Promise, not command » THE PERKS OF BEING A WALLFLOWER » *вздох*


Рейтинг форумов | Создать форум бесплатно