refactor(utils): categorize functions into separate files (#6773)

This commit is contained in:
Joshua Chen 2022-02-26 21:17:21 +08:00 committed by GitHub
parent 908ad52025
commit 670f2e5268
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 928 additions and 886 deletions

View file

@ -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, '/');
}