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 let collator: Intl.Collator | undefined;
40 const prefix = directoryPath ? `${directoryPath}/` : "";
41 return entries
42 .flatMap((entry) => {
43 if (!entry.path.startsWith(prefix)) return [];
44 const label = entry.path.slice(prefix.length);
45 if (!label || label.includes("/")) return [];
46 return [{ ...entry, label }];
47 })
48 .toSorted((left, right) => {
49 if (left.kind !== right.kind) return left.kind === "directory" ? -1 : 1;
50 collator ??= new Intl.Collator(undefined, {
51 numeric: true,
52 sensitivity: "base",
53 });
54 return collator.compare(left.label, right.label);
55 });
56}
57
58export function fileBreadcrumbParent(directoryPath: string): string | null {
59 if (!directoryPath) return null;
60 const separatorIndex = directoryPath.lastIndexOf("/");
61 return separatorIndex === -1 ? "" : directoryPath.slice(0, separatorIndex);
62}