|
1
|
import path from "path" |
|
2
|
import type { Transformer } from "unified" |
|
3
|
import type { Sidebar, UnistTree } from "types" |
|
4
|
|
|
5
|
export function pageNumberRehypePlugin({ |
|
6
|
sidebar, |
|
7
|
}: { |
|
8
|
sidebar: Sidebar.RawSidebarItem[] |
|
9
|
}): Transformer { |
|
10
|
return async (tree, file) => { |
|
11
|
const { valueToEstree } = await import("estree-util-value-to-estree") |
|
12
|
let number = "" |
|
13
|
|
|
14
|
if (file.history.length) { |
|
15
|
// get page path |
|
16
|
const pageFilePath = file.history[0].replace( |
|
17
|
path.join(file.cwd, "app"), |
|
18
|
"" |
|
19
|
) |
|
20
|
let pagePath = pageFilePath.replace(`/${path.basename(pageFilePath)}`, "") |
|
21
|
|
|
22
|
if (!pagePath.length) { |
|
23
|
pagePath = "/" |
|
24
|
} |
|
25
|
|
|
26
|
const pageSidebarItem = findSidebarItem(sidebar, pagePath) |
|
27
|
|
|
28
|
if (pageSidebarItem?.number) { |
|
29
|
number = pageSidebarItem?.number |
|
30
|
} |
|
31
|
} |
|
32
|
|
|
33
|
;(tree as UnistTree).children.unshift({ |
|
34
|
type: "mdxjsEsm", |
|
35
|
value: `export const pageNumber = "${number}"`, |
|
36
|
data: { |
|
37
|
estree: { |
|
38
|
type: "Program", |
|
39
|
body: [ |
|
40
|
{ |
|
41
|
type: "ExportNamedDeclaration", |
|
42
|
declaration: { |
|
43
|
type: "VariableDeclaration", |
|
44
|
declarations: [ |
|
45
|
{ |
|
46
|
type: "VariableDeclarator", |
|
47
|
id: { |
|
48
|
type: "Identifier", |
|
49
|
name: "pageNumber", |
|
50
|
}, |
|
51
|
init: valueToEstree(number), |
|
52
|
}, |
|
53
|
], |
|
54
|
kind: "const", |
|
55
|
}, |
|
56
|
specifiers: [], |
|
57
|
source: null, |
|
58
|
}, |
|
59
|
], |
|
60
|
sourceType: "module", |
|
61
|
}, |
|
62
|
}, |
|
63
|
}) |
|
64
|
} |
|
65
|
} |
|
66
|
|
|
67
|
function findSidebarItem( |
|
68
|
sidebar: Sidebar.RawSidebarItem[], |
|
69
|
path: string |
|
70
|
): Sidebar.RawSidebarItem | undefined { |
|
71
|
let foundItem = undefined |
|
72
|
for (const item of sidebar) { |
|
73
|
if (item.type === "separator") { |
|
74
|
continue |
|
75
|
} |
|
76
|
if (item.type === "link" && path === item.path) { |
|
77
|
foundItem = item |
|
78
|
} else if (item.children) { |
|
79
|
foundItem = findSidebarItem(item.children, path) |
|
80
|
} |
|
81
|
|
|
82
|
if (foundItem) { |
|
83
|
break |
|
84
|
} |
|
85
|
} |
|
86
|
|
|
87
|
return foundItem |
|
88
|
} |