rich-html-theme.js 3.05 KB
/**
 * 富文本在暗色模式下的可读性处理:
 * - 过深的文字色改为浅色
 * - 保留红/橙/绿等强调色
 * - 过浅背景改为透明,避免黑底白底块
 */

function parseColorToRgb(value) {
  if (!value) return null
  const v = String(value).trim().toLowerCase()
  if (v === 'transparent' || v === 'inherit' || v === 'currentcolor') return null

  const hex = v.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i)
  if (hex) {
    let h = hex[1]
    if (h.length === 3) h = h.split('').map(c => c + c).join('')
    return {
      r: parseInt(h.slice(0, 2), 16),
      g: parseInt(h.slice(2, 4), 16),
      b: parseInt(h.slice(4, 6), 16)
    }
  }

  const rgb = v.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i)
  if (rgb) {
    return { r: Number(rgb[1]), g: Number(rgb[2]), b: Number(rgb[3]) }
  }

  const named = {
    black: { r: 0, g: 0, b: 0 },
    white: { r: 255, g: 255, b: 255 },
    gray: { r: 128, g: 128, b: 128 },
    grey: { r: 128, g: 128, b: 128 },
    red: { r: 255, g: 0, b: 0 },
    blue: { r: 0, g: 0, b: 255 },
    green: { r: 0, g: 128, b: 0 },
    navy: { r: 0, g: 0, b: 128 },
    maroon: { r: 128, g: 0, b: 0 }
  }
  return named[v] || null
}

function luminance({ r, g, b }) {
  return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255
}

function isAccentColor(rgb) {
  if (!rgb) return false
  const { r, g, b } = rgb
  // 红/橙强调
  if (r > 160 && g < 120 && b < 120) return true
  // 绿强调
  if (g > 140 && r < 120 && b < 120) return true
  // 蓝强调(非极深蓝)
  if (b > 160 && r < 120 && g < 160 && luminance(rgb) > 0.25) return true
  return false
}

function adaptColorValue(value, kind) {
  const rgb = parseColorToRgb(value)
  if (!rgb) return value
  const lum = luminance(rgb)

  if (kind === 'color') {
    if (isAccentColor(rgb)) return value
    // 深色文字 → 浅色
    if (lum < 0.55) return '#e8eef7'
    return value
  }

  if (kind === 'background') {
    // 浅色/白色背景在暗色下显得刺眼,改为透明
    if (lum > 0.85) return 'transparent'
    return value
  }

  return value
}

function adaptStyleAttr(styleText) {
  if (!styleText) return styleText
  return styleText
    .replace(/(^|;)\s*color\s*:\s*([^;]+)/gi, (m, sep, val) => `${sep}color:${adaptColorValue(val.trim(), 'color')}`)
    .replace(/(^|;)\s*background(?:-color)?\s*:\s*([^;]+)/gi, (m, sep, val) => {
      const next = adaptColorValue(val.trim(), 'background')
      return `${sep}background-color:${next}`
    })
}

/**
 * @param {string} html
 * @param {boolean} isDark
 * @returns {string}
 */
export function adaptRichHtmlForTheme(html, isDark) {
  if (!html || !isDark) return html
  let out = String(html)

  // style="color:#333;..."
  out = out.replace(/\sstyle\s*=\s*(["'])([\s\S]*?)\1/gi, (m, quote, style) => {
    return ` style=${quote}${adaptStyleAttr(style)}${quote}`
  })

  // <font color="#333"> / color='black'
  out = out.replace(/\scolor\s*=\s*(["']?)([^"'>\s]+)\1/gi, (m, quote, val) => {
    const next = adaptColorValue(val, 'color')
    const q = quote || '"'
    return ` color=${q}${next}${q}`
  })

  return out
}