1
- import React , { useState , useEffect } from 'react' ;
1
+ import React , { useState , useEffect , useMemo } from 'react' ;
2
2
import styled from 'styled-components' ;
3
3
import MarkdownRender from '../common/MarkdownRender' ;
4
4
import PostHtmlContent from './PostHtmlContent' ;
@@ -24,19 +24,40 @@ export interface PostContentProps {
24
24
body : string ;
25
25
}
26
26
27
+ function optimizeImagesFromPost ( markdown : string ) {
28
+ const matches = markdown . match (
29
+ / (?: ! \[ ( .* ?) \] \( h t t p s : \/ \/ i m a g e s .v e l o g .i o \/ ( .* ?) \) ) / g,
30
+ ) ;
31
+ if ( ! matches ) return markdown ;
32
+ const replacers = matches . map ( match => [
33
+ match ,
34
+ match . replace ( 'https://images.' , 'https://img.' ) . replace ( / \) $ / , '?w=1024)' ) ,
35
+ ] ) ;
36
+ return replacers . reduce ( ( acc , [ original , optimized ] ) => {
37
+ return acc . replace ( original , optimized ) ;
38
+ } , markdown ) ;
39
+ }
40
+
27
41
const PostContent : React . FC < PostContentProps > = ( { isMarkdown, body } ) => {
28
42
const [ html , setHtml ] = useState ( isMarkdown ? null : body ) ;
29
43
const dispatch = usePostViewerDispatch ( ) ;
44
+ const imageOptimizedPost = useMemo ( ( ) => optimizeImagesFromPost ( body ) , [
45
+ body ,
46
+ ] ) ;
30
47
31
48
useEffect ( ( ) => {
32
49
if ( ! html ) return ;
33
50
const toc = parseHeadings ( html ) ;
34
51
dispatch ( { type : 'SET_TOC' , payload : toc } ) ;
35
52
} , [ dispatch , html ] ) ;
53
+
36
54
return (
37
55
< PostContentBlock >
38
56
{ isMarkdown ? (
39
- < MarkdownRender markdown = { body } onConvertFinish = { setHtml } />
57
+ < MarkdownRender
58
+ markdown = { imageOptimizedPost }
59
+ onConvertFinish = { setHtml }
60
+ />
40
61
) : (
41
62
< PostHtmlContent html = { body } />
42
63
) }
0 commit comments