Skip to content

Commit

Permalink
with-d3-require returns wrap-callback fn for :ref error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
mhuebert committed Oct 14, 2022
1 parent 26658eb commit e91208b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
2 changes: 1 addition & 1 deletion resources/viewer-js-hash
Original file line number Diff line number Diff line change
@@ -1 +1 @@
4ZdAZwg7ydXGHHZcCH31qfLYEfKa
4HD1mR7S3FQkZPw8nJSggBZeDPRi
29 changes: 22 additions & 7 deletions src/nextjournal/clerk/sci_viewer.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -618,14 +618,29 @@
(defn reagent-viewer [x]
(r/as-element (cond-> x (fn? x) vector)))

(defn wrap-f-async
"Wraps f to catch all synchronous and asynchronous errors"
[f on-error]
(fn [& args]
(-> (try (apply f args) (catch js/Error e (on-error e)))
js/Promise.resolve
(.catch on-error))))

(defn with-d3-require [{:keys [package then loading-view]
:or {loading-view "Loading..." then identity}} f]
(r/with-let [!package (r/atom {:loading loading-view})
_ (-> (if (string? package)
(d3-require/require package)
(apply d3-require/require package))
(.then then)
(.then f)
(.then
(fn wrap-callback [packages]
(f packages
(fn wrap-callback
;; wraps callback function to display errors here, serving
;; as an error boundary.
[callback]
(wrap-f-async callback #(reset! !package {:error %}))))))
(.then #(reset! !package {:value %}))
(.catch #(reset! !package {:error %})))]
(let [{:keys [loading error value]} @!package]
Expand All @@ -636,13 +651,13 @@

(defn vega-lite-viewer [value]
(when value
(html ^{:key value}
[with-d3-require {:package ["vega-embed@6.11.1"]
:then (fn [embed] (.container embed (clj->js value)))}
(j/fn [vega-el]
(html [with-d3-require {:package ["vega-embed@6.11.1"]
:key value} ;; specify what value should trigger re-render
(fn [vega-embed wrap-callback]
[:div {:style {:overflow-x "auto"}}
[:div.vega-lite {:ref #(when %
(.appendChild % vega-el))}]])])))
[:div.vega-lite {:ref (wrap-callback
(fn [el]
(when el (.embed vega-embed el (clj->js value)))))}]])])))

(def mathjax-viewer (comp normalize-viewer-meta mathjax/viewer))
(def code-viewer (comp normalize-viewer-meta code/viewer))
Expand Down

0 comments on commit e91208b

Please sign in to comment.