Skip to content
Open
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
1 change: 1 addition & 0 deletions src/cmem/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ export * from "./ContentBlobToggler";
export * from "./DateTimeDisplay/ElapsedDateTimeDisplay";
export * from "./markdown/Markdown";
export * from "./markdown/highlightSearchWords";
export * from "./markdown/markdownToText";
export * from "./react-flow";
17 changes: 17 additions & 0 deletions src/cmem/markdown/Markdown.test.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
import React from "react";
import ReactMarkdown from "react-markdown";
import { render } from "@testing-library/react";

import { truncateMarkdownDisplay } from "../../common/utils/truncateMarkdownDisplay";

import { Markdown } from "./Markdown";

jest.mock("react-markdown", () => {
const actual = jest.requireActual<typeof import("react-markdown")>("react-markdown");
return { ...actual, __esModule: true, default: jest.fn(actual.default) };
});

describe("Markdown", () => {
it("keeps the default rehype plugin count stable across renders", () => {
const getPluginCount = () => jest.mocked(ReactMarkdown).mock.lastCall?.[0].rehypePlugins?.length;
const { rerender } = render(<Markdown>First render</Markdown>);
const pluginCount = getPluginCount();
expect(pluginCount).toBeGreaterThan(0);

rerender(<Markdown>Second render</Markdown>);

expect(getPluginCount()).toBe(pluginCount);
});

it("keeps markdown links valid when cutOff is calculated from rendered link labels", () => {
const linkHeavy = Array.from({ length: 20 }, (_, i) => `[click](https://example.com/${i})`).join(" ");
const { container } = render(<Markdown cutOff={60}>{linkHeavy}</Markdown>);
Expand Down
19 changes: 6 additions & 13 deletions src/cmem/markdown/Markdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,6 @@ const configDefault = {
*/
// @see https://github.com/remarkjs/remark/blob/main/doc/plugins.md#list-of-plugins
remarkPlugins: [remarkGfm, remarkDefinitionList] as PluggableList,
// @see https://github.com/rehypejs/rehype/blob/main/doc/plugins.md#list-of-plugins
rehypePlugins: [] as PluggableList,
allowedElements: [...markdownAllowedInlineElements, ...markdownAllowedBlockElements],
// remove all unwanted HTML markup
unwrapDisallowed: true,
Expand All @@ -138,16 +136,14 @@ export const Markdown = ({
cutOffSuffix = DEFAULT_CUTOFF_SUFFIX,
...otherProps
}: MarkdownProps) => {
const configHtmlExternalLinks = {
rel: ["nofollow"],
target: linkTargetName,
};

configDefault.rehypePlugins = configDefault.rehypePlugins.concat([[rehypeExternalLinks, configHtmlExternalLinks]]);
const rehypePlugins: PluggableList = [
[rehypeExternalLinks, { rel: ["nofollow"], target: linkTargetName }],
...(allowHtml ? [rehypeRaw] : []),
...(reHypePlugins ?? []),
];

const configHtml = allowHtml
? {
rehypePlugins: [...configDefault.rehypePlugins].concat([rehypeRaw]),
// switch from allowed list to disallowed list
allowedElements: undefined,
disallowedElements: ["applet", "script", "style", "link", "iframe", "form", "button"],
Expand All @@ -166,6 +162,7 @@ export const Markdown = ({

const reactMarkdownProperties = {
children: renderContent.trim(),
rehypePlugins,
...configDefault,
...configHtml,
...configTextOnly,
Expand Down Expand Up @@ -195,10 +192,6 @@ export const Markdown = ({
allowedElements,
};

if (reHypePlugins) {
reactMarkdownProperties.rehypePlugins = reactMarkdownProperties.rehypePlugins.concat(reHypePlugins);
}

const markdownDisplay = <ReactMarkdown {...reactMarkdownProperties} />;
return inheritBlock && !(otherProps["data-test-id"] || htmlContentBlockProps) ? (
markdownDisplay
Expand Down
35 changes: 35 additions & 0 deletions src/cmem/markdown/markdownToText.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { markdownToText } from "../../../index";

describe("markdownToText", () => {
it("keeps link labels and code, and decodes entities", () => {
expect(
markdownToText(
"Use **regular expressions** and [replacement rules](https://example.com/hidden). `x < y` &amp; `a*b`.",
),
).toBe("Use regular expressions and replacement rules. x < y & a*b.");
});

it("preserves word boundaries across paragraphs, lists, line breaks, and table cells", () => {
const markdown = [
"# Overview",
"",
"- First item",
"- Second item",
"",
"Hard break\\",
"next line",
"",
"| Name | Value |",
"| --- | --- |",
"| alpha | one |",
].join("\n");

expect(markdownToText(markdown)).toBe(
"Overview First item Second item Hard break next line Name Value alpha one",
);
});

it("returns an empty string for blank Markdown", () => {
expect(markdownToText(" \n\t ")).toBe("");
});
});
19 changes: 19 additions & 0 deletions src/cmem/markdown/markdownToText.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import React from "react";

import { reduceToText } from "../../common/utils/reduceToText";

import { Markdown } from "./Markdown";

/** Extracts visible Markdown text and collapses whitespace to a single line. */
export const markdownToText = (markdown: string): string => {
if (!markdown.trim()) {
return "";
}

return reduceToText(
<Markdown inheritBlock removeMarkup allowedElements={[]}>
{markdown}
</Markdown>,
{ decodeHtmlEntities: true },
).replace(/\s+/g, " ");
};
Loading