Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/intl/.size-limit.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"name": "All publics",
"path": "dist/index.js",
"import": "*",
"limit": "1.8 kB"
"limit": "1.85 kB"
},
{
"name": "Minimal set",
Expand Down
46 changes: 46 additions & 0 deletions packages/intl/src/format/rich.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ const tags = {
strong: (chunks: (string | Node)[]) => ({
type: 'strong',
children: chunks
}),
br: () => ({
type: 'br',
children: []
})
}

Expand Down Expand Up @@ -93,6 +97,48 @@ describe('intl', () => {
'guidelines.'
])
})

it('should map self-closing tags', () => {
expect(mapTags('First line<br/>second line', tags)).toEqual([
'First line',
{
type: 'br',
children: []
},
'second line'
])
expect(mapTags('First line<br />second line', tags)).toEqual([
'First line',
{
type: 'br',
children: []
},
'second line'
])
})

it('should map self-closing tags inside other tags', () => {
expect(mapTags('<strong>First<br/>second</strong>', tags)).toEqual([
{
type: 'strong',
children: [
'First',
{
type: 'br',
children: []
},
'second'
]
}
])
})

it('should ignore unknown self-closing tags', () => {
expect(mapTags('First<hr/>second', tags)).toEqual([
'First',
'second'
])
})
})
})
})
9 changes: 6 additions & 3 deletions packages/intl/src/format/rich.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export function rich<T>(
}
}

const tagRegex = /<\/?([A-Za-z][\w.-]*)>/g
const tagRegex = /<(\/?)([A-Za-z][\w.-]*)\s*(\/?)>/g

interface RichFrame<T> {
tag: string
Expand All @@ -72,6 +72,7 @@ interface RichFrame<T> {

/**
* Maps rich-text tags in a string to chunks using provided tag handlers.
* Self-closing tags are mapped with empty chunks.
* Unknown or malformed tags are ignored as markup and only their text content is kept.
* @param input - Rich-text input string.
* @param tags - Tag handlers used to map known tags.
Expand All @@ -91,21 +92,23 @@ export function mapTags<T>(
let match: RegExpExecArray | null

while (match = tagRegex.exec(input)) {
const [rawTag, tag] = match
const [, closing, tag, selfClosing] = match
const current = stack[stack.length - 1]

if (match.index > lastIndex) {
current.chunks.push(input.slice(lastIndex, match.index))
}

if (tag in tags) {
if (rawTag[1] === '/') {
if (closing) {
if (current.tag === tag) {
stack.pop()
stack[stack.length - 1].chunks.push(
tags[tag](current.chunks)
)
}
} else if (selfClosing) {
current.chunks.push(tags[tag]([]))
} else {
stack.push({
tag,
Expand Down