114514 / IRCCloud Send with Style

// ==UserScript==
// @name   IRCCloud     Send with Style
// @description Enables font styles in IRCCloud
// @include     https://www.irccloud.com/*
// @version     1.0.0
// @grant       none
// @license AGPL-3.0-or-later
// ==/UserScript==

(function () {
  'use strict';

  var fontStyles = {
    color: '\u0003',
    bold: '\u0002',
    reset: '\u000f',
    italic: '\u001d',
    underline: '\u001f',
    strikethrough: '\u001e',
    hexcolor: '\u0004',
  };

  // 核心样式替换
  function replaceFontStyles(str) {
    return str.replace(/\$B/g, fontStyles.bold)
      .replace(/\$R/g, fontStyles.reset)
      .replace(/\$I/g, fontStyles.italic)
      .replace(/\$U/g, fontStyles.underline)
      .replace(/\$X/g, fontStyles.strikethrough)
      .replace(/\$C/g, fontStyles.color)
      .replace(/\$H/g, fontStyles.hexcolor);
  }

  // 彩虹效果处理
  function rainbow(text, match) {
    var colors = ['05', '04', '07', '08', '09', '03', '11', '10', '12', '02', '06', '13', '15', '14'];
    var output = '';
    var colorIndex = Math.floor(Math.random() * colors.length);

    for (var i = 0; i < match.length; i++) {
      output += fontStyles.color + colors[colorIndex] + match[i];
      colorIndex = (colorIndex + 1) % colors.length;
    }
    return output + fontStyles.color;
  }

  function replaceSpecials(str) {
    return str.replace(/<RB>(.*?)<\/RB>/gi, (_, p1) => rainbow(_, p1));
  }

  // 输入框事件绑定
  function bindTextarea() {
    if (!cb()) return;

    var input = $('#bufferInputView' + cb().bid());
    if (input.data('sws') === '1') return;

    input.on('keydown', function (e) {
      if (e.keyCode === 13) { // 回车键
        let val = input.val();
        val = replaceFontStyles(val);
        val = replaceSpecials(val);
        input.val(val);
      }
    }).data('sws', '1');
  }

  // 初始化
  (function init() {
    window.SESSION?.bind('init', () => {
      window.SESSION.buffers.on('doneSelected', bindTextarea);
      bindTextarea();
    });

    if (!window.SESSION) setTimeout(init, 100);
  })();
})();