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
61 changes: 61 additions & 0 deletions packages/intl/src/format/rich.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,67 @@ describe('intl', () => {
'second'
])
})

it('should support nested calls in tag handlers', () => {
const nestedTags = {
...tags,
wrap: (chunks: (string | Node)[]) => ({
type: 'wrap',
children: [...chunks, ...mapTags('<strong>inner</strong>', tags)]
})
}

expect(mapTags('<wrap>outer</wrap> and <strong>after</strong>', nestedTags)).toEqual([
{
type: 'wrap',
children: [
'outer',
{
type: 'strong',
children: ['inner']
}
]
},
' and ',
{
type: 'strong',
children: ['after']
}
])
})

it('should pass unique index to tag handlers', () => {
const indexedTags = {
strong: (chunks: unknown[], index: number) => ({
type: 'strong',
index,
children: chunks
}),
br: (_: unknown[], index: number) => ({
type: 'br',
index,
children: []
})
}

expect(mapTags('<strong>First</strong><br/><strong>second</strong>', indexedTags)).toEqual([
{
type: 'strong',
index: 0,
children: ['First']
},
{
type: 'br',
index: 1,
children: []
},
{
type: 'strong',
index: 2,
children: ['second']
}
])
})
})
})
})
16 changes: 12 additions & 4 deletions packages/intl/src/format/rich.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Format } from './types.js'

export type RichChunks<T> = (string | T)[]

export type RichTag<T> = (chunks: RichChunks<T>) => T
export type RichTag<T> = (chunks: RichChunks<T>, index: number) => T

export type RichTags<T> = Record<string, RichTag<T>>

Expand Down Expand Up @@ -72,6 +72,7 @@ interface RichFrame<T> {

/**
* Maps rich-text tags in a string to chunks using provided tag handlers.
* Each handler call receives an unique index, usable as a key for framework nodes.
* 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.
Expand All @@ -89,8 +90,12 @@ export function mapTags<T>(
}
const stack = [root]
let lastIndex = 0
let index = 0
let match: RegExpExecArray | null

// reset the shared regex state possibly clobbered by an interrupted outer call
tagRegex.lastIndex = 0

while (match = tagRegex.exec(input)) {
const [, closing, tag, selfClosing] = match
const current = stack[stack.length - 1]
Expand All @@ -99,16 +104,18 @@ export function mapTags<T>(
current.chunks.push(input.slice(lastIndex, match.index))
}

lastIndex = tagRegex.lastIndex

if (tag in tags) {
if (closing) {
if (current.tag === tag) {
stack.pop()
stack[stack.length - 1].chunks.push(
tags[tag](current.chunks)
tags[tag](current.chunks, index++)
)
}
} else if (selfClosing) {
current.chunks.push(tags[tag]([]))
current.chunks.push(tags[tag]([], index++))
} else {
stack.push({
tag,
Expand All @@ -117,7 +124,8 @@ export function mapTags<T>(
}
}

lastIndex = tagRegex.lastIndex
// restore the shared regex state possibly clobbered by a nested call in a tag handler
tagRegex.lastIndex = lastIndex
}

if (lastIndex < input.length) {
Expand Down
9 changes: 5 additions & 4 deletions website/src/content/docs/intl/api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -410,17 +410,18 @@ $t().message({

### `rich(tags)` / `rich(fallback, tags)`

Maps lightweight tags inside translated strings to rich chunks.
Maps lightweight tags inside translated strings to rich chunks. Self-closing tags like `<br/>` are supported and mapped with empty chunks. Each tag handler also receives an unique index, usable as a key for framework nodes.

```ts
const [$t] = messages('docs', {
message: rich('Read <link>the docs</link>', {
link: chunks => <a href='/docs'>{chunks}</a>
message: rich('Read <link>the docs</link><br/>today', {
link: (chunks, i) => <a key={i} href='/docs'>{chunks}</a>,
br: (_, i) => <br key={i} />
})
})

$t().message
// ['Read ', <a href='/docs'>the docs</a>]
// ['Read ', <a href='/docs'>the docs</a>, <br />, 'today']
```

### `markup(tags)` / `markup(fallback, tags)`
Expand Down