mirror of
https://github.com/facebook/docusaurus.git
synced 2025-08-06 10:20:09 +02:00
refactor(utils): categorize functions into separate files (#6773)
This commit is contained in:
parent
908ad52025
commit
670f2e5268
13 changed files with 928 additions and 886 deletions
|
@ -5,6 +5,9 @@
|
|||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {removeSuffix} from './jsUtils';
|
||||
import resolvePathnameUnsafe from 'resolve-pathname';
|
||||
|
||||
export function normalizeUrl(rawUrls: string[]): string {
|
||||
const urls = [...rawUrls];
|
||||
const resultArray = [];
|
||||
|
@ -94,3 +97,53 @@ export function getEditUrl(
|
|||
normalizeUrl([editUrl, fileRelativePath.replace(/\\/g, '/')])
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert filepath to url path.
|
||||
* Example: 'index.md' -> '/', 'foo/bar.js' -> '/foo/bar',
|
||||
*/
|
||||
export function fileToPath(file: string): string {
|
||||
const indexRE = /(?<dirname>^|.*\/)index\.(?:mdx?|jsx?|tsx?)$/i;
|
||||
const extRE = /\.(?:mdx?|jsx?|tsx?)$/;
|
||||
|
||||
if (indexRE.test(file)) {
|
||||
return file.replace(indexRE, '/$1');
|
||||
}
|
||||
return `/${file.replace(extRE, '').replace(/\\/g, '/')}`;
|
||||
}
|
||||
|
||||
export function encodePath(userPath: string): string {
|
||||
return userPath
|
||||
.split('/')
|
||||
.map((item) => encodeURIComponent(item))
|
||||
.join('/');
|
||||
}
|
||||
|
||||
export function isValidPathname(str: string): boolean {
|
||||
if (!str.startsWith('/')) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
// weird, but is there a better way?
|
||||
const parsedPathname = new URL(str, 'https://domain.com').pathname;
|
||||
return parsedPathname === str || parsedPathname === encodeURI(str);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// resolve pathname and fail fast if resolution fails
|
||||
export function resolvePathname(to: string, from?: string): string {
|
||||
return resolvePathnameUnsafe(to, from);
|
||||
}
|
||||
export function addLeadingSlash(str: string): string {
|
||||
return str.startsWith('/') ? str : `/${str}`;
|
||||
}
|
||||
|
||||
// TODO deduplicate: also present in @docusaurus/utils-common
|
||||
export function addTrailingSlash(str: string): string {
|
||||
return str.endsWith('/') ? str : `${str}/`;
|
||||
}
|
||||
export function removeTrailingSlash(str: string): string {
|
||||
return removeSuffix(str, '/');
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue