fleet/frontend/components/ClickableUrls/ClickableUrls.tsx
Scott Gress 75bbbf6731
Fix issue with policy details modal causing 500 error page (#26628)
For #26604 

This PR fixes the way we import DOMPurify, so that we can access its
`sanitize` method.

I'm not sure why this popped up now -- the last release was a month ago.
Perhaps a new release of webpack or a related dependency in our build
chain?

**Before:**

![26604-broken](https://github.com/user-attachments/assets/629567a6-d989-45e2-a90c-eca8f69b1105)

---

**After:**

![26604-fixed](https://github.com/user-attachments/assets/4ec580f1-d189-4692-80d2-fee1d3ed8207)
2025-02-27 09:43:34 -06:00

38 lines
1.1 KiB
TypeScript

import React from "react";
import DOMPurify from "dompurify";
import classnames from "classnames";
interface IClickableUrls {
text: string;
className?: string;
}
const baseClass = "clickable-urls";
const urlReplacer = (match: string) => {
const url = match.startsWith("http") ? match : `https://${match}`;
return `<a href=${url} target="_blank" rel="noreferrer">
${match}
</a>`;
};
const ClickableUrls = ({ text, className }: IClickableUrls): JSX.Element => {
const clickableUrlClasses = classnames(baseClass, className);
// Regex to find case insensitive URLs and replace with link
const textWithLinks = text.replaceAll(
/(((https?)?(:\/\/))|((https?)?(:\/\/)?(www\.)))[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/g,
urlReplacer
);
const sanitizedTextWithLinks = DOMPurify.sanitize(textWithLinks, {
ADD_ATTR: ["target"], // Allows opening in a new tab
});
return (
<div
className={clickableUrlClasses}
dangerouslySetInnerHTML={{ __html: sanitizedTextWithLinks }}
/>
);
};
export default ClickableUrls;