Improve changed-files tree UX and harden attachment path handling
- Compact single-directory chains in turn diff trees and preserve branch points - Add per-turn expand/collapse-all controls and themed VS Code file icons in ChatView - Centralize attachment route prefix stripping and tighten image/extension normalization helpers
This commit is contained in:
1 parent
d6ed393255
commit
5c03804bac
14 files changed
+204
-56
No files matched your search
@@ -2,6 +2,14 @@ import path from "node:path";
|
||||
|
||||
export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
|
||||
|
||||
export function stripAttachmentRoutePrefix(pathname: string): string | null {
|
||||
if (!pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
const remainder = pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||
return remainder.startsWith("/") ? remainder.slice(1) : remainder;
|
||||
}
|
||||
|
||||
export function normalizeAttachmentRelativePath(rawRelativePath: string): string | null {
|
||||
const normalized = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
|
||||
if (normalized.length === 0 || normalized.startsWith("..") || normalized.includes("\0")) {
|
||||
|
||||
@@ -14,6 +14,7 @@ const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
|
||||
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
|
||||
const ATTACHMENT_ID_UUID_PATTERN =
|
||||
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
||||
// Keep this regex strict so attachment IDs cannot be used as path traversal vectors.
|
||||
const ATTACHMENT_ID_PATTERN = new RegExp(
|
||||
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
|
||||
"i",
|
||||
|
||||
@@ -9,9 +9,12 @@
|
||||
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||
|
||||
export const DEFAULT_PORT = 3773;
|
||||
export const KEYBINDINGS_CONFIG_FILENAME = "keybindings.json" as const;
|
||||
|
||||
export type RuntimeMode = "web" | "desktop";
|
||||
|
||||
export const isDesktopMode = (mode: RuntimeMode): mode is "desktop" => mode === "desktop";
|
||||
|
||||
/**
|
||||
* ServerConfigShape - Process/runtime configuration required by the server.
|
||||
*/
|
||||
@@ -50,7 +53,7 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
|
||||
port: 0,
|
||||
host: undefined,
|
||||
authToken: undefined,
|
||||
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
|
||||
keybindingsConfigPath: path.join(statedir, KEYBINDINGS_CONFIG_FILENAME),
|
||||
staticDir: undefined,
|
||||
devUrl: undefined,
|
||||
noBrowser: false,
|
||||
|
||||
@@ -59,6 +59,8 @@ export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()(
|
||||
|
||||
/**
|
||||
* GitManagerServiceError - Errors emitted by stacked Git workflow orchestration.
|
||||
*
|
||||
* Keep this union centralized so callers can pattern-match once at API boundaries.
|
||||
*/
|
||||
export type GitManagerServiceError =
|
||||
| GitManagerError
|
||||
|
||||
@@ -38,6 +38,8 @@ export interface GitManagerShape {
|
||||
|
||||
/**
|
||||
* GitManager - Service tag for stacked Git workflow orchestration.
|
||||
*
|
||||
* Single tag keeps orchestration wiring swappable in Layer-based tests.
|
||||
*/
|
||||
export class GitManager extends ServiceMap.Service<GitManager, GitManagerShape>()(
|
||||
"t3/git/Services/GitManager",
|
||||
|
||||
@@ -62,6 +62,8 @@ export interface TextGenerationService {
|
||||
|
||||
/**
|
||||
* TextGenerationShape - Service API for commit/PR text generation.
|
||||
*
|
||||
* Interface isolates provider-specific model behavior behind deterministic method contracts.
|
||||
*/
|
||||
export interface TextGenerationShape {
|
||||
/**
|
||||
|
||||
@@ -29,6 +29,28 @@ export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
|
||||
".webp",
|
||||
]);
|
||||
|
||||
const normalizeImageExtension = (extension: string): string | null => {
|
||||
const trimmed = extension.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const lower = trimmed.toLowerCase();
|
||||
return lower.startsWith(".") ? lower : `.${lower}`;
|
||||
};
|
||||
|
||||
const coerceSafeImageExtension = (
|
||||
extension: string | null | undefined,
|
||||
): string | null => {
|
||||
if (!extension) return null;
|
||||
const normalized = normalizeImageExtension(extension);
|
||||
if (!normalized) return null;
|
||||
return SAFE_IMAGE_FILE_EXTENSIONS.has(normalized) ? normalized : null;
|
||||
};
|
||||
|
||||
export const isSafeImageExtension = (extension: string): boolean =>
|
||||
coerceSafeImageExtension(extension) !== null;
|
||||
|
||||
export function parseBase64DataUrl(
|
||||
dataUrl: string,
|
||||
): { readonly mimeType: string; readonly base64: string } | null {
|
||||
@@ -63,15 +85,15 @@ export function inferImageExtension(input: { mimeType: string; fileName?: string
|
||||
return fromMime;
|
||||
}
|
||||
|
||||
const fromMimeExtension = Mime.getExtension(input.mimeType);
|
||||
if (fromMimeExtension && SAFE_IMAGE_FILE_EXTENSIONS.has(fromMimeExtension)) {
|
||||
const fromMimeExtension = coerceSafeImageExtension(Mime.getExtension(input.mimeType));
|
||||
if (fromMimeExtension) {
|
||||
return fromMimeExtension;
|
||||
}
|
||||
|
||||
const fileName = input.fileName?.trim() ?? "";
|
||||
const extensionMatch = /\.([a-z0-9]{1,8})$/i.exec(fileName);
|
||||
const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : "";
|
||||
if (SAFE_IMAGE_FILE_EXTENSIONS.has(fileNameExtension)) {
|
||||
const fileNameExtension = extensionMatch ? coerceSafeImageExtension(extensionMatch[1]) : null;
|
||||
if (fileNameExtension) {
|
||||
return fileNameExtension;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import { version } from "../package.json" with { type: "json" };
|
||||
import { ServerLive } from "./wsServer";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
// Compose all required services once so every CLI invocation shares the same runtime.
|
||||
const RuntimeLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(CliConfig.layer),
|
||||
Layer.provideMerge(ServerLive),
|
||||
|
||||
+11
-7
@@ -12,8 +12,10 @@ import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
KEYBINDINGS_CONFIG_FILENAME,
|
||||
resolveStaticDir,
|
||||
ServerConfig,
|
||||
isDesktopMode,
|
||||
type RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
} from "./config";
|
||||
@@ -133,6 +135,8 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
);
|
||||
|
||||
const mode = Option.getOrElse(input.mode, () => env.mode);
|
||||
const isDesktop = isDesktopMode(mode);
|
||||
const isWeb = !isDesktop;
|
||||
|
||||
const port = yield* Option.match(input.port, {
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
@@ -140,7 +144,7 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
if (env.port) {
|
||||
return Effect.succeed(env.port);
|
||||
}
|
||||
if (mode === "desktop") {
|
||||
if (isDesktop) {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
@@ -153,15 +157,15 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
const noBrowser = Option.match(input.noBrowser, {
|
||||
// effect/cli boolean flags parse to `false` when absent; in that case
|
||||
// we still want env/mode fallbacks to apply.
|
||||
onSome: (value) => (value ? true : (env.noBrowser ?? mode === "desktop")),
|
||||
onNone: () => env.noBrowser ?? mode === "desktop",
|
||||
onSome: (value) => (value ? true : (env.noBrowser ?? isDesktop)),
|
||||
onNone: () => env.noBrowser ?? isDesktop,
|
||||
});
|
||||
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
|
||||
const autoBootstrapProjectFromCwd = Option.match(input.autoBootstrapProjectFromCwd, {
|
||||
// effect/cli boolean flags parse to `false` when absent; in that case
|
||||
// we still want env/mode fallbacks to apply.
|
||||
onSome: (value) => (value ? true : (env.autoBootstrapProjectFromCwd ?? mode === "web")),
|
||||
onNone: () => env.autoBootstrapProjectFromCwd ?? mode === "web",
|
||||
onSome: (value) => (value ? true : (env.autoBootstrapProjectFromCwd ?? isWeb)),
|
||||
onNone: () => env.autoBootstrapProjectFromCwd ?? isWeb,
|
||||
});
|
||||
const logWebSocketEvents = Option.match(input.logWebSocketEvents, {
|
||||
// effect/cli boolean flags parse to `false` when absent; in that case
|
||||
@@ -171,11 +175,11 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
});
|
||||
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
|
||||
const { join } = yield* Path.Path;
|
||||
const keybindingsConfigPath = join(stateDir, "keybindings.json");
|
||||
const keybindingsConfigPath = join(stateDir, KEYBINDINGS_CONFIG_FILENAME);
|
||||
const host =
|
||||
Option.getOrUndefined(input.host) ??
|
||||
env.host ??
|
||||
(mode === "desktop" ? "127.0.0.1" : undefined);
|
||||
(isDesktop ? "127.0.0.1" : undefined);
|
||||
|
||||
return {
|
||||
mode,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Effect, Path } from "effect";
|
||||
import { execFileSync } from "node:child_process";
|
||||
|
||||
export function fixPath(): void {
|
||||
// Only macOS shells need PATH hydration from interactive startup files.
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
|
||||
@@ -60,9 +60,9 @@ import { ServerConfig } from "./config";
|
||||
import { GitCore } from "./git/Services/GitCore.ts";
|
||||
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
|
||||
import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
stripAttachmentRoutePrefix,
|
||||
} from "./attachmentPaths";
|
||||
import {
|
||||
createAttachmentId,
|
||||
@@ -350,9 +350,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
||||
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
||||
const routeRelativePath = stripAttachmentRoutePrefix(url.pathname);
|
||||
if (routeRelativePath !== null) {
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(routeRelativePath);
|
||||
if (!normalizedRelativePath) {
|
||||
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
|
||||
return;
|
||||
|
||||
@@ -340,6 +340,7 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
pathValue: string;
|
||||
kind: "file" | "directory";
|
||||
theme: "light" | "dark";
|
||||
className?: string;
|
||||
}) {
|
||||
const [failedIconUrl, setFailedIconUrl] = useState<string | null>(null);
|
||||
const iconUrl = useMemo(
|
||||
@@ -350,9 +351,9 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
|
||||
if (failed) {
|
||||
return props.kind === "directory" ? (
|
||||
<FolderIcon className="size-4 text-muted-foreground/80" />
|
||||
<FolderIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
|
||||
) : (
|
||||
<FileIcon className="size-4 text-muted-foreground/80" />
|
||||
<FileIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
|
||||
);
|
||||
}
|
||||
|
||||
@@ -361,7 +362,7 @@ const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
src={iconUrl}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
className="size-4 shrink-0"
|
||||
className={cn("size-4 shrink-0", props.className)}
|
||||
loading="lazy"
|
||||
onError={() => setFailedIconUrl(iconUrl)}
|
||||
/>
|
||||
@@ -2554,6 +2555,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
isRevertingCheckpoint={isRevertingCheckpoint}
|
||||
onImageExpand={onExpandTimelineImage}
|
||||
markdownCwd={gitCwd ?? undefined}
|
||||
resolvedTheme={resolvedTheme}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -3154,14 +3156,23 @@ const DiffStatLabel = memo(function DiffStatLabel(props: {
|
||||
);
|
||||
});
|
||||
|
||||
function buildInitiallyExpandedDirectoryState(
|
||||
nodes: ReadonlyArray<TurnDiffTreeNode>,
|
||||
function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
|
||||
const paths: string[] = [];
|
||||
for (const node of nodes) {
|
||||
if (node.kind !== "directory") continue;
|
||||
paths.push(node.path);
|
||||
paths.push(...collectDirectoryPaths(node.children));
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
function buildDirectoryExpansionState(
|
||||
directoryPaths: ReadonlyArray<string>,
|
||||
expanded: boolean,
|
||||
): Record<string, boolean> {
|
||||
const expandedState: Record<string, boolean> = {};
|
||||
for (const node of nodes) {
|
||||
if (node.kind === "directory") {
|
||||
expandedState[node.path] = true;
|
||||
}
|
||||
for (const directoryPath of directoryPaths) {
|
||||
expandedState[directoryPath] = expanded;
|
||||
}
|
||||
return expandedState;
|
||||
}
|
||||
@@ -3169,13 +3180,27 @@ function buildInitiallyExpandedDirectoryState(
|
||||
const ChangedFilesTree = memo(function ChangedFilesTree(props: {
|
||||
turnId: TurnId;
|
||||
files: ReadonlyArray<TurnDiffFileChange>;
|
||||
allDirectoriesExpanded: boolean;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
}) {
|
||||
const { files, onOpenTurnDiff, turnId } = props;
|
||||
const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, turnId } = props;
|
||||
const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
|
||||
const [expandedDirectories, setExpandedDirectories] = useState<Record<string, boolean>>(
|
||||
() => buildInitiallyExpandedDirectoryState(treeNodes),
|
||||
const directoryPathsKey = useMemo(() => collectDirectoryPaths(treeNodes).join("\u0000"), [treeNodes]);
|
||||
const allDirectoryExpansionState = useMemo(
|
||||
() =>
|
||||
buildDirectoryExpansionState(
|
||||
directoryPathsKey ? directoryPathsKey.split("\u0000") : [],
|
||||
allDirectoriesExpanded,
|
||||
),
|
||||
[allDirectoriesExpanded, directoryPathsKey],
|
||||
);
|
||||
const [expandedDirectories, setExpandedDirectories] = useState<Record<string, boolean>>(
|
||||
() => buildDirectoryExpansionState((directoryPathsKey ? directoryPathsKey.split("\u0000") : []), true),
|
||||
);
|
||||
useEffect(() => {
|
||||
setExpandedDirectories(allDirectoryExpansionState);
|
||||
}, [allDirectoryExpansionState]);
|
||||
|
||||
const toggleDirectory = useCallback((pathValue: string) => {
|
||||
setExpandedDirectories((current) => ({
|
||||
@@ -3233,7 +3258,12 @@ const ChangedFilesTree = memo(function ChangedFilesTree(props: {
|
||||
onClick={() => onOpenTurnDiff(turnId, node.path)}
|
||||
>
|
||||
<span aria-hidden="true" className="size-3.5 shrink-0" />
|
||||
<FileIcon className="size-3.5 shrink-0 text-muted-foreground/70" />
|
||||
<VscodeEntryIcon
|
||||
pathValue={node.path}
|
||||
kind="file"
|
||||
theme={resolvedTheme}
|
||||
className="size-3.5 text-muted-foreground/70"
|
||||
/>
|
||||
<span className="truncate font-mono text-[11px] text-muted-foreground/80 group-hover:text-foreground/90">
|
||||
{node.name}
|
||||
</span>
|
||||
@@ -3272,6 +3302,7 @@ interface MessagesTimelineProps {
|
||||
isRevertingCheckpoint: boolean;
|
||||
onImageExpand: (preview: ExpandedImagePreview) => void;
|
||||
markdownCwd: string | undefined;
|
||||
resolvedTheme: "light" | "dark";
|
||||
}
|
||||
|
||||
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
|
||||
@@ -3312,6 +3343,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
isRevertingCheckpoint,
|
||||
onImageExpand,
|
||||
markdownCwd,
|
||||
resolvedTheme,
|
||||
}: MessagesTimelineProps) {
|
||||
const timelineRootRef = useRef<HTMLDivElement | null>(null);
|
||||
const [timelineWidthPx, setTimelineWidthPx] = useState<number | null>(null);
|
||||
@@ -3484,6 +3516,15 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
|
||||
const virtualRows = rowVirtualizer.getVirtualItems();
|
||||
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
|
||||
const [allDirectoriesExpandedByTurnId, setAllDirectoriesExpandedByTurnId] = useState<
|
||||
Record<string, boolean>
|
||||
>({});
|
||||
const onToggleAllDirectories = useCallback((turnId: TurnId) => {
|
||||
setAllDirectoriesExpandedByTurnId((current) => ({
|
||||
...current,
|
||||
[turnId]: !(current[turnId] ?? true),
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const renderRowContent = (row: TimelineRow) => (
|
||||
<div
|
||||
@@ -3659,6 +3700,8 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
if (checkpointFiles.length === 0) return null;
|
||||
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
|
||||
const changedFileCountLabel = String(checkpointFiles.length);
|
||||
const allDirectoriesExpanded =
|
||||
allDirectoriesExpandedByTurnId[turnSummary.turnId] ?? true;
|
||||
return (
|
||||
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
|
||||
<div className="mb-1.5 flex items-center justify-between gap-2">
|
||||
@@ -3674,21 +3717,33 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
|
||||
}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onToggleAllDirectories(turnSummary.turnId)}
|
||||
>
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
|
||||
}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnSummary.turnId}`}
|
||||
turnId={turnSummary.turnId}
|
||||
files={checkpointFiles}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -96,32 +96,54 @@ describe("buildTurnDiffTree", () => {
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "apps",
|
||||
path: "apps",
|
||||
name: "apps/web/src",
|
||||
path: "apps/web/src",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "index.ts",
|
||||
path: "apps/web/src/index.ts",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("compacts only single-directory chains and stops at branch points", () => {
|
||||
const tree = buildTurnDiffTree([
|
||||
{ path: "apps/server/src/index.ts", additions: 2, deletions: 1 },
|
||||
{ path: "apps/server/main.ts", additions: 4, deletions: 0 },
|
||||
]);
|
||||
|
||||
expect(tree).toEqual([
|
||||
{
|
||||
kind: "directory",
|
||||
name: "apps/server",
|
||||
path: "apps/server",
|
||||
stat: { additions: 6, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "directory",
|
||||
name: "web",
|
||||
path: "apps/web",
|
||||
name: "src",
|
||||
path: "apps/server/src",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "directory",
|
||||
name: "src",
|
||||
path: "apps/web/src",
|
||||
kind: "file",
|
||||
name: "index.ts",
|
||||
path: "apps/server/src/index.ts",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
children: [
|
||||
{
|
||||
kind: "file",
|
||||
name: "index.ts",
|
||||
path: "apps/web/src/index.ts",
|
||||
stat: { additions: 2, deletions: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: "file",
|
||||
name: "main.ts",
|
||||
path: "apps/server/main.ts",
|
||||
stat: { additions: 4, deletions: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -54,10 +54,34 @@ function readStat(file: TurnDiffFileChange): TurnDiffStat | null {
|
||||
};
|
||||
}
|
||||
|
||||
function compactDirectoryNode(node: TurnDiffTreeDirectoryNode): TurnDiffTreeDirectoryNode {
|
||||
const compactedChildren = node.children.map((child) =>
|
||||
child.kind === "directory" ? compactDirectoryNode(child) : child,
|
||||
);
|
||||
|
||||
let compactedNode: TurnDiffTreeDirectoryNode = {
|
||||
...node,
|
||||
children: compactedChildren,
|
||||
};
|
||||
|
||||
while (compactedNode.children.length === 1 && compactedNode.children[0]?.kind === "directory") {
|
||||
const onlyChild = compactedNode.children[0];
|
||||
compactedNode = {
|
||||
kind: "directory",
|
||||
name: `${compactedNode.name}/${onlyChild.name}`,
|
||||
path: onlyChild.path,
|
||||
stat: onlyChild.stat,
|
||||
children: onlyChild.children,
|
||||
};
|
||||
}
|
||||
|
||||
return compactedNode;
|
||||
}
|
||||
|
||||
function toTreeNodes(directory: MutableDirectoryNode): TurnDiffTreeNode[] {
|
||||
const subdirectories: TurnDiffTreeDirectoryNode[] = Array.from(directory.directories.values())
|
||||
.toSorted(compareByName)
|
||||
.map((subdirectory) => ({
|
||||
.map<TurnDiffTreeDirectoryNode>((subdirectory) => ({
|
||||
kind: "directory",
|
||||
name: subdirectory.name,
|
||||
path: subdirectory.path,
|
||||
@@ -66,7 +90,8 @@ function toTreeNodes(directory: MutableDirectoryNode): TurnDiffTreeNode[] {
|
||||
deletions: subdirectory.stat.deletions,
|
||||
},
|
||||
children: toTreeNodes(subdirectory),
|
||||
}));
|
||||
}))
|
||||
.map((subdirectory) => compactDirectoryNode(subdirectory));
|
||||
|
||||
const files = directory.files.toSorted(compareByName);
|
||||
return [...subdirectories, ...files];
|
||||
|
||||
Reference in new issue
Block a user