Skip to content

Commit 87a04b6

Browse files
committed
feat: create remark table plugin
1 parent eacb9ee commit 87a04b6

File tree

4 files changed

+49
-0
lines changed

4 files changed

+49
-0
lines changed

apps/site/next.mdx.plugins.mjs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import rehypeSlug from 'rehype-slug';
77
import remarkGfm from 'remark-gfm';
88
import readingTime from 'remark-reading-time';
99

10+
import remarkTableTitles from './util/table';
11+
1012
/**
1113
* Provides all our Rehype Plugins that are used within MDX
1214
*/
@@ -30,4 +32,5 @@ export const REMARK_PLUGINS = [
3032
remarkHeadings,
3133
// Calculates the reading time of the content
3234
readingTime,
35+
remarkTableTitles,
3336
];

apps/site/package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959
"feed": "~5.1.0",
6060
"github-slugger": "~2.0.0",
6161
"gray-matter": "~4.0.3",
62+
"mdast-util-to-string": "^4.0.0",
6263
"next": "15.5.0",
6364
"next-intl": "~4.3.4",
6465
"next-themes": "~0.4.6",
@@ -73,6 +74,7 @@
7374
"semver": "~7.7.2",
7475
"sval": "^0.6.3",
7576
"tailwindcss": "catalog:",
77+
"unist-util-visit": "^5.0.0",
7678
"vfile": "~6.0.3",
7779
"vfile-matter": "~5.0.1"
7880
},
@@ -85,6 +87,7 @@
8587
"@opennextjs/cloudflare": "^1.6.4",
8688
"@playwright/test": "^1.54.1",
8789
"@testing-library/user-event": "~14.6.1",
90+
"@types/mdast": "^4.0.4",
8891
"@types/mdx": "^2.0.13",
8992
"@types/semver": "~7.7.0",
9093
"eslint-config-next": "15.5.0",

apps/site/util/table.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import type { Root } from 'mdast';
2+
import { toString } from 'mdast-util-to-string';
3+
import { visit } from 'unist-util-visit';
4+
5+
/**
6+
* Remark plugin that adds data-label attributes to table cells (td)
7+
* based on their corresponding table headers (th).
8+
*/
9+
export default function remarkTableTitles() {
10+
return (tree: Root) => {
11+
visit(tree, 'table', table => {
12+
// Ensure table has at least a header row and one data row
13+
if (table.children.length < 2) return;
14+
15+
const [headerRow, ...dataRows] = table.children;
16+
17+
// Extract header labels from the first row
18+
const headerLabels = headerRow.children.map(headerCell =>
19+
toString(headerCell.children)
20+
);
21+
22+
// Assign data-label to each cell in data rows
23+
dataRows.forEach(row => {
24+
row.children.forEach((cell, idx) => {
25+
cell.data ??= {};
26+
27+
cell.data.hProperties = {
28+
'data-label': headerLabels[idx],
29+
};
30+
});
31+
});
32+
});
33+
};
34+
}

pnpm-lock.yaml

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)