DirectoryBrowser.tsx 10 KB

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