Skip to content

Commit 86fadd5

Browse files
Fix IRC to discord formatting nested styles
1 parent bc71228 commit 86fadd5

File tree

2 files changed

+31
-8
lines changed

2 files changed

+31
-8
lines changed

lib/formatting.js

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,30 @@ export function formatFromDiscordToIRC(text) {
1818
}
1919

2020
export function formatFromIRCToDiscord(text) {
21-
const blocks = ircFormatting.parse(text);
22-
return blocks.map((block) => {
23-
let mdText = block.text;
24-
if (block.italic || block.reverse) mdText = `*${mdText}*`;
25-
if (block.bold) mdText = `**${mdText}**`;
26-
if (block.underline) mdText = `__${mdText}__`;
27-
return mdText;
28-
}).join('');
21+
const blocks = ircFormatting.parse(text).map(block =>
22+
// Consider reverse as italic, some IRC clients use that
23+
_.assign({}, block, { italic: block.italic || block.reverse })
24+
);
25+
let mdText = '';
26+
27+
for (let i = 0; i <= blocks.length; i += 1) {
28+
// Default to unstyled blocks when index out of range
29+
const block = blocks[i] || {};
30+
const prevBlock = blocks[i - 1] || {};
31+
32+
// Add start markers when style turns from false to true
33+
if (!prevBlock.italic && block.italic) mdText += '*';
34+
if (!prevBlock.bold && block.bold) mdText += '**';
35+
if (!prevBlock.underline && block.underline) mdText += '__';
36+
37+
// Add end markers when style turns from true to false
38+
// (and apply in reverse order to maintain nesting)
39+
if (prevBlock.underline && !block.underline) mdText += '__';
40+
if (prevBlock.bold && !block.bold) mdText += '**';
41+
if (prevBlock.italic && !block.italic) mdText += '*';
42+
43+
mdText += block.text || '';
44+
}
45+
46+
return mdText;
2947
}

test/formatting.test.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,5 +55,10 @@ describe('Formatting', () => {
5555
formatFromIRCToDiscord('\x02bold \x16italics\x16\x02')
5656
.should.equal('**bold *italics***');
5757
});
58+
59+
it('should convert nested IRC format', () => {
60+
formatFromIRCToDiscord('\x02bold \x1funderline\x1f\x02')
61+
.should.equal('**bold __underline__**');
62+
});
5863
});
5964
});

0 commit comments

Comments
 (0)