OpenSplitButton.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. import type { EditorInfo } from "@zcode/shared";
  2. import { ChevronDownIcon, CopyIcon, ExternalLinkIcon } from "lucide-react";
  3. import { useCallback, useMemo, useState } from "react";
  4. import { Button } from "@/components/ui/button.js";
  5. import { toast } from "@/components/ui/toast.js";
  6. import type { MessageFileLinkTarget } from "@/components/ai-elements/message.js";
  7. import {
  8. DropdownMenu,
  9. DropdownMenuContent,
  10. DropdownMenuItem,
  11. DropdownMenuSeparator,
  12. DropdownMenuTrigger,
  13. } from "@/components/ui/dropdown-menu.js";
  14. import { usePlatform } from "@/hooks/usePlatform.js";
  15. import { useFileContextActions } from "@/hooks/useFileContextActions.js";
  16. import { useWorkspaceOpenInEditorTarget } from "@/hooks/useWorkspaceOpenInEditorTarget.js";
  17. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  18. import { persistLastSelectedEditorId, readLastSelectedEditorId } from "@/lib/editorPreference.js";
  19. import type { CodeViewerSource } from "@/lib/codeViewer.js";
  20. import { getWorkspaceFileRelativePath } from "@/workspace-file-tree/model.js";
  21. import { resolveWorkspaceEditorSelection } from "@/lib/workspaceEditorSelection.js";
  22. import { logger } from "@/logger.js";
  23. // 导出类型供共用时间线以 import type 引用(构建期擦除,不把 open-with 子树带进公开页 bundle)。
  24. export type OpenSplitButtonTarget =
  25. | {
  26. type: "website";
  27. url: string;
  28. localPath?: string;
  29. }
  30. | {
  31. type: "file";
  32. path: string;
  33. title: string;
  34. label: string;
  35. previewSource?: CodeViewerSource;
  36. };
  37. interface OpenSplitButtonProps {
  38. target: OpenSplitButtonTarget;
  39. onOpenBrowserUrl?: (url: string) => void;
  40. onOpenFileLink?: (target: MessageFileLinkTarget) => void;
  41. onOpenCodeViewer?: (source: CodeViewerSource) => void;
  42. hideOpenWithMenu?: boolean;
  43. stopPropagation?: boolean;
  44. }
  45. export function OpenSplitButton({
  46. target,
  47. onOpenBrowserUrl,
  48. onOpenFileLink,
  49. onOpenCodeViewer,
  50. hideOpenWithMenu = false,
  51. stopPropagation = false,
  52. }: OpenSplitButtonProps) {
  53. const { intl } = useZCodeIntl();
  54. const platform = usePlatform();
  55. const fileActions = useFileContextActions();
  56. const previewSource = target.type === "file" ? target.previewSource : undefined;
  57. const matchedOpenContext = useWorkspaceOpenInEditorTarget({
  58. workspacePath: previewSource?.workspacePath,
  59. workspaceIdentity: previewSource?.workspaceIdentity,
  60. workspaceRemoteSessionId: previewSource?.workspaceRemoteSessionId,
  61. });
  62. const openInEditorRemoteTarget = matchedOpenContext.remoteTarget;
  63. const isRemoteSource = Boolean(
  64. previewSource?.workspaceIdentity ||
  65. previewSource?.workspaceRemoteSessionId ||
  66. matchedOpenContext.isRemoteWorkspace,
  67. );
  68. const [editors, setEditors] = useState<EditorInfo[]>([]);
  69. const [editorsLoaded, setEditorsLoaded] = useState(false);
  70. const [loadingEditors, setLoadingEditors] = useState(false);
  71. const sortedEditors = useMemo(
  72. () =>
  73. isRemoteSource && !openInEditorRemoteTarget
  74. ? []
  75. : resolveWorkspaceEditorSelection({
  76. installedEditors: editors,
  77. selectedEditorId: null,
  78. remoteTarget: openInEditorRemoteTarget,
  79. }).availableEditors,
  80. [editors, isRemoteSource, openInEditorRemoteTarget],
  81. );
  82. const canPreview =
  83. target.type === "website"
  84. ? Boolean(onOpenBrowserUrl)
  85. : Boolean(onOpenFileLink || onOpenCodeViewer);
  86. const selectedEditor = useMemo(() => {
  87. const selectedEditorId = readLastSelectedEditorId();
  88. return (
  89. sortedEditors.find((editor) => editor.id === selectedEditorId) ?? sortedEditors[0] ?? null
  90. );
  91. }, [sortedEditors]);
  92. const stopEventPropagation = (event: { stopPropagation: () => void }) => {
  93. if (stopPropagation) {
  94. event.stopPropagation();
  95. }
  96. };
  97. const loadEditors = useCallback(async () => {
  98. if (editorsLoaded || loadingEditors || target.type !== "file") {
  99. return;
  100. }
  101. setLoadingEditors(true);
  102. try {
  103. setEditors(await platform.getInstalledEditors());
  104. setEditorsLoaded(true);
  105. } catch (error) {
  106. logger.warn("[OpenSplitButton] 获取第三方打开方式失败", {
  107. path: target.path,
  108. error: error instanceof Error ? error.message : String(error),
  109. });
  110. } finally {
  111. setLoadingEditors(false);
  112. }
  113. }, [editorsLoaded, loadingEditors, platform, target]);
  114. const handlePreview = () => {
  115. if (target.type === "website") {
  116. onOpenBrowserUrl?.(target.url);
  117. return;
  118. }
  119. if (onOpenCodeViewer) {
  120. onOpenCodeViewer(
  121. target.previewSource ?? {
  122. type: "file",
  123. title: target.title,
  124. path: target.path,
  125. },
  126. );
  127. return;
  128. }
  129. onOpenFileLink?.({
  130. path: target.path,
  131. label: target.label,
  132. pathKind: "file",
  133. workspacePath: target.previewSource?.workspacePath,
  134. workspaceIdentity: target.previewSource?.workspaceIdentity,
  135. workspaceRemoteSessionId: target.previewSource?.workspaceRemoteSessionId,
  136. });
  137. };
  138. const handleOpenInEditor = (editor: EditorInfo) => {
  139. if (target.type !== "file") {
  140. return;
  141. }
  142. persistLastSelectedEditorId(editor.id);
  143. void platform
  144. .openInEditor(editor.id, target.path, {
  145. pathKind: "file",
  146. remoteTarget: openInEditorRemoteTarget,
  147. workspaceIdentity: target.previewSource?.workspaceIdentity,
  148. })
  149. .then((result) => {
  150. if (result.success) {
  151. return;
  152. }
  153. logger.warn("[OpenSplitButton] 第三方 App 打开文件失败", {
  154. editorId: editor.id,
  155. path: target.path,
  156. error: result.error ?? "unknown-error",
  157. });
  158. });
  159. };
  160. const handleOpenExternal = () => {
  161. if (target.type !== "website" || !target.localPath || !platform.openExternalFile) {
  162. platform.openExternal(target.type === "website" ? target.url : target.path);
  163. return;
  164. }
  165. const localPath = target.localPath;
  166. const reportFailure = (error: unknown) => {
  167. logger.warn("[OpenSplitButton] 浏览器打开本地文件失败", {
  168. path: localPath,
  169. error: error instanceof Error ? error.message : String(error),
  170. });
  171. toast(intl.formatMessage({ id: "chat.previewCards.openExternalFailed" }));
  172. };
  173. void platform
  174. .openExternalFile(localPath)
  175. .then((result) => {
  176. if (!result.success) reportFailure(result.error ?? "unknown-error");
  177. })
  178. .catch(reportFailure);
  179. };
  180. if (hideOpenWithMenu) {
  181. return (
  182. <div
  183. className="flex h-7 shrink-0 items-center overflow-hidden rounded-lg border border-border bg-input transition-all hover:border-border-hover"
  184. onClick={stopEventPropagation}
  185. onPointerDown={stopEventPropagation}
  186. >
  187. <Button
  188. type="button"
  189. variant="ghost"
  190. size="default"
  191. className="h-7 rounded-none border-0 gap-1 px-2"
  192. disabled={!canPreview}
  193. onClick={(event) => {
  194. stopEventPropagation(event);
  195. handlePreview();
  196. }}
  197. >
  198. {intl.formatMessage({ id: "common.open" })}
  199. </Button>
  200. </div>
  201. );
  202. }
  203. return (
  204. <DropdownMenu onOpenChange={(open) => open && void loadEditors()}>
  205. <div
  206. className="flex h-7 shrink-0 items-center overflow-hidden rounded-lg border border-border bg-input transition-all hover:border-border-hover"
  207. onClick={stopEventPropagation}
  208. onPointerDown={stopEventPropagation}
  209. >
  210. <Button
  211. type="button"
  212. variant="ghost"
  213. size="default"
  214. className="h-7 rounded-none border-0 gap-1 pr-1.5"
  215. disabled={!canPreview}
  216. onClick={(event) => {
  217. stopEventPropagation(event);
  218. handlePreview();
  219. }}
  220. >
  221. {intl.formatMessage({ id: "common.open" })}
  222. </Button>
  223. <DropdownMenuTrigger asChild>
  224. <Button
  225. type="button"
  226. variant="ghost"
  227. size="icon-md"
  228. className="!w-5 rounded-none border-0 text-foreground-subtlest"
  229. aria-label={intl.formatMessage({ id: "appHeader.selectOpenApp" })}
  230. title={intl.formatMessage({ id: "appHeader.selectOpenApp" })}
  231. onClick={stopEventPropagation}
  232. >
  233. <ChevronDownIcon className="size-3.5" />
  234. </Button>
  235. </DropdownMenuTrigger>
  236. </div>
  237. <DropdownMenuContent align="end" side="top" className="w-44" onClick={stopEventPropagation}>
  238. {target.type === "website" ? (
  239. <DropdownMenuItem onSelect={handleOpenExternal}>
  240. <ExternalLinkIcon className="size-4" />
  241. <span>
  242. {intl.formatMessage({
  243. id: "chat.previewCards.openExternal",
  244. })}
  245. </span>
  246. </DropdownMenuItem>
  247. ) : (
  248. <>
  249. {selectedEditor ? (
  250. sortedEditors.map((editor) => (
  251. <DropdownMenuItem key={editor.id} onSelect={() => handleOpenInEditor(editor)}>
  252. <img src={editor.iconDataUrl} alt={editor.name} className="size-4 shrink-0" />
  253. <span>{editor.name}</span>
  254. </DropdownMenuItem>
  255. ))
  256. ) : (
  257. <DropdownMenuItem disabled>
  258. {intl.formatMessage({
  259. id: loadingEditors ? "common.loading" : "chat.previewCards.noOpenApps",
  260. })}
  261. </DropdownMenuItem>
  262. )}
  263. <DropdownMenuSeparator />
  264. <DropdownMenuItem
  265. onSelect={() => void fileActions.copyAbsolutePath({ path: target.path })}
  266. >
  267. <CopyIcon className="size-4" />
  268. {intl.formatMessage({ id: "fileActions.copyAbsolutePath" })}
  269. </DropdownMenuItem>
  270. <DropdownMenuItem
  271. onSelect={() =>
  272. void fileActions.copyRelativePath({
  273. path: target.path,
  274. relativePath: target.previewSource?.workspacePath
  275. ? getWorkspaceFileRelativePath(target.previewSource.workspacePath, target.path)
  276. : target.label,
  277. })
  278. }
  279. >
  280. <CopyIcon className="size-4" />
  281. {intl.formatMessage({ id: "fileActions.copyRelativePath" })}
  282. </DropdownMenuItem>
  283. </>
  284. )}
  285. </DropdownMenuContent>
  286. </DropdownMenu>
  287. );
  288. }