Creating a tree from a text file in json - Clojure - json

I have a text file consisting of a json value in each line. My file is as follows:
{"id":"a","family":"root","parent":nil,"value":"valueofa"}
{"id":"b1","family":"b","parent":"a","value":"valueofb1"}
{"id":"c1","family":"c","parent":"b1","value":"valueofc1"}
{"id":"c2","family":"c","parent":"b1","value":"valueofc2"}
{"id":"b2","family":"b","parent":"root","value":"valueofb2"}
{"id":"d1","family":"d","parent":"b1","value":"valueofd1"}
In the json given above, we the family attribute indicates a hierarchy, we would have "root" as the root,"b" as child of the "root","c" as child of "b" and and "d" would be child of "b" as well.
The idea is to iterate through the file and add the node being read at its proper place in a tree. One way would be to read these entries into a "map" and then use this map for any tree-manipulations. For any complex tree manipulations, I am not sure how this would work. It is quite possible that based on a certain requirement, I might have to detach a child from an existing parent and attach it to another parent. Apparently Clojure zippers are supposed to help in this regard but I am getting a little confused by how the hierarchy of nodes work in zippers.
It will be great if somebody could point me in the right direction here.

This is several questions, and probably too broad, but here's a sampling.
How do I read a file?
(def file-contents (slurp "foo.txt"))`
How do I convert JSON to Clojure data?
(require '[cheshire.core :refer [parse-string]])`
(def data (map #(parse-string % true)
(clojure.string/split file-contents #"\n")))
How do I treat a list with parent references like a tree?
(require '[clojure.zip :as z])
(defn create-zipper [s]
(let [g (group-by :parent s)]
(z/zipper g #(map :id (g %)) nil (-> nil g first :id))))
(def t (create-zipper data))
See how to transform a seq into a tree
How do I use zippers?
user=> (-> t z/node)
"a"
user=> (-> t z/children)
("b1")
user=> (-> t z/down z/node)
"b1"
user=> (-> t z/down z/children)
("c1" "c2" "d1")
user=> (-> t z/down z/down z/rightmost z/node)
"d1"

Related

ClojureScript. Reset atom in Reagent when re-render occurs

I'm displaying a set of questions for a quiz test and I'm assigning a number to each question just to number them when they are shown in the browser:
(defn questions-list
[]
(let [counter (atom 0)]
(fn []
(into [:section]
(for [question #(re-frame/subscribe [:questions])]
[display-question (assoc question :counter (swap! counter inc))])))))
The problem is that when someone edits a question in the browser (and the dispatch is called and the "app-db" map is updated) the component is re-rendered but the atom "counter" logically starts from the last number not from zero. So I need to reset the atom but I don't know where. I tried with a let inside the anonymous function but that didn't work.
In this case I'd just remove the state entirely. I haven't tested this code, but your thinking imperatively here. The functional version of what your trying to do is something along the lines of:
Poor but stateless:
(let [numbers (range 0 (count questions))
indexed (map #(assoc (nth questions %) :index %) questions)]
[:section
(for [question indexed]
[display-question question])])
but this is ugly, and nth is inefficient. So lets try one better. Turns out map can take more than one collection as it's argument.
(let [numbers (range 0 (count questions))
indexed (map (fn [idx question] (assoc question :index idx)) questions)]
[:section
(for [question indexed]
[display-question question])])
But even better, turns out there is a built in function for exactly this. What I'd actually write:
[:section
(doall
(map-indexed
(fn [idx question]
[display-question (assoc question :index idx)])
questions))]
Note: None of this code has actually been run, so you might have to tweak it a bit before it works. I'd recommend looking up all of the functions in ClojureDocs to make sure you understand what they do.
If you need counter to be just an index for a question, you could instead use something like this:
(defn questions-list
[]
(let [questions #(re-frame/subscribe [:questions])
n (count questions)]
(fn []
[:section
[:ul
(map-indexed (fn [idx question] ^{:key idx} [:li question]) questions)]])))
Note: here I used [:li question] because I assumed that question is some kind of text.
Also, you could avoid computing the count for questions in this component and do it with a layer 3 subscription:
(ns your-app.subs
(:require
[re-frame.core :as rf]))
;; other subscriptions...
(rf/reg-sub
:questions-count
(fn [_ _]
[(rf/subscribe [:questions])])
(fn [[questions] _]
(count questions)))
Then in the let binding of your component you would need to replace n (count questions) with n #(re-frame/subscribe [:questions-count]).

Reagent not rendering as expected when adding a new item at end of reactive vector

I'm working on a tree control in ClojureScript and Reagent. It can be used as a file system navigator, topic navigator, outliner, etc.
When a headline in an outline is selected and being edited, the traditional behavior when Return is tapped is to create a new headline (a child or sibling depending on the expansion state of the headline and whether it already has children or not) then focus it leaving it ready to edit. My control does that all correctly except in the case of editing the last sibling in a group.
In the problematic case, the headline is created as expected, but focusing the new control fails.
I created an MCVE using the figwheel template.
lein new figwheel test-reagent-vector -- --reagent
Here's a listing exhibiting the problem.
(ns test-reagent-vector.core
(:require [clojure.string :as s]
[reagent.core :as r]))
(def ^{:constant true} topic-separator \u02D1)
(def empty-test-topic {:topic "Empty Test Topic"})
(defonce global-state-with-hierarchy
(r/atom {:name "Global Application State, Inc."
:data {:one "one" :two 2 :three [3]}
:tree [{:topic "First Headline"}
{:topic "Middle Headline"}
{:topic "Last Headline"}]}))
(defn get-element-by-id
[id]
(.getElementById js/document id))
(defn event->target-element
[evt]
(.-target evt))
(defn event->target-value
[evt]
(.-value (event->target-element evt)))
(defn swap-style-property
"Swap the specified style settings for the two elements."
[first-id second-id property]
(let [style-declaration-of-first (.-style (get-element-by-id first-id))
style-declaration-of-second (.-style (get-element-by-id second-id))
value-of-first (.getPropertyValue style-declaration-of-first property)
value-of-second (.getPropertyValue style-declaration-of-second property)]
(.setProperty style-declaration-of-first property value-of-second)
(.setProperty style-declaration-of-second property value-of-first)))
(defn swap-display-properties
"Swap the display style properties for the two elements."
[first-id second-id]
(swap-style-property first-id second-id "display"))
;;------------------------------------------------------------------------------
;; Vector-related manipulations.
(defn delete-at
"Remove the nth element from the vector and return the result."
[v n]
(vec (concat (subvec v 0 n) (subvec v (inc n)))))
(defn remove-last
"Remove the last element in the vector and return the result."
[v]
(subvec v 0 (dec (count v))))
(defn remove-last-two
"Remove the last two elements in the vector and return the result."
[v]
(subvec v 0 (- (count v) 2)))
(defn insert-at
"Return a copy of the vector with new-item inserted at the given n. If
n is less than zero, the new item will be inserted at the beginning of
the vector. If n is greater than the length of the vector, the new item
will be inserted at the end of the vector."
[v n new-item]
(cond (< n 0) (into [new-item] v)
(>= n (count v)) (conj v new-item)
:default (vec (concat (conj (subvec v 0 n) new-item) (subvec v n)))))
(defn replace-at
"Replace the current element in the vector at index with the new-element
and return it."
[v index new-element]
(insert-at (delete-at v index) index new-element))
;;------------------------------------------------------------------------------
;; Tree id manipulation functions.
(defn tree-id->tree-id-parts
"Split a DOM id string (as used in this program) into its parts and return
a vector of the parts"
[id]
(s/split id topic-separator))
(defn tree-id-parts->tree-id-string
"Return a string formed by interposing the topic-separator between the
elements of the input vector."
[v]
(str (s/join topic-separator v)))
(defn increment-leaf-index
"Given the tree id of a leaf node, return an id with the node index
incremented."
[tree-id]
(let [parts (tree-id->tree-id-parts tree-id)
index-in-vector (- (count parts) 2)
leaf-index (int (nth parts index-in-vector))
new-parts (replace-at parts index-in-vector (inc leaf-index))]
(tree-id-parts->tree-id-string new-parts)))
(defn change-tree-id-type
"Change the 'type' of a tree DOM element id to something else."
[id new-type]
(let [parts (tree-id->tree-id-parts id)
shortened (remove-last parts)]
(str (tree-id-parts->tree-id-string shortened) (str topic-separator new-type))))
(defn tree-id->nav-vector-and-index
"Parse the id into a navigation path vector to the parent of the node and an
index within the vector of children. Return a map containing the two pieces
of data. Basically, parse the id into a vector of information to navigate
to the parent (a la get-n) and the index of the child encoded in the id."
[tree-id]
(let [string-vec (tree-id->tree-id-parts tree-id)
idx (int (nth string-vec (- (count string-vec) 2)))
without-last-2 (remove-last-two string-vec)
without-first (delete-at without-last-2 0)
index-vector (mapv int without-first)
interposed (interpose :children index-vector)]
{:path-to-parent (vec interposed) :child-index idx}))
;;------------------------------------------------------------------------------
;; Functions to manipulate the tree and subtrees.
(defn add-child!
"Insert the given topic at the specified index in the parents vector of
children. No data is deleted."
[parent-topic-ratom index topic-to-add]
(swap! parent-topic-ratom insert-at index topic-to-add))
(defn graft-topic!
"Add a new topic at the specified location in the tree. The topic is inserted
into the tree. No data is removed. Any existing information after the graft
is pushed down in the tree."
[root-ratom id-of-desired-node topic-to-graft]
(let [path-and-index (tree-id->nav-vector-and-index id-of-desired-node)]
(add-child! (r/cursor root-ratom (:path-to-parent path-and-index))
(:child-index path-and-index) topic-to-graft)))
;;;-----------------------------------------------------------------------------
;;; Functions to handle keystroke events.
(defn handle-enter-key-down!
"Handle a key-down event for the Enter/Return key. Insert a new headline
in the tree and focus it, ready for editing."
[root-ratom span-id]
(let [id-of-new-child (increment-leaf-index span-id)]
(graft-topic! root-ratom id-of-new-child empty-test-topic)
(let [id-of-new-editor (change-tree-id-type id-of-new-child "editor")
id-of-new-label (change-tree-id-type id-of-new-child "label")]
(swap-display-properties id-of-new-label id-of-new-editor)
(.focus (get-element-by-id id-of-new-editor)))))
(defn handle-key-down
"Detect key-down events and dispatch them to the appropriate handlers."
[evt root-ratom span-id]
(when
(= (.-key evt) "Enter") (handle-enter-key-down! root-ratom span-id)))
;;;-----------------------------------------------------------------------------
;;; Functions to build the control.
(defn build-topic-span
"Build the textual part of a topic/headline."
[root-ratom topic-ratom span-id]
(let [label-id (change-tree-id-type span-id "label")
editor-id (change-tree-id-type span-id "editor")]
[:span
[:label {:id label-id
:style {:display :initial}
:onClick (fn [e]
(swap-display-properties label-id editor-id)
(.focus (get-element-by-id editor-id))
(.stopPropagation e))}
#topic-ratom]
[:input {:type "text"
:id editor-id
:style {:display :none}
:onKeyDown #(handle-key-down % root-ratom span-id)
:onFocus #(.stopPropagation %)
:onBlur #(swap-display-properties label-id editor-id)
:onChange #(reset! topic-ratom (event->target-value %))
:value #topic-ratom}]]))
(defn tree->hiccup
"Given a data structure containing a hierarchical tree of topics, generate
hiccup to represent that tree. Also generates a unique, structure-based
id that is included in the hiccup so that the correct element in the
application state can be located when its corresponding HTML element is
clicked."
([root-ratom]
(tree->hiccup root-ratom root-ratom "root"))
([root-ratom sub-tree-ratom path-so-far]
[:ul
(doall
(for
[index (range (count #sub-tree-ratom))]
(let [t (r/cursor sub-tree-ratom [index])
topic-ratom (r/cursor t [:topic])
id-prefix (str path-so-far topic-separator index)
topic-id (str id-prefix topic-separator "topic")
span-id (str id-prefix topic-separator "span")]
^{:key topic-id}
[:li {:id topic-id}
[:div (build-topic-span root-ratom topic-ratom span-id)]])))]))
(defn home
"Return a function to layout the home (only) page."
[app-state-atom]
(fn [app-state-ratom]
[:div (tree->hiccup (r/cursor app-state-ratom [:tree]))]))
(r/render-component [home global-state-with-hierarchy]
(get-element-by-id "app"))
(I assume some of this is not relevant to the problem, like the tree id manipulation functions. They are just here to make building the example easier.)
The control uses a vector to contain siblings, something about inserting a new element at the end of the vector seems to cause the timing of rendering to change.
When the user has the last item selected and clicks Return, an error message appears in the browser console about a null argument being passed to get-element-by-id. This is triggered by the keyboard handling function handle-enter-key-down!.
The items in the list of headlines are really two HTML elements: a label that displays when the user is not editing it, and a text input that is shown during editing. When a new headline is created, the swap-display-properties function is called to make the editor visible, then it is focused.
When a headline is created at the end of a vector of siblings, the DOM identifiers for the new label and text input are not available to switch the visibility of the two elements. Thus the error message about a null argument to get-element-by-id.
But it works correctly for all of the other positions.
I've reproduced this
on a Mac
with OpenJDK 9 and 11
with the original versions of the dependencies used in the template and after updating them to current
on Safari and Firefox
I can force it to work by delaying the call to swap-display-properties by 25ms or longer.
;; Wait for rendering to catch up.
(js/setTimeout #(do (swap-display-properties id-of-new-label id-of-new-editor)
(.focus (get-element-by-id id-of-new-editor))) 25)
I assume I could do something with Reacts componentDidMount method, but I don't understand why there is a failure only when inserting a new headline at the end of a vector of siblings.
So...
Is it just a coincidence that the other cases work as expected?
Am I misunderstanding something about the Reagent workflow?
Is there some problem with Reagent?
Any ideas would be appreciated.
I think you have already identified the problem as a race condition between adding the new element in Reagent and it getting created in the DOM (where get-element-by-id is looking for it).
The simplest answer (besides adding 25 ms sleeps everywhere) is to use an event loop library like re-frame to schedule a "set-focus" event which will be processed on the next pass through the event loop.
As an aside, I never use concat or subvec. Keep it simple with take & drop, and always wrap the output of a fn with (vec ...) to force it in to a plain vector w/o any sneaky/problematic laziness.
Browser focus is difficult and confusing to maintain.
Here's what I think is happening when you hit enter
The keydown event fires
You add the new topic via graft-topic!
You switch the styles such that the input is showing and the label is
hidden
You focus on the next element in the list
then, after the keydown event is done, reagent rerenders
When this happens the element that is focused is replaced by the new element you created
In the case that the element you are hitting enter from is not the final element in the list
You are able to focus on the already existing element and then later reagent replaces this element with the new element created in graft-topic!
In the case that the element you are hitting enter from is the final element in the list
Focusing fails to happen because no element with that id exists yet
therefore no element is in focus when reagent rerenders with the newly created element
What the browser is doing
The new element you created is in the same place as the old focused element, so the browser keeps the focus in that place
You can test this with the following code snippet which switches the two inputs on every keydown.
Despite having different ids and being different components, focus remains in the same place it was even when swapping the two components
(defn test-comp []
(r/with-let [*test? (r/atom true)]
[:div
(if #*test?
[:div
[:input
{:value "test"
:id "test"
:on-key-down #(swap! *test? not)}]
[:input
{:value "not test"
:id "not test"
:on-key-down #(swap! *test? not)}]]
[:div
[:input
{:value "not test"
:id "not test"
:on-key-down #(swap! *test? not)}]
[:input
{:value "test"
:id "test"
:on-key-down #(swap! *test? not)}]])]))
(note: this will give you a warning about not having an on-change handler, but that's not important for this demo, just wanted to specify the value so you could see the two inputs swap places, but the focus remain in the same place)
As to how to fix this...
Don't rely on waiting a cycle or using js timeout to fix this, that just wastes precious time
I would recommend not using the browser to retain focus
The simple answer is to keep what index is focused in app-state, and then decide whether the label or the input is rendered based on what
Then add an auto-focus attribute to the input so that when it renders it will come into focus
Some pointers for how to use reagent
In your code you are resolving the reagent component with (), but what you should do is use []
This relates to how reagent decides when to rerender components, but since you resolve the whole tree, every time you change an atom that you derefed it will rerender your whole tree, not just the place you derefed the atom. (test this by adding a println to your code in the build-topic-span component)
Define cursors in a form-2 component (or use with-let), they only need to be defined once per component, so no need to have them be redefined on every subsequent render (not sure if this will lead to bugs, but it's good practice)
also you can use cursor like get-in, so instead of
t (r/cursor sub-tree-ratom [index])
topic-ratom (r/cursor t [:topic])
you can do
topic-ratom (r/cursor t [index :topic])
Some other notes
The swapping styles thing you're doing is confusing, if you keep track of what is focused, you can just render a different component depending on what is focused, no need to have both the label and the input in the dom at the same time.
passing around a bunch of string ids is very confusing, especially when calling graft-topic! you destructure the string back into the path. Data is much easier to work with, keep the path in a vector and make it a string only when it needs to be
This example refactored with these things in mind
(ns test-reagent-vector.core
(:require [clojure.string :as s]
[reagent.core :as r]))
(def ^{:constant true} topic-separator \u02D1)
(def empty-test-topic {:topic "Empty Test Topic"})
(defonce global-state-with-hierarchy
(r/atom {:name "Global Application State, Inc."
:focused-index nil
:data {:one "one" :two 2 :three [3]}
:tree [{:topic "First Headline"}
{:topic "Middle Headline"}
{:topic "Last Headline"}]}))
(defn get-element-by-id
[id]
(.getElementById js/document id))
(defn event->target-element
[evt]
(.-target evt))
(defn event->target-value
[evt]
(.-value (event->target-element evt)))
(defn swap-style-property
"Swap the specified style settings for the two elements."
[first-id second-id property]
(let [style-declaration-of-first (.-style (get-element-by-id first-id))
style-declaration-of-second (.-style (get-element-by-id second-id))
value-of-first (.getPropertyValue style-declaration-of-first property)
value-of-second (.getPropertyValue style-declaration-of-second property)]
(.setProperty style-declaration-of-first property value-of-second)
(.setProperty style-declaration-of-second property value-of-first)))
(defn swap-display-properties
"Swap the display style properties for the two elements."
[first-id second-id]
(swap-style-property first-id second-id "display"))
;;------------------------------------------------------------------------------
;; Vector-related manipulations.
(defn delete-at
"Remove the nth element from the vector and return the result."
[v n]
(vec (concat (subvec v 0 n) (subvec v (inc n)))))
(defn remove-last
"Remove the last element in the vector and return the result."
[v]
(subvec v 0 (dec (count v))))
(defn remove-last-two
"Remove the last two elements in the vector and return the result."
[v]
(subvec v 0 (- (count v) 2)))
(defn insert-at
"Return a copy of the vector with new-item inserted at the given n. If
n is less than zero, the new item will be inserted at the beginning of
the vector. If n is greater than the length of the vector, the new item
will be inserted at the end of the vector."
[v n new-item]
(cond (< n 0) (into [new-item] v)
(>= n (count v)) (conj v new-item)
:default (vec (concat (conj (subvec v 0 n) new-item) (subvec v n)))))
(defn replace-at
"Replace the current element in the vector at index with the new-element
and return it."
[v index new-element]
(insert-at (delete-at v index) index new-element))
;;------------------------------------------------------------------------------
;; Tree id manipulation functions.
(defn tree-id->tree-id-parts
"Split a DOM id string (as used in this program) into its parts and return
a vector of the parts"
[id]
(s/split id topic-separator))
(defn tree-id-parts->tree-id-string
"Return a string formed by interposing the topic-separator between the
elements of the input vector."
[v]
(str (s/join topic-separator v)))
(defn increment-leaf-index
"Given the tree id of a leaf node, return an id with the node index
incremented."
[tree-id]
(let [parts (tree-id->tree-id-parts tree-id)
index-in-vector (- (count parts) 2)
leaf-index (int (nth parts index-in-vector))
new-parts (replace-at parts index-in-vector (inc leaf-index))]
(tree-id-parts->tree-id-string new-parts)))
(defn change-tree-id-type
"Change the 'type' of a tree DOM element id to something else."
[id new-type]
(let [parts (tree-id->tree-id-parts id)
shortened (remove-last parts)]
(str (tree-id-parts->tree-id-string shortened) (str topic-separator new-type))))
(defn tree-id->nav-vector-and-index
"Parse the id into a navigation path vector to the parent of the node and an
index within the vector of children. Return a map containing the two pieces
of data. Basically, parse the id into a vector of information to navigate
to the parent (a la get-n) and the index of the child encoded in the id."
[tree-id]
(let [string-vec (tree-id->tree-id-parts tree-id)
idx (int (nth string-vec (- (count string-vec) 2)))
without-last-2 (remove-last-two string-vec)
without-first (delete-at without-last-2 0)
index-vector (mapv int without-first)
interposed (interpose :children index-vector)]
{:path-to-parent (vec interposed) :child-index idx}))
;;------------------------------------------------------------------------------
;; Functions to manipulate the tree and subtrees.
(defn add-child!
"Insert the given topic at the specified index in the parents vector of
children. No data is deleted."
[parent-topic-ratom index topic-to-add]
(swap! parent-topic-ratom insert-at index topic-to-add))
(defn graft-topic!
"Add a new topic at the specified location in the tree. The topic is inserted
into the tree. No data is removed. Any existing information after the graft
is pushed down in the tree."
[root-ratom id-of-desired-node topic-to-graft]
(let [path-and-index (tree-id->nav-vector-and-index id-of-desired-node)]
(add-child! (r/cursor root-ratom (:path-to-parent path-and-index))
(:child-index path-and-index) topic-to-graft)))
;;;-----------------------------------------------------------------------------
;;; Functions to handle keystroke events.
(defn handle-enter-key-down!
"Handle a key-down event for the Enter/Return key. Insert a new headline
in the tree and focus it, ready for editing."
[app-state root-ratom index]
(add-child! root-ratom (inc index) empty-test-topic)
(swap! app-state update :focused-index inc)
)
(defn handle-key-down
"Detect key-down events and dispatch them to the appropriate handlers."
[evt app-state root-ratom index]
(when (= (.-key evt) "Enter")
(handle-enter-key-down! app-state root-ratom index)))
;;;-----------------------------------------------------------------------------
;;; Functions to build the control.
(defn build-topic-span
"Build the textual part of a topic/headline."
[root-ratom index]
(r/with-let [topic-ratom (r/cursor root-ratom [index :topic])
focused-index (r/cursor global-state-with-hierarchy [:focused-index])]
(if-not (= index #focused-index)
[:label
{:onClick #(reset! focused-index index)}
#topic-ratom]
[:input {:type "text"
:auto-focus true
:onKeyDown #(handle-key-down % global-state-with-hierarchy root-ratom index)
:onChange #(reset! topic-ratom (event->target-value %))
:on-blur #(when (= index #focused-index)
(reset! focused-index nil))
:value #topic-ratom}])))
(defn tree->hiccup
"Given a data structure containing a hierarchical tree of topics, generate
hiccup to represent that tree. Also generates a unique, structure-based
id that is included in the hiccup so that the correct element in the
application state can be located when its corresponding HTML element is
clicked."
([root-ratom]
[tree->hiccup root-ratom root-ratom "root"])
([root-ratom sub-tree-ratom path-so-far]
[:ul
(doall
(for [index (range (count #sub-tree-ratom))]
^{:key (str index)}
[:li
[:div
[build-topic-span root-ratom index]]]
))]))
(defn home
"Return a function to layout the home (only) page."
[app-state-ratom]
(r/with-let [tree-ratom (r/cursor app-state-ratom [:tree])]
[:div
[tree->hiccup tree-ratom]]))
(r/render
[home global-state-with-hierarchy]
(get-element-by-id "app"))
I only changed home, tree→hiccup, build topic span and handle keydown.
In the future
The example I wrote up assumes this is a flat list, but seems like you're planning on making this a nested list in the future and if that's true I would recommend changing some things
associate a unique id to every topic and use that id to determine if that element is in focus
specify the path-so-far as a vector of the ids up to that point in the tree
don't specify the the key as a function of the index, what if the element switches places with another element in the tree? we don't want to rerender it. Base this off a unique id
investigate the reagent track! function to cut down on rerenders when asking if the current element is focused
Hope this helps
Feel free to message me if you have any more questions regarding how to build a nested interactive list :)
After the responses from Joshua Brown and Alan Thompson, I got to reviewing the API docs in Reagent again to understand what with-let did.
Then I noticed after-render, which was exactly what I needed. To fix the problem in my example, add after-render in the handle-enter-key-down! like this.
(defn handle-enter-key-down!
"Handle a key-down event for the Enter/Return key. Insert a new headline
in the tree and focus it, ready for editing."
[root-ratom span-id]
(let [id-of-new-child (increment-leaf-index span-id)]
(graft-topic! root-ratom id-of-new-child empty-test-topic)
(let [id-of-new-editor (change-tree-id-type id-of-new-child "editor")
id-of-new-label (change-tree-id-type id-of-new-child "label")]
(r/after-render
(fn []
(swap-display-properties id-of-new-label id-of-new-editor)
(.focus (get-element-by-id id-of-new-editor)))))))
Since the identifiers for the new label and text input exist after the render, swapping their display properties now works as expected and the newly visible input can be focused.
I believe this also fixes the potential race condition that existed before (but did not manifest) when inserting new headlines at other positions in the vector as well.

Clojurescript `:optimizations :advanced` breaks access to dataset

Following code:
(set! (.. e -target -dataset -some-field) "some-value")
is compiled into:
return a.target.dataset.Qh=Yf(b)
some_field is compressed into Qh. And I need it to be exactly some_field.
I understand this is due to compression optimization. But is there a way to hint, or to bypass this behavior?
PS: simple optimization gives the desired output
return a.target.dataset.some_field=cljs.core.name.call(null,b)}
You may also be interested in the cljs-oops library: https://github.com/binaryage/cljs-oops
Then you can say:
(oset! el "innerHTML" "Hi!")
More examples below, and also on the CLJS Cheatsheet:
The problem is that some-field (or is it some_field or someField?) gets simplified to Qh. This is because the compiler does not know that the dataset object has a some-field property.
One solution is to write extern files so that the Google Closure Compiler will know that the given field must not be renamed.
An other solution is to use aset function or call goog.object.set function. This way you reference the field of the object with a string value and the string values do not get simplified.
Second example:
cljs.user=> (def a (clj->js {"a" 1}))
#'cljs.user/a
cljs.user=> a
#js {:a 1}
cljs.user=> (aset a "b" 2)
2
cljs.user=> a
#js {:a 1, :b 2}

loading configuration file in clojure as data structure

Is there a reader function in clojure to parse clojure data structure? My use case is to read configuration properties files and one value for a property should be a list. I'd like to be able to write this as:
file.properties:
property1 = ["value1" "value2"]
and in clojure:
(load-props "file.properties")
and get a map with value {property1, ["value1" "value2"]
Right now,m I'm doing the following, with the same input file "file.properties":
(defn load-props [filename]
(let [io (java.io.FileInputStream. filename)
prop (java.util.Properties.)]
(.load prop io)
(into {} prop)))
;; returns:
;; {"property1" "[\"valu1\", \"valu2\"]"}
(load-props "file.properties")
But I cannot get a way to parse the result to a clojure's vector. I'm basically looking for something like Erlang's file:consult/1 function. Any idea how to do this?
If you want to read java-style properties files, look at Dave Ray's answer - though properties files have many limitations.
If you are using Clojure 1.5 or later, I suggest you use edn, the extensible data notation used in Datomic - it's basically clojure data structures, with no arbitrary code execution, and the ability to add tags for things like instances or arbitrary types.
The simplest way to use it is via read-string and slurp:
(require 'clojure.edn)
(clojure.edn/read-string (slurp "filename.edn"))
That's it. Note that read-string only reads a single variable, so you should set up your configuration as a map:
{ :property1 ["value1" "value2"] }
Then:
(require 'clojure.edn)
(def config (clojure.edn/read-string (slurp "config.edn")))
(println (:property1 config))
returns
["value1" "value2"]
java.util.Properties implements Map so this can be done very easily without manually parsing properties files:
(require 'clojure.java.io)
(defn load-props
[file-name]
(with-open [^java.io.Reader reader (clojure.java.io/reader file-name)]
(let [props (java.util.Properties.)]
(.load props reader)
(into {} (for [[k v] props] [(keyword k) (read-string v)])))))
(load-props "test.properties")
;=> {:property3 {:foo 100, :bar :test}, :property2 99.9, :property1 ["foo" "bar"]}
In particular, properties files are more complicated than you think (comments, escaping, etc, etc) and java.util.Properties is very good at loading them.
Is there a reader function in clojure to parse clojure data structure?
Yes. It's called read. You can also use it to read configuration data.
A file props.clj containing
{:property1 ["value1" 2]
:property2 {:some "key"}}
can be read like this:
(ns somens.core
(:require [clojure.java.io :as io])
(:import [java.io PushbackReader]))
(def conf (with-open [r (io/reader "props.clj")]
(read (PushbackReader. r))))
When reading untrusted sources it might be a good idea to turn of *read-eval*:
(def conf (binding [*read-eval* false]
(with-open [r (io/reader "props.clj")]
(read (PushbackReader. r)))))
For writing configuration data back to a file you should look at print functions such as pr and friends.
contrib has functions for reading writing properties,
http://richhickey.github.com/clojure-contrib/java-utils-api.html#clojure.contrib.java-utils/as-properties
If this is for your own consumption then I would suggest reading/writing clojure data structures you can just print them to disk and read them.
(use '[clojure.contrib.duck-streams :only (read-lines)])
(import '(java.io StringReader PushbackReader))
(defn propline->map [line] ;;property1 = ["value1" "value2"] -> { :property1 ["value1" "value2"] }
(let [[key-str value-str] (seq (.split line "="))
key (keyword (.trim key-str))
value (read (PushbackReader. (StringReader. value-str)))]
{ key value } ))
(defn load-props [filename]
(reduce into (map propline->map (read-lines filename))))
DEMO
user=> (def prop (load-props "file.properties"))
#'user/prop
user=> (prop :property1)
["value1" "value2"]
user=> ((prop :property1) 1)
"value2"
UPDATE
(defn non-blank? [line] (if (re-find #"\S" line) true false))
(defn non-comment? [line] (if (re-find #"^\s*\#" line) false true))
(defn load-props [filename]
(reduce into (map propline->map (filter #(and (non-blank? %)(non-comment? %)) (read-lines filename)))))

Clojure: creating new instance from String class name

In Clojure, given a class name as a string, I need to create a new instance of the class. In other words, how would I implement new-instance-from-class-name in
(def my-class-name "org.myorg.pkg.Foo")
; calls constructor of org.myorg.pkg.Foo with arguments 1, 2 and 3
(new-instance-from-class-name my-class-name 1 2 3)
I am looking for a solution more elegant than
calling the Java newInstance method on a constructor from the class
using eval, load-string, ...
In practice, I will be using it on classes created using defrecord. So if there is any special syntax for that scenario, I would be quite interested.
There are two good ways to do this. Which is best depends on the specific circumstance.
The first is reflection:
(clojure.lang.Reflector/invokeConstructor
(resolve (symbol "Integer"))
(to-array ["16"]))
That's like calling (new Integer "16") ...include any other ctor arguments you need in the to-array vector. This is easy, but slower at runtime than using new with sufficient type hints.
The second option is as fast as possible, but a bit more complicated, and uses eval:
(defn make-factory [classname & types]
(let [args (map #(with-meta (symbol (str "x" %2)) {:tag %1}) types (range))]
(eval `(fn [~#args] (new ~(symbol classname) ~#args)))))
(def int-factory (make-factory "Integer" 'String))
(int-factory "42")
The key point is to eval code that defines an anonymous function, as make-factory does. This is slow -- slower than the reflection example above, so only do it as infrequently as possible such as once per class. But having done that you have a regular Clojure function that you can store somewhere, in a var like int-factory in this example, or in a hash-map or vector depending on how you'll be using it. Regardless, this factory function will run at full compiled speed, can be inlined by HotSpot, etc. and will always run much faster than the reflection example.
When you're specifically dealing with classes generated by deftype or defrecord, you can skip the type list since those classes always have exactly two ctors each with different arities. This allows something like:
(defn record-factory [recordname]
(let [recordclass ^Class (resolve (symbol recordname))
max-arg-count (apply max (map #(count (.getParameterTypes %))
(.getConstructors recordclass)))
args (map #(symbol (str "x" %)) (range (- max-arg-count 2)))]
(eval `(fn [~#args] (new ~(symbol recordname) ~#args)))))
(defrecord ExampleRecord [a b c])
(def example-record-factory (record-factory "ExampleRecord"))
(example-record-factory "F." "Scott" 'Fitzgerald)
Since 'new' is a special form, I'm not sure there you can do this without a macro. Here is a way to do it using a macro:
user=> (defmacro str-new [s & args] `(new ~(symbol s) ~#args))
#'user/str-new
user=> (str-new "String" "LOL")
"LOL"
Check out Michal's comment on the limitations of this macro.
Here is a technique for extending defrecord to automatically create well-named constructor functions to construct record instances (either new or based on an existing record).
http://david-mcneil.com/post/765563763/enhanced-clojure-records
In Clojure 1.3, defrecord will automatically defn a factory function using the record name with "->" prepended. Similarly, a variant that takes a map will be the record name prepended with "map->".
user=> (defrecord MyRec [a b])
user.MyRec
user=> (->MyRec 1 "one")
#user.MyRec{:a 1, :b "one"}
user=> (map->MyRec {:a 2})
#user.MyRec{:a 2, :b nil}
A macro like this should work to create an instance from the string name of the record type:
(defmacro newbie [recname & args] `(~(symbol (str "->" recname)) ~#args))