-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgenerate-permalink.js
More file actions
50 lines (43 loc) · 2.14 KB
/
Copy pathgenerate-permalink.js
File metadata and controls
50 lines (43 loc) · 2.14 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
49
50
import slugify from '@sindresorhus/slugify';
/**
* @param {object} data - The data object for the current collection item.
* @param {string} collectionType - The collection type.
* @param {string} collectionSlug - A localized, URL-safe slug for the collection type, used in the generated permalink.
* @param {string} paginationSlug - A localized, URL-safe slug for paginated URLs such as /page/2, used in the generated permalink.
* @returns {string} - The generated permalink.
*/
export default function generatePermalink(data, collectionType, collectionSlug, paginationSlug = 'page') {
/*
If this post is a "stub" with no localized title, we assume it does not exist and prevent it from building.
*/
if (!Object.hasOwn(data, 'title')) {
return false;
}
const lang = data.lang || data.defaultLanguage;
const langSlug = data.supportedLanguages[lang].slug || lang;
collectionSlug ||= collectionType;
if (collectionType === 'pages') {
/*
If the page is a 404 page, return 404.html, optionally prepended with the language code.
*/
if (data.page.fileSlug === '404') {
return (lang === data.defaultLanguage) ? '/404.html' : `/${langSlug}/404.html`;
}
/**
If the page is the index page, the base path, optionally prepended with the language code.
*/
if (data.page.fileSlug === lang || data.page.inputPath.endsWith('index.md')) {
return (lang === data.defaultLanguage) ? '/' : `/${langSlug}/`;
}
/*
If the page is not the index page, return the page title in a URL-safe format, optionally prepended with the language code.
*/
const slug = data.slug || slugify(data.title, { decamelize: false });
if (Object.hasOwn(data, 'pagination') && data.pagination.pageNumber > 0) {
return (lang === data.defaultLanguage) ? `/${slug}/${paginationSlug}/${data.pagination.pageNumber + 1}/` : `/${langSlug}/${slug}/${paginationSlug}/${data.pagination.pageNumber + 1}/`;
}
return lang === data.defaultLanguage ? `/${slug}/` : `/${langSlug}/${slug}/`;
}
const slug = data.slug || slugify(data.title, { decamelize: false });
return lang === data.defaultLanguage ? `/${collectionSlug}/${slug}/` : `/${langSlug}/${collectionSlug}/${slug}/`;
}