Skip to content

🤯 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.

✨ feat(share): share topics, agents and AI generations to X / Weibo / Instagram / WeChat Moments (#23168)

Rdmclin2c5c2ee82c1fe
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 160910f67c1..57cb8f3ce16 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2338,6 +2338,16 @@
"shareModal.format.markdown": "Markdown",
"shareModal.generatePdf": "Generate PDF",
"shareModal.generatingPdf": "Generating PDF...",
+ "shareModal.generation.disabled": "Public link turned off",
+ "shareModal.generation.disabledHint": "Turn on the public link to share it on social media",
+ "shareModal.generation.enabled": "Public link created and copied",
+ "shareModal.generation.enabledNotCopied": "Public link created",
+ "shareModal.generation.entry": "Share",
+ "shareModal.generation.link.desc": "Visitors can view and download the file. You can turn the link off at any time.",
+ "shareModal.generation.link.label": "Anyone with the link can view",
+ "shareModal.generation.loadError": "Couldn't load the share settings",
+ "shareModal.generation.title": "Share this creation",
+ "shareModal.generation.updateError": "Couldn't update the link. Try again.",
"shareModal.imageType": "Image Format",
"shareModal.includeTool": "Include Skill messages",
"shareModal.includeUser": "Include User Messages",
@@ -2386,6 +2396,32 @@
"shareModal.regeneratePdf": "Regenerate PDF",
"shareModal.screenshot": "Screenshot",
"shareModal.settings": "Export Settings",
+ "shareModal.social.agent.description": "An AI agent worth a try",
+ "shareModal.social.agent.disabledHint": "Publish this agent to the Community to share it on social media",
+ "shareModal.social.agent.entry": "Share to social media",
+ "shareModal.social.agent.untitled": "Untitled agent",
+ "shareModal.social.copyText": "Copy caption",
+ "shareModal.social.copyTextSuccess": "Caption copied",
+ "shareModal.social.description": "A conversation worth a look",
+ "shareModal.social.disabledHint": "Turn on link sharing to post this topic",
+ "shareModal.social.generation.description.image": "An image made with AI",
+ "shareModal.social.generation.description.music": "A song made with AI",
+ "shareModal.social.generation.description.video": "A video made with AI",
+ "shareModal.social.generation.fallbackTitle.image": "AI image",
+ "shareModal.social.generation.fallbackTitle.music": "AI music",
+ "shareModal.social.generation.fallbackTitle.video": "AI video",
+ "shareModal.social.instagram.copied": "Caption copied. Paste it into an Instagram post or story",
+ "shareModal.social.instagram.hint": "Instagram can't be filled in from the web. Copy the caption with the link, then paste it into a post or story.",
+ "shareModal.social.instagram.open": "Open Instagram",
+ "shareModal.social.platform.instagram": "Instagram",
+ "shareModal.social.platform.wechat": "WeChat",
+ "shareModal.social.platform.weibo": "Weibo",
+ "shareModal.social.platform.x": "X",
+ "shareModal.social.shareTo": "Share to {{platform}}",
+ "shareModal.social.title": "Share to social media",
+ "shareModal.social.untitled": "Untitled topic",
+ "shareModal.social.wechat.hint": "Scan with WeChat, then tap ··· on the opened page to share to Moments",
+ "shareModal.social.wechat.qrLabel": "QR code of the share link",
"shareModal.text": "Text",
"shareModal.title": "Export",
"shareModal.widthMode.label": "Width Mode",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 17506c4a539..c39ec6a4a22 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2338,6 +2338,16 @@
"shareModal.format.markdown": "Markdown",
"shareModal.generatePdf": "生成 PDF",
"shareModal.generatingPdf": "正在生成 PDF…",
+ "shareModal.generation.disabled": "公开链接已关闭",
+ "shareModal.generation.disabledHint": "开启公开链接后即可分享到社交媒体",
+ "shareModal.generation.enabled": "公开链接已生成并复制",
+ "shareModal.generation.enabledNotCopied": "公开链接已生成",
+ "shareModal.generation.entry": "分享",
+ "shareModal.generation.link.desc": "访客可以查看和下载这个文件,链接随时可以关闭。",
+ "shareModal.generation.link.label": "获得链接的任何人都可以查看",
+ "shareModal.generation.loadError": "分享设置加载失败",
+ "shareModal.generation.title": "分享这个作品",
+ "shareModal.generation.updateError": "分享链接更新失败,请重试",
"shareModal.imageType": "图片格式",
"shareModal.includeTool": "包含技能消息",
"shareModal.includeUser": "包含用户消息",
@@ -2386,6 +2396,32 @@
"shareModal.regeneratePdf": "重新生成 PDF",
"shareModal.screenshot": "截图",
"shareModal.settings": "导出设置",
+ "shareModal.social.agent.description": "一个值得一试的 AI 助手",
+ "shareModal.social.agent.disabledHint": "发布到社区后即可分享到社交媒体",
+ "shareModal.social.agent.entry": "分享到社交媒体",
+ "shareModal.social.agent.untitled": "未命名助手",
+ "shareModal.social.copyText": "复制文案",
+ "shareModal.social.copyTextSuccess": "文案已复制",
+ "shareModal.social.description": "这段对话值得一看",
+ "shareModal.social.disabledHint": "开启链接分享后即可分享到社交媒体",
+ "shareModal.social.generation.description.image": "一张 AI 生成的图片",
+ "shareModal.social.generation.description.music": "一首 AI 创作的歌曲",
+ "shareModal.social.generation.description.video": "一段 AI 生成的视频",
+ "shareModal.social.generation.fallbackTitle.image": "AI 图片",
+ "shareModal.social.generation.fallbackTitle.music": "AI 音乐",
+ "shareModal.social.generation.fallbackTitle.video": "AI 视频",
+ "shareModal.social.instagram.copied": "文案已复制,请在 Instagram 中粘贴到帖子或快拍",
+ "shareModal.social.instagram.hint": "Instagram 不支持从网页预填内容:复制带链接的文案后,粘贴到帖子或快拍中即可。",
+ "shareModal.social.instagram.open": "打开 Instagram",
+ "shareModal.social.platform.instagram": "Instagram",
+ "shareModal.social.platform.wechat": "朋友圈",
+ "shareModal.social.platform.weibo": "微博",
+ "shareModal.social.platform.x": "X",
+ "shareModal.social.shareTo": "分享到 {{platform}}",
+ "shareModal.social.title": "分享到社交媒体",
+ "shareModal.social.untitled": "未命名话题",
+ "shareModal.social.wechat.hint": "微信扫码打开后,点右上角「···」分享到朋友圈",
+ "shareModal.social.wechat.qrLabel": "分享链接二维码",
"shareModal.text": "文本",
"shareModal.title": "导出",
"shareModal.widthMode.label": "宽度模式",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 219ded712ca..5e90e7fb1e2 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1963,6 +1963,17 @@ export default {
'shareModal.format.markdown': 'Markdown',
'shareModal.generatePdf': 'Generate PDF',
'shareModal.generatingPdf': 'Generating PDF...',
+ 'shareModal.generation.disabled': 'Public link turned off',
+ 'shareModal.generation.disabledHint': 'Turn on the public link to share it on social media',
+ 'shareModal.generation.enabled': 'Public link created and copied',
+ 'shareModal.generation.enabledNotCopied': 'Public link created',
+ 'shareModal.generation.entry': 'Share',
+ 'shareModal.generation.link.desc':
+ 'Visitors can view and download the file. You can turn the link off at any time.',
+ 'shareModal.generation.link.label': 'Anyone with the link can view',
+ 'shareModal.generation.loadError': "Couldn't load the share settings",
+ 'shareModal.generation.title': 'Share this creation',
+ 'shareModal.generation.updateError': "Couldn't update the link. Try again.",
'shareModal.imageType': 'Image Format',
'shareModal.includeTool': 'Include Skill messages',
'shareModal.includeUser': 'Include User Messages',
@@ -2009,6 +2020,35 @@ export default {
'shareModal.popover.privacyWarning.title': 'Before you share this link',
'shareModal.popover.title': 'Share Topic',
'shareModal.popover.visibility': 'Visibility',
+ 'shareModal.social.agent.description': 'An AI agent worth a try',
+ 'shareModal.social.agent.disabledHint':
+ 'Publish this agent to the Community to share it on social media',
+ 'shareModal.social.agent.entry': 'Share to social media',
+ 'shareModal.social.agent.untitled': 'Untitled agent',
+ 'shareModal.social.copyText': 'Copy caption',
+ 'shareModal.social.copyTextSuccess': 'Caption copied',
+ 'shareModal.social.description': 'A conversation worth a look',
+ 'shareModal.social.disabledHint': 'Turn on link sharing to post this topic',
+ 'shareModal.social.generation.description.image': 'An image made with AI',
+ 'shareModal.social.generation.description.music': 'A song made with AI',
+ 'shareModal.social.generation.description.video': 'A video made with AI',
+ 'shareModal.social.generation.fallbackTitle.image': 'AI image',
+ 'shareModal.social.generation.fallbackTitle.music': 'AI music',
+ 'shareModal.social.generation.fallbackTitle.video': 'AI video',
+ 'shareModal.social.instagram.copied': 'Caption copied. Paste it into an Instagram post or story',
+ 'shareModal.social.instagram.hint':
+ "Instagram can't be filled in from the web. Copy the caption with the link, then paste it into a post or story.",
+ 'shareModal.social.instagram.open': 'Open Instagram',
+ 'shareModal.social.platform.instagram': 'Instagram',
+ 'shareModal.social.platform.wechat': 'WeChat',
+ 'shareModal.social.platform.weibo': 'Weibo',
+ 'shareModal.social.platform.x': 'X',
+ 'shareModal.social.shareTo': 'Share to {{platform}}',
+ 'shareModal.social.title': 'Share to social media',
+ 'shareModal.social.untitled': 'Untitled topic',
+ 'shareModal.social.wechat.hint':
+ 'Scan with WeChat, then tap ··· on the opened page to share to Moments',
+ 'shareModal.social.wechat.qrLabel': 'QR code of the share link',
'shareModal.regeneratePdf': 'Regenerate PDF',
'shareModal.screenshot': 'Screenshot',
'shareModal.settings': 'Export Settings',
diff --git a/src/features/GenerationShareModal/GenerationShareContent.tsx b/src/features/GenerationShareModal/GenerationShareContent.tsx
new file mode 100644
index 00000000000..5d19f94feda
--- /dev/null
+++ b/src/features/GenerationShareModal/GenerationShareContent.tsx
@@ -0,0 +1,151 @@
+'use client';
+
+import type { FileShareSettings, FileShareVisibility } from '@lobechat/types';
+import { fileShareUrl } from '@lobechat/utils/fileShare';
+import {
+ Button,
+ copyToClipboard,
+ Flexbox,
+ Input,
+ Skeleton,
+ Switch,
+ Text,
+ toast,
+ useModalContext,
+} from '@lobehub/ui';
+import { CopyIcon } from 'lucide-react';
+import { memo, useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import useSWR from 'swr';
+
+import SocialShare from '@/features/SocialShare';
+import { useAppOrigin } from '@/hooks/useAppOrigin';
+import { mutate as globalMutate } from '@/libs/swr';
+import { lambdaClient } from '@/libs/trpc/client';
+
+export type GenerationShareType = 'image' | 'music' | 'video';
+
+/**
+ * Same key as the file share button in the resource library and file preview,
+ * so every entry to one file's share shows the same state.
+ */
+const FILE_SHARE_SETTINGS_KEY = (fileId: string) => ['fileShare.getShareSettings', fileId];
+
+export interface GenerationShareContentProps {
+ /** Library file the generation was saved as; the share link is that file's. */
+ fileId: string;
+ /** Prompt of the batch; leads the post when there is no title. */
+ prompt?: string;
+ /** Song title, when the generation has one. */
+ title?: string;
+ type: GenerationShareType;
+}
+
+/**
+ * The owner's share panel for one generation: the public-link switch of the
+ * file it was saved as, the link, and the four-channel social share.
+ */
+const GenerationShareContent = memo<GenerationShareContentProps>(
+ ({ fileId, prompt, title, type }) => {
+ const { t } = useTranslation('chat');
+ const { close } = useModalContext();
+ const appOrigin = useAppOrigin();
+ const [updating, setUpdating] = useState(false);
+
+ const { data, error, isLoading, mutate } = useSWR(
+ FILE_SHARE_SETTINGS_KEY(fileId),
+ () => lambdaClient.fileShare.getShareSettings.query({ fileId }),
+ { revalidateOnFocus: false },
+ );
+
+ const isPublic = data?.visibility === 'link';
+ const shareUrl = isPublic ? fileShareUrl(appOrigin, data.shareId) : undefined;
+
+ const setVisibility = useCallback(
+ async (visibility: FileShareVisibility) => {
+ setUpdating(true);
+ let next: FileShareSettings | null;
+ try {
+ next = await lambdaClient.fileShare.updateShareSettings.mutate({ fileId, visibility });
+ await globalMutate(FILE_SHARE_SETTINGS_KEY(fileId), next, { revalidate: false });
+ } catch {
+ toast.error(t('shareModal.generation.updateError'));
+ return;
+ } finally {
+ setUpdating(false);
+ }
+
+ if (visibility !== 'link' || !next) {
+ toast.success(t('shareModal.generation.disabled'));
+ return;
+ }
+
+ // Turning the link on is the moment people want it: copy it right away.
+ // The link is already live, so a refused clipboard is not a failed update.
+ try {
+ await copyToClipboard(fileShareUrl(appOrigin, next.shareId));
+ toast.success(t('shareModal.generation.enabled'));
+ } catch {
+ toast.success(t('shareModal.generation.enabledNotCopied'));
+ }
+ },
+ [appOrigin, fileId, t],
+ );
+
+ const copyLink = useCallback(async () => {
+ if (!shareUrl) return;
+ await copyToClipboard(shareUrl);
+ toast.success(t('shareModal.copyLinkSuccess'));
+ }, [shareUrl, t]);
+
+ if (isLoading) return <Skeleton.Text rows={4} />;
+
+ if (error && !data)
+ return (
+ <Flexbox align={'center'} gap={12} paddingBlock={16}>
+ <Text type={'secondary'}>{t('shareModal.generation.loadError')}</Text>
+ <Button onClick={() => mutate()}>{t('retry', { ns: 'common' })}</Button>
+ </Flexbox>
+ );
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
+ <Flexbox gap={2}>
+ <Text strong>{t('shareModal.generation.link.label')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('shareModal.generation.link.desc')}
+ </Text>
+ </Flexbox>
+ <Switch
+ aria-label={t('shareModal.generation.link.label')}
+ checked={isPublic}
+ loading={updating}
+ onChange={(checked) => setVisibility(checked ? 'link' : 'private')}
+ />
+ </Flexbox>
+
+ {shareUrl && (
+ <Flexbox horizontal gap={8}>
+ <Input readOnly value={shareUrl} variant={'filled'} />
+ <Button icon={CopyIcon} onClick={copyLink}>
+ {t('shareModal.copyLink')}
+ </Button>
+ </Flexbox>
+ )}
+
+ <SocialShare
+ description={t(`shareModal.social.generation.description.${type}`)}
+ disabledHint={t('shareModal.generation.disabledHint')}
+ shareUrl={shareUrl}
+ title={title || prompt || t(`shareModal.social.generation.fallbackTitle.${type}`)}
+ onLeave={close}
+ />
+ </Flexbox>
+ );
+ },
+);
+
+GenerationShareContent.displayName = 'GenerationShareContent';
+
+export default GenerationShareContent;
diff --git a/src/features/GenerationShareModal/index.tsx b/src/features/GenerationShareModal/index.tsx
new file mode 100644
index 00000000000..4e2a331e8f4
--- /dev/null
+++ b/src/features/GenerationShareModal/index.tsx
@@ -0,0 +1,37 @@
+'use client';
+
+import { createModal } from '@lobehub/ui';
+import { t } from 'i18next';
+
+import { useServerConfigStore } from '@/store/serverConfig';
+import { serverConfigSelectors } from '@/store/serverConfig/selectors';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import GenerationShareContent, { type GenerationShareContentProps } from './GenerationShareContent';
+
+export type { GenerationShareType } from './GenerationShareContent';
+
+/** Opens the share panel of one generation result (image, video or song). */
+export const openGenerationShareModal = (props: GenerationShareContentProps) =>
+ createModal({
+ content: <GenerationShareContent {...props} />,
+ footer: null,
+ maskClosable: true,
+ title: t('shareModal.generation.title', { ns: 'chat' }),
+ width: 'min(92vw, 400px)',
+ });
+
+/**
+ * A generation is shared as the library file it was saved as, so it needs:
+ * - file sharing, which only the cloud edition implements;
+ * - a saved file (`fileId`); older generations without one have nothing to share;
+ * - to be the creator's own. The file share API enforces the same; a batch
+ * without a creator is a personal-space one, always the user's.
+ */
+export const useCanShareGeneration = (fileId?: string | null, creatorId?: string | null) => {
+ const currentUserId = useUserStore(userProfileSelectors.userId);
+ const enableFileShare = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);
+
+ return enableFileShare && !!fileId && (!creatorId || creatorId === currentUserId);
+};
diff --git a/src/features/SharePopover/index.social.test.tsx b/src/features/SharePopover/index.social.test.tsx
new file mode 100644
index 00000000000..cdef1901610
--- /dev/null
+++ b/src/features/SharePopover/index.social.test.tsx
@@ -0,0 +1,100 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import type * as BaseUI from '@lobehub/ui';
+import { fireEvent, render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { SharePopoverContent } from './index';
+
+const mocks = vi.hoisted(() => ({
+ canPublishLink: true,
+ close: vi.fn(),
+ share: undefined as undefined | { id: string; visibility: 'link' | 'private' },
+}));
+
+vi.mock('@lobehub/ui', async (importOriginal) => {
+ const actual = await importOriginal<typeof BaseUI>();
+ return {
+ ...actual,
+ QRCode: () => <div data-testid={'qrcode'} />,
+ usePopoverContext: () => ({ close: mocks.close }),
+ };
+});
+
+vi.mock('@/hooks/useAppOrigin', () => ({ useAppOrigin: () => 'https://app.lobehub.com' }));
+vi.mock('@/hooks/useIsMobile', () => ({ useIsMobile: () => false }));
+vi.mock('@/hooks/usePermission', () => ({
+ usePermission: () => ({ allowed: true, reason: '' }),
+}));
+vi.mock('@/hooks/useTopicSharePermission', () => ({
+ useTopicSharePermission: () => ({
+ allowed: mocks.canPublishLink,
+ reason: 'only the creator can publish',
+ }),
+}));
+vi.mock('./useTopicShare', () => ({
+ useTopicShare: () => ({
+ error: undefined,
+ isLoading: false,
+ retry: vi.fn(),
+ setVisibility: vi.fn(),
+ shareInfo: mocks.share,
+ visibility: mocks.share?.visibility ?? 'private',
+ }),
+}));
+
+const tiles = () => [...document.querySelectorAll<HTMLButtonElement>('button[data-platform]')];
+
+describe('SharePopover social share section', () => {
+ beforeEach(() => {
+ mocks.canPublishLink = true;
+ mocks.share = undefined;
+ mocks.close.mockReset();
+ });
+
+ it('disables social share and asks to enable link sharing when there is no share id', () => {
+ render(<SharePopoverContent topicId={'tpc_1'} />);
+
+ expect(screen.getByText('shareModal.social.title')).toBeInTheDocument();
+ expect(screen.getByText('shareModal.social.disabledHint')).toBeInTheDocument();
+ expect(tiles()).toHaveLength(4);
+ for (const tile of tiles()) expect(tile).toBeDisabled();
+ });
+
+ it('stays disabled while a share record exists but is private', () => {
+ mocks.share = { id: 'abc123', visibility: 'private' };
+ render(<SharePopoverContent topicId={'tpc_1'} />);
+
+ for (const tile of tiles()) expect(tile).toBeDisabled();
+ });
+
+ it('shows the publish restriction instead when the user may not publish a link', () => {
+ mocks.canPublishLink = false;
+ render(<SharePopoverContent topicId={'tpc_1'} />);
+
+ expect(screen.getAllByText('only the creator can publish')).toHaveLength(1);
+ expect(screen.queryByText('shareModal.social.disabledHint')).not.toBeInTheDocument();
+ for (const tile of tiles()) expect(tile).toBeDisabled();
+ });
+
+ it('enables all four channels once the topic is shared by link', () => {
+ mocks.share = { id: 'abc123', visibility: 'link' };
+ render(<SharePopoverContent topicId={'tpc_1'} />);
+
+ expect(screen.queryByText('shareModal.social.disabledHint')).not.toBeInTheDocument();
+ for (const tile of tiles()) expect(tile).toBeEnabled();
+ });
+
+ it('closes the popover when a channel sends the user to another site', () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ mocks.share = { id: 'abc123', visibility: 'link' };
+ render(<SharePopoverContent topicId={'tpc_1'} />);
+
+ fireEvent.click(document.querySelector<HTMLButtonElement>('button[data-platform="x"]')!);
+
+ expect(open).toHaveBeenCalledTimes(1);
+ expect(mocks.close).toHaveBeenCalledTimes(1);
+ open.mockRestore();
+ });
+});
diff --git a/src/features/SharePopover/index.tsx b/src/features/SharePopover/index.tsx
index da1a81b5815..567fbb3a625 100644
--- a/src/features/SharePopover/index.tsx
+++ b/src/features/SharePopover/index.tsx
@@ -33,11 +33,13 @@ import { memo, useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ArticleSkeleton } from '@/components/Skeleton';
+import SocialShare from '@/features/SocialShare';
import { useAppOrigin } from '@/hooks/useAppOrigin';
import { useIsMobile } from '@/hooks/useIsMobile';
import { usePermission } from '@/hooks/usePermission';
import { useTopicSharePermission } from '@/hooks/useTopicSharePermission';
import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -74,6 +76,9 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ agentId, onOpenMod
const chatActiveTopicId = useChatStore((s) => s.activeTopicId);
const activeTopicId = topicId ?? chatActiveTopicId;
+ const topicTitle = useChatStore((s) =>
+ activeTopicId ? topicSelectors.getTopicById(activeTopicId)(s)?.title : undefined,
+ );
const [hideTopicSharePrivacyWarning, updateSystemStatus] = useGlobalStore((s) => [
systemStatusSelectors.systemStatus(s).hideTopicSharePrivacyWarning ?? false,
s.updateSystemStatus,
@@ -268,6 +273,19 @@ const SharePopoverContent = memo<SharePopoverContentProps>(({ agentId, onOpenMod
<div className={styles.divider} />
+ {/* Posting needs a public link; the section stays disabled until there is one. */}
+ <SocialShare
+ className={styles.section}
+ description={t('shareModal.social.description')}
+ // The publish restriction is already explained above.
+ disabledHint={linkRestricted ? undefined : t('shareModal.social.disabledHint')}
+ shareUrl={isLinkShared ? shareUrl : undefined}
+ title={topicTitle || t('shareModal.social.untitled')}
+ onLeave={close}
+ />
+
+ <div className={styles.divider} />
+
<button className={styles.exportRow} type={'button'} onClick={handleOpenModal}>
<Icon className={styles.exportIcon} icon={DownloadIcon} size={16} />
<span className={styles.exportLabel}>{t('shareModal.popover.export')}</span>
@@ -326,4 +344,6 @@ const SharePopover = memo<SharePopoverProps>(
},
);
+export { SharePopoverContent };
+
export default SharePopover;
diff --git a/src/features/SocialShare/index.test.tsx b/src/features/SocialShare/index.test.tsx
new file mode 100644
index 00000000000..ddb57ed4fae
--- /dev/null
+++ b/src/features/SocialShare/index.test.tsx
@@ -0,0 +1,226 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import type * as BaseUI from '@lobehub/ui';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import SocialShare from '.';
+
+const mocks = vi.hoisted(() => ({
+ copyToClipboard: vi.fn(),
+ isMobile: false,
+ toastSuccess: vi.fn(),
+}));
+
+vi.mock('@lobehub/ui', async (importOriginal) => {
+ const actual = await importOriginal<typeof BaseUI>();
+ return {
+ ...actual,
+ QRCode: ({ value, 'aria-label': label }: { 'aria-label'?: string; 'value': string }) => (
+ <div aria-label={label} data-testid={'qrcode'} data-value={value} />
+ ),
+ copyToClipboard: mocks.copyToClipboard,
+ toast: { ...actual.toast, success: mocks.toastSuccess },
+ };
+});
+
+vi.mock('@/hooks/useIsMobile', () => ({ useIsMobile: () => mocks.isMobile }));
+
+const shareUrl = 'https://app.lobehub.com/share/t/abc123';
+
+const tile = (platform: string) =>
+ document.querySelector<HTMLButtonElement>(`button[data-platform="${platform}"]`)!;
+
+describe('SocialShare', () => {
+ beforeEach(() => {
+ mocks.copyToClipboard.mockReset().mockResolvedValue(undefined);
+ mocks.toastSuccess.mockReset();
+ mocks.isMobile = false;
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('renders four platform entries', () => {
+ render(<SocialShare shareUrl={shareUrl} title={'My topic'} />);
+
+ expect(screen.getByText('shareModal.social.title')).toBeInTheDocument();
+ for (const platform of ['x', 'weibo', 'instagram', 'wechat']) {
+ expect(tile(platform)).toBeEnabled();
+ }
+ });
+
+ it('disables every entry and shows the hint without a share link', () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ render(
+ <SocialShare disabledHint={'turn on link sharing'} shareUrl={undefined} title={'My topic'} />,
+ );
+
+ expect(screen.getByText('turn on link sharing')).toBeInTheDocument();
+ for (const platform of ['x', 'weibo', 'instagram', 'wechat']) {
+ expect(tile(platform)).toBeDisabled();
+ fireEvent.click(tile(platform));
+ }
+ expect(open).not.toHaveBeenCalled();
+ expect(mocks.copyToClipboard).not.toHaveBeenCalled();
+ expect(screen.queryByTestId('qrcode')).not.toBeInTheDocument();
+ });
+
+ it('opens the X intent in a new window with the encoded link', () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ render(<SocialShare shareUrl={shareUrl} title={'My topic'} />);
+
+ fireEvent.click(tile('x'));
+
+ const [href, target, features] = open.mock.calls[0];
+ expect(String(href)).toMatch(/^https:\/\/twitter\.com\/intent\/tweet\?/);
+ expect(String(href)).toContain(`url=${encodeURIComponent(shareUrl)}`);
+ expect(new URL(String(href)).searchParams.get('text')).toContain('My topic');
+ expect(target).toBe('_blank');
+ expect(features).toContain('noopener');
+ });
+
+ it('opens the Weibo share page in a new window with the encoded link', () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ render(<SocialShare shareUrl={shareUrl} title={'My topic'} />);
+
+ fireEvent.click(tile('weibo'));
+
+ const href = String(open.mock.calls[0][0]);
+ expect(href).toMatch(/^https:\/\/service\.weibo\.com\/share\/share\.php\?/);
+ expect(href).toContain(`url=${encodeURIComponent(shareUrl)}`);
+ expect(new URL(href).searchParams.get('title')).toContain('My topic');
+ });
+
+ it('copies the caption for Instagram and shows how to post it', async () => {
+ render(<SocialShare shareUrl={shareUrl} title={'My topic'} />);
+
+ fireEvent.click(tile('instagram'));
+
+ await waitFor(() => expect(mocks.copyToClipboard).toHaveBeenCalledTimes(1));
+ const copied = mocks.copyToClipboard.mock.calls[0][0] as string;
+ expect(copied).toContain('My topic');
+ expect(copied).toContain('via LobeHub');
+ expect(copied.endsWith(shareUrl)).toBe(true);
+ expect(mocks.toastSuccess).toHaveBeenCalledWith('shareModal.social.instagram.copied');
+
+ const panel = screen.getByTestId('social-instagram-panel');
+ expect(panel).toHaveTextContent('shareModal.social.instagram.hint');
+ expect(panel).toHaveTextContent(shareUrl);
+ expect(tile('instagram')).toHaveAttribute('aria-expanded', 'true');
+ expect(screen.getByText('shareModal.social.instagram.open').closest('a')).toHaveAttribute(
+ 'href',
+ 'https://www.instagram.com/',
+ );
+ });
+
+ it('uses the system share sheet for Instagram on mobile', async () => {
+ mocks.isMobile = true;
+ const share = vi.fn().mockResolvedValue(undefined);
+ Object.defineProperty(navigator, 'share', { configurable: true, value: share });
+ Object.defineProperty(navigator, 'canShare', { configurable: true, value: () => true });
+
+ render(<SocialShare shareUrl={shareUrl} title={'My topic'} />);
+ fireEvent.click(tile('instagram'));
+
+ await waitFor(() => expect(share).toHaveBeenCalledTimes(1));
+ expect(mocks.copyToClipboard).not.toHaveBeenCalled();
+
+ delete (navigator as any).share;
+ delete (navigator as any).canShare;
+ });
+
+ it('shows a QR code of the share link for WeChat Moments, with copy actions', async () => {
+ render(<SocialShare shareUrl={shareUrl} title={'My topic'} />);
+
+ fireEvent.click(tile('wechat'));
+
+ const panel = screen.getByTestId('social-wechat-panel');
+ expect(screen.getByTestId('qrcode')).toHaveAttribute('data-value', shareUrl);
+ expect(panel).toHaveTextContent('shareModal.social.wechat.hint');
+
+ fireEvent.click(screen.getByText('shareModal.copyLink'));
+ await waitFor(() => expect(mocks.copyToClipboard).toHaveBeenCalledWith(shareUrl));
+
+ fireEvent.click(screen.getByText('shareModal.social.copyText'));
+ await waitFor(() => expect(mocks.copyToClipboard).toHaveBeenCalledTimes(2));
+ expect(mocks.copyToClipboard.mock.calls[1][0]).toContain('via LobeHub');
+
+ // Pressing it again folds the panel.
+ fireEvent.click(tile('wechat'));
+ expect(screen.queryByTestId('qrcode')).not.toBeInTheDocument();
+ });
+
+ describe('closing the popover before leaving the page', () => {
+ it.each(['x', 'weibo'])('closes the popover before opening the %s intent', (platform) => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ const onLeave = vi.fn();
+ render(<SocialShare shareUrl={shareUrl} title={'My topic'} onLeave={onLeave} />);
+
+ fireEvent.click(tile(platform));
+
+ expect(open).toHaveBeenCalledTimes(1);
+ expect(onLeave).toHaveBeenCalledTimes(1);
+ expect(onLeave.mock.invocationCallOrder[0]).toBeLessThan(open.mock.invocationCallOrder[0]);
+ });
+
+ it('calls onLeave from "Open Instagram" but not when the panel opens', async () => {
+ const onLeave = vi.fn();
+ render(<SocialShare shareUrl={shareUrl} title={'My topic'} onLeave={onLeave} />);
+
+ fireEvent.click(tile('instagram'));
+ await waitFor(() => expect(mocks.copyToClipboard).toHaveBeenCalledTimes(1));
+ // The caption panel has to stay up so the user can read and copy it.
+ expect(onLeave).not.toHaveBeenCalled();
+
+ const openLink = screen.getByText('shareModal.social.instagram.open').closest('a')!;
+ fireEvent.click(openLink);
+ expect(onLeave).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not call onLeave for WeChat, which stays inside the popover', () => {
+ const onLeave = vi.fn();
+ render(<SocialShare shareUrl={shareUrl} title={'My topic'} onLeave={onLeave} />);
+
+ fireEvent.click(tile('wechat'));
+ expect(onLeave).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('resetting the open panel when the link changes', () => {
+ it.each([
+ ['wechat', 'social-wechat-panel'],
+ ['instagram', 'social-instagram-panel'],
+ ])('drops the %s panel once the link is turned off and back on', async (platform, testId) => {
+ const { rerender } = render(<SocialShare shareUrl={shareUrl} title={'My topic'} />);
+
+ fireEvent.click(tile(platform));
+ await waitFor(() => expect(screen.getByTestId(testId)).toBeInTheDocument());
+
+ rerender(<SocialShare shareUrl={undefined} title={'My topic'} />);
+ expect(screen.queryByTestId(testId)).not.toBeInTheDocument();
+
+ rerender(<SocialShare shareUrl={shareUrl} title={'My topic'} />);
+ expect(screen.queryByTestId(testId)).not.toBeInTheDocument();
+ expect(tile(platform)).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it.each([
+ ['wechat', 'social-wechat-panel'],
+ ['instagram', 'social-instagram-panel'],
+ ])('drops the %s panel when another topic link takes over', async (platform, testId) => {
+ const { rerender } = render(<SocialShare shareUrl={shareUrl} title={'My topic'} />);
+
+ fireEvent.click(tile(platform));
+ await waitFor(() => expect(screen.getByTestId(testId)).toBeInTheDocument());
+
+ rerender(
+ <SocialShare shareUrl={'https://app.lobehub.com/share/t/other'} title={'Other topic'} />,
+ );
+ expect(screen.queryByTestId(testId)).not.toBeInTheDocument();
+ expect(screen.queryByTestId('qrcode')).not.toBeInTheDocument();
+ });
+ });
+});
diff --git a/src/features/SocialShare/index.tsx b/src/features/SocialShare/index.tsx
new file mode 100644
index 00000000000..fdf5d470497
--- /dev/null
+++ b/src/features/SocialShare/index.tsx
@@ -0,0 +1,246 @@
+'use client';
+
+import SiInstagram from '@icons-pack/react-simple-icons/icons/SiInstagram';
+import SiSinaweibo from '@icons-pack/react-simple-icons/icons/SiSinaweibo';
+import SiWechat from '@icons-pack/react-simple-icons/icons/SiWechat';
+import SiX from '@icons-pack/react-simple-icons/icons/SiX';
+import { Button, copyToClipboard, cx, Flexbox, QRCode, Text, toast, useTheme } from '@lobehub/ui';
+import { CopyIcon, ExternalLinkIcon, LinkIcon } from 'lucide-react';
+import {
+ type ComponentType,
+ type CSSProperties,
+ memo,
+ useCallback,
+ useMemo,
+ useState,
+} from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useIsMobile } from '@/hooks/useIsMobile';
+
+import {
+ buildSocialShareActions,
+ openShareWindow,
+ shareToInstagram,
+ SOCIAL_PLATFORMS,
+ type SocialPlatform,
+} from './socialShare';
+import { styles } from './style';
+
+const QR_SIZE = 112;
+/**
+ * Scanners need dark modules on a light ground, so the code ignores the theme.
+ * The light ground comes from `theme.colorWhite`; there is no black token.
+ */
+// lobe-design-ignore LOBE-RAW-COLOR: QR modules must stay black in dark mode or WeChat can't scan them
+const QR_MODULE_COLOR = '#000';
+
+const PLATFORM_ICONS: Record<SocialPlatform, ComponentType<{ size?: number }>> = {
+ instagram: SiInstagram,
+ wechat: SiWechat,
+ weibo: SiSinaweibo,
+ x: SiX,
+};
+
+type SocialPanel = 'instagram' | 'wechat';
+
+export interface SocialShareProps {
+ className?: string;
+ /** One line under the title in every post, e.g. what kind of content this is. */
+ description?: string;
+ /** Shown under the title while the buttons are disabled. */
+ disabledHint?: string;
+ /**
+ * Called right before the user is sent to another site (X, Weibo, Instagram),
+ * so the host popover can close instead of lingering over the page.
+ */
+ onLeave?: () => void;
+ /** Public share link; empty while the content has no public link yet. */
+ shareUrl?: string;
+ style?: CSSProperties;
+ /** Name of the shared content; leads every post. */
+ title: string;
+}
+
+/**
+ * Four-channel social share (X, Weibo, Instagram, WeChat Moments) for any
+ * content that has a public link: topics, community agents, generations.
+ */
+const SocialShare = memo<SocialShareProps>(
+ ({ className, style, description, disabledHint, onLeave, shareUrl, title }) => {
+ const { t } = useTranslation('chat');
+ const isMobile = useIsMobile();
+ const theme = useTheme();
+ // Instagram and WeChat have no web intent; their fallback opens inline.
+ const [panel, setPanel] = useState<SocialPanel>();
+ // The panel belongs to the link it was opened for. Turning the link off, back
+ // on, or switching to another topic's link folds it (reset during render, so
+ // the stale panel never paints).
+ const [panelUrl, setPanelUrl] = useState(shareUrl);
+ if (panelUrl !== shareUrl) {
+ setPanelUrl(shareUrl);
+ setPanel(undefined);
+ }
+
+ const disabled = !shareUrl;
+
+ const actions = useMemo(
+ () =>
+ shareUrl
+ ? buildSocialShareActions({
+ description,
+ title,
+ url: shareUrl,
+ })
+ : undefined,
+ [description, shareUrl, title],
+ );
+
+ const copyText = useCallback(async () => {
+ if (!actions) return;
+ await copyToClipboard(actions.instagram.copy.textWithUrl);
+ toast.success(t('shareModal.social.copyTextSuccess'));
+ }, [actions, t]);
+
+ const copyLink = useCallback(async () => {
+ if (!shareUrl) return;
+ await copyToClipboard(shareUrl);
+ toast.success(t('shareModal.copyLinkSuccess'));
+ }, [shareUrl, t]);
+
+ const handleClick = useCallback(
+ async (platform: SocialPlatform) => {
+ if (!actions) return;
+ const action = actions[platform];
+
+ switch (action.kind) {
+ case 'intent': {
+ setPanel(undefined);
+ // Close the popover first, then leave; the click's user activation
+ // still lets `window.open` through.
+ onLeave?.();
+ openShareWindow(action.href);
+ return;
+ }
+ case 'clipboard': {
+ setPanel('instagram');
+ const result = await shareToInstagram(action.copy, {
+ copy: copyToClipboard,
+ // Desktop share sheets do not offer Instagram; only use it on mobile.
+ navigator: isMobile && typeof navigator !== 'undefined' ? navigator : undefined,
+ });
+ if (result === 'copied') toast.success(t('shareModal.social.instagram.copied'));
+ return;
+ }
+ case 'qrcode': {
+ setPanel((current) => (current === 'wechat' ? undefined : 'wechat'));
+ }
+ }
+ },
+ [actions, isMobile, onLeave, t],
+ );
+
+ return (
+ <Flexbox className={className} gap={10} style={style}>
+ <Flexbox gap={1}>
+ <Text strong type={disabled ? 'secondary' : undefined}>
+ {t('shareModal.social.title')}
+ </Text>
+ {disabled && disabledHint && (
+ <Text fontSize={12} type={'secondary'}>
+ {disabledHint}
+ </Text>
+ )}
+ </Flexbox>
+
+ <div className={styles.socialGrid} role={'group'}>
+ {SOCIAL_PLATFORMS.map((platform) => {
+ const PlatformIcon = PLATFORM_ICONS[platform];
+ const hasPanel = platform === 'instagram' || platform === 'wechat';
+ const label = t(`shareModal.social.platform.${platform}`);
+
+ return (
+ <button
+ aria-expanded={hasPanel ? panel === platform : undefined}
+ aria-label={t('shareModal.social.shareTo', { platform: label })}
+ className={cx(styles.socialTile, panel === platform && styles.socialTileActive)}
+ data-platform={platform}
+ disabled={disabled}
+ key={platform}
+ type={'button'}
+ onClick={() => handleClick(platform)}
+ >
+ <span className={styles.socialIcon}>
+ <PlatformIcon size={18} />
+ </span>
+ <span className={styles.socialLabel}>{label}</span>
+ </button>
+ );
+ })}
+ </div>
+
+ {actions && panel === 'instagram' && (
+ <Flexbox className={styles.socialPanel} data-testid={'social-instagram-panel'} gap={10}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('shareModal.social.instagram.hint')}
+ </Text>
+ <div className={styles.socialPreview}>{actions.instagram.copy.textWithUrl}</div>
+ <Flexbox horizontal gap={6}>
+ <Button block icon={CopyIcon} size={'small'} type={'primary'} onClick={copyText}>
+ {t('shareModal.social.copyText')}
+ </Button>
+ <Button
+ block
+ href={actions.instagram.openUrl}
+ icon={ExternalLinkIcon}
+ rel={'noopener noreferrer'}
+ size={'small'}
+ target={'_blank'}
+ onClick={onLeave}
+ >
+ {t('shareModal.social.instagram.open')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ )}
+
+ {actions && panel === 'wechat' && (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.socialPanel}
+ data-testid={'social-wechat-panel'}
+ gap={12}
+ >
+ <div className={styles.qrcode}>
+ <QRCode
+ aria-label={t('shareModal.social.wechat.qrLabel')}
+ // Dark modules on a light ground in every theme, or WeChat can't scan it.
+ bgColor={theme.colorWhite}
+ bordered={false}
+ color={QR_MODULE_COLOR}
+ size={QR_SIZE}
+ value={actions.wechat.qrValue}
+ />
+ </div>
+ <Flexbox flex={1} gap={8} style={{ minWidth: 0 }}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('shareModal.social.wechat.hint')}
+ </Text>
+ <Button block icon={LinkIcon} size={'small'} onClick={copyLink}>
+ {t('shareModal.copyLink')}
+ </Button>
+ <Button block icon={CopyIcon} size={'small'} onClick={copyText}>
+ {t('shareModal.social.copyText')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+SocialShare.displayName = 'SocialShare';
+
+export default SocialShare;
diff --git a/src/features/SocialShare/socialShare.test.ts b/src/features/SocialShare/socialShare.test.ts
new file mode 100644
index 00000000000..82792fb4531
--- /dev/null
+++ b/src/features/SocialShare/socialShare.test.ts
@@ -0,0 +1,194 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ buildSocialShareActions,
+ buildTwitterShareUrl,
+ buildTwitterText,
+ buildWeiboShareUrl,
+ composeShareCopy,
+ INSTAGRAM_URL,
+ openShareWindow,
+ SHARE_SIGNATURE,
+ shareToInstagram,
+ TWITTER_MAX_WEIGHT,
+ TWITTER_URL_WEIGHT,
+ twitterTextWeight,
+} from './socialShare';
+
+const url = 'https://app.lobehub.com/share/t/abc123';
+const input = { description: '来看看这段对话', title: 'React & Vue 对比?', url };
+
+describe('composeShareCopy', () => {
+ it('joins title, description and the LobeHub signature, then the link', () => {
+ const copy = composeShareCopy(input);
+
+ expect(copy.text).toBe(`React & Vue 对比? — 来看看这段对话 ${SHARE_SIGNATURE}`);
+ expect(copy.textWithUrl).toBe(`${copy.text}\n${url}`);
+ expect(copy.url).toBe(url);
+ });
+
+ it('drops an empty description and collapses whitespace', () => {
+ expect(composeShareCopy({ title: ' Hello \n world ', url }).text).toBe(
+ `Hello world ${SHARE_SIGNATURE}`,
+ );
+ });
+});
+
+describe('platform share URLs', () => {
+ it('builds an X intent with the encoded link and copy', () => {
+ const href = buildTwitterShareUrl(input);
+ const parsed = new URL(href);
+
+ expect(parsed.origin + parsed.pathname).toBe('https://twitter.com/intent/tweet');
+ expect(parsed.searchParams.get('url')).toBe(url);
+ expect(parsed.searchParams.get('text')).toBe(composeShareCopy(input).text);
+ // Reserved characters in the link and the copy are percent-encoded.
+ expect(href).toContain(`url=${encodeURIComponent(url)}`);
+ expect(href).toContain('%26');
+ expect(href).toContain('%3F');
+ expect(href).not.toContain(' ');
+ expect(href).not.toContain('+');
+ });
+
+ it('builds a Weibo share page URL with the encoded link and copy', () => {
+ const href = buildWeiboShareUrl(input);
+ const parsed = new URL(href);
+
+ expect(parsed.origin + parsed.pathname).toBe('https://service.weibo.com/share/share.php');
+ expect(parsed.searchParams.get('url')).toBe(url);
+ expect(parsed.searchParams.get('title')).toBe(composeShareCopy(input).text);
+ expect(href).toContain(`url=${encodeURIComponent(url)}`);
+ expect(href).toContain('%2Fshare%2Ft%2Fabc123');
+ // Weibo shows `+` literally, so spaces must be %20.
+ expect(href).not.toContain('+');
+ expect(href).toContain('React%20%26%20Vue');
+ });
+
+ it('keeps the same link and copy across all four platforms', () => {
+ const actions = buildSocialShareActions(input);
+ const copy = composeShareCopy(input);
+
+ const x = new URL(actions.x.href);
+ const weibo = new URL(actions.weibo.href);
+
+ expect(x.searchParams.get('url')).toBe(url);
+ expect(weibo.searchParams.get('url')).toBe(url);
+ expect(x.searchParams.get('text')).toBe(copy.text);
+ expect(weibo.searchParams.get('title')).toBe(copy.text);
+
+ expect(actions.instagram).toEqual({
+ copy,
+ kind: 'clipboard',
+ openUrl: INSTAGRAM_URL,
+ platform: 'instagram',
+ });
+ expect(actions.wechat).toEqual({ copy, kind: 'qrcode', platform: 'wechat', qrValue: url });
+ });
+});
+
+describe('buildTwitterText', () => {
+ it('shortens a long title so the post fits X and keeps the signature', () => {
+ const long = { title: '超长标题'.repeat(80), url };
+ const text = buildTwitterText(long);
+
+ expect(twitterTextWeight(text) + 1 + TWITTER_URL_WEIGHT).toBeLessThanOrEqual(
+ TWITTER_MAX_WEIGHT,
+ );
+ expect(text.endsWith(`… ${SHARE_SIGNATURE}`)).toBe(true);
+ });
+
+ // The ellipsis (U+2026) itself weighs 2 on X; reserving only 1 for it used
+ // to push a long Latin title to 281.
+ it.each([
+ ['Latin', { title: 'a'.repeat(400), url }],
+ ['Latin words', { title: 'lorem ipsum dolor sit amet '.repeat(20), url }],
+ ['Chinese', { title: '超长标题'.repeat(80), url }],
+ [
+ 'mixed',
+ {
+ description: '对比 React and Vue 的差异 🚀'.repeat(10),
+ title: 'AI 编程 Tips '.repeat(30),
+ url,
+ },
+ ],
+ ['odd boundary', { title: `${'a'.repeat(243)}中文`, url }],
+ ])('keeps a long %s title within 280 with the full link', (_, longInput) => {
+ const text = buildTwitterText(longInput);
+ const shareUrl = buildTwitterShareUrl(longInput);
+ const params = new URL(shareUrl).searchParams;
+
+ expect(text).toContain('…');
+ expect(text.endsWith(SHARE_SIGNATURE)).toBe(true);
+ // X joins text and link with a space and weighs any link at 23.
+ expect(twitterTextWeight(text) + 1 + TWITTER_URL_WEIGHT).toBeLessThanOrEqual(
+ TWITTER_MAX_WEIGHT,
+ );
+ expect(params.get('text')).toBe(text);
+ expect(params.get('url')).toBe(url);
+ expect(params.get('url')).toMatch(/\/share\/t\/abc123$/);
+ });
+
+ it('counts the ellipsis as two', () => {
+ expect(twitterTextWeight('…')).toBe(2);
+ });
+
+ it('counts CJK as two and Latin as one', () => {
+ expect(twitterTextWeight('ab')).toBe(2);
+ expect(twitterTextWeight('中文')).toBe(4);
+ });
+});
+
+describe('openShareWindow', () => {
+ it('opens a new window without an opener', () => {
+ const open = vi.fn();
+ openShareWindow('https://twitter.com/intent/tweet?url=x', { open });
+
+ expect(open).toHaveBeenCalledWith(
+ 'https://twitter.com/intent/tweet?url=x',
+ '_blank',
+ expect.stringContaining('noopener'),
+ );
+ });
+});
+
+describe('shareToInstagram', () => {
+ const copy = composeShareCopy(input);
+
+ it('copies the caption with the link when there is no share sheet', async () => {
+ const writeClipboard = vi.fn().mockResolvedValue(undefined);
+
+ await expect(shareToInstagram(copy, { copy: writeClipboard })).resolves.toBe('copied');
+ expect(writeClipboard).toHaveBeenCalledWith(copy.textWithUrl);
+ });
+
+ it('prefers the system share sheet when available', async () => {
+ const writeClipboard = vi.fn();
+ const share = vi.fn().mockResolvedValue(undefined);
+
+ await expect(
+ shareToInstagram(copy, { copy: writeClipboard, navigator: { canShare: () => true, share } }),
+ ).resolves.toBe('native');
+ expect(share).toHaveBeenCalledWith({ text: copy.textWithUrl });
+ expect(writeClipboard).not.toHaveBeenCalled();
+ });
+
+ it('treats a dismissed share sheet as cancelled', async () => {
+ const writeClipboard = vi.fn();
+ const share = vi.fn().mockRejectedValue(Object.assign(new Error('x'), { name: 'AbortError' }));
+
+ await expect(
+ shareToInstagram(copy, { copy: writeClipboard, navigator: { share } }),
+ ).resolves.toBe('cancelled');
+ expect(writeClipboard).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the clipboard when the share sheet fails', async () => {
+ const writeClipboard = vi.fn().mockResolvedValue(undefined);
+ const share = vi.fn().mockRejectedValue(new Error('not allowed'));
+
+ await expect(
+ shareToInstagram(copy, { copy: writeClipboard, navigator: { share } }),
+ ).resolves.toBe('copied');
+ expect(writeClipboard).toHaveBeenCalledWith(copy.textWithUrl);
+ });
+});
diff --git a/src/features/SocialShare/socialShare.ts b/src/features/SocialShare/socialShare.ts
new file mode 100644
index 00000000000..48a1b567a7c
--- /dev/null
+++ b/src/features/SocialShare/socialShare.ts
@@ -0,0 +1,200 @@
+/**
+ * Social sharing for a public topic link.
+ *
+ * Every channel is built from the same {@link composeShareCopy} skeleton
+ * (title — description · via LobeHub · link), so a post reads the same and
+ * points at the same `/share/t/<id>` link whichever platform it lands on.
+ *
+ * - X (Twitter) and Weibo have web share intents: we open them in a new window.
+ * - Instagram has no web intent and no prefill: we hand the text to the system
+ * share sheet when there is one (mobile), otherwise copy it to the clipboard.
+ * - WeChat Moments can only be reached from the WeChat app: we render the link
+ * as a QR code to scan, next to a copy action.
+ */
+
+export type SocialPlatform = 'x' | 'weibo' | 'instagram' | 'wechat';
+
+export const SOCIAL_PLATFORMS: SocialPlatform[] = ['x', 'weibo', 'instagram', 'wechat'];
+
+/** Identifies LobeHub as the source on every channel. */
+export const SHARE_SIGNATURE = 'via LobeHub';
+
+export const TWITTER_INTENT_URL = 'https://twitter.com/intent/tweet';
+export const WEIBO_SHARE_URL = 'https://service.weibo.com/share/share.php';
+export const INSTAGRAM_URL = 'https://www.instagram.com/';
+
+/** X caps a post at 280 weighted characters; every link counts as 23. */
+export const TWITTER_MAX_WEIGHT = 280;
+export const TWITTER_URL_WEIGHT = 23;
+
+export interface SocialShareInput {
+ description?: string;
+ title: string;
+ /** Public link of the shared content, e.g. `https://app.lobehub.com/share/t/<id>`. */
+ url: string;
+}
+
+export interface ShareCopy {
+ /** `title — description via LobeHub`, without the link (intents take the link separately). */
+ text: string;
+ /** {@link text} followed by the link on its own line, for clipboard / QR fallbacks. */
+ textWithUrl: string;
+ url: string;
+}
+
+const clean = (value?: string) => (value ?? '').replaceAll(/\s+/g, ' ').trim();
+
+const joinText = (title: string, description: string) =>
+ [[title, description].filter(Boolean).join(' — '), SHARE_SIGNATURE].filter(Boolean).join(' ');
+
+export const composeShareCopy = ({ url, title, description }: SocialShareInput): ShareCopy => {
+ const text = joinText(clean(title), clean(description));
+
+ return { text, textWithUrl: `${text}\n${url}`, url };
+};
+
+/**
+ * Weight of one code point in X's counting: Latin and common punctuation count
+ * 1, everything else (CJK, emoji…) counts 2. Mirrors twitter-text's v3 config.
+ */
+const codePointWeight = (cp: number) =>
+ cp <= 4351 ||
+ (cp >= 8192 && cp <= 8205) ||
+ (cp >= 8208 && cp <= 8223) ||
+ (cp >= 8242 && cp <= 8247)
+ ? 1
+ : 2;
+
+export const twitterTextWeight = (text: string) =>
+ [...text].reduce((sum, char) => sum + codePointWeight(char.codePointAt(0)!), 0);
+
+const ELLIPSIS = '…';
+
+const truncateToWeight = (text: string, maxWeight: number) => {
+ if (twitterTextWeight(text) <= maxWeight) return text;
+
+ // Reserve the ellipsis at its real weight: X counts U+2026 as 2, not 1.
+ let weight = twitterTextWeight(ELLIPSIS);
+ let result = '';
+ for (const char of text) {
+ const next = weight + codePointWeight(char.codePointAt(0)!);
+ if (next > maxWeight) break;
+ weight = next;
+ result += char;
+ }
+
+ return `${result.trimEnd()}${ELLIPSIS}`;
+};
+
+/**
+ * Text for an X post that fits next to the link. The title / description are
+ * shortened first so the signature always survives.
+ */
+export const buildTwitterText = (input: SocialShareInput) => {
+ const { text } = composeShareCopy(input);
+ // Link plus the space X puts in front of it.
+ const budget = TWITTER_MAX_WEIGHT - TWITTER_URL_WEIGHT - 1;
+ if (twitterTextWeight(text) <= budget) return text;
+
+ const head = [clean(input.title), clean(input.description)].filter(Boolean).join(' — ');
+ const suffix = ` ${SHARE_SIGNATURE}`;
+
+ return `${truncateToWeight(head, budget - twitterTextWeight(suffix))}${suffix}`;
+};
+
+/**
+ * Percent-encodes every value with `encodeURIComponent`. `URLSearchParams`
+ * would write spaces as `+`, which Weibo's share page shows literally.
+ */
+const toQuery = (params: Record<string, string>) =>
+ Object.entries(params)
+ .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
+ .join('&');
+
+export const buildTwitterShareUrl = (input: SocialShareInput) =>
+ `${TWITTER_INTENT_URL}?${toQuery({ text: buildTwitterText(input), url: input.url })}`;
+
+export const buildWeiboShareUrl = (input: SocialShareInput) => {
+ const { text } = composeShareCopy(input);
+
+ return `${WEIBO_SHARE_URL}?${toQuery({ title: text, url: input.url })}`;
+};
+
+export interface IntentShareAction<P extends 'x' | 'weibo'> {
+ href: string;
+ kind: 'intent';
+ platform: P;
+}
+
+export interface ClipboardShareAction {
+ copy: ShareCopy;
+ kind: 'clipboard';
+ openUrl: string;
+ platform: 'instagram';
+}
+
+export interface QrCodeShareAction {
+ copy: ShareCopy;
+ kind: 'qrcode';
+ platform: 'wechat';
+ qrValue: string;
+}
+
+export interface SocialShareActions {
+ instagram: ClipboardShareAction;
+ wechat: QrCodeShareAction;
+ weibo: IntentShareAction<'weibo'>;
+ x: IntentShareAction<'x'>;
+}
+
+export type SocialShareAction = SocialShareActions[SocialPlatform];
+
+/** One action per platform, all built from the same link and copy. */
+export const buildSocialShareActions = (input: SocialShareInput): SocialShareActions => {
+ const copy = composeShareCopy(input);
+
+ return {
+ instagram: { copy, kind: 'clipboard', openUrl: INSTAGRAM_URL, platform: 'instagram' },
+ wechat: { copy, kind: 'qrcode', platform: 'wechat', qrValue: input.url },
+ weibo: { href: buildWeiboShareUrl(input), kind: 'intent', platform: 'weibo' },
+ x: { href: buildTwitterShareUrl(input), kind: 'intent', platform: 'x' },
+ };
+};
+
+const SHARE_WINDOW_FEATURES = 'noopener,noreferrer,width=600,height=640';
+
+/** Opens a share intent in a new window without handing it `window.opener`. */
+export const openShareWindow = (href: string, win: Pick<Window, 'open'> = window) =>
+ win.open(href, '_blank', SHARE_WINDOW_FEATURES);
+
+export type InstagramShareResult = 'native' | 'copied' | 'cancelled';
+
+interface InstagramShareDeps {
+ copy: (text: string) => Promise<void>;
+ navigator?: Partial<Pick<Navigator, 'share' | 'canShare'>>;
+}
+
+/**
+ * Instagram cannot be prefilled from the web. Hand the post to the system share
+ * sheet when the device has one (Instagram is a target there on mobile);
+ * otherwise put the text on the clipboard for the user to paste.
+ */
+export const shareToInstagram = async (
+ copy: ShareCopy,
+ { copy: writeClipboard, navigator: nav }: InstagramShareDeps,
+): Promise<InstagramShareResult> => {
+ const data: ShareData = { text: copy.textWithUrl };
+
+ if (nav?.share && (!nav.canShare || nav.canShare(data))) {
+ try {
+ await nav.share(data);
+ return 'native';
+ } catch (error) {
+ // Dismissing the sheet is a choice, not a failure.
+ if ((error as DOMException)?.name === 'AbortError') return 'cancelled';
+ }
+ }
+
+ await writeClipboard(copy.textWithUrl);
+ return 'copied';
+};
diff --git a/src/features/SocialShare/style.ts b/src/features/SocialShare/style.ts
new file mode 100644
index 00000000000..1fbfbeedcbe
--- /dev/null
+++ b/src/features/SocialShare/style.ts
@@ -0,0 +1,100 @@
+// oxlint-disable-next-line stylex-migration/no-emotion-styles -- moved verbatim from SharePopover/style.ts; the tile's nested :hover/:disabled span selectors have no StyleX form yet
+import { createStaticStyles } from '@lobehub/ui';
+
+export const styles = createStaticStyles(({ css, cssVar }) => ({
+ qrcode: css`
+ flex: none;
+ padding: 6px;
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorWhite};
+ `,
+ socialGrid: css`
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ gap: 6px;
+ `,
+ socialIcon: css`
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ socialLabel: css`
+ overflow: hidden;
+
+ max-width: 100%;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ socialPanel: css`
+ padding: 12px;
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ socialPreview: css`
+ padding-block: 6px;
+ padding-inline: 8px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusSM};
+
+ font-size: 12px;
+ line-height: 1.5;
+ color: ${cssVar.colorText};
+ word-break: break-all;
+ white-space: pre-wrap;
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ socialTile: css`
+ cursor: pointer;
+
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ align-items: center;
+ justify-content: center;
+
+ min-width: 0;
+ min-height: 56px;
+ padding: 6px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadius};
+
+ font: inherit;
+
+ background: transparent;
+
+ transition:
+ background 150ms ${cssVar.motionEaseOut},
+ border-color 150ms ${cssVar.motionEaseOut};
+
+ &:hover:not(:disabled) {
+ background: ${cssVar.colorFillTertiary};
+ }
+
+ &:hover:not(:disabled) span {
+ color: ${cssVar.colorText};
+ }
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimaryBorder};
+ outline-offset: -2px;
+ }
+
+ &:disabled {
+ cursor: not-allowed;
+ opacity: 0.45;
+ }
+ `,
+ socialTileActive: css`
+ border-color: ${cssVar.colorPrimaryBorder};
+ background: ${cssVar.colorPrimaryBg};
+
+ span {
+ color: ${cssVar.colorPrimaryText};
+ }
+ `,
+}));
diff --git a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/ActionButtons.tsx b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/ActionButtons.tsx
index 83db2fb1b03..f71e2471cbd 100644
--- a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/ActionButtons.tsx
+++ b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/ActionButtons.tsx
@@ -2,7 +2,7 @@
import { type ActionIconGroupProps, type ActionIconProps } from '@lobehub/ui';
import { ActionIconGroup } from '@lobehub/ui';
-import { Dices, Download, Trash2 } from 'lucide-react';
+import { Dices, Download, Share2, Trash2 } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -18,11 +18,12 @@ export const ActionButtons = memo<ActionButtonsProps>(
onDelete,
onDownload,
onCopySeed,
+ onShare,
showDownload = false,
showCopySeed = false,
seedTooltip,
}) => {
- const { t } = useTranslation('image');
+ const { t } = useTranslation(['image', 'chat']);
return (
<ActionIconGroup
@@ -39,6 +40,12 @@ export const ActionButtons = memo<ActionButtonsProps>(
label: t('generation.actions.download'),
onClick: onDownload,
},
+ Boolean(onShare) && {
+ icon: Share2,
+ key: 'share',
+ label: t('shareModal.generation.entry', { ns: 'chat' }),
+ onClick: onShare,
+ },
Boolean(showCopySeed && onCopySeed) && {
icon: Dices,
key: 'copySeed',
@@ -53,7 +60,7 @@ export const ActionButtons = memo<ActionButtonsProps>(
onClick: onDelete,
},
].filter(Boolean) as ActionIconGroupProps['items'],
- [showDownload, onDownload, showCopySeed, onCopySeed, seedTooltip, onDelete],
+ [showDownload, onDownload, onShare, showCopySeed, onCopySeed, seedTooltip, onDelete, t],
)}
/>
);
diff --git a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/SuccessState.tsx b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/SuccessState.tsx
index 9fdc0b82d8d..c6bb3fb8b8a 100644
--- a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/SuccessState.tsx
+++ b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/SuccessState.tsx
@@ -20,6 +20,7 @@ export const SuccessState = memo<SuccessStateProps>(
onDelete,
onDownload,
onCopySeed,
+ onShare,
seedTooltip,
}) => {
return (
@@ -49,6 +50,7 @@ export const SuccessState = memo<SuccessStateProps>(
onCopySeed={onCopySeed}
onDelete={onDelete}
onDownload={onDownload}
+ onShare={onShare}
/>
</Block>
);
diff --git a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/index.tsx b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/index.tsx
index 5f1a41e50f4..118c6cea5ba 100644
--- a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/index.tsx
+++ b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/index.tsx
@@ -5,6 +5,7 @@ import dayjs from 'dayjs';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
+import { openGenerationShareModal, useCanShareGeneration } from '@/features/GenerationShareModal';
import { useDownloadImage } from '@/hooks/useDownloadImage';
import { useImageStore } from '@/store/image';
import { imageGenerationConfigSelectors } from '@/store/image/selectors';
@@ -86,6 +87,12 @@ export const GenerationItem = memo<GenerationItemProps>(
}
}, [generation.seed, isSupportSeed, t, reuseSeed]);
+ const canShare = useCanShareGeneration(generation.fileId, generationBatch.creator?.id);
+ const handleShare = useCallback(() => {
+ if (!generation.fileId) return;
+ openGenerationShareModal({ fileId: generation.fileId, prompt, type: 'image' });
+ }, [generation.fileId, prompt]);
+
const handleCopyError = useCallback(async () => {
if (!generation.task.error) return;
@@ -119,6 +126,7 @@ export const GenerationItem = memo<GenerationItemProps>(
onCopySeed={handleCopySeed}
onDelete={handleDeleteGeneration}
onDownload={handleDownloadImage}
+ onShare={canShare ? handleShare : undefined}
/>
);
}
diff --git a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/types.ts b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/types.ts
index 2f8e61991e1..63adbd130be 100644
--- a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/types.ts
+++ b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/types.ts
@@ -10,6 +10,8 @@ export interface ActionButtonsProps {
onCopySeed?: () => void;
onDelete: () => void;
onDownload?: () => void;
+ /** Opens the share panel; the item is left out when absent. */
+ onShare?: () => void;
seedTooltip?: string;
showCopySeed?: boolean;
showDownload?: boolean;
@@ -22,6 +24,7 @@ export interface SuccessStateProps {
onCopySeed?: () => void;
onDelete: () => void;
onDownload: () => void;
+ onShare?: () => void;
prompt: string;
seedTooltip?: string;
}
diff --git a/src/routes/(main)/(create)/music/features/GenerationFeed/BatchItem.test.tsx b/src/routes/(main)/(create)/music/features/GenerationFeed/BatchItem.test.tsx
index b770b2c613c..ff0c4ca6555 100644
--- a/src/routes/(main)/(create)/music/features/GenerationFeed/BatchItem.test.tsx
+++ b/src/routes/(main)/(create)/music/features/GenerationFeed/BatchItem.test.tsx
@@ -34,6 +34,11 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
vi.mock('@/components/LobeIcons', () => ({ ModelIcon: () => null }));
+vi.mock('@/features/GenerationShareModal', () => ({
+ openGenerationShareModal: vi.fn(),
+ useCanShareGeneration: () => false,
+}));
+
vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
useWorkspaceAwareNavigate: () => navigate,
}));
diff --git a/src/routes/(main)/(create)/music/features/GenerationFeed/MusicTrackItem.tsx b/src/routes/(main)/(create)/music/features/GenerationFeed/MusicTrackItem.tsx
index 2599aaeada6..568122de11e 100644
--- a/src/routes/(main)/(create)/music/features/GenerationFeed/MusicTrackItem.tsx
+++ b/src/routes/(main)/(create)/music/features/GenerationFeed/MusicTrackItem.tsx
@@ -4,7 +4,7 @@ import type { MusicGenerationAsset } from '@lobechat/types';
import { ActionIcon, Block, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
import * as stylex from '@stylexjs/stylex';
-import { MusicIcon, Trash2Icon } from 'lucide-react';
+import { MusicIcon, Share2Icon, Trash2Icon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -39,12 +39,14 @@ interface MusicTrackItemProps {
downloadFileName: string;
generationId: string;
onDelete: () => void;
+ /** Opens the share panel; no share button when absent. */
+ onShare?: () => void;
title: string;
}
const MusicTrackItem = memo<MusicTrackItemProps>(
- ({ asset, downloadFileName, generationId, onDelete, title }) => {
- const { t } = useTranslation('music');
+ ({ asset, downloadFileName, generationId, onDelete, onShare, title }) => {
+ const { t } = useTranslation(['music', 'chat']);
const duration = formatSongDuration(asset.duration);
return (
@@ -90,6 +92,15 @@ const MusicTrackItem = memo<MusicTrackItemProps>(
url={asset.url!}
/>
</Flexbox>
+ {onShare && (
+ <ActionIcon
+ icon={Share2Icon}
+ size={'small'}
+ style={{ flex: 'none' }}
+ title={t('shareModal.generation.entry', { ns: 'chat' })}
+ onClick={onShare}
+ />
+ )}
<ActionIcon
icon={Trash2Icon}
size={'small'}
diff --git a/src/routes/(main)/(create)/music/features/GenerationFeed/SongItem.tsx b/src/routes/(main)/(create)/music/features/GenerationFeed/SongItem.tsx
index 925dc67b010..15fc2996212 100644
--- a/src/routes/(main)/(create)/music/features/GenerationFeed/SongItem.tsx
+++ b/src/routes/(main)/(create)/music/features/GenerationFeed/SongItem.tsx
@@ -4,6 +4,7 @@ import { toast } from '@lobehub/ui';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
+import { openGenerationShareModal, useCanShareGeneration } from '@/features/GenerationShareModal';
import { useMusicStore } from '@/store/music';
import { createMusicSelectors } from '@/store/music/selectors';
import { AsyncTaskStatus } from '@/types/asyncTask';
@@ -66,6 +67,8 @@ const SongItem = memo<SongItemProps>(({ batch, generation, index, topicId }) =>
}, [generation.task.error, t]);
const asset = getMusicAsset(generation);
+ const { fileId } = generation;
+ const canShare = useCanShareGeneration(fileId, batch.creator?.id);
if (status === AsyncTaskStatus.Success && asset?.url) {
const config = batch.config as { title?: string | null } | undefined;
@@ -84,6 +87,17 @@ const SongItem = memo<SongItemProps>(({ batch, generation, index, topicId }) =>
index,
})}
onDelete={handleDelete}
+ onShare={
+ canShare && fileId
+ ? () =>
+ openGenerationShareModal({
+ fileId,
+ prompt: batch.prompt,
+ title: asset.title || config?.title || undefined,
+ type: 'music',
+ })
+ : undefined
+ }
/>
);
}
diff --git a/src/routes/(main)/(create)/video/features/GenerationFeed/BatchItem.tsx b/src/routes/(main)/(create)/video/features/GenerationFeed/BatchItem.tsx
index 0c5dfc80a5a..adcb0337b22 100644
--- a/src/routes/(main)/(create)/video/features/GenerationFeed/BatchItem.tsx
+++ b/src/routes/(main)/(create)/video/features/GenerationFeed/BatchItem.tsx
@@ -21,6 +21,7 @@ import { useTranslation } from 'react-i18next';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import useRenderBusinessVideoBatchItem from '@/business/client/hooks/useRenderBusinessVideoBatchItem';
import { ModelIcon } from '@/components/LobeIcons';
+import { openGenerationShareModal, useCanShareGeneration } from '@/features/GenerationShareModal';
import { GenerationInvalidAPIKey } from '@/routes/(main)/(create)/features/GenerationInput';
import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
import { useVideoStore } from '@/store/video';
@@ -192,6 +193,16 @@ export const VideoGenerationBatchItem = memo<VideoGenerationBatchItemProps>(
}
}, [generation?.asset?.url, generation?.createdAt, batch.prompt]);
+ const canShare = useCanShareGeneration(generation?.fileId, batch.creator?.id);
+ const handleShare = useCallback(() => {
+ if (!generation?.fileId) return;
+ openGenerationShareModal({
+ fileId: generation.fileId,
+ prompt: batch.prompt,
+ type: 'video',
+ });
+ }, [batch.prompt, generation]);
+
const handleCopyError = useCallback(async () => {
if (!generation?.task.error) return;
@@ -254,6 +265,7 @@ export const VideoGenerationBatchItem = memo<VideoGenerationBatchItemProps>(
isEditing={isEditingSource}
onDelete={handleDelete}
onDownload={handleDownload}
+ onShare={canShare ? handleShare : undefined}
/>
);
}
diff --git a/src/routes/(main)/(create)/video/features/GenerationFeed/VideoSuccessItem.tsx b/src/routes/(main)/(create)/video/features/GenerationFeed/VideoSuccessItem.tsx
index e4d60d2f8a0..ea92fd452ad 100644
--- a/src/routes/(main)/(create)/video/features/GenerationFeed/VideoSuccessItem.tsx
+++ b/src/routes/(main)/(create)/video/features/GenerationFeed/VideoSuccessItem.tsx
@@ -43,10 +43,11 @@ interface VideoSuccessItemProps {
isEditing?: boolean;
onDelete: () => void;
onDownload: () => void;
+ onShare?: () => void;
}
const VideoSuccessItem = memo<VideoSuccessItemProps>(
- ({ generation, isEditing, onDelete, onDownload }) => {
+ ({ generation, isEditing, onDelete, onDownload, onShare }) => {
const { t } = useTranslation('video');
const asset = generation.asset as VideoGenerationAsset;
@@ -70,7 +71,7 @@ const VideoSuccessItem = memo<VideoSuccessItemProps>(
{t('generation.editing.badge')}
</div>
)}
- <ActionButtons showDownload onDelete={onDelete} onDownload={onDownload} />
+ <ActionButtons showDownload onDelete={onDelete} onDownload={onDownload} onShare={onShare} />
</Block>
);
},
diff --git a/src/routes/(main)/agent/profile/features/Header/AgentSocialShare.test.ts b/src/routes/(main)/agent/profile/features/Header/AgentSocialShare.test.ts
new file mode 100644
index 00000000000..b8ffb3a707d
--- /dev/null
+++ b/src/routes/(main)/agent/profile/features/Header/AgentSocialShare.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+
+import { getAgentPublicUrl } from './AgentSocialShare';
+
+describe('getAgentPublicUrl', () => {
+ it('points a published listing at its Community page', () => {
+ expect(getAgentPublicUrl('my-agent', 'published')).toBe('https://lobehub.com/agent/my-agent');
+ });
+
+ it.each(['unpublished', 'archived', 'deprecated', null])(
+ 'has no public link while the listing is %s',
+ (status) => {
+ expect(getAgentPublicUrl('my-agent', status)).toBeUndefined();
+ },
+ );
+
+ it('has no public link without a Market identifier', () => {
+ expect(getAgentPublicUrl(undefined, 'published')).toBeUndefined();
+ });
+});
diff --git a/src/routes/(main)/agent/profile/features/Header/AgentSocialShare.tsx b/src/routes/(main)/agent/profile/features/Header/AgentSocialShare.tsx
new file mode 100644
index 00000000000..5f2a742fcd9
--- /dev/null
+++ b/src/routes/(main)/agent/profile/features/Header/AgentSocialShare.tsx
@@ -0,0 +1,72 @@
+'use client';
+
+import { ActionIcon, Popover } from '@lobehub/ui';
+import { MegaphoneIcon } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import urlJoin from 'url-join';
+
+import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
+import { AGENTS_OFFICIAL_URL } from '@/const/url';
+import SocialShare from '@/features/SocialShare';
+import { useIsMobile } from '@/hooks/useIsMobile';
+import { useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+
+import { useAgentMarketTags } from './useAgentMarketTags';
+
+/**
+ * The public link of an agent is its Community page. Only a published listing
+ * has one: an unpublished, archived or deprecated listing would 404 for the
+ * people the post reaches.
+ */
+export const getAgentPublicUrl = (
+ marketIdentifier: string | undefined,
+ status: string | null,
+): string | undefined =>
+ marketIdentifier && status === 'published'
+ ? urlJoin(AGENTS_OFFICIAL_URL, marketIdentifier)
+ : undefined;
+
+/** Header entry that posts the current agent's Community page to social media. */
+const AgentSocialShare = memo(() => {
+ const { t } = useTranslation('chat');
+ const isMobile = useIsMobile();
+ const [open, setOpen] = useState(false);
+ const meta = useAgentStore(agentSelectors.currentAgentMeta);
+ const { status } = useAgentMarketTags();
+
+ const shareUrl = getAgentPublicUrl(meta?.marketIdentifier, status);
+
+ return (
+ <Popover
+ arrow={false}
+ open={open}
+ placement={isMobile ? 'top' : 'bottomRight'}
+ styles={{ content: { padding: 0, width: isMobile ? '100vw' : 340 } }}
+ trigger={['click']}
+ content={
+ <SocialShare
+ description={meta?.description || t('shareModal.social.agent.description')}
+ disabledHint={t('shareModal.social.agent.disabledHint')}
+ shareUrl={shareUrl}
+ style={{ padding: 12 }}
+ title={meta?.title || t('shareModal.social.agent.untitled')}
+ onLeave={() => setOpen(false)}
+ />
+ }
+ onOpenChange={setOpen}
+ >
+ <ActionIcon
+ icon={MegaphoneIcon}
+ size={DESKTOP_HEADER_ICON_SMALL_SIZE}
+ title={t('shareModal.social.agent.entry')}
+ tooltipProps={{ placement: 'bottom' }}
+ />
+ </Popover>
+ );
+});
+
+AgentSocialShare.displayName = 'AgentSocialShare';
+
+export default AgentSocialShare;
diff --git a/src/routes/(main)/agent/profile/features/Header/index.tsx b/src/routes/(main)/agent/profile/features/Header/index.tsx
index c0640cbf786..cd78beaecf4 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.tsx
@@ -56,6 +56,7 @@ import { sanitizeFileName } from '@/utils/sanitizeFileName';
import { openAgentSettingsModal } from '../AgentSettings';
import { selectors as profileSelectors, useProfileStore } from '../store';
import AgentForkTag from './AgentForkTag';
+import AgentSocialShare from './AgentSocialShare';
import AgentVersionReviewTag from './AgentVersionReviewTag';
type HeaderTranslation = TFunction<
@@ -436,6 +437,8 @@ const Header = memo<HeaderProps>(({ active = 'profile' }) => {
}
right={
<Flexbox horizontal align={'center'} gap={4}>
+ {/* Posts the agent's public Community page; disabled until it is published. */}
+ {showMarketSubmission && <AgentSocialShare />}
{canShareAgent && (
<ActionIcon
icon={Share2Icon}
diff --git a/src/routes/(main)/community/(detail)/features/ShareButton.tsx b/src/routes/(main)/community/(detail)/features/ShareButton.tsx
index ecb4fc9fb2a..b04b1dcb825 100644
--- a/src/routes/(main)/community/(detail)/features/ShareButton.tsx
+++ b/src/routes/(main)/community/(detail)/features/ShareButton.tsx
@@ -22,6 +22,7 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import ImperativeModal from '@/components/ImperativeModal';
+import SocialShare from '@/features/SocialShare';
import { useShare } from '@/hooks/useShare';
import CardBanner from '../../components/CardBanner';
@@ -73,7 +74,8 @@ const fallback = createStaticStyles(({ css }) => ({
}));
const ShareButton = memo<ShareButtonProps>(({ meta, ...rest }) => {
- const { x, reddit, telegram, whatsapp, mastodon, weibo } = useShare({
+ // X and Weibo go through the four-channel SocialShare above; these are the extras.
+ const { reddit, telegram, whatsapp, mastodon } = useShare({
avatar: '',
desc: '',
hashtags: [],
@@ -119,8 +121,15 @@ const ShareButton = memo<ShareButtonProps>(({ meta, ...rest }) => {
{meta.tags}
</Center>
</Flexbox>
+ <SocialShare
+ description={meta.desc}
+ shareUrl={meta.url}
+ style={{ width: '100%' }}
+ title={meta.title || meta.url}
+ onLeave={() => setOpen(false)}
+ />
<Flexbox horizontal align={'center'} gap={8} justify={'center'} wrap={'wrap'}>
- {[x, reddit, telegram, whatsapp, mastodon, weibo].map(
+ {[reddit, telegram, whatsapp, mastodon].map(
(item) =>
item.icon && (
<a href={item.link} key={item.title} rel="noreferrer" target="_blank">
@@ -153,6 +162,7 @@ const ShareButton = memo<ShareButtonProps>(({ meta, ...rest }) => {
return (
<>
<Button
+ aria-label={t('share')}
icon={<Icon icon={Share2Icon} />}
size={'large'}
onClick={() => setOpen(true)}