Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add throttle to prevent preview's indiscriminate updates #391

Merged
merged 4 commits into from
Nov 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 26 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";
JOOHOJANG marked this conversation as resolved.
Show resolved Hide resolved
import { addSoftLineBreak } from "../../utils/document";

const DELAY = 500;

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

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

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

updatePreviewContent();
throttledUpdatePreviewContent();

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

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

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