Skip to content

Commit 77744e2

Browse files
committed
size codeblock for lazy loading
1 parent 151d6ee commit 77744e2

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

src/theme/CodeBlock/index.js

+10-2
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,16 @@ import React, {useState, useRef, useCallback, useEffect} from 'react';
22
import CodeBlock from '@theme-original/CodeBlock';
33
import styles from './styles.module.css';
44

5+
function countLines(text) {
6+
// Split the string by newline characters
7+
const lines = text.split('\n');
8+
// Return the number of lines
9+
return lines.length;
10+
}
511
export default function CodeBlockWrapper(props) {
12+
const lineHeight = 18.85;
613
const [isLoaded, setIsLoaded] = useState(false);
14+
const [estimatedHeight, setEstimatedHeight] = useState(countLines(props.children)*lineHeight);
715
const codeBlockRef = useRef(null);
816

917
const handleIntersection = useCallback((entries) => {
@@ -15,7 +23,7 @@ export default function CodeBlockWrapper(props) {
1523

1624
useEffect(() => {
1725
const observer = new IntersectionObserver(handleIntersection, {
18-
rootMargin: '0px 0px',
26+
rootMargin: '200px 0px',
1927
});
2028

2129
const currentRef = codeBlockRef.current; // Store current ref value
@@ -33,7 +41,7 @@ export default function CodeBlockWrapper(props) {
3341

3442
if (!isLoaded) {
3543
return (
36-
<div ref={codeBlockRef} className={styles.wrapper}>
44+
<div ref={codeBlockRef} className={styles.wrapper} style={{ height: estimatedHeight + 'px' }}>
3745
<div className={styles.activity}></div>
3846
</div>
3947
);

src/theme/CodeBlock/styles.module.css

-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
.wrapper {
22
position: relative;
3-
height: 100px;
43
width: 100%;
54
z-index: 44;
65
overflow: hidden;

0 commit comments

Comments
 (0)