-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathv2.cljs
More file actions
517 lines (427 loc) · 14.3 KB
/
v2.cljs
File metadata and controls
517 lines (427 loc) · 14.3 KB
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
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;;
;; Copyright (c) Andrey Antukh <niwi@niwi.nz>
(ns rumext.v2
(:refer-clojure :exclude [ref deref use])
(:require-macros [rumext.v2 :refer [defc fnc]])
(:require
["react" :as react]
["react-dom" :as rdom]
["react-dom/client" :as rdomc]
["react/jsx-runtime" :as jsxrt]
[cljs.core :as c]
[goog.functions :as gf]
[rumext.v2.util :as util]
[rumext.v2.validation]
[shadow.lazy]))
(def ^:const undefined (js* "(void 0)"))
(def browser-context?
"A boolean var, indicates if the current code is running on browser main thread or not."
(exists? js/window))
(def Component
"The `react.Component` class"
react/Component)
(def Fragment
"The `react.Fragment class"
react/Fragment)
(def Profiler
"The `react.Profiler` class"
react/Profiler)
(def Suspense
"The `react.Suspense` class"
react/Suspense)
(extend-type cljs.core.UUID
INamed
(-name [this] (js* "\"\" + ~{}" this))
(-namespace [_] ""))
(def ^:no-doc ^function jsx jsxrt/jsx)
(def ^:no-doc ^function jsxs jsxrt/jsxs)
(defn merge-props
[props1 props2]
(js/Object.assign #js {} props1 props2))
(def ^function forward-ref
"lets your component expose a DOM node to parent component with a ref."
react/forwardRef)
;; --- Main Api
(def ^function portal
"Render `element` in a DOM `node` that is ouside of current DOM hierarchy."
rdom/createPortal)
(def ^function create-root
"Creates react root"
rdomc/createRoot)
(def hydrate-root
"Lets you display React components inside a browser DOM node whose
HTML content was previously generated by react-dom/server"
rdomc/hydrateRoot)
(defn render!
[root element]
(.render ^js root element))
(defn unmount!
"Removes component from the DOM tree."
[root]
(.unmount ^js root))
(def ^function create-ref react/createRef)
(defn ref-val
"Given state and ref handle, returns React component."
[ref]
(unchecked-get ref "current"))
(defn set-ref-val!
[ref val]
(unchecked-set ref "current" val)
val)
(def ^function lazy
"A helper for creating lazy loading components."
react/lazy)
;; --- Context API
(def ^function create-context
"Create a react context"
react/createContext)
(defn provider
"Get the current provider for specified context"
[ctx]
(unchecked-get ctx "Provider"))
;; --- Raw Hooks
(def ^function useId
"The `react.useId` hook function"
react/useId)
(def ^function useRef
"The `react.useRef` hook function"
react/useRef)
(def ^function useState
"The `react.useState` hook function"
react/useState)
(def ^function useEffect
"The `react.useEffect` hook function"
react/useEffect)
(def ^function useEffectEvent
"The `react.useEffectEvent` hook function"
react/useEffectEvent)
(def ^function useInsertionEffect
"The react.useInsertionEffect` hook function"
react/useInsertionEffect)
(def ^function useLayoutEffect
"The `react.useLayoutEffect` hook function"
react/useLayoutEffect)
(def ^function useDeferredValue
"The `react.useDeferredValue hook function"
react/useDeferredValue)
(def ^function useMemo
"The `react.useMemo` hook function"
react/useMemo)
(def ^function useCallback
"The `react.useCallback` hook function"
react/useCallback)
(def ^function useContext
"The `react.useContext` hook function"
react/useContext)
(def ^function useTransition
"The `react.useTransition` hook function"
react/useTransition)
;; --- Hooks
(def ^function use
"The `react.use` helper"
react/use)
(def ^:private adapt-sym
(js/Symbol "rumext:adapt-fn"))
(unchecked-set (.-prototype cljs.core/UUID)
adapt-sym
(fn [o] (.-uuid ^cljs.core/UUID o)))
(unchecked-set (.-prototype cljs.core/Keyword)
adapt-sym
(fn [o] (.toString ^js o)))
(unchecked-set (.-prototype cljs.core/Symbol)
adapt-sym
(fn [o] (.toString ^js o)))
(defn adapt
[o]
(when (some? o)
(let [adapt-fn (unchecked-get o adapt-sym)]
(if ^boolean adapt-fn
(^function adapt-fn o)
o))))
(defn deps
"A helper for creating hook deps array, that handles some
adaptations for clojure specific data types such that UUID and
keywords"
([] #js [])
([a] #js [(adapt a)])
([a b] #js [(adapt a) (adapt b)])
([a b c] #js [(adapt a) (adapt b) (adapt c)])
([a b c d] #js [(adapt a) (adapt b) (adapt c) (adapt d)])
([a b c d e] #js [(adapt a) (adapt b) (adapt c) (adapt d) (adapt e)])
([a b c d e f] #js [(adapt a) (adapt b) (adapt c) (adapt d) (adapt e) (adapt f)])
([a b c d e f g] #js [(adapt a) (adapt b) (adapt c) (adapt d) (adapt e) (adapt f) (adapt g)])
([a b c d e f g h] #js [(adapt a) (adapt b) (adapt c) (adapt d) (adapt e) (adapt f) (adapt g) (adapt h)])
([a b c d e f g h & rest] (into-array (map adapt (into [a b c d e f g h] rest)))))
(def ^function use-ref
"A lisp-case alias for `useRef`"
react/useRef)
(def ^function use-ctx
"A lisp-case short alias for the `useContext` hook function"
react/useContext)
(def ^function use-id
"A lisp-case alias fro `useId` hook function"
react/useId)
(def ^function use-effect-event
"A lisp-case alias for `useEffectEvent` hook function"
react/useEffectEvent)
(def ^function start-transition
"An alias for react.startTransition function"
react/startTransition)
(def noop (constantly nil))
(defn use-effect
"A rumext variant of the `useEffect` hook function with order of
arguments inverted"
([f] (use-effect #js [] f))
([deps f]
(useEffect #(let [r (^function f)] (if (fn? r) r noop)) deps)))
(defn use-insertion-effect
"A rumext variant of the `useInsertionEffect` hook function with order
of arguments inverted"
([f] (use-insertion-effect #js [] f))
([deps f]
(useInsertionEffect #(let [r (^function f)] (if (fn? r) r noop)) deps)))
(defn use-layout-effect
"A rumext variant of the `useLayoutEffect` hook function with order
of arguments inverted"
([f] (use-layout-effect #js [] f))
([deps f]
(useLayoutEffect #(let [r (^function f)] (if (fn? r) r noop)) deps)))
(defn use-ssr-effect
"An EXPERIMENTAL use-effect version that detects if we are in a NON
browser context and runs the effect fn inmediatelly."
[deps effect-fn]
(if ^boolean browser-context?
(use-effect deps effect-fn)
(let [ret (effect-fn)]
(when (fn? ret)
(ret)))))
(defn use-memo
"A rumext variant of the `useMemo` hook function with order
of arguments inverted"
([f] (useMemo f #js []))
([deps f] (useMemo f deps)))
(defn use-transition
"A rumext version of the `useTransition` hook function. Returns a
function object that implements the IPending protocol for check the
state of the transition."
[]
(let [tmp (useTransition)
is-pending (aget tmp 0)
start-fn (aget tmp 1)]
(use-memo
#js [is-pending]
(fn []
(specify! (fn [cb-fn]
(^function start-fn cb-fn))
cljs.core/IPending
(-realized? [_] (not ^boolean is-pending)))))))
(defn use-callback
"A rumext variant of the `useCallback` hook function with order
of arguments inverted"
([f] (useCallback f #js []))
([deps f] (useCallback f deps)))
(defn use-fn
"A convenience short alias for `use-callback`"
([f] (useCallback f #js []))
([deps f] (useCallback f deps)))
(defn deref
"A rumext hook for deref and watch an atom or atom like object. It
internally uses the react.useSyncExternalSource API"
[iref]
(let [state (use-ref (c/deref iref))
key (use-id)
get-state (use-fn #js [state] #(unchecked-get state "current"))
subscribe (use-fn #js [iref key]
(fn [listener-fn]
(unchecked-set state "current" (c/deref iref))
(add-watch iref key (fn [_ _ _ newv]
(unchecked-set state "current" newv)
(^function listener-fn)))
#(remove-watch iref key)))
snapshot (use-fn #js [iref] #(c/deref iref))]
(react/useSyncExternalStore subscribe get-state snapshot)))
(deftype State [update-fn value]
c/IReset
(-reset! [_ value]
(^function update-fn value))
c/ISwap
(-swap! [self f]
(^function update-fn f))
(-swap! [self f x]
(^function update-fn #(f % x)))
(-swap! [self f x y]
(^function update-fn #(f % x y)))
(-swap! [self f x y more]
(^function update-fn #(apply f % x y more)))
c/IDeref
(-deref [_] value))
(defn use-state
"A rumext variant of `useState`. Returns an object that implements
the Atom protocols."
([] (use-state nil))
([initial]
(let [tmp (useState initial)
ref (useRef nil)
value (aget tmp 0)
update-fn (aget tmp 1)]
(use-memo #js [value] #(State. update-fn value)))))
(defn use-var
"A rumext custom hook that uses `useRef` under the hood. Returns an
object that implements the Atom protocols. The updates does not
trigger rerender."
([] (use-var nil))
([initial]
(let [ref (useRef nil)]
(when (nil? (.-current ^js ref))
(let [self (fn [value]
(let [target (unchecked-get ref "current")]
(unchecked-set target "value" value)))]
(unchecked-set self "value" initial)
(unchecked-set ref "current" self)
(specify! self
c/IDeref
(-deref [this]
(.-value ^js this))
c/IReset
(-reset! [this v]
(unchecked-set this "value" v))
c/ISwap
(-swap!
([this f]
(unchecked-set this "value" (f (.-value ^js this))))
([this f a]
(unchecked-set this "value" (f (.-value ^js this) a)))
([this f a b]
(unchecked-set this "value" (f (.-value ^js this) a b)))
([this f a b xs]
(unchecked-set this "value" (apply f (.-value ^js this) a b xs)))))))
(.-current ^js ref))))
;; --- Other API
(defn element
"Create a react element. This is a public API for the internal `jsx`
function"
([klass]
(jsx klass #js {} undefined))
([klass props]
(let [props (cond
(object? props) ^js props
(map? props) (util/map->obj props)
:else (throw (ex-info "Unexpected props" {:props props})))]
(jsx klass props undefined))))
(def ^function create-element react/createElement)
(def ^function element? react/isValidElement)
;; --- Higher-Order Components
(defn memo
"High order component for memoizing component props. Is a rumext
variant of React.memo what accepts a value comparator
function (instead of props comparator)"
([component] (react/memo component))
([component eq?]
(react/memo component #(util/props-equals? eq? %1 %2))))
(def ^function memo'
"A raw variant of React.memo."
react/memo)
(def ^:private schedule
(or (and (exists? js/window) js/window.requestAnimationFrame)
#(js/setTimeout % 16)))
(defn deferred
"A higher-order component that just deffers the first render to the next tick"
([component] (deferred component schedule))
([component sfn]
(fnc deferred
{::wrap-props false}
[props]
(let [tmp (useState false)
render? (aget tmp 0)
set-render (aget tmp 1)]
(use-effect (fn [] (^function sfn #(^function set-render true))))
(when ^boolean render?
[:> component props])))))
(defn throttle
"A higher-order component that throttles the rendering"
[component ms]
(fnc throttle
{::wrap-props false}
[props]
(let [tmp (useState props)
state (aget tmp 0)
set-state (aget tmp 1)
ref (useRef false)
render (useMemo
#(gf/throttle
(fn [v]
(when-not ^boolean (ref-val ref)
(^function set-state v)))
ms)
#js [])]
(useEffect #(^function render props) #js [props])
(useEffect #(fn [] (set-ref-val! ref true)) #js [])
[:> component state])))
(defn check-props
"Utility function to use with `memo'`.
Will check the `props` keys to see if they are equal.
Usage:
```clojure
(mf/defc my-component
{::mf/wrap [#(mf/memo' % (mf/check-props [\"prop1\" \"prop2\"]))]}
[props]
```
)"
([props] (check-props props =))
([props eqfn?]
(fn [np op]
(every? #(eqfn? (unchecked-get np %)
(unchecked-get op %))
props))))
(defn use-debounce
"A rumext custom hook that debounces the value changes"
[ms value]
(let [[state update-fn] (useState value)
update-fn (useMemo #(gf/debounce update-fn ms) #js [ms])]
(useEffect #(update-fn value) #js [value])
state))
(defn use-equal-memo
"A rumext custom hook that preserves object identity through using a
`=` (value equality). Optionally, you can provide your own
function."
([val]
(let [ref (use-ref nil)]
(when-not (= (ref-val ref) val)
(set-ref-val! ref val))
(ref-val ref)))
([eqfn val]
(let [ref (use-ref nil)]
(when-not (eqfn (ref-val ref) val)
(set-ref-val! ref val))
(ref-val ref))))
(def ^function use-deferred
"A lisp-case shorter alias for `useDeferredValue`"
react/useDeferredValue)
(defn use-previous
"A rumext custom hook that returns a value from previous render"
[value]
(let [ref (use-ref value)]
(use-effect #js [value] #(set-ref-val! ref value))
(ref-val ref)))
(defn use-update-ref
"A rumext custom hook that updates the ref value if the value changes"
[value]
(let [ref (use-ref value)]
(use-effect #js [value] #(set-ref-val! ref value))
ref))
(defn use-ref-fn
"A rumext custom hook that returns a stable callback pointer what
calls the interned callback. The interned callback will be
automatically updated on each render if the reference changes and
works as noop if the pointer references to nil value."
[f]
(let [ptr (use-ref nil)]
(use-effect #js [f] #(set-ref-val! ptr f))
(use-fn (fn []
(let [f (ref-val ptr)
args (js-arguments)]
(when (some? f)
(.apply f args)))))))