Skip to content

How to use d3 force simulation? #10

Open
@Folcon

Description

@Folcon

Firstly I'd like to say this library is great!

I'm just not sure how to hook in something like the d3 force simulation?

I've been trying to use the example code to get an idea of how this works, but I'm pretty stumped.
The state sim appears to initialise properly, but normally you use the tick to set the values of cx and cy values of the circles, but I've been trying to not directly mutate the dom. My current approach is to try and swap the values in the nodes/edges within the simulation?

(defn ->dots [did-mount?]
  (let [state (atom {:simulation
                     (.. js/d3
                        forceSimulation
                        (force "link" (.. js/d3 forceLink (id #(.id %)) (distance 120) (strength 1)))
                        (force "charge" (.. js/d3 forceManyBody (strength #(identity -30))))
                        (force "center" (.. js/d3 (forceCenter (/ 200 2) (/ 200 2))))
                      )})
    ]
    (.log js/console "d3:" (get @state :simulation))
    (fn [node ratom]
      (when did-mount?
        (set! (.-nodes (get @state :simulation)) (prepare-dataset ratom))
        (.on (get @state :simulation) "tick" #(.log js/console "TICK:" % node))
        (.. (get @state :simulation) (alpha 1) (alphaTarget 0) restart))
      (.log js/console "out:" node ratom)
        (rid3-> node
          {:cx 100
          :cy 100
          :r  50
          :sim #(.stringify js/JSON (.-nodes (get @state :simulation)))
          :data (fn [d] (.stringify js/JSON d))
          :title (fn [d] (or (gobj/get d "label") (gobj/getKeys d)))}))))

(defn prepare-dataset [ratom]
  (-> @ratom
    (#(map (fn [m] (into {} (for [[k v] m] [(str k) v]))) %))
      clj->js))

[rid3/viz
            {:id    "some-id"
            :ratom display
            :svg   {:did-mount (fn [node ratom]
                                  (rid3-> node
                                          {:width  400
                                           :height 400
                                           :style  {:background-color "white"}}))}
            :pieces [
              {:kind      :elem-with-data
               :class     "dots"
               :tag       "circle"
               :prepare-dataset prepare-dataset
               :did-mount  (->dots true)
               :did-update (->dots false)}
              ]
            }]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions