-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Expand file tree
/
Copy pathtable.ts
More file actions
48 lines (40 loc) · 1.21 KB
/
table.ts
File metadata and controls
48 lines (40 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import type { Root } from 'mdast';
import { toString } from 'mdast-util-to-string';
import { visit } from 'unist-util-visit';
/**
* Remark plugin that adds data-label attributes to table cells (td)
* based on their corresponding table headers (th).
*/
export default function remarkTableTitles() {
return (tree: Root) => {
visit(tree, 'table', table => {
// Ensure table has at least a header row and one data row
if (table.children.length < 2) {
return;
}
const [headerRow, ...dataRows] = table.children;
if (headerRow.children.length <= 1) {
table.data ??= {};
table.data.hProperties = {
'data-cards': 'false',
};
}
// Extract header labels from the first row
const headerLabels = headerRow.children.map(headerCell =>
toString(headerCell.children)
);
// Assign data-label to each cell in data rows
dataRows.forEach(row => {
row.children.forEach((cell, idx) => {
cell.data ??= {};
if (idx > headerLabels.length) {
return;
}
cell.data.hProperties = {
'data-label': headerLabels[idx],
};
});
});
});
};
}