MediaWiki:Qlzq-CtrlF-by-Number.js

From 清冽之泉
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/* 以下专为法条设计,生成透明的数字,Ctrl F 检索时只用输数字。且会有一个短暂的位置显色提示 */

/* 法条中文编号自动生成数字搜索别名 */
(function () {
    'use strict';

    if (mw.config.get('wgAction') !== 'view') return;

    // 中文数字转整数
    function chineseToNumber(s) {
        const digits = {
            零: 0, 〇: 0, 一: 1, 二: 2, 两: 2,
            三: 3, 四: 4, 五: 5, 六: 6,
            七: 7, 八: 8, 九: 9
        };
        const units = { 十: 10, 百: 100, 千: 1000 };

        let total = 0, section = 0, digit = 0;

        for (const ch of s) {
            if (Object.hasOwn(digits, ch)) {
                digit = digits[ch];
            } else if (Object.hasOwn(units, ch)) {
                section += (digit || 1) * units[ch];
                digit = 0;
            } else if (ch === '万') {
                total += (section + digit) * 10000;
                section = 0;
                digit = 0;
            }
        }

        return total + section + digit;
    }

    mw.hook('wikipage.content').add(function ($content) {
        const root = $content[0];
        if (!root) return;

        // 只处理段落、列表项和标题
        root.querySelectorAll(
            'p, dd, dt, li, h2, h3, h4, h5, h6'
        ).forEach(function (el) {
            if (el.querySelector(':scope > .qlzq-law-alias')) {
                return;
            }

            // 只识别段落开头的“第……条”
            const match = el.textContent.match(
                /^\s*第([零〇一二两三四五六七八九十百千万]+)条(?=\s|[::]|$)/
            );

            if (!match) return;

            const number = chineseToNumber(match[1]);
            if (!number) return;

            // 生成透明、可搜索的数字别名
            const alias = document.createElement('span');
            alias.className = 'qlzq-law-alias';
            alias.setAttribute('aria-hidden', 'true');
            alias.textContent = '#' + number;

            alias.style.cssText =
                'position:absolute;' +
                'opacity:0;' +
                'white-space:nowrap;' +
                'pointer-events:none;' +
                'user-select:none;';

            el.insertBefore(alias, el.firstChild);
        });
    });
}());


/* Ctrl+F 命中法条时,短暂突出整条法条 */
(function () {
    'use strict';

    if (mw.config.get('wgAction') !== 'view') return;

    // 注入提示样式
    const style = document.createElement('style');
    style.textContent = `
        .qlzq-law-located {
            background-color: rgba(245, 197, 61, 0.15) !important;
            box-shadow: inset 3px 0 0 #d4a037 !important;
            border-radius: 3px;
        }
    `;
    document.head.appendChild(style);

    let previous = null;
    let timer = null;

    function findAlias(node) {
        if (!node) return null;

        const el = node.nodeType === 1
            ? node
            : node.parentElement;

        return el && el.closest
            ? el.closest('.qlzq-law-alias')
            : null;
    }

    document.addEventListener('selectionchange', function () {
        const selection = window.getSelection();

        if (!selection || selection.isCollapsed ||
            !selection.rangeCount) return;

        // 只响应纯数字法条搜索
        const text = selection.toString().trim();
        if (!/^#?\d+$/.test(text)) return;

        // 判断命中的是否为之前生成的法条别名
        const alias =
            findAlias(selection.anchorNode) ||
            findAlias(selection.focusNode) ||
            findAlias(selection.getRangeAt(0).startContainer);

        if (!alias) return;

        const target = alias.parentElement;
        if (!target) return;

        // 清除上一次提示
        if (previous) {
            previous.classList.remove('qlzq-law-located');
        }
        clearTimeout(timer);

        // 突出当前法条
        target.classList.add('qlzq-law-located');
        previous = target;

        // 3秒后自动恢复
        timer = setTimeout(function () {
            target.classList.remove('qlzq-law-located');
            if (previous === target) previous = null;
        }, 3000);
    });
}());