Open History to see the last commit
1import type { ProjectEntry } from "@t3tools/contracts";
2import { isWindowsAbsolutePath } from "@t3tools/shared/path";
3
4import { isAbsolutePath } from "~/terminal-links";
5
6export interface FileBreadcrumb {
7 label: string;
8 path: string;
9 kind: "project" | "directory" | "file";
10}
11
12export interface FileBreadcrumbChild extends ProjectEntry {
13 label: string;
14}
15
16/**
17 * Crumbs for a workspace-relative path start at the project. An absolute host
18 * path is outside the workspace, so its crumbs start at the filesystem root.
19 */
20export function fileBreadcrumbs(projectName: string, relativePath: string): FileBreadcrumb[] {
21 const hostPath = isAbsolutePath(relativePath);
22 const separator = isWindowsAbsolutePath(relativePath) ? "\\" : "/";
23 const parts = relativePath.split(/[\\/]/).filter(Boolean);
24 const root = relativePath.startsWith("\\\\") ? "\\\\" : hostPath && separator === "/" ? "/" : "";
25 return [
26 ...(hostPath ? [] : [{ label: projectName, path: "", kind: "project" as const }]),
27 ...parts.map((part, index) => ({
28 label: part,
29 path: root + parts.slice(0, index + 1).join(separator),
30 kind: index === parts.length - 1 ? ("file" as const) : ("directory" as const),
31 })),
32 ];
33}
34
35export function fileBreadcrumbChildren(
36 entries: readonly ProjectEntry[],
37 directoryPath: string,
38): FileBreadcrumbChild[] {
39 const prefix = directoryPath ? `${directoryPath}/` : "";
40 return entries
41 .flatMap((entry) => {
42 if (!entry.path.startsWith(prefix)) return [];
43 const label = entry.path.slice(prefix.length);
44 if (!label || label.includes("/")) return [];
45 return [{ ...entry, label }];
46 })
47 .toSorted((left, right) => {
48 if (left.kind !== right.kind) return left.kind === "directory" ? -1 : 1;
49 return left.label.localeCompare(right.label, undefined, {
50 numeric: true,
51 sensitivity: "base",
52 });
53 });
54}
55
56export function fileBreadcrumbParent(directoryPath: string): string | null {
57 if (!directoryPath) return null;
58 const separatorIndex = directoryPath.lastIndexOf("/");
59 return separatorIndex === -1 ? "" : directoryPath.slice(0, separatorIndex);
60}