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

Added "pipeReplacer" and "prefixCellValues" options to table entries. #46

Merged
merged 1 commit into from
Jun 3, 2024
Merged
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
82 changes: 82 additions & 0 deletions src/renderers/table.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,29 @@ describe('given a table entry', () => {
| Row|3 | Row|4 |`
);
});

test('uses custom pipeReplacer function', () => {
expect(
tsMarkdown([
{
table: {
columns: ['Col|1', 'Col|2'],
rows: [
['Link', '[[Path/to/note.md|Display Text]]'],
['Row|3', 'Row|4'],
],
},
pipeReplacer: (content: string) =>
content.replace(/(?<!\\)\|/g, '\\|'),
},
])
).toBe(
`| Col\\|1 | Col\\|2 |
| ------ | --------------------------------- |
| Link | [[Path/to/note.md\\|Display Text]] |
| Row\\|3 | Row\\|4 |`
);
});
});

describe('with rich row text', () => {
Expand Down Expand Up @@ -237,6 +260,24 @@ describe('given a table entry', () => {
| **Row1&#124;&#124;** works |`
);
});

test('renders a markdown table with rich row text and escaped pipes, using a custom pipeReplacer function', () => {
expect(
tsMarkdown([
{
table: {
columns: ['Col1'],
rows: [[{ text: [{ bold: 'Row1||' }, ' works'] }]],
},
pipeReplacer: (content: string) => content.replace('|', '<PIPE>'),
},
])
).toBe(
`| Col1 |
| -------------------------- |
| **Row1<PIPE><PIPE>** works |`
);
});
});

describe('with rich text including a link in one row and rich text including an image in another row', () => {
Expand Down Expand Up @@ -406,4 +447,45 @@ describe('given a table entry', () => {
);
});
});

describe('with prefixCellValues option set', () => {
test.each([[undefined], [true]])(
'applies prefix to cell values when prefixCellValues = %s',
(prefixCellValues) => {
expect(
tsMarkdown([
{
blockquote: {
table: {
columns: ['Col1', 'Col2'],
rows: [['Row 1-Left', 'Row 1-Right']],
},
prefixCellValues,
},
},
])
).toBe(`> | Col1 | Col2 |
> | ------------ | ------------- |
> | > Row 1-Left | > Row 1-Right |`);
skleinjung marked this conversation as resolved.
Show resolved Hide resolved
}
);

test('does not prefix cell values when prefixCellValues = false', () => {
expect(
tsMarkdown([
{
blockquote: {
table: {
columns: ['Col1', 'Col2'],
rows: [['Row 1-Left', 'Row 1-Right']],
},
prefixCellValues: false,
},
},
])
).toBe(`> | Col1 | Col2 |
> | ---------- | ----------- |
> | Row 1-Left | Row 1-Right |`);
});
});
});
54 changes: 42 additions & 12 deletions src/renderers/table.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { renderEntries } from '../rendering';
import { MarkdownRenderer, RenderOptions } from '../rendering.types';
import {
InlineTypes,
MarkdownEntry,
SupportedPrimitive,
RichTextEntry,
} from '../shared.types';
import { TextEntry } from './text';

/**
* A markdown entry for generating tables.
Expand All @@ -31,6 +29,23 @@ export interface TableEntry extends MarkdownEntry {
* Option which will arbitrarily append a string immediately below the table, ignoring block-level settings.
*/
append?: string;

/**
* Function to replace pipes in a cell's content, which is necessary to avoid breaking the table layout.
* @defaultValue Function which replaces pipe characters with the entity "&#124;".
*/
pipeReplacer?: (content: string) => string;

/**
* Determines whether the "prefix" specified via RenderOptions is applied to cell values or not. If set to true,
* every data cell (excluding table headers and the separator row) will have the prefix prepended. If set to false,
* then the prefix will not be included in the cells.
*
* In any case, the prefix will be prepended to every row of the table (including header and separator rows).
*
* @defaultValue true
*/
prefixCellValues?: boolean;
}

/**
Expand Down Expand Up @@ -89,7 +104,7 @@ export const tableRenderer: MarkdownRenderer = (
};

function getTableMarkdown(entry: TableEntry, options: RenderOptions) {
escapePipes(entry);
escapePipes(entry, entry.pipeReplacer);
let columnCount = entry.table.columns.length;
let columnNames = entry.table.columns.reduce<string[]>(
(prev, curr) => prev.concat(typeof curr === 'string' ? curr : curr.name),
Expand All @@ -109,7 +124,7 @@ function getTableMarkdown(entry: TableEntry, options: RenderOptions) {
? curr[i]
: curr[getDataRowPropertyName(column)];
if (value !== undefined) {
let result = renderCellText(value, options);
let result = renderCellText(value, options, entry.prefixCellValues);
if (typeof result === 'string') {
prev.push(result);
} else {
Expand Down Expand Up @@ -149,7 +164,7 @@ function buildDataRows(
cells = [
...row.map((cell, index) =>
padAlign(
renderCellText(cell, options),
renderCellText(cell, options, entry.prefixCellValues),
cellWidths[index],
entry.table.columns[index]
)
Expand All @@ -160,7 +175,11 @@ function buildDataRows(
(prev, curr, index) =>
prev.concat(
padAlign(
renderCellText(row[getDataRowPropertyName(curr)], options) ?? '',
renderCellText(
row[getDataRowPropertyName(curr)],
options,
entry.prefixCellValues
) ?? '',
cellWidths[index],
entry.table.columns[index]
)
Expand All @@ -174,9 +193,13 @@ function buildDataRows(

function renderCellText(
value: RichTextEntry | SupportedPrimitive,
options: RenderOptions
options: RenderOptions,
prefixCellValues = true
): string {
return renderEntries([value], options);
return renderEntries([value], {
...options,
prefix: prefixCellValues ? options.prefix : '',
});
}

function padAlign(
Expand Down Expand Up @@ -248,21 +271,28 @@ function getColumnHeaderTextLength(column: string | TableColumn) {
return typeof column === 'string' ? column.length : column.name.length;
}

function escapePipes<T>(target: T): T {
function defaultPipeReplacer(content: string) {
return content.replaceAll('|', '&#124;');
}

function escapePipes<T>(
target: T,
pipeReplacer: (content: string) => string = defaultPipeReplacer
): T {
if (typeof target === 'string') {
return target.replaceAll('|', '&#124;') as unknown as T;
return pipeReplacer(target) as unknown as T;
}

if (Array.isArray(target)) {
for (let i = 0; i < target.length; i++) {
target[i] = escapePipes(target[i]);
target[i] = escapePipes(target[i], pipeReplacer);
}
}

if (typeof target === 'object' && target !== null) {
let assignable = target as Record<string, any>;
for (let key of Object.keys(assignable)) {
assignable[key] = escapePipes(assignable[key]);
assignable[key] = escapePipes(assignable[key], pipeReplacer);
}
}

Expand Down
Loading