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

ProjectFaviconPickerDialog.tsx

175 lines6.6 KB

1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { m as resolveMessage } from "~/i18n/messages";
3import { useAtomValue } from "@effect/atom-react";
4import type { EnvironmentId } from "@t3tools/contracts";
5import { isWindowsAbsolutePath } from "@t3tools/shared/path";
6import { msg, useGT, useMessages } from "gt-react";
7import { useState } from "react";
8​
9import type { MessageResolver } from "~/i18n/messages";
10import { primaryServerKeybindingsAtom } from "~/state/server";
11import { useTheme } from "~/hooks/useTheme";
12import { getLocalFileManagerName, isWindowsPlatform } from "~/lib/utils";
13import { CommandPaletteContent } from "../CommandPaletteContent";
14import type { CommandPaletteActionItem } from "../CommandPalette.logic";
15import { CommandPaletteResults } from "../CommandPaletteResults";
16import { PierreEntryIcon } from "../chat/PierreEntryIcon";
17import {
18 getProjectFilePickerMatches,
19 PROJECT_FILE_PICKER_RESULT_LIMIT,
20} from "../files/ProjectFilePicker.logic";
21import { useProjectFilePickerQuery } from "../files/projectFilesQueryState";
22import { CommandDialog, CommandDialogPopup, CommandFooterAction } from "../ui/command";
23import { toastManager } from "../ui/toast";
24import { ProjectFaviconThumbnail } from "./ProjectFaviconThumbnail";
25​
26function emptyMessage(
27 query: string,
28 error: string | null,
29 isPending: boolean,
30 resolve: MessageResolver,
31): string {
32 if (error) return error;
33 if (isPending)
34 return query.trim()
35 ? resolve(msg("Searching project files…"))
36 : resolve(msg("Indexing project files…"));
37 return query.trim()
38 ? resolve(msg("No matching image files."))
39 : resolve(msg("No image files found."));
41export function canPickExternalProjectFavicon(cwd: string, platform: string): boolean {
42 return !isWindowsPlatform(platform) || isWindowsAbsolutePath(cwd);
44​
45export function ProjectFaviconPickerDialog(props: {
46 readonly cwd: string;
47 readonly environmentId: EnvironmentId;
48 readonly onOpenChange: (open: boolean) => void;
49 readonly onPickExternal?: () => Promise<string | null>;
50 readonly onSelect: (path: string) => void;
51 readonly open: boolean;
52 readonly projectName: string;
53}) {
54 const gt = useGT();
55 const m = useMessages();
56 const [query, setQuery] = useState("");
57 const [highlightedItemValue, setHighlightedItemValue] = useState<string | null>(null);
58 const [isPickingExternal, setIsPickingExternal] = useState(false);
59 const result = useProjectFilePickerQuery(
60 props.environmentId,
61 props.cwd,
62 query,
63 PROJECT_FILE_PICKER_RESULT_LIMIT,
64 { imageOnly: true },
65 );
66 const { resolvedTheme } = useTheme();
67 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
68 const { onPickExternal: pickExternal, onSelect } = props;
69 const fileManagerName = getLocalFileManagerName(
70 typeof navigator === "undefined" ? "" : navigator.platform,
71 m,
72 );
73 const items: CommandPaletteActionItem[] = getProjectFilePickerMatches(
74 result.entries,
75 result.matchedQuery,
76 ).map((match) => ({
77 kind: "action",
78 value: `project-favicon:${match.path}`,
79 searchTerms: [match.name, match.path],
80 title: match.name,
81 description: match.path,
82 icon: (
83 <ProjectFaviconThumbnail
84 cwd={props.cwd}
85 environmentId={props.environmentId}
86 fallback={<PierreEntryIcon pathValue={match.path} kind="file" theme={resolvedTheme} />}
87 path={match.path}
88 />
89 ),
90 run: async () => onSelect(match.path),
91 }));
92​
93 // Kept rows never re-trigger the primitive's auto-highlight event, so default to the first row.
94 const activeItemValue = items.some((item) => item.value === highlightedItemValue)
95 ? highlightedItemValue
96 : (items[0]?.value ?? null);
97​
98 return (
99 <CommandDialog open={props.open} onOpenChange={props.onOpenChange}>
100 {props.open ? (
101 <CommandDialogPopup
102 aria-label={gt`Choose project icon`}
103 className="overflow-hidden"
104 onBackdropPointerDown={() => props.onOpenChange(false)}
105 >
106 <CommandPaletteContent
107 aria-label={gt`Choose project icon`}
108 autoHighlight="always"
109 escapeLabel={gt`Close`}
110 footerActionLabel={gt`Select icon`}
111 footerTrailing={
112 pickExternal ? (
113 <CommandFooterAction
114 disabled={isPickingExternal}
115 onClick={() => {
116 setIsPickingExternal(true);
117 void pickExternal()
118 .then((path) => {
119 if (!path) return;
120 props.onOpenChange(false);
121 onSelect(path);
122 })
123 .catch((error: unknown) => {
124 toastManager.add({
125 type: "error",
126 title: gt`Could not open image picker`,
127 description:
128 error instanceof Error
129 ? (thrownErrorMessage(error, resolveMessage) ?? error.message)
130 : gt`An error occurred.`,
131 });
132 })
133 .finally(() => setIsPickingExternal(false));
134 }}
135 >
136 {gt`Open in ${{ fileManager: fileManagerName }}`}
137 </CommandFooterAction>
138 ) : null
139 }
140 inputProps={{ placeholder: gt`Search image files…` }}
141 mode="none"
142 items={items.map((item) => item.value)}
143 onItemHighlighted={(value) => {
144 setHighlightedItemValue(typeof value === "string" ? value : null);
145 }}
146 onValueChange={(value) => {
147 setHighlightedItemValue(null);
148 setQuery(value);
149 }}
150 panelSize="tall-list"
151 testId="project-favicon-picker"
152 value={query}
153 >
154 <CommandPaletteResults
155 groups={
156 items.length > 0
157 ? [{ value: "project-favicon-files", label: props.projectName, items }]
158 : []
159 }
160 highlightedItemValue={activeItemValue}
161 isActionsOnly={false}
162 keybindings={keybindings}
163 onExecuteItem={(item) => {
164 if (item.kind !== "action" || result.isPending) return;
165 props.onOpenChange(false);
166 void item.run();
167 }}
168 emptyStateMessage={emptyMessage(query, result.error, result.isPending, m)}
169 />
170 </CommandPaletteContent>
171 </CommandDialogPopup>
172 ) : null}
173 </CommandDialog>
174 );