refactor(nvim-tree): abstract away file tree building

This commit is contained in:
Pihkaal
2024-01-28 17:27:32 +01:00
parent 5542dce881
commit 965fff6226
3 changed files with 76 additions and 58 deletions

View File

@@ -1,11 +1,18 @@
import { type Cell } from "./terminal/cell";
import { theme } from "./terminal/theme";
import { type Manifest } from "./types";
export const FILE_STYLES = {
directory: {
char: "\ue6ad", // \ue6ad ||| \ueaf6
foreground: theme.blue,
},
export const getExtension = (path: string) => {
const parts = path.split(".");
return parts[Math.max(0, parts.length - 1)] ?? "";
};
export const DEFAULT_FILE_STYLE: Cell = {
char: "F",
foreground: theme.white,
};
export const FILE_STYLES: Record<string, Cell> = {
md: {
char: "\ue73e",
foreground: theme.blue,
@@ -14,15 +21,13 @@ export const FILE_STYLES = {
char: "\uf43d",
foreground: theme.yellow,
},
} as const satisfies Record<string, Cell>;
export type FileType = keyof typeof FILE_STYLES;
};
export type File = {
name: string;
} & (
| {
type: Exclude<FileType, "directory">;
type: "file";
}
| {
type: "directory";
@@ -30,3 +35,42 @@ export type File = {
folded: boolean;
}
);
const sortFiles = (files: Array<File>) =>
files
.sort((a, b) => a.name.localeCompare(b.name))
.sort((a, b) =>
a.type === "directory" && b.type !== "directory"
? -1
: a.type !== "directory" && b.type === "directory"
? 1
: 0,
);
export const buildFileTree = (manifest: Manifest): Array<File> => {
const files: Array<File> = [];
manifest.projects.forEach(project => {
if (project.name === "pihkaal") {
project.files.forEach(file => {
files.push({
name: file,
type: "file",
});
});
} else {
files.push({
name: project.name,
type: "directory",
folded: true,
children: sortFiles(
project.files.map(file => ({
name: file,
type: "file",
})),
),
});
}
});
return sortFiles(files);
};