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.

⚡️ perf: improve Chat Screenshot and fix image geneartion (#10261)

René Wanga5bb31b844aa
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index ada76239e51..7a3bfffebf1 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -330,6 +330,11 @@
"screenshot": "Screenshot",
"settings": "Export Settings",
"text": "Text",
+ "widthMode": {
+ "label": "Width Mode",
+ "narrow": "Narrow",
+ "wide": "Wide"
+ },
"withBackground": "Include Background Image",
"withFooter": "Include Footer",
"withPluginInfo": "Include Plugin Information",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 62cbda0946a..07743e042c6 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -330,6 +330,11 @@
"screenshot": "截图",
"settings": "导出设置",
"text": "文本",
+ "widthMode": {
+ "label": "宽度模式",
+ "narrow": "窄屏模式",
+ "wide": "宽屏模式"
+ },
"withBackground": "包含背景图片",
"withFooter": "包含页脚",
"withPluginInfo": "包含插件信息",
diff --git a/package.json b/package.json
index cee3875eaf6..95f4dd8fe14 100644
--- a/package.json
+++ b/package.json
@@ -191,6 +191,7 @@
"@vercel/speed-insights": "^1.2.0",
"@virtuoso.dev/masonry": "^1.3.5",
"@xterm/xterm": "^5.5.0",
+ "@zumer/snapdom": "^1.9.14",
"ahooks": "^3.9.6",
"antd": "^5.28.1",
"antd-style": "^3.7.1",
@@ -228,7 +229,6 @@
"marked": "^16.4.2",
"mdast-util-to-markdown": "^2.1.2",
"model-bank": "workspace:*",
- "modern-screenshot": "^4.6.6",
"nanoid": "^5.1.6",
"next": "^16.0.3",
"next-auth": "5.0.0-beta.30",
diff --git a/src/features/Portal/Artifacts/Body/Renderer/SVG.tsx b/src/features/Portal/Artifacts/Body/Renderer/SVG.tsx
index 49c3114308a..25110cc329d 100644
--- a/src/features/Portal/Artifacts/Body/Renderer/SVG.tsx
+++ b/src/features/Portal/Artifacts/Body/Renderer/SVG.tsx
@@ -1,9 +1,9 @@
import { copyImageToClipboard, sanitizeSVGContent } from '@lobechat/utils/client';
import { Button, Dropdown, Tooltip } from '@lobehub/ui';
+import { snapdom } from '@zumer/snapdom';
import { App, Space } from 'antd';
import { css, cx } from 'antd-style';
import { CopyIcon, DownloadIcon } from 'lucide-react';
-import { domToPng } from 'modern-screenshot';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Center, Flexbox } from 'react-layout-kit';
@@ -41,12 +41,29 @@ const SVGRenderer = ({ content }: SVGRendererProps) => {
const sanitizedContent = useMemo(() => sanitizeSVGContent(content), [content]);
const generatePng = async () => {
- return domToPng(document.querySelector(`#${DOM_ID}`) as HTMLDivElement, {
- features: {
- // 不启用移除控制符,否则会导致 safari emoji 报错
- removeControlCharacter: false,
- },
+ const blob = await snapdom.toBlob(document.querySelector(`#${DOM_ID}`) as HTMLDivElement, {
scale: 2,
+ type: 'png',
+ });
+
+ if (!blob) {
+ throw new Error('Failed to generate PNG blob');
+ }
+
+ // Convert blob to data URL
+ return new Promise<string>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.addEventListener('load', () => {
+ if (typeof reader.result === 'string') {
+ resolve(reader.result);
+ } else {
+ reject(new Error('FileReader result is not a string'));
+ }
+ });
+ reader.addEventListener('error', () =>
+ reject(reader.error || new Error('Failed to read blob as data URL')),
+ );
+ reader.readAsDataURL(blob);
});
};
diff --git a/src/features/ShareModal/ShareImage/Preview.tsx b/src/features/ShareModal/ShareImage/Preview.tsx
index 977325c01e2..025ef349c81 100644
--- a/src/features/ShareModal/ShareImage/Preview.tsx
+++ b/src/features/ShareModal/ShareImage/Preview.tsx
@@ -19,7 +19,7 @@ import { useStyles } from './style';
import { FieldType } from './type';
const Preview = memo<FieldType & { title?: string }>(
- ({ title, withSystemRole, withBackground, withFooter }) => {
+ ({ title, withSystemRole, withBackground, withFooter, widthMode }) => {
const [model, plugins, systemRole] = useAgentStore((s) => [
agentSelectors.currentAgentModel(s),
agentSelectors.displayableAgentPlugins(s),
@@ -34,7 +34,7 @@ const Preview = memo<FieldType & { title?: string }>(
const { t } = useTranslation('chat');
const { styles } = useStyles(withBackground);
- const { styles: containerStyles } = useContainerStyles();
+ const { styles: containerStyles } = useContainerStyles(widthMode);
const displayTitle = isInbox ? t('inbox.title') : title;
const displayDesc = isInbox ? t('inbox.desc') : description;
diff --git a/src/features/ShareModal/ShareImage/index.tsx b/src/features/ShareModal/ShareImage/index.tsx
index 40c96b1887b..3be6715d7fe 100644
--- a/src/features/ShareModal/ShareImage/index.tsx
+++ b/src/features/ShareModal/ShareImage/index.tsx
@@ -14,10 +14,11 @@ import { sessionMetaSelectors } from '@/store/session/selectors';
import { useStyles } from '../style';
import Preview from './Preview';
-import { FieldType } from './type';
+import { FieldType, WidthMode } from './type';
const DEFAULT_FIELD_VALUE: FieldType = {
imageType: ImageType.JPG,
+ widthMode: WidthMode.Wide,
withBackground: true,
withFooter: true,
withPluginInfo: false,
@@ -34,7 +35,20 @@ const ShareImage = memo<{ mobile?: boolean }>(() => {
title: currentAgentTitle,
});
const { loading: copyLoading, onCopy } = useImgToClipboard();
+
+ const widthModeOptions = [
+ { label: t('shareModal.widthMode.wide'), value: WidthMode.Wide },
+ { label: t('shareModal.widthMode.narrow'), value: WidthMode.Narrow },
+ ];
+
const settings: FormItemProps[] = [
+ {
+ children: <Segmented options={widthModeOptions} />,
+ label: t('shareModal.widthMode.label'),
+ layout: 'horizontal',
+ minWidth: undefined,
+ name: 'widthMode',
+ },
{
children: <Switch />,
label: t('shareModal.withSystemRole'),
diff --git a/src/features/ShareModal/ShareImage/type.ts b/src/features/ShareModal/ShareImage/type.ts
index 4b3c0fb7514..c4c99f8472f 100644
--- a/src/features/ShareModal/ShareImage/type.ts
+++ b/src/features/ShareModal/ShareImage/type.ts
@@ -1,7 +1,13 @@
import { ImageType } from '@/hooks/useScreenshot';
+export enum WidthMode {
+ Narrow = 'narrow',
+ Wide = 'wide'
+}
+
export type FieldType = {
imageType: ImageType;
+ widthMode: WidthMode;
withBackground: boolean;
withFooter: boolean;
withPluginInfo: boolean;
diff --git a/src/features/ShareModal/style.ts b/src/features/ShareModal/style.ts
index b0b247b40cd..0ba099ef7de 100644
--- a/src/features/ShareModal/style.ts
+++ b/src/features/ShareModal/style.ts
@@ -1,36 +1,46 @@
import { createStyles } from 'antd-style';
-export const useContainerStyles = createStyles(({ css, token, stylish, cx, responsive }) => ({
- preview: cx(
- stylish.noScrollbar,
- css`
- overflow: hidden scroll;
+import { WidthMode } from './ShareImage/type';
- width: 100%;
- max-height: 70dvh;
- border: 1px solid ${token.colorBorder};
- border-radius: ${token.borderRadiusLG}px;
-
- background: ${token.colorBgLayout};
-
- /* stylelint-disable selector-class-pattern */
- .react-pdf__Document *,
- .react-pdf__Page * {
- pointer-events: none;
- }
- /* stylelint-enable selector-class-pattern */
-
- ::-webkit-scrollbar {
- width: 0 !important;
- height: 0 !important;
- }
-
- ${responsive.mobile} {
- max-height: 40dvh;
- }
- `,
- ),
-}));
+export const useContainerStyles = createStyles(
+ ({ css, token, stylish, cx, responsive }, widthMode?: WidthMode) => {
+ const isNarrow = widthMode === WidthMode.Narrow;
+
+ return {
+ preview: cx(
+ stylish.noScrollbar,
+ css`
+ overflow: hidden scroll;
+
+ width: 100%;
+ max-width: ${isNarrow ? '480px' : 'none'};
+ max-height: 70dvh;
+ margin: ${isNarrow ? '0 auto' : '0'};
+ border: 1px solid ${token.colorBorder};
+ border-radius: ${token.borderRadiusLG}px;
+
+ background: ${token.colorBgLayout};
+
+ /* stylelint-disable selector-class-pattern */
+ .react-pdf__Document *,
+ .react-pdf__Page * {
+ pointer-events: none;
+ }
+ /* stylelint-enable selector-class-pattern */
+
+ ::-webkit-scrollbar {
+ width: 0 !important;
+ height: 0 !important;
+ }
+
+ ${responsive.mobile} {
+ max-height: 40dvh;
+ }
+ `,
+ ),
+ };
+ },
+);
export const useStyles = createStyles(({ responsive, token, css }) => ({
body: css`
diff --git a/src/hooks/useScreenshot.ts b/src/hooks/useScreenshot.ts
index b2967f9bfe2..14d2c12188a 100644
--- a/src/hooks/useScreenshot.ts
+++ b/src/hooks/useScreenshot.ts
@@ -1,6 +1,6 @@
import type { SegmentedProps } from '@lobehub/ui';
+import { snapdom } from '@zumer/snapdom';
import dayjs from 'dayjs';
-import { domToJpeg, domToPng, domToSvg, domToWebp } from 'modern-screenshot';
import { useCallback, useState } from 'react';
import { BRANDING_NAME } from '@/const/branding';
@@ -40,26 +40,6 @@ export const getImageUrl = async ({
imageType: ImageType;
width?: number;
}) => {
- let screenshotFn: any;
- switch (imageType) {
- case ImageType.JPG: {
- screenshotFn = domToJpeg;
- break;
- }
- case ImageType.PNG: {
- screenshotFn = domToPng;
- break;
- }
- case ImageType.SVG: {
- screenshotFn = domToSvg;
- break;
- }
- case ImageType.WEBP: {
- screenshotFn = domToWebp;
- break;
- }
- }
-
const dom: HTMLDivElement = document.querySelector(id) as HTMLDivElement;
let copy: HTMLDivElement = dom;
@@ -69,18 +49,54 @@ export const getImageUrl = async ({
document.body.append(copy);
}
- const dataUrl = await screenshotFn(width ? copy : dom, {
- features: {
- // 不启用移除控制符,否则会导致 safari emoji 报错
- removeControlCharacter: false,
- },
+ const baseOptions = {
scale: 2,
width,
- });
+ };
+
+ let blob: Blob;
+
+ if (imageType === ImageType.SVG) {
+ // For SVG, we need to use the full snapdom API to get the raw SVG string
+ const result = await snapdom(width ? copy : dom, baseOptions);
+ const svgString = result.toRaw();
+ blob = new Blob([svgString], { type: 'image/svg+xml' });
+ } else {
+ // For raster formats, use toBlob directly with type option
+ const blobType = (imageType === ImageType.JPG ? 'jpg' : imageType) as 'png' | 'jpg' | 'webp';
+ const blobResult = await snapdom.toBlob(width ? copy : dom, {
+ type: blobType,
+ useProxy: 'https://proxy.corsfix.com/?',
+ });
+
+ if (!blobResult) {
+ throw new Error('Failed to generate blob from snapdom');
+ }
+
+ blob = blobResult;
+ }
if (width && copy) copy?.remove();
- return dataUrl;
+ if (!blob) {
+ throw new Error('Blob is undefined');
+ }
+
+ // Convert blob to data URL using FileReader
+ return new Promise<string>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.addEventListener('load', () => {
+ if (typeof reader.result === 'string') {
+ resolve(reader.result);
+ } else {
+ reject(new Error('FileReader result is not a string'));
+ }
+ });
+ reader.addEventListener('error', () =>
+ reject(reader.error || new Error('Failed to read blob as data URL')),
+ );
+ reader.readAsDataURL(blob);
+ });
};
export const useScreenshot = ({
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 3f634fe8b97..16e87089f05 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -361,6 +361,11 @@ export default {
screenshot: '截图',
settings: '导出设置',
text: '文本',
+ widthMode: {
+ label: '宽度模式',
+ narrow: '窄屏模式',
+ wide: '宽屏模式',
+ },
withBackground: '包含背景图片',
withFooter: '包含页脚',
withPluginInfo: '包含插件信息',