MediaWiki:Qlzq-Smart-SimpleTooltip.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.
/* QLZQ:选中文字,Ctrl+Alt+M 插入 SimpleTooltip */

(function () {
    if (!['edit', 'submit'].includes(mw.config.get('wgAction'))) {
        return;
    }

    document.addEventListener('keydown', function (e) {
        if (!(e.ctrlKey && e.altKey && e.key.toLowerCase() === 'm')) {
            return;
        }

        const editor = document.getElementById('wpTextbox1');

        if (!editor || document.activeElement !== editor) {
            return;
        }

        const start = editor.selectionStart;
        const end = editor.selectionEnd;

        if (start === end) return;

        e.preventDefault();

        const selected = editor.value.slice(start, end);

        const prefix = '{{#simple-tooltip: ';
        const middle = ' | ';
        const suffix = '}}';

        const replacement = prefix + selected + middle + suffix;

        editor.setRangeText(replacement, start, end, 'end');

        const cursor = start + prefix.length
                     + selected.length + middle.length;

        editor.setSelectionRange(cursor, cursor);
        editor.dispatchEvent(new Event('input', { bubbles: true }));
    });
})();