import type { ReactIsland } from "@ethicdevs/react-monolith";
import React, { useCallback } from "react";
import styled from "styled-components";
import type { RepositoryFile, RepositoryLog } from "../types";
import { Grid } from "../components";
export interface RepositoryTreeViewProps {
currentPath: string;
currentRef: string;
lastCommit: RepositoryLog;
orgSlug: string;
repoFiles: RepositoryFile[];
repoSlug: string;
}
const RepositoryTreeView: ReactIsland<RepositoryTreeViewProps> = ({
currentPath,
currentRef,
orgSlug,
repoFiles,
repoSlug,
}) => {
const buildRepoFileLink = useCallback(
(file: RepositoryFile) => {
const fileName = `${file.name}${file.type === "tree" ? "/" : ""}`;
return {
text: fileName,
href:
currentPath === "/"
? `/${orgSlug}/${repoSlug}/${currentRef}/tree/${fileName}`
: `/${orgSlug}/${repoSlug}/${currentRef}/tree/${
currentPath.endsWith("/") || currentPath === ""
? currentPath
: `${currentPath}/`
}${fileName}`,
};
},
[orgSlug, repoSlug, currentPath]
);
const currPathParts = currentPath.split("/");
let prevPath: string | null = currPathParts
.slice(0, currPathParts.length - 2)
.join("/");
prevPath = prevPath.trim() === "" ? null : prevPath;
prevPath = prevPath == null ? "/" : prevPath;
const prevPathLink =
prevPath === "/"
? `/${orgSlug}/${repoSlug}`
: `/${orgSlug}/${repoSlug}/${currentRef}/tree/${
prevPath.endsWith("/") ? prevPath : `${prevPath}/`
}`;
const shouldShowPrevPath = currentPath !== "/";
return (
<StyledRepositoryTreeViewContainer>
<Grid.Col fluid>
<Grid.Row
gap={8}
alignItems={"center"}
justifyContent={"flex-end"}
style={{ marginTop: 8, width: "100%" }}
>
<a href={`/${orgSlug}/${repoSlug}/commits`}>Commits History</a>
</Grid.Row>
<div>
<ul>
{shouldShowPrevPath && (
<li key={"go-previous"}>
<a href={prevPathLink}>..</a>
</li>
)}
{repoFiles.map((file) => {
const fileLink = buildRepoFileLink(file);
return (
<li key={[file.id, file.name].join(":")}>
<a href={fileLink.href}>{fileLink.text}</a>
</li>
);
})}
</ul>
</div>
</Grid.Col>
</StyledRepositoryTreeViewContainer>
);
};
const StyledRepositoryTreeViewContainer = styled.div`
width: 100%;
`;
RepositoryTreeView.displayName = "RepositoryTreeView";
export default RepositoryTreeView;