feat(parser): support conditionals in template strings

This commit is contained in:
teidesu 2022-06-05 23:23:26 +03:00
parent e0d1102408
commit 1cce5c79a2
2 changed files with 19 additions and 6 deletions

View file

@ -20,10 +20,12 @@ const MENTION_REGEX =
*/ */
export function html( export function html(
strings: TemplateStringsArray, strings: TemplateStringsArray,
...sub: (string | FormattedString<'html'>)[] ...sub: (string | FormattedString<'html'> | boolean | undefined | null)[]
): FormattedString<'html'> { ): FormattedString<'html'> {
let str = '' let str = ''
sub.forEach((it, idx) => { sub.forEach((it, idx) => {
if (typeof it === 'boolean' || !it) return
if (typeof it === 'string') it = HtmlMessageEntityParser.escape(it) if (typeof it === 'string') it = HtmlMessageEntityParser.escape(it)
else { else {
if (it.mode && it.mode !== 'html') if (it.mode && it.mode !== 'html')

View file

@ -26,12 +26,18 @@ const TO_BE_ESCAPED = /[*_\-~`[\\\]|]/g
*/ */
export function md( export function md(
strings: TemplateStringsArray, strings: TemplateStringsArray,
...sub: (string | FormattedString<'markdown'>)[] ...sub: (
| string
| FormattedString<'markdown'>
| boolean
| undefined
| null
)[]
): FormattedString<'markdown'> { ): FormattedString<'markdown'> {
let str = '' let str = ''
sub.forEach((it, idx) => { sub.forEach((it, idx) => {
if (typeof it === 'string') if (typeof it === 'boolean' || !it) return
it = MarkdownMessageEntityParser.escape(it as string) if (typeof it === 'string') it = MarkdownMessageEntityParser.escape(it)
else { else {
if (it.mode && it.mode !== 'markdown') if (it.mode && it.mode !== 'markdown')
throw new Error(`Incompatible parse mode: ${it.mode}`) throw new Error(`Incompatible parse mode: ${it.mode}`)
@ -249,8 +255,13 @@ export class MarkdownMessageEntityParser implements IMessageEntityParser {
if (c === text[pos + 1]) { if (c === text[pos + 1]) {
// maybe (?) start or end of an entity // maybe (?) start or end of an entity
let type: 'Italic' | 'Bold' | 'Underline' | 'Strike' | 'Spoiler' | null = let type:
null | 'Italic'
| 'Bold'
| 'Underline'
| 'Strike'
| 'Spoiler'
| null = null
switch (c) { switch (c) {
case '_': case '_':
type = 'Italic' type = 'Italic'