Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add code formatting to table headers & cells #92

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
21 changes: 15 additions & 6 deletions components/PostContent/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import ResponsiveEmbed from 'react-responsive-embed';
import truncate from 'truncate';
import slugify from 'utils/slugify';
import partnerStyles from '/pages/partners/[partnerSlug]/style.module.css';
import { backticksToHtmlCodeBlock } from '../../utils/backticksToHtmlCodeBlock';
import { parseShortCodes } from '../../utils/table';
import defaultStyles from './style.module.css';

Expand Down Expand Up @@ -363,18 +364,26 @@ function renderBlock(s, block, defaultAltForImages) {
<thead>
<tr>
{columns.map((col) => (
<th key={col.id} style={toCss(col.style)}>
{col.content}
</th>
<th
key={col.id}
style={toCss(col.style)}
dangerouslySetInnerHTML={{
__html: backticksToHtmlCodeBlock(col.content),
}}
/>
))}
</tr>
</thead>
{block.table.data.map((row) => (
<tr key={JSON.stringify(row)}>
{columns.map((col) => (
<td key={col.id} style={toCss(col.style)}>
{row[col.id]}
</td>
<td
key={col.id}
style={toCss(col.style)}
dangerouslySetInnerHTML={{
__html: backticksToHtmlCodeBlock(row[col.id]),
}}
/>
))}
</tr>
))}
Expand Down
21 changes: 21 additions & 0 deletions utils/backticksToHtmlCodeBlock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { escape as escapeHtml } from 'lodash-es';

/**
* Converts text wrapped in backticks within a string to HTML code blocks.
*
* Escapes HTML chars within the input string (using lodash's escape() func)
* then replaces instances of backtick-wrapped text with HTML `<code>` tags.
*
* In a React component, you'll have to use dangerouslySetInnerHTML to render this output.
*
* @param {string} input - The input string containing text with potential backtick-wrapped sections.
* @returns {string} - The input string with backtick-wrapped sections converted to `<code>` blocks.
*/
export const backticksToHtmlCodeBlock = (input) => {
const escapedInput = escapeHtml(input);
const backticksToCodeBlocks = escapedInput.replace(
/`([^`]+?)`/g,
'<code>$1</code>',
);
return backticksToCodeBlocks;
};