-
-
Notifications
You must be signed in to change notification settings - Fork 97
/
Platform.elm
1637 lines (1430 loc) · 68.5 KB
/
Platform.elm
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
module Pages.Internal.Platform exposing
( Flags, Model, Msg(..), Program, application, init, update
, Effect(..), RequestInfo, view
)
{-| Exposed for internal use only (used in generated code).
@docs Flags, Model, Msg, Program, application, init, update
@docs Effect, RequestInfo, view
-}
import AriaLiveAnnouncer
import Base64
import Browser
import Browser.Dom as Dom
import Browser.Navigation
import BuildError exposing (BuildError)
import Bytes exposing (Bytes)
import Bytes.Decode
import Dict exposing (Dict)
import Form
import Html exposing (Html)
import Html.Attributes as Attr
import Http
import Json.Decode as Decode
import Json.Encode
import Pages.ConcurrentSubmission
import Pages.ContentCache as ContentCache
import Pages.Fetcher
import Pages.Flags
import Pages.Internal.Msg
import Pages.Internal.NotFoundReason exposing (NotFoundReason)
import Pages.Internal.ResponseSketch as ResponseSketch exposing (ResponseSketch)
import Pages.Internal.String as String
import Pages.Navigation
import Pages.ProgramConfig exposing (ProgramConfig)
import Pages.StaticHttpRequest as StaticHttpRequest
import PagesMsg exposing (PagesMsg)
import QueryParams
import Task
import Time
import Url exposing (Url)
import UrlPath exposing (UrlPath)
{-| -}
type alias Program userModel userMsg pageData actionData sharedData errorPage =
Platform.Program Flags (Model userModel pageData actionData sharedData) (Msg userMsg pageData actionData sharedData errorPage)
mainView :
ProgramConfig userMsg userModel route pageData actionData sharedData effect (Msg userMsg pageData actionData sharedData errorPage) errorPage
-> Model userModel pageData actionData sharedData
-> { title : String, body : List (Html (PagesMsg userMsg)) }
mainView config model =
case model.notFound of
Just info ->
Pages.Internal.NotFoundReason.document config.pathPatterns info
Nothing ->
case model.pageData of
Ok pageData ->
let
urls : { currentUrl : Url, basePath : List String }
urls =
{ currentUrl = model.url
, basePath = config.basePath
}
currentUrl : Url
currentUrl =
model.url
in
(config.view model.pageFormState
(model.inFlightFetchers |> toFetcherState)
(model.transition |> Maybe.map Tuple.second)
{ path = ContentCache.pathForUrl urls |> UrlPath.join
, route = config.urlToRoute { currentUrl | path = model.currentPath }
}
Nothing
pageData.sharedData
pageData.pageData
pageData.actionData
|> .view
)
pageData.userModel
Err error ->
{ title = "Page Data Error"
, body =
[ Html.div [] [ Html.text error ] ]
}
urlsToPagePath :
{ currentUrl : Url, basePath : List String }
-> UrlPath
urlsToPagePath urls =
urls.currentUrl.path
|> String.chopForwardSlashes
|> String.split "/"
|> List.filter ((/=) "")
|> List.drop (List.length urls.basePath)
|> UrlPath.join
{-| -}
view :
ProgramConfig userMsg userModel route pageData actionData sharedData effect (Msg userMsg pageData actionData sharedData errorPage) errorPage
-> Model userModel pageData actionData sharedData
-> Browser.Document (Msg userMsg pageData actionData sharedData errorPage)
view config model =
let
{ title, body } =
mainView config model
in
{ title = title
, body =
[ onViewChangeElement model.url
, AriaLiveAnnouncer.view model.ariaNavigationAnnouncement
]
++ List.map (Html.map UserMsg) body
}
onViewChangeElement : Url -> Html msg
onViewChangeElement currentUrl =
-- this is a hidden tag
-- it is used from the JS-side to reliably
-- check when Elm has changed pages
-- (and completed rendering the view)
Html.div
[ Attr.attribute "data-url" (Url.toString currentUrl)
, Attr.attribute "display" "none"
]
[]
{-| -}
type alias Flags =
Decode.Value
type InitKind shared page actionData errorPage
= OkPage shared page (Maybe actionData)
| NotFound { reason : NotFoundReason, path : UrlPath }
{-| -}
init :
ProgramConfig userMsg userModel route pageData actionData sharedData userEffect (Msg userMsg pageData actionData sharedData errorPage) errorPage
-> Flags
-> Url
-> Maybe Browser.Navigation.Key
-> ( Model userModel pageData actionData sharedData, Effect userMsg pageData actionData sharedData userEffect errorPage )
init config flags url key =
let
pageDataResult : Result BuildError (InitKind sharedData pageData actionData errorPage)
pageDataResult =
flags
|> Decode.decodeValue (Decode.field "pageDataBase64" Decode.string)
|> Result.toMaybe
|> Maybe.andThen Base64.toBytes
|> Maybe.andThen
(\justBytes ->
case
Bytes.Decode.decode
-- TODO should this use byteDecodePageData, or should it be decoding ResponseSketch data?
config.decodeResponse
justBytes
of
Just (ResponseSketch.RenderPage _ _) ->
Nothing
Just (ResponseSketch.HotUpdate pageData shared actionData) ->
OkPage shared pageData actionData
|> Just
Just (ResponseSketch.NotFound notFound) ->
NotFound notFound
|> Just
_ ->
Nothing
)
|> Result.fromMaybe
(StaticHttpRequest.DecoderError "Bytes decode error"
|> StaticHttpRequest.toBuildError url.path
)
in
case pageDataResult of
Ok (OkPage sharedData pageData actionData) ->
let
urls : { currentUrl : Url, basePath : List String }
urls =
{ currentUrl = url
, basePath = config.basePath
}
pagePath : UrlPath
pagePath =
urlsToPagePath urls
userFlags : Pages.Flags.Flags
userFlags =
flags
|> Decode.decodeValue
(Decode.field "userFlags" Decode.value)
|> Result.withDefault Json.Encode.null
|> Pages.Flags.BrowserFlags
( userModel, userCmd ) =
Just
{ path =
{ path = pagePath
, query = url.query
, fragment = url.fragment
}
, metadata = config.urlToRoute url
, pageUrl =
Just
{ protocol = url.protocol
, host = url.host
, port_ = url.port_
, path = pagePath
, query = url.query |> Maybe.map QueryParams.fromString |> Maybe.withDefault Dict.empty
, fragment = url.fragment
}
}
|> config.init userFlags sharedData pageData actionData
cmd : Effect userMsg pageData actionData sharedData userEffect errorPage
cmd =
UserCmd userCmd
initialModel : Model userModel pageData actionData sharedData
initialModel =
{ key = key
, url = url
, currentPath = url.path
, pageData =
Ok
{ pageData = pageData
, sharedData = sharedData
, userModel = userModel
, actionData = actionData
}
, ariaNavigationAnnouncement = ""
, userFlags = flags
, notFound = Nothing
, transition = Nothing
, nextTransitionKey = 0
, inFlightFetchers = Dict.empty
, pageFormState = Dict.empty
, pendingRedirect = False
, pendingData = Nothing
}
in
( { initialModel
| ariaNavigationAnnouncement = mainView config initialModel |> .title
}
, cmd
)
Ok (NotFound info) ->
( { key = key
, url = url
, currentPath = url.path
, pageData = Err "Not found"
, ariaNavigationAnnouncement = "Page Not Found" -- TODO use error page title for announcement?
, userFlags = flags
, notFound = Just info
, transition = Nothing
, nextTransitionKey = 0
, inFlightFetchers = Dict.empty
, pageFormState = Dict.empty
, pendingRedirect = False
, pendingData = Nothing
}
, NoEffect
)
Err error ->
( { key = key
, url = url
, currentPath = url.path
, pageData =
error
|> BuildError.errorToString
|> Err
, ariaNavigationAnnouncement = "Error"
, userFlags = flags
, notFound = Nothing
, transition = Nothing
, nextTransitionKey = 0
, inFlightFetchers = Dict.empty
, pageFormState = Dict.empty
, pendingRedirect = False
, pendingData = Nothing
}
, NoEffect
)
{-| -}
type Msg userMsg pageData actionData sharedData errorPage
= LinkClicked Browser.UrlRequest
| UrlChanged Url
-- TODO rename to PagesMsg
| UserMsg (PagesMsg userMsg)
--| SetField { formId : String, name : String, value : String }
| FormMsg (Form.Msg (Msg userMsg pageData actionData sharedData errorPage))
| UpdateCacheAndUrlNew Bool Url (Maybe userMsg) (Result Http.Error ( Url, ResponseSketch pageData actionData sharedData ))
| FetcherComplete Bool String Int (Result Http.Error ( Maybe userMsg, ActionDataOrRedirect actionData ))
| FetcherStarted String Int FormData Time.Posix
| PageScrollComplete
| HotReloadCompleteNew Bytes
| ProcessFetchResponse Int (Result Http.Error ( Url, ResponseSketch pageData actionData sharedData )) (Result Http.Error ( Url, ResponseSketch pageData actionData sharedData ) -> Msg userMsg pageData actionData sharedData errorPage)
type ActionDataOrRedirect action
= ActionResponse (Maybe action)
| RedirectResponse String
{-| -}
type alias Model userModel pageData actionData sharedData =
{ key : Maybe Browser.Navigation.Key
, url : Url
, currentPath : String
, ariaNavigationAnnouncement : String
, pageData :
Result
String
{ userModel : userModel
, pageData : pageData
, sharedData : sharedData
, actionData : Maybe actionData
}
, notFound : Maybe { reason : NotFoundReason, path : UrlPath }
, userFlags : Decode.Value
, transition : Maybe ( Int, Pages.Navigation.Navigation )
, nextTransitionKey : Int
, inFlightFetchers : Dict String ( Int, Pages.ConcurrentSubmission.ConcurrentSubmission actionData )
, pageFormState : Form.Model
, pendingRedirect : Bool
, pendingData : Maybe ( pageData, sharedData, Maybe actionData )
}
{-| -}
type Effect userMsg pageData actionData sharedData userEffect errorPage
= ScrollToTop
| NoEffect
| BrowserLoadUrl String
| BrowserPushUrl String
| BrowserReplaceUrl String
| FetchPageData Int (Maybe FormData) Url (Result Http.Error ( Url, ResponseSketch pageData actionData sharedData ) -> Msg userMsg pageData actionData sharedData errorPage)
| Submit FormData
| SubmitFetcher String Int FormData
| Batch (List (Effect userMsg pageData actionData sharedData userEffect errorPage))
| UserCmd userEffect
| CancelRequest Int
| RunCmd (Cmd (Msg userMsg pageData actionData sharedData errorPage))
{-| -}
update :
ProgramConfig userMsg userModel route pageData actionData sharedData userEffect (Msg userMsg pageData actionData sharedData errorPage) errorPage
-> Msg userMsg pageData actionData sharedData errorPage
-> Model userModel pageData actionData sharedData
-> ( Model userModel pageData actionData sharedData, Effect userMsg pageData actionData sharedData userEffect errorPage )
update config appMsg model =
case appMsg of
FormMsg formMsg ->
let
-- TODO trigger formCmd
( newModel, formCmd ) =
Form.update formMsg model.pageFormState
in
( { model
| pageFormState = newModel
}
, RunCmd formCmd
)
LinkClicked urlRequest ->
case urlRequest of
Browser.Internal url ->
let
navigatingToSamePage : Bool
navigatingToSamePage =
url.path == model.url.path && url.query == model.url.query && url.fragment /= Nothing
in
if navigatingToSamePage then
-- this is a workaround for an issue with anchor fragment navigation
-- see https://github.com/elm/browser/issues/39
( model
, BrowserLoadUrl (Url.toString url)
)
else
( model
, BrowserPushUrl (Url.toString url)
)
Browser.External href ->
( model
, BrowserLoadUrl href
)
UrlChanged url ->
case model.pendingData of
Just ( newPageData, newSharedData, newActionData ) ->
loadDataAndUpdateUrl
( newPageData, newSharedData, newActionData )
Nothing
url
url
False
config
model
Nothing ->
if model.url.path == url.path && model.url.query == url.query then
if url.fragment == Nothing then
( { model
| -- update the URL in case query params or fragment changed
url = url
}
, ScrollToTop
)
else
( { model
| -- update the URL in case query params or fragment changed
url = url
}
, NoEffect
)
else
( model
, NoEffect
)
-- TODO is it reasonable to always re-fetch route data if you re-navigate to the current route? Might be a good
-- parallel to the browser behavior
|> startNewGetLoad url (UpdateCacheAndUrlNew True url Nothing)
FetcherComplete _ fetcherKey _ userMsgResult ->
case userMsgResult of
Ok ( userMsg, actionOrRedirect ) ->
case actionOrRedirect of
ActionResponse maybeFetcherDoneActionData ->
( { model
| inFlightFetchers =
model.inFlightFetchers
|> Dict.update fetcherKey
(Maybe.map
(\( transitionId, fetcherState ) ->
( transitionId
, { fetcherState
| status =
maybeFetcherDoneActionData
|> Maybe.map Pages.ConcurrentSubmission.Reloading
-- TODO remove this bad default, FetcherSubmitting is incorrect
|> Maybe.withDefault Pages.ConcurrentSubmission.Submitting
}
)
)
)
}
, NoEffect
)
|> (case userMsg of
Just justUserMsg ->
performUserMsg justUserMsg config
Nothing ->
identity
)
|> startNewGetLoad (currentUrlWithPath model.url.path model) (UpdateCacheAndUrlNew False model.url Nothing)
RedirectResponse redirectTo ->
( { model
| inFlightFetchers =
model.inFlightFetchers
|> Dict.remove fetcherKey
, pendingRedirect = True
}
, NoEffect
)
|> startNewGetLoad (currentUrlWithPath redirectTo model) (UpdateCacheAndUrlNew False model.url Nothing)
Err _ ->
-- TODO how to handle error?
( model, NoEffect )
|> startNewGetLoad (currentUrlWithPath model.url.path model) (UpdateCacheAndUrlNew False model.url Nothing)
ProcessFetchResponse transitionId response toMsg ->
case response of
Ok ( _, ResponseSketch.Redirect redirectTo ) ->
let
isAbsoluteUrl : Bool
isAbsoluteUrl =
Url.fromString redirectTo /= Nothing
in
if isAbsoluteUrl then
( model, BrowserLoadUrl redirectTo )
else
( model, NoEffect )
|> startNewGetLoad (currentUrlWithPath redirectTo model) toMsg
_ ->
update config (toMsg response) (clearLoadingFetchersAfterDataLoad transitionId model)
UserMsg userMsg_ ->
case userMsg_ of
Pages.Internal.Msg.UserMsg userMsg ->
( model, NoEffect )
|> performUserMsg userMsg config
Pages.Internal.Msg.Submit fields ->
if fields.valid then
let
payload : { fields : List ( String, String ), method : Form.Method, action : String, id : Maybe String }
payload =
{ fields = fields.fields
, method = fields.method
, action = fields.action
, id = Just fields.id
}
in
if fields.useFetcher then
( { model | nextTransitionKey = model.nextTransitionKey + 1 }
, SubmitFetcher fields.id model.nextTransitionKey payload
)
|> (case fields.msg of
Just justUserMsg ->
performUserMsg justUserMsg config
Nothing ->
identity
)
else
( { model
-- TODO should I setSubmitAttempted here, too?
| transition =
Just
( -- TODO remove hardcoded number
-1
, Pages.Navigation.Submitting payload
)
}
, Submit payload
)
|> (case fields.msg of
Just justUserMsg ->
performUserMsg justUserMsg config
Nothing ->
identity
)
else
-- TODO should the user msg still be run if the form is invalid?
( model, NoEffect )
Pages.Internal.Msg.FormMsg formMsg ->
-- TODO when init is called for a new page, also need to clear out client-side `pageFormState`
let
( formModel, formCmd ) =
Form.update formMsg model.pageFormState
in
( { model | pageFormState = formModel }
, RunCmd (Cmd.map UserMsg formCmd)
)
Pages.Internal.Msg.NoOp ->
( model, NoEffect )
UpdateCacheAndUrlNew scrollToTopWhenDone urlWithoutRedirectResolution maybeUserMsg updateResult ->
-- TODO remove all fetchers that are in the state `FetcherReloading` here -- I think that's the right logic?
case
Result.map2 Tuple.pair
(updateResult
|> Result.mapError (\_ -> "Http error")
)
model.pageData
of
Ok ( ( newUrl, newData ), previousPageData ) ->
let
redirectPending : Bool
redirectPending =
newUrl /= urlWithoutRedirectResolution
in
if redirectPending then
( { model
| pendingRedirect = True
, pendingData =
case newData of
ResponseSketch.RenderPage pageData actionData ->
Just ( pageData, previousPageData.sharedData, actionData )
ResponseSketch.HotUpdate pageData sharedData actionData ->
Just ( pageData, sharedData, actionData )
_ ->
Nothing
}
, BrowserReplaceUrl newUrl.path
)
else
let
stayingOnSamePath : Bool
stayingOnSamePath =
newUrl.path == model.url.path
( newPageData, newSharedData, newActionData ) =
case newData of
ResponseSketch.RenderPage pageData actionData ->
( pageData, previousPageData.sharedData, actionData )
ResponseSketch.HotUpdate pageData sharedData actionData ->
( pageData, sharedData, actionData )
_ ->
( previousPageData.pageData, previousPageData.sharedData, previousPageData.actionData )
updatedPageData : { userModel : userModel, sharedData : sharedData, actionData : Maybe actionData, pageData : pageData }
updatedPageData =
{ userModel = userModel
, sharedData = newSharedData
, pageData = newPageData
, actionData = newActionData
}
( userModel, userEffect ) =
-- TODO if urlWithoutRedirectResolution is different from the url with redirect resolution, then
-- instead of calling update, call pushUrl (I think?)
-- TODO include user Cmd
if stayingOnSamePath then
( previousPageData.userModel, NoEffect )
else
config.update model.pageFormState
(model.inFlightFetchers |> toFetcherState)
(model.transition |> Maybe.map Tuple.second)
newSharedData
newPageData
model.key
(config.onPageChange
{ protocol = model.url.protocol
, host = model.url.host
, port_ = model.url.port_
, path = urlPathToPath urlWithoutRedirectResolution
, query = urlWithoutRedirectResolution.query
, fragment = urlWithoutRedirectResolution.fragment
, metadata = config.urlToRoute urlWithoutRedirectResolution
}
)
previousPageData.userModel
|> Tuple.mapSecond UserCmd
updatedModel : Model userModel pageData actionData sharedData
updatedModel =
-- TODO should these be the same (no if)?
if model.pendingRedirect || redirectPending then
{ model
| url = newUrl
, pageData = Ok updatedPageData
, transition = Nothing
, pendingRedirect = False
, pageFormState = Dict.empty
}
else
{ model
| url = newUrl
, pageData = Ok updatedPageData
, pendingRedirect = False
, transition = Nothing
}
onActionMsg : Maybe userMsg
onActionMsg =
newActionData |> Maybe.andThen config.onActionData
in
( { updatedModel
| ariaNavigationAnnouncement = mainView config updatedModel |> .title
, currentPath = newUrl.path
}
, if not stayingOnSamePath && scrollToTopWhenDone then
Batch
[ ScrollToTop
, userEffect
]
else
userEffect
)
|> (case maybeUserMsg of
Just userMsg ->
withUserMsg config userMsg
Nothing ->
identity
)
|> (case onActionMsg of
Just actionMsg ->
withUserMsg config actionMsg
Nothing ->
identity
)
Err _ ->
{-
When there is an error loading the content.dat, we are either
1) in the dev server, and should show the relevant BackendTask error for the page
we're navigating to. This could be done more cleanly, but it's simplest to just
do a fresh page load and use the code path for presenting an error for a fresh page.
2) In a production app. That means we had a successful build, so there were no BackendTask failures,
so the app must be stale (unless it's in some unexpected state from a bug). In the future,
it probably makes sense to include some sort of hash of the app version we are fetching, match
it with the current version that's running, and perform this logic when we see there is a mismatch.
But for now, if there is any error we do a full page load (not a single-page navigation), which
gives us a fresh version of the app to make sure things are in sync.
-}
( model
, urlWithoutRedirectResolution
|> Url.toString
|> BrowserLoadUrl
)
PageScrollComplete ->
( model, NoEffect )
HotReloadCompleteNew pageDataBytes ->
model.pageData
|> Result.map
(\pageData ->
let
newThing : Maybe (ResponseSketch pageData actionData sharedData)
newThing =
-- TODO if ErrorPage, call ErrorPage.init to get appropriate Model?
pageDataBytes
|> Bytes.Decode.decode config.decodeResponse
in
case newThing of
Just (ResponseSketch.RenderPage newPageData newActionData) ->
( { model
| pageData =
Ok
{ userModel = pageData.userModel
, sharedData = pageData.sharedData
, pageData = newPageData
, actionData = newActionData
}
, notFound = Nothing
}
, NoEffect
)
Just (ResponseSketch.HotUpdate newPageData newSharedData newActionData) ->
( { model
| pageData =
Ok
{ userModel = pageData.userModel
, sharedData = newSharedData
, pageData = newPageData
, actionData = newActionData
}
, notFound = Nothing
}
, NoEffect
)
Just (ResponseSketch.NotFound info) ->
( { model | notFound = Just info }, NoEffect )
_ ->
( model, NoEffect )
)
|> Result.withDefault
(let
pageDataResult : Maybe (InitKind sharedData pageData actionData errorPage)
pageDataResult =
case Bytes.Decode.decode config.decodeResponse pageDataBytes of
Just (ResponseSketch.RenderPage _ _) ->
Nothing
Just (ResponseSketch.HotUpdate pageData shared actionData) ->
OkPage shared pageData actionData
|> Just
Just (ResponseSketch.NotFound notFound) ->
NotFound notFound
|> Just
_ ->
Nothing
in
case pageDataResult of
Just (OkPage sharedData pageData actionData) ->
let
urls : { currentUrl : Url, basePath : List String }
urls =
{ currentUrl = model.url
, basePath = config.basePath
}
pagePath : UrlPath
pagePath =
urlsToPagePath urls
userFlags : Pages.Flags.Flags
userFlags =
model.userFlags
|> Decode.decodeValue
(Decode.field "userFlags" Decode.value)
|> Result.withDefault Json.Encode.null
|> Pages.Flags.BrowserFlags
( userModel, userCmd ) =
Just
{ path =
{ path = pagePath
, query = model.url.query
, fragment = model.url.fragment
}
, metadata = config.urlToRoute model.url
, pageUrl =
Just
{ protocol = model.url.protocol
, host = model.url.host
, port_ = model.url.port_
, path = pagePath
, query = model.url.query |> Maybe.map QueryParams.fromString |> Maybe.withDefault Dict.empty
, fragment = model.url.fragment
}
}
|> config.init userFlags sharedData pageData actionData
cmd : Effect userMsg pageData actionData sharedData userEffect errorPage
cmd =
UserCmd userCmd
in
( { model
| pageData =
Ok
{ userModel = userModel
, sharedData = sharedData
, pageData = pageData
, actionData = actionData
}
, notFound = Nothing
}
, cmd
)
_ ->
( model, NoEffect )
)
FetcherStarted fetcherKey transitionId fetcherData initiatedAt ->
( { model
| inFlightFetchers =
model.inFlightFetchers
|> Dict.insert fetcherKey
( transitionId
, { payload = fetcherData
, status = Pages.ConcurrentSubmission.Submitting
, initiatedAt = initiatedAt
}
)
}
, NoEffect
)
toFetcherState : Dict String ( Int, Pages.ConcurrentSubmission.ConcurrentSubmission actionData ) -> Dict String (Pages.ConcurrentSubmission.ConcurrentSubmission actionData)
toFetcherState inFlightFetchers =
inFlightFetchers
|> Dict.map (\_ ( _, fetcherState ) -> fetcherState)
performUserMsg :
userMsg
-> ProgramConfig userMsg userModel route pageData actionData sharedData userEffect (Msg userMsg pageData actionData sharedData errorPage) errorPage
-> ( Model userModel pageData actionData sharedData, Effect userMsg pageData actionData sharedData userEffect errorPage )
-> ( Model userModel pageData actionData sharedData, Effect userMsg pageData actionData sharedData userEffect errorPage )
performUserMsg userMsg config ( model, effect ) =
case model.pageData of
Ok pageData ->
let
( userModel, userCmd ) =
config.update model.pageFormState (model.inFlightFetchers |> toFetcherState) (model.transition |> Maybe.map Tuple.second) pageData.sharedData pageData.pageData model.key userMsg pageData.userModel
updatedPageData : Result error { userModel : userModel, pageData : pageData, actionData : Maybe actionData, sharedData : sharedData }
updatedPageData =
Ok { pageData | userModel = userModel }
in
( { model | pageData = updatedPageData }
, Batch [ effect, UserCmd userCmd ]
)
Err _ ->
( model, effect )
perform : ProgramConfig userMsg userModel route pageData actionData sharedData userEffect (Msg userMsg pageData actionData sharedData errorPage) errorPage -> Model userModel pageData actionData sharedData -> Effect userMsg pageData actionData sharedData userEffect errorPage -> Cmd (Msg userMsg pageData actionData sharedData errorPage)
perform config model effect =
-- elm-review: known-unoptimized-recursion
case effect of
NoEffect ->
Cmd.none
RunCmd cmd ->
cmd
Batch effects ->
effects
|> List.map (perform config model)
|> Cmd.batch
ScrollToTop ->
Task.perform (\_ -> PageScrollComplete) (Dom.setViewport 0 0)
BrowserLoadUrl url ->
Browser.Navigation.load url
BrowserPushUrl url ->
model.key
|> Maybe.map
(\key ->
Browser.Navigation.pushUrl key url
)
|> Maybe.withDefault Cmd.none
BrowserReplaceUrl url ->
model.key
|> Maybe.map
(\key ->
Browser.Navigation.replaceUrl key url
)
|> Maybe.withDefault Cmd.none
FetchPageData transitionKey maybeRequestInfo url toMsg ->
fetchRouteData transitionKey toMsg config url maybeRequestInfo
Submit fields ->
if fields.method == Form.Get then
model.key
|> Maybe.map (\key -> Browser.Navigation.pushUrl key (appendFormQueryParams fields))
|> Maybe.withDefault Cmd.none
else
let
urlToSubmitTo : Url
urlToSubmitTo =
-- TODO add optional path parameter to Submit variant to allow submitting to other routes
model.url
in
fetchRouteData -1 (UpdateCacheAndUrlNew False model.url Nothing) config urlToSubmitTo (Just fields)
SubmitFetcher fetcherKey transitionId formData ->
startFetcher2 config False fetcherKey transitionId formData model
UserCmd cmd ->
case model.key of
Just key ->
let
prepare :
(Result Http.Error Url -> userMsg)
-> Result Http.Error ( Url, ResponseSketch pageData actionData sharedData )
-> Msg userMsg pageData actionData sharedData errorPage
prepare toMsg info =
UpdateCacheAndUrlNew False model.url (info |> Result.map Tuple.first |> toMsg |> Just) info
in
cmd
|> config.perform
{ fetchRouteData =
\fetchInfo ->
fetchRouteData
-1
(prepare fetchInfo.toMsg)
config
(urlFromAction model.url fetchInfo.data)
fetchInfo.data
---- TODO map the Msg with the wrapper type (like in the PR branch)
, submit =
\fetchInfo ->