Open History to see the last commit
1import type { DraftId } from "~/composerDraftStore";
2import { useComposerDraftStore } from "~/composerDraftStore";
3import { resolveEnvironmentMachineKind, type ScopedProjectRef } from "@t3tools/contracts";
4import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
5import { isScratchProject } from "@t3tools/client-runtime/state/projects";
6import { FolderPlusIcon, MessageSquareDashedIcon } from "lucide-react";
7import { useAtomValue } from "@effect/atom-react";
8import { useCallback, useEffect, useMemo, useRef } from "react";
9
10import { openCommandPalette } from "~/commandPaletteBus";
11import { shortcutLabelForCommand } from "~/keybindings";
12import { projectIconColorClassName } from "~/projectIconColors";
13import { primaryServerKeybindingsAtom } from "~/state/server";
14import { useScratchProject } from "~/hooks/useScratchProject";
15import { useClientSettings } from "~/hooks/useSettings";
16import { hasExplicitComposerModelSelection } from "~/lib/chatThreadActions";
17import {
18 deriveLogicalProjectKeyFromSettings,
19 selectProjectGroupingSettings,
20} from "~/logicalProject";
21import {
22 buildSidebarProjectPickerEntries,
23 buildSidebarProjectSnapshots,
24 projectGroupsSpanEnvironments,
25} from "~/sidebarProjectGrouping";
26import { useProjects, useThreadShells } from "~/state/entities";
27import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";
28import { ProjectEnvironmentBadge } from "../ProjectEnvironmentBadge";
29import { ProjectFavicon } from "../ProjectFavicon";
30import { sortLogicalProjectsForSidebar } from "../Sidebar.logic";
31import {
32 Menu,
33 MenuItem,
34 MenuPopup,
35 MenuRadioGroup,
36 MenuRadioItem,
37 MenuSeparator,
38 MenuTrigger,
39} from "../ui/menu";
40import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
41import { InlineButton } from "../ui/button";
42import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
43
44// Menu value for "No project"; real entries are keyed by logical project key.
45const NO_PROJECT_VALUE = "no-project";
46
47interface DraftHeroHeadlineProps {
48 readonly draftId: DraftId | null;
49 readonly activeProjectRef: ScopedProjectRef | null;
50 readonly activeProjectTitle: string | null;
51}
52
53export function DraftHeroHeadline({
54 draftId,
55 activeProjectRef,
56 activeProjectTitle,
57}: DraftHeroHeadlineProps) {
58 const projects = useProjects();
59 const threads = useThreadShells();
60 const { environments } = useEnvironments();
61 const primaryEnvironmentId = usePrimaryEnvironmentId();
62 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
63 const projectSortOrder = useClientSettings((settings) => settings.sidebarProjectSortOrder);
64 const setLogicalProjectDraftThreadId = useComposerDraftStore(
65 (store) => store.setLogicalProjectDraftThreadId,
66 );
67 const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
68 const applyStickyState = useComposerDraftStore((store) => store.applyStickyState);
69 const setModelSelection = useComposerDraftStore((store) => store.setModelSelection);
70 const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);
71 const { scratchEnvironmentId, scratchWorkspaceRootFor, openScratchProject } = useScratchProject();
72 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
73
74 const environmentLabelById = useMemo(
75 () =>
76 new Map(
77 environments.map((environment) => [environment.environmentId, environment.label] as const),
78 ),
79 [environments],
80 );
81 const projectGroups = useMemo(
82 () =>
83 sortLogicalProjectsForSidebar(
84 buildSidebarProjectSnapshots({
85 projects,
86 settings: projectGroupingSettings,
87 primaryEnvironmentId,
88 resolveEnvironmentLabel: (environmentId) =>
89 environmentLabelById.get(environmentId) ?? null,
90 }),
91 threads,
92 projectSortOrder,
93 ),
94 [
95 environmentLabelById,
96 primaryEnvironmentId,
97 projectGroupingSettings,
98 projectSortOrder,
99 projects,
100 threads,
101 ],
102 );
103 // Same-named projects on two machines are only told apart by where they
104 // live, so rows on another machine carry its icon once the catalog spans
105 // more than one environment; a single-machine catalog stays as it was.
106 const showProjectEnvironments = useMemo(
107 () => projectGroupsSpanEnvironments(projectGroups),
108 [projectGroups],
109 );
110 const environmentMachineById = useMemo(
111 () =>
112 new Map(
113 environments.map(
114 (environment) =>
115 [
116 environment.environmentId,
117 resolveEnvironmentMachineKind(environment.serverConfig),
118 ] as const,
119 ),
120 ),
121 [environments],
122 );
123 const projectPickerEntries = useMemo(
124 () =>
125 buildSidebarProjectPickerEntries({
126 groups: projectGroups,
127 preferredProjectRef: activeProjectRef,
128 }),
129 [activeProjectRef, projectGroups],
130 );
131 const projectEntryByKey = useMemo(
132 () => new Map(projectPickerEntries.map((entry) => [entry.group.projectKey, entry] as const)),
133 [projectPickerEntries],
134 );
135 const activeProjectGroup =
136 activeProjectRef === null
137 ? null
138 : (projectGroups.find((group) =>
139 group.memberProjectRefs.some(
140 (projectRef) => scopedProjectKey(projectRef) === scopedProjectKey(activeProjectRef),
141 ),
142 ) ?? null);
143 const activeProjectKey = activeProjectGroup?.projectKey ?? "";
144 const activeProjectDisplayName = activeProjectGroup?.displayName ?? activeProjectTitle;
145 const hasResolvedProject = activeProjectTitle !== null;
146 const canChooseProject = projectPickerEntries.length > 0;
147 const shouldShowProjectMenu = canChooseProject;
148 // The project that hosts threads without a project appears once, as the
149 // "No project" item, not as a project row.
150 const menuEntries = projectPickerEntries.filter(
151 ({ targetProject }) =>
152 !isScratchProject(targetProject, scratchWorkspaceRootFor(targetProject.environmentId)),
153 );
154 const activeProject =
155 activeProjectRef === null
156 ? null
157 : (projects.find(
158 (project) =>
159 project.environmentId === activeProjectRef.environmentId &&
160 project.id === activeProjectRef.projectId,
161 ) ?? null);
162 const scratchTargetEnvironmentId = scratchEnvironmentId(
163 activeProjectRef?.environmentId ?? primaryEnvironmentId,
164 );
165 const scratchWorkspaceRoot = scratchWorkspaceRootFor(scratchTargetEnvironmentId);
166 const isScratchDraft =
167 activeProject !== null && isScratchProject(activeProject, scratchWorkspaceRoot);
168
169 // The picker can change the draft's target while the no-project home is
170 // still being opened; a stale continuation must not retarget it again.
171 const latestTargetRef = useRef({ draftId, activeProjectKey, scratchTargetEnvironmentId });
172 useEffect(() => {
173 latestTargetRef.current = { draftId, activeProjectKey, scratchTargetEnvironmentId };
174 }, [activeProjectKey, scratchTargetEnvironmentId, draftId]);
175 // Project selection changes the target of the open draft in place. The
176 // prompt stays in the same composer session, so the sidebar only gets a
177 // draft row if the user later navigates away.
178 const selectProject = (project: (typeof projects)[number], logicalProjectKey: string) => {
179 if (!draftId) {
180 return;
181 }
182 latestTargetRef.current = {
183 draftId,
184 activeProjectKey: logicalProjectKey,
185 scratchTargetEnvironmentId: project.environmentId,
186 };
187 const currentDraft = getComposerDraft(draftId);
188 setLogicalProjectDraftThreadId(
189 logicalProjectKey,
190 scopeProjectRef(project.environmentId, project.id),
191 draftId,
192 );
193 if (!hasExplicitComposerModelSelection(currentDraft)) {
194 applyStickyState(draftId);
195 const environmentSettings = environments.find(
196 (environment) => environment.environmentId === project.environmentId,
197 )?.serverConfig?.settings;
198 const defaultModelSelection = environmentSettings
199 ? resolveProjectSettings(environmentSettings, project.id, project).settings
200 .defaultModelSelection
201 : project.defaultModelSelection;
202 if (defaultModelSelection) {
203 setModelSelection(draftId, defaultModelSelection, {
204 replaceOptions: true,
205 });
206 }
207 }
208 };
209 const startScratch = async (): Promise<boolean> => {
210 if (scratchTargetEnvironmentId === null || isScratchDraft) {
211 return false;
212 }
213 const requested = { draftId, activeProjectKey, scratchTargetEnvironmentId };
214 const project = await openScratchProject(scratchTargetEnvironmentId);
215 const latest = latestTargetRef.current;
216 if (
217 !project ||
218 latest.draftId !== requested.draftId ||
219 latest.activeProjectKey !== requested.activeProjectKey ||
220 latest.scratchTargetEnvironmentId !== requested.scratchTargetEnvironmentId
221 ) {
222 return false;
223 }
224 selectProject(project, deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings));
225 return true;
226 };
227
228 const projectSelector = shouldShowProjectMenu ? (
229 <Menu>
230 <Tooltip>
231 <TooltipTrigger
232 render={
233 // The trigger's accessible name comes from its visible text (the
234 // project title) so the hero sentence reads naturally: an
235 // aria-label here would replace the title with an action phrase
236 // mid-sentence and baffle screen-reader users.
237 <MenuTrigger
238 render={<InlineButton tone="picker" />}
239 data-draft-project-trigger=""
240 className="pointer-events-auto max-w-64 align-baseline"
241 />
242 }
243 >
244 <span className="min-w-0 truncate">
245 {isScratchDraft ? "No project" : (activeProjectDisplayName ?? "Choose a project")}
246 </span>
247 </TooltipTrigger>
248 {activeProjectDisplayName && !isScratchDraft ? (
249 <TooltipPopup side="top">{activeProjectDisplayName}</TooltipPopup>
250 ) : null}
251 </Tooltip>
252 <MenuPopup align="center" className="max-h-80 overflow-y-auto">
253 <MenuRadioGroup
254 value={isScratchDraft ? NO_PROJECT_VALUE : activeProjectKey}
255 onValueChange={(value) => {
256 if (value === NO_PROJECT_VALUE) {
257 void startScratch();
258 return;
259 }
260 const entry = projectEntryByKey.get(value as string);
261 if (!entry || value === activeProjectKey) {
262 return;
263 }
264 selectProject(entry.targetProject, entry.group.projectKey);
265 }}
266 >
267 {scratchWorkspaceRoot === null ? null : (
268 <MenuRadioItem value={NO_PROJECT_VALUE} closeOnClick>
269 <span className="flex min-w-0 items-center gap-2">
270 {/* Boxed like ProjectFavicon so the label lines up with project rows. */}
271 <span
272 aria-hidden="true"
273 className={`inline-flex size-4 shrink-0 ${projectIconColorClassName("gray")}`}
274 >
275 <MessageSquareDashedIcon className="size-full" />
276 </span>
277 No project
278 </span>
279 </MenuRadioItem>
280 )}
281 {menuEntries.map(({ group }) => {
282 return (
283 <MenuRadioItem key={group.projectKey} value={group.projectKey} closeOnClick>
284 <span className="flex min-w-0 items-center gap-2">
285 <ProjectFavicon project={group} className="size-4 shrink-0" />
286 <Tooltip>
287 <TooltipTrigger render={<span className="block min-w-0 truncate" />}>
288 {group.displayName}
289 </TooltipTrigger>
290 <TooltipPopup side="top">{group.displayName}</TooltipPopup>
291 </Tooltip>
292 {showProjectEnvironments ? (
293 <ProjectEnvironmentBadge
294 group={group}
295 primaryEnvironmentId={primaryEnvironmentId}
296 machineByEnvironmentId={environmentMachineById}
297 />
298 ) : null}
299 </span>
300 </MenuRadioItem>
301 );
302 })}
303 </MenuRadioGroup>
304 {projectPickerEntries.length > 0 ? <MenuSeparator /> : null}
305 <MenuItem onClick={openAddProject}>
306 <FolderPlusIcon />
307 New project
308 </MenuItem>
309 </MenuPopup>
310 </Menu>
311 ) : (
312 <button
313 type="button"
314 onClick={openAddProject}
315 className="pointer-events-auto inline cursor-pointer border-muted-foreground/35 border-b border-dotted text-muted-foreground/60 transition-colors hover:border-muted-foreground/60 hover:text-muted-foreground/80 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
316 >
317 {activeProjectTitle ?? "Add a project"}
318 </button>
319 );
320
321 // The composer hero is a sentence, so the heading's accessible name must be
322 // a complete sentence too. The project picker is a control rendered inline
323 // in the h1; without an explicit label its widget state bleeds into the
324 // announced phrase.
325 const headingLabel = isScratchDraft
326 ? "What should we work on?"
327 : hasResolvedProject
328 ? `What should we build in ${activeProjectDisplayName}?`
329 : canChooseProject
330 ? `${activeProjectDisplayName ?? "Choose a project"} to start`
331 : "Add a project to start";
332
333 // One click out of the project, phrased as the alternative to the question
334 // above it. Focus moves to the project picker once this line has gone.
335 const noProjectShortcut = shortcutLabelForCommand(keybindings, "chat.newWithoutProject");
336 const orStartWithoutProject =
337 scratchWorkspaceRoot !== null && !isScratchDraft && (hasResolvedProject || canChooseProject) ? (
338 <Tooltip>
339 <TooltipTrigger
340 render={
341 <InlineButton
342 tone="muted"
343 className="pointer-events-auto"
344 onClick={() =>
345 void startScratch().then((started) => {
346 if (started) {
347 document.querySelector<HTMLElement>("[data-draft-project-trigger]")?.focus();
348 }
349 })
350 }
351 />
352 }
353 >
354 or start without a project
355 </TooltipTrigger>
356 {noProjectShortcut ? <TooltipPopup side="bottom">{noProjectShortcut}</TooltipPopup> : null}
357 </Tooltip>
358 ) : null;
359
360 return (
361 <div className="mx-auto flex w-full max-w-5xl flex-col items-center">
362 <h1
363 aria-label={headingLabel}
364 className="w-full text-center font-normal text-2xl text-foreground tracking-tight sm:text-3xl"
365 >
366 {isScratchDraft ? (
367 <>What should we work on?</>
368 ) : hasResolvedProject ? (
369 <>What should we build in {projectSelector}?</>
370 ) : canChooseProject ? (
371 <>{projectSelector} to start</>
372 ) : (
373 <>Add a project to start</>
374 )}
375 </h1>
376 {/* Reserved whenever threads can skip a project, so the heading does not
377 move. Without a project, the picker moves here to choose one. */}
378 {scratchWorkspaceRoot === null ? null : (
379 <p className="mt-2 flex h-6 items-center text-sm">
380 {isScratchDraft ? projectSelector : orStartWithoutProject}
381 </p>
382 )}
383 </div>
384 );
385}