Skip to content

Commit

Permalink
Add reinit!, to reset a form to its initial state
Browse files Browse the repository at this point in the history
  • Loading branch information
plexus committed Oct 12, 2023
1 parent db65508 commit 513505f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
6 changes: 2 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@

## Added

## Fixed

## Changed
- add `reinit!` (since `reset!` was taken), to reset a form to its initial state

# 0.1.4 (2023-09-06 / 85cc0b6)

## Added

- `with-form` / `deform`
- `with-form` / `deform`
19 changes: 14 additions & 5 deletions src/lambdaisland/morf.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,19 @@
formdef)]
[@p form]))

(defprotocol IMorf
(reinit! [r]))

(defn- compute-bindings [binding form placeholders init]
(let [lookup (gensym "lookup")]
(conj (into []
(mapcat (fn [p]
[p `(reagent.core/atom ~(get init p))])
[p `(let [init# ~(get init p)]
(cljs.core/specify! (reagent.core/atom init#)
IMorf
(~'reinit! [this#] (reset! this# init#))))])
placeholders))

lookup
(zipmap
(map (comp keyword str) placeholders)
Expand All @@ -32,10 +39,13 @@
binding
`(cljs.core/specify! (reagent.core/reaction ~form)
cljs.core/ILookup

(~'-lookup
([_# k#] (~'-lookup ~lookup k#))
([_# k# not-found#] (~'-lookup ~lookup k# not-found#)))))))
([_# k# not-found#] (~'-lookup ~lookup k# not-found#)))
IMorf
(~'reinit! [_#]
(doseq [p# ~(into [] placeholders)]
(reinit! p#)))))))

#?(:clj
(defmacro with-form [[binding formdef & {:keys [init]}] & body]
Expand All @@ -49,5 +59,4 @@
(let [[placeholders form] (find-placeholders formdef)]
`(do
~@(for [[bind form] (partition 2 (compute-bindings binding form placeholders init))]
`(def ~bind ~form))
))))
`(def ~bind ~form))))))

0 comments on commit 513505f

Please sign in to comment.