☰

Rule34.xxx Keyboard Shortcuts

Keyboard shortcuts for rule34.xxx: navigation, interactions, and more!

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name            Rule34.xxx Keyboard Shortcuts
// @namespace       861ddd094884eac5bea7a3b12e074f34
// @version         3.9.0
// @description     Keyboard shortcuts for rule34.xxx: navigation, interactions, and more!
// @author          Anonymous
// @match           https://rule34.xxx/index.php?page=post&s=view&id=*
// @match           https://rule34.xxx/index.php?page=post&s=list*
// @match           https://rule34.xxx/index.php?page=gmail&s=view&id=*
// @match           https://rule34.xxx/index.php?page=comment&s=list*
// @match           https://rule34.xxx/index.php?page=comment&s=user&user=*
// @match           https://rule34.xxx/index.php?page=favorites&s=view&id=*
// @match           https://rule34.xxx/index.php?page=wiki&s=list&search=*
// @match           https://rule34.xxx/index.php?page=artist&s=list&search=*
// @match           https://rule34.xxx/index.php?page=tags&s=list&tags=*
// @match           https://rule34.xxx/index.php?page=forum&s=view*
// @match           https://rule34.xxx/index.php?page=account&s=profile*
// @icon            https://external-content.duckduckgo.com/ip3/rule34.xxx.ico
// @require         https://update.greasyfork.org/scripts/588114/1899921/Logging%20Handler%20%20UI%20Overlay.js
// @require         https://update.greasyfork.org/scripts/591898/1906160/Transport%20policy%20enforcer.js
// @require         https://update.greasyfork.org/scripts/587399/1906167/Rule34xxx%20challenge-aware%20fetch%20wrapper.js
// @require         https://cdn.jsdelivr.net/npm/[email protected]/src/toastify.min.js
// @grant           GM_getValue
// @grant           GM_setValue
// @grant           GM_addValueChangeListener
// @grant           GM_xmlhttpRequest
// @grant           GM.xmlHttpRequest
// @grant           GM_notification
// @grant           GM_openInTab
// @grant           GM.openInTab
// @grant           GM_addStyle
// @connect         rule34.xxx
// @connect         challenges.cloudflare.com
// @license         0BSD
// ==/UserScript==

/* CONTRIBUTORS
 ****************

 Various AI models:
 - Claude Sonnet 4.5 High
 - GitHub Copilot (GPT 5 mini, Claude 4.5 Haiku)
 - Claude Opus 4.8 High
 - Claude Opus 5 Low
 - Claude Fable 5 Low

   TODO
 ********

QoL
- Reimplement debouncing for elements already undergoing an operation (vote, fave)

Features
- Remove from favorites (f/F) depending on if we are aware that post is favorited
- Enhance 'show original' to be 'toggle between sample and original',
    reflowing to viewport, like Danbooru can.
    (possibly with the help of native 'resize image' button?)
- Open search for artist in new tab (A)
- Reverse image search with SauceNao (1) and Fluffle (2)

Fixes
- loadOriginal() stopped working at some point
- broken on global comments page for EDG v7
  - thumb border flashing

*/

(function() {
    'use strict';

    const ITEMS_PER_PAGE = {
        'comment': 15, // user comments
        'comment-list': 10, // global comments
        'post': 42, // search
        'favorites': 50,
        'wiki': 25, // term search
        'artist': 25,
        'tags': 20,
        'forum': 15 // thread
    };

    const TIMEOUT = {
        note: 2500, // notifications
        net: 2000,  // network requests
    };

    const DEBUG = true;

    // GM API compatibility shim
    ///////////////////////////////

    const GMC = (function() {
        const gm = (typeof GM !== 'undefined') ? GM : {};

        const openInTab =
            (typeof gm.openInTab === 'function')
                ? gm.openInTab.bind(gm)
            : (typeof GM_openInTab !== 'undefined')
                ? GM_openInTab
            : ((url, _options) => window.open(url, '_blank'));

        const addStyle =
            (typeof gm.addStyle === 'function')
                ? gm.addStyle.bind(gm)
            : (typeof GM_addStyle !== 'undefined')
                ? GM_addStyle
            : (css => {
                const style = document.createElement('style');
                style.textContent = css;
                (document.head || document.documentElement).appendChild(style);
                return style;
            });

        return { openInTab, addStyle };
    })();

    // styling
    /////////////

    GMC.addStyle(`
        .thumb.thumb-alt img.thumb-status {
            border-radius: 6px !important;
            box-sizing: border-box !important;
        }
        .thumb.thumb-alt img.thumb-status.thumb-status-success {
            border: 2px solid #00a000 !important;
        }
        .thumb.thumb-alt img.thumb-status.thumb-status-alert {
            border: 2px solid #a08000 !important;
        }
        .thumb.thumb-alt img.thumb-status.thumb-status-error {
            border: 2px solid #a00000 !important;
        }
        .thumb.thumb-alt img.thumb-status.thumb-status-wait {
            border: 2px solid #4080a0 !important;
        }
        /* The theme borders the <a> wrapper for webm/video posts; hide it
           while an operation is shown so we never get two borders. Keeping the
           border width (transparent colour) avoids a layout shift. */
        .thumb.thumb-alt > a.thumb-op {
            border-color: transparent !important;
        }
        /* Suppress the theme's hover zoom during an operation. */
        .thumb.thumb-alt > a:hover {
            transform: none !important;
        }
    `);

    const toastifyLink = document.createElement('link');
    toastifyLink.rel = 'stylesheet';
    toastifyLink.href = 'https://cdn.jsdelivr.net/npm/[email protected]/src/toastify.min.css';
    document.head.appendChild(toastifyLink);

    function getThumbContainer(id) {
        if (['favorites', 'comment'].includes(P.page)) {
            return document.querySelector('.thumb:hover');
        } else if (PP.postList) {
            return document.getElementById('s' + id);
        }
    }

    function modifyStyles(o, action, toggle = false) {
        for (const k in o) {
            if (action === 'add') {
                o[k][0].classList.add(o[k][1]);
            } else if (action === 'remove') {
                o[k][0].classList.remove(o[k][1]);
            }
        }

        if (toggle) {
            return setTimeout(() => {
                for (const k in o) {
                    if (action === 'add') {
                        o[k][0].classList.remove(o[k][1]);
                    } else if (action === 'remove') {
                        o[k][0].classList.add(o[k][1]);
                    }
                }
            }, TIMEOUT.note);
        }
    }

    function styleThumbBorder(target, color, action, flash = true) {
        const anchor = target.children[0];
        const image = anchor?.children[0];
        if (!image
            || !['success', 'alert', 'error', 'wait'].includes(color)
            || !['add', 'remove'].includes(action))
                return false;
        const styles = {
            0: [target, 'thumb-alt'],          // .thumb hook (specificity + hover)
            1: [anchor, 'thumb-op'],           // hides the theme's wrapper border
            2: [image, 'thumb-status'],        // base (radius, box-sizing)
            3: [image, `thumb-status-${color}`],
        };
        return modifyStyles(styles, action, flash);
    }

    // logging
    /////////////

    const logger = LoggingUI.create({
        name: 'Keyboard Shortcuts',
        tag: 'rkb',
        console: true,
        panel: DEBUG,
        prefsKey: 'log_prefs',
        minLevel: DEBUG ? 'debug' : 'info',
    });

    if (typeof R34ChallengeRequest === 'undefined') {
        logger.error('R34ChallengeRequest unavailable; falling back to GM request');
        const gm = (typeof GM !== 'undefined') ? GM : {};
        const xmlHttpRequest = (typeof gm.xmlHttpRequest === 'function')
            ? gm.xmlHttpRequest.bind(gm)
            : (typeof GM_xmlhttpRequest !== 'undefined')
                ? GM_xmlhttpRequest
                : null;
        window.R34ChallengeRequest = { xmlHttpRequest };
    }

    // notifications
    ///////////////////

    function showToast(message, type = 'info', destination = null) {
        let background = String();
        switch (type) {
            case 'error':   background = '#a00000'; break;
            case 'alert':   background = '#a08000'; break;
            case 'success': background = '#00a000'; break;
            case 'info':    background = '#4080a0'; break;
        }

        window.Toastify({
            text: message,
            duration: TIMEOUT.note,
            gravity: 'top',
            position: 'right',
            style: { background },
            stopOnFocus: true,
            destination
        }).showToast();
    };

    // post interactions
    ///////////////////////

    function updateScore(key, value, color) {
        key.innerHTML = value;
        key.style.color = color;
        key.style.fontWeight = 'bold';
        return setTimeout(() => {
            key.style.color = null;
            key.style.fontWeight = null;
        }, TIMEOUT.note);
    }

    function scoreError(type, id) {
        let score;
        if (type === 'comment') {
            score = document.getElementById('sc' + id);
        } else if (type === 'post') {
            score = document.getElementById('psc' + id);
            if (PP.commentsAll || P.s === 'view')
                showToast('Upvote failed', 'error');
        }
        return updateScore(score, score.innerHTML, 'red');
    }

    function commentVote(postId, commentId) {
        R34ChallengeRequest.xmlHttpRequest({
            method: 'GET',
            url: location.origin + `/index.php?page=comment&id=${postId}&s=vote&cid=${commentId}&vote=up`,
            timeout: TIMEOUT.net,
            transport: 'fetch-first',
            onload: xhr => {
                const value = parseInt(xhr.responseText);
                let log = `Comment ${commentId} upvote`;
                if (isNaN(value) || xhr.status != 200) {
                    logger.error(`${log} failed`);
                    scoreError('comment', commentId);
                } else {
                    logger.info(`${log} success; score=${value}`);
                    const score = document.getElementById('sc' + commentId);
                    updateScore(score, value, '#b0e0b0');
                }
            }
        });
    }

    function request(url, container, onLoad, onError = null) {
        const clearWait = () =>
            container && styleThumbBorder(container, 'wait', 'remove', false);
        const fail = reason => {
            clearWait();
            logger.error(`Request failed (${reason}): ${url}`);
            if (container) styleThumbBorder(container, 'error', 'add');
            if (onError) onError(reason);
        };

        if (container) styleThumbBorder(container, 'wait', 'add', false);
        R34ChallengeRequest.xmlHttpRequest({
            method: 'GET', url: location.origin + url, timeout: TIMEOUT.net,
            transport: 'fetch-first',
            onload: xhr => { clearWait(); onLoad(xhr); },
            onerror: () => fail('Network error'),
            ontimeout: () => fail('Request timed out'),
        });
    }

    function postVote(id, notify = true, container = null) {
        request(
            `/index.php?page=post&s=vote&id=${id}&type=up`,
            container,
            xhr => {
                const value = parseInt(xhr.responseText);
                const type = (isNaN(value) || xhr.status !== 200)
                    ? 'error' : 'success';

                if (PP.commentsAll || PP.postDetail) {
                    if (type === 'error') return scoreError('post', id);
                    updateScore(
                        document.getElementById('psc' + id), value, '#b0e0b0');
                    if (notify && PP.postDetail)
                        showToast('Post upvoted', 'success');
                }
                if (notify && PP.hasThumbs && container)
                    styleThumbBorder(container, type, 'add');

                if (type === 'error')
                    return logger.error(`Post ${id} upvote error`);
                logger.info(`Post ${id} upvote success; score=${value}`);
            },
            () => { if (PP.commentsAll || PP.postDetail) scoreError('post', id); }
        );
    }

    function _addFave(id, container = null) {
        // TODO: on add/already-faved, store in LS so key handler may choose
        //   between add/remove action
        const outcomes = {
            3: ['Post added to favorites', 'success'],
            1: ['Post already favorited', 'alert'],
            2: ['Not logged in', 'error'],
        };
        request(
            `/public/addfav.php?id=${id}`,
            container,
            xhr => {
                const [text, type] = (xhr.status !== 200)
                    ? [`Network error (HTTP ${xhr.status})`, 'error']
                    : outcomes[parseInt(xhr.responseText)]
                        || ['Unexpected response', 'error'];
                logger.info(`Favoriting post ${id} `
                    + (type === 'success' ? type : `failed; ${text}`));
                if (PP.hasThumbs && container) {
                    styleThumbBorder(container, type, 'add');
                    if (type !== 'success') showToast(text, type);
                } else if (PP.postDetail && text) {
                    showToast(text, type);
                }
            },
            reason => { if (PP.postDetail) showToast(reason, 'error'); }
        );
    }

    // image-related
    ///////////////////

    function loadOriginal(elementId, postId) {
        /* (site-native variable)
            window.image = {
                'domain': 'https://wimg.rule34.xxx/',
                'width': 2048,
                'height': 1720,
                'dir': 2375,
                'img': '22588922742b34b9059544161a853b39.jpeg',
                'base_dir': 'images',
                'sample_dir': 'samples',
                'sample_width': '850',
                'sample_height': '714'
            };
        */

        const note = document.getElementById('resized_notice');
        if (note.style.display || !Note.sample) return;
        note.style.display = 'none';

        // load original image and resize
        let image = document.getElementById(elementId);
        image.style.display = 'none';
        image.src = 'about:blank';
        image.width = image.width;
        image.height = image.height;
        image.src = [
            `${image.domain}/`,
            `${image.base_dir}/`,
            `${image.dir}/`,
            image.img
        ].join('')

        // reflow notes (site-native object)
        Note.all.invoke('adjustScale');
        Note.sample = false;

        // show original image
        image.style.display = '';

        logger.info(`Loaded original quality of post ${postId}`);
    }

    // the 'Original image' link of a post detail document; hrefs there are
    // absolute, so a detached (fetched) document resolves them identically
    function findOriginalHref(root) {
        const linkList = root.querySelector('div.link-list');
        if (!linkList) return null;
        const anchor = Array.from(
            linkList.querySelectorAll('a[href]')
        ).find(a =>
            a.textContent.includes('Original')
            && (/\/images\//.test(a.href))
        );
        return anchor?.href || null;
    }

    function openOriginal(postId) {
        const href = findOriginalHref(document);
        if (!href) return logger.error(`No original image link for ${postId}`);
        logger.info(`Opening original image of post ${postId}`);
        GMC.openInTab(href);
    }

    // post lists carry no original-quality URL (thumbnails omit the file
    // extension), and dapi needs an API key, so the post's own page is the
    // cheapest unauthenticated source of the link
    function openOriginalRemote(postId, container = null) {
        request(
            `/index.php?page=post&s=view&id=${postId}`,
            container,
            xhr => {
                const doc = new DOMParser()
                    .parseFromString(xhr.responseText, 'text/html');
                const href = (xhr.status === 200) ? findOriginalHref(doc) : null;
                if (!href) {
                    logger.error(`No original image link for post ${postId}`);
                    if (container) styleThumbBorder(container, 'error', 'add');
                    showToast('Original image unavailable', 'error');
                    return;
                }
                logger.info(`Opening original image of post ${postId}`);
                GMC.openInTab(href, { active: false, insert: true });
                if (container) styleThumbBorder(container, 'success', 'add');
            },
            reason => showToast(reason, 'error')
        );
    }

    // form-related
    //////////////////

    function focusInput(formQuery, fieldQuery) {
        // TODO: turn this repetitive flow into a function
        let form = document.querySelector(`form[name="${formQuery}"]`)
        if (!form) form = document.querySelector(`form[id="${formQuery}"]`)
        if (!form) form = document.querySelector(`form[action="${formQuery}"]`)
        if (!form) return null;
        let field = form.querySelector(`input[name="${fieldQuery}"]`);
        if (!field) field = form.querySelector(`input[id="${fieldQuery}"]`);
        if (!field) field = form.querySelector(`textarea[name="${fieldQuery}"]`);
        if (!field) field = form.querySelector(`textarea[id="${fieldQuery}"]`);
        if (!field) return null;
        logger.info('Focusing search field');
        field.focus();
        return field;
    }

    function clickAnchor(selector) {
        const anchor = document.querySelector(`a[href^='${selector}']`);
        anchor.click();
    }

    function _submitForm(e) {
        // ripped from danbooru app/javascript/src/javascripts/shortcuts.js
        // e.target can be a shadow host (retargeted event) with no form ancestor
        e.target.closest("form")?.querySelector('[type="submit"]')?.click();
        e.preventDefault();
    };

    // obj:     element id (string) or DOM element (object)
    // state:   whether to show the element or not (boolean)
    function toggleDisplay(obj, state) {
        let element;
        if (typeof obj === 'string')
            element = document.getElementById(obj);
        else if (typeof obj === 'object')
            element = obj;

        if (!state) {
            if (element.style.display === 'none')
                element.style.removeProperty('display');
            else if (!element.style.display)
                element.style.display = 'none';
        } else {
            if (state === false)
                element.style.display = 'none';
            else if (state === true)
                element.style.removeProperty('display');
        }
    }

    function getDeepActiveElement() {
        let el = document.activeElement;
        while (el?.shadowRoot?.activeElement) el = el.shadowRoot.activeElement;
        return el;
    }

    // key events
    ////////////////

    // normalize an event into a dispatch key, e.g. 'shift+v', 'arrowleft'
    // (alt & meta are globally excluded modifiers)
    function chord(e) {
        const parts = [];
        if (e.ctrlKey)  parts.push('ctrl');
        if (e.shiftKey) parts.push('shift');
        parts.push(e.key.toLowerCase());
        return parts.join('+');
    }

    // navigation

    function navigate(ctx, dir) {
        let newPid = null;
        const currentPid = parseInt(PARAMS.get('pid')) || 0;
        if (['prev', 'start'].includes(dir)) {
            if (currentPid === 0) return false;
            newPid = (dir === 'start')
                ? 0 : Math.max(0, currentPid - ITEMS_PER_PAGE[ctx.page]);
        } else if (dir === 'next') {
            let a = document.querySelector("a[alt='last page']");
            if (!a) a = document.querySelector("a[name='lastpage']");
            if (!a) return false; // inhibit when on last page
            newPid = currentPid + ITEMS_PER_PAGE[ctx.page];
        }

        if (newPid !== null) {
            PARAMS.set('pid', newPid);
            const path = window.location.pathname;
            window.location.href = `${path}?${PARAMS.toString()}`;
        }
    }

    const navHandler = {
        // inhibit when ctrl held or a video player has focus, unless
        // navigating (for when also using the Video Previews userscript)
        guard: e => e.ctrlKey || !!document.querySelector('video:hover'),
        bindings: {
            'shift+arrowleft':  ctx => navigate(ctx, 'start'),
            'arrowleft':        ctx => navigate(ctx, 'prev'),
            'a':                ctx => navigate(ctx, 'prev'),
            // 'backspace':        () => history.back(),
            'shift+a':          () => history.back(),
            'arrowright':       ctx => navigate(ctx, 'next'),
            'd':                ctx => navigate(ctx, 'next'),
            'shift+d':          () => history.forward(),
        },
    };

    // post list

    function focusSearchField(e, select) {
        e.preventDefault();
        const field = focusInput('index.php?page=search', 'tags');
        if (select && field) field.select();
    }

    function getHoveredPostId() {
        const link = document.querySelector('a:hover');
        const image = link?.children[0];
        if (!image || image.tagName !== 'IMG') return null;

        if (P.page !== 'favorites'
            && !image.classList.contains('preview'))
                return null;

        const targetParams = new URLSearchParams(link.href);
        if (!targetParams.has('id')) return null;
        return targetParams.get('id');
    }

    function upvoteHovered() {
        const id = getHoveredPostId();
        if (!id) return;
        const container = PP.hasThumbs ? getThumbContainer(id) : null;
        postVote(id, true, container);
    }

    function faveHovered() {
        const id = getHoveredPostId();
        if (!id) return;
        const container = PP.hasThumbs ? getThumbContainer(id) : null;
        postVote(id, false);
        _addFave(id, container);
    }

    const postListHandler = {
        guard: e => e.ctrlKey,
        bindings: {
            'shift+f': faveHovered,
            'q':       ctx => focusSearchField(ctx.e, false),
            'shift+q': ctx => focusSearchField(ctx.e, true),
            'v':       upvoteHovered,
        },
    };

    // post detail

    function faveDetail(ctx) {
        if (document.querySelector('video:active')) ctx.e.preventDefault();
        postVote(ctx.id, false);
        _addFave(ctx.id);
    }

    function openCommentForm() {
        toggleDisplay('comment_form', true);
        setTimeout(() => focusInput('comment_form', 'comment'), 100);
    }

    function openEditForm() {
        toggleDisplay('edit_form', true);
        setTimeout(() => focusInput('edit_form', 'tags'), 100);
    }

    function viewTagHistory(id) {
        window.location.href =
            `/index.php?page=history&type=tag_history&id=${id}`;
    }

    function upvoteComment(ctx) {
        const hov = document.querySelector('#comment-list div:hover');
        if (hov) commentVote(ctx.id, hov.id.replace('c', ''));
    }

    const postDetailHandler = {
        bindings: {
            'c':          () =>  openCommentForm(),
            // TODO: reproduce iCame logic
            'shift+c':    ctx => iCame(ctx.id),
            'shift+p':    () =>  openHoveredCommentAuthor(),
            'e':          () =>  openEditForm(),
            'f':          ctx => faveDetail(ctx),
            'h':          ctx => viewTagHistory(ctx.id),
            'o':          ctx => openOriginal(ctx.id),
            'r':          ctx => pflag(ctx.id), // native
            'u':          ctx => loadOriginal('image', ctx.id),
            // TODO: repurpose v key for reflowing media to viewport
            'v':          ctx => postVote(ctx.id),
            'shift+v':    ctx => upvoteComment(ctx),
            'shift+w':    ctx => postVote(ctx.id),
            'z':          ctx => loadOriginal('image', ctx.id),
            'ctrl+enter': ctx => _submitForm(ctx.e),
        },
    };

    // comments (hovered)

    // migrated from the mail helper userscript: opens the hovered comment's
    // author profile. The author is read from the link's text, not its href —
    // the feed-rewrite script replaces profile links with href-less menu
    // anchors. Comment blocks nest in .response-list on comment listings and
    // sit directly in #comment-list on post detail pages.
    function openHoveredCommentAuthor() {
        const comment = document.querySelector(
            '.response-list > div[id^="c"]:hover, '
            + '#comment-list > div[id^="c"]:hover');
        if (!comment) return false;
        const author = (comment.querySelector('a[href*="s=profile"]')
            ?? comment.querySelector('.author a'))?.textContent.trim();
        if (!author) return false;
        logger.info(`Opening profile of ${author}`);
        GMC.openInTab(
            `${window.location.origin}/index.php?page=account&s=profile`
                + `&uname=${encodeURIComponent(author)}`,
            { active: false, insert: true });
        return true;
    }

    const commentAuthorHandler = {
        guard: e => e.ctrlKey,
        bindings: {
            // hovering a comment wins; anywhere else in a post block opens
            // its detail
            'shift+p': ctx =>
                openHoveredCommentAuthor() || openDetailHoveredPost(ctx),
        },
    };

    // member profile

    // migrated from the mail helper userscript: the stats table's Comments
    // row links that member's comment listing with the correct user param
    function gotoProfileComments() {
        const href = document.querySelector(
            '#content a[href*="page=comment"][href*="s=user"]')?.href;
        if (href) window.location.href = href;
    }

    const profileHandler = {
        guard: e => e.ctrlKey,
        bindings: {
            'shift+c': () => gotoProfileComments(),
        },
    };

    // global comments

    // margin above a post's top edge when jumped to
    const POST_JUMP_MARGIN = 8;
    // global_comments_revamp seats posts 12px above their top (followMarginPx)
    // after a filter jump; a post whose top sits within this band past the jump
    // margin still counts as the current one
    const POST_SEAT_TOLERANCE = 8;

    function getCommentPagePosts() {
        // top-level post containers only; nested comments use c-prefixed ids
        return Array.from(document.querySelectorAll('div.post[id^="p"]'));
    }

    function postJumpTop(post) {
        return post.getBoundingClientRect().top
            + window.scrollY - POST_JUMP_MARGIN;
    }

    function jumpToPost(ctx, dir) {
        const posts = getCommentPagePosts();
        if (!posts.length) return;
        ctx.e.preventDefault();

        // index of the last post whose top is at or above the viewport top
        let index = -1;
        for (let i = 0; i < posts.length; i++) {
            if (postJumpTop(posts[i])
                <= window.scrollY + POST_SEAT_TOLERANCE) index = i;
            else break;
        }

        let target = index + dir;
        // pageup while scrolled into a post returns to its top first
        if (dir === -1 && index >= 0
            && window.scrollY > postJumpTop(posts[index]) + 1)
                target = index;
        target = Math.max(0, Math.min(target, posts.length - 1));

        window.scrollTo({top: postJumpTop(posts[target])});
    }

    // the whole block is the hover target here, not just its thumbnail: the
    // comment column is most of a post's area on this page
    function openOriginalHoveredPost(ctx) {
        const post = document.querySelector('div.post[id^="p"]:hover');
        if (!post) return;
        ctx.e.preventDefault();
        openOriginalRemote(post.id.slice(1), post.querySelector('.thumb'));
    }

    function openDetailHoveredPost(ctx) {
        const post = document.querySelector('div.post[id^="p"]:hover');
        if (!post) return;
        ctx.e.preventDefault();
        const id = post.id.slice(1);
        logger.info(`Opening post detail of post ${id}`);
        GMC.openInTab(
            `${window.location.origin}/index.php?page=post&s=view&id=${id}`,
            { active: false, insert: true });
    }

    const commentsGlobalHandler = {
        guard: e => e.ctrlKey,
        bindings: {
            'shift+o': openOriginalHoveredPost,
            // hovering a comment wins; anywhere else in a post block opens
            // its detail
            'shift+p': ctx =>
                openHoveredCommentAuthor() || openDetailHoveredPost(ctx),
        },
    };

    const postJumpHandler = {
        guard: e => e.ctrlKey || e.shiftKey,
        bindings: {
            'pageup':   ctx => jumpToPost(ctx, -1),
            'pagedown': ctx => jumpToPost(ctx, 1),
        },
    };

    // mail detail

    const mailHandler = {
        guard: e => e.ctrlKey,
        bindings: {
            'shift+d': () => clickAnchor(
                'index.php?page=gmail&s=manage&action=delete'),
            'r':       () => submitform(), // native
            'shift+r': () => clickAnchor(
                'index.php?page=gmail&s=manage&action=report'),
        },
    };

    // routing
    /////////////

    const PARAMS = new URLSearchParams(window.location.search);
    const P = { page: PARAMS.get('page'), s: PARAMS.get('s') };
    const PP = {
        postList: (P.page === 'post' && P.s === 'list'),
        postDetail: (P.page === 'post' && P.s === 'view'),
        commentsAll: (P.page === 'comment' && ['user', 'list'].includes(P.s)),
        commentsGlobal: (P.page === 'comment' && P.s === 'list'),
        commentsUser: (P.page === 'comment' && P.s === 'user'),
        favorites: (P.page === 'favorites' && P.s === 'view'),
        profile: (P.page === 'account' && P.s === 'profile'),
    }
    PP.hasThumbs = (PP.commentsAll || PP.favorites || PP.postList);

    let activeHandlers = [];
    let activeCtx = {};
    if (PP.postList) {
        activeHandlers = [navHandler, postListHandler];
        activeCtx = { page: 'post' };
    } else if (PP.postDetail && PARAMS.has('id')) {
        // we don't support post comment list navigation as it overlaps
        // with site-native post navigation
        activeHandlers = [postDetailHandler];
        activeCtx = { id: PARAMS.get('id') };
    } else if (P.page === 'gmail' && P.s === 'view') {
        activeHandlers = [mailHandler];
    } else if (PP.commentsAll || PP.favorites) {
        activeHandlers = [navHandler, postListHandler];
        if (PP.commentsAll) activeHandlers.push(postJumpHandler);
        if (PP.commentsGlobal) activeHandlers.push(commentsGlobalHandler);
        if (PP.commentsUser) activeHandlers.push(commentAuthorHandler);
        activeCtx = { page: PP.commentsGlobal ? 'comment-list' : P.page };
    } else if (PP.profile) {
        activeHandlers = [profileHandler];
    } else if (
        ['tags', 'wiki', 'artist'].includes(P.page)
        || (P.page === 'forum' && P.s === 'view')
    ) {
        activeHandlers = [navHandler];
        activeCtx = { page: P.page };
    }

    document.addEventListener('keydown', function(e) {
        const key = e.key.toLowerCase();

        if (e.altKey || e.metaKey) return; // unsupported modifiers
        if (key === 'escape') return;

        // allow ctrl+enter (form submit) to pass the editable guard
        const submitting = e.ctrlKey && key === 'enter';
        const tagExclusions = ['INPUT', 'TEXTAREA', 'SELECT'];
        const active = getDeepActiveElement();
        const editable = active.isContentEditable
            || tagExclusions.includes(active.tagName);
        if (editable && !submitting)
            return;

        const c = chord(e);
        for (const { guard, bindings } of activeHandlers) {
            if (guard && guard(e)) continue;
            bindings[c]?.({ e, ...activeCtx });
        }
    });

    if (PP.commentsAll || PP.postList) {
        window.location.hash = '#content';
        const url = new URL(window.location);
        url.hash = '';
        window.history.replaceState(null, document.title, url.toString());
    }
})();