Skip to content

Commit b96edef

Browse files
committed
Fix formatHTML to work with emojis and HTML tags
1 parent c462c1c commit b96edef

2 files changed

Lines changed: 47 additions & 4 deletions

File tree

markup.js

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -168,11 +168,10 @@ class Markup {
168168
}
169169

170170
static formatHTML (text = '', entities = []) {
171-
const chars = [...text]
172171
const available = [...entities]
173172
const opened = []
174173
const result = []
175-
for (let offset = 0; offset < chars.length; offset++) {
174+
for (let offset = 0; offset < text.length; offset++) {
176175
while (true) {
177176
const index = available.findIndex((entity) => entity.offset === offset)
178177
if (index === -1) {
@@ -213,7 +212,7 @@ class Markup {
213212
available.splice(index, 1)
214213
}
215214

216-
result.push(chars[offset])
215+
result.push(escapeHTML(text[offset]))
217216

218217
while (true) {
219218
const index = opened.findIndex((entity) => entity.offset + entity.length - 1 === offset)
@@ -256,6 +255,18 @@ class Markup {
256255
}
257256
}
258257

258+
const escapedChars = {
259+
'"': '&quot;',
260+
'&': '&amp;',
261+
'<': '&lt;',
262+
'>': '&gt;'
263+
}
264+
265+
function escapeHTML (string) {
266+
const chars = [...string]
267+
return chars.map(char => escapedChars[char] || char).join('')
268+
}
269+
259270
function buildKeyboard (buttons, options) {
260271
const result = []
261272
if (!Array.isArray(buttons)) {

test/markup.js

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ test('should generate nested multi markup', (t) => {
222222
t.deepEqual(markup, '<s>strike<b>bold<u>under</u></b></s>')
223223
})
224224

225-
test.only('should generate nested multi markup 2', (t) => {
225+
test('should generate nested multi markup 2', (t) => {
226226
const markup = Markup.formatHTML('×11 22 333× ×С123456× ×1 22 333×', [
227227
{
228228
offset: 1,
@@ -252,3 +252,35 @@ test.only('should generate nested multi markup 2', (t) => {
252252
])
253253
t.deepEqual(markup, '×<b><i>11 22 333</i></b>× <i> ×С</i><i><b>123456× </b> ×1 22 333×</i>')
254254
})
255+
256+
test('should generate correct markup with emojis', (t) => {
257+
const markup = Markup.formatHTML('bold🙂👨‍👩‍👧‍👧 italic', [
258+
{
259+
offset: 0,
260+
length: 6,
261+
type: 'bold'
262+
},
263+
{
264+
offset: 18,
265+
length: 6,
266+
type: 'italic'
267+
}
268+
])
269+
t.deepEqual(markup, '<b>bold🙂</b>👨‍👩‍👧‍👧 <i>italic</i>')
270+
})
271+
272+
test('should generate correct markup with HTML tags', (t) => {
273+
const markup = Markup.formatHTML('<b>bold</b> <i>italic</i>', [
274+
{
275+
offset: 3,
276+
length: 4,
277+
type: 'bold'
278+
},
279+
{
280+
offset: 15,
281+
length: 6,
282+
type: 'italic'
283+
}
284+
])
285+
t.deepEqual(markup, '&lt;b&gt;<b>bold</b>&lt;/b&gt; &lt;i&gt;<i>italic</i>&lt;/i&gt;')
286+
})

0 commit comments

Comments
 (0)