Skip to content

Commit

Permalink
Added missing FindAndReplace
Browse files Browse the repository at this point in the history
  • Loading branch information
paales committed Feb 17, 2025
1 parent 6d2420c commit 6224558
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
35 changes: 35 additions & 0 deletions packages/next-ui/FindAndReplace/FindAndReplace.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import React from 'react'

export type FindAndReplacerProps = { part: string }

type FindAndReplaceTuple = [string, React.FC<FindAndReplacerProps> | React.ReactNode]

export type FindAndReplaceProps = {
source: string
findAndReplace: [FindAndReplaceTuple, ...FindAndReplaceTuple[]]
}

export function FindAndReplace(props: FindAndReplaceProps) {
const { source, findAndReplace } = props

// Create a regex pattern that matches any of the strings to be replaced
const pattern = new RegExp(
`(${findAndReplace.map(([find]) => find.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})`,
'g',
)

// Split the string and map parts to either original string or replaced content
const parts = source.split(pattern)

return parts.map((part, index) => {
const key = `${part}-${index}`
// Check if this part matches any of our replacement keys
const Replacement = findAndReplace.find(([find]) => find === part)?.[1]

if (!Replacement) return <React.Fragment key={key}>{part}</React.Fragment>
if (typeof Replacement === 'function') {
return <Replacement part={part} key={key} />
}
return <React.Fragment key={key}>{Replacement}</React.Fragment>
})
}
1 change: 1 addition & 0 deletions packages/next-ui/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export * from './Blog/BlogTitle/BlogTitle'
export * from './Breadcrumbs'
export * from './Button'
export * from './ChipMenu/ChipMenu'
export * from './FindAndReplace/FindAndReplace'
export * from './ContainerWithHeader/ContainerWithHeader'
export * from './Fab'
export * from './FlagAvatar/FlagAvatar'
Expand Down

0 comments on commit 6224558

Please sign in to comment.