You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.9 KiB

4 weeks ago
// 表情图片基础路径(若环境变量未定义,使用默认路径 /static/emoji/
const EMO_BASE_URL = '/static/emoji/'
const emoTextList = [
'憨笑', '媚眼', '开心', '坏笑', '可怜', '爱心', '笑哭', '拍手', '惊喜', '打气',
'大哭', '流泪', '饥饿', '难受', '健身', '示爱', '色色', '眨眼', '暴怒', '惊恐',
'思考', '头晕', '大吐', '酷笑', '翻滚', '享受', '鼻涕', '快乐', '雀跃', '微笑',
'贪婪', '红心', '粉心', '星星', '大火', '眼睛', '音符', '叹号', '问号', '绿叶',
'燃烧', '喇叭', '警告', '信封', '房子', '礼物', '点赞', '举手', '拍手', '点头',
'摇头', '偷瞄', '庆祝', '疾跑', '打滚', '惊吓', '起跳'
]
const regex = /\#[\u4E00-\u9FA5]{1,3}\;/gi
/**
* 判断文本是否包含表情标记
* @param {string} content 文本内容
* @returns {boolean}
*/
const containEmoji = (content) => regex.test(content)
/**
* 将文本中的表情标记替换为 <img> 标签
* @param {string} content 原始文本
* @param {string} extClass 图片的 CSS 类名
* @returns {string} 替换后的 HTML 字符串
*/
const transform = (content, extClass) => {
return content.replace(regex, (emoText) => {
const word = emoText.replace(/\#|\;/g, '')
const idx = emoTextList.indexOf(word)
if (idx === -1) return emoText
const path = textToPath(emoText)
return `<img src="${path}" class="${extClass}" />`
})
}
/**
* 根据表情标记生成图片路径
* @param {string} emoText 表情标记 '#开心;'
* @returns {string} 图片完整路径
*/
const textToPath = (emoText) => {
const word = emoText.replace(/\#|\;/g, '')
const idx = emoTextList.indexOf(word)
// 若找不到对应表情,返回占位图或空字符串(此处返回原标记)
if (idx === -1) return emoText
return EMO_BASE_URL + idx + '.gif'
}
export default {
containEmoji,
emoTextList,
transform,
textToPath
}