-
Notifications
You must be signed in to change notification settings - Fork 990
/
Copy pathfast_image.cljs
79 lines (73 loc) · 2.7 KB
/
fast_image.cljs
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
(ns react-native.fast-image
(:require
["react-native-fast-image" :as FastImage]
[clojure.string :as string]
[react-native.core :as rn]
[reagent.core :as reagent]
[utils.transforms :as transforms]))
(defn- build-source
[source]
(if (string? source)
{:uri source
:priority :high}
source))
(defn- remove-port
[source]
(cond
(string? source) (string/replace-first source #":\d+" "")
(:uri source) (some-> source
:uri
(string/replace-first #":\d+" ""))
:else source))
(defn- placeholder
[{:keys [style fallback-content error? loaded?]}]
[rn/view
{:style (assoc style
:flex 1
:justify-content :center
:align-items :center)}
(cond
(and error? fallback-content) fallback-content
error? [rn/text "X"]
(not loaded?) [rn/activity-indicator {:animating true}])])
;; We cannot use hooks since `reactify-component` seems to ignore the functional compiler
(defn- internal-fast-image
[_]
(let [loaded? (reagent/atom false)
error? (reagent/atom false)
on-image-error (fn [event on-error]
(when (fn? on-error) (on-error event))
(reset! error? true))
on-image-loaded (fn [event on-load]
(when (fn? on-load) (on-load event))
(reset! loaded? true)
(reset! error? false))]
(fn [{:keys [source fallback-content on-error on-load] :as props}]
[:> FastImage
(assoc props
:source (build-source source)
:on-error #(on-image-error % on-error)
:on-load #(on-image-loaded % on-load))
(when (or @error? (not @loaded?))
[placeholder
{:style (js->clj (:style props))
:fallback-content fallback-content
:error? @error?
:loaded? @loaded?}])])))
(defn- compare-props
[old-props new-props]
(let [old-props-clj (transforms/js->clj old-props)
new-props-clj (transforms/js->clj new-props)
old-source (some-> old-props-clj
:source
remove-port)
new-source (some-> new-props-clj
:source
remove-port)]
(and (= old-source new-source)
(= (dissoc old-props-clj :source) (dissoc new-props-clj :source)))))
(def fast-image
(-> internal-fast-image
(reagent/reactify-component)
(rn/memo compare-props)
(reagent/adapt-react-class)))