/
Doc.elm
3423 lines (2830 loc) · 110 KB
/
Doc.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 Page.Doc exposing (Model, Msg, getTitle, init, subscriptions, toUser, update, view)
import Ant.Icons.Svg as AntIcons
import Browser.Dom exposing (Element)
import Bytes exposing (Bytes)
import Coders exposing (sortByEncoder, treeToMarkdownString, treeToValue)
import Debouncer.Basic as Debouncer exposing (Debouncer, fromSeconds, provideInput, toDebouncer)
import Doc.ContactForm as ContactForm
import Doc.Data as Data
import Doc.Data.Conflict exposing (Selection)
import Doc.Fonts as Fonts
import Doc.Fullscreen as Fullscreen
import Doc.List as DocList exposing (Model(..))
import Doc.Metadata as Metadata exposing (Metadata)
import Doc.Switcher
import Doc.TreeStructure as TreeStructure exposing (defaultTree)
import Doc.TreeUtils exposing (..)
import Doc.UI as UI exposing (countWords, viewConflict, viewMobileButtons, viewSearchField)
import File exposing (File)
import File.Download as Download
import File.Select as Select
import Html exposing (Html, div, h1, span, text, textarea, ul)
import Html.Attributes exposing (attribute, class, classList, dir, id, style, title, value)
import Html.Events exposing (onClick, onDoubleClick, onInput)
import Html.Extra exposing (viewIf)
import Html.Keyed as Keyed
import Html.Lazy exposing (lazy2, lazy4, lazy5, lazy7, lazy8)
import Html5.DragDrop as DragDrop
import Http
import Import.Bulk.UI as ImportModal
import Import.Incoming
import Import.Single
import Json.Decode as Json
import Json.Encode as Enc
import List.Extra as ListExtra
import Markdown
import Outgoing exposing (Msg(..), send)
import Page.Doc.Export as Export exposing (ExportFormat(..), ExportSelection(..), exportView, exportViewError)
import Page.Doc.Incoming as Incoming exposing (Msg(..))
import Page.Doc.Theme as Theme exposing (Theme(..), applyTheme, setTourStep)
import Process
import Random
import RandomId
import Regex
import Route
import Session exposing (Session)
import Svg exposing (circle, mask, rect, svg)
import Svg.Attributes exposing (cx, cy, height, preserveAspectRatio, r, rx, ry, viewBox, width, x, y)
import Task
import Time
import Translation exposing (Language, TranslationId(..), langToString, tr)
import Types exposing (..)
import Upgrade exposing (Msg(..))
import Utils exposing (randomPositiveInt)
-- MODEL
type alias Model =
-- Document state
{ workingTree : TreeStructure.Model
, data : Data.Model
, metadata : Metadata
-- SPA Page State
, session : Session
, loading : Bool
-- Transient state
, viewState : ViewState
, dirty : Bool
, lastLocalSave : Maybe Time.Posix
, lastRemoteSave : Maybe Time.Posix
, field : String
, textCursorInfo : TextCursorInfo
, debouncerStateCommit : Debouncer () ()
, titleField : Maybe String
, sidebarState : SidebarState
, sidebarMenuState : SidebarMenuState
, modalState : ModalState
, fileSearchField : String
, headerMenu : HeaderMenuState
, exportSettings : ( ExportSelection, ExportFormat )
, wordcountTrayOpen : Bool
, tourStep : Maybe Int
, tooltip : Maybe ( Element, TooltipPosition, String )
, fontSelectorOpen : Bool
-- Settings
, uid : String
, fonts : Fonts.Model
, theme : Theme
, startingWordcount : Int
}
type ModalState
= NoModal
| FileSwitcher Doc.Switcher.Model
| SidebarContextMenu String ( Float, Float )
| TemplateSelector
| Wordcount
| ImportModal ImportModal.Model
| ContactForm ContactForm.Model
| UpgradeModal
defaultModel : Bool -> Session -> String -> Model
defaultModel isNew session docId =
{ workingTree = TreeStructure.defaultModel
, data = Data.empty
, metadata = Metadata.new docId
, session = session
, loading = not isNew
, debouncerStateCommit =
Debouncer.throttle (fromSeconds 3)
|> Debouncer.settleWhenQuietFor (Just <| fromSeconds 3)
|> toDebouncer
, uid = "0"
, viewState =
{ active = "1"
, viewMode =
if isNew then
Editing
else
Normal
, activePast = []
, descendants = []
, ancestors = [ "0" ]
, searchField = Nothing
, dragModel = DragDrop.init
, draggedTree = Nothing
, copiedTree = Nothing
, clipboardTree = Nothing
, collaborators = []
}
, dirty = False
, lastLocalSave = Nothing
, lastRemoteSave = Nothing
, field = ""
, textCursorInfo = { selected = False, position = End, text = ( "", "" ) }
, titleField = Nothing
, sidebarState =
if Session.fileMenuOpen session then
File
else
SidebarClosed
, sidebarMenuState = NoSidebarMenu
, modalState = NoModal
, fileSearchField = ""
, headerMenu = NoHeaderMenu
, exportSettings = ( ExportEverything, DOCX )
, wordcountTrayOpen = False
, tourStep = Nothing
, tooltip = Nothing
, fontSelectorOpen = False
, fonts = Fonts.default
, theme = Default
, startingWordcount = 0
}
init : Session -> String -> Bool -> ( Model, Cmd Msg )
init session dbName isNew =
let
initModel =
defaultModel isNew session dbName
in
if isNew then
( initModel
, Cmd.batch
[ send <| InitDocument dbName
, focus "1"
]
)
|> activate "1" True
|> addToHistoryDo
else
( initModel, send <| LoadDocument dbName )
toUser : Model -> Session
toUser model =
model.session
getTitle : Model -> String
getTitle model =
Metadata.getDocName model.metadata
|> Maybe.withDefault "Untitled"
-- UPDATE
type Msg
= NoOp
-- === Card Activation ===
| Activate String
| SearchFieldUpdated String
-- === Card Editing ===
| OpenCard String String
| UpdateActiveField String String
| FullscreenMsg Fullscreen.Msg
| DeleteCard String
-- === Card Insertion ===
| InsertAbove String
| InsertBelow String
| InsertChild String
-- === Card Moving ===
| DragDropMsg (DragDrop.Msg String DropId)
-- === History ===
| ThrottledCommit (Debouncer.Msg ())
| Commit Time.Posix
| CheckoutCommit String
| Restore
| CancelHistory
| SetSelection String Selection String
| Resolve String
-- === UI ===
| ReceivedDocuments DocList.Model
| SettingsChanged Json.Value
| LogoutRequested
| LoginStateChanged Session
| TitleFocused
| TitleFieldChanged String
| TitleEdited
| TitleEditCanceled
| ToggledHelpMenu Bool
| LanguageMenuRequested (Maybe String)
| LanguageMenuReceived Element
| ToggledAccountMenu Bool
-- Sidebar & Modals
| SidebarStateChanged SidebarState
| TemplateSelectorOpened
| SwitcherOpened
| SwitcherClosed
| WordcountModalOpened
| ModalClosed
| ImportBulkClicked
| ImportJSONRequested
| FileSearchChanged String
| SortByChanged SortBy
| SidebarContextClicked String ( Float, Float )
| DuplicateDoc String
| DeleteDoc String
| HistoryToggled Bool
| DocSettingsToggled Bool
| ExportPreviewToggled Bool
| ExportSelectionChanged ExportSelection
| ExportFormatChanged ExportFormat
-- Upgrade
| ToggledUpgradeModal Bool
| UpgradeModalMsg Upgrade.Msg
-- HELP
| ClickedEmailSupport
| TourStep (Maybe Int)
| ContactFormMsg ContactForm.Model ContactForm.Msg
| CopyEmailClicked Bool
| ContactFormSubmitted ContactForm.Model
| ContactFormSent (Result Http.Error ())
-- Import
| ImportModalMsg ImportModal.Msg
| ImportJSONSelected File
| ImportJSONLoaded String String
| ImportJSONIdGenerated Tree String String
| ImportJSONCompleted String
| ImportBulkCompleted
-- Misc UI
| LanguageChanged Language
| ThemeChanged Theme
| TooltipRequested String TooltipPosition String
| TooltipReceived Element TooltipPosition String
| TooltipClosed
| FullscreenRequested
| PrintRequested
| TimeUpdate Time.Posix
| FontsMsg Fonts.Msg
| ShortcutTrayToggle
-- === Ports ===
| Pull
| Export
| Exported String (Result Http.Error Bytes)
| Incoming Incoming.Msg
| LogErr String
update : Msg -> Model -> ( Model, Cmd Msg )
update msg ({ workingTree } as model) =
let
vs =
model.viewState
in
case msg of
-- === Card Activation ===
Activate id ->
( model
, Cmd.none
)
|> saveCardIfEditing
|> activate id False
SearchFieldUpdated inputField ->
let
searchFilter term_ cols =
case term_ of
Just term ->
let
hasTerm tree =
term
|> Regex.fromStringWith { caseInsensitive = True, multiline = False }
|> Maybe.withDefault Regex.never
|> (\t -> Regex.contains t tree.content)
in
cols
|> List.map (\c -> List.map (\g -> List.filter hasTerm g) c)
Nothing ->
cols
( maybeBlur, newSearchField ) =
case inputField of
"" ->
( \( m, c ) ->
( m
, Cmd.batch [ c, Task.attempt (\_ -> NoOp) (Browser.Dom.blur "search-input") ]
)
, Nothing
)
str ->
( identity
, Just str
)
filteredCardIds =
searchFilter newSearchField model.workingTree.columns
|> List.map (\c -> List.map (\g -> List.map .id g) c)
|> List.concat
|> List.concat
allCardsInOrder =
getDescendants model.workingTree.tree
|> List.map .id
firstFilteredCardId_ =
ListExtra.find (\cId -> List.member cId filteredCardIds) allCardsInOrder
maybeActivate =
case ( newSearchField, firstFilteredCardId_ ) of
( Just _, Just id ) ->
activate id False
( Nothing, _ ) ->
activate vs.active False
_ ->
identity
in
( { model | viewState = { vs | searchField = newSearchField } }
, Cmd.none
)
|> maybeBlur
|> maybeActivate
-- === Card Editing ===
OpenCard id str ->
( model
, Cmd.none
)
|> openCard id str
UpdateActiveField id str ->
( { model
| field = str
, dirty = True
}
, Cmd.batch
[ send <| SetDirty True
, send <| SetTextareaClone id str
]
)
FullscreenMsg fullscreenMsg ->
case fullscreenMsg of
Fullscreen.OpenCard id str ->
( model
, Cmd.none
)
|> saveCardIfEditing
|> openCardFullscreen id str
Fullscreen.UpdateField id str ->
( { model | dirty = True, field = str }
, send <| SetDirty True
)
|> (if vs.active /= id then
activate id False
else
identity
)
Fullscreen.ExitFullscreenRequested ->
exitFullscreen model
DeleteCard id ->
( model
, Cmd.none
)
|> deleteCard id
-- === Card Insertion ===
InsertAbove id ->
( model
, Cmd.none
)
|> insertAbove id ""
InsertBelow id ->
( model
, Cmd.none
)
|> insertBelow id ""
InsertChild id ->
( model
, Cmd.none
)
|> insertChild id ""
-- === Card Moving ===
DragDropMsg dragDropMsg ->
let
( newDragModel, dragResult_ ) =
DragDrop.update dragDropMsg vs.dragModel
modelDragUpdated =
{ model
| viewState =
{ vs
| dragModel = newDragModel
}
}
in
case ( DragDrop.getDragId newDragModel, dragResult_ ) of
( Just _, Nothing ) ->
-- Dragging
( modelDragUpdated
, DragDrop.getDragstartEvent dragDropMsg
|> Maybe.map .event
|> Maybe.map (\json -> send <| DragStart json)
|> Maybe.withDefault Cmd.none
)
( Nothing, Just ( _, dropId, _ ) ) ->
-- Drop success
case vs.draggedTree of
Just ( draggedTree, _, _ ) ->
let
moveOperation =
case dropId of
Into id ->
move draggedTree id 999999
Above id ->
move draggedTree
((getParent id model.workingTree.tree |> Maybe.map .id) |> Maybe.withDefault "0")
((getIndex id model.workingTree.tree |> Maybe.withDefault 0) |> Basics.max 0)
Below id ->
move draggedTree
((getParent id model.workingTree.tree |> Maybe.map .id) |> Maybe.withDefault "0")
((getIndex id model.workingTree.tree |> Maybe.withDefault 0) + 1)
in
( { modelDragUpdated | viewState = { vs | draggedTree = Nothing }, dirty = True }, send <| SetDirty True )
|> moveOperation
Nothing ->
( modelDragUpdated, Cmd.none )
( Nothing, Nothing ) ->
-- NotDragging
case vs.draggedTree of
Just ( draggedTree, parentId, idx ) ->
( modelDragUpdated, Cmd.none )
|> move draggedTree parentId idx
Nothing ->
( modelDragUpdated, Cmd.none )
( Just _, Just _ ) ->
-- Should be Impossible: both Dragging and Dropped
( modelDragUpdated, Cmd.none )
-- === History ===
ThrottledCommit subMsg ->
let
( subModel, subCmd, emitted_ ) =
Debouncer.update subMsg model.debouncerStateCommit
mappedCmd =
Cmd.map ThrottledCommit subCmd
updatedModel =
{ model | debouncerStateCommit = subModel }
in
case emitted_ of
Just () ->
( updatedModel
, Cmd.batch [ Task.perform Commit Time.now, mappedCmd ]
)
Nothing ->
( updatedModel, mappedCmd )
Commit time ->
( { model | session = Session.updateTime time model.session }, Cmd.none )
|> addToHistoryDo
CheckoutCommit commitSha ->
case model.headerMenu of
HistoryView historyState ->
( { model | headerMenu = HistoryView { historyState | currentView = commitSha } }
, Cmd.none
)
|> checkoutCommit commitSha
_ ->
( model, Cmd.none )
Restore ->
( { model | headerMenu = NoHeaderMenu }
, Cmd.none
)
|> addToHistoryDo
CancelHistory ->
case model.headerMenu of
HistoryView historyState ->
( { model | headerMenu = NoHeaderMenu, tooltip = Nothing }
, Cmd.none
)
|> checkoutCommit historyState.start
_ ->
( model
, Cmd.none
)
SetSelection cid selection id ->
let
newData =
Data.conflictSelection cid selection model.data
in
( { model
| data = newData
, workingTree = TreeStructure.setTreeWithConflicts (Data.conflictList newData) model.workingTree.tree model.workingTree
}
, Cmd.none
)
|> activate id True
Resolve cid ->
let
newData =
Data.resolve cid model.data
in
( { model
| data = newData
, workingTree = TreeStructure.setTreeWithConflicts (Data.conflictList newData) model.workingTree.tree model.workingTree
}
, Cmd.none
)
|> addToHistory
-- === UI ===
ReceivedDocuments newListState ->
let
updatedSession =
Session.updateDocuments newListState model.session
( newModel, newCmd ) =
case DocList.current model.metadata newListState of
Just currentMetadata ->
( { model | metadata = currentMetadata, titleField = Metadata.getDocName currentMetadata, session = updatedSession }, Cmd.none )
Nothing ->
( { model | session = updatedSession }
, Route.replaceUrl (Session.navKey model.session) Route.Root
)
in
( newModel, newCmd )
SettingsChanged json ->
( { model | session = Session.sync json model.session }, Cmd.none )
TitleFocused ->
case model.titleField of
Nothing ->
( model, send <| SelectAll "title-rename" )
Just _ ->
( model, Cmd.none )
TitleFieldChanged newTitle ->
( { model | titleField = Just newTitle }, Cmd.none )
TitleEdited ->
case model.titleField of
Just editedTitle ->
if String.trim editedTitle == "" then
( model, Cmd.batch [ send <| Alert "Title cannot be blank", Task.attempt (always NoOp) (Browser.Dom.focus "title-rename") ] )
else if Just editedTitle /= Metadata.getDocName model.metadata then
( model, Cmd.batch [ send <| RenameDocument editedTitle, Task.attempt (always NoOp) (Browser.Dom.blur "title-rename") ] )
else
( model, Cmd.none )
Nothing ->
( model, Cmd.none )
TitleEditCanceled ->
( { model | titleField = Metadata.getDocName model.metadata }, Task.attempt (always NoOp) (Browser.Dom.blur "title-rename") )
LogoutRequested ->
( model, Session.logout )
LoginStateChanged newUser ->
( { model | session = newUser }, Route.pushUrl (Session.navKey newUser) Route.Login )
ToggledHelpMenu isOpen ->
let
( newDropdownState, newSidebarState ) =
if isOpen then
( Help, SidebarClosed )
else
( NoSidebarMenu, model.sidebarState )
newTourStep =
if model.tourStep == Just 6 then
Just 7
else
model.tourStep
in
( { model
| sidebarMenuState = newDropdownState
, sidebarState = newSidebarState
, tooltip = Nothing
, tourStep = newTourStep
}
, Cmd.none
)
LanguageMenuRequested elId_ ->
case ( elId_, model.sidebarMenuState ) of
( Just elId, Account _ ) ->
( model
, Browser.Dom.getElement elId
|> Task.attempt
(\result ->
case result of
Ok el ->
LanguageMenuReceived el
Err _ ->
NoOp
)
)
_ ->
( { model | sidebarMenuState = Account Nothing }, Cmd.none )
LanguageMenuReceived el ->
( { model | sidebarMenuState = Account (Just el) }, Cmd.none )
ToggledAccountMenu isOpen ->
let
( newDropdownState, newSidebarState ) =
if isOpen then
( Account Nothing, SidebarClosed )
else
( NoSidebarMenu, model.sidebarState )
in
( { model
| sidebarMenuState = newDropdownState
, sidebarState = newSidebarState
, tooltip = Nothing
}
, Cmd.none
)
ToggledUpgradeModal isOpen ->
( { model
| modalState =
if isOpen then
UpgradeModal
else
NoModal
}
, Cmd.none
)
UpgradeModalMsg upgradeModalMsg ->
case upgradeModalMsg of
UpgradeModalClosed ->
( { model | modalState = NoModal }, Cmd.none )
CheckoutClicked checkoutData ->
case Session.name model.session of
Just email ->
let
data =
Upgrade.toValue email checkoutData
in
( model, send <| CheckoutButtonClicked data )
Nothing ->
( model, Cmd.none )
_ ->
let
newSession =
Session.updateUpgrade upgradeModalMsg model.session
maybeFlash =
case upgradeModalMsg of
PlanChanged _ ->
send <| FlashPrice
_ ->
Cmd.none
in
( { model | session = newSession }, maybeFlash )
ClickedEmailSupport ->
let
fromEmail =
Session.name model.session
|> Maybe.withDefault ""
in
( { model | modalState = ContactForm (ContactForm.init fromEmail), sidebarMenuState = NoSidebarMenu }
, Task.attempt (\_ -> NoOp) (Browser.Dom.focus "contact-body")
)
TourStep step_ ->
( { model | tourStep = step_ }, Cmd.none )
ContactFormMsg formModel formMsg ->
( { model | modalState = ContactForm (ContactForm.update formMsg formModel) }, Cmd.none )
CopyEmailClicked isUrgent ->
if isUrgent then
( model, send <| CopyToClipboard "{%SUPPORT_URGENT_EMAIL%}" "#email-copy-btn" )
else
( model, send <| CopyToClipboard "{%SUPPORT_EMAIL%}" "#email-copy-btn" )
ContactFormSubmitted formModel ->
( model, ContactForm.send ContactFormSent formModel )
ContactFormSent res ->
case res of
Ok _ ->
( { model | modalState = NoModal }, Cmd.none )
_ ->
( model, Cmd.none )
SidebarStateChanged newSidebarState ->
let
( newSessionData, maybeSaveSidebarState ) =
case newSidebarState of
File ->
( Session.setFileOpen True model.session, send <| SetSidebarState True )
_ ->
( Session.setFileOpen True model.session, send <| SetSidebarState False )
newDropdownState =
case ( newSidebarState, model.sidebarMenuState ) of
( File, Help ) ->
NoSidebarMenu
( File, Account _ ) ->
NoSidebarMenu
( _, _ ) ->
model.sidebarMenuState
in
( { model
| session = newSessionData
, sidebarState = newSidebarState
, tooltip = Nothing
, sidebarMenuState = newDropdownState
}
, maybeSaveSidebarState
)
TemplateSelectorOpened ->
let
newTourStep =
if model.tourStep == Just 7 then
Nothing
else
model.tourStep
in
( { model | modalState = TemplateSelector, tourStep = newTourStep }, Cmd.none )
SwitcherOpened ->
openSwitcher model
SwitcherClosed ->
closeSwitcher model
WordcountModalOpened ->
( { model | modalState = Wordcount, headerMenu = NoHeaderMenu }, Cmd.none )
ModalClosed ->
( { model | modalState = NoModal }, Cmd.none )
ImportBulkClicked ->
( { model | modalState = ImportModal (ImportModal.init model.session) }, Cmd.none )
FileSearchChanged term ->
let
updatedModal =
case model.modalState of
FileSwitcher switcherModel ->
FileSwitcher (Doc.Switcher.search term switcherModel)
_ ->
model.modalState
in
( { model | fileSearchField = term, modalState = updatedModal }, Cmd.none )
SortByChanged newSort ->
let
newSession =
Session.setSortBy newSort model.session
in
( { model | session = newSession }, send <| SaveUserSetting ( "sortBy", sortByEncoder newSort ) )
SidebarContextClicked docId ( x, y ) ->
( { model | modalState = SidebarContextMenu docId ( x, y ) }, Cmd.none )
DuplicateDoc docId ->
( { model | modalState = NoModal }, Route.replaceUrl (Session.navKey model.session) (Route.Copy docId) )
DeleteDoc docId ->
( { model | modalState = NoModal }, send <| RequestDelete docId )
HistoryToggled isOpen ->
model |> toggleHistory isOpen
DocSettingsToggled isOpen ->
( { model
| headerMenu =
if isOpen then
Settings
else
NoHeaderMenu
, tooltip = Nothing
}
, Cmd.none
)
ExportPreviewToggled previewEnabled ->
( { model
| headerMenu =
if previewEnabled then
ExportPreview
else
NoHeaderMenu
, tooltip = Nothing
}
, Cmd.none
)
|> activate vs.active True
ExportSelectionChanged expSel ->
( { model | exportSettings = Tuple.mapFirst (always expSel) model.exportSettings }, Cmd.none )
ExportFormatChanged expFormat ->
( { model | exportSettings = Tuple.mapSecond (always expFormat) model.exportSettings }, Cmd.none )
ImportModalMsg modalMsg ->
case model.modalState of
ImportModal importModal ->
let
( newModalState, newCmd ) =
ImportModal.update modalMsg importModal
|> Tuple.mapBoth ImportModal (Cmd.map ImportModalMsg)
in
( { model | modalState = newModalState }, newCmd )
_ ->
( model, Cmd.none )
ImportJSONRequested ->
( model, Select.file [ "application/json", "text/plain" ] ImportJSONSelected )
ImportJSONSelected file ->
( model, Task.perform (ImportJSONLoaded (File.name file)) (File.toString file) )
ImportJSONLoaded fileName jsonString ->
let
( importTreeDecoder, newSeed ) =
Import.Single.decoder (Session.seed model.session)
newSession =
Session.setSeed newSeed model.session
in
case Json.decodeString importTreeDecoder jsonString of
Ok tree ->
( { model | loading = True, session = newSession }
, RandomId.generate (ImportJSONIdGenerated tree fileName)
)
Err err ->
( { model | session = newSession }, Cmd.none )
ImportJSONIdGenerated tree fileName docId ->
let
author =
model.session |> Session.name |> Maybe.withDefault "jane.doe@gmail.com"
commitReq_ =
Data.requestCommit tree author Data.empty (Metadata.new docId |> Metadata.renameAndEncode fileName)
in
case commitReq_ of
Just commitReq ->
( model, send <| SaveImportedData commitReq )
Nothing ->
( model, Cmd.none )
ImportJSONCompleted docId ->
( model, Route.pushUrl (Session.navKey model.session) (Route.DocUntitled docId) )
ImportBulkCompleted ->
( { model | modalState = NoModal }, Cmd.none )
LanguageChanged newLang ->
if newLang /= Session.language model.session then
( { model
| session = Session.setLanguage newLang model.session
, sidebarMenuState = NoSidebarMenu
}
, send <| SaveUserSetting ( "language", langToString newLang |> Enc.string )
)
else
( model, Cmd.none )
ThemeChanged newTheme ->
( { model | theme = newTheme }, send <| SaveThemeSetting newTheme )
TooltipRequested elId tipPos content ->
( model
, Browser.Dom.getElement elId
|> Task.attempt
(\result ->
case result of
Ok el ->
TooltipReceived el tipPos content
Err _ ->
NoOp
)
)
TooltipReceived el tipPos content ->
( { model | tooltip = Just ( el, tipPos, content ) }, Cmd.none )
TooltipClosed ->
( { model | tooltip = Nothing }, Cmd.none )
FullscreenRequested ->
( model, send <| RequestFullscreen )
PrintRequested ->
( model, send <| Print )
TimeUpdate time ->
( { model | session = Session.updateTime time model.session }