-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathHooks.purs
578 lines (499 loc) · 16.9 KB
/
Hooks.purs
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
module React.Basic.Hooks
( Component
, component
, reactComponent
, reactComponentWithChildren
, reactComponentFromHook
, ReactChildren
, reactChildrenToArray
, reactChildrenFromArray
, memo
, memo'
, useState
, useState'
, UseState
, useEffect
, useEffectOnce
, useEffectAlways
, UseEffect
, useLayoutEffect
, useLayoutEffectOnce
, useLayoutEffectAlways
, UseLayoutEffect
, useInsertionEffect
, useInsertionEffectOnce
, useInsertionEffectAlways
, UseInsertionEffect
, Reducer
, mkReducer
, runReducer
, useReducer
, UseReducer
, readRef
, readRefMaybe
, writeRef
, useRef
, UseRef
, useContext
, UseContext
, useEqCache
, UseEqCache
, useMemo
, UseMemo
, useDebugValue
, UseDebugValue
, useId
, UseId
, useTransition
, UseTransition
, useDeferredValue
, UseDeferredValue
, useSyncExternalStore
, useSyncExternalStore'
, UseSyncExternalStore
, UnsafeReference(..)
, displayName
, module React.Basic.Hooks.Internal
, module React.Basic
, module Data.Tuple.Nested
) where
import Prelude hiding (bind, discard)
import Data.Bifunctor (rmap)
import Data.Function.Uncurried (Fn2, mkFn2, runFn2)
import Data.Maybe (Maybe)
import Data.Newtype (class Newtype)
import Data.Nullable (Nullable, toMaybe)
import Data.Tuple (Tuple(..))
import Data.Tuple.Nested (type (/\), (/\))
import Effect (Effect)
import Effect.Uncurried (EffectFn1, EffectFn2, EffectFn3, mkEffectFn1, runEffectFn1, runEffectFn2, runEffectFn3)
import Prelude (bind) as Prelude
import Prim.Row (class Lacks)
import React.Basic (JSX, ReactComponent, ReactContext, Ref, consumer, contextConsumer, contextProvider, createContext, element, elementKeyed, empty, keyed, fragment, provider)
import React.Basic.Hooks.Internal (Hook, HookApply, Pure, Render, bind, discard, coerceHook, unsafeHook, unsafeRenderEffect, type (&))
import Unsafe.Coerce (unsafeCoerce)
import Unsafe.Reference (unsafeRefEq)
--| A simple type alias to clean up component definitions.
type Component props
= Effect (props -> JSX)
--| Create a component function given a display name and render function.
--| Creating components is effectful because React uses the function
--| instance as the component's "identity" or "type". Components should
--| be created during a bootstrap phase and not within component
--| lifecycles or render functions.
component ::
forall hooks props.
String ->
(props -> Render Unit hooks JSX) ->
Component props
component name renderFn = Prelude.do
c <- reactComponent name (renderFn <<< _.nested)
pure (element c <<< { nested: _ })
--| Create a React component given a display name and render function.
--| Creating components is effectful because React uses the function
--| instance as the component's "identity" or "type". Components should
--| be created during a bootstrap phase and not within component
--| lifecycles or render functions. See `componentWithChildren` if
--| you need to use the `children` prop.
reactComponent ::
forall hooks props.
Lacks "children" props =>
Lacks "key" props =>
Lacks "ref" props =>
String ->
({ | props } -> Render Unit hooks JSX) ->
Effect (ReactComponent { | props })
reactComponent = unsafeReactComponent
--| Create a React component given a display name and render function.
--| This is the same as `component` but allows the use of the `children`
--| prop.
reactComponentWithChildren ::
forall hooks props children.
Lacks "key" props =>
Lacks "ref" props =>
String ->
({ children :: ReactChildren children | props } -> Render Unit hooks JSX) ->
Effect (ReactComponent { children :: ReactChildren children | props })
reactComponentWithChildren = unsafeReactComponent
--| Convert a hook to a render-prop component. The value returned from the
--| hook will be passed to the `render` prop, a function from that value
--| to `JSX`.
--|
--| This function is useful for consuming a hook within a non-hook component.
reactComponentFromHook ::
forall hooks props r.
Lacks "children" props =>
Lacks "key" props =>
Lacks "ref" props =>
String ->
({ render :: r -> JSX | props } -> Hook hooks r) ->
Effect (ReactComponent { render :: r -> JSX | props })
reactComponentFromHook name propsToHook = do
reactComponent name \props -> map props.render $ propsToHook props
unsafeReactComponent ::
forall hooks props.
Lacks "key" props =>
Lacks "ref" props =>
String ->
({ | props } -> Render Unit hooks JSX) ->
Effect (ReactComponent { | props })
unsafeReactComponent name renderFn =
let
c =
unsafeReactFunctionComponent
( mkEffectFn1
( \props ->
unsafeDiscardRenderEffects (renderFn props)
)
)
in
runEffectFn2 unsafeSetDisplayName name c
unsafeDiscardRenderEffects :: forall x y a. Render x y a -> Effect a
unsafeDiscardRenderEffects = unsafeCoerce
unsafeReactFunctionComponent :: forall props. EffectFn1 props JSX -> ReactComponent props
unsafeReactFunctionComponent = unsafeCoerce
data ReactChildren :: forall k. k -> Type
data ReactChildren a
foreign import reactChildrenToArray :: forall a. ReactChildren a -> Array a
reactChildrenFromArray :: forall a. Array a -> ReactChildren a
reactChildrenFromArray = unsafeCoerce
--| Prevents a component from re-rendering if its new props are referentially
--| equal to its old props (not value-based equality -- this is due to the
--| underlying React implementation).
--| Prefer `memo'` for more PureScript-friendldy behavior.
memo ::
forall props.
Effect (ReactComponent props) ->
Effect (ReactComponent props)
memo = flip Prelude.bind (runEffectFn1 memo_)
--| Similar to `memo` but takes a function to compare previous and new props.
--| For example:
--|
--| ```purs
--| mkMyComponent :: Effect (ReactComponent { id :: Int })
--| mkMyComponent =
--| memo' eq do
--| reactComponent "MyComponent" \{ id } -> React.do
--| ...
--| ```
memo' ::
forall props.
(props -> props -> Boolean) ->
Effect (ReactComponent props) ->
Effect (ReactComponent props)
memo' arePropsEqual comp = Prelude.do
c <- comp
runEffectFn2 memoEq_ c (mkFn2 arePropsEqual)
useState ::
forall state.
state ->
Hook (UseState state) (state /\ ((state -> state) -> Effect Unit))
useState initialState =
unsafeHook do
runEffectFn2 useState_ (mkFn2 Tuple) initialState
useState' ::
forall state.
state ->
Hook (UseState state) (state /\ (state -> Effect Unit))
useState' initialState = useState initialState <#> rmap (_ <<< const)
foreign import data UseState :: Type -> Type -> Type
--| Runs the given effect when the component is mounted and any time the given
--| dependencies change. The effect should return its cleanup function. For
--| example, if the effect registers a global event listener, it should return
--| an Effect which removes the listener.
--|
--| ```purs
--| useEffect deps do
--| timeoutId <- setTimeout 1000 (logShow deps)
--| pure (clearTimeout timeoutId)
--| ```
--|
--| If no cleanup is needed, use `pure (pure unit)` or `pure mempty` to return
--| a no-op Effect
--|
--| ```purs
--| useEffect deps do
--| logShow deps
--| pure mempty
--| ```
useEffect ::
forall deps.
Eq deps =>
deps ->
Effect (Effect Unit) ->
Hook (UseEffect deps) Unit
useEffect deps effect =
unsafeHook do
runEffectFn3 useEffect_ (mkFn2 eq) deps effect
--| Like `useEffect`, but the effect is only performed a single time per component
--| instance. Prefer `useEffect` with a proper dependency list whenever possible!
useEffectOnce :: Effect (Effect Unit) -> Hook (UseEffect Unit) Unit
useEffectOnce effect = unsafeHook (runEffectFn3 useEffect_ (mkFn2 \_ _ -> true) unit effect)
--| Like `useEffect`, but the effect is performed on every render. Prefer `useEffect`
--| with a proper dependency list whenever possible!
useEffectAlways :: Effect (Effect Unit) -> Hook (UseEffect Unit) Unit
useEffectAlways effect = unsafeHook (runEffectFn1 useEffectAlways_ effect)
foreign import data UseEffect :: Type -> Type -> Type
--| Like `useEffect`, but the effect is performed synchronously after the browser has
--| calculated layout. Useful for reading properties from the DOM that are not available
--| before layout, such as element sizes and positions. Prefer `useEffect` whenever
--| possible to avoid blocking browser painting.
useLayoutEffect ::
forall deps.
Eq deps =>
deps ->
Effect (Effect Unit) ->
Hook (UseLayoutEffect deps) Unit
useLayoutEffect deps effect = unsafeHook (runEffectFn3 useLayoutEffect_ (mkFn2 eq) deps effect)
--| Like `useLayoutEffect`, but the effect is only performed a single time per component
--| instance. Prefer `useLayoutEffect` with a proper dependency list whenever possible!
useLayoutEffectOnce :: Effect (Effect Unit) -> Hook (UseLayoutEffect Unit) Unit
useLayoutEffectOnce effect = unsafeHook (runEffectFn3 useLayoutEffect_ (mkFn2 \_ _ -> true) unit effect)
--| Like `useLayoutEffect`, but the effect is performed on every render. Prefer `useLayoutEffect`
--| with a proper dependency list whenever possible!
useLayoutEffectAlways :: Effect (Effect Unit) -> Hook (UseLayoutEffect Unit) Unit
useLayoutEffectAlways effect = unsafeHook (runEffectFn1 useLayoutEffectAlways_ effect)
foreign import data UseLayoutEffect :: Type -> Type -> Type
useInsertionEffect ::
forall deps.
Eq deps =>
deps ->
Effect (Effect Unit) ->
Hook (UseInsertionEffect deps) Unit
useInsertionEffect deps effect = unsafeHook (runEffectFn3 useInsertionEffect_ (mkFn2 eq) deps effect)
--| Like `useInsertionEffect`, but the effect is only performed a single time per component
--| instance. Prefer `useInsertionEffect` with a proper dependency list whenever possible!
useInsertionEffectOnce :: Effect (Effect Unit) -> Hook (UseInsertionEffect Unit) Unit
useInsertionEffectOnce effect = unsafeHook (runEffectFn3 useInsertionEffect_ (mkFn2 \_ _ -> true) unit effect)
--| Like `useInsertionEffect`, but the effect is performed on every render. Prefer `useInsertionEffect`
--| with a proper dependency list whenever possible!
useInsertionEffectAlways :: Effect (Effect Unit) -> Hook (UseInsertionEffect Unit) Unit
useInsertionEffectAlways effect = unsafeHook (runEffectFn1 useInsertionEffectAlways_ effect)
foreign import data UseInsertionEffect :: Type -> Type -> Type
newtype Reducer state action
= Reducer (Fn2 state action state)
--| Creating reducer functions for React is effectful because
--| React uses the function instance's reference to optimize
--| rendering behavior.
mkReducer :: forall state action. (state -> action -> state) -> Effect (Reducer state action)
mkReducer = pure <<< Reducer <<< mkFn2
--| Run a wrapped `Reducer` function as a normal function (like `runFn2`).
--| Useful for testing, simulating actions, or building more complicated
--| hooks on top of `useReducer`
runReducer :: forall state action. Reducer state action -> state -> action -> state
runReducer (Reducer reducer) = runFn2 reducer
--| Use `mkReducer` to construct a reducer function.
useReducer ::
forall state action.
state ->
Reducer state action ->
Hook (UseReducer state action) (state /\ (action -> Effect Unit))
useReducer initialState (Reducer reducer) =
unsafeHook do
runEffectFn3 useReducer_
(mkFn2 Tuple)
reducer
initialState
foreign import data UseReducer :: Type -> Type -> Type -> Type
useRef :: forall a. a -> Hook (UseRef a) (Ref a)
useRef initialValue =
unsafeHook do
runEffectFn1 useRef_ initialValue
readRef :: forall a. Ref a -> Effect a
readRef = runEffectFn1 readRef_
readRefMaybe :: forall a. Ref (Nullable a) -> Effect (Maybe a)
readRefMaybe a = map toMaybe (readRef a)
writeRef :: forall a. Ref a -> a -> Effect Unit
writeRef = runEffectFn2 writeRef_
foreign import data UseRef :: Type -> Type -> Type
useContext :: forall a. ReactContext a -> Hook (UseContext a) a
useContext context = unsafeHook (runEffectFn1 useContext_ context)
foreign import data UseContext :: Type -> Type -> Type
--| Cache an instance of a value, replacing it when `eq` returns `false`.
--|
--| This is a low-level performance optimization tool. It can be useful
--| for optimizing a component's props for use with `memo`, where
--| JavaScript instance equality matters.
useEqCache ::
forall a.
Eq a =>
a ->
Hook (UseEqCache a) a
useEqCache a =
unsafeHook do
runEffectFn2 useEqCache_ (mkFn2 eq) a
foreign import data UseEqCache :: Type -> Type -> Type
--| Lazily compute a value. The result is cached until the `deps` change.
useMemo ::
forall deps a.
Eq deps =>
deps ->
(Unit -> a) ->
Hook (UseMemo deps a) a
useMemo deps computeA =
unsafeHook do
runEffectFn3 useMemo_ (mkFn2 eq) deps computeA
foreign import data UseMemo :: Type -> Type -> Type -> Type
--| Use this hook to display a label for custom hooks in React DevTools
useDebugValue :: forall a. a -> (a -> String) -> Hook (UseDebugValue a) Unit
useDebugValue debugValue display = unsafeHook (runEffectFn2 useDebugValue_ debugValue display)
foreign import data UseDebugValue :: Type -> Type -> Type
foreign import data UseId :: Type -> Type
useId :: Hook UseId String
useId = unsafeHook useId_
foreign import data UseTransition :: Type -> Type
useTransition ::
Hook UseTransition (Boolean /\ ((Effect Unit) -> Effect Unit))
useTransition = unsafeHook $ runEffectFn1 useTransition_ (mkFn2 Tuple)
foreign import data UseDeferredValue :: Type -> Type -> Type
useDeferredValue :: forall a. a -> Hook (UseDeferredValue a) a
useDeferredValue a = unsafeHook $ runEffectFn1 useDeferredValue_ a
foreign import data UseSyncExternalStore :: Type -> Type -> Type
useSyncExternalStore :: forall a.
((Effect Unit) -> Effect (Effect Unit))
-> (Effect a)
-> (Effect a)
-> Hook (UseSyncExternalStore a) a
useSyncExternalStore subscribe getSnapshot getServerSnapshot =
unsafeHook $
runEffectFn3 useSyncExternalStore3_
(mkEffectFn1 subscribe)
getSnapshot
getServerSnapshot
useSyncExternalStore' :: forall a.
((Effect Unit) -> Effect (Effect Unit))
-> (Effect a)
-> Hook (UseSyncExternalStore a) a
useSyncExternalStore' subscribe getSnapshot =
unsafeHook $
runEffectFn2 useSyncExternalStore2_ (mkEffectFn1 subscribe) getSnapshot
newtype UnsafeReference a
= UnsafeReference a
derive instance newtypeUnsafeReference :: Newtype (UnsafeReference a) _
instance eqUnsafeReference :: Eq (UnsafeReference a) where
eq = unsafeRefEq
--| Retrieve the Display Name from a `ReactComponent`. Useful for debugging and improving
--| error messages in logs.
--|
--| __*See also:* `component`__
foreign import displayName ::
forall props.
ReactComponent props ->
String
--|
--| Internal utility or FFI functions
--|
foreign import memo_ ::
forall props.
EffectFn1
(ReactComponent props)
(ReactComponent props)
foreign import memoEq_ ::
forall props.
EffectFn2
(ReactComponent props)
(Fn2 props props Boolean)
(ReactComponent props)
foreign import unsafeSetDisplayName ::
forall props.
EffectFn2 String (ReactComponent props) (ReactComponent props)
foreign import useState_ ::
forall state.
EffectFn2
(forall a b. Fn2 a b (a /\ b))
state
(state /\ ((state -> state) -> Effect Unit))
foreign import useEffect_ ::
forall deps.
EffectFn3
(Fn2 deps deps Boolean)
deps
(Effect (Effect Unit))
Unit
foreign import useEffectAlways_ ::
EffectFn1
(Effect (Effect Unit))
Unit
foreign import useLayoutEffect_ ::
forall deps.
EffectFn3
(Fn2 deps deps Boolean)
deps
(Effect (Effect Unit))
Unit
foreign import useLayoutEffectAlways_ ::
EffectFn1
(Effect (Effect Unit))
Unit
foreign import useInsertionEffect_ ::
forall deps.
EffectFn3
(Fn2 deps deps Boolean)
deps
(Effect (Effect Unit))
Unit
foreign import useInsertionEffectAlways_ ::
EffectFn1
(Effect (Effect Unit))
Unit
foreign import useReducer_ ::
forall state action.
EffectFn3
(forall a b. Fn2 a b (a /\ b))
(Fn2 state action state)
state
(state /\ (action -> Effect Unit))
foreign import readRef_ ::
forall a.
EffectFn1
(Ref a)
a
foreign import writeRef_ ::
forall a.
EffectFn2
(Ref a)
a
Unit
foreign import useRef_ ::
forall a.
EffectFn1
a
(Ref a)
foreign import useContext_ ::
forall a.
EffectFn1
(ReactContext a)
a
foreign import useEqCache_ ::
forall a.
EffectFn2
(Fn2 a a Boolean)
a
a
foreign import useMemo_ ::
forall deps a.
EffectFn3
(Fn2 deps deps Boolean)
deps
(Unit -> a)
a
foreign import useDebugValue_ ::
forall a.
EffectFn2
a
(a -> String)
Unit
foreign import useId_ :: Effect String
foreign import useTransition_
:: forall a b. EffectFn1 (Fn2 a b (a /\ b))
(Boolean /\ ((Effect Unit) -> Effect Unit))
foreign import useDeferredValue_ :: forall a. EffectFn1 a a
foreign import useSyncExternalStore2_ :: forall a. EffectFn2
(EffectFn1 (Effect Unit) (Effect Unit)) -- subscribe
(Effect a) -- getSnapshot
a
foreign import useSyncExternalStore3_ :: forall a. EffectFn3
(EffectFn1 (Effect Unit) (Effect Unit)) -- subscribe
(Effect a) -- getSnapshot
(Effect a) -- getServerSnapshot
a