2ch tree post

try to take over the world!

Från och med 2020-11-02. Se den senaste versionen.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         2ch tree post
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  try to take over the world!
// @author       You
// @match        http://2ch.hk/*/res/*
// @match        https://2ch.hk/*/res/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
window.onload = function () {
  const post = document.querySelectorAll('.thread > .thread__post');
  //функцию вызываем на все посты в треде и рекурсионно на все ответы на пост
  //Создаёт контейнер для дерева, куда попадают все ответы на пост
  function movePost(node) {
    const idReply = node.querySelector('.post__refmap').textContent.match(/\d+?\s/g);
    //Проверка на существование ответов на пост.
    //Если ответов нет, то собственный контейнер ненужен
    if (!idReply) {
      return;
    }
    //создаём контейнер для дерева
    const tree = document.createElement('div');
    tree.className = `container-${node.id}`;
    tree.style['border-left'] = '2px dashed';
    tree.style['padding-left'] = '2px';
    tree.style['margin-left'] = '21px';
    //перемещаем контейнер после поста
    node.after(tree);

    //цикл перебора ответов в посте
    for (let i = 0; i < idReply.length; i++) {
      //селектор ответа поста
      const replyPost = document.querySelector(`#post-${idReply[i]}`);
      //добавляем пост в дерево
      tree.append(replyPost);
      //вызываем рекурсию
      movePost(replyPost);
    }
  }

  for (let i = 0; i < post.length; i++) {
    //проверка на положение элемента. Если его уже переместили в контейнер
    //то обрабатываем следующий
    if (post[i].parentElement.className === 'thread') {
      movePost(post[i]);
    }
  }

  //функция для новых постов
  function newPostMove(node) {
    //ищём ссылки в посте, кроме ОП-поста
    const opNumber = document.querySelector('.post.post_type_oppost [data-num]').innerText;
    const postMessage = node.querySelectorAll(
      `.post__message > [data-num]:not([data-num="${opNumber}"])`
    );
    //есть ли ссылки в посте?
    if (!postMessage) {
      return;
    }
    for (let i = 0; i < postMessage.length; i++) {
      const container = document.querySelector(
        `.container-post-${postMessage[i].innerText.match(/\d+/)[0]}`
      );
      //создан ли уже контейнер дерева?
      if (container) {
        return container.append(node);
      }
      //если нет, создаём
      const linkPost = document.querySelector(`#post-${postMessage[i].innerText.match(/\d+/)[0]}`);
      const tree = document.createElement('div');
      tree.className = `container-${linkPost.id}`;
      tree.style['border-left'] = '2px dashed';
      tree.style['padding-left'] = '2px';
      tree.style['margin-left'] = '21px';
      //перемещаем контейнер после поста
      linkPost.after(tree);
      //перемещаем пост в котейнер
      tree.append(node);
    }
  }
  //наблюдаем за появлением новых постов
  const fromThreads = document.querySelector('.thread');

  const observer = new MutationObserver((mutationRecords) => {
    for (const key of mutationRecords) {
      if (key.addedNodes.length > 0) {
        newPostMove(key.addedNodes[0]);
      }
    }
  });
  observer.observe(fromThreads, { childList: true });
};
})();