🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(portal): fixed local-file preview toolbar (#18758)
Innei0ea389b026d2
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex db84a914d88..aab2ccf05af 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2186,6 +2186,7 @@"workingPanel.localFile.document.truncatedRows": "Showing the first {{count}} rows","workingPanel.localFile.document.unsupported": "This document type can't be previewed in-app yet","workingPanel.localFile.error": "Couldn't load this file",+ "workingPanel.localFile.preview.openExternal": "Open in browser","workingPanel.localFile.preview.raw": "Raw","workingPanel.localFile.preview.reload": "Reload preview","workingPanel.localFile.preview.render": "Preview",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 731eb41305a..c8f441651f8 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2186,6 +2186,7 @@"workingPanel.localFile.document.truncatedRows": "仅显示前 {{count}} 行","workingPanel.localFile.document.unsupported": "此文档类型暂不支持应用内预览","workingPanel.localFile.error": "无法加载此文件",+ "workingPanel.localFile.preview.openExternal": "在浏览器中打开","workingPanel.localFile.preview.raw": "原文","workingPanel.localFile.preview.reload": "刷新预览","workingPanel.localFile.preview.render": "预览",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 0f7b5243016..3070cd4a62c 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2451,6 +2451,7 @@ export default {'workingPanel.localFile.preview.raw': 'Raw','workingPanel.localFile.sandboxUnavailable':'This file is no longer available — its sandbox environment has been recycled',+ 'workingPanel.localFile.preview.openExternal': 'Open in browser','workingPanel.localFile.preview.reload': 'Reload preview','workingPanel.localFile.preview.render': 'Preview','workingPanel.localFile.preview.source': 'Source',diff --git a/src/components/HtmlPreview/index.ts b/src/components/HtmlPreview/index.tsindex ad3f1c2954b..d0dccf57471 100644--- a/src/components/HtmlPreview/index.ts+++ b/src/components/HtmlPreview/index.ts@@ -1,3 +1,4 @@+export { applyHtmlPreviewBaseUrl } from './applyBaseUrl';export { isHtmlFile } from './fileType';export { default as InlineHtmlPreview } from './InlinePreview';export { default as HtmlPreviewDrawer } from './PreviewDrawer';diff --git a/src/features/Portal/LocalFile/Body.test.tsx b/src/features/Portal/LocalFile/Body.test.tsxindex 33f127e83e9..b797e211a20 100644--- a/src/features/Portal/LocalFile/Body.test.tsx+++ b/src/features/Portal/LocalFile/Body.test.tsx@@ -21,6 +21,7 @@ vi.mock('antd-style', async (importOriginal) => ({row: 'row',value: 'value',}),+ cx: (...args: unknown[]) => args.filter(Boolean).join(' '),cssVar: {colorBgContainer: 'var(--color-bg-container)',colorBorderSecondary: 'var(--color-border-secondary)',@@ -29,6 +30,30 @@ vi.mock('antd-style', async (importOriginal) => ({},}));+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}));++vi.mock('@lobehub/ui', () => ({+ ActionIcon: () => null,+ Center: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ Empty: ({ description }: { description?: ReactNode }) => <div>{description}</div>,+ Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ Icon: () => null,+ Image: ({ alt, src }: { alt?: string; src?: string }) => <img alt={alt} src={src} />,+ Markdown: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,+ Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,+}));++vi.mock('@lobehub/ui/base-ui', () => ({+ Tabs: () => null,+ Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,+ ToggleGroup: () => null,+}));+vi.mock('@/components/CodeEditorPane', () => ({default: () => <textarea data-testid="code-editor" />,}));diff --git a/src/features/Portal/LocalFile/Body.tsx b/src/features/Portal/LocalFile/Body.tsxindex 951b6816bf7..88da559e706 100644--- a/src/features/Portal/LocalFile/Body.tsx+++ b/src/features/Portal/LocalFile/Body.tsx@@ -1,14 +1,14 @@import { isDesktop } from '@lobechat/const';import type { MarkdownProps } from '@lobehub/ui';-import { Center, Empty, Flexbox, Icon, Image, Markdown } from '@lobehub/ui';-import { ActionIcon, Tabs, Text } from '@lobehub/ui/base-ui';+import { Center, Empty, Flexbox, Image, Markdown } from '@lobehub/ui';+import { Text, ToggleGroup } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';-import { CodeIcon, EyeIcon, RefreshCwIcon } from 'lucide-react';+import { CodeIcon, ExternalLinkIcon, EyeIcon, RefreshCwIcon } from 'lucide-react';import { lazy, memo, Suspense, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import CodeEditorPane from '@/components/CodeEditorPane';-import { InlineHtmlPreview, isHtmlFile } from '@/components/HtmlPreview';+import { applyHtmlPreviewBaseUrl, InlineHtmlPreview, isHtmlFile } from '@/components/HtmlPreview';import Loading from '@/components/Loading/CircleLoading';import {PublishHtmlArtifactLiveBar,@@ -18,6 +18,7 @@ import {import { useClientDataSWR } from '@/libs/swr';import { localFileKeys } from '@/libs/swr/keys';import { cloudSandboxService } from '@/services/cloudSandbox';+import { localFileService } from '@/services/electron/localFileService';import { type LocalFilePreview, projectFileService } from '@/services/projectFile';import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';@@ -30,6 +31,7 @@ import {import { extensionToLanguage, getFileExtension } from './Body.helpers';import MarkdownImage from './MarkdownImage';+import PreviewToolbar, { ToolbarActionButton } from './PreviewToolbar';// Deferred: pulls in react-pdf, only needed once a binary document is opened.const DocumentPreview = lazy(() => import('./DocumentPreview'));@@ -130,31 +132,6 @@ type TextPreviewMode = 'render' | 'raw';const NO_TOPIC_KEY = '__no_topic__';-const floatingControlsStyles = createStaticStyles(({ css }) => ({- container: css`- position: absolute;- z-index: 2;- inset-block-start: 8px;- inset-inline-end: 12px;-- padding: 4px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadiusLG};-- opacity: 0.55;- background: ${cssVar.colorBgElevated};- backdrop-filter: blur(8px);- box-shadow: ${cssVar.boxShadowTertiary};-- transition: opacity 0.15s ease;-- &:hover,- &:focus-within {- opacity: 1;- }- `,-}));-interface TextPreviewPaneProps {activeTopicId?: string | null;content: string;@@ -282,6 +259,26 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(await onReload?.();setHtmlPreviewRevision((prev) => prev + 1);}, [onReload]);+ // Electron's window-open handler denies blob: URLs, so the blob path only+ // works on web; desktop hands local files to the system default app instead,+ // and remote/sandbox files have no external route there.+ const canOpenExternal = isDesktop ? !deviceId && !sandboxTopicId : true;+ const handleOpenExternal = useCallback(() => {+ if (isDesktop) {+ void localFileService.openLocalFile({ path: filePath });+ return;+ }++ // A top-level blob: document inherits this app's origin, so untrusted HTML+ // must stay inside a sandboxed (no allow-same-origin) iframe wrapper.+ const html = applyHtmlPreviewBaseUrl(editingValue, resourceBaseUrl);+ const srcdoc = html.replaceAll('&', '&').replaceAll('"', '"');+ const shell = `<!doctype html><title>${filePath.split(/[/\\]/).at(-1) ?? ''}</title><style>html,body{margin:0;height:100%}iframe{display:block;width:100%;height:100%;border:0}</style><iframe sandbox="allow-scripts allow-modals allow-popups" srcdoc="${srcdoc}"></iframe>`;+ const url = URL.createObjectURL(new Blob([shell], { type: 'text/html' }));+ window.open(url, '_blank', 'noopener,noreferrer');+ // Revoking immediately can abort the new window's document load — defer it.+ setTimeout(() => URL.revokeObjectURL(url), 60_000);+ }, [editingValue, filePath, resourceBaseUrl]);return (<PublishHtmlArtifactProvider@@ -294,52 +291,53 @@ const TextPreviewPane = memo<TextPreviewPaneProps>(><Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}><PublishHtmlArtifactLiveBar />- <Flexbox- flex={1}- height={'100%'}- style={{ minHeight: 0, overflow: 'hidden', position: 'relative' }}- >- {canRender && (- <Flexbox- horizontal- align={'center'}- className={floatingControlsStyles.container}- gap={4}- >+ <PreviewToolbar+ path={filePath}+ actions={+ <>{isHtml && (- <ActionIcon+ <ToolbarActionButtonicon={RefreshCwIcon}loading={reloading}- size={'small'}title={t('workingPanel.localFile.preview.reload')}onClick={handleReloadPreview}/>)}-- <Tabs- activeKey={mode}- size={'small'}- items={[- {- icon: <Icon icon={EyeIcon} />,- key: 'render',- label: t('workingPanel.localFile.preview.render'),- },- {- icon: <Icon icon={CodeIcon} />,- key: 'raw',- label: t(- isHtml- ? 'workingPanel.localFile.preview.source'- : 'workingPanel.localFile.preview.raw',- ),- },- ]}- onChange={(key) => setMode(key as TextPreviewMode)}- />+ {canRender && (+ <ToggleGroup+ value={mode}+ variant={'outlined'}+ options={[+ {+ icon: <EyeIcon size={14} />,+ label: t('workingPanel.localFile.preview.render'),+ value: 'render',+ },+ {+ icon: <CodeIcon size={14} />,+ label: t(+ isHtml+ ? 'workingPanel.localFile.preview.source'+ : 'workingPanel.localFile.preview.raw',+ ),+ value: 'raw',+ },+ ]}+ onChange={(value) => setMode(value as TextPreviewMode)}+ />+ )}+ {isHtml && canOpenExternal && (+ <ToolbarActionButton+ icon={ExternalLinkIcon}+ title={t('workingPanel.localFile.preview.openExternal')}+ onClick={handleOpenExternal}+ />+ )}<PublishHtmlArtifactTrigger />- </Flexbox>- )}+ </>+ }+ />+ <Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflow: 'hidden' }}><div style={{ flex: 1, minHeight: 0, overflow: showHtmlPreview ? 'hidden' : 'auto' }}>{isMarkdown && mode === 'render' ? (<>diff --git a/src/features/Portal/LocalFile/PreviewToolbar.tsx b/src/features/Portal/LocalFile/PreviewToolbar.tsxnew file mode 100644index 00000000000..a1620ee1546--- /dev/null+++ b/src/features/Portal/LocalFile/PreviewToolbar.tsx@@ -0,0 +1,174 @@+import { Flexbox, Icon, Tooltip } from '@lobehub/ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import type { LucideIcon } from 'lucide-react';+import type { MouseEventHandler, ReactNode } from 'react';+import { memo } from 'react';++const styles = createStaticStyles(({ css }) => ({+ action: css`+ cursor: pointer;++ display: flex;+ gap: 6px;+ align-items: center;++ height: 28px;+ padding-inline: 8px;+ border: none;+ border-radius: ${cssVar.borderRadius};++ font-size: 12px;+ line-height: 1;+ color: ${cssVar.colorTextSecondary};++ background: none;++ /* Icon renders an inline .anticon span whose svg sits on the text+ baseline, floating icons a few px above center — flex-normalize it. */+ .anticon {+ display: inline-flex;+ align-items: center;+ }++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ }++ &:disabled {+ cursor: not-allowed;+ opacity: 0.45;+ }+ `,+ actionActive: css`+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ `,+ actionLabel: css`+ white-space: nowrap;++ @container (max-width: 300px) {+ display: none;+ }+ `,+ actions: css`+ @container (max-width: 300px) {+ .toggle-group-item-label {+ display: none;+ }+ }+ `,+ bar: css`+ container-type: inline-size;+ flex-shrink: 0;++ height: 40px;+ padding-inline: 12px 8px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ background: ${cssVar.colorBgContainer};+ `,+ dir: css`+ overflow: hidden;++ /* Shrinks long before the filename does — the filename only starts+ ellipsizing once the directory is fully collapsed. */+ flex-shrink: 100;++ color: ${cssVar.colorTextTertiary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ name: css`+ overflow: hidden;+ color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ path: css`+ overflow: hidden;+ min-width: 0;+ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;++ /* Yield to the actions only when they actually rendered something —+ an all-hidden actions slot (e.g. plain code files) keeps the path. */+ @container (max-width: 440px) {+ &:has(~ [data-toolbar-actions] > *) {+ display: none;+ }+ }+ `,+}));++interface ToolbarActionButtonProps {+ active?: boolean;+ disabled?: boolean;+ icon: LucideIcon;+ label?: ReactNode;+ loading?: boolean;+ onClick?: MouseEventHandler<HTMLButtonElement>;+ title?: string;+}++export const ToolbarActionButton = memo<ToolbarActionButtonProps>(+ ({ active, disabled, icon, label, loading, onClick, title }) => {+ const button = (+ <button+ aria-label={title ?? (typeof label === 'string' ? label : undefined)}+ aria-pressed={active}+ className={cx(styles.action, active && styles.actionActive)}+ disabled={disabled || loading}+ type={'button'}+ onClick={onClick}+ >+ <Icon icon={icon} size={14} spin={loading} />+ {label && <span className={styles.actionLabel}>{label}</span>}+ </button>+ );++ return title ? <Tooltip title={title}>{button}</Tooltip> : button;+ },+);++ToolbarActionButton.displayName = 'ToolbarActionButton';++interface PreviewToolbarProps {+ actions?: ReactNode;+ path: string;+}++const PreviewToolbar = memo<PreviewToolbarProps>(({ actions, path }) => {+ const lastSlash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));+ const dir = lastSlash > 0 ? path.slice(0, lastSlash) : '';+ const sep = lastSlash > 0 ? path[lastSlash] : '';+ const name = path.slice(lastSlash + 1);++ return (+ <Flexbox horizontal align={'center'} className={styles.bar} gap={8} justify={'space-between'}>+ <Tooltip title={path}>+ <Flexbox horizontal align={'center'} className={styles.path} flex={1}>+ {dir && <span className={styles.dir}>{dir}</span>}+ <span className={styles.name}>{dir ? `${sep}${name}` : name}</span>+ </Flexbox>+ </Tooltip>+ {actions && (+ <Flexbox+ data-toolbar-actions+ horizontal+ align={'center'}+ className={styles.actions}+ flex={'none'}+ gap={2}+ style={{ marginInlineStart: 'auto' }}+ >+ {actions}+ </Flexbox>+ )}+ </Flexbox>+ );+});++PreviewToolbar.displayName = 'PreviewToolbar';++export default PreviewToolbar;diff --git a/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx b/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsxindex 36c1cedf2aa..a80f05e620d 100644--- a/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx+++ b/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx@@ -1,5 +1,12 @@-import { Accordion, AccordionItem, Flexbox } from '@lobehub/ui';-import { Button, createModal, ScrollArea, Text, useModalContext } from '@lobehub/ui/base-ui';+import { Flexbox } from '@lobehub/ui';+import {+ Accordion,+ Button,+ createModal,+ ScrollArea,+ Text,+ useModalContext,+} from '@lobehub/ui/base-ui';import { t } from 'i18next';import { useTranslation } from 'react-i18next';@@ -50,59 +57,64 @@ const PublishHtmlArtifactConfirmContent = ({<Flexbox gap={8} style={{ paddingBlock: 12, paddingInline: 16 }}><Text>{t('workingPanel.localFile.publish.privacy')}</Text>{showDetails && (- <Accordion defaultExpandedKeys={[]} gap={0} variant={'borderless'}>- <AccordionItem- defaultExpand={false}- indicatorPlacement={'start'}- itemKey={'details'}- paddingBlock={4}- paddingInline={0}- title={- <Text fontSize={12} type={'secondary'} weight={500}>- {t('workingPanel.localFile.publish.details')}- </Text>- }- >- <Flexbox gap={8} paddingBlock={'4px 0'}>- {inlinedPaths.length > 0 && (- <>- <Text>- {t('workingPanel.localFile.publish.inline', {- count: inlinedPaths.length,- limit: inlineLimit,- })}- </Text>- <PathList items={inlinedPaths} />- </>- )}- {uploadedPaths.length > 0 && (- <>- <Text>- {t('workingPanel.localFile.publish.upload', { count: uploadedPaths.length })}- </Text>- <PathList items={uploadedPaths} />- </>- )}- {missing.length > 0 && (- <Text type={'secondary'}>- {t('workingPanel.localFile.publish.missing', { list: missing.join(', ') })}+ <Accordion+ indicatorPlacement={'start'}+ variant={'borderless'}+ items={[+ {+ children: (+ <Flexbox gap={8} paddingBlock={'4px 0'}>+ {inlinedPaths.length > 0 && (+ <>+ <Text>+ {t('workingPanel.localFile.publish.inline', {+ count: inlinedPaths.length,+ limit: inlineLimit,+ })}+ </Text>+ <PathList items={inlinedPaths} />+ </>+ )}+ {uploadedPaths.length > 0 && (+ <>+ <Text>+ {t('workingPanel.localFile.publish.upload', {+ count: uploadedPaths.length,+ })}+ </Text>+ <PathList items={uploadedPaths} />+ </>+ )}+ {missing.length > 0 && (+ <Text type={'secondary'}>+ {t('workingPanel.localFile.publish.missing', { list: missing.join(', ') })}+ </Text>+ )}+ {oversized.length > 0 && (+ <Text type={'secondary'}>+ {t('workingPanel.localFile.publish.oversized', {+ list: oversized.join(', '),+ })}+ </Text>+ )}+ {remotes.length > 0 && (+ <>+ <Text>{t('workingPanel.localFile.publish.remotes')}</Text>+ <PathList items={remotes} />+ </>+ )}+ <Text type={'secondary'}>{t('workingPanel.localFile.publish.dynamic')}</Text>+ </Flexbox>+ ),+ key: 'details',+ title: (+ <Text fontSize={12} type={'secondary'} weight={500}>+ {t('workingPanel.localFile.publish.details')}</Text>- )}- {oversized.length > 0 && (- <Text type={'secondary'}>- {t('workingPanel.localFile.publish.oversized', { list: oversized.join(', ') })}- </Text>- )}- {remotes.length > 0 && (- <>- <Text>{t('workingPanel.localFile.publish.remotes')}</Text>- <PathList items={remotes} />- </>- )}- <Text type={'secondary'}>{t('workingPanel.localFile.publish.dynamic')}</Text>- </Flexbox>- </AccordionItem>- </Accordion>+ ),+ },+ ]}+ />)}<Text type={'secondary'}>{t('workingPanel.localFile.publish.note')}</Text></Flexbox>