forked from unraid/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sitebar-semver-sort.js
88 lines (76 loc) · 2.44 KB
/
sitebar-semver-sort.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Reverse the sidebar items ordering (including nested category items)
const semver = require("semver");
function getTitleFromItemId(id) {
return id.split("/").at(-1)
}
function getSemverFromId(id) {
try {
// console.log('id',id.split('/').at(-1))
return semver.parse(getTitleFromItemId(id));
} catch (error) {
return null;
}
}
function addItemTitle(item) {
return {
...item,
label: getTitleFromItemId(item.id)
}
}
/**
* This function sorts the Release Notes section by semver, leaving all other sorting to the default sorting algorthm
* More info below:
* https://docusaurus.io/docs/sidebar/autogenerated#customize-the-sidebar-items-generator
* @param {Array<{ type: 'doc' | 'autogenerated', 'id': string, 'items': Array<any>}>} items
* @param {*} sortBySemver
* @returns
*/
function sortSidebarItems(items, sortBySemver = false) {
// Reverse items in categories
const result = items.map((item) => {
if (item.type === "category") {
if (item.label === "Release Notes") {
return { ...item, items: sortSidebarItems(item.items, true) };
} else {
return { ...item, items: sortSidebarItems(item.items, false) };
}
}
return item;
});
if (sortBySemver) {
// Build subfolders for each major semver, then sort each one by minor semver
const subfolderArrays = result.reduce((acc, item) => {
const semverCompare = getSemverFromId(item.id);
const compareString = `${semverCompare.major}.${semverCompare.minor}`;
if (acc[compareString]) {
acc[compareString].push(item);
} else {
acc[compareString] = [item];
}
return acc;
}, {});
const subfolders = Object.entries(subfolderArrays).map(([folderName, items]) => {
// Sort the sub-items by semver (these are the actual release note docs)
const sortedSubfoler = items.map(addItemTitle).sort((a, b) => {
return semver.compare(getSemverFromId(a.id), getSemverFromId(b.id));
});
return {
type: "category",
label: folderName,
items: sortedSubfoler,
};
}).sort((a, b) => {
// Reorder a, b to change sort direction
return semver.compare(getSemverFromId(`${b.label}.0`), getSemverFromId(`${a.label}.0`));
});
// Set latest subfolder to open by default
if (subfolders[0]) {
subfolders[0].collapsed = false;
}
return subfolders;
}
return result;
}
module.exports = {
sortSidebarItems,
};