DEV Community

Daniel Ziltener
Daniel Ziltener

Posted on

Adding custom toolbar buttons to Fulcro 3 Workspaces cards

Recently I came across the problem that I wanted to use Workspaces' toolbar functionality - but with Fulcro 3 cards. There is no official documentation of doing this, so I ended up taking the standard Fulcro 3 card as a base and creating this custom card.
I used the following imports:

(ns util
  (:require [com.fulcrologic.fulcro.algorithms.merge :as m]
            [nubank.workspaces.core :as ws]
            [nubank.workspaces.model :as wsm]
            [nubank.workspaces.ui :as ui]
            [nubank.workspaces.ui.core :as uc]
            [com.fulcrologic.fulcro.dom :as dom]
            [nubank.workspaces.card-types.fulcro3 :as ct.fulcro]))
Enter fullscreen mode Exit fullscreen mode

And created this card:

(defn custom-toolbar-card [fulcro-class & {::keys [toolbar-items card-width card-height] :as props}]
  {::wsm/card-width card-width
   ::wsm/card-height card-height
   ::wsm/align {:flex 1}
   ::wsm/init
   (fn [card]
     (let [fulcro-card (ct.fulcro/fulcro-card-init card {::ct.fulcro/wrap-root? true
                                                         ::ct.fulcro/root       fulcro-class})
           card-id     (::wsm/card-id card)
           app         (::ct.fulcro/app fulcro-card)]
       (assoc fulcro-card
              ::wsm/render-toolbar
              (fn []
                (dom/div
                 (mapv #(uc/button {:onClick ((:fn %) app)} (:text %)) toolbar-items)
                 (uc/button {:onClick #(ct.fulcro/inspector-set-app card-id)}
                            "Inspector")
                 (uc/button {:onClick #(ui/restart-card card-id)}
                            "Restart"))))))})
Enter fullscreen mode Exit fullscreen mode

Note that I added the standard card-with and card-height parameters as well - you can leave those out - and added the default Fulcro 3 buttons.

Buttons can now be added in the format {:fn (fn [app-of-the-card] ...) :text "Button Text")}.

You can use it like this:

(ws/defcard login-card
            (util/custom-toolbar-card
             account-forms/LoginForm
             ::util/card-width 6
             ::util/card-height 16
             ::util/toolbar-items
             [{:fn (fn [app]
                     #(m/merge-component! app account-forms/LoginForm {:ui/error "The credentials you entered are incorrect."}))
               :text "Trigger error"}]))
Enter fullscreen mode Exit fullscreen mode

In this example, I made a card for a login form (account-forms/LoginForm) which is a Fulcro 3 component. I added a toolbar item with the button text "Trigger error" that, when clicked, calls the fn, which is given the fulcro app of the card, updating the LoginForm to set a login error text.

Top comments (0)