Handle form-2 and form-3 components

This commit is contained in:
Juho Teperi 2020-02-06 00:06:30 +02:00
parent 9042db423f
commit 678e8adf7b
1 changed files with 59 additions and 50 deletions

View File

@ -402,19 +402,34 @@
(defn functional-render [jsprops]
(let [argv (.-argv jsprops)
tag (.-tag jsprops)
res (if util/*non-reactive*
(apply tag argv)
;; Create persistent ID for each rendered functional component,
tag (.-tag jsprops)]
(if util/*non-reactive*
(let [res (apply tag argv)]
(cond
(vector? res) (as-element res)
(ifn? res) (let [f (if (reagent-class? res)
(fn [& args]
(as-element (apply vector res args)))
res)]
(as-element (apply f argv)))
:else res))
(let [;; Create persistent ID for each rendered functional component,
;; this is used to store internal Reagent state, like render
;; reaction etc. in a separate store where changes doesn't
;; trigger render.
(let [[id _] (react/useState (js/Symbol))
[id _] (react/useState (js/Symbol))
;; Use counter to trigger render manually.
[_ update-count] (react/useState 0)
;; This object mimics React Class attributes and methods.
;; To support form-2 components, even the render fn needs to
;; be stored as it is created during the first render,
;; and subsequent renders need to retrieve the created fn.
reagent-state (or (gobj/get fun-component-state id)
;; TODO: Mock state atom?
(let [obj #js {:forceUpdate (fn [] (update-count inc))
:cljsMountOrder (batch/next-mount-count)}]
:cljsMountOrder (batch/next-mount-count)
:renderFn tag}]
(gobj/set fun-component-state id obj)
obj))]
@ -426,35 +441,29 @@
;; Only run effect once on mount and unmount
#js [])
;; Note: it might be possible to mock some React Component
;; methods in the object and use it as *current-component*
;; TODO: If return value is ifn?, consider form-2 component.
(assert-callable tag)
(batch/mark-rendered reagent-state)
;; static-fns :render
(if-let [rat (.-cljsRatom reagent-state)]
(let [res (if-let [rat (.-cljsRatom reagent-state)]
(._run rat false)
(ratom/run-in-reaction
;; Mock Class component API
#(binding [*current-component* reagent-state]
(apply tag argv))
(apply (.-renderFn reagent-state) argv))
reagent-state
"cljsRatom"
batch/queue-render
rat-opts))))]
;; do-render
;; wrap-render
rat-opts))]
(cond
(vector? res) (as-element res)
;; FIXME: Support form-2 components???
; (ifn? res) (let [f (if (reagent-class? res)
; (create-class
; {:reagent-render (fn [& args]
; (as-element (apply vector res args)))})
; res)]
; f)
:else res)))
(ifn? res) (let [;; If original fn returned class (create-class) wrap in fn and call that.
f (if (reagent-class? res)
(fn [& args]
(as-element (apply vector res args)))
res)]
;; Store the returned fn in state, so it will be used in following render calls.
(set! (.-renderFn reagent-state) f)
(as-element (apply f argv)))
:else res))))))