Open History to see the last commit
1import { scopedProjectKey, scopeProjectRef } from "../environment/scoped.ts";
2import type {
3 EnvironmentId,
4 ScopedProjectRef,
5 SidebarProjectGroupingMode,
6} from "@t3tools/contracts";
7import type { ClientSettings } from "@t3tools/contracts/settings";
8
9import type { EnvironmentProject } from "./models.ts";
10import { normalizeProjectPathForComparison } from "./projects.ts";
11
12export interface ProjectGroupingSettings {
13 readonly sidebarProjectGroupingMode: SidebarProjectGroupingMode;
14 readonly sidebarProjectGroupingOverrides: Record<string, SidebarProjectGroupingMode>;
15}
16
17export type ProjectGroupingMode = SidebarProjectGroupingMode;
18
19export function selectProjectGroupingSettings(settings: ClientSettings): ProjectGroupingSettings {
20 return {
21 sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
22 sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
23 };
24}
25
26function uniqueNonEmptyValues(values: ReadonlyArray<string | null | undefined>): string[] {
27 const seen = new Set<string>();
28 const unique: string[] = [];
29 for (const value of values) {
30 const trimmed = value?.trim();
31 if (!trimmed || seen.has(trimmed)) {
32 continue;
33 }
34 seen.add(trimmed);
35 unique.push(trimmed);
36 }
37 return unique;
38}
39
40function deriveRepositoryRelativeProjectPath(
41 project: Pick<EnvironmentProject, "workspaceRoot" | "repositoryIdentity">,
42): string | null {
43 const rootPath = project.repositoryIdentity?.rootPath?.trim();
44 if (!rootPath) {
45 return null;
46 }
47
48 const normalizedProjectPath = normalizeProjectPathForComparison(project.workspaceRoot);
49 const normalizedRootPath = normalizeProjectPathForComparison(rootPath);
50 if (normalizedProjectPath.length === 0 || normalizedRootPath.length === 0) {
51 return null;
52 }
53
54 if (normalizedProjectPath === normalizedRootPath) {
55 return "";
56 }
57
58 const separator = normalizedRootPath.includes("\\") ? "\\" : "/";
59 const rootPrefix = `${normalizedRootPath}${separator}`;
60 if (!normalizedProjectPath.startsWith(rootPrefix)) {
61 return null;
62 }
63
64 return normalizedProjectPath.slice(rootPrefix.length).replaceAll("\\", "/");
65}
66
67export function derivePhysicalProjectKeyFromPath(environmentId: string, cwd: string): string {
68 return `${environmentId}:${normalizeProjectPathForComparison(cwd)}`;
69}
70
71export function derivePhysicalProjectKey(
72 project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
73): string {
74 return derivePhysicalProjectKeyFromPath(project.environmentId, project.workspaceRoot);
75}
76
77export function deriveProjectGroupingOverrideKey(
78 project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
79): string {
80 return derivePhysicalProjectKey(project);
81}
82
83export function getProjectOrderKey(
84 project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
85): string {
86 return derivePhysicalProjectKey(project);
87}
88
89export function resolveProjectGroupingMode(
90 project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
91 settings: ProjectGroupingSettings,
92): SidebarProjectGroupingMode {
93 return (
94 settings.sidebarProjectGroupingOverrides?.[deriveProjectGroupingOverrideKey(project)] ??
95 settings.sidebarProjectGroupingMode
96 );
97}
98
99function deriveRepositoryScopedKey(
100 project: Pick<EnvironmentProject, "workspaceRoot" | "repositoryIdentity">,
101 groupingMode: SidebarProjectGroupingMode,
102): string | null {
103 const canonicalKey = project.repositoryIdentity?.canonicalKey;
104 if (!canonicalKey) {
105 return null;
106 }
107
108 if (groupingMode === "repository") {
109 return canonicalKey;
110 }
111
112 const relativeProjectPath = deriveRepositoryRelativeProjectPath(project);
113 if (relativeProjectPath === null) {
114 return canonicalKey;
115 }
116
117 return relativeProjectPath.length === 0
118 ? canonicalKey
119 : `${canonicalKey}::${relativeProjectPath}`;
120}
121
122export function deriveLogicalProjectKey(
123 project: Pick<
124 EnvironmentProject,
125 "environmentId" | "id" | "workspaceRoot" | "repositoryIdentity"
126 >,
127 options?: {
128 readonly groupingMode?: SidebarProjectGroupingMode;
129 },
130): string {
131 const groupingMode = options?.groupingMode ?? "repository";
132 if (groupingMode === "separate") {
133 return derivePhysicalProjectKey(project);
134 }
135
136 return (
137 deriveRepositoryScopedKey(project, groupingMode) ??
138 derivePhysicalProjectKey(project) ??
139 scopedProjectKey(scopeProjectRef(project.environmentId, project.id))
140 );
141}
142
143export function deriveLogicalProjectKeyFromSettings(
144 project: Pick<
145 EnvironmentProject,
146 "environmentId" | "id" | "workspaceRoot" | "repositoryIdentity"
147 >,
148 settings: ProjectGroupingSettings,
149): string {
150 return deriveLogicalProjectKey(project, {
151 groupingMode: resolveProjectGroupingMode(project, settings),
152 });
153}
154
155export function deriveLogicalProjectKeyFromRef(
156 projectRef: ScopedProjectRef,
157 project:
158 | Pick<EnvironmentProject, "environmentId" | "id" | "workspaceRoot" | "repositoryIdentity">
159 | null
160 | undefined,
161 options?: {
162 readonly groupingMode?: SidebarProjectGroupingMode;
163 },
164): string {
165 return project ? deriveLogicalProjectKey(project, options) : scopedProjectKey(projectRef);
166}
167
168export function deriveProjectGroupLabel(input: {
169 readonly representative: Pick<EnvironmentProject, "title" | "repositoryIdentity">;
170 readonly members: ReadonlyArray<Pick<EnvironmentProject, "title" | "repositoryIdentity">>;
171}): string {
172 const sharedTitles = uniqueNonEmptyValues(input.members.map((member) => member.title));
173 const sharedDisplayNames = uniqueNonEmptyValues(
174 input.members.map((member) => member.repositoryIdentity?.displayName),
175 );
176 const sharedRepositoryNames = uniqueNonEmptyValues(
177 input.members.map((member) => member.repositoryIdentity?.name),
178 );
179 const sharedTitle = sharedTitles[0];
180 if (
181 sharedTitles.length === 1 &&
182 sharedTitle !== undefined &&
183 !sharedDisplayNames.includes(sharedTitle) &&
184 !sharedRepositoryNames.includes(sharedTitle)
185 ) {
186 return sharedTitle;
187 }
188 if (sharedDisplayNames.length === 1) {
189 return sharedDisplayNames[0]!;
190 }
191
192 if (sharedRepositoryNames.length === 1) {
193 return sharedRepositoryNames[0]!;
194 }
195
196 return input.representative.title;
197}
198
199export interface ProjectGroupMember<TProject extends EnvironmentProject = EnvironmentProject> {
200 readonly physicalProjectKey: string;
201 readonly project: TProject;
202}
203
204export interface ProjectGroup<TProject extends EnvironmentProject = EnvironmentProject> {
205 readonly key: string;
206 readonly label: string;
207 readonly representative: TProject;
208 readonly members: ReadonlyArray<ProjectGroupMember<TProject>>;
209 readonly memberProjectRefs: ReadonlyArray<ScopedProjectRef>;
210}
211
212function projectFreshnessTime(project: EnvironmentProject): number {
213 const updatedAtTime = Date.parse(project.updatedAt);
214 if (Number.isFinite(updatedAtTime)) {
215 return updatedAtTime;
216 }
217 const createdAtTime = Date.parse(project.createdAt);
218 return Number.isFinite(createdAtTime) ? createdAtTime : 0;
219}
220
221function shouldReplacePhysicalProjectWinner<TProject extends EnvironmentProject>(
222 existing: TProject,
223 candidate: TProject,
224): boolean {
225 const freshnessDelta = projectFreshnessTime(candidate) - projectFreshnessTime(existing);
226 return freshnessDelta > 0 || (freshnessDelta === 0 && candidate.id > existing.id);
227}
228
229function selectProjectIdentitySource<TProject extends EnvironmentProject>(
230 projects: ReadonlyArray<TProject>,
231 winner: TProject,
232): TProject {
233 if (winner.repositoryIdentity !== null) {
234 return winner;
235 }
236
237 let freshestIdentifiedProject: TProject | null = null;
238 for (const project of projects) {
239 if (project.repositoryIdentity === null) {
240 continue;
241 }
242 if (
243 freshestIdentifiedProject === null ||
244 shouldReplacePhysicalProjectWinner(freshestIdentifiedProject, project)
245 ) {
246 freshestIdentifiedProject = project;
247 }
248 }
249 return freshestIdentifiedProject ?? winner;
250}
251
252/**
253 * Builds logical project groups without losing the physical projects that
254 * remain the actual navigation and task-creation targets.
255 *
256 * Presentation-specific metadata, filtering, and activity sorting stay in
257 * each client. Grouping modes, overrides, physical deduplication, labels, and
258 * member preservation live here so web and mobile cannot drift.
259 */
260export function buildProjectGroups<TProject extends EnvironmentProject>(input: {
261 readonly projects: ReadonlyArray<TProject>;
262 readonly settings: ProjectGroupingSettings;
263 readonly preferredEnvironmentId?: EnvironmentId | null;
264}): ReadonlyArray<ProjectGroup<TProject>> {
265 const projectsByPhysicalKey = new Map<string, TProject[]>();
266 for (const project of input.projects) {
267 const physicalProjectKey = derivePhysicalProjectKey(project);
268 const existing = projectsByPhysicalKey.get(physicalProjectKey);
269 if (existing) {
270 existing.push(project);
271 } else {
272 projectsByPhysicalKey.set(physicalProjectKey, [project]);
273 }
274 }
275
276 const logicalKeyByPhysicalKey = new Map<string, string>();
277 const groupedMembers = new Map<string, ProjectGroupMember<TProject>[]>();
278 for (const [physicalProjectKey, physicalProjects] of projectsByPhysicalKey) {
279 const winner = physicalProjects.reduce((current, candidate) =>
280 shouldReplacePhysicalProjectWinner(current, candidate) ? candidate : current,
281 );
282 const identitySource = selectProjectIdentitySource(physicalProjects, winner);
283 const logicalKey = deriveLogicalProjectKey(identitySource, {
284 groupingMode: resolveProjectGroupingMode(winner, input.settings),
285 });
286 logicalKeyByPhysicalKey.set(physicalProjectKey, logicalKey);
287 const member = { physicalProjectKey, project: winner };
288 const existing = groupedMembers.get(logicalKey);
289 if (existing) {
290 existing.push(member);
291 } else {
292 groupedMembers.set(logicalKey, [member]);
293 }
294 }
295
296 const projectRefsByLogicalKey = new Map<string, ScopedProjectRef[]>();
297 const seenProjectRefs = new Set<string>();
298 for (const project of input.projects) {
299 const physicalProjectKey = derivePhysicalProjectKey(project);
300 const logicalKey =
301 logicalKeyByPhysicalKey.get(physicalProjectKey) ??
302 deriveLogicalProjectKeyFromSettings(project, input.settings);
303 const projectRefKey = scopedProjectKey(scopeProjectRef(project.environmentId, project.id));
304 if (seenProjectRefs.has(projectRefKey)) continue;
305 seenProjectRefs.add(projectRefKey);
306 const projectRef = scopeProjectRef(project.environmentId, project.id);
307 const existing = projectRefsByLogicalKey.get(logicalKey);
308 if (existing) {
309 existing.push(projectRef);
310 } else {
311 projectRefsByLogicalKey.set(logicalKey, [projectRef]);
312 }
313 }
314
315 const preferredEnvironmentId = input.preferredEnvironmentId ?? null;
316 return Array.from(groupedMembers, ([key, members]) => {
317 const representative =
318 (preferredEnvironmentId
319 ? members.find((member) => member.project.environmentId === preferredEnvironmentId)?.project
320 : null) ?? members[0]!.project;
321 return {
322 key,
323 label:
324 members.length > 1
325 ? deriveProjectGroupLabel({
326 representative,
327 members: members.map((member) => member.project),
328 })
329 : representative.title,
330 representative,
331 members,
332 memberProjectRefs: projectRefsByLogicalKey.get(key) ?? [],
333 };
334 });
335}