-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.ur
2044 lines (2015 loc) · 96.6 KB
/
main.ur
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
open Datatypes
open Css
open Utils
open Payments
open Import
open SubItem
open Share
open Uim
open Feeds
open Discovery
open Articles
open Filters
open Appearance
open Account
structure P = Popups
val _ = Settings.imagesWidthEq
val _ = Settings.feedAlignEq
val showLeftPanel = Unsafe.boolSource "Main.showLeftPanel" False
val toggleLeftPanel =
s <- get showLeftPanel;
Js.blurActiveElement;
Js.enableMenuTransitions;
P.toggleExternalPopup showLeftPanel
val userExperimentEq : eq userExperiment =
mkEq (fn a b => case (a,b) of
| (UENo9, UENo9) => True
)
val tupleEq : eq (string * string) =
mkEq (fn (a1,a2) (b1,b2) => a1=b1 && a2=b2)
val eqPaidTill : eq paidTill =
mkEq (fn a b => case (a,b) of
| (PTUnknown, PTUnknown) => True
| (PTFreeTrial a, PTFreeTrial b) => a.Till = b.Till
| (PTFreeTrialFinished a, PTFreeTrialFinished b) => a.Till = b.Till
| (PTPaid a, PTPaid b) => a.Till = b.Till
| (PTPaidFinished a, PTPaidFinished b) => a.Till = b.Till
| _ => False)
val feedPasswordWarning =
"WARNING: username and password are kept in pain text in feed URL in standard HTTP basic access authentication format:
https://USERNAME:PASSWORD@example.com/feed
Please, if possible, use unique password! Username and password will be visible in OPML, in web server logs (some apps make requests with feed address) and, unlike usual cases when only password hash is kept, this password needs to be kept as is, so there are many unpredictable ways it could leak.
Only HTTP basic authentication is supported. If after entering right username and password feed still returns “HTTP 401 Unauthorized” then it could be misconfigured or require another authentication method."
val defaultWelcomeState : welcomeState =
{ HasPrevAccount = False
, HasPrevSubs = False
, StarredRestored = False
, TaggedRestored = False }
fun welcomeText ws paidTill curTime opmlUploadClick restoreSubscriptions : (string * xbody) =
let val importOpml =
dyn_ (return (Js.opmlForm
(linkButton "import an OPML file"
(stopPropagation; opmlUploadClick))))
val addSub = <xml>
{buttonName "Add subscription"} button to add new feeds.
</xml>
val clickOn = <xml>the
<span class="displayIfLeftPanelStatic">{addSub}</span>
<span class="displayIfLeftPanelMovable">{buttonSymbol Css.iconHamburger} hamburger button <span class="displayIfTouch">(or swipe right)</span>
and then {addSub}</span>
</xml>
val title = "Welcome" ^ (if ws.HasPrevAccount then " back" else "") ^ "!"
in
("", <xml>
<div class={Css.welcomeText}>
<h2>{[title]}</h2>
(* <p>To start using BazQux Reader please</p> *)
(* <p>{linkButton "import your subscriptions" greaderImportClick} from Google Reader</p> *)
{displayIfC ws.HasPrevAccount
(dyn_ (
pt <- signal paidTill;
ct <- signal curTime;
return (case pt of
| PTFreeTrial { Till = t } =>
(* сообщаем о предыдущем аккаунте только в первый день
free trial-а (не пишем после оплаты о начале нового free
trial)
*)
displayIfC (diffInSeconds ct t / 86400 + 1 > 29) <xml>
<p>Your previous account has expired more than a month ago. New free trial has just started!</p>
{displayIfC (ws.StarredRestored || ws.TaggedRestored) <xml>
<p>We have restored your
{[case (ws.StarredRestored, ws.TaggedRestored) of
| (True, True) => "starred and tagged"
| (True, False) => "starred"
| (False, True) => "tagged"
| _ => ""
]} items.</p></xml>}
</xml>
| _ => <xml/>)))}
{if ws.HasPrevSubs then <xml>
<p>You can {linkButton "restore your previous subscriptions" restoreSubscriptions} in one click!</p>
<p>Alternatively, you can click on {clickOn}</p></xml>
else <xml>
<p>Click on {clickOn}</p></xml>
}
<p>Search for sites you love to read and add them to BazQux Reader or {importOpml}.</p>
<p>You could read more about {hrefLink' (txt "how to import your feeds") (show (url Pages.how_to_import_my_feeds))} from other feed readers.</p>
(* <p>After adding your feeds don’t forget to play with view modes (they can be set per feed), set username and password in Account setting and try some of the apps, search (and maybe add some filters!), and enjoy fast.</p> *)
(* <p>Hint: You can download your OPML from {hrefLinkStopPropagation (txt "Feedly") "http://cloud.feedly.com/#opml"}, {hrefLinkStopPropagation (txt "The Old Reader") "https://theoldreader.com/reader/subscriptions/export"} or {hrefLinkStopPropagation (txt "NewsBlur") "http://newsblur.com/import/opml_export"}.</p> *)
(* <p>or *)
(* <a href={bless "/importFromGoogleReader"} *)
(* onclick={fn _ => redirect (effectfulUrl importFromGoogleReader)}> *)
(* import your subscriptions from Google Reader</a> *)
(* </p> *)
</div></xml>)
end
fun whatsNew lastWhatsNewTime = dyn_ (
lto <- signal lastWhatsNewTime;
return (case lto of None => <xml/> | Some lt =>
let fun item year month day title link =
let val time = Js.fromDatetimeUtc year (month-1) day 0 0 0
(* у JavaScript Date() месяцы начинаются с 0 *)
val act =
BackgroundRpc.addAction (BGWhatsNewClick { Time = time })
in
(time, actHrefLink act (txt title) link)
end
val wnList =
item 2020 7 27 "Mark above or below as read and article menu" "https://blog.bazqux.com/2020/07/mark-above-below-article-menu.html" ::
item 2019 11 20 "Email registration and account management" "https://blog.bazqux.com/2019/11/email-registration-account-management.html" ::
item 2019 6 18 "Themes, typography and image proxy" "https://blog.bazqux.com/2019/06/themes-typography-image-proxy.html" ::
item 2018 7 23 "Mobile web interface" "https://blog.bazqux.com/2018/07/mobile-web-interface.html" ::
[]
val wn = List.filter (fn (t,_) => t > lt) wnList
val close = case wn of
| (t,_) :: _ =>
BackgroundRpc.addAction (BGWhatsNewClose { Time = t });
set lastWhatsNewTime (Some t)
| _ =>
return ()
in
if isNull wn then <xml/>
else <xml>
<div class={Css.whatsNew}>
{dialog "New in reader:" close
(List.mapX (fn (_,x) => <xml><p>{x}</p></xml>) wn)}
</div>
</xml>
end))
val dragMarkId = Unsafe.id "Main.dragMarkId"
fun userUI paidTill_ uid : transaction page =
hrUid_ <- Session.humanReadableUID uid;
hrUid <- source hrUid_;
searchBoxId <- fresh; (* чтобы всегда был одинаковый *)
experiments <- source [];
paidTill <- source paidTill_;
payments <- source [];
maxPaidSubscriptions <- source 0;
maxFiltersOrSmartStreams <- source 0;
curTime_ <- now;
curTime <- source curTime_;
beta <- Session.isBeta;
local <- Session.isLocal;
buyT0 <- Pages.buyText "" paidTill;
buyT <- (* hyphenateXbody *) return buyT0;
let val testing = beta || local
fun mainPage () =
currentFeedUrl <- source "";
currentTagPath <- source "";
dummyId <- fresh;
loadingFeed <- source True;
onlyUpdatedSubscriptions <- source False;
exactUnreadCounts <- source False;
setFeedStub <- source (fn _ => return ());
onUpdateSubInfoStub <- source (fn _ _ => return ());
associatedAccounts <- source [];
associatedAccountNames <- source [];
passwordSet <- source False;
subscribeDiscoveryFeedStub <- source (fn _ => return ());
clearMtvmStub <- source (fn _ => return ());
reloadStub <- source (return ());
filteringIsInProgress <- source None;
addSubscriptionStub <- source (fn _ => return ());
let fun subscribeDiscoveryFeed u =
s <- get subscribeDiscoveryFeedStub;
s u
fun clearMtvm u =
c <- get clearMtvmStub;
c u
val reload =
r <- get reloadStub;
r
fun addSubscription u =
a <- get addSubscriptionStub;
a u
fun selectSubscription typ =
i <- fresh;
d <- P.newBox ("Select " ^ typ)
<xml><ctextbox id={i} class="selectSubscriptionInput" size={30} dir={Js.dirAuto} /></xml>;
P.toggle d;
Js.setupSubscriptionAutocomplete typ i;
Js.select i;
Js.focus i
(* val greaderImportClick = *)
(* redirect (effectfulUrl Import.importFromGoogleReader) *)
(* val greaderImportStarredClick = *)
(* redirect (effectfulUrl Import.importStarredAndTaggedItemsFromGoogleReader) *)
val opmlUploadClick =
Js.opmlUpload BackgroundRpc.flush
fun setFeed si = sf <- get setFeedStub; sf si
fun onUpdateSubInfo si si2 = o <- get onUpdateSubInfoStub; o si si2
fun searchQueryAndPath path =
if isPrefixOf "search/" path then
case strindex (strsuffix path 7) #"/" of
| Some c =>
Some (Js.decodeURIComponent (substring path 7 c),
strsuffix path (7+c+1))
| None => None
else
None
val updateCurrentFeed =
c <- get (getSubItem 0).Counters;
if c.Feed = 0 && c.Error = 0 && c.Scanning = 0 then
return () (* ничего не делаем, если у нас пусто *)
else
path <- Js.getInterfacePath;
case searchQueryAndPath path of
| Some (_, p) =>
si <- getSubItemByPath p;
withSome (set currentSearchFeed) si
| None =>
si <- getSubItemByPath path;
withSome (set currentFeed) si
fun updatePaidTill (pt, ct) =
pt0 <- get paidTill;
when (pt <> pt0) (set paidTill pt);
set curTime ct
in
updateSubscriptionsStub <- source (return ());
updateMarkReqReadCountersStub <- source (fn _ _ _ => return ());
msgsWidget <- msgsWidget
(u <- get updateSubscriptionsStub; u)
(fn vm mr mids => u <- get updateMarkReqReadCountersStub; u vm mr mids)
loadingFeed setFeed;
editStreamDialog <- source (fn _ => return ());
ssWidget <- subscriptionsWidget
updateCurrentFeed onUpdateSubInfo setFeed
onlyUpdatedSubscriptions exactUnreadCounts
subscribeDiscoveryFeed clearMtvm reload
(fn n => e <- get editStreamDialog; e n) updatePaidTill
msgsWidget.HasAbove msgsWidget.HasBelow msgsWidget.ClearTags
;
set updateSubscriptionsStub ssWidget.UpdateSubscriptionsIgnoringErrors;
set updateMarkReqReadCountersStub ssWidget.UpdateMarkReqReadCounters;
set editStreamDialog (editSmartStreamDialog ssWidget (fn () => reload));
toggleAccountBox <- accountBox associatedAccounts associatedAccountNames passwordSet paidTill payments maxPaidSubscriptions hrUid buyT ssWidget maxFiltersOrSmartStreams;
infoMessage <- infoMessageAtTheTop;
searchQuery <- source "";
searchCounters <- source emptyCounters;
searchResults <- source (None : option filterResults);
path <- bind Js.getInterfacePath source;
subscribeUrlId <- fresh;
endDivId <- fresh;
scrollTimeoutActive <- source False;
fullscreen <- source False;
lastCounters <- source emptyCounters;
scannedPercent <- source <xml/>;
reloadAvailable <- source False;
msgTreeSpacerText <- source <xml/>;
welcomeState <- source defaultWelcomeState;
displayDiscovery <- source False;
searchBarActive <- source False;
appearanceDialog <- newAppearanceDialog;
lastWhatsNewTime <- source None;
ht <- (* hyphenateXbody *) return (Pages.helpText addSubscription);
helpBox <- P.newBigBox "Help" ht;
discovery <- discoveryWidget addSubscription opmlUploadClick displayDiscovery;
let fun toggleDiscovery fromWelcome =
lv <- Js.isLeftPanelVisible;
dd <- (if not lv then return False else get displayDiscovery);
set displayDiscovery (not dd);
when (not dd && not lv) toggleLeftPanel;
when (not dd && not (fromWelcome && Js.hasOnscreenKeyboard ()))
(* на iPad показывается сначала верх, потом низ, пока
клавиатура выплывает.
А через setTimeout не работает, т.к. focus() на iPad
работает только внутри user-initiated events
*)
(Js.select discoveryTextBoxId;
Js.focus discoveryTextBoxId)
fun subInfoMsg t = <xml>
<div class="subInfoScanning">
<span class="spinner"></span> {[t]}
</div>
</xml>
val snInfoMsgAdding = subInfoMsg "Adding new feed…"
val snInfoMsgScanning = subInfoMsg "Fetching new feed…"
fun scannedPercentXml text = <xml><div class={Css.scannedPercent}>
<span class="spinner"></span>
{dyn_ (ls <- signal lastCounters;
return <xml><span class="percent">{[ls.ScannedPercent]}%</span></xml>)}
{[text]}
{ifDynClass (Monad.mp not (signal reloadAvailable))
Css.visibilityHidden (textButton "Refresh" reload)}
</div></xml>
fun scannedPercent100Xml text = <xml><div class={Css.scannedPercent}>
{[text]} {textButton "Refresh" reload}
</div></xml>
(* val snImportTags = <xml><div class={Css.scannedPercent}> *)
(* {textButton "Import starred and tagged items" *)
(* greaderImportStarredClick} *)
(* </div></xml> *)
val snScanningComments = scannedPercentXml "Fetching comments…"
val snAllCommentsScanned = scannedPercent100Xml "All comments fetched."
val snInfoMsg = <xml><dyn signal={
si <- signal currentFeed;
c <- signal si.Counters;
case si.SIType of
| SITSearch _ => return <xml/>
| SITFeed f =>
return <xml/>
| _ => (* SITFolder _ | SITAll *)
return <xml/>
(* исчезает, когда сканирование заканчивается *)
(* (if c.Scanning > 0 then <xml> *)
(* <div class="subInfoScanning"> *)
(* <span class="spinner"></span> Fetching new feeds… *)
(* {textButton "Refresh" reload} *)
(* </div> *)
(* </xml> *)
(* else <xml/>) *)
}/></xml>
fun modifyMsgTreeViewMode vmName (f : msgTreeViewMode -> msgTreeViewMode) =
cf <- get currentFeed;
let fun updSub si = case si.SIType of
| SITFeed feed =>
mtvm0 <- get si.ViewMode;
let val mtvm = f mtvm0 in
set si.ViewMode mtvm;
discovery.SetMtvm feed.Subscription.Url mtvm;
when (mtvm0.ExpandedComments <> mtvm.ExpandedComments)
(Js.updateExpandedComments si.Index
mtvm.ExpandedComments);
BackgroundRpc.addAction (BGSetSubscriptionViewMode
{ Url = feed.Subscription.Url, ViewMode = mtvm });
return True
end
| _ => return False
fun updFolder' si name =
mtvm <- Monad.mp f (get si.ViewMode);
set si.ViewMode mtvm;
BackgroundRpc.addAction (BGSetFolderViewMode
{ Folder = name, ViewMode = mtvm })
fun updFolder si name = case vmName of
| None =>
(* выбор ascending/unread/group by feed *)
updFolder' si name;
return True
| Some vm => (* режим просмотра *)
c <- confirm ("Do you really want to set " ^ vm ^
" for all feeds" ^
(if name <> "" then " in “" ^ name ^ "”"
else "") ^
"? \nAll per-feed settings will be cleared.");
(* Js.logTime "update" *) (if c then
updFolder' si name;
(* TODO: тут надо бы все папки обновлять,
если это корень *)
List.app (fn s => x <- updSub s; return ())
(getSubItems si.Index);
return True
else
return False)
fun upd si =
case si.SIType of
SITAll => updFolder si ""
| SITFolder f => updFolder si f.Folder
| SITFeed f => updSub si
| SITStarred => updFolder' si ",SITStarred"; return True
| SITAllTags => updFolder' si ",SITAllTags"; return True
| SITTag t => updFolder' si t.TagName; return True
| SITSmartStream s =>
updFolder' si s.StreamName; return True
| SITSearch _ =>
csf <- get currentSearchFeed;
upd csf
in
m <- upd cf;
when m retryPendingUpdates;
(* фоновое обновление может вернуть старый режим просмотра *)
return m
end
(* fun isFolder si = *)
(* case si.SIType of *)
(* SITAll => return True *)
(* | SITFolder _ => return True *)
(* | SITFeed _ => return False *)
(* | SITSearch _ => *)
(* csf <- signal currentSearchFeed; *)
(* isFolder csf *)
fun setUnreadOnly x =
m <- modifyMsgTreeViewMode None (setF [#UnreadOnly] x);
when m reload
fun setAscending x =
m <- modifyMsgTreeViewMode None (setF [#Ascending] x);
when m reload
val toggleGroupByFeed =
m <- modifyMsgTreeViewMode None notMtvmGroupByFeed;
when m reload
fun isMixedViewSi si =
case si.SIType of
| SITStarred => return True
| SITAllTags => return True
| SITTag _ => return True
| SITSmartStream _ => return True
| SITSearch _ =>
csf <- signal currentSearchFeed;
isMixedViewSi csf
| _ => return False
val isMixedView =
si <- get currentFeed;
current (isMixedViewSi si)
fun setViewMode name expanded posts f =
mixed <- isMixedView;
m <- modifyMsgTreeViewMode (Some name)
(fn vm =>
setF [#NoOverride] (f (not mixed))
(setF2 [#ExpandedComments] [#Posts] expanded posts vm));
when m reload
val withCommentsVM =
( iconFullViewWithComments
, fn vm => vm.ExpandedComments
, setViewMode "expanded view with expanded comments" True PVMFull id
, "Expanded view with expanded comments")
val fullVM =
( iconFullView
, fn vm => not vm.ExpandedComments && vm.Posts = PVMFull
, setViewMode "expanded view" False PVMFull id
, "Expanded view")
val shortVM =
( iconListView
, fn vm => not vm.ExpandedComments && vm.Posts = PVMShort
, setViewMode "list view" False PVMShort id
, "List view")
val magazineVM =
( iconMagazineView
, fn vm => not vm.ExpandedComments && vm.Posts = PVMMagazine
, setViewMode "magazine view" False PVMMagazine id
, "Magazine view")
val mosaicVM =
( iconMosaicView
, fn vm => not vm.ExpandedComments && vm.Posts = PVMMosaic
, setViewMode "mosaic view" False PVMMosaic id
, "Mosaic view" )
val mixedVM =
( iconMixedView
, fn vm => vm.NoOverride
, setViewMode "mixed view" False PVMFull (fn _ => True)
, "Mixed view (using each feed view modes)" )
val subscriptionTitle =
dyn_ (f <- signal currentFeed;
return <xml><span dir="auto">{[f.Title]}</span></xml>)
fun setForest f mr =
msgsWidget.SetForest f mr
fun setDocumentTitle si =
Js.setDocumentTitle ("bq | " ^ subItemTitle si)
(* иногда оставляет в заголовке окна только концовку,
и непонятно, что это вообще за окно
*)
fun updatePath si =
let val h' = subItemPath si in
set path h';
tryPushInterfacePath h'
(* не трогаем историю при back, чтобы можно было сделать forward *)
end
fun setCurrentFeed si =
updatePath si;
Js.setScrollTop Settings.msgDivId 0.0;
(* прокручиваем в начало до SetForest,
почему-то, если делать это после, firefox не сбрасывает scroll
(или пытается восстановить его?)
*)
setForest emptyMF emptyMarkReq;
Js.discoveryClearSelection;
set currentFeed si;
set currentSearchFeed defaultSubItem;
setDocumentTitle si;
set searchResults None;
set scannedPercent <xml/>;
set msgTreeSpacerText <xml/>;
set currentFeedUrl "";
set currentTagPath "";
set reloadAvailable False;
l <- get showLeftPanel;
when l toggleLeftPanel
fun mkDiscoveryFeed url title feedLink faviconStyle mbmtvm =
c <- source emptyCounters;
mtvm <- (case mbmtvm of
| Some m => return m
| None => discovery.LookupMtvm url);
m <- source mtvm;
return
({ Path = "subscription/" ^ Js.encodeURIComponent url
, Index = discoverySubItemIndex
, Title = title
, SIType = SITFeed { Subscription =
{ State = SSFeed { Url = url }
, Url = url
, EditsCount = 0
, Title = None
, Folders = [] }
, FeedLink = feedLink
, PointAllDesc = None
}
, Counters = c
, ViewMode = m
, ParentFolders = []
, DomIds = []
, FaviconStyle = faviconStyle
})
fun setFeedAdding si =
setCurrentFeed (setF [#Index] (discoverySubItemIndex - 1) si);
set msgTreeSpacerText snInfoMsgAdding
fun setFeedUrlAdding url =
si <- mkDiscoveryFeed url (Js.titleFromUrl url) None None None;
setFeedAdding si
val loadingIndicator =
dyn_ (a <- msgsWidget.LoadingAppendRequests;
l <- msgsWidget.LoadingComments;
(* loadingComments -- уже есть индикатор при expand *)
return (if a && not l then
<xml><div class={Css.loading}>
<span class="spinner"></span> Loading…
</div></xml>
else <xml/>))
fun subInfoErrorText m =
<xml><div class={Css.subInfoErrorText}>{[m]}</div></xml>
fun feedAuthInput si url e parents =
if strsindex e "HTTP 401 " = Some 0 then
activeXml
let val (username, password) = Js.getUrlUsernameAndPassword url
in
uSrc <- source username;
pSrc <- source password;
let val hasPwd = username <> "" || password <> ""
val rUrl = case parents of
| (SpuRedirect r) :: _ => Some r.Url
| (SpuHtml h) :: _ => Some h.Url
| _ => None
val subscribe =
u <- get uSrc;
p <- get pSrc;
if u = "" && p = "" then
alert "Please, enter username and password."
else
let val url' = Js.setUrlUsernameAndPassword
(u,p) (Option.get url rUrl)
in
if url' <> url then
setFeedUrlAdding url';
ssWidget.Unsubscribe
(si :: [])
(ssWidget.AddSubscription url')
else
ssWidget.RetryScanning si
end
val keydown = onEnter subscribe
val msg =
case (hasPwd, rUrl) of
| (False, None) =>
"This feed is password protected.\n\nPlease, enter authentication information:"
| (True, None) =>
"Invalid username or password.\n\nPlease, enter authentication information:"
| (False, Some u) =>
"Feed was redirected to\n" ^ u ^ "\nand this feed is password protected.\n\nPlease, enter authentication information:"
| (True, Some u) =>
"Feed was redirected to\n" ^ u ^ "\nand this feed is password protected too. You could use the same username and password or enter new ones:"
in
return <xml>
<p>
{subInfoErrorText msg}
</p>
<p>Username<br/>
<ctextbox class="mlLogin" source={uSrc} size={20}
onkeydown={keydown} dir={Js.dirAuto} />
</p>
<p>Password<br/>
<cpassword class="mlPassword" source={pSrc} size={20}
onkeydown={keydown} />
</p>
<p>{textButton "Subscribe" subscribe}</p>
{subInfoErrorText feedPasswordWarning}
</xml>
end end
else
<xml></xml>
fun subErrorText si s =
let val (m, p) = case s.State of
| SSError e => (e.Message, [])
| SSErrorPath e => (e.Message, e.Path)
| _ => ("", [])
in
<xml>
{subInfoErrorText (Js.strReplace "<br/>" "\n" m)}
{feedAuthInput si s.Url m p}
</xml>
end
val restoreSubscriptions =
P.hide;
set loadingFeed True;
showInfo "Restoring…" infoMessage
(x <- rpc (Rpcs.restoreSubscriptions []);
set loadingFeed False;
ssWidget.UpdateSubscriptions_ x;
discovery.Hide);
reload
fun setEmptyResult x =
set msgTreeSpacerText
<xml><div class="emptySetFeedResult">{x}
</div></xml>
fun feedsOrDiscovery discoveryUrl (si : subItem) =
case discoveryUrl of
| Some u => return (FODDiscovery { Url = u })
| None =>
rcs <- getUrls si;
return (FODFeeds { ReadCounters = rcs })
fun emptyFod fod = case fod of
| FODFeeds { ReadCounters = [] } => True
| _ => False
fun fodFeeds fod = case fod of
| FODFeeds { ReadCounters = rcs } => rcs
| _ => []
fun viewAllButton t =
displayIfSig (mtvm <- msgTreeViewMode;
return mtvm.UnreadOnly)
(textButton t (setUnreadOnly False))
val showLoading = infoMessage.Show "Loading…"
val hideLoading = infoMessage.Hide
fun setFolderForest uic name si fod vm =
if emptyFod fod then
c <- get si.Counters;
case si.SIType of
| SITFolder { Folder = "" } => set msgTreeSpacerText <xml/>
| SITFeed f => set msgTreeSpacerText (* snInfoMsg *)
(if c.Scanning > 0 then
snInfoMsgScanning
else if c.Error > 0 then
<xml>
<div class="subInfoError"><h1>Error</h1>
{subErrorText si f.Subscription}
</div>
<div class="subInfoErrorButtons">
{textButton "Unsubscribe"
(setFeed defaultSubItem;
ssWidget.Unsubscribe (si :: []) (return ()))}
{textButton "Retry"
(ssWidget.RetryScanning si)}
</div>
</xml>
else
<xml/>)
| SITSmartStream s =>
setEmptyResult <xml><h2>No feeds in smart stream
“{[s.StreamName]}”</h2></xml>
| _ =>
if c.Scanning > 0 then set msgTreeSpacerText <xml>
<div class="subInfoScanning">
<span class="spinner"></span>
Fetching new feeds…
{textButton "Refresh" reload}
</div>
</xml>
else if c.Error = 0 then
ws <- get welcomeState;
let val (title, text) = welcomeText ws
paidTill curTime
opmlUploadClick restoreSubscriptions
in
cf <- get currentFeed;
set currentFeed (setF [#Title] title cf);
set msgTreeSpacerText text
end
else
setEmptyResult <xml><h2>No feeds.</h2></xml>
else
showLoading;
queueCancellableCustomUpdate uic ssWidget
(fn l =>
set loadingFeed True;
case si.SIType of
| SITSmartStream s =>
rpc (Rpcs.smartStreamForest s.StreamName (fodFeeds fod) vm l)
| _ =>
rpc (Rpcs.folderForest name fod vm l))
(fn (markReq,uc,(MsgForest f)) =>
hideLoading;
(case (fod,uc) of
| (FODDiscovery _,
(_, rp,rc,tp,tc) :: []) =>
(* обновляем счетчики discovery фида *)
c <- get si.Counters;
set si.Counters
(c -- #ReadPosts -- #ReadComments
-- #TotalPosts -- #TotalComments
++ { ReadPosts = rp, ReadComments = rc
, TotalPosts = tp, TotalComments = tc })
| _ => return ());
updateReadCounters uc;
setForest (MsgForest f) markReq;
set loadingFeed False;
if not (isNull f.List) then
set msgTreeSpacerText loadingIndicator
else
c <- get si.Counters;
setEmptyResult <|
if c.TotalPosts = 0 && c.TotalComments = 0 then <xml>
<h2>“{subscriptionTitle}” is empty (feed exists but contains no articles).</h2>
</xml> else if vm.UnreadOnly then <xml>
<h2>“{subscriptionTitle}” has no unread articles.</h2>
(* без subscriptionTitle непонятно, что за фид в
Feed has no unread articles,
а если сделать
No unread articles,
то непонятно, почему это нет непрочитанных,
если в других фидах они есть
*)
{viewAllButton "View all articles"}
</xml> else <xml>
<h2>“{subscriptionTitle}” has all articles filtered out (go to {buttonName "Filters & streams"} settings to adjust filters).</h2>
</xml>
)
fun setFolder uic name si vm =
fod <- feedsOrDiscovery None si;
setFolderForest uic name si fod vm
fun setTags uic si ts c =
set currentTagPath si.Path;
set msgTreeSpacerText <xml/>;
vm <- getMsgTreeViewMode;
showLoading;
queueCancellableCustomUpdate uic ssWidget
(fn l =>
set loadingFeed True;
rpc (Rpcs.tagsForest ts vm l))
(fn (markReq,uc,mf) =>
hideLoading;
updateReadCounters uc;
setForest mf markReq;
set loadingFeed False;
emf <- current msgsWidget.IsForestEmpty;
c <- get si.Counters;
if emf then
setEmptyResult <| case ts of
| Some (ITStarred :: []) =>
if c.TotalPosts = 0 && c.TotalComments = 0 then
<xml><h2>There are no starred items yet.
Please, star some articles first.</h2></xml>
else
<xml><h2>There are no unread starred items.</h2>
{viewAllButton "Show all starred items"}
</xml>
| Some ((ITTag { TagName = n }) :: []) =>
if c.TotalPosts = 0 && c.TotalComments = 0 then
<xml><h2>There are no items tagged “{[n]}”.
Perhaps you’ve untagged articles in another
browser window or app (try reload page
or press “r” to remove nonexistent tag).
</h2></xml>
else
<xml><h2>There are no unread items tagged “{[n]}”.</h2>
{viewAllButton "Show all tagged items"}
</xml>
| _ =>
if c.TotalPosts = 0 && c.TotalComments = 0 then
<xml><h2>There are no tagged items.
Please, tag some articles first.</h2></xml>
else
<xml><h2>There are no unread tagged items.</h2>
{viewAllButton "Show all tagged items"}
</xml>
else
set msgTreeSpacerText loadingIndicator)
fun setFeed_ hide uic si =
when hide P.hide;
set searchBarActive False;
set searchQuery "";
Js.selectSubItem si.Index;
setCurrentFeed si;
c <- get si.Counters;
vm <- getMsgTreeViewMode;
case (si.SIType, c) of
| (SITFolder f, _) => setFolder uic (Some f.Folder) si vm
| (SITAll, _) => setFolder uic None si vm
| (SITSmartStream s, _) => setFolder uic None si vm
| (SITStarred, _) => setTags uic si (Some (ITStarred :: [])) c
| (SITAllTags, _) => setTags uic si None c
| (SITTag t, _) =>
setTags uic si (Some (ITTag { TagName = t.TagName } :: [])) c
| (SITFeed
{ Subscription = { State = SSFeed f, ... }, ... },
{ ScannedPercent = sp, ... }) =>
set currentFeedUrl f.Url;
when (sp <> 100)
(set lastCounters c;
set scannedPercent snScanningComments);
du <- current discoverySubItemUrl;
fod <- feedsOrDiscovery du si;
setFolderForest uic None si fod vm
| (SITFeed _, _) =>
setFolderForest uic None si (FODFeeds { ReadCounters = [] }) vm
| _ => return ()
fun setDiscoveryFeed url title feedLink faviconStyle mbmtvm =
df <- mkDiscoveryFeed url title feedLink faviconStyle mbmtvm;
setFeed df
fun addSubscription u =
when (u <> "")
(P.hide;
setFeedUrlAdding u;
ssWidget.AddSubscription u)
fun subscribeDiscoveryFeed url =
c <- discovery.GetCountry;
q <- discovery.GetQuery;
discovery.Hide;
si <- get currentFeed;
setFeedAdding si;
ssWidget.AddDiscoverySubscription url c q
fun search' uic (q : string) (csi : subItem) =
let val searchInAllArticlesIcon =
textButton "Search in all articles"
(m <- modifyMsgTreeViewMode None (setF [#UnreadOnly] False);
search' uic q csi)
val si =
{ Path =
"search/" ^ Js.encodeURIComponent q ^ "/" ^ csi.Path
, Index = -1
, Title = q
, SIType = SITSearch { Query = q }
, Counters = searchCounters
, ViewMode = csi.ViewMode
, ParentFolders = []
, DomIds = []
, FaviconStyle = None
}
val folder = case csi.SIType of
| SITFolder { Folder = f } => Some f
| _ => None
in
when (q <> "")
(Js.updateSearchAutocomplete q;
set searchCounters emptyCounters;
sq <- get searchQuery;
when (sq <> q) (set searchQuery q);
Js.selectSubItem csi.Index;
setCurrentFeed si;
set currentSearchFeed csi;
vm <- getMsgTreeViewMode;
(taggedFeed, tags) <- return (isTagFeed csi);
du <- current discoverySubItemUrl;
fod <- feedsOrDiscovery du csi;
if emptyFod fod && not taggedFeed then
(if isNull (getSubItems csi.Index) then
setEmptyResult <xml>
<h2>No feeds to search. Please, add feeds using {buttonName "Add subscription"} panel first.</h2>
</xml>
else
setEmptyResult <xml>
<h2>You have no unread articles to search.</h2>
{searchInAllArticlesIcon}
</xml>);
BackgroundRpc.addAction (BGSaveFilterQuery { Query = q })
else
(showLoading;
queueCancellableCustomUpdate uic ssWidget
(fn l =>
set loadingFeed True;
if taggedFeed then
rpc (Rpcs.filterTagsForest q tags vm l)
else
case csi.SIType of
| SITSmartStream ss =>
rpc (Rpcs.filterSmartStreamForest ss.StreamName q (fodFeeds fod) vm l)
| _ =>
rpc (Rpcs.filterForest q folder fod vm l)
)
(fn (r : either string (markReq * Js.readCounters * filterResults)) =>
hideLoading;
case r of
| Left e =>
set msgTreeSpacerText <xml>
<div class="subInfoError">
<h1>Syntax error (please, edit your search query):</h1>
{subInfoErrorText e}
</div>
</xml>
| Right (markReq,uc,sr) =>
updateReadCounters uc;
let val (up,uc) = (sr.UnreadPosts, sr.UnreadComments)
val (tp,tc) = (sr.TotalPosts, sr.TotalComments)
in
set searchCounters
{ ReadPosts = tp-up, TotalPosts = tp
, ReadComments = tc-uc, TotalComments = tc
, Scanning = 0, ScanningComments = 0
, Error = 0, Feed = 1, ScannedPercent = 100 };
set searchResults (Some sr);
setForest sr.MsgForest markReq;
set loadingFeed False;
if vm.UnreadOnly && up+uc = 0 && tp+tc > 0 then
setEmptyResult <xml>
<h2>Nothing found in unread articles.</h2>
{searchInAllArticlesIcon}
</xml>
else if tp+tc = 0 then
setEmptyResult <xml>
<h2>Nothing found, sorry.</h2>
</xml>
else
set msgTreeSpacerText loadingIndicator
end)))
end
val search =
q <- get searchQuery;
cf <- get currentFeed;
csi <- (case cf.SIType of
| SITSearch _ => get currentSearchFeed
| _ => return cf);
search' False q csi
fun reloadFeed' hide updateIfCancelled () =
path0 <- Js.getInterfacePath;
if isPrefixOf "account" path0 then
Js.replaceInterfacePath "";
toggleAccountBox;
reloadFeed' False False ()
else
let val (setF, cf, path) = case searchQueryAndPath path0 of
| Some (q, p) => (search' updateIfCancelled q, currentSearchFeed, p)
| _ => (setFeed_ hide updateIfCancelled, currentFeed, path0)
in
si <- getSubItemByPath path;
cf <- get cf;
(case si of
| Some si => setF si
| None =>
if isPrefixOf "subscription/" path then
(let val url = Js.decodeURIComponent (strsuffix path (strlen "subscription/"))
val (uname, pwd) = Js.getUrlUsernameAndPassword url
in
if pwd <> "" then
setDefaultFeed setFeed
(* фид с паролем, от которого отписались *)
else if cf.Path = path then
mtvm <- get cf.ViewMode;
df <- mkDiscoveryFeed
url
cf.Title
(case cf.SIType of
| SITFeed f => f.FeedLink
| _ => None)
cf.FaviconStyle
(Some mtvm);
setF df
else
d <- tryRpc (Rpcs.feedDetails url);
(* не круто, что запрос фида пойдет после,
ну и ладно
*)
df <- (case d of
| Some (title, link, favicon, mtvm) =>
mkDiscoveryFeed url title link
favicon (Some mtvm)
| _ =>
mkDiscoveryFeed url "" None None None);
setF df
end)
else if isPrefixOf "tag" path then
setDefaultFeed setFeed (* тег удалили *)
else
return ())
end
fun reloadFeed () = reloadFeed' True False ()
val onPopstate =
p0 <- get path;
p <- Js.getInterfacePath;
(* debug ("onPopstate p0 = " ^ p0 ^ "; p = " ^ p); *)
when (p <> p0)
(preventDefault;
reloadFeed ())
fun markAllRead t d =
msgsWidget.MarkAllAsRead t d (reloadFeed' True True ())
fun err caption details =
ex <- get exiting;
when (not ex)
(infoMessage.Error caption details;
BackgroundRpc.onError;
set filteringIsInProgress None;
msgsWidget.OnError;
ssWidget.OnError;
set scrollTimeoutActive False;
set loadingFeed False)