52 lines · 1.9 KB · TypeScript
RawDownload
import {  fileBasename,  formatFilePathPosition,  splitFilePathPosition,  stripSlashPrefixedWindowsDrive,} from "@t3tools/client-runtime/markdown-links"; function normalizePathSeparators(path: string): string {  return path.replaceAll("\\", "/");} function trimTrailingPathSeparators(path: string): string {  return path.replace(/[\\/]+$/, "");} function stripRelativePrefixes(path: string): string {  return path.replace(/^\.\/+/, "").replace(/^\/+/, "");} export function formatWorkspaceRelativePath(  pathWithPosition: string,  workspaceRoot: string | undefined,): string {  const position = splitFilePathPosition(pathWithPosition);  const normalizedPath = stripSlashPrefixedWindowsDrive(normalizePathSeparators(position.path));   let displayPath = normalizedPath;  if (workspaceRoot) {    const normalizedWorkspaceRoot = stripSlashPrefixedWindowsDrive(      normalizePathSeparators(trimTrailingPathSeparators(workspaceRoot)),    );    const workspaceLabel = fileBasename(normalizedWorkspaceRoot);    const pathForCompare = normalizedPath.toLowerCase();    const workspaceForCompare = normalizedWorkspaceRoot.toLowerCase();    const workspaceWithSeparator = `${workspaceForCompare}/`;    const workspaceLabelWithSeparator = `${workspaceLabel.toLowerCase()}/`;     if (pathForCompare === workspaceForCompare) {      displayPath = workspaceLabel;    } else if (pathForCompare.startsWith(workspaceWithSeparator)) {      const relativeSuffix = normalizedPath.slice(normalizedWorkspaceRoot.length + 1);      displayPath = `${workspaceLabel}/${relativeSuffix}`;    } else if (!normalizedPath.startsWith("/")) {      const relativePath = stripRelativePrefixes(normalizedPath);      displayPath = pathForCompare.startsWith(workspaceLabelWithSeparator)        ? normalizedPath        : `${workspaceLabel}/${relativePath}`;    }  }   return formatFilePathPosition({ ...position, path: displayPath });}