Skip to content

Commit

Permalink
Add HighlightedText component
Browse files Browse the repository at this point in the history
  • Loading branch information
aleksandr-slobodian committed Jun 26, 2024
1 parent 7a505a5 commit 826ac8a
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/components/highlighted-text/HighlightedText.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { Meta, StoryObj } from "@storybook/react";
import { HighlightedText } from "./HighlightedText";

const meta: Meta<typeof HighlightedText> = {
title: "Components/HighlightedText",
component: HighlightedText,
};

export default meta;
type Story = StoryObj<typeof HighlightedText>;

export const Default: Story = {
args: {
text: "Lorem test string Test string",
highlight: "TesT",
},
};
35 changes: 35 additions & 0 deletions src/components/highlighted-text/HighlightedText.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import React, { ComponentProps } from "react";
import { splitTextWithHighlight } from "../../utils";

import styles from "./styles/index.module.scss";

interface IHighlightedTextProps {
text: string;
highlight?: string;
className?: ComponentProps<"div">["className"];
}

export const HighlightedText: React.FC<IHighlightedTextProps> = (props) => {
const { highlight, text, className } = props;

if (!highlight) {
return text;
}

const parts = splitTextWithHighlight(text, highlight);

return (
<span className={className}>
{parts.map((part, index) => {
if (part.toLowerCase() === highlight.toLowerCase()) {
return (
<span className={styles.highlight_text} key={`h-text-${index}`}>
{part}
</span>
);
}
return <span key={`nh-text-${index}`}>{part}</span>;
})}
</span>
);
};
1 change: 1 addition & 0 deletions src/components/highlighted-text/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./HighlightedText";
4 changes: 4 additions & 0 deletions src/components/highlighted-text/styles/index.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.highlight_text {
background-color: var(--pv-color-attention-tint-4);
color: var(--pv-color-attention-shade-3);
}
10 changes: 10 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,13 @@ export function formatBytes(bytes: number, decimals = 2) {

return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
}

export function escapeRegexCharacters(str: string) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

export function splitTextWithHighlight(text: string, highlight: string) {
const escapedHighlight = escapeRegexCharacters(highlight);
const highlightRegex = new RegExp(`(${escapedHighlight})`, "gi");
return text.split(highlightRegex);
}

0 comments on commit 826ac8a

Please sign in to comment.