-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.purs
265 lines (232 loc) · 7.73 KB
/
App.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
-- This is a PureScript implementation of
-- https://codesandbox.io/s/github/the-road-to-learn-react/hacker-stories/tree/hs/Data-Re-Fetching-in-React
module App where
import Prelude
import Affjax (get)
import Affjax.ResponseFormat (json)
import Control.Monad.Maybe.Trans (MaybeT(MaybeT), runMaybeT)
import Control.Monad.Trans.Class (lift)
import Data.Argonaut.Core (Json)
import Data.Argonaut.Prisms (_Array, _Object, _String)
import Data.Array (mapMaybe)
import Data.Array as Array
import Data.Either (Either(Left, Right))
import Data.Int (fromString)
import Data.Lens ((^?), (^..), to, traversed)
import Data.Lens.Index (ix)
import Data.List (List, toUnfoldable)
import Data.Maybe (Maybe, fromMaybe)
import Data.Monoid (guard)
import Data.Newtype (class Newtype)
import Data.Nullable (null)
import Record (merge)
import Data.String as String
import Data.Tuple.Nested ((/\), type (/\))
import Effect (Effect)
import Effect.Class (liftEffect)
import Prim.Row (class Nub, class Union)
import React.Basic.DOM as R
import React.Basic.DOM.Events (capture, capture_, targetValue)
import React.Basic.Hooks
( Hook, JSX, ReactComponent, UseEffect, UseState, coerceHook, component
, fragment, keyed, mkReducer, reactComponent, readRefMaybe, useEffect
, useReducer, useRef, useState
)
import React.Basic.Hooks as React
import React.Basic.Hooks.Aff (useAff)
import Web.DOM.Node (Node)
import Web.HTML.HTMLElement (focus, fromNode)
-------------
-- Helpers --
-------------
class (Union inputProps optProps x, Nub x allProps) <=
InputProps inputProps optProps allProps x
instance inputPropsC :: (Union inputProps optProps x, Nub x allProps) =>
InputProps inputProps optProps allProps x
liftMaybe :: forall m a. Applicative m => Maybe a -> MaybeT m a
liftMaybe = MaybeT <<< pure
---------
-- App --
---------
type Story = { title :: String, url :: String, author :: String, objectId :: Int }
jsonToStory :: Json -> Maybe Story
jsonToStory storyJson = do
storyObj <- storyJson ^? _Object
title <- storyObj ^? ix "title" <<< _String
url <- storyObj ^? ix "url" <<< _String
author <- storyObj ^? ix "author" <<< _String
maybeObjectId <- storyObj ^? ix "objectID" <<< _String <<< to fromString
objectId <- maybeObjectId
pure ({ title, url, author, objectId } :: Story)
apiEndpoint :: String
apiEndpoint = "https://hn.algolia.com/api/v1/search?query="
newtype UseSemiPersistentState hooks
= UseSemiPersistentState (UseEffect (String /\ String) (UseState String hooks))
derive instance newtypeUseSemiPersistentState :: Newtype (UseSemiPersistentState hooks) _
useSemiPersistentState
:: String
-> String
-> Hook
UseSemiPersistentState
(String /\ ((String -> String) -> Effect Unit))
useSemiPersistentState key initialState = coerceHook React.do
value /\ setValue <- useState initialState
useEffect (value /\ key) $ do
pure mempty
pure (value /\ setValue)
data StoriesAction
= StoriesFetchInit
| StoriesFetchSuccess (Array Story)
| StoriesFetchFailure
| RemoveStory Story
storiesReducerFun
:: { data :: Array Story, isLoading :: Boolean, isError :: Boolean }
-> StoriesAction
-> { data :: Array Story, isLoading :: Boolean, isError :: Boolean }
storiesReducerFun state =
case _ of
StoriesFetchInit -> state { isLoading = true, isError = false }
StoriesFetchSuccess newStories ->
state { isLoading = false, isError = false, data = newStories }
StoriesFetchFailure -> state { isLoading = false, isError = true }
RemoveStory storyToRemove ->
state
{ data =
Array.filter
(\story -> storyToRemove.objectId /= story.objectId)
state.data
}
app :: Effect (ReactComponent {})
app = do
inputWithLabel <- makeInputWithLabel
list <- makeList
storiesReducer <- mkReducer storiesReducerFun
reactComponent "App" \props -> React.do
searchTerm /\ setSearchTerm <- useSemiPersistentState "search" "Re"
stories /\ dispatchStories <-
useReducer
{ data: [], isLoading: false, isError: false }
storiesReducer
useAff searchTerm $
when (not (String.null searchTerm)) do
liftEffect $ dispatchStories StoriesFetchInit
eitherResp <- get json (apiEndpoint <> searchTerm)
case eitherResp of
Right resp -> do
let maybeObj = resp.body ^? _Object
(maybeStories :: List (Maybe Story)) =
maybeObj ^.. traversed <<< ix "hits" <<< _Array <<< traversed <<< to jsonToStory
stories' = mapMaybe identity $ toUnfoldable maybeStories
liftEffect $ dispatchStories (StoriesFetchSuccess stories')
Left _ ->
liftEffect $ dispatchStories StoriesFetchFailure
let handleRemoveStory story =
dispatchStories (RemoveStory story)
handleSearch eventTargetValue =
setSearchTerm \_ -> fromMaybe "" eventTargetValue
pure $
R.div_
[ R.h1_ [ R.text "My Hacker Stories" ]
, inputWithLabel
{ children:
[ R.text "Search:" ]
, id: "search"
, value: searchTerm
, onInputChange: handleSearch
, isFocused: true
}
, R.hr {}
, if stories.isError then R.p_ [ R.text "Something went wrong..." ] else mempty
, if stories.isLoading
then R.p_ [R.text "Loading ..."]
else
list
{ list: stories.data
, onRemoveItem: handleRemoveStory
}
]
type PropsInputWithLabel =
( children :: Array JSX
, id :: String
, isFocused :: Boolean
, onInputChange :: Maybe String -> Effect Unit
, value :: String
| PropsInputWithLabelOpt
)
type PropsInputWithLabelOpt = (type_ :: String)
makeInputWithLabel
:: forall props x
. InputProps props PropsInputWithLabelOpt PropsInputWithLabel x
=> Effect (Record props -> JSX)
makeInputWithLabel =
component "InputWithLabel" \props_ -> React.do
let def = { type_: "text" }
{ children, id, isFocused, onInputChange, type_, value } = merge props_ def
inputRef <- useRef null
useEffect isFocused $
guard isFocused $ do
void $ runMaybeT $ do
(node :: Node) <- MaybeT $ readRefMaybe inputRef
htmlElem <- liftMaybe $ fromNode node
lift (focus htmlElem)
pure (pure unit)
pure $
fragment
[ R.label
{ htmlFor: id
, children: children
}
, R.span
{ dangerouslySetInnerHTML:
{ __html: " "
}
}
, R.input
{ id
, onChange: capture targetValue onInputChange
, ref: inputRef
, type: type_
, value
}
]
type PropsList =
( list :: Array Story
, onRemoveItem :: Story -> Effect Unit
)
makeList :: Effect (Record PropsList -> JSX)
makeList = do
item <- makeItem
component "List" \{list, onRemoveItem} -> React.do
let items =
map
(\story ->
keyed
(show story.objectId)
(item { item: story, onRemoveItem })
)
list
pure (fragment items)
type PropsItem =
( item :: Story
, onRemoveItem :: Story -> Effect Unit
)
makeItem :: Effect (Record PropsItem -> JSX)
makeItem = do
component "Item" \{item, onRemoveItem} -> React.do
pure $
R.div_
[ R.span_
[ R.a
{ href: item.url
, children: [ R.text item.title ]
}
]
, R.span_ [ R.text item.author ]
, R.span_
[ R.button
{ type: "button"
, onClick: capture_ (onRemoveItem item)
, children: [ R.text "Dismiss" ]
}
]
]