Skip to content

Instantly share code, notes, and snippets.

@mainarthur
Created June 13, 2021 13:10
Show Gist options
  • Save mainarthur/965524bc0439dae75f4aa881c013618e to your computer and use it in GitHub Desktop.
Save mainarthur/965524bc0439dae75f4aa881c013618e to your computer and use it in GitHub Desktop.
const HTMLMap = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
}
/**
* @param {String} c
* @returns {String}
*/
const escapeHTMLChar = (c) => HTMLMap[c] ?? c
/**
*
* @param {String} name
* @param {Object} params
* @returns
*/
function tag(name, params) {
return {
open: params
? `<${name} ${Object.entries(params)
.map(
([key, value]) =>
`${key}="${value.replace(/[<&"]/g, escapeHTMLChar)}"`,
)
.join(' ')}>`
: `<${name}>`,
close: `</${name}>`,
}
}
const HTMLTags = {
bold: tag('b'),
italic: tag('i'),
code: tag('code'),
pre: tag('pre'),
strikethrough: tag('s'),
underline: tag('u'),
text_link: ({ url }) => tag('a', { href: url }),
text_mention: ({ user }) => tag('a', { href: `tg://user?id=${user.id}` }),
}
/**
*
* @param {import('node-telegram-bot-api').MessageEntity} entity
* @returns
*/
function getHTMLTag(entity) {
const tag = HTMLTags[entity.type || 'unknown']
if (!tag) return { open: '', close: '' }
return typeof tag === 'function' ? tag(entity) : tag
}
/**
*
* @param {String} text
* @param {import('node-telegram-bot-api').MessageEntity[]} entities
*/
const formatHTML = (text = '', entities = []) => {
const chars = ['', ...text, ''].map(escapeHTMLChar)
entities.forEach((entity) => {
const tag = getHTMLTag(entity)
const openPos = entity.offset
const closePos = entity.offset + entity.length + 1
chars[openPos] += tag.open
chars[closePos] = tag.close + chars[closePos]
})
return chars.join('')
}
module.exports = { getHTMLTag, HTMLTags, escapeHTMLChar, tag, formatHTML }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment