Skip to content

Commit

Permalink
Added "pipeReplacer" and "prefixCellValues" options to table entries. (
Browse files Browse the repository at this point in the history
…#46)

pipeReplacer: This option supports use cases that require a different mechanism for
escaping pipes within tables. For example, including an Obsidian link with a display
name requires escaping with a slash (i.e. "\|") instead of using an HTML entity.

prefixCellValues: The default table rendering is to include the "prefix" string before
the value in every table cell, in addition to prefixing each individual table row. This
option allows this behavior to be disabled, so that cell values are not prefixed. (It
is possible the default behavior is a bug, but by providing a flag to change it this PR
maintains backwards compatibility.)
  • Loading branch information
skleinjung authored Jun 3, 2024
1 parent b381645 commit 5029ac9
Show file tree
Hide file tree
Showing 2 changed files with 124 additions and 12 deletions.
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 |`);
}
);

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

0 comments on commit 5029ac9

Please sign in to comment.