Skip to content

Commit

Permalink
feat(react): preserve newlines during string formatting (#2158)
Browse files Browse the repository at this point in the history
  • Loading branch information
Garbanas authored Jan 27, 2025
1 parent 20d8478 commit f0566fb
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
16 changes: 15 additions & 1 deletion packages/react/src/format.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@ describe("formatElements", function () {
).toEqual('<a href="/about">About</a>')
})

it("should preserve newlines", function () {
expect(html(formatElements("<0>Inn\ner</0>", { 0: <strong /> }))).toEqual(
"<strong>Inn\ner</strong>"
)

expect(
html(formatElements("Before <0>Inn\r\ner</0> After", { 0: <strong /> }))
).toEqual("Before <strong>Inn\r\ner</strong> After")

expect(
html(formatElements("<0>Ab\rout</0>", { 0: <a href="/about" /> }))
).toEqual('<a href="/about">Ab\rout</a>')
})

it("should preserve named element props", function () {
expect(
html(
Expand Down Expand Up @@ -69,7 +83,7 @@ describe("formatElements", function () {
)
)
).toEqual(
'Before <a href="/about">Inside <strong>Nested</strong> Between <br> After</a>'
'Before \n<a href="/about">Inside <strong>\nNested</strong>\n Between <br> After</a>'
)
})

Expand Down
5 changes: 2 additions & 3 deletions packages/react/src/format.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import React from "react"

// match <tag>paired</tag> and <tag/> unpaired tags
const tagRe = /<([a-zA-Z0-9]+)>(.*?)<\/\1>|<([a-zA-Z0-9]+)\/>/
const nlRe = /(?:\r\n|\r|\n)/g
const tagRe = /<([a-zA-Z0-9]+)>([\s\S]*?)<\/\1>|<([a-zA-Z0-9]+)\/>/

// For HTML, certain tags should omit their close tag. We keep a whitelist for
// those special-case tags.
Expand Down Expand Up @@ -37,7 +36,7 @@ function formatElements(
elements: { [key: string]: React.ReactElement } = {}
): string | React.ReactElement | Array<React.ReactElement | string> {
const uniqueId = makeCounter(0, "$lingui$")
const parts = value.replace(nlRe, "").split(tagRe)
const parts = value.split(tagRe)

// no inline elements, return
if (parts.length === 1) return value
Expand Down

0 comments on commit f0566fb

Please sign in to comment.