forked from fulcrologic/fulcro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
primitives.cljc
3421 lines (3103 loc) · 155 KB
/
primitives.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(ns fulcro.client.primitives
#?(:cljs (:require-macros fulcro.client.primitives))
(:refer-clojure :exclude #?(:clj [deftype replace var? force]
:cljs [var? key replace force]))
(:require
#?@(:clj [clojure.main
[cljs.core :refer [deftype specify! this-as js-arguments]]
[clojure.reflect :as reflect]
[cljs.util]]
:cljs [[goog.string :as gstring]
[goog.log :as glog]
[goog.object :as gobj]])
[clojure.core.async :as async]
[clojure.set :as set]
[fulcro.history :as hist]
[fulcro.client.logging :as log]
[fulcro.tempid :as tempid]
[fulcro.transit :as transit]
[clojure.zip :as zip]
[fulcro.client.impl.data-targeting :as targeting]
[fulcro.client.impl.protocols :as p]
[fulcro.client.impl.parser :as parser]
[fulcro.util :as util]
[clojure.walk :as walk :refer [prewalk]]
[clojure.string :as str]
[clojure.spec.alpha :as s]
#?(:clj
[clojure.future :refer :all])
[cognitect.transit :as t])
#?(:clj
(:import [java.io Writer])
:cljs (:import [goog.debug Console])))
(declare app-state app-root tempid? normalize-query focus-query* ast->query query->ast transact! remove-root! component?
integrate-ident)
(defprotocol Ident
(ident [this props] "Return the ident for this component"))
(defprotocol IQueryParams
(params [this] "Return the query parameters"))
(defprotocol IQuery
(query [this] "Return the component's unbound static query"))
;; DEPRECATED: Unless someone can give me a compelling case to keep this, I'm dropping it:
(defprotocol ILocalState
(-set-state! [this new-state] "Set the component's local state")
(-get-state [this] "Get the component's local state")
(-get-rendered-state [this] "Get the component's rendered local state")
(-merge-pending-state! [this] "Get the component's pending local state"))
(defprotocol InitialAppState
(initial-state [clz params] "Get the initial state to be used for this component in app state. You are responsible for composing these together."))
(defn has-initial-app-state?
#?(:cljs {:tag boolean})
[component]
#?(:clj (if (fn? component)
(some? (-> component meta :initial-state))
(let [class (cond-> component (component? component) class)]
(extends? InitialAppState class)))
:cljs (implements? InitialAppState component)))
(defn has-ident?
#?(:cljs {:tag boolean})
[component]
#?(:clj (if (fn? component)
(some? (-> component meta :ident))
(let [class (cond-> component (component? component) class)]
(extends? Ident class)))
:cljs (implements? Ident component)))
(defn has-query?
#?(:cljs {:tag boolean})
[component]
#?(:clj (if (fn? component)
(some? (-> component meta :query))
(let [class (cond-> component (component? component) class)]
(extends? IQuery class)))
:cljs (implements? IQuery component)))
(defn has-query-params?
#?(:cljs {:tag boolean})
[component]
#?(:clj (if (fn? component)
(some? (-> component meta :params))
(let [class (cond-> component (component? component) class)]
(extends? IQueryParams class)))
:cljs (implements? IQueryParams component)))
(defn get-initial-state
"Get the initial state of a component. Needed because calling the protocol method from a defui component in clj will not work as expected."
[class params]
#?(:clj (when-let [initial-state (-> class meta :initial-state)]
(initial-state class params))
:cljs (when (implements? InitialAppState class)
(initial-state class params))))
(s/def ::remote keyword?)
(s/def ::ident util/ident?)
(s/def ::query vector?)
(s/def ::transaction (s/every #(or (keyword? %) (util/mutation? %))
:kind vector?))
(s/def ::component-or-reconciler vector?)
(s/def ::pessimistic? boolean?)
(s/def ::tempids (s/map-of tempid? any?))
(defn get-history
"pass-through function for getting history, that enables testing (cannot mock protocols easily)"
[reconciler]
(when reconciler
(p/get-history reconciler)))
(defn add-basis-time* [{:keys [children]} props time]
(if (map? props)
(if (seq children)
(let [children (if (= :union (-> children first :type))
(apply concat (->> children first :children (map :children)))
children)]
(-> (into props
(comp
(filter #(contains? props (:key %)))
(map (fn [{:keys [key query] :as ast}]
(let [x (get props key)
ast (cond-> ast
(= '... query)
(assoc :children children)
(pos-int? query)
(assoc :children (mapv #(cond-> %
(pos-int? (:query %))
(update :query dec))
children)))]
[key
(if (sequential? x)
(mapv #(add-basis-time* ast % time) x)
(add-basis-time* ast x time))]))))
children)
(vary-meta assoc ::time time)))
(vary-meta props assoc ::time time))
props))
(defn add-basis-time
"Recursively add the given basis time to all of the maps in the props. This is part of the UI refresh optimization
algorithm. Children that refresh in isolation could be mis-drawn if a parent subsequently does a re-render without
a query (e.g. local state change). The basis times allow us to detect and avoid that."
([props time]
(prewalk (fn [ele]
(if (map? ele)
(vary-meta ele assoc ::time time)
ele)) props))
([q props time]
(add-basis-time* (query->ast q) props time)))
(defn get-basis-time
"Returns the basis time from the given props, or ::unset if not available."
[props] (or (-> props meta ::time) :unset))
(defn get-current-time
"get the current basis time from the reconciler. Used instead of calling the protocol method `basis-t` to facilitate testing."
[reconciler] (p/basis-t reconciler))
(defn collect-statics
"Collect the static declarations from the defui."
[dt]
(letfn [(split-on-static [forms]
(split-with (complement '#{static}) forms))
(split-on-symbol [forms]
(split-with (complement symbol?) forms))]
(loop [dt (seq dt) dt' [] statics {:fields {} :protocols []}]
(if dt
(let [[pre [_ sym & remaining :as post]] (split-on-static dt)
dt' (into dt' pre)]
(if (seq post)
(cond
(= sym 'field)
(let [[field-info dt] (split-at 2 remaining)]
(recur (seq dt) dt'
(update-in statics [:fields] conj (vec field-info))))
(symbol? sym)
(let [[protocol-info dt] (split-on-symbol remaining)]
(recur (seq dt) dt'
(update-in statics [:protocols]
into (concat [sym] protocol-info))))
:else (throw #?(:clj (IllegalArgumentException. "Malformed static")
:cljs (js/Error. "Malformed static"))))
(recur nil dt' statics)))
{:dt dt' :statics statics}))))
(defn- validate-statics [dt]
(when-let [invalid (some #{"Ident" "IQuery" "IQueryParams"}
(map #(-> % str (str/split #"/") last)
(filter symbol? dt)))]
(throw
#?(:clj (IllegalArgumentException.
(str invalid " protocol declaration must appear with `static`."))
:cljs (js/Error.
(str invalid " protocol declaration must appear with `static`."))))))
(def lifecycle-sigs
'{initLocalState [this]
shouldComponentUpdate [this next-props next-state]
componentWillReceiveProps [this next-props]
componentWillUpdate [this next-props next-state]
componentDidUpdate [this prev-props prev-state]
componentWillMount [this]
componentDidMount [this]
componentWillUnmount [this]
render [this]})
(defn validate-sig [[name sig :as method]]
(let [sig' (get lifecycle-sigs name)]
(assert (= (count sig') (count sig))
(str "Invalid signature for " name " got " sig ", need " sig'))))
#?(:clj
(def reshape-map-clj
{:reshape
{'render
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#]
(binding [fulcro.client.primitives/*reconciler* (fulcro.client.primitives/get-reconciler this#)
fulcro.client.primitives/*depth* (inc (fulcro.client.primitives/depth this#))
fulcro.client.primitives/*shared* (fulcro.client.primitives/shared this#)
fulcro.client.primitives/*instrument* (fulcro.client.primitives/instrument this#)
fulcro.client.primitives/*parent* this#]
(let [ret# (do ~@body)
props# (:props this#)]
(when-not @(:fulcro$mounted? props#)
(swap! (:fulcro$mounted? props#) not))
ret#)))))
'componentWillMount
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#
reconciler# (fulcro.client.primitives/get-reconciler this#)
indexer# (get-in reconciler# [:config :indexer])]
(when-not (nil? indexer#)
(fulcro.client.impl.protocols/index-component! indexer# this#))
~@body)))}
:defaults
`{~'initLocalState
([this#])
~'componentWillMount
([this#]
(let [reconciler# (fulcro.client.primitives/get-reconciler this#)
lifecycle# (get-in reconciler# [:config :lifecycle])
indexer# (get-in reconciler# [:config :indexer])]
(when-not (nil? lifecycle#)
(lifecycle# this# :mount))
(when-not (nil? indexer#)
(fulcro.client.impl.protocols/index-component! indexer# this#))))
~'render
([this#])}}))
(def reshape-map
{:reshape
{'initLocalState
(fn [[name [this :as args] & body]]
`(~name ~args
(let [ret# (do ~@body)]
(cljs.core/js-obj "fulcro$state" ret#))))
'componentWillReceiveProps
(fn [[name [this next-props :as args] & body]]
`(~name [this# next-props#]
(let [~this this#
~next-props (fulcro.client.primitives/-next-props next-props# this#)]
~@body)))
'componentWillUpdate
(fn [[name [this next-props next-state :as args] & body]]
`(~name [this# next-props# next-state#]
(let [~this this#
~next-props (fulcro.client.primitives/-next-props next-props# this#)
~next-state (or (goog.object/get next-state# "fulcro$pendingState")
(goog.object/get next-state# "fulcro$state"))
ret# (do ~@body)]
(when (cljs.core/implements? fulcro.client.primitives/Ident this#)
(let [ident# (fulcro.client.primitives/ident this# (fulcro.client.primitives/props this#))
next-ident# (fulcro.client.primitives/ident this# ~next-props)]
(when (not= ident# next-ident#)
(let [idxr# (get-in (fulcro.client.primitives/get-reconciler this#) [:config :indexer])]
(when-not (nil? idxr#)
(swap! (:indexes idxr#)
(fn [indexes#]
(-> indexes#
(update-in [:ref->components ident#] disj this#)
(update-in [:ref->components next-ident#] (fnil conj #{}) this#)))))))))
(fulcro.client.primitives/merge-pending-props! this#)
(fulcro.client.primitives/merge-pending-state! this#)
ret#)))
'componentDidUpdate
(fn [[name [this prev-props prev-state :as args] & body]]
`(~name [this# prev-props# prev-state#]
(let [~this this#
~prev-props (fulcro.client.primitives/-prev-props prev-props# this#)
~prev-state (goog.object/get prev-state# "fulcro$previousState")]
~@body
(fulcro.client.primitives/clear-prev-props! this#))))
'componentWillMount
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#
reconciler# (fulcro.client.primitives/get-reconciler this#)
indexer# (get-in reconciler# [:config :indexer])]
(when-not (nil? indexer#)
(fulcro.client.impl.protocols/index-component! indexer# this#))
~@body)))
'componentDidMount
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#
reconciler# (fulcro.client.primitives/get-reconciler this#)
lifecycle# (get-in reconciler# [:config :lifecycle])]
(goog.object/set this# "fulcro$mounted" true)
(when-not (nil? lifecycle#)
(lifecycle# this# :mount))
~@body)))
'componentWillUnmount
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#
reconciler# (fulcro.client.primitives/get-reconciler this#)
lifecycle# (get-in reconciler# [:config :lifecycle])
cfg# (:config reconciler#)
st# (:state cfg#)
indexer# (:indexer cfg#)]
(goog.object/set this# "fulcro$mounted" false)
(when (and (not (nil? st#))
(get-in @st# [:fulcro.client.primitives/queries this#]))
(swap! st# update-in [:fulcro.client.primitives/queries] dissoc this#))
(when-not (nil? lifecycle#)
(lifecycle# this# :unmount))
(when-not (nil? indexer#)
(fulcro.client.impl.protocols/drop-component! indexer# this#))
~@body)))
'render
(fn [[name [this :as args] & body]]
`(~name [this#]
(let [~this this#]
(binding [fulcro.client.primitives/*reconciler* (fulcro.client.primitives/get-reconciler this#)
fulcro.client.primitives/*depth* (inc (fulcro.client.primitives/depth this#))
fulcro.client.primitives/*shared* (fulcro.client.primitives/shared this#)
fulcro.client.primitives/*instrument* (fulcro.client.primitives/instrument this#)
fulcro.client.primitives/*parent* this#]
~@body))))}
:defaults
`{~'shouldComponentUpdate
([this# next-props# next-state#]
(let [next-children# (. next-props# -children)
next-props# (goog.object/get next-props# "fulcro$value")
next-props# (cond-> next-props#
(instance? FulcroProps next-props#) unwrap)
current-props# (fulcro.client.primitives/props this#)
; a parent could send in stale props due to a component-local state change..make sure we don't use them. (Props have a timestamp on metadata)
next-props-stale?# (> (get-basis-time current-props#) (get-basis-time next-props#))
props-changed?# (and
(not next-props-stale?#)
(not= current-props# next-props#))
state-changed?# (and (.. this# ~'-state)
(not= (goog.object/get (. this# ~'-state) "fulcro$state")
(goog.object/get next-state# "fulcro$state")))
children-changed?# (not= (.. this# -props -children)
next-children#)]
(or props-changed?# state-changed?# children-changed?#)))
~'componentWillUpdate
([this# next-props# next-state#]
(when (cljs.core/implements? fulcro.client.primitives/Ident this#)
(let [ident# (fulcro.client.primitives/ident this# (fulcro.client.primitives/props this#))
next-ident# (fulcro.client.primitives/ident this# (fulcro.client.primitives/-next-props next-props# this#))]
(when (not= ident# next-ident#)
(let [idxr# (get-in (fulcro.client.primitives/get-reconciler this#) [:config :indexer])]
(when-not (nil? idxr#)
(swap! (:indexes idxr#)
(fn [indexes#]
(-> indexes#
(update-in [:ref->components ident#] disj this#)
(update-in [:ref->components next-ident#] (fnil conj #{}) this#)))))))))
(fulcro.client.primitives/merge-pending-props! this#)
(fulcro.client.primitives/merge-pending-state! this#))
~'componentDidUpdate
([this# prev-props# prev-state#]
(fulcro.client.primitives/clear-prev-props! this#))
~'componentWillMount
([this#]
(let [indexer# (get-in (fulcro.client.primitives/get-reconciler this#) [:config :indexer])]
(when-not (nil? indexer#)
(fulcro.client.impl.protocols/index-component! indexer# this#))))
~'componentDidMount
([this#] (goog.object/set this# "fulcro$mounted" true))
~'componentWillUnmount
([this#]
(let [r# (fulcro.client.primitives/get-reconciler this#)
cfg# (:config r#)
st# (:state cfg#)
indexer# (:indexer cfg#)]
(goog.object/set this# "fulcro$mounted" false)
(when (and (not (nil? st#))
(get-in @st# [:fulcro.client.primitives/queries this#]))
(swap! st# update-in [:fulcro.client.primitives/queries] dissoc this#))
(when-not (nil? indexer#)
(fulcro.client.impl.protocols/drop-component! indexer# this#))))}})
(defn reshape [dt {:keys [reshape defaults]}]
(letfn [(reshape* [x]
(if (and (sequential? x)
(contains? reshape (first x)))
(let [reshapef (get reshape (first x))]
(validate-sig x)
(reshapef x))
x))
(add-defaults-step [ret [name impl]]
(if-not (some #{name} (map first (filter seq? ret)))
(let [[before [p & after]] (split-with (complement '#{Object}) ret)]
(into (conj (vec before) p (cons name impl)) after))
ret))
(add-defaults [dt]
(reduce add-defaults-step dt defaults))
(add-object-protocol [dt]
(if-not (some '#{Object} dt)
(conj dt 'Object)
dt))]
(->> dt (map reshape*) vec add-object-protocol add-defaults)))
#?(:clj
(defn- add-proto-methods* [pprefix type type-sym [f & meths :as form]]
(let [pf (str pprefix (name f))
emit-static (when (-> type-sym meta :static)
`(~'js* "/** @nocollapse */"))]
(if (vector? (first meths))
;; single method case
(let [meth meths]
[`(do
~emit-static
(set! ~(#'cljs.core/extend-prefix type-sym (str pf "$arity$" (count (first meth))))
~(with-meta `(fn ~@(#'cljs.core/adapt-proto-params type meth)) (meta form))))])
(map (fn [[sig & body :as meth]]
`(do
~emit-static
(set! ~(#'cljs.core/extend-prefix type-sym (str pf "$arity$" (count sig)))
~(with-meta `(fn ~(#'cljs.core/adapt-proto-params type meth)) (meta form)))))
meths)))))
#?(:clj (intern 'cljs.core 'add-proto-methods* add-proto-methods*))
#?(:clj
(defn- proto-assign-impls [env resolve type-sym type [p sigs]]
(#'cljs.core/warn-and-update-protocol p type env)
(let [psym (resolve p)
pprefix (#'cljs.core/protocol-prefix psym)
skip-flag (set (-> type-sym meta :skip-protocol-flag))
static? (-> p meta :static)
type-sym (cond-> type-sym
static? (vary-meta assoc :static true))
emit-static (when static?
`(~'js* "/** @nocollapse */"))]
(if (= p 'Object)
(#'cljs.core/add-obj-methods type type-sym sigs)
(concat
(when-not (skip-flag psym)
(let [{:keys [major minor qualifier]} cljs.util/*clojurescript-version*]
(if (and (== major 1) (== minor 9) (>= qualifier 293))
[`(do
~emit-static
(set! ~(#'cljs.core/extend-prefix type-sym pprefix) cljs.core/PROTOCOL_SENTINEL))]
[`(do
~emit-static
(set! ~(#'cljs.core/extend-prefix type-sym pprefix) true))])))
(mapcat
(fn [sig]
(if (= psym 'cljs.core/IFn)
(#'cljs.core/add-ifn-methods type type-sym sig)
(#'cljs.core/add-proto-methods* pprefix type type-sym sig)))
sigs))))))
#?(:clj (intern 'cljs.core 'proto-assign-impls proto-assign-impls))
#?(:clj (defn- extract-static-methods [protocols]
(letfn [(add-protocol-method [existing-methods method]
(let [nm (first method)
new-arity (rest method)
k (keyword nm)
existing-method (get existing-methods k)]
(if existing-method
(let [single-arity? (vector? (second existing-method))
existing-arities (if single-arity?
(list (rest existing-method))
(rest existing-method))]
(assoc existing-methods k (conj existing-arities new-arity 'fn)))
(assoc existing-methods k (list 'fn new-arity)))))]
(when-not (empty? protocols)
(let [result (->> protocols
(filter #(not (symbol? %)))
(reduce
(fn [r impl] (add-protocol-method r impl))
{}))]
(if (contains? result :params)
result
(assoc result :params '(fn [this]))))))))
#?(:clj
(defn defui*-clj [name forms]
(let [docstring (when (string? (first forms))
(first forms))
forms (cond-> forms
docstring rest)
{:keys [dt statics]} (collect-statics forms)
[other-protocols obj-dt] (split-with (complement '#{Object}) dt)
klass-name (symbol (str name "_klass"))
lifecycle-method-names (set (keys lifecycle-sigs))
{obj-dt false non-lifecycle-dt true} (group-by
(fn [x]
(and (sequential? x)
(not (lifecycle-method-names (first x)))))
obj-dt)
class-methods (extract-static-methods (:protocols statics))]
`(do
~(when-not (empty? non-lifecycle-dt)
`(defprotocol ~(symbol (str name "_proto"))
~@(map (fn [[m-name args]] (list m-name args)) non-lifecycle-dt)))
(declare ~name)
(defrecord ~klass-name [~'state ~'refs ~'props ~'children]
;; TODO: non-lifecycle methods defined in the JS prototype - António
fulcro.client.impl.protocols/IReactLifecycle
~@(rest (reshape obj-dt reshape-map-clj))
~@other-protocols
~@(:protocols statics)
~@(when-not (empty? non-lifecycle-dt)
(list* (symbol (str name "_proto"))
non-lifecycle-dt))
fulcro.client.impl.protocols/IReactComponent
(~'-render [this#]
(p/componentWillMount this#)
(p/render this#)))
(defmethod clojure.core/print-method ~(symbol (str (munge *ns*) "." klass-name))
[o# ^Writer w#]
(.write w# (str "#object[" (ns-name *ns*) "/" ~(str name) "]")))
(let [c# (fn ~name [state# refs# props# children#]
(~(symbol (str (munge *ns*) "." klass-name ".")) state# refs# props# children#))]
(def ~(with-meta name
(merge (meta name)
(when docstring
{:doc docstring})))
(with-meta c#
(merge {:component c#
:component-ns (ns-name *ns*)
:component-name ~(str name)}
~class-methods))))))))
(defn defui*
([name form] (defui* name form nil))
([name forms env]
(letfn [(field-set! [obj [field value]]
`(set! (. ~obj ~(symbol (str "-" field))) ~value))]
(let [docstring (when (string? (first forms))
(first forms))
forms (cond-> forms
docstring rest)
{:keys [dt statics]} (collect-statics forms)
_ (validate-statics dt)
fqn (if env
(symbol (-> env :ns :name str) (str name))
name)
ctor `(defn ~(with-meta name
(merge {:jsdoc ["@constructor"]}
(meta name)
(when docstring
{:doc docstring})))
[]
(this-as this#
(.apply js/React.Component this# (js-arguments))
(if-not (nil? (.-initLocalState this#))
(set! (.-state this#) (.initLocalState this#))
(set! (.-state this#) (cljs.core/js-obj)))
this#))
set-react-proto! `(set! (.-prototype ~name)
(goog.object/clone js/React.Component.prototype))
ctor (if (-> name meta :once)
`(when-not (cljs.core/exists? ~name)
~ctor
~set-react-proto!)
`(do
~ctor
~set-react-proto!))
display-name (if env
(str (-> env :ns :name) "/" name)
'js/undefined)]
`(do
~ctor
(specify! (.-prototype ~name) ~@(reshape dt reshape-map))
(set! (.. ~name -prototype -constructor) ~name)
(set! (.. ~name -prototype -constructor -displayName) ~display-name)
(set! (.. ~name -prototype -fulcro$isComponent) true)
~@(map #(field-set! name %) (:fields statics))
(specify! ~name
~@(mapv #(cond-> %
(symbol? %) (vary-meta assoc :static true)) (:protocols statics)))
(specify! (. ~name ~'-prototype) ~@(:protocols statics))
(set! (.-cljs$lang$type ~name) true)
(set! (.-cljs$lang$ctorStr ~name) ~(str fqn))
(set! (.-cljs$lang$ctorPrWriter ~name)
(fn [this# writer# opt#]
(cljs.core/-write writer# ~(str fqn))))
;; TODO: here is where we could emit uses of the statics in a try/catch so the Closure will not collapse them
)))))
(defmacro defui [name & forms]
(if (boolean (:ns &env))
(defui* name forms &env)
#?(:clj (defui*-clj name forms))))
(defmacro ui
[& forms]
(let [t (with-meta (gensym "ui_") {:anonymous true})]
`(do (defui ~t ~@forms) ~t)))
;; =============================================================================
;; Globals & Dynamics
(def ^:private roots (atom {}))
(def ^{:dynamic true} *raf* nil)
(def ^{:dynamic true :private true} *reconciler* nil)
(def ^{:dynamic true :private true} *parent* nil)
(def ^{:dynamic true :private true} *shared* nil)
(def ^{:dynamic true :private true} *instrument* nil)
(def ^{:dynamic true :private true} *depth* 0)
#?(:clj
(defn- munge-component-name [x]
(let [ns-name (-> x meta :component-ns)
cl-name (-> x meta :component-name)]
(munge
(str (str/replace (str ns-name) "." "$") "$" cl-name)))))
#?(:clj
(defn- compute-react-key [cl props]
(when-let [idx (-> props meta :om-path)]
(str (munge-component-name cl) "_" idx))))
#?(:cljs
(defn- compute-react-key [cl props]
(if-let [rk (:react-key props)]
rk
(if-let [idx (-> props meta :om-path)]
(str (. cl -name) "_" idx)
js/undefined))))
(defn component?
"Returns true if the argument is a component."
#?(:cljs {:tag boolean})
[x]
(if-not (nil? x)
#?(:clj (or (instance? fulcro.client.impl.protocols.IReactComponent x)
(satisfies? p/IReactComponent x))
:cljs (true? (. x -fulcro$isComponent)))
false))
#?(:clj
(defn react-type
"Returns the component type, regardless of whether the component has been
mounted"
[component]
{:pre [(component? component)]}
(let [[klass-name] (str/split (reflect/typename (type component)) #"_klass")
last-idx-dot (.lastIndexOf klass-name ".")
ns (clojure.main/demunge (subs klass-name 0 last-idx-dot))
c (subs klass-name (inc last-idx-dot))]
@(or (find-var (symbol ns c))
(find-var (symbol ns (clojure.main/demunge c)))))))
#?(:cljs
(defn react-type
"Returns the component type, regardless of whether the component has been
mounted"
[x]
(or (gobj/get x "type") (type x))))
(defn- state [c]
{:pre [(component? c)]}
(.-state c))
(defn- get-prop
"PRIVATE: Do not use"
[c k]
#?(:clj (get (:props c) k)
:cljs (gobj/get (.-props c) k)))
#?(:cljs (deftype ^:private FulcroProps [props basis-t]))
#?(:cljs
(defn- om-props [props basis-t]
(FulcroProps. props basis-t)))
#?(:cljs
(defn- om-props-basis [om-props]
(.-basis-t om-props)))
#?(:cljs (def ^:private nil-props (om-props nil -1)))
#?(:cljs
(defn- get-props*
[x k]
(if (nil? x)
nil-props
(let [y (gobj/get x k)]
(if (nil? y)
nil-props
y)))))
#?(:cljs
(defn- get-prev-props [x]
(get-props* x "fulcro$prev$value")))
#?(:cljs
(defn- get-next-props [x]
(get-props* x "fulcro$next$value")))
#?(:cljs
(defn- get-props [x]
(get-props* x "fulcro$value")))
#?(:cljs
(defn- set-prop!
"PRIVATE: Do not use"
[c k v]
(gobj/set (.-props c) k v)))
(defn reconciler?
"Returns true if x is a reconciler."
#?(:cljs {:tag boolean})
[x]
#?(:cljs (implements? p/IReconciler x)
:clj (or (instance? p/IReconciler x)
(satisfies? p/IReconciler x))))
(defn get-indexer
"PRIVATE: Get the indexer associated with the reconciler."
[reconciler]
{:pre [(reconciler? reconciler)]}
(-> reconciler :config :indexer))
(defn- sift-idents [res]
(let [{idents true rest false} (group-by #(vector? (first %)) res)]
[(into {} idents) (into {} rest)]))
(defn get-reconciler
[c]
{:pre [(component? c)]}
(get-prop c #?(:clj :fulcro$reconciler
:cljs "fulcro$reconciler")))
#?(:cljs
(defn- unwrap [om-props]
(.-props om-props)))
#?(:cljs
(defn- props*
([x y]
(max-key om-props-basis x y))
([x y z]
(max-key om-props-basis x (props* y z)))))
#?(:cljs
(defn- prev-props*
([x y]
(min-key om-props-basis x y))
([x y z]
(min-key om-props-basis
(props* x y) (props* y z)))))
#?(:cljs
(defn -prev-props [prev-props component]
(let [cst (.-state component)
props (.-props component)]
(unwrap
(prev-props*
(props* (get-props prev-props) (get-prev-props cst))
(props* (get-props cst) (get-props props)))))))
#?(:cljs
(defn -next-props [next-props component]
(unwrap
(props*
(-> component .-props get-props)
(get-props next-props)
(-> component .-state get-next-props)))))
#?(:cljs
(defn- merge-pending-props! [c]
{:pre [(component? c)]}
(let [cst (. c -state)
props (.-props c)
pending (gobj/get cst "fulcro$next$value")
prev (props* (get-props cst) (get-props props))]
(gobj/set cst "fulcro$prev$value" prev)
(when-not (nil? pending)
(gobj/remove cst "fulcro$next$value")
(gobj/set cst "fulcro$value" pending)))))
#?(:cljs
(defn- clear-prev-props! [c]
(gobj/remove (.-state c) "fulcro$prev$value")))
#?(:cljs
(defn- t
"Get basis t value for when the component last read its props from
the global state."
[c]
(om-props-basis
(props*
(-> c .-props get-props)
(-> c .-state get-props)))))
(defn- parent
"Returns the parent component."
[component]
(get-prop component #?(:clj :fulcro$parent
:cljs "fulcro$parent")))
(defn depth
"PRIVATE: Returns the render depth (a integer) of the component relative to
the mount root."
[component]
(when (component? component)
(get-prop component #?(:clj :fulcro$depth
:cljs "fulcro$depth"))))
(defn react-key
"Returns the components React key."
[component]
(get-prop component #?(:clj :fulcro$reactKey
:cljs "fulcro$reactKey")))
#?(:clj
(defn props [component]
{:pre [(component? component)]}
(:fulcro$value (:props component))))
#?(:cljs
(defn props
"Return a components props."
[component]
{:pre [(component? component)]}
;; When force updating we write temporarily props into state to avoid bogus
;; complaints from React. We record the basis T of the reconciler to determine
;; if the props recorded into state are more recent - props will get updated
;; when React actually re-renders the component.
(unwrap
(props*
(-> component .-props get-props)
(-> component .-state get-props)))))
#?(:clj
(defn init-local-state [component]
(reset! (:state component) (.initLocalState component))))
(defn get-state
"Get a component's local state. May provide a single key or a sequential
collection of keys for indexed access into the component's local state."
([component]
(get-state component []))
([component k-or-ks]
{:pre [(component? component)]}
(let [cst (if #?(:clj (satisfies? ILocalState component)
:cljs (implements? ILocalState component))
(-get-state component)
#?(:clj @(:state component)
:cljs (when-let [state (. component -state)]
(or (gobj/get state "fulcro$pendingState")
(gobj/get state "fulcro$state")))))]
(get-in cst (if (sequential? k-or-ks) k-or-ks [k-or-ks])))))
(defn- get-static-query
"Get the statically-declared query of IQuery from a given class."
[c]
{:pre (has-query? c)}
#?(:clj ((-> c meta :query) c) :cljs (query c)))
(defn some-hasquery?
"Returns true if the given component or one of its parents has a query."
[c]
(loop [c c]
(cond
(nil? c) false
(has-query? c) true
:else (recur (parent c)))))
(defn get-ident
"Given a mounted component with assigned props, return the ident for the
component. 2-arity version works on client or server using a component and
explicit props."
([x]
{:pre [(component? x)]}
(let [m (props x)]
(assert (not (nil? m)) "get-ident invoked on component with nil props")
(ident x m)))
([class props]
#?(:clj (when-let [ident (-> class meta :ident)]
(ident class props))
:cljs (when (implements? Ident class)
(ident class props)))))
(defn- var? [x]
(and (symbol? x)
#?(:clj (.startsWith (str x) "?")
:cljs (gstring/startsWith (str x) "?"))))
(defn- var->keyword [x]
(keyword (.substring (str x) 1)))
(defn- replace-var [expr params]
(if (var? expr)
(get params (var->keyword expr) expr)
expr))
(defn- bind-query [query params]
(let [qm (meta query)
tr (map #(bind-query % params))
ret (cond
(seq? query) (apply list (into [] tr query))
#?@(:clj [(instance? clojure.lang.IMapEntry query) (into [] tr query)])
(coll? query) (into (empty query) tr query)
:else (replace-var query params))]
(cond-> ret
(and qm #?(:clj (instance? clojure.lang.IObj ret)
:cljs (satisfies? IMeta ret)))
(with-meta qm))))
(defn query-id
"Returns a string ID for the query of the given class with qualifier"
[class qualifier]
(if (nil? class)
(log/error "Query ID received no class (if you see this warning, it probably means metadata was lost on your query)" (ex-info "" {}))
(when-let [classname #?(:clj (-> (str (-> class meta :component-ns) "." (-> class meta :component-name))
(str/replace "." "$")
(str/replace "-" "_"))
:cljs (.-name class))]
(str classname (when qualifier (str "$" qualifier))))))
#?(:clj
(defn factory
"Create a factory constructor from a component class created with
fulcro.client.primitives/defui."
([class]
(factory class nil))
([class {:keys [validator keyfn instrument? qualifier]
:or {instrument? true} :as opts}]
{:pre [(fn? class)]}
(with-meta
(fn element-factory
([] (element-factory nil))
([props & children]
(when-not (nil? validator)
(assert (validator props)))
(if (and *instrument* (var-get *instrument*) instrument?)
(*instrument*
{:props props
:children children
:class class
:factory (factory class (assoc opts :instrument? false))})
(let [react-key (cond
(some? keyfn) (keyfn props)
(some? (:react-key props)) (:react-key props)
:else (compute-react-key class props))
ctor class
ref (:ref props)
props {:fulcro$reactRef ref
:fulcro$reactKey react-key
:fulcro$value (cond-> props
(map? props) (dissoc :ref))
:fulcro$queryid (query-id class qualifier)
:fulcro$mounted? (atom false)
:fulcro$path (-> props meta :om-path)
:fulcro$reconciler *reconciler*
:fulcro$parent *parent*
:fulcro$shared *shared*
:fulcro$instrument *instrument*
:fulcro$depth *depth*}
component (ctor (atom nil) (atom nil) props children)]
(when ref
(assert (some? *parent*))
(swap! (:refs *parent*) assoc ref component))
(init-local-state component)
component))))
{:class class
:queryid (query-id class qualifier)
:qualifier qualifier}))))
#?(:cljs
(defn create-element [class props children]