From 0337629d7577bbda53209d2592b90bfff1e1887d Mon Sep 17 00:00:00 2001 From: fantasticit Date: Wed, 13 Apr 2022 20:30:03 +0800 Subject: [PATCH] feat: use lazyload image --- .../src/tiptap/wrappers/image/index.tsx | 33 ++++++++++++------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/packages/client/src/tiptap/wrappers/image/index.tsx b/packages/client/src/tiptap/wrappers/image/index.tsx index f093edbe..84a089fa 100644 --- a/packages/client/src/tiptap/wrappers/image/index.tsx +++ b/packages/client/src/tiptap/wrappers/image/index.tsx @@ -1,7 +1,8 @@ +import Image from 'next/image'; +import cls from 'classnames'; +import { useCallback, useEffect, useMemo, useRef } from 'react'; import { NodeViewWrapper, NodeViewContent } from '@tiptap/react'; import { Resizeable } from 'components/resizeable'; -import { useEffect, useRef } from 'react'; -import cls from 'classnames'; import { Typography, Spin } from '@douyinfe/semi-ui'; import { useToggle } from 'hooks/use-toggle'; import { uploadFile } from 'services/file'; @@ -10,30 +11,35 @@ import styles from './index.module.scss'; const { Text } = Typography; +const isNumber = (v) => typeof v === 'number'; + export const ImageWrapper = ({ editor, node, updateAttributes }) => { const isEditable = editor.isEditable; const { hasTrigger, error, src, alt, title, width, height, textAlign } = node.attrs; const $upload = useRef(); const [loading, toggleLoading] = useToggle(false); - const onResize = (size) => { + const onResize = useCallback((size) => { updateAttributes({ height: size.height, width: size.width }); - }; + }, []); - const selectFile = () => { + const selectFile = useCallback(() => { if (!isEditable || error || src) return; isEditable && $upload.current.click(); - }; + }, [isEditable, error, src]); - const handleFile = async (e) => { + const handleFile = useCallback(async (e) => { const file = e.target.files && e.target.files[0]; + const fileInfo = { fileName: extractFilename(file.name), fileSize: file.size, fileType: file.type, fileExt: extractFileExtension(file.name), }; + toggleLoading(true); + try { const src = await uploadFile(file); const size = await getImageWidthHeight(file); @@ -43,7 +49,7 @@ export const ImageWrapper = ({ editor, node, updateAttributes }) => { updateAttributes({ error: '图片上传失败:' + (error && error.message) || '未知错误' }); toggleLoading(false); } - }; + }, []); useEffect(() => { if (!src && !hasTrigger) { @@ -52,7 +58,7 @@ export const ImageWrapper = ({ editor, node, updateAttributes }) => { } }, [src, hasTrigger]); - const content = (() => { + const content = useMemo(() => { if (error) { return (
@@ -72,7 +78,12 @@ export const ImageWrapper = ({ editor, node, updateAttributes }) => { ); } - const img = {alt}; + const img = + isNumber(width) && isNumber(height) ? ( + {alt} + ) : ( + {alt} + ); if (isEditable) { return ( @@ -87,7 +98,7 @@ export const ImageWrapper = ({ editor, node, updateAttributes }) => { {img}
); - })(); + }, [error, src, isEditable]); return (