-
-
Notifications
You must be signed in to change notification settings - Fork 137
/
primitives.cljc
3466 lines (3139 loc) · 166 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.async.Throttle]
[cljsjs.react]
[goog.object :as gobj]])
#?(:clj
[cljs.analyzer :as ana])
fulcro-css.css-protocols
fulcro-css.css-implementation
[clojure.core.async :as async]
[clojure.set :as set]
[fulcro.history :as hist]
[fulcro.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.client.network :as net]
[fulcro.util :as util]
[clojure.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])))
(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 IQuery
(query [this] "Return the component's unbound static query"))
(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 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]
(some->
#?(:clj (when-let [initial-state (-> class meta :initial-state)]
(initial-state class params))
:cljs (when (implements? InitialAppState class)
(initial-state class params)))
(with-meta {:computed true})))
(defn computed-initial-state?
"Returns true if the given initial state was computed from a call to get-initial-state."
[s]
(and (map? s) (some-> s meta :computed)))
(s/def ::remote keyword?)
(s/def ::ident (s/or :missing nil? :ident util/ident?))
(s/def ::query vector?)
(s/def ::transaction (s/every #(or (keyword? %) (util/mutation? %))
:kind 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 get-network-activity
""
[reconciler]
(when reconciler
(p/get-network-activity 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"}
(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`."))))))
#?(:clj
(def lifecycle-sigs
'{initLocalState [this]
shouldComponentUpdate [this next-props next-state]
componentWillReceiveProps [this next-props]
componentWillUpdate [this next-props next-state]
;; TODO: snapshot
componentDidUpdate [this prev-props prev-state]
componentWillMount [this]
componentDidMount [this]
componentWillUnmount [this]
render [this]
;; react 16
componentDidCatch [this error info]
UNSAFE_componentWillReceiveProps [this next-props]
UNSAFE_componentWillUpdate [this next-props next-state]
UNSAFE_componentWillMount [this]
getSnapshotBeforeUpdate [this prev-props prev-state]}))
#?(:clj
(defn- validate-sig [[name sig :as method]]
(let [required-signature (get lifecycle-sigs name)]
(assert
(<= (count required-signature) (count sig)) ; allow additional arg (context or snapshot)
(str "Invalid signature for " name " got " sig ", need " required-signature)))))
#?(: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#)))))
'componentDidMount
(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#])}}))
#?(:clj
(let [will-receive-props (fn [[name [this next-props :as args] & body]]
`(~name [this# next-props#]
(let [~this this#
~next-props (goog.object/get next-props# "fulcro$value")]
~@body)))
will-update (fn [[name [this next-props next-state :as args] & body]]
`(~name [this# next-props# next-state#]
(let [~this this#
~next-props (goog.object/get next-props# "fulcro$value")
~next-state (goog.object/get next-state# "fulcro$state")]
~@body)))]
(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 will-receive-props
'UNSAFE_componentWillReceiveProps will-receive-props
'componentWillUpdate will-update
'UNSAFE_componentWillUpdate will-update
'componentDidUpdate (fn [[name [this prev-props prev-state & optional :as args] & body]]
(let [snapshot-sym (if (symbol? (first optional)) (first optional) (gensym "snapshot"))]
`(~name [this# prev-props# prev-state# snapshot#]
(let [~this this#
~snapshot-sym snapshot#
~prev-props (goog.object/get prev-props# "fulcro$value")
~prev-state (goog.object/get prev-state# "fulcro$state")]
(when (cljs.core/implements? fulcro.client.primitives/Ident this#)
(let [ident# (fulcro.client.primitives/ident this# ~prev-props)
next-ident# (fulcro.client.primitives/ident this# (fulcro.client.primitives/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#)))))))))
~@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])
indexer# (get-in reconciler# [:config :indexer])]
(goog.object/set this# "fulcro$mounted" true)
(when-not (nil? indexer#)
(fulcro.client.impl.protocols/index-component! indexer# this#))
(when 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 lifecycle#
(lifecycle# this# :unmount))
(when indexer#
(fulcro.client.impl.protocols/drop-component! indexer# this#))
~@body)))
'shouldComponentUpdate (fn [[name [this next-props next-state :as args] & body]]
`(~name [this# next-props# next-state#]
(let [~this this#
~next-props (goog.object/get next-props# "fulcro$value")
~next-state (goog.object/get next-state# "fulcro$state")]
~@body)))
'getSnapshotBeforeUpdate (fn [[name [this prev-props prev-state :as args] & body]]
`(~name [this# prev-props# prev-state#]
(let [~this this#
~prev-props (goog.object/get prev-props# "fulcro$value")
~prev-state (goog.object/get prev-state# "fulcro$state")]
~@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))))}})))
#?(:clj
(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 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]))))))))
;; =============================================================================
;; Globals & Dynamics
(def roots (atom {}))
(def ^{:dynamic true} *raf* nil)
(def ^{:dynamic true} *reconciler* nil)
(def ^{:dynamic true} *parent* nil)
(def ^{:dynamic true} *blindly-render* false) ; when true: shouldComponentUpdate will return true even if their data/state hasn't changed
(def ^{:dynamic true} *shared* nil)
(def ^{:dynamic true} *instrument* nil)
(def ^{:dynamic 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 ::parser/data-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 ::parser/data-path)]
(str (. cl -name) "_" idx)
js/undefined))))
(defn component?
"Returns true if the argument is a component. A component is defined as a *mounted React-based javascript component*.
This function returns false for component classes, and also returns false for the output of a Fulcro component factory."
#?(:cljs {:tag boolean})
[x]
(if-not (nil? x)
#?(:clj (or (instance? fulcro.client.impl.protocols.IReactComponent x)
(satisfies? p/IReactComponent x))
:cljs (true? (.-fulcro$isComponent ^js x)))
false))
(s/def ::component
(s/with-gen component? #(s/gen #?(:clj #{(reify p/IReactComponent (-render [_]))}
:cljs #{#js {:fulcro$isComponent true}}))))
(defn component-class?
"Returns true if the given `x` is a `defsc` or `defui` component class definition."
[x]
(boolean
#?(:clj (and x
(fn? x)
(some-> x meta :component))
:cljs (true? (some-> ^js x (.-prototype) .-fulcro$isComponent)))))
(s/def ::component-class
(s/with-gen component-class? #(s/gen #?(:clj #{(with-meta {} {:component true})}
:cljs #{#js {:prototype #js {:fulcro$isComponent true}}}))))
#?(: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-raw-react-prop
"PRIVATE: Do not use. GET a RAW react prop"
[c k]
#?(:clj (get (:props c) k)
:cljs (gobj/get (.-props c) k)))
(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-raw-react-prop c #?(:clj :fulcro$reconciler
:cljs "fulcro$reconciler")))
(defn- parent
"Returns the parent component."
[component]
(get-raw-react-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-raw-react-prop component #?(:clj :fulcro$depth
:cljs "fulcro$depth"))))
(defn react-key
"Returns the components React key."
[component]
(get-raw-react-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)]}
(gobj/get (.-props component) "fulcro$value")))
#?(: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 #?(:clj @(:state component)
:cljs (when-let [state (. component -state)] (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
"Get the ident for a mounted component OR using a component class.
That arity-2 will return the ident using the supplied props map.
The single-arity version should only be used with a mounted component (e.g. `this` from `render`), and will derive the
props that were sent to it most recently."
([x]
{:pre [(component? x)]}
(if-let [m (props x)]
(ident x m)
(log/warn "get-ident was invoked on component with nil props (this could mean it wasn't yet mounted): " x)))
([class props]
#?(:clj (if-let [ident (if (component? class)
ident
(-> class meta :ident))]
(let [id (ident class props)]
(if-not (util/ident? id)
(log/warn "get-ident returned an invalid ident for class:" class))
(if (= ::not-found (second id)) [(first id) nil] id))
(log/warn "get-ident called with something that is either not a class or does not implement ident: " class))
:cljs (if (implements? Ident class)
(let [id (ident class props)]
(if-not (util/ident? id)
(log/warn "get-ident returned an invalid ident for class:" class))
(if (= ::not-found (second id)) [(first id) nil] id))
(log/warn "get-ident called with something that is either not a class or does not implement ident: " class)))))
(defn component-name
"Returns a string version of the given react component's name."
[class]
#?(:clj (str (-> class meta :component-ns) "/" (-> class meta :component-name))
:cljs (.-displayName class)))
(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 (component-name class)]
(str classname (when qualifier (str "$" qualifier))))))
#?(:clj
(defn- is-element? [e]
(or
(instance? fulcro.client.impl.protocols.IReactComponent e)
(instance? fulcro.client.impl.protocols.IReactDOMElement e)
(satisfies? p/IReactComponent e)
(satisfies? p/IReactDOMElement e))))
#?(:clj
(defn fragment [& args]
(let [children (if (is-element? (first args)) args (rest args))]
(vec children))))
#?(:cljs
(defn fragment
"Wraps children in a React.Fragment. Props are optional, like normal DOM elements."
[& args]
(let [[props children] (if (map? (first args))
[(first args) (rest args)]
[#js {} args])]
(apply js/React.createElement js/React.Fragment (clj->js props) children))))
#?(: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$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]
(apply js/React.createElement class props children)))
#?(:cljs
(defn factory
"Create a factory constructor from a component class created with
defui."
([class] (factory class nil))
([class {:keys [validator keyfn instrument? qualifier]
:or {instrument? true} :as opts}]
{:pre [(fn? class)]}
(with-meta
(fn element-factory [props & children]
(when-not (nil? validator)
(assert (validator props)))
(if (and *instrument* instrument?)
(*instrument*
{:props props
:children children
:class class
:factory (factory class (assoc opts :instrument? false))})
(let [key (if-not (nil? keyfn)
(keyfn props)
(compute-react-key class props))
ref (:ref props)
ref (cond-> ref (keyword? ref) str)]
(create-element class
#js {:key key
:ref ref
:fulcro$reactKey key
:fulcro$value props
:fulcro$queryid (query-id class qualifier)
:fulcro$reconciler *reconciler*
:fulcro$parent *parent*
:fulcro$shared *shared*
:fulcro$instrument *instrument*
:fulcro$depth *depth*}
(or (util/force-children children) [])))))
{:class class
:queryid (query-id class qualifier)
:qualifier qualifier}))))
(defn denormalize-query
"Takes a state map that may contain normalized queries and a query ID. Returns the stored query or nil."
[state-map ID]
(let [get-stored-query (fn [id] (get-in state-map [::queries id :query]))]
(when-let [normalized-query (get-stored-query ID)]
(prewalk (fn [ele]
(if-let [q (and (string? ele) (get-stored-query ele))]
q
ele)) normalized-query))))
(defn get-query-by-id [state-map class queryid]
(let [query (or (denormalize-query state-map queryid) (get-static-query class))]
(with-meta query {:component class
:queryid queryid})))
(defn is-factory?
[class-or-factory]
(and (fn? class-or-factory)
(-> class-or-factory meta (contains? :qualifier))))
(def ^{:dynamic true :private true} *query-state* {})
(defn- get-query-id
"Get the query id that is cached in the component's props."
[component]
{:pre [(component? component)]}
(get-raw-react-prop component #?(:clj :fulcro$queryid
:cljs "fulcro$queryid")))
(defn get-query
"Get the query for the given class or factory. If called without a state map, then you'll get the declared static
query of the class. If a state map is supplied, then the dynamically set queries in that state will result in
the current dynamically-set query according to that state."
([class-or-factory] (get-query class-or-factory *query-state*))
([class-or-factory state-map]
(binding [*query-state* state-map]
(let [class (cond
(is-factory? class-or-factory) (-> class-or-factory meta :class)
(component? class-or-factory) (react-type class-or-factory)
:else class-or-factory)
qualifier (if (is-factory? class-or-factory)
(-> class-or-factory meta :qualifier)
nil)
queryid (if (component? class-or-factory)
(get-query-id class-or-factory)
(query-id class qualifier))]
(when (and class (has-query? class))
(get-query-by-id state-map class queryid))))))
(defn link-element [element]
(prewalk (fn link-element-helper [ele]
(let [{:keys [queryid]} (meta ele)]
(if queryid queryid ele))) element))
(defn deep-merge [& xs]
"Merges nested maps without overwriting existing keys."
(if (every? map? xs)
(apply merge-with deep-merge xs)
(last xs)))
(defn normalize-query-elements
"Determines if there are query elements in the present query that need to be normalized as well. If so, it does so.
Returns the new state map."
[state-map query]
(reduce (fn normalize-query-elements-reducer [state ele]
(let [parameterized? (seq? ele) ; not using list? because it could show up as a lazyseq
raw-element (if parameterized? (first ele) ele)]
(cond
(util/union? raw-element) (let [union-alternates (first (vals raw-element))
union-meta (-> union-alternates meta)
normalized-union-alternates (-> (into {} (map link-element union-alternates))
(with-meta union-meta))
union-query-id (-> union-alternates meta :queryid)]
(assert union-query-id "Union query has an ID. Did you use extended get-query?")
(deep-merge
{::queries {union-query-id {:query normalized-union-alternates
:id union-query-id}}}
(reduce (fn normalize-union-reducer [s [_ subquery]]
(normalize-query s subquery)) state union-alternates)))
(util/join? raw-element) (normalize-query state (util/join-value raw-element))
:else state)))
state-map query))
(defn link-query
"Find all of the elements (only at the top level) of the given query and replace them
with their query ID"
[query]
(let [metadata (meta query)]
(with-meta
(mapv link-element query)
metadata)))
(defn normalize-query
"Given a state map and a query, returns a state map with the query normalized into the database. Query fragments
that already appear in the state will not be added. "
[state-map query]
(let [new-state (normalize-query-elements state-map query)
new-state (if (nil? (::queries new-state))
(assoc new-state ::queries {})
new-state)
top-query (link-query query)]
(if-let [queryid (some-> query meta :queryid)]
(deep-merge {::queries {queryid {:query top-query :id queryid}}} new-state)
new-state)))
(defn set-query*
"Put a query in app state.
NOTE: Indexes must be rebuilt after setting a query, so this function should primarily be used to build
up an initial app state."
[state-map class-or-factory {:keys [query] :as args}]
(let [queryid (cond
(nil? class-or-factory)
nil
(some-> class-or-factory meta (contains? :queryid))
(some-> class-or-factory meta :queryid)
:otherwise (query-id class-or-factory nil))
component (or (-> class-or-factory meta :class) class-or-factory)
setq* (fn [state]
(normalize-query
(update state ::queries dissoc queryid)
(vary-meta query assoc :queryid queryid :component component)))]
(if (string? queryid)
(cond-> state-map
(contains? args :query) (setq*))
(do
(log/error "Set query failed. There was no query ID. Use a class or factory for the second argument.")
state-map))))
(defn gather-keys
"Gather the keys that would be considered part of the refresh set for the given query.
E.g. [:a {:j [:b]} {:u {:x [:l] :y [:k]}}] ==> #{:a :j :u}"
[query]
(cond
(vector? query) (reduce (fn gather-keys-reducer [rv e]
(cond
(keyword? e) (conj rv e)
(and (util/ident? e) (= '_ (second e))) (conj rv (first e))
(and (list? e) (keyword? (first e))) (conj rv (first e))
(and (util/join? e) (util/ident? (util/join-key e)) (= '_ (-> e util/join-key second))) (conj rv (first (util/join-key e)))
(and (util/join? e) (keyword? (util/join-key e))) (conj rv (util/join-key e))
:else rv))
#{} query)
(map? query) (-> query keys set) ; a union component, which has a map for a query
:else #{}))
(defn- normalize* [query data refs union-seen]
(cond
(= '[*] query) data
;; union case
(map? query)
(let [class (-> query meta :component)
ident #?(:clj (when-let [ident (-> class meta :ident)]
(ident class data))
:cljs (when (implements? Ident class)
(get-ident class data)))]
(if-not (nil? ident)
(vary-meta (normalize* (get query (first ident)) data refs union-seen)
assoc ::tag (first ident)) ; FIXME: What is tag for?
(throw #?(:clj (IllegalArgumentException. "Union components must implement Ident")
:cljs (js/Error. "Union components must implement Ident")))))
(vector? data) data ;; already normalized
:else
(loop [q (seq query) ret data]
(if-not (nil? q)
(let [expr (first q)]
(if (util/join? expr)
(let [[k sel] (util/join-entry expr)
recursive? (util/recursion? sel)
union-entry (if (util/union? expr) sel union-seen)
sel (if recursive?
(if-not (nil? union-seen)
union-seen
query)
sel)
class (-> sel meta :component)
v (get data k)]
(cond
;; graph loop: db->tree leaves ident in place
(and recursive? (util/ident? v)) (recur (next q) ret)
;; normalize one
(map? v)
(let [x (normalize* sel v refs union-entry)]
(if-not (or (nil? class) (not #?(:clj (-> class meta :ident)
:cljs (implements? Ident class))))
(let [i #?(:clj ((-> class meta :ident) class v)
:cljs (get-ident class v))]
(swap! refs update-in [(first i) (second i)] merge x)
(recur (next q) (assoc ret k i)))
(recur (next q) (assoc ret k x))))
;; normalize many
(vector? v)
(let [xs (into [] (map #(normalize* sel % refs union-entry)) v)]
(if-not (or (nil? class) (not #?(:clj (-> class meta :ident)
:cljs (implements? Ident class))))
(let [is (into [] (map #?(:clj #((-> class meta :ident) class %)
:cljs #(get-ident class %))) xs)]
(if (vector? sel)
(when-not (empty? is)
(swap! refs
(fn [refs]
(reduce (fn [m [i x]]
(update-in m i merge x))
refs (zipmap is xs)))))
;; union case
(swap! refs
(fn [refs']
(reduce
(fn [ret [i x]]
(update-in ret i merge x))
refs' (map vector is xs)))))
(recur (next q) (assoc ret k is)))
(recur (next q) (assoc ret k xs))))
;; missing key
(nil? v)
(recur (next q) ret)
;; can't handle
:else (recur (next q) (assoc ret k v))))
(let [k (if (seq? expr) (first expr) expr)
v (get data k)]
(if (nil? v)
(recur (next q) ret)
(recur (next q) (assoc ret k v))))))
ret))))
(defn tree->db
"Given a component class or instance and a tree of data, use the component's
query to transform the tree into the default database format. All nodes that
can be mapped via Ident implementations wil be replaced with ident links. The
original node data will be moved into tables indexed by ident. If merge-idents
option is true, will return these tables in the result instead of as metadata."
([x data]
(tree->db x data false))
([x data #?(:clj merge-idents :cljs ^boolean merge-idents)]
(let [refs (atom {})
x (if (vector? x) x (get-query x data))
ret (normalize* x data refs nil)]
(if merge-idents
(let [refs' @refs] (merge ret refs'))
(with-meta ret @refs)))))
(defn- focused-join [expr ks full-expr union-expr]
(let [expr-meta (meta expr)
expr' (cond
(map? expr)
(let [join-value (-> expr first second)
join-value (if (and (util/recursion? join-value)
(seq ks))
(if-not (nil? union-expr)
union-expr
full-expr)
join-value)]
{(ffirst expr) (focus-query* join-value ks nil)})
(seq? expr) (list (focused-join (first expr) ks nil nil) (second expr))