DirectoryBrowser.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. import { useEffect, useState, useRef } from "react";
  2. import type { IServiceAccessor } from "@zcode/services";
  3. import type { FileEntry } from "@zcode/shared";
  4. import { FolderIcon, FolderSymlinkIcon } from "lucide-react";
  5. import { Button } from "./components/ui/button.js";
  6. import { Input } from "./components/ui/input.js";
  7. import { useZCodeIntl } from "./i18n/IntlProvider.js";
  8. import { logger } from "./logger.js";
  9. export function createDirectoryBrowserReadParams(
  10. path: string,
  11. showHiddenDirectories: boolean,
  12. ): { path: string; includeHidden?: boolean } {
  13. return showHiddenDirectories ? { path, includeHidden: true } : { path };
  14. }
  15. export function filterDirectoryBrowserEntries(entries: FileEntry[]): FileEntry[] {
  16. return entries.filter((e) => e.type === "directory");
  17. }
  18. // 修复原因:远程目录条目已经携带 isSymbolicLink,这里只替换展示图标,不改变进入和选择目录的路径语义。
  19. export function getDirectoryBrowserEntryIconKind(
  20. entry: Pick<FileEntry, "isSymbolicLink" | "type">,
  21. ): "folder" | "folder-symlink" {
  22. return entry.type === "directory" && entry.isSymbolicLink === true
  23. ? "folder-symlink"
  24. : "folder";
  25. }
  26. export function createDirectoryBrowserRequestGuard(): {
  27. begin: () => number;
  28. isCurrent: (requestId: number) => boolean;
  29. } {
  30. let latestRequestId = 0;
  31. return {
  32. begin: () => {
  33. latestRequestId += 1;
  34. return latestRequestId;
  35. },
  36. isCurrent: (requestId: number) => requestId === latestRequestId,
  37. };
  38. }
  39. /**
  40. * 服务端目录浏览对话框。
  41. * 通过 fileService.readdir 浏览远程/本地服务器的目录结构,
  42. * 适用于 web 端无法调用系统原生文件选择器的场景。
  43. */
  44. export function DirectoryBrowser({
  45. services,
  46. onSelect,
  47. onCancel,
  48. onPathChange,
  49. embedded = false,
  50. }: {
  51. services: IServiceAccessor;
  52. onSelect: (path: string) => void;
  53. onCancel: () => void;
  54. onPathChange?: (path: string) => void;
  55. embedded?: boolean;
  56. }) {
  57. const [currentPath, setCurrentPath] = useState("");
  58. const [inputPath, setInputPath] = useState("");
  59. const [entries, setEntries] = useState<FileEntry[]>([]);
  60. const [loading, setLoading] = useState(true);
  61. const [error, setError] = useState("");
  62. const [showHiddenDirectories, setShowHiddenDirectories] = useState(false);
  63. const listRef = useRef<HTMLDivElement>(null);
  64. const showHiddenDirectoriesRef = useRef(false);
  65. const requestGuardRef = useRef(createDirectoryBrowserRequestGuard());
  66. const { intl } = useZCodeIntl();
  67. // 初始化:获取 homedir 作为起始路径
  68. useEffect(() => {
  69. services.systemService
  70. .info()
  71. .then((info) => {
  72. navigateTo(info.homedir);
  73. })
  74. .catch((err) => {
  75. logger.error("[DirectoryBrowser] 获取系统信息失败:", err);
  76. setError(intl.formatMessage({ id: "directoryBrowser.errorSystem" }));
  77. setLoading(false);
  78. });
  79. // eslint-disable-next-line react-hooks/exhaustive-deps
  80. }, []);
  81. const navigateTo = async (
  82. path: string,
  83. nextShowHiddenDirectories = showHiddenDirectoriesRef.current,
  84. ) => {
  85. const requestId = requestGuardRef.current.begin();
  86. setLoading(true);
  87. setError("");
  88. try {
  89. const result = await services.fileService.readdir(
  90. createDirectoryBrowserReadParams(path, nextShowHiddenDirectories),
  91. );
  92. if (!requestGuardRef.current.isCurrent(requestId)) {
  93. return;
  94. }
  95. const dirs = filterDirectoryBrowserEntries(result);
  96. setEntries(dirs);
  97. setCurrentPath(path);
  98. setInputPath(path);
  99. onPathChange?.(path);
  100. // 滚动到顶部
  101. listRef.current?.scrollTo(0, 0);
  102. } catch (err) {
  103. if (!requestGuardRef.current.isCurrent(requestId)) {
  104. return;
  105. }
  106. // 用户快速切换目录或隐藏目录时,较早 readdir 可能后返回;
  107. // 过期错误不能覆盖最新导航状态,否则 UI 会展示和当前按钮状态不一致的目录/错误。
  108. logger.error("[DirectoryBrowser] readdir 失败:", err);
  109. setError(
  110. intl.formatMessage(
  111. { id: "directoryBrowser.errorReadDir" },
  112. { error: String(err) },
  113. ),
  114. );
  115. } finally {
  116. if (requestGuardRef.current.isCurrent(requestId)) {
  117. setLoading(false);
  118. }
  119. }
  120. };
  121. const handleGoUp = () => {
  122. // 提取父目录路径
  123. const parent = currentPath.replace(/\/[^/]+\/?$/, "") || "/";
  124. navigateTo(parent);
  125. };
  126. const handleInputSubmit = (e: React.FormEvent) => {
  127. e.preventDefault();
  128. const trimmed = inputPath.trim();
  129. if (trimmed) navigateTo(trimmed);
  130. };
  131. const handleToggleHiddenDirectories = () => {
  132. const nextShowHiddenDirectories = !showHiddenDirectoriesRef.current;
  133. showHiddenDirectoriesRef.current = nextShowHiddenDirectories;
  134. setShowHiddenDirectories(nextShowHiddenDirectories);
  135. if (currentPath) {
  136. void navigateTo(currentPath, nextShowHiddenDirectories);
  137. }
  138. };
  139. const handleSelectCurrentPath = () => {
  140. const selectedPath = currentPath.trim();
  141. if (!selectedPath || loading) {
  142. return;
  143. }
  144. onSelect(selectedPath);
  145. };
  146. const handleKeyDown = (e: React.KeyboardEvent) => {
  147. if (e.key === "Escape") onCancel();
  148. };
  149. const browserContent = (
  150. <div className="flex min-h-0 flex-1 flex-col gap-3">
  151. <div>
  152. <div className="mb-1 block text-ui-base text-foreground-subtle">
  153. {intl.formatMessage({ id: "directoryBrowser.title" })}
  154. </div>
  155. {/* 路径输入 */}
  156. <form onSubmit={handleInputSubmit} className="flex flex-col gap-2 sm:flex-row">
  157. <Input
  158. type="text"
  159. size="lg"
  160. value={inputPath}
  161. onChange={(e) => setInputPath(e.target.value)}
  162. placeholder={intl.formatMessage({
  163. id: "directoryBrowser.pathPlaceholder",
  164. })}
  165. className="h-9 min-w-0 flex-1 text-ui-base"
  166. autoFocus
  167. />
  168. <div className="flex gap-2 sm:shrink-0">
  169. <Button
  170. type="submit"
  171. size="lg"
  172. className="h-9 min-w-0 flex-1 px-4 text-ui-base sm:flex-none"
  173. >
  174. {intl.formatMessage({ id: "directoryBrowser.go" })}
  175. </Button>
  176. <Button
  177. type="button"
  178. variant={showHiddenDirectories ? "secondary" : "outline"}
  179. size="lg"
  180. aria-pressed={showHiddenDirectories}
  181. className="h-9 min-w-0 flex-1 px-3 text-ui-base sm:flex-none"
  182. onClick={handleToggleHiddenDirectories}
  183. >
  184. {intl.formatMessage({
  185. id: showHiddenDirectories
  186. ? "directoryBrowser.hideHidden"
  187. : "directoryBrowser.showHidden",
  188. })}
  189. </Button>
  190. </div>
  191. </form>
  192. </div>
  193. {/* 错误提示 */}
  194. {error ? <div className="text-ui-base text-destructive">{error}</div> : null}
  195. {/* 目录列表 */}
  196. <div
  197. ref={listRef}
  198. className="flex-1 flex flex-col overflow-y-auto rounded-lg border border-border bg-background"
  199. >
  200. {/* 上级目录 */}
  201. {currentPath && currentPath !== "/" ? (
  202. <button
  203. onClick={handleGoUp}
  204. // 滚动容器是纵向 flex 布局,子项默认允许 shrink;
  205. // 当目录很多触发滚动时,首行“返回上级”会被压缩导致高度变化。
  206. className="flex h-10 w-full shrink-0 cursor-pointer items-center gap-2 border-b border-border px-3 text-left text-ui-base transition hover:bg-hover/50"
  207. >
  208. <FolderIcon className="size-4 shrink-0 text-foreground-subtle" />
  209. <span className="text-foreground">..</span>
  210. </button>
  211. ) : null}
  212. {loading ? (
  213. <div className="p-4 text-center text-ui-base text-foreground-subtle">
  214. {intl.formatMessage({ id: "common.loading" })}
  215. </div>
  216. ) : entries.length === 0 ? (
  217. <div className="p-4 text-center text-ui-base text-foreground-subtle">
  218. {intl.formatMessage({ id: "directoryBrowser.noSubdirs" })}
  219. </div>
  220. ) : (
  221. entries.map((entry) => {
  222. const EntryIcon =
  223. getDirectoryBrowserEntryIconKind(entry) === "folder-symlink"
  224. ? FolderSymlinkIcon
  225. : FolderIcon;
  226. return (
  227. <button
  228. key={entry.path}
  229. onClick={() => navigateTo(entry.path)}
  230. className="flex w-full shrink-0 cursor-pointer items-center gap-2 px-3 py-2 text-left text-ui-base transition hover:bg-hover/50"
  231. >
  232. <EntryIcon className="size-4 shrink-0 text-foreground-subtle" />
  233. <span className="truncate">{entry.name}</span>
  234. </button>
  235. );
  236. })
  237. )}
  238. </div>
  239. </div>
  240. );
  241. if (embedded) {
  242. return browserContent;
  243. }
  244. return (
  245. <div
  246. className="fixed inset-0 z-50 flex items-center justify-center bg-foreground/30 backdrop-blur-sm"
  247. onClick={(e) => e.target === e.currentTarget && onCancel()}
  248. onKeyDown={handleKeyDown}
  249. >
  250. <div className="flex h-[min(36rem,calc(100vh-4rem))] w-[min(44rem,calc(100vw-2rem))] flex-col rounded-xl border border-border bg-popover p-4 shadow-xl">
  251. {browserContent}
  252. {/* Bugfix: 非嵌入模式之前只能继续进入子目录,没有确认当前目录的路径。
  253. Web 目录浏览器作为独立选择器使用时因此永远拿不到 onSelect 结果。
  254. 这里把确认动作收口到弹窗 footer,选择当前浏览路径并交回上层。 */}
  255. <div className="mt-3 flex shrink-0 justify-end gap-2">
  256. <Button
  257. type="button"
  258. variant="secondary"
  259. size="lg"
  260. className="h-10 min-w-0 px-5 text-ui-base"
  261. onClick={onCancel}
  262. >
  263. {intl.formatMessage({ id: "common.cancel" })}
  264. </Button>
  265. <Button
  266. type="button"
  267. size="lg"
  268. className="h-10 min-w-0 px-5 text-ui-base"
  269. disabled={!currentPath.trim() || loading}
  270. onClick={handleSelectCurrentPath}
  271. >
  272. {intl.formatMessage({ id: "directoryBrowser.selectDir" })}
  273. </Button>
  274. </div>
  275. </div>
  276. </div>
  277. );
  278. }