Browse Source

Only render markdown component on content changes.

gwillz 2 years ago
parent
commit
c70d71a233
2 changed files with 34 additions and 5 deletions
  1. 15 5
      app.js
  2. 19 0
      src/markdown.tsx

+ 15 - 5
app.js

@@ -5,19 +5,29 @@ const express = require('express');
 const PORT = 5000;
 const PATH = path.resolve(__dirname, "public");
 
+
+
 function main() {
-    express()
+    const app = express();
+    const delay = parseInt(process.argv[2], 10) || 0;
     
-    .use(express.static(PATH))
+    if (delay) {
+        app.use("/*plugins.js", (req, res, next) => {
+            setTimeout(() => next(), delay);
+        });
+    }
     
-    .get("/", (req, res) => {
+    app.use(express.static(PATH));
+    
+    app.get("/", (req, res) => {
         res.sendFile(path.resolve(PATH, "index.html"));
-    })
+    });
     
-    .listen(PORT, err => {
+    app.listen(PORT, err => {
         if (err) console.error(err);
         console.log('serving:', PATH);
         console.log('listening on port:', PORT);
+        if (delay) console.log('delay of:', delay);
         console.log('Press Ctrl+C to quit.');
     });
 }

+ 19 - 0
src/markdown.tsx

@@ -19,6 +19,8 @@ const markdown = new showdown.Converter({
     tables: true,
 })
 
+let PLUGINS_LOADED = false;
+
 ;(async function() {
     const plugins = await import('./showdown-plugins' /* webpackChunkName: 'plugins' */);
     
@@ -26,9 +28,11 @@ const markdown = new showdown.Converter({
         markdown.addExtension(plugin, plugin.name);
     });
     
+    PLUGINS_LOADED = true;
     store.dispatch({type: 'RENDER'});
 })();
 
+
 function doCopy(text: string) {
     const element = document.createElement('textarea');
     element.value = text;
@@ -41,8 +45,23 @@ function doCopy(text: string) {
     document.body.removeChild(element);
 }
 
+
 export class Markdown extends React.Component<Props> {
     private element: HTMLElement | null;
+    private plugins_loaded = false;
+    
+    // Perform an update once plugins are loaded.
+    // Otherwise only update on prop changes, aka PureComponent.
+    shouldComponentUpdate(props: Props) {
+        if (PLUGINS_LOADED && !this.plugins_loaded) {
+            this.plugins_loaded = true;
+            return true;
+        }
+        return (
+            this.props.className !== props.className ||
+            this.props.content !== props.content
+        )
+    }
     
     componentDidMount() {
         // mounted, but rendering is delayed by makeHtml() / DOM insertion.