on master help sign in
lib: add 'sort' to prev/next post functions

Lets you specify how a post is 'next' or 'previous'

commit0ac7aa84721dbd9f8248b540876f178fb4dcb178 authorMatilde Park <matilde@tlon.io> dateThu 22 Jul 2021, 15:57 (5 years ago) parent9667e77
1 file changed+16−8
lib/lib.js+16−8
lib/lib.js+16−8
@@ -27,8 +27,10 @@ const directories = (dir) => {
2727};
2828
2929export function getPostSlugs(key) {
30− const dir = fs.readdirSync(directories(key), { withFileTypes: true })
31− return dir.filter((f) => f.isFile() && f.name !== "_index.md").map((f) => f.name);
30+ const dir = fs.readdirSync(directories(key), { withFileTypes: true });
31+ return dir
32+ .filter((f) => f.isFile() && f.name !== "_index.md")
33+ .map((f) => f.name);
3234}
3335
3436// NB Gavin: This could be much simpler if we converted everything to a more common standard, like YAML
@@ -68,12 +70,18 @@ export function getPostBySlug(slug, fields = [], key) {
6870 return items;
6971}
7072
71−export function getAllPosts(fields = [], key) {
73+export function getAllPosts(fields = [], key, sort = "date") {
7274 const slugs = getPostSlugs(key);
7375 const posts = slugs
7476 .map((slug) => getPostBySlug(slug, fields, key))
7577 // sort posts by date in descending order
76− .sort((post1, post2) => (post1.date > post2.date ? -1 : 1));
78+ .sort((post1, post2) => {
79+ if (sort === "date") {
80+ return post1.date > post2.date ? -1 : 1;
81+ } else if (sort === "weight") {
82+ return post1.weight > post2.weight ? -1 : 1;
83+ }
84+ });
7785
7886 return posts;
7987}
@@ -98,10 +106,10 @@ export function getDocsPaths() {
98106 return getAllPaths(directories("docs"), []);
99107}
100108
101−export function getNextPost(slug, fields = [], key) {
109+export function getNextPost(slug, fields = [], key, sort = "date") {
102110 let resultPost = null;
103111
104− getAllPosts(fields, key).forEach((post, index, array) => {
112+ getAllPosts(fields, key, sort).forEach((post, index, array) => {
105113 if (post.slug === slug) {
106114 resultPost = array[index - 1];
107115 }
@@ -109,10 +117,10 @@ export function getNextPost(slug, fields = [], key) {
109117 return resultPost;
110118}
111119
112−export function getPreviousPost(slug, fields = [], key) {
120+export function getPreviousPost(slug, fields = [], key, sort = "date") {
113121 let resultPost = null;
114122
115− getAllPosts(fields, key).forEach((post, index, array) => {
123+ getAllPosts(fields, key, sort).forEach((post, index, array) => {
116124 if (post.slug === slug) {
117125 resultPost = array[index + 1];
118126 }