OpenSplitButton.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. import type { EditorInfo } from "@zcode/shared";
  2. import {
  3. ChevronDownIcon,
  4. CopyIcon,
  5. ExternalLinkIcon,
  6. FolderOpenIcon,
  7. PanelRightIcon,
  8. } from "lucide-react";
  9. import {
  10. useCallback,
  11. useEffect,
  12. useMemo,
  13. useRef,
  14. useState,
  15. type ReactElement,
  16. type ReactNode,
  17. } from "react";
  18. import { Button } from "@/components/ui/button.js";
  19. import { toast } from "@/components/ui/toast.js";
  20. import type { MessageFileLinkTarget } from "@/components/ai-elements/message.js";
  21. import {
  22. DropdownMenu,
  23. DropdownMenuContent,
  24. DropdownMenuItem,
  25. DropdownMenuSeparator,
  26. DropdownMenuTrigger,
  27. } from "@/components/ui/dropdown-menu.js";
  28. import {
  29. ContextMenu,
  30. ContextMenuTrigger,
  31. ContextMenuContent,
  32. ContextMenuItem,
  33. ContextMenuSeparator,
  34. } from "@/components/ui/context-menu.js";
  35. import {
  36. DefaultFileApplicationLabel,
  37. FileApplicationChoices,
  38. FileSaveAsMenuItem,
  39. useFileApplications,
  40. } from "@/file-menu/index.js";
  41. import { usePlatform } from "@/hooks/usePlatform.js";
  42. import { useFileContextActions } from "@/hooks/useFileContextActions.js";
  43. import { useWorkspaceOpenInEditorTarget } from "@/hooks/useWorkspaceOpenInEditorTarget.js";
  44. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  45. import { persistLastSelectedEditorId } from "@/lib/editorPreference.js";
  46. import type { CodeViewerSource } from "@/lib/codeViewer.js";
  47. import { getFileManagerLabel } from "@/workspace-file-tree/helpers.js";
  48. import { getWorkspaceFileRelativePath } from "@/workspace-file-tree/model.js";
  49. import { resolveWorkspaceEditorSelection } from "@/lib/workspaceEditorSelection.js";
  50. import { logger } from "@/logger.js";
  51. // 导出类型供共用时间线以 import type 引用(构建期擦除,不把 open-with 子树带进公开页 bundle)。
  52. export type OpenSplitButtonTarget =
  53. | {
  54. type: "website";
  55. url: string;
  56. localPath?: string;
  57. /** 卡片背后的本机文件(localhost 预览也可能有),只用于在文件管理器中定位,不参与打开。 */
  58. sourcePath?: string;
  59. workspacePath?: string;
  60. }
  61. | {
  62. type: "file";
  63. path: string;
  64. title: string;
  65. label: string;
  66. previewSource?: CodeViewerSource;
  67. };
  68. interface OpenSplitButtonProps {
  69. target: OpenSplitButtonTarget;
  70. onOpenBrowserUrl?: (url: string) => void;
  71. onOpenFileLink?: (target: MessageFileLinkTarget) => void;
  72. onOpenCodeViewer?: (source: CodeViewerSource) => void;
  73. hideOpenWithMenu?: boolean;
  74. openDefaultOnPrimary?: boolean;
  75. /** 预览专属的显示选项,追加在统一文件动作之后,不复制文件操作。 */
  76. viewMenuItems?: ReactNode;
  77. stopPropagation?: boolean;
  78. /** 整张卡片复用按钮的操作与状态,右键和下拉不会维护两套动作。 */
  79. renderCard?: (
  80. button: ReactNode,
  81. /** 卡片主体整卡点击复用主按钮的预览动作与可用状态。 */
  82. actions: { handlePreview: () => void; canPreview: boolean },
  83. ) => ReactElement;
  84. }
  85. export function OpenSplitButton({
  86. target,
  87. onOpenBrowserUrl,
  88. onOpenFileLink,
  89. onOpenCodeViewer,
  90. hideOpenWithMenu = false,
  91. openDefaultOnPrimary = false,
  92. viewMenuItems,
  93. stopPropagation = false,
  94. renderCard,
  95. }: OpenSplitButtonProps) {
  96. const { intl } = useZCodeIntl();
  97. const platform = usePlatform();
  98. const previewSource = target.type === "file" ? target.previewSource : undefined;
  99. const matchedOpenContext = useWorkspaceOpenInEditorTarget({
  100. workspacePath: previewSource?.workspacePath,
  101. workspaceIdentity: previewSource?.workspaceIdentity,
  102. workspaceRemoteSessionId: previewSource?.workspaceRemoteSessionId,
  103. });
  104. const openInEditorRemoteTarget = matchedOpenContext.remoteTarget;
  105. const isRemoteSource = Boolean(
  106. previewSource?.workspaceIdentity ||
  107. previewSource?.workspaceRemoteSessionId ||
  108. matchedOpenContext.isRemoteWorkspace,
  109. );
  110. const fileActions = useFileContextActions({
  111. canOpenLocalFileManager: Boolean(platform.canOpenLocalFiles),
  112. isRemoteWorkspace: isRemoteSource,
  113. remoteTarget: openInEditorRemoteTarget,
  114. workspaceIdentity: previewSource?.workspaceIdentity,
  115. });
  116. const filePath = target.type === "file" ? target.path : target.localPath;
  117. const workspacePath =
  118. target.type === "file" ? previewSource?.workspacePath : target.workspacePath;
  119. const canOpenNative = Boolean(platform.canOpenLocalFiles && !isRemoteSource);
  120. // 只有落在本机(或 WSL)的文件产物能定位到所在目录:文件卡用自身路径,file:// HTML 用 localPath,
  121. // localhost 预览只有映射到本轮写出的本机 HTML 时才带 sourcePath;纯网址没有文件可找。
  122. const revealPath = target.type === "file" ? target.path : (target.localPath ?? target.sourcePath);
  123. const canReveal = Boolean(
  124. revealPath && fileActions.canRevealInFileManager({ path: revealPath }),
  125. );
  126. const fileManagerLabel = getFileManagerLabel(intl);
  127. const handleReveal = () => {
  128. // macOS / Windows 定位并选中文件;无系统定位能力时 hook 内部回退为打开所在目录。
  129. if (revealPath) void fileActions.revealFileInFileManager({ path: revealPath, kind: "file" });
  130. };
  131. const fileApplications = useFileApplications(
  132. target.type === "file"
  133. ? { path: target.path, pathKind: "file", workspaceIdentity: previewSource?.workspaceIdentity }
  134. : null,
  135. isRemoteSource,
  136. );
  137. const defaultApplication = fileApplications.defaultApplication;
  138. const defaultApplicationTitle = intl.formatMessage(
  139. {
  140. id: defaultApplication ? "fileActions.openInApplication" : "chat.previewCards.openDefaultApp",
  141. },
  142. defaultApplication ? { application: defaultApplication.name } : undefined,
  143. );
  144. useEffect(() => {
  145. if (openDefaultOnPrimary && canOpenNative) void fileApplications.load();
  146. }, [openDefaultOnPrimary, canOpenNative, fileApplications.load]);
  147. const editorRequest = useRef(0);
  148. const primaryEditorLoadStarted = useRef(false);
  149. const [editors, setEditors] = useState<EditorInfo[]>([]);
  150. const [editorsLoaded, setEditorsLoaded] = useState(false);
  151. const [loadingEditors, setLoadingEditors] = useState(false);
  152. const sortedEditors: Array<EditorInfo & { isDefault?: boolean }> = useMemo(
  153. () =>
  154. !isRemoteSource
  155. ? fileApplications.apps.map((app) => ({ ...app, iconDataUrl: app.iconDataUrl ?? "" }))
  156. : isRemoteSource && !openInEditorRemoteTarget
  157. ? []
  158. : resolveWorkspaceEditorSelection({
  159. installedEditors: editors,
  160. selectedEditorId: null,
  161. remoteTarget: openInEditorRemoteTarget,
  162. }).availableEditors,
  163. [editors, isRemoteSource, openInEditorRemoteTarget, fileApplications.apps],
  164. );
  165. const canPreview = openDefaultOnPrimary
  166. ? Boolean(canOpenNative || sortedEditors.length)
  167. : target.type === "website"
  168. ? Boolean(onOpenBrowserUrl)
  169. : Boolean(onOpenFileLink || onOpenCodeViewer);
  170. useEffect(() => {
  171. primaryEditorLoadStarted.current = false;
  172. setEditors([]);
  173. setEditorsLoaded(false);
  174. setLoadingEditors(false);
  175. // 卡片虚拟行重用时旧目标的异步应用结果不能覆盖新目标。
  176. editorRequest.current += 1;
  177. return () => {
  178. editorRequest.current += 1;
  179. };
  180. }, [
  181. filePath,
  182. workspacePath,
  183. previewSource?.workspaceIdentity,
  184. previewSource?.workspaceRemoteSessionId,
  185. ]);
  186. const stopEventPropagation = (event: { stopPropagation: () => void }) => {
  187. if (stopPropagation) {
  188. event.stopPropagation();
  189. }
  190. };
  191. const loadEditors = useCallback(async () => {
  192. if (target.type !== "file") return;
  193. if (!isRemoteSource) {
  194. await fileApplications.load();
  195. return;
  196. }
  197. if (editorsLoaded || loadingEditors) {
  198. return;
  199. }
  200. const request = ++editorRequest.current;
  201. setLoadingEditors(true);
  202. try {
  203. const result = await platform.getInstalledEditors(target.path);
  204. if (request !== editorRequest.current) return;
  205. setEditors(result);
  206. setEditorsLoaded(true);
  207. } catch (error) {
  208. if (request !== editorRequest.current) return;
  209. logger.warn("[OpenSplitButton] 获取第三方打开方式失败", {
  210. path: target.path,
  211. error: error instanceof Error ? error.message : String(error),
  212. });
  213. } finally {
  214. if (request === editorRequest.current) setLoadingEditors(false);
  215. }
  216. }, [editorsLoaded, loadingEditors, platform, target, isRemoteSource, fileApplications.load]);
  217. useEffect(() => {
  218. // 远端主按钮也需要提前获取可用编辑器;不能等用户先打开下拉才解除禁用。
  219. // 每个来源只自动请求一次,失败后仍可由用户打开菜单重试,避免渲染循环重试。
  220. if (
  221. openDefaultOnPrimary &&
  222. isRemoteSource &&
  223. openInEditorRemoteTarget &&
  224. !primaryEditorLoadStarted.current &&
  225. !editorsLoaded &&
  226. !loadingEditors
  227. ) {
  228. primaryEditorLoadStarted.current = true;
  229. void loadEditors();
  230. }
  231. }, [
  232. openDefaultOnPrimary,
  233. isRemoteSource,
  234. openInEditorRemoteTarget,
  235. loadEditors,
  236. editorsLoaded,
  237. loadingEditors,
  238. ]);
  239. const handlePreview = () => {
  240. if (openDefaultOnPrimary) {
  241. if (canOpenNative) handleOpenDefault();
  242. else if (sortedEditors[0]) handleOpenInEditor(sortedEditors[0]);
  243. return;
  244. }
  245. if (target.type === "website") {
  246. onOpenBrowserUrl?.(target.url);
  247. return;
  248. }
  249. if (onOpenCodeViewer) {
  250. onOpenCodeViewer(
  251. target.previewSource ?? {
  252. type: "file",
  253. title: target.title,
  254. path: target.path,
  255. },
  256. );
  257. return;
  258. }
  259. onOpenFileLink?.({
  260. path: target.path,
  261. label: target.label,
  262. pathKind: "file",
  263. workspacePath: target.previewSource?.workspacePath,
  264. workspaceIdentity: target.previewSource?.workspaceIdentity,
  265. workspaceRemoteSessionId: target.previewSource?.workspaceRemoteSessionId,
  266. });
  267. };
  268. const handleOpenInEditor = (editor: EditorInfo) => {
  269. if (target.type !== "file") {
  270. return;
  271. }
  272. if (!isRemoteSource) {
  273. void fileApplications.open({ ...editor, isDefault: false });
  274. return;
  275. }
  276. persistLastSelectedEditorId(editor.id);
  277. // 返回失败和 IPC 拒绝都必须有可见反馈,不能只写日志后静默结束。
  278. void platform
  279. .openInEditor(editor.id, target.path, {
  280. pathKind: "file",
  281. remoteTarget: openInEditorRemoteTarget,
  282. workspaceIdentity: target.previewSource?.workspaceIdentity,
  283. })
  284. .then((result) => {
  285. if (!result.success) throw new Error(result.error ?? "unknown-error");
  286. })
  287. .catch((error: unknown) => {
  288. logger.warn("[OpenSplitButton] 第三方 App 打开文件失败", {
  289. editorId: editor.id,
  290. path: target.path,
  291. error: error instanceof Error ? error.message : String(error),
  292. });
  293. toast(intl.formatMessage({ id: "chat.previewCards.openFileFailed" }));
  294. });
  295. };
  296. const handleOpenExternal = () => {
  297. if (target.type !== "website" || !target.localPath || !platform.openExternalFile) {
  298. platform.openExternal(target.type === "website" ? target.url : target.path);
  299. return;
  300. }
  301. const localPath = target.localPath;
  302. const reportFailure = (error: unknown) => {
  303. logger.warn("[OpenSplitButton] 浏览器打开本地文件失败", {
  304. path: localPath,
  305. error: error instanceof Error ? error.message : String(error),
  306. });
  307. toast(intl.formatMessage({ id: "chat.previewCards.openExternalFailed" }));
  308. };
  309. void platform
  310. .openExternalFile(localPath)
  311. .then((result) => {
  312. if (!result.success) reportFailure(result.error ?? "unknown-error");
  313. })
  314. .catch(reportFailure);
  315. };
  316. const handleOpenDefault = () => {
  317. void fileApplications.openDefault();
  318. };
  319. // 卡片右键和 Open 下拉共用应用查询与保存动作。
  320. const renderContextActions = () => {
  321. const Item = ContextMenuItem;
  322. const Separator = ContextMenuSeparator;
  323. return (
  324. <>
  325. <Item disabled={!canPreview} onSelect={handlePreview}>
  326. <PanelRightIcon className="size-4" />
  327. {intl.formatMessage({
  328. id: "chat.previewCards.previewInSidePane",
  329. })}
  330. </Item>
  331. {target.type === "website" ? (
  332. <Item onSelect={handleOpenExternal}>
  333. <ExternalLinkIcon className="size-4" />
  334. {intl.formatMessage({ id: "common.open" })}
  335. </Item>
  336. ) : (
  337. <>
  338. {platform.canOpenLocalFiles && (!isRemoteSource || openInEditorRemoteTarget) && (
  339. <FileApplicationChoices
  340. variant="context"
  341. applications={sortedEditors}
  342. loading={loadingEditors || fileApplications.loading}
  343. onOpenDefault={
  344. canOpenNative && platform.openExternalFile ? handleOpenDefault : undefined
  345. }
  346. onSelect={handleOpenInEditor}
  347. />
  348. )}
  349. </>
  350. )}
  351. {target.type === "file" && (
  352. <FileSaveAsMenuItem
  353. variant="context"
  354. path={target.path}
  355. workspacePath={workspacePath}
  356. workspaceIdentity={previewSource?.workspaceIdentity}
  357. workspaceRemoteSessionId={previewSource?.workspaceRemoteSessionId}
  358. />
  359. )}
  360. <Separator />
  361. {canReveal && (
  362. <Item onSelect={handleReveal}>
  363. <FolderOpenIcon className="size-4" />
  364. {fileManagerLabel}
  365. </Item>
  366. )}
  367. {target.type === "website" && (
  368. <Item onSelect={() => void fileActions.copyAbsolutePath({ path: target.url })}>
  369. <CopyIcon className="size-4" />
  370. {intl.formatMessage({ id: "chat.previewCards.copyLink" })}
  371. </Item>
  372. )}
  373. {filePath && (
  374. <>
  375. {workspacePath && (
  376. <Item
  377. onSelect={() =>
  378. void fileActions.copyRelativePath({
  379. path: filePath,
  380. relativePath: getWorkspaceFileRelativePath(workspacePath, filePath),
  381. })
  382. }
  383. >
  384. <CopyIcon className="size-4" />
  385. {intl.formatMessage({ id: "fileActions.copyRelativePath" })}
  386. </Item>
  387. )}
  388. <Item onSelect={() => void fileActions.copyAbsolutePath({ path: filePath })}>
  389. <CopyIcon className="size-4" />
  390. {intl.formatMessage({ id: "fileActions.copyAbsolutePath" })}
  391. </Item>
  392. </>
  393. )}
  394. </>
  395. );
  396. };
  397. const button = (
  398. <DropdownMenu onOpenChange={(open) => open && void loadEditors()}>
  399. <div
  400. className="flex h-7 shrink-0 items-center overflow-hidden rounded-lg border border-border bg-input transition-all hover:border-border-hover"
  401. onClick={stopEventPropagation}
  402. onPointerDown={stopEventPropagation}
  403. >
  404. <Button
  405. type="button"
  406. variant="ghost"
  407. size="default"
  408. className={`h-7 rounded-none border-0 gap-1 ${hideOpenWithMenu ? "px-2" : "pr-1.5"}`}
  409. disabled={!canPreview}
  410. title={openDefaultOnPrimary ? defaultApplicationTitle : undefined}
  411. aria-label={openDefaultOnPrimary ? defaultApplicationTitle : undefined}
  412. onClick={(event) => {
  413. stopEventPropagation(event);
  414. handlePreview();
  415. }}
  416. >
  417. {openDefaultOnPrimary ? (
  418. <DefaultFileApplicationLabel application={defaultApplication}>
  419. {intl.formatMessage({ id: "common.open" })}
  420. </DefaultFileApplicationLabel>
  421. ) : (
  422. intl.formatMessage({ id: "common.open" })
  423. )}
  424. </Button>
  425. {!hideOpenWithMenu && (
  426. <DropdownMenuTrigger asChild>
  427. <Button
  428. type="button"
  429. variant="ghost"
  430. size="icon-md"
  431. className="!w-5 rounded-none border-0 text-foreground-subtlest"
  432. aria-label={intl.formatMessage({ id: "appHeader.selectOpenApp" })}
  433. title={intl.formatMessage({ id: "appHeader.selectOpenApp" })}
  434. onClick={stopEventPropagation}
  435. >
  436. <ChevronDownIcon className="size-3.5" />
  437. </Button>
  438. </DropdownMenuTrigger>
  439. )}
  440. </div>
  441. {!hideOpenWithMenu && (
  442. <DropdownMenuContent
  443. align="end"
  444. side="top"
  445. className="w-64 max-w-[calc(100vw-1rem)]"
  446. onClick={stopEventPropagation}
  447. >
  448. <OpenSplitButtonDropdownActions
  449. target={target}
  450. sortedEditors={sortedEditors}
  451. loadingEditors={loadingEditors || fileApplications.loading}
  452. canOpenWith={Boolean(
  453. platform.canOpenLocalFiles && (!isRemoteSource || openInEditorRemoteTarget),
  454. )}
  455. handleOpenExternal={handleOpenExternal}
  456. handleOpenInEditor={handleOpenInEditor}
  457. handleOpenDefault={
  458. canOpenNative && platform.openExternalFile ? handleOpenDefault : undefined
  459. }
  460. reveal={canReveal ? { label: fileManagerLabel, onSelect: handleReveal } : undefined}
  461. />
  462. {viewMenuItems ? (
  463. <>
  464. <DropdownMenuSeparator />
  465. {viewMenuItems}
  466. </>
  467. ) : null}
  468. </DropdownMenuContent>
  469. )}
  470. </DropdownMenu>
  471. );
  472. if (!renderCard) return button;
  473. return (
  474. <ContextMenu
  475. onOpenChange={(open) =>
  476. open &&
  477. platform.canOpenLocalFiles &&
  478. (!isRemoteSource || openInEditorRemoteTarget) &&
  479. void loadEditors()
  480. }
  481. >
  482. <ContextMenuTrigger asChild>
  483. {renderCard(button, { handlePreview, canPreview })}
  484. </ContextMenuTrigger>
  485. <ContextMenuContent className="w-64 max-w-[calc(100vw-1rem)]">
  486. {renderContextActions()}
  487. </ContextMenuContent>
  488. </ContextMenu>
  489. );
  490. }
  491. // 下拉保持紧凑的平铺应用列表,保存副本与路径动作都可以直接发现。
  492. function OpenSplitButtonDropdownActions({
  493. target,
  494. sortedEditors,
  495. loadingEditors,
  496. handleOpenExternal,
  497. handleOpenInEditor,
  498. handleOpenDefault,
  499. canOpenWith,
  500. reveal,
  501. }: {
  502. target:
  503. | { type: "website" }
  504. | {
  505. type: "file";
  506. path: string;
  507. label: string;
  508. previewSource?: {
  509. workspacePath?: string;
  510. workspaceIdentity?: string;
  511. workspaceRemoteSessionId?: string;
  512. };
  513. };
  514. sortedEditors: readonly (EditorInfo & { isDefault?: boolean })[];
  515. loadingEditors: boolean;
  516. handleOpenExternal: () => void;
  517. handleOpenInEditor: (editor: EditorInfo) => void;
  518. handleOpenDefault?: () => void;
  519. canOpenWith: boolean;
  520. reveal?: { label: string; onSelect: () => void };
  521. }) {
  522. const { intl } = useZCodeIntl();
  523. const fileActions = useFileContextActions();
  524. const revealItem = reveal ? (
  525. <DropdownMenuItem onSelect={reveal.onSelect}>
  526. <FolderOpenIcon className="size-4" />
  527. {reveal.label}
  528. </DropdownMenuItem>
  529. ) : null;
  530. return (
  531. <>
  532. {target.type === "website" ? (
  533. <>
  534. <DropdownMenuItem onSelect={handleOpenExternal}>
  535. <ExternalLinkIcon className="size-4" />
  536. <span>
  537. {intl.formatMessage({
  538. id: "chat.previewCards.openExternal",
  539. })}
  540. </span>
  541. </DropdownMenuItem>
  542. {revealItem}
  543. </>
  544. ) : (
  545. <>
  546. {(handleOpenDefault || canOpenWith) && (
  547. <FileApplicationChoices
  548. applications={sortedEditors}
  549. loading={loadingEditors}
  550. onOpenDefault={handleOpenDefault}
  551. onSelect={handleOpenInEditor}
  552. />
  553. )}
  554. {(handleOpenDefault || canOpenWith) && <DropdownMenuSeparator />}
  555. {revealItem}
  556. <FileSaveAsMenuItem path={target.path} {...target.previewSource} />
  557. <DropdownMenuItem
  558. onSelect={() => void fileActions.copyAbsolutePath({ path: target.path })}
  559. >
  560. <CopyIcon className="size-4" />
  561. {intl.formatMessage({ id: "fileActions.copyAbsolutePath" })}
  562. </DropdownMenuItem>
  563. <DropdownMenuItem
  564. onSelect={() =>
  565. void fileActions.copyRelativePath({
  566. path: target.path,
  567. relativePath: target.previewSource?.workspacePath
  568. ? getWorkspaceFileRelativePath(target.previewSource.workspacePath, target.path)
  569. : target.label,
  570. })
  571. }
  572. >
  573. <CopyIcon className="size-4" />
  574. {intl.formatMessage({ id: "fileActions.copyRelativePath" })}
  575. </DropdownMenuItem>
  576. </>
  577. )}
  578. </>
  579. );
  580. }