Skip to content

Commit

Permalink
Add throttle to prevent preview's indiscriminate updates
Browse files Browse the repository at this point in the history
  • Loading branch information
JOOHOJANG authored and devleejb committed Nov 3, 2024
1 parent 9e08612 commit db0f772
Showing 1 changed file with 23 additions and 11 deletions.
34 changes: 23 additions & 11 deletions frontend/src/components/editor/Preview.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { CircularProgress, Stack } from "@mui/material";
import "katex/dist/katex.min.css";
import { useEffect, useRef, useState } from "react";
import { useEffect, useRef, useState, useMemo } from "react";
import { useSelector } from "react-redux";
import { useCurrentTheme } from "../../hooks/useCurrentTheme";
import { selectEditor } from "../../store/editorSlice";
import { addSoftLineBreak } from "../../utils/document";
import MarkdownIt from "markdown-it";
import { toHtml } from "hast-util-to-html";
import markdownItKatex from "@vscode/markdown-it-katex";
Expand All @@ -18,6 +17,10 @@ import markdownItSanitizer from "markdown-it-sanitizer";
import * as IncrementalDOM from "incremental-dom";
import "./editor.css";
import "./preview.css";
import _ from "lodash";
import { addSoftLineBreak } from "../../utils/document";

const DELAY = 500;

const md = new MarkdownIt({
html: true,
Expand Down Expand Up @@ -46,27 +49,36 @@ const Preview = () => {
const editorStore = useSelector(selectEditor);
const [content, setContent] = useState("");
const containerRef = useRef<HTMLDivElement>(null);
const throttledUpdatePreviewConetent = useMemo(
() =>
_.throttle(
() => {
const editorText = editorStore.doc?.getRoot().content?.toString() || "";

// Add soft line break
setContent(addSoftLineBreak(editorText));
},
DELAY,
// Set trailing true to prevent ignoring last call
{ trailing: true }
),
[editorStore.doc]
);

useEffect(() => {
if (!editorStore.doc) return;

const updatePreviewContent = () => {
const editorText = editorStore.doc?.getRoot().content?.toString() || "";
// Add soft line break
setContent(addSoftLineBreak(editorText));
};

updatePreviewContent();
throttledUpdatePreviewConetent();

const unsubscribe = editorStore.doc.subscribe("$.content", () => {
updatePreviewContent();
throttledUpdatePreviewConetent();
});

return () => {
unsubscribe();
setContent("");
};
}, [editorStore.doc]);
}, [editorStore.doc, throttledUpdatePreviewConetent]);

useEffect(() => {
if (containerRef.current == null) {
Expand Down

0 comments on commit db0f772

Please sign in to comment.