From 37a7bb202b024307e35f5f8a6b794ba279ba8e6c Mon Sep 17 00:00:00 2001 From: Andrey Antukh Date: Fri, 22 Dec 2023 12:50:43 +0100 Subject: [PATCH] :sparkles: Add lazy loading for highlightjs on code-block component Mainly because highlight.js is a heavy library but only used on a very concrete situations, so it does not make sense to load it all the time. --- .../src/app/main/ui/components/code_block.cljs | 17 ++++++++++------- frontend/src/app/util/code_highlight.cljs | 15 +++++++++++++++ 2 files changed, 25 insertions(+), 7 deletions(-) create mode 100644 frontend/src/app/util/code_highlight.cljs diff --git a/frontend/src/app/main/ui/components/code_block.cljs b/frontend/src/app/main/ui/components/code_block.cljs index 8079cc0067..d6d81f8495 100644 --- a/frontend/src/app/main/ui/components/code_block.cljs +++ b/frontend/src/app/main/ui/components/code_block.cljs @@ -7,12 +7,15 @@ (ns app.main.ui.components.code-block (:require-macros [app.main.style :as stl]) (:require - ["highlight.js" :as hljs] [app.common.data.macros :as dm] [app.main.ui.context :as ctx] - [app.util.dom :as dom] [cuerdas.core :as str] - [rumext.v2 :as mf])) + [promesa.core :as p] + [rumext.v2 :as mf] + [shadow.lazy :as lazy])) + +(def highlight-fn + (lazy/loadable app.util.code-highlight/highlight!)) (mf/defc code-block {::mf/wrap-props false} @@ -20,11 +23,11 @@ (let [new-css-system (mf/use-ctx ctx/new-css-system) block-ref (mf/use-ref) code (str/trim code)] - (mf/with-effect - [code type] + + (mf/with-effect [code type] (when-let [node (mf/ref-val block-ref)] - (dom/set-data! node "highlighted" nil) - (hljs/highlightElement node))) + (p/let [highlight-fn (lazy/load highlight-fn)] + (highlight-fn node)))) (if new-css-system [:pre {:class (dm/str type " " (stl/css :code-display)) :ref block-ref} code] diff --git a/frontend/src/app/util/code_highlight.cljs b/frontend/src/app/util/code_highlight.cljs new file mode 100644 index 0000000000..62c7617202 --- /dev/null +++ b/frontend/src/app/util/code_highlight.cljs @@ -0,0 +1,15 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; License, v. 2.0. If a copy of the MPL was not distributed with this +;; file, You can obtain one at http://mozilla.org/MPL/2.0/. +;; +;; Copyright (c) KALEIDOS INC + +(ns app.util.code-highlight + (:require + ["highlight.js" :as hljs] + [app.util.dom :as dom])) + +(defn highlight! + [node] + (dom/set-data! node "highlighted" nil) + (hljs/highlightElement node))