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 committed Oct 28, 2024
1 parent eda0444 commit 392edf1
Showing 1 changed file with 20 additions and 9 deletions.
29 changes: 20 additions & 9 deletions frontend/src/components/editor/Preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { CircularProgress, Stack } from "@mui/material";
import MarkdownPreview from "@uiw/react-markdown-preview";
import katex from "katex";
import "katex/dist/katex.min.css";
import { useEffect, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import { useSelector } from "react-redux";
import rehypeExternalLinks from "rehype-external-links";
import rehypeKatex from "rehype-katex";
Expand All @@ -13,25 +13,36 @@ import { useCurrentTheme } from "../../hooks/useCurrentTheme";
import { selectEditor } from "../../store/editorSlice";
import { addSoftLineBreak } from "../../utils/document";
import "./editor.css";
import _ from "lodash";

const DELAY = 500;

function Preview() {
const currentTheme = useCurrentTheme();
const editorStore = useSelector(selectEditor);
const [content, setContent] = useState("");
const throttledUpdatePreviewConetent = useCallback(
_.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 }
),
[]
);

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

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

updatePreviewContent();
throttledUpdatePreviewConetent();

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

return () => {
Expand Down

0 comments on commit 392edf1

Please sign in to comment.