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