Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

projectGrouping.ts

322 lines10.7 KB

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>;
16​
17export type ProjectGroupingMode = SidebarProjectGroupingMode;
18​
19export function selectProjectGroupingSettings(settings: ClientSettings): ProjectGroupingSettings {
20 return {
21 sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
22 sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
23 };
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;
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("\\", "/");
66​
67export function derivePhysicalProjectKeyFromPath(environmentId: string, cwd: string): string {
68 return `${environmentId}:${normalizeProjectPathForComparison(cwd)}`;
70​
71export function derivePhysicalProjectKey(
72 project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
73): string {
74 return derivePhysicalProjectKeyFromPath(project.environmentId, project.workspaceRoot);
76​
77export function deriveProjectGroupingOverrideKey(
78 project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
79): string {
80 return derivePhysicalProjectKey(project);
82​
83export function getProjectOrderKey(
84 project: Pick<EnvironmentProject, "environmentId" | "workspaceRoot">,
85): string {
86 return derivePhysicalProjectKey(project);
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 );
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}`;
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 );
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 });
154​
155export function deriveProjectGroupLabel(input: {
156 readonly representative: Pick<EnvironmentProject, "title" | "repositoryIdentity">;
157 readonly members: ReadonlyArray<Pick<EnvironmentProject, "title" | "repositoryIdentity">>;
158}): string {
159 const sharedTitles = uniqueNonEmptyValues(input.members.map((member) => member.title));
160 const sharedDisplayNames = uniqueNonEmptyValues(
161 input.members.map((member) => member.repositoryIdentity?.displayName),
162 );
163 const sharedRepositoryNames = uniqueNonEmptyValues(
164 input.members.map((member) => member.repositoryIdentity?.name),
165 );
166 const sharedTitle = sharedTitles[0];
167 if (
168 sharedTitles.length === 1 &&
169 sharedTitle !== undefined &&
170 !sharedDisplayNames.includes(sharedTitle) &&
171 !sharedRepositoryNames.includes(sharedTitle)
172 ) {
173 return sharedTitle;
174 }
175 if (sharedDisplayNames.length === 1) {
176 return sharedDisplayNames[0]!;
177 }
178​
179 if (sharedRepositoryNames.length === 1) {
180 return sharedRepositoryNames[0]!;
181 }
182​
183 return input.representative.title;
185​
186export interface ProjectGroupMember<TProject extends EnvironmentProject = EnvironmentProject> {
187 readonly physicalProjectKey: string;
188 readonly project: TProject;
190​
191export interface ProjectGroup<TProject extends EnvironmentProject = EnvironmentProject> {
192 readonly key: string;
193 readonly label: string;
194 readonly representative: TProject;
195 readonly members: ReadonlyArray<ProjectGroupMember<TProject>>;
196 readonly memberProjectRefs: ReadonlyArray<ScopedProjectRef>;
198​
199function projectFreshnessTime(project: EnvironmentProject): number {
200 const updatedAtTime = Date.parse(project.updatedAt);
201 if (Number.isFinite(updatedAtTime)) {
202 return updatedAtTime;
203 }
204 const createdAtTime = Date.parse(project.createdAt);
205 return Number.isFinite(createdAtTime) ? createdAtTime : 0;
207​
208function shouldReplacePhysicalProjectWinner<TProject extends EnvironmentProject>(
209 existing: TProject,
210 candidate: TProject,
211): boolean {
212 const freshnessDelta = projectFreshnessTime(candidate) - projectFreshnessTime(existing);
213 return freshnessDelta > 0 || (freshnessDelta === 0 && candidate.id > existing.id);
215​
216function selectProjectIdentitySource<TProject extends EnvironmentProject>(
217 projects: ReadonlyArray<TProject>,
218 winner: TProject,
219): TProject {
220 if (winner.repositoryIdentity !== null) {
221 return winner;
222 }
223​
224 let freshestIdentifiedProject: TProject | null = null;
225 for (const project of projects) {
226 if (project.repositoryIdentity === null) {
227 continue;
228 }
229 if (
230 freshestIdentifiedProject === null ||
231 shouldReplacePhysicalProjectWinner(freshestIdentifiedProject, project)
232 ) {
233 freshestIdentifiedProject = project;
234 }
235 }
236 return freshestIdentifiedProject ?? winner;
238​
239/**
240 * Builds logical project groups without losing the physical projects that
241 * remain the actual navigation and task-creation targets.
242 *
243 * Presentation-specific metadata, filtering, and activity sorting stay in
244 * each client. Grouping modes, overrides, physical deduplication, labels, and
245 * member preservation live here so web and mobile cannot drift.
246 */
247export function buildProjectGroups<TProject extends EnvironmentProject>(input: {
248 readonly projects: ReadonlyArray<TProject>;
249 readonly settings: ProjectGroupingSettings;
250 readonly preferredEnvironmentId?: EnvironmentId | null;
251}): ReadonlyArray<ProjectGroup<TProject>> {
252 const projectsByPhysicalKey = new Map<string, TProject[]>();
253 for (const project of input.projects) {
254 const physicalProjectKey = derivePhysicalProjectKey(project);
255 const existing = projectsByPhysicalKey.get(physicalProjectKey);
256 if (existing) {
257 existing.push(project);
258 } else {
259 projectsByPhysicalKey.set(physicalProjectKey, [project]);
260 }
261 }
262​
263 const logicalKeyByPhysicalKey = new Map<string, string>();
264 const groupedMembers = new Map<string, ProjectGroupMember<TProject>[]>();
265 for (const [physicalProjectKey, physicalProjects] of projectsByPhysicalKey) {
266 const winner = physicalProjects.reduce((current, candidate) =>
267 shouldReplacePhysicalProjectWinner(current, candidate) ? candidate : current,
268 );
269 const identitySource = selectProjectIdentitySource(physicalProjects, winner);
270 const logicalKey = deriveLogicalProjectKey(identitySource, {
271 groupingMode: resolveProjectGroupingMode(winner, input.settings),
272 });
273 logicalKeyByPhysicalKey.set(physicalProjectKey, logicalKey);
274 const member = { physicalProjectKey, project: winner };
275 const existing = groupedMembers.get(logicalKey);
276 if (existing) {
277 existing.push(member);
278 } else {
279 groupedMembers.set(logicalKey, [member]);
280 }
281 }
282​
283 const projectRefsByLogicalKey = new Map<string, ScopedProjectRef[]>();
284 const seenProjectRefs = new Set<string>();
285 for (const project of input.projects) {
286 const physicalProjectKey = derivePhysicalProjectKey(project);
287 const logicalKey =
288 logicalKeyByPhysicalKey.get(physicalProjectKey) ??
289 deriveLogicalProjectKeyFromSettings(project, input.settings);
290 const projectRefKey = scopedProjectKey(scopeProjectRef(project.environmentId, project.id));
291 if (seenProjectRefs.has(projectRefKey)) continue;
292 seenProjectRefs.add(projectRefKey);
293 const projectRef = scopeProjectRef(project.environmentId, project.id);
294 const existing = projectRefsByLogicalKey.get(logicalKey);
295 if (existing) {
296 existing.push(projectRef);
297 } else {
298 projectRefsByLogicalKey.set(logicalKey, [projectRef]);
299 }
300 }
301​
302 const preferredEnvironmentId = input.preferredEnvironmentId ?? null;
303 return Array.from(groupedMembers, ([key, members]) => {
304 const representative =
305 (preferredEnvironmentId
306 ? members.find((member) => member.project.environmentId === preferredEnvironmentId)?.project
307 : null) ?? members[0]!.project;
308 return {
309 key,
310 label:
311 members.length > 1
312 ? deriveProjectGroupLabel({
313 representative,
314 members: members.map((member) => member.project),
315 })
316 : representative.title,
317 representative,
318 members,
319 memberProjectRefs: projectRefsByLogicalKey.get(key) ?? [],
320 };
321 });