Skip to content

Commit 7796cd0

Browse files
authored
Merge pull request #395 from eccenca/feature/markdownCutOff-CMEM-7659
Markdown component: cutOff property
2 parents 2e1dbc2 + af49730 commit 7796cd0

13 files changed

Lines changed: 1058 additions & 62 deletions

‎CHANGELOG.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,22 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p
1010

1111
- `<Switch />`
1212
- `noDrag` parameter: Add the `nodrag` class to the Switch element. Default: `true`
13+
- `<Markdown />`
14+
- Added `cutOff` property to set maximum number of raw Markdown characters to render
15+
- new `utils` methods:
16+
- `truncateMarkdownDisplay`: helper function to iterate over `Markdown` renderings to improve the experienced `cutOff` value
1317

1418
### Changed
1519

1620
- Upgrading base libraries
1721
- Carbon, Codemirror, React-Flow
1822
- minimum node version (`engines.node`) is `18.19.0` now
1923
- the build of the ESM distribution needs a synchronous `import.meta.resolve`, which is only available since this version
24+
- `<StringPreviewContentBlobToggler />`
25+
- `allowedHtmlElementsInPreview` option is set to inline elements on default
26+
- uses now the `Markdown.cutOff` property
27+
- this enables Markdown rendering even if the preview need to be shortened
28+
- this may lead to slightly different preview lengths
2029

2130
### Fixed
2231

‎src/cmem/ContentBlobToggler/StringPreviewContentBlobToggler.tsx‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import React from "react";
22

33
import { utils } from "../../common";
44
import InlineText from "../../components/Typography/InlineText";
5-
import { Markdown } from "../markdown/Markdown";
5+
import { Markdown, markdownAllowedInlineElements } from "../markdown/Markdown";
66

77
import { ContentBlobToggler, ContentBlobTogglerProps } from "./ContentBlobToggler";
88

@@ -50,7 +50,7 @@ export function StringPreviewContentBlobToggler({
5050
startExtended,
5151
useOnly,
5252
renderPreviewAsMarkdown = false,
53-
allowedHtmlElementsInPreview,
53+
allowedHtmlElementsInPreview = markdownAllowedInlineElements,
5454
noTogglerContentSuffix,
5555
...otherContentBlobTogglerProps
5656
}: StringPreviewContentBlobTogglerProps) {
@@ -77,7 +77,19 @@ export function StringPreviewContentBlobToggler({
7777
previewMaxLength &&
7878
utils.reduceToText(previewContent, { decodeHtmlEntities: true }).length > previewMaxLength
7979
) {
80-
previewContent = utils.reduceToText(previewContent, { decodeHtmlEntities: true }).slice(0, previewMaxLength);
80+
previewContent = renderPreviewAsMarkdown
81+
? utils.truncateMarkdownDisplay(
82+
<Markdown
83+
key="markdown-content"
84+
allowedElements={allowedHtmlElementsInPreview}
85+
cutOff={previewMaxLength}
86+
cutOffSuffix={""}
87+
>
88+
{previewString}
89+
</Markdown>,
90+
{ decodeHtmlEntities: true },
91+
)
92+
: utils.reduceToText(previewContent, { decodeHtmlEntities: true }).slice(0, previewMaxLength);
8193
enableToggler = true;
8294
}
8395

‎src/cmem/ContentBlobToggler/stories/StringPreviewContentBlobToggler.stories.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ const Template: StoryFn<typeof StringPreviewContentBlobToggler> = (args) => (
1414
);
1515

1616
const initialTeststring =
17-
"A library for GUI elements.\nIn order to create graphical user interfaces, please have look at the documentation at [Github](https://github.com/eccenca/gui-elements).";
17+
"# A library for [GUI elements](https://github.com/eccenca/gui-elements).\nIn order to create graphical user interfaces, please\n* have look at the documentation at [Github](https://github.com/eccenca/gui-elements).";
1818

1919
export const Default = Template.bind({});
2020
Default.args = {

‎src/cmem/ContentBlobToggler/tests/StringPreviewContentBlobToggler.test.tsx‎

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,8 @@ describe("StringPreviewContentBlobToggler", () => {
2323
{...(StringPreviewContentBlobTogglerStory.args as StringPreviewContentBlobTogglerProps)}
2424
/>,
2525
);
26-
textMustExist(queryByText, "A library for GUI elements.");
27-
textMustNotExist(
28-
queryByText,
29-
"In order to create graphical user interfaces, please have look at the documentation at",
30-
);
26+
textMustExist(queryByText, "A library for");
27+
textMustNotExist(queryByText, "documentation at");
3128
textMustExist(queryByText, "show more");
3229
});
3330
it("should display full view if `startExtended` is enabled, and show toggler to reduce", () => {
@@ -37,10 +34,8 @@ describe("StringPreviewContentBlobToggler", () => {
3734
startExtended
3835
/>,
3936
);
40-
textMustExist(
41-
queryByText,
42-
"In order to create graphical user interfaces, please have look at the documentation at",
43-
);
37+
textMustExist(queryByText, "In order to create graphical user interfaces, please");
38+
textMustExist(queryByText, "have look at the documentation at");
4439
textMustExist(queryByText, "show less");
4540
});
4641
it('should display only first content line on `useOnly={"firstNonEmptyLine"}`', () => {
@@ -50,7 +45,7 @@ describe("StringPreviewContentBlobToggler", () => {
5045
useOnly={"firstNonEmptyLine"}
5146
/>,
5247
);
53-
textMustExist(queryByText, "A library for GUI elements.");
48+
textMustExist(queryByText, "A library for");
5449
textMustNotExist(queryByText, "In order to create");
5550
});
5651
it('should use first Markdown paragraph as preview content on `useOnly={"firstMarkdownSection"}` but shorten it', () => {
@@ -60,9 +55,9 @@ describe("StringPreviewContentBlobToggler", () => {
6055
useOnly={"firstMarkdownSection"}
6156
/>,
6257
);
63-
textMustExist(queryByText, "A library for GUI elements.");
58+
textMustExist(queryByText, "A library for");
6459
textMustExist(queryByText, "In order to create");
65-
textMustNotExist(queryByText, "please have look at the documentation at");
60+
textMustNotExist(queryByText, "documentation at");
6661
});
6762
it("should display full preview and no toggler if content is short enough", () => {
6863
const { queryByText } = render(
@@ -71,11 +66,9 @@ describe("StringPreviewContentBlobToggler", () => {
7166
previewMaxLength={144}
7267
/>,
7368
);
74-
textMustExist(queryByText, "A library for GUI elements.");
75-
textMustExist(
76-
queryByText,
77-
"In order to create graphical user interfaces, please have look at the documentation at",
78-
);
69+
textMustExist(queryByText, "A library for");
70+
textMustExist(queryByText, "In order to create graphical user interfaces, please");
71+
textMustExist(queryByText, "have look at the documentation at");
7972
textMustNotExist(queryByText, "https://github.com/"); // test if Markdown was rendered
8073
textMustNotExist(queryByText, "show more");
8174
});
@@ -87,11 +80,7 @@ describe("StringPreviewContentBlobToggler", () => {
8780
renderPreviewAsMarkdown={false}
8881
/>,
8982
);
90-
textMustExist(queryByText, "A library for GUI elements.");
91-
textMustExist(
92-
queryByText,
93-
"In order to create graphical user interfaces, please have look at the documentation at",
94-
);
83+
textMustExist(queryByText, "A library for [GUI elements]"); // raw Markdown link syntax visible
9584
textMustExist(queryByText, "https://github.com/"); // test if Markdown was rendered
9685
textMustExist(queryByText, "show more");
9786
});

‎src/cmem/markdown/Markdown.stories.tsx‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,101 @@ A line with some <strong>HTML code</strong> inside.
6767
[^1]: This is the text related to the the footnote referrer.
6868
`,
6969
};
70+
71+
export const CutOff = Template.bind({});
72+
73+
const cutOffContent = `This component renders Markdown content safely. It supports **GitHub Flavoured Markdown**, syntax highlighting for code blocks, and definition lists.
74+
75+
You can:
76+
* configure _link targets_
77+
* add custom __rehype__ plugins
78+
* and filter content through an allowed elements list
79+
A third paragraph that will not appear once the cutOff limit is reached.`;
80+
81+
CutOff.args = {
82+
children: cutOffContent,
83+
cutOff: cutOffContent.indexOf("filter"),
84+
};
85+
86+
export const CutOffWithCodeFence = Template.bind({});
87+
88+
CutOffWithCodeFence.args = {
89+
children: `A short paragraph before the code block.
90+
Here is an important code example:
91+
\`\`\`json
92+
{
93+
"host": "localhost",
94+
"port": 8080,
95+
"debug": true
96+
}
97+
\`\`\`
98+
99+
This paragraph comes after the code block and should not appear when the cutOff limit falls inside the fence above.
100+
`,
101+
cutOff: 110,
102+
};
103+
104+
const indentedCodeFenceContent = `Intro.
105+
106+
\`\`\`ts
107+
const first = 1;
108+
const second = 2;
109+
\`\`\`
110+
111+
Outro.`;
112+
113+
export const CutOffWithIndentedCodeFence = Template.bind({});
114+
115+
CutOffWithIndentedCodeFence.args = {
116+
children: indentedCodeFenceContent,
117+
cutOff: indentedCodeFenceContent.indexOf("first"),
118+
};
119+
120+
export const CutOffWithLinks = Template.bind({});
121+
122+
CutOffWithLinks.args = {
123+
children: Array.from(
124+
{ length: 20 },
125+
(_, index) => `[open item ${index + 1}](https://example.com/item/${index + 1})`,
126+
).join(" "),
127+
cutOff: 80,
128+
};
129+
130+
export const CutOffWithFenceAndLink = Template.bind({});
131+
132+
CutOffWithFenceAndLink.args = {
133+
children: `A short paragraph before the code block.
134+
135+
\`\`\`ts
136+
const status = "ready";
137+
const nextStep = "open details";
138+
\`\`\`
139+
140+
~~~ts
141+
some code here
142+
~~~
143+
Continue with the [detailed implementation guide](https://example.com/docs/implementation/very/long/path) after the code block.`,
144+
cutOff: 153,
145+
};
146+
147+
export const CutOffWithTable = Template.bind({});
148+
149+
CutOffWithTable.args = {
150+
children: `| Name | Value |
151+
| --- | --- |
152+
| Alpha | First visible row |
153+
| Beta | Second visible row |
154+
| Gamma | Row that should not be partially rendered |
155+
156+
This paragraph comes after the table and should not appear in the preview.`,
157+
cutOff: 90,
158+
cutOffSuffix: "...",
159+
};
160+
161+
export const CutOffWithBoldText = Template.bind({});
162+
163+
CutOffWithBoldText.args = {
164+
children: "Some intro text and then **an important warning** and more text afterwards here.",
165+
cutOff: 35,
166+
};
167+
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
import React from "react";
2+
import { render } from "@testing-library/react";
3+
4+
import { truncateMarkdownDisplay } from "../../common/utils/truncateMarkdownDisplay";
5+
6+
import { Markdown } from "./Markdown";
7+
8+
describe("Markdown", () => {
9+
it("keeps markdown links valid when cutOff is calculated from rendered link labels", () => {
10+
const linkHeavy = Array.from({ length: 20 }, (_, i) => `[click](https://example.com/${i})`).join(" ");
11+
const { container } = render(<Markdown cutOff={60}>{linkHeavy}</Markdown>);
12+
13+
expect(container.querySelectorAll("a").length).toBeGreaterThan(0);
14+
expect(container.textContent).toContain("click");
15+
expect(container.textContent).not.toContain("https://example.com");
16+
});
17+
18+
it("backs up before a fenced code block when cutOff falls inside it after a paragraph boundary", () => {
19+
const content = [
20+
"Intro.",
21+
"",
22+
"```",
23+
"const first = 1;",
24+
"const second = 2;",
25+
"const third = 3;",
26+
"```",
27+
"",
28+
"Outro.",
29+
].join("\n");
30+
31+
const { container } = render(<Markdown cutOff={35}>{content}</Markdown>);
32+
33+
expect(container.querySelector("pre")).toBeFalsy();
34+
expect(container.textContent).toContain("Intro.");
35+
expect(container.textContent).not.toContain("const first");
36+
expect(container.textContent).not.toContain("Outro");
37+
});
38+
39+
it("backs up before a fenced code block when cutOff falls inside it after preceding text without a paragraph boundary", () => {
40+
const content = [
41+
"A short paragraph before the code block.",
42+
"Here is an important code example:",
43+
"```json",
44+
"{",
45+
' "host": "localhost"',
46+
"}",
47+
"```",
48+
"",
49+
"After fence.",
50+
].join("\n");
51+
52+
const { container } = render(<Markdown cutOff={content.indexOf("localhost")}>{content}</Markdown>);
53+
54+
expect(container.querySelector("pre")).toBeFalsy();
55+
expect(container.textContent).toContain("Here is an important code example:");
56+
expect(container.textContent).not.toContain("localhost");
57+
expect(container.textContent).not.toContain("After fence");
58+
});
59+
60+
it("renders a valid table when cutOff falls inside a markdown table", () => {
61+
const content = [
62+
"| Name | Value |",
63+
"| --- | --- |",
64+
"| alpha | one |",
65+
"| beta | two |",
66+
"| gamma | three |",
67+
"",
68+
"After table.",
69+
].join("\n");
70+
71+
const { container } = render(<Markdown cutOff={55}>{content}</Markdown>);
72+
73+
expect(container.querySelector("table")).toBeTruthy();
74+
expect(container.textContent).toContain("Name");
75+
expect(container.textContent).toContain("alpha");
76+
expect(container.textContent).not.toContain("After table");
77+
});
78+
79+
it("keeps a complete list when cutOff falls after it without a paragraph boundary", () => {
80+
const content = `This component renders Markdown content safely. It supports **GitHub Flavoured Markdown**, syntax highlighting for code blocks, and definition lists.
81+
82+
You can:
83+
* configure _link targets_
84+
* add custom __rehype__ plugins
85+
* and filter content through an allowed elements list
86+
A third paragraph that will not appear once the cutOff limit is reached.`;
87+
88+
const { container } = render(<Markdown cutOff={300}>{content}</Markdown>);
89+
90+
expect(container.textContent).toContain("You can:");
91+
expect(container.textContent).toContain("configure link targets");
92+
expect(container.textContent).toContain("add custom rehype plugins");
93+
expect(container.textContent).toContain("and filter content through an allowed elements list");
94+
expect(container.textContent).not.toContain("A third paragraph");
95+
});
96+
97+
it("keeps complete fenced blocks before a following link with display cutOff", () => {
98+
const content = [
99+
"A short paragraph before the code block.",
100+
"",
101+
"```ts",
102+
'const status = "ready";',
103+
'const nextStep = "open details";',
104+
"```",
105+
"",
106+
"~~~ts",
107+
"some code here",
108+
"~~~",
109+
"Continue with the [detailed implementation guide](https://example.com/docs/implementation/very/long/path) after the code block.",
110+
].join("\n");
111+
112+
for (const cutOff of [152, 153]) {
113+
const { container } = render(truncateMarkdownDisplay(<Markdown cutOff={cutOff}>{content}</Markdown>));
114+
115+
expect(container.querySelectorAll("pre")).toHaveLength(2);
116+
expect(container.textContent).toContain('const status = "ready";');
117+
expect(container.textContent).toContain("some code here");
118+
expect(container.textContent).toContain("Continue with the");
119+
expect(container.textContent).not.toContain("https://example.com");
120+
}
121+
});
122+
123+
it("renders a link at the end of long content when cutOff is absent", () => {
124+
const content = `${Array.from({ length: 40 }, (_, index) => `Long visible paragraph part ${index + 1}.`).join(
125+
" ",
126+
)} [final reference](https://example.com/final-reference)`;
127+
128+
const { container } = render(<Markdown>{content}</Markdown>);
129+
130+
expect(container.textContent).toContain("Long visible paragraph part 1.");
131+
expect(container.textContent).toContain("final reference");
132+
expect(container.querySelector('a[href="https://example.com/final-reference"]')).toBeTruthy();
133+
});
134+
});

0 commit comments

Comments
 (0)