☰

Lezhin ES - Middle Click New Tab

Open Lezhin works and episodes in a new tab with the middle mouse button.

이 스크립트를 설치하려면 Tampermonkey, Greasemonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램을 먼저 설치해야 합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Userscripts와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 유저 스크립트 관리자 확장 프로그램이 필요합니다.

(이미 유저 스크립트 관리자가 설치되어 있습니다. 설치를 진행합니다!)

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

(이미 유저 스타일 관리자가 설치되어 있습니다. 설치를 진행합니다!)

// ==UserScript==
// @name         Lezhin ES - Middle Click New Tab
// @namespace    jack.lezhin.middleclick
// @version      16.1.0
// @description  Open Lezhin works and episodes in a new tab with the middle mouse button.
// @match        https://www.lezhin.es/*
// @match        https://lezhin.es/*
// @run-at       document-start
// @grant        none
// @license      MIT
// ==/UserScript==

(function () {
    'use strict';

    const API_PREFIX = '/api/balcony-api-v2/contents/';
    const RELAY_PARAM = '__jack_lz_middle_v161';
    const MAX_PARENT_DEPTH = 14;
    const RELAY_TIMEOUT = 12000;

    const comicPromises = new Map();
    const comicData = new Map();

    let pendingAction = null;

    // Dentro del lector no intervenir.
    if (/^\/viewer(?:\/|$)/i.test(location.pathname)) return;

    function normalize(value) {
        return String(value || '')
            .replace(/\s+/g, ' ')
            .trim()
            .toLocaleLowerCase('es');
    }

    function textOf(element) {
        return String(element?.innerText || element?.textContent || '')
            .replace(/\s+/g, ' ')
            .trim();
    }

    function linesOf(element) {
        return String(element?.innerText || '')
            .split(/\n+/)
            .map(line => line.replace(/\s+/g, ' ').trim())
            .filter(Boolean);
    }

    function isDetailPage() {
        return /^\/detail(?:\/|$)/i.test(location.pathname);
    }

    function isLibraryPage() {
        return /^\/my\/library(?:\/|$)/i.test(location.pathname);
    }

    function currentDetailSlug() {
        const match = location.pathname.match(
            /^\/detail\/([^/?#]+)\/?$/i
        );

        return match
            ? decodeURIComponent(match[1])
            : null;
    }

    function validHttpUrl(value) {
        if (
            !value ||
            /^\s*(?:javascript:|#\s*$)/i.test(String(value))
        ) {
            return null;
        }

        try {
            const url = new URL(
                String(value),
                location.href
            );

            return /^https?:$/i.test(url.protocol)
                ? url.href
                : null;

        } catch (_) {
            return null;
        }
    }

    function sameOriginRoute(value, type) {
        const href = validHttpUrl(value);

        if (!href) return null;

        try {
            const url = new URL(href);

            if (url.origin !== location.origin) {
                return null;
            }

            const regex =
                type === 'viewer'
                    ? /^\/viewer\//i
                    : /^\/detail\//i;

            return regex.test(url.pathname)
                ? url.href
                : null;

        } catch (_) {
            return null;
        }
    }

    function stopMiddleEvent(event) {
        event.preventDefault();
        event.stopPropagation();
        event.stopImmediatePropagation();
    }

    function chapterLike(text) {
        return /\b(?:CAP(?:Í|I)?TULO|CAP|EPISODE|EPISODIO|CHAPTER|EPÍLOGO|EPILOGO|PRÓLOGO|PROLOGO|NOTA DEL AUTOR)\b/i
            .test(text || '');
    }

    function getImageSource(element) {
        if (!(element instanceof Element)) {
            return '';
        }

        const img =
            element.matches('img')
                ? element
                : element.querySelector('img');

        if (!img) return '';

        const raw =
            img.currentSrc ||
            img.getAttribute('src') ||
            img.getAttribute('data-src') ||
            img.getAttribute('data-original') ||
            '';

        if (!raw) return '';

        try {
            return new URL(
                raw,
                location.href
            ).href;

        } catch (_) {
            return raw;
        }
    }

    // ============================================================
    // API DE LEZHIN ES
    // ============================================================

    function fetchComic(slug) {
        if (!slug) {
            return Promise.resolve(null);
        }

        if (comicPromises.has(slug)) {
            return comicPromises.get(slug);
        }

        const promise = fetch(
            API_PREFIX +
            encodeURIComponent(slug) +
            '?isNotLoginAdult=false',
            {
                credentials: 'include',

                headers: {
                    accept: 'application/json',
                    'x-balcony-id': 'LEZHIN_ES',
                    'x-platform': 'WEB'
                }
            }
        )
            .then(response => {
                if (!response.ok) {
                    throw new Error(
                        `HTTP ${response.status}`
                    );
                }

                return response.json();
            })

            .then(json => {
                comicData.set(
                    slug,
                    json
                );

                return json;
            })

            .catch(error => {
                console.warn(
                    '[Lezhin Middle Click] API error:',
                    error
                );

                comicData.set(
                    slug,
                    null
                );

                return null;
            });

        comicPromises.set(
            slug,
            promise
        );

        return promise;
    }

    function warmCurrentDetail() {
        const slug =
            currentDetailSlug();

        if (slug) {
            fetchComic(slug);
        }
    }

    // Una sola petición asíncrona.
    warmCurrentDetail();

    // Detectar navegación interna de Lezhin sin observar todo el DOM.
    const originalPushState =
        history.pushState;

    history.pushState =
        function (...args) {
            const result =
                originalPushState.apply(
                    this,
                    args
                );

            queueMicrotask(
                warmCurrentDetail
            );

            return result;
        };

    const originalReplaceState =
        history.replaceState;

    history.replaceState =
        function (...args) {
            const result =
                originalReplaceState.apply(
                    this,
                    args
                );

            queueMicrotask(
                warmCurrentDetail
            );

            return result;
        };

    window.addEventListener(
        'popstate',
        () =>
            queueMicrotask(
                warmCurrentDetail
            )
    );

    // ============================================================
    // CAPÍTULOS
    // ============================================================

    function findEpisodeCard(target) {
        if (
            !isDetailPage() ||
            !(target instanceof Element)
        ) {
            return null;
        }

        let element =
            target;

        let fallback =
            null;

        for (
            let depth = 0;
            element &&
            depth < MAX_PARENT_DEPTH;
            depth++,
            element = element.parentElement
        ) {
            const text =
                textOf(element);

            if (
                !text ||
                text.length > 1200 ||
                !chapterLike(text)
            ) {
                continue;
            }

            fallback =
                element;

            const hasImage =
                Boolean(
                    element.querySelector(
                        'img, picture'
                    )
                );

            const hasDate =
                /\b\d{2}\.\d{2}\.\d{4}\b/
                    .test(text);

            if (
                hasImage &&
                hasDate
            ) {
                return element;
            }
        }

        return fallback;
    }

    function episodeFingerprint(card) {
        const lines =
            linesOf(card);

        const title =
            lines.find(
                chapterLike
            )
            ||
            lines[0]
            ||
            '';

        const fullText =
            textOf(card);

        const date =
            fullText.match(
                /\b\d{2}\.\d{2}\.\d{4}\b/
            )?.[0]
            ||
            '';

        return {
            title,
            titleNormalized:
                normalize(title),
            date,
            image:
                getImageSource(card)
        };
    }

    function apiEpisodes(json) {
        const candidates = [
            json?.data?.episodes,
            json?.episodes,
            json?.data?.episodeList
        ];

        return (
            candidates.find(
                Array.isArray
            )
            ||
            []
        );
    }

    function episodeLabels(episode) {
        return [
            episode?.title,
            episode?.displayName,
            episode?.name,
            episode?.display?.displayName,
            episode?.display?.title
        ]
            .filter(
                value =>
                    typeof value === 'string' &&
                    value.trim()
            )
            .map(normalize);
    }

    function viewerUrlFromApiData(
        card,
        json
    ) {
        const slug =
            currentDetailSlug();

        if (
            !slug ||
            !json
        ) {
            return null;
        }

        const fp =
            episodeFingerprint(card);

        const episodes =
            apiEpisodes(json);

        if (!episodes.length) {
            return null;
        }

        // Coincidencia exacta por título.
        let matches =
            episodes.filter(
                episode =>
                    episodeLabels(
                        episode
                    )
                        .some(
                            label =>
                                label ===
                                fp.titleNormalized
                        )
            );

        // Respaldo, solo si deja exactamente un resultado.
        if (matches.length !== 1) {
            const loose =
                episodes.filter(
                    episode =>
                        episodeLabels(
                            episode
                        )
                            .some(
                                label =>
                                    label &&
                                    fp.titleNormalized &&
                                    (
                                        label.includes(
                                            fp.titleNormalized
                                        )
                                        ||
                                        fp.titleNormalized.includes(
                                            label
                                        )
                                    )
                            )
                );

            if (loose.length === 1) {
                matches =
                    loose;
            }
        }

        if (matches.length !== 1) {
            console.debug(
                '[Lezhin Middle Click] No se pudo identificar un episodio único:',
                fp,
                matches
            );

            return null;
        }

        const episode =
            matches[0];

        const alias =
            episode?.alias;

        if (
            alias === undefined ||
            alias === null ||
            String(alias).trim() === ''
        ) {
            return null;
        }

        console.debug(
            '[Lezhin Middle Click]',
            fp.title,
            '=> alias:',
            alias
        );

        return (
            `${location.origin}/viewer/` +
            `${encodeURIComponent(slug)}/` +
            `${encodeURIComponent(String(alias))}`
        );
    }

    // ============================================================
    // URLS REALES EN EL HTML
    // ============================================================

    function directRouteInside(
        element,
        type
    ) {
        if (
            !(element instanceof Element)
        ) {
            return null;
        }

        const selector =
            type === 'viewer'
                ? 'a[href*="/viewer/"]'
                : 'a[href*="/detail/"]';

        const anchor =
            element.closest?.(
                selector
            )
            ||
            element.querySelector?.(
                selector
            );

        if (anchor) {
            const route =
                sameOriginRoute(
                    anchor.getAttribute(
                        'href'
                    ),
                    type
                );

            if (route) {
                return route;
            }
        }

        const attributes = [
            'href',
            'data-href',
            'data-url',
            'data-link',
            'data-path',
            'data-route',
            'data-to',
            'data-target-url'
        ];

        const nodes = [
            element,

            ...element.querySelectorAll(
                '[href],' +
                '[data-href],' +
                '[data-url],' +
                '[data-link],' +
                '[data-path],' +
                '[data-route],' +
                '[data-to],' +
                '[data-target-url]'
            )
        ];

        for (const node of nodes) {
            for (
                const attribute
                of attributes
            ) {
                const route =
                    sameOriginRoute(
                        node.getAttribute?.(
                            attribute
                        ),
                        type
                    );

                if (route) {
                    return route;
                }
            }
        }

        return null;
    }

    // ============================================================
    // RESPALDO PARA CAPÍTULOS NORMALES
    // ============================================================

    function standardChapterFallback(card) {
        const slug =
            currentDetailSlug();

        if (!slug) {
            return null;
        }

        const title =
            episodeFingerprint(
                card
            ).title;

        /*
         * Solo:
         *
         * CAP 1
         * CAP 7
         * CAP 36
         *
         * Nunca CAP Extra.
         */

        const match =
            title.match(
                /^CAP(?:ÍTULO)?\.?\s*#?\s*(\d+)\b/i
            );

        if (!match) {
            return null;
        }

        return (
            `${location.origin}/viewer/` +
            `${encodeURIComponent(slug)}/` +
            `${Number(match[1])}`
        );
    }

    function resolveEpisodeSync(card) {
        const direct =
            directRouteInside(
                card,
                'viewer'
            );

        if (direct) {
            return direct;
        }

        const slug =
            currentDetailSlug();

        const cached =
            slug
                ? comicData.get(slug)
                : null;

        const apiUrl =
            viewerUrlFromApiData(
                card,
                cached
            );

        if (apiUrl) {
            return apiUrl;
        }

        return standardChapterFallback(
            card
        );
    }

    async function resolveEpisodeAsync(card) {
        const immediate =
            resolveEpisodeSync(card);

        if (immediate) {
            return immediate;
        }

        const slug =
            currentDetailSlug();

        if (!slug) {
            return null;
        }

        const json =
            await fetchComic(slug);

        return viewerUrlFromApiData(
            card,
            json
        );
    }

    // ============================================================
    // BIBLIOTECA
    // ============================================================

    function findLibraryCard(target) {
        if (
            !isLibraryPage() ||
            !(target instanceof Element)
        ) {
            return null;
        }

        let element =
            target;

        let fallback =
            null;

        for (
            let depth = 0;
            element &&
            depth < MAX_PARENT_DEPTH;
            depth++,
            element = element.parentElement
        ) {
            const text =
                textOf(element);

            if (
                !text ||
                text.length > 950
            ) {
                continue;
            }

            if (
                element
                    .querySelectorAll(
                        'img'
                    )
                    .length !== 1
            ) {
                continue;
            }

            const hasProgress =
                /\b\d{1,3}\s*%\b/
                    .test(text);

            const hasAction =
                /\b(?:Completar|Continuar|Leer|Completado)\b/i
                    .test(text);

            if (
                !hasProgress &&
                !hasAction
            ) {
                continue;
            }

            fallback =
                element;

            if (
                text.length < 500
            ) {
                return element;
            }
        }

        return fallback;
    }

    // ============================================================
    // OBRAS EN OTRAS LISTAS
    // ============================================================

    function findGenericWorkCard(target) {
        if (
            !(target instanceof Element) ||
            isDetailPage() ||
            isLibraryPage()
        ) {
            return null;
        }

        let element =
            target;

        for (
            let depth = 0;
            element &&
            depth < MAX_PARENT_DEPTH;
            depth++,
            element = element.parentElement
        ) {
            const text =
                textOf(element);

            if (
                !text ||
                text.length > 1100
            ) {
                continue;
            }

            if (
                element
                    .querySelectorAll(
                        'img,picture'
                    )
                    .length !== 1
            ) {
                continue;
            }

            if (
                directRouteInside(
                    element,
                    'detail'
                )
            ) {
                return element;
            }

            try {
                if (
                    getComputedStyle(
                        element
                    ).cursor === 'pointer'
                ) {
                    return element;
                }
            } catch (_) {}
        }

        return null;
    }

    function workFingerprint(card) {
        const lines =
            linesOf(card);

        const ignored =
            /^(?:\d{1,3}\s*%|Completar|Continuar|Leer|Completado)$/i;

        return {
            title:
                lines.find(
                    line =>
                        !ignored.test(line)
                )
                ||
                lines[0]
                ||
                '',

            image:
                getImageSource(card)
        };
    }

    // ============================================================
    // REACT - SOLO AL HACER CLIC
    // ============================================================

    /*
     * No se ejecuta constantemente.
     *
     * Solo intenta obtener el slug de la obra
     * cuando realmente haces clic central.
     */

    function detailRouteFromReact(card) {
        const wantedTitle =
            normalize(
                workFingerprint(
                    card
                ).title
            );

        if (!wantedTitle) {
            return null;
        }

        const roots = [];
        const nodes = [];

        let element =
            card;

        for (
            let i = 0;
            element &&
            i < 4;
            i++,
            element = element.parentElement
        ) {
            nodes.push(
                element
            );
        }

        if (
            card instanceof Element
        ) {
            nodes.push(
                ...[
                    ...card.querySelectorAll(
                        'img,span,a,button'
                    )
                ]
                    .slice(
                        0,
                        10
                    )
            );
        }

        for (const node of nodes) {
            let keys = [];

            try {
                keys =
                    Object.getOwnPropertyNames(
                        node
                    );
            } catch (_) {}

            for (const key of keys) {
                if (
                    key.startsWith(
                        '__reactProps$'
                    )
                ) {
                    try {
                        if (node[key]) {
                            roots.push(
                                node[key]
                            );
                        }
                    } catch (_) {}
                }

                if (
                    key.startsWith(
                        '__reactFiber$'
                    )
                ) {
                    try {
                        let fiber =
                            node[key];

                        for (
                            let depth = 0;
                            fiber &&
                            depth < 4;
                            depth++,
                            fiber = fiber.return
                        ) {
                            if (
                                fiber.memoizedProps
                            ) {
                                roots.push(
                                    fiber.memoizedProps
                                );
                            }

                            if (
                                fiber.pendingProps
                            ) {
                                roots.push(
                                    fiber.pendingProps
                                );
                            }
                        }

                    } catch (_) {}
                }
            }
        }

        const seen =
            new WeakSet();

        let visited =
            0;

        const MAX_VISITED =
            400;

        function walk(
            value,
            depth
        ) {
            if (
                visited++ > MAX_VISITED ||
                depth > 5 ||
                value == null
            ) {
                return null;
            }

            if (
                typeof value === 'string'
            ) {
                const explicit =
                    value.match(
                        /(?:https?:\/\/[^\s"']+)?\/detail\/[A-Za-z0-9._~%\-]+/i
                    )?.[0];

                return explicit
                    ? sameOriginRoute(
                        explicit,
                        'detail'
                    )
                    : null;
            }

            if (
                typeof value !== 'object' ||
                value instanceof Element ||
                value === window ||
                value === document
            ) {
                return null;
            }

            if (
                seen.has(value)
            ) {
                return null;
            }

            seen.add(value);

            let entries;

            try {
                entries =
                    Object.entries(
                        value
                    );
            } catch (_) {
                return null;
            }

            const titleMatches =
                entries.some(
                    ([key, child]) =>
                        /^(?:title|contentsTitle|contentTitle|name)$/i
                            .test(key)
                        &&
                        typeof child === 'string'
                        &&
                        normalize(child) ===
                            wantedTitle
                );

            if (titleMatches) {
                for (
                    const [
                        key,
                        child
                    ]
                    of entries
                ) {
                    if (
                        /^(?:alias|slug|comicAlias|contentAlias)$/i
                            .test(key)
                        &&
                        typeof child === 'string'
                        &&
                        /^[A-Za-z0-9][A-Za-z0-9._~-]{1,180}$/
                            .test(child)
                    ) {
                        return (
                            `${location.origin}/detail/` +
                            `${encodeURIComponent(child)}`
                        );
                    }
                }
            }

            for (
                const [, child]
                of entries
            ) {
                if (
                    typeof child === 'function'
                ) {
                    continue;
                }

                const result =
                    walk(
                        child,
                        depth + 1
                    );

                if (result) {
                    return result;
                }
            }

            return null;
        }

        for (
            const root
            of roots
        ) {
            const result =
                walk(
                    root,
                    0
                );

            if (result) {
                return result;
            }
        }

        return null;
    }

    function resolveWorkUrl(card) {
        return (
            directRouteInside(
                card,
                'detail'
            )
            ||
            detailRouteFromReact(
                card
            )
        );
    }

    // ============================================================
    // RELAY DE RESPALDO
    // ============================================================

    function buildRelayUrl(
        type,
        fingerprint
    ) {
        const url =
            new URL(
                location.href
            );

        url.searchParams.delete(
            RELAY_PARAM
        );

        url.searchParams.set(
            RELAY_PARAM,
            JSON.stringify({
                type,
                fingerprint,
                createdAt:
                    Date.now()
            })
        );

        return url.href;
    }

    function sameImage(
        element,
        wanted
    ) {
        if (!wanted) {
            return true;
        }

        const current =
            getImageSource(
                element
            );

        if (!current) {
            return false;
        }

        try {
            return (
                new URL(current)
                    .pathname
                ===
                new URL(wanted)
                    .pathname
            );

        } catch (_) {
            return (
                current === wanted
            );
        }
    }

    function findExactTextNode(text) {
        if (
            !text ||
            !document.body
        ) {
            return null;
        }

        const wanted =
            normalize(text);

        const walker =
            document.createTreeWalker(
                document.body,
                NodeFilter.SHOW_TEXT
            );

        let node;

        while (
            (
                node =
                    walker.nextNode()
            )
        ) {
            if (
                normalize(
                    node.nodeValue
                ) === wanted
            ) {
                return node.parentElement;
            }
        }

        return null;
    }

    function findRelayCard(payload) {
        const fp =
            payload?.fingerprint;

        if (!fp) {
            return null;
        }

        const titleNode =
            findExactTextNode(
                fp.title
            );

        if (!titleNode) {
            return null;
        }

        let element =
            titleNode;

        for (
            let depth = 0;
            element &&
            depth < MAX_PARENT_DEPTH;
            depth++,
            element = element.parentElement
        ) {
            const text =
                textOf(element);

            const hasImage =
                Boolean(
                    element.querySelector(
                        'img,picture'
                    )
                );

            const dateOkay =
                !fp.date ||
                text.includes(
                    fp.date
                );

            const imageOkay =
                !fp.image ||
                sameImage(
                    element,
                    fp.image
                );

            if (
                hasImage &&
                dateOkay &&
                imageOkay
            ) {
                return {
                    card:
                        element,

                    preferred:
                        titleNode
                };
            }
        }

        return {
            card:
                titleNode,

            preferred:
                titleNode
        };
    }

    async function activateRelay(
        payload,
        match
    ) {
        if (!match?.card) {
            return false;
        }

        if (
            payload.type === 'episode'
        ) {
            const exact =
                await resolveEpisodeAsync(
                    match.card
                );

            if (exact) {
                location.replace(
                    exact
                );

                return true;
            }

        } else {
            const exact =
                resolveWorkUrl(
                    match.card
                );

            if (exact) {
                location.replace(
                    exact
                );

                return true;
            }
        }

        try {
            (
                match.preferred ||
                match.card
            ).click();

            return true;

        } catch (_) {
            return false;
        }
    }

    function processRelay() {
        const url =
            new URL(
                location.href
            );

        const raw =
            url.searchParams.get(
                RELAY_PARAM
            );

        if (!raw) {
            return;
        }

        let payload =
            null;

        try {
            payload =
                JSON.parse(
                    raw
                );

        } catch (_) {}

        url.searchParams.delete(
            RELAY_PARAM
        );

        history.replaceState(
            history.state,
            '',
            url.href
        );

        if (!payload) {
            return;
        }

        let busy =
            false;

        let done =
            false;

        const attempt =
            async () => {
                if (
                    busy ||
                    done
                ) {
                    return done;
                }

                const match =
                    findRelayCard(
                        payload
                    );

                if (!match) {
                    return false;
                }

                busy =
                    true;

                done =
                    await activateRelay(
                        payload,
                        match
                    );

                busy =
                    false;

                return done;
            };

        const start =
            () => {
                if (!document.body) {
                    requestAnimationFrame(
                        start
                    );

                    return;
                }

                attempt();

                /*
                 * Este Observer solo existe
                 * en la pestaña temporal de respaldo.
                 *
                 * No funciona constantemente
                 * mientras navegas normalmente.
                 */

                const observer =
                    new MutationObserver(
                        async () => {
                            if (
                                await attempt()
                            ) {
                                observer.disconnect();
                            }
                        }
                    );

                observer.observe(
                    document.body,
                    {
                        childList:
                            true,

                        subtree:
                            true
                    }
                );

                setTimeout(
                    () =>
                        observer.disconnect(),
                    RELAY_TIMEOUT
                );
            };

        start();
    }

    processRelay();

    // ============================================================
    // QUÉ ELEMENTO SE CLICÓ
    // ============================================================

    function findAction(target) {
        if (
            !(target instanceof Element)
        ) {
            return null;
        }

        if (
            target.closest(
                'input,' +
                'textarea,' +
                'select,' +
                'option,' +
                '[contenteditable="true"]'
            )
        ) {
            return null;
        }

        // --------------------------------------------------------
        // CAPÍTULO
        // --------------------------------------------------------

        if (
            isDetailPage()
        ) {
            const episodeCard =
                findEpisodeCard(
                    target
                );

            if (episodeCard) {
                const url =
                    resolveEpisodeSync(
                        episodeCard
                    );

                if (url) {
                    return {
                        type:
                            'direct',

                        url,

                        card:
                            episodeCard
                    };
                }

                return {
                    type:
                        'async-episode',

                    card:
                        episodeCard,

                    fingerprint:
                        episodeFingerprint(
                            episodeCard
                        )
                };
            }
        }

        // --------------------------------------------------------
        // ENLACE NORMAL
        // --------------------------------------------------------

        const anchor =
            target.closest(
                'a[href]'
            );

        if (anchor) {
            const href =
                validHttpUrl(
                    anchor.getAttribute(
                        'href'
                    )
                );

            if (href) {
                return {
                    type:
                        'direct',

                    url:
                        href,

                    card:
                        anchor
                };
            }
        }

        // --------------------------------------------------------
        // BIBLIOTECA
        // --------------------------------------------------------

        const libraryCard =
            findLibraryCard(
                target
            );

        if (libraryCard) {
            const url =
                resolveWorkUrl(
                    libraryCard
                );

            if (url) {
                return {
                    type:
                        'direct',

                    url,

                    card:
                        libraryCard
                };
            }

            return {
                type:
                    'relay-work',

                card:
                    libraryCard,

                fingerprint:
                    workFingerprint(
                        libraryCard
                    )
            };
        }

        // --------------------------------------------------------
        // HOME / OTRAS LISTAS
        // --------------------------------------------------------

        const workCard =
            findGenericWorkCard(
                target
            );

        if (workCard) {
            const url =
                resolveWorkUrl(
                    workCard
                );

            if (url) {
                return {
                    type:
                        'direct',

                    url,

                    card:
                        workCard
                };
            }

            return {
                type:
                    'relay-work',

                card:
                    workCard,

                fingerprint:
                    workFingerprint(
                        workCard
                    )
            };
        }

        return null;
    }

    // ============================================================
    // CLIC CENTRAL
    // ============================================================

    function onMiddleDown(event) {
        if (
            event.button !== 1
        ) {
            return;
        }

        const action =
            pendingAction ||
            findAction(
                event.target
            );

        pendingAction =
            action;

        if (action) {
            stopMiddleEvent(
                event
            );
        }
    }

    function onMiddleUp(event) {
        if (
            event.button !== 1
        ) {
            return;
        }

        const action =
            pendingAction ||
            findAction(
                event.target
            );

        if (action) {
            stopMiddleEvent(
                event
            );
        }
    }

    document.addEventListener(
        'pointerdown',
        onMiddleDown,
        true
    );

    document.addEventListener(
        'mousedown',
        onMiddleDown,
        true
    );

    document.addEventListener(
        'pointerup',
        onMiddleUp,
        true
    );

    document.addEventListener(
        'mouseup',
        onMiddleUp,
        true
    );

    document.addEventListener(
        'auxclick',
        event => {
            if (
                event.button !== 1
            ) {
                return;
            }

            const action =
                pendingAction ||
                findAction(
                    event.target
                );

            pendingAction =
                null;

            /*
             * Zona vacía:
             * dejar el scroll normal.
             */

            if (!action) {
                return;
            }

            stopMiddleEvent(
                event
            );

            // ----------------------------------------------------
            // URL YA CONOCIDA
            // ----------------------------------------------------

            if (
                action.type ===
                    'direct'
            ) {
                window.open(
                    action.url,
                    '_blank',
                    'noopener'
                );

                return;
            }

            // ----------------------------------------------------
            // LA API TODAVÍA ESTÁ CARGANDO
            // ----------------------------------------------------

            if (
                action.type ===
                    'async-episode'
            ) {
                const tab =
                    window.open(
                        'about:blank',
                        '_blank'
                    );

                if (!tab) {
                    return;
                }

                resolveEpisodeAsync(
                    action.card
                )
                    .then(url => {
                        tab.location.replace(
                            url
                            ||
                            buildRelayUrl(
                                'episode',
                                action.fingerprint
                            )
                        );
                    })

                    .catch(() => {
                        tab.location.replace(
                            buildRelayUrl(
                                'episode',
                                action.fingerprint
                            )
                        );
                    });

                return;
            }

            // ----------------------------------------------------
            // OBRA SIN URL VISIBLE
            // ----------------------------------------------------

            window.open(
                buildRelayUrl(
                    'work',
                    action.fingerprint
                ),
                '_blank',
                'noopener'
            );
        },
        true
    );

})();