-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathViewUtils.cs
More file actions
1471 lines (1259 loc) · 58.5 KB
/
Copy pathViewUtils.cs
File metadata and controls
1471 lines (1259 loc) · 58.5 KB
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using ServiceStack.Configuration;
using ServiceStack.IO;
using ServiceStack.Script;
using ServiceStack.Text;
using ServiceStack.Web;
namespace ServiceStack
{
/// <summary>
/// High-level Input options for rendering HTML Input controls
/// </summary>
public class InputOptions
{
/// <summary>
/// Display the Control inline
/// </summary>
public bool Inline { get; set; }
/// <summary>
/// Label for the control
/// </summary>
public string Label { get; set; }
/// <summary>
/// Class for Label
/// </summary>
public string LabelClass { get; set; }
/// <summary>
/// Override the class on the error message (default: invalid-feedback)
/// </summary>
public string ErrorClass { get; set; }
/// <summary>
/// Small Help Text displayed with the control
/// </summary>
public string Help { get; set; }
/// <summary>
/// Bootstrap Size of the Control: sm, lg
/// </summary>
public string Size { get; set; }
/// <summary>
/// Multiple Value Data Source for Checkboxes, Radio boxes and Select Controls
/// </summary>
public object Values { get; set; }
/// <summary>
/// Typed setter of Multi Input Values
/// </summary>
public IEnumerable<KeyValuePair<string, string>> InputValues
{
set => Values = value;
}
/// <summary>
/// Whether to preserve value state after post back
/// </summary>
public bool PreserveValue { get; set; } = true;
/// <summary>
/// Whether to show Error Message associated with this control
/// </summary>
public bool ShowErrors { get; set; } = true;
}
/// <summary>
/// Customize JS/CSS/HTML bundles
/// </summary>
public class BundleOptions
{
/// <summary>
/// List of file and directory sources to include in this bundle, directory sources must end in `/`.
/// Sources can include prefixes to specify which Virtual File System Source to use, options:
/// 'content:' (ContentRoot HostContext.VirtualFiles), 'filesystem:' (WebRoot FileSystem), 'memory:' (WebRoot Memory)
/// </summary>
public List<string> Sources { get; set; } = new List<string>();
/// <summary>
/// Write bundled file to this Virtual Path
/// </summary>
public string OutputTo { get; set; }
/// <summary>
/// If needed, use alternative OutputTo Virtual Path in html tag
/// </summary>
public string OutputWebPath { get; set; }
/// <summary>
/// If needed, include PathBase prefix in output tag
/// </summary>
public string PathBase { get; set; }
/// <summary>
/// Whether to minify sources in bundle (default true)
/// </summary>
public bool Minify { get; set; } = true;
/// <summary>
/// Whether to save to disk or Memory File System (default Memory)
/// </summary>
public bool SaveToDisk { get; set; }
/// <summary>
/// Whether to return cached bundle if exists (default true)
/// </summary>
public bool Cache { get; set; } = true;
/// <summary>
/// Whether to bundle and emit single or not bundle and emit multiple html tags
/// </summary>
public bool Bundle { get; set; } = true;
/// <summary>
/// Whether to call AMD define for CommonJS modules
/// </summary>
public bool RegisterModuleInAmd { get; set; }
/// <summary>
/// Whether to wrap JS scripts in an Immediately-Invoked Function Expression
/// </summary>
public bool IIFE { get; set; }
}
public class TextDumpOptions
{
public TextStyle HeaderStyle { get; set; }
public string Caption { get; set; }
public string CaptionIfEmpty { get; set; }
public bool IncludeRowNumbers { get; set; } = true;
public DefaultScripts Defaults { get; set; } = ViewUtils.DefaultScripts;
internal int Depth { get; set; }
internal bool HasCaption { get; set; }
public static TextDumpOptions Parse(Dictionary<string, object> options, DefaultScripts defaults=null)
{
return new TextDumpOptions
{
HeaderStyle = options.TryGetValue("headerStyle", out var oHeaderStyle)
? oHeaderStyle.ConvertTo<TextStyle>()
: TextStyle.SplitCase,
Caption = options.TryGetValue("caption", out var caption)
? caption?.ToString()
: null,
CaptionIfEmpty = options.TryGetValue("captionIfEmpty", out var captionIfEmpty)
? captionIfEmpty?.ToString()
: null,
IncludeRowNumbers = !options.TryGetValue("rowNumbers", out var rowNumbers)
|| (!(rowNumbers is bool b) || b),
Defaults = defaults ?? ViewUtils.DefaultScripts,
};
}
}
public class HtmlDumpOptions
{
public string Id { get; set; }
public string ClassName { get; set; }
public string ChildClass { get; set; }
public TextStyle HeaderStyle { get; set; }
public string HeaderTag { get; set; }
public string Caption { get; set; }
public string CaptionIfEmpty { get; set; }
public DefaultScripts Defaults { get; set; } = ViewUtils.DefaultScripts;
public string Display { get; set; }
internal int Depth { get; set; }
internal int ChildDepth { get; set; } = 1;
internal bool HasCaption { get; set; }
public static HtmlDumpOptions Parse(Dictionary<string, object> options, DefaultScripts defaults=null)
{
return new HtmlDumpOptions
{
Id = options.TryGetValue("id", out var oId)
? (string)oId
: null,
ClassName = options.TryGetValue("className", out var oClassName)
? (string)oClassName
: null,
ChildClass = options.TryGetValue("childClass", out var oChildClass)
? (string)oChildClass
: null,
HeaderStyle = options.TryGetValue("headerStyle", out var oHeaderStyle)
? oHeaderStyle.ConvertTo<TextStyle>()
: TextStyle.SplitCase,
HeaderTag = options.TryGetValue("headerTag", out var oHeaderTag)
? (string)oHeaderTag
: null,
Caption = options.TryGetValue("caption", out var caption)
? caption?.ToString()
: null,
CaptionIfEmpty = options.TryGetValue("captionIfEmpty", out var captionIfEmpty)
? captionIfEmpty?.ToString()
: null,
Display = options.TryGetValue("display", out var display)
? display?.ToString()
: null,
Defaults = defaults ?? ViewUtils.DefaultScripts,
};
}
}
public enum TextStyle
{
None,
SplitCase,
Humanize,
TitleCase,
PascalCase,
CamelCase,
}
/// <summary>
/// Generic collection of Nav Links
/// </summary>
public static class NavDefaults
{
public static string NavClass { get; set; } = "nav";
public static string NavItemClass { get; set; } = "nav-item";
public static string NavLinkClass { get; set; } = "nav-link";
public static string ChildNavItemClass { get; set; } = "nav-item dropdown";
public static string ChildNavLinkClass { get; set; } = "nav-link dropdown-toggle";
public static string ChildNavMenuClass { get; set; } = "dropdown-menu";
public static string ChildNavMenuItemClass { get; set; } = "dropdown-item";
public static NavOptions Create() => new NavOptions {
NavClass = NavClass,
NavItemClass = NavItemClass,
NavLinkClass = NavLinkClass,
ChildNavItemClass = ChildNavItemClass,
ChildNavLinkClass = ChildNavLinkClass,
ChildNavMenuClass = ChildNavMenuClass,
ChildNavMenuItemClass = ChildNavMenuItemClass,
};
public static NavOptions ForNav(this NavOptions options) => options; //Already uses NavDefaults
public static NavOptions OverrideDefaults(NavOptions targets, NavOptions source)
{
if (targets == null)
return source;
if (targets.NavClass == NavClass && source.NavClass != null)
targets.NavClass = source.NavClass;
if (targets.NavItemClass == NavItemClass && source.NavItemClass != null)
targets.NavItemClass = source.NavItemClass;
if (targets.NavLinkClass == NavLinkClass && source.NavLinkClass != null)
targets.NavLinkClass = source.NavLinkClass;
if (targets.ChildNavItemClass == ChildNavItemClass && source.ChildNavItemClass != null)
targets.ChildNavItemClass = source.ChildNavItemClass;
if (targets.ChildNavLinkClass == ChildNavLinkClass && source.ChildNavLinkClass != null)
targets.ChildNavLinkClass = source.ChildNavLinkClass;
if (targets.ChildNavMenuClass == ChildNavMenuClass && source.ChildNavMenuClass != null)
targets.ChildNavMenuClass = source.ChildNavMenuClass;
if (targets.ChildNavMenuItemClass == ChildNavMenuItemClass && source.ChildNavMenuItemClass != null)
targets.ChildNavMenuItemClass = source.ChildNavMenuItemClass;
return targets;
}
}
/// <summary>
/// Single NavLink List Item
/// </summary>
public static class NavLinkDefaults
{
public static NavOptions ForNavLink(this NavOptions options) => options; //Already uses NavDefaults
}
/// <summary>
/// Navigation Bar Menu Items
/// </summary>
public static class NavbarDefaults
{
public static string NavClass { get; set; } = "navbar-nav";
public static NavOptions Create() => new NavOptions { NavClass = NavClass };
public static NavOptions ForNavbar(this NavOptions options) => NavDefaults.OverrideDefaults(options, Create());
}
/// <summary>
/// Collection of Link Buttons (e.g. used to render /auth buttons)
/// </summary>
public static class NavButtonGroupDefaults
{
public static string NavClass { get; set; } = "btn-group";
public static string NavItemClass { get; set; } = "btn btn-primary";
public static NavOptions Create() => new NavOptions { NavClass = NavClass, NavItemClass = NavItemClass };
public static NavOptions ForNavButtonGroup(this NavOptions options) => NavDefaults.OverrideDefaults(options, Create());
}
public class NavOptions
{
/// <summary>
/// User Attributes for conditional rendering, e.g:
/// - auth - User is Authenticated
/// - role:name - User Role
/// - perm:name - User Permission
/// </summary>
public HashSet<string> Attributes { get; set; }
/// <summary>
/// Path Info that should set as active
/// </summary>
public string ActivePath { get; set; }
/// <summary>
/// Prefix to include before NavItem.Path (if any)
/// </summary>
public string BaseHref { get; set; }
/// <summary>
/// Custom classes applied to different navigation elements (defaults to Bootstrap classes)
/// </summary>
public string NavClass { get; set; } = NavDefaults.NavClass;
public string NavItemClass { get; set; } = NavDefaults.NavItemClass;
public string NavLinkClass { get; set; } = NavDefaults.NavLinkClass;
public string ChildNavItemClass { get; set; } = NavDefaults.ChildNavItemClass;
public string ChildNavLinkClass { get; set; } = NavDefaults.ChildNavLinkClass;
public string ChildNavMenuClass { get; set; } = NavDefaults.ChildNavMenuClass;
public string ChildNavMenuItemClass { get; set; } = NavDefaults.ChildNavMenuItemClass;
}
/// <summary>
/// Public API for ViewUtils
/// </summary>
public static class View
{
public static List<NavItem> NavItems => ViewUtils.NavItems;
public static Dictionary<string, List<NavItem>> NavItemsMap => ViewUtils.NavItemsMap;
public static void Load(IAppSettings settings) => ViewUtils.Load(settings);
public static List<NavItem> GetNavItems(string key) => ViewUtils.GetNavItems(key);
}
/// <summary>
/// Shared Utils shared between different Template Filters and Razor Views/Helpers
/// </summary>
public static class ViewUtils
{
internal static readonly DefaultScripts DefaultScripts = new DefaultScripts();
private static readonly HtmlScripts HtmlScripts = new HtmlScripts();
public static string NavItemsKey { get; set; } = "NavItems";
public static string NavItemsMapKey { get; set; } = "NavItemsMap";
public static void Load(IAppSettings settings)
{
var navItems = settings?.Get<List<NavItem>>(NavItemsKey);
if (navItems != null)
{
NavItems.AddRange(navItems);
}
var navItemsMap = settings?.Get<Dictionary<string, List<NavItem>>>(NavItemsMapKey);
if (navItemsMap != null)
{
foreach (var entry in navItemsMap)
{
NavItemsMap[entry.Key] = entry.Value;
}
}
}
public static bool ShowNav(this NavItem navItem, HashSet<string> attributes)
{
if (attributes.IsEmpty())
return navItem.Show == null;
if (navItem.Show != null && !attributes.Contains(navItem.Show))
return false;
if (navItem.Hide != null && attributes.Contains(navItem.Hide))
return false;
return true;
}
public static List<NavItem> NavItems { get; } = new List<NavItem>();
public static Dictionary<string, List<NavItem>> NavItemsMap { get; } = new Dictionary<string, List<NavItem>>();
public static List<NavItem> GetNavItems(string key) => NavItemsMap.TryGetValue(key, out var navItems)
? navItems
: TypeConstants<NavItem>.EmptyList;
public static string CssIncludes(IVirtualPathProvider vfs, List<string> cssFiles)
{
if (vfs == null || cssFiles == null || cssFiles.Count == 0)
return null;
var sb = StringBuilderCache.Allocate();
sb.AppendLine("<style>");
foreach (var cssFile in cssFiles)
{
var virtualPath = !cssFile.StartsWith("/")
? "/css/" + cssFile + ".css"
: cssFile;
var file = vfs.GetFile(virtualPath.TrimStart('/'));
if (file == null)
continue;
using (var reader = file.OpenText())
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.AppendLine(line);
}
}
}
sb.AppendLine("</style>");
return StringBuilderCache.ReturnAndFree(sb);
}
public static string JsIncludes(IVirtualPathProvider vfs, List<string> jsFiles)
{
if (vfs == null || jsFiles == null || jsFiles.Count == 0)
return null;
var sb = StringBuilderCache.Allocate();
sb.AppendLine("<script>");
foreach (var jsFile in jsFiles)
{
var virtualPath = !jsFile.StartsWith("/")
? "/js/" + jsFile + ".js"
: jsFile;
var file = vfs.GetFile(virtualPath.TrimStart('/'));
if (file == null)
continue;
using (var reader = file.OpenText())
{
string line;
while ((line = reader.ReadLine()) != null)
{
sb.AppendLine(line);
}
}
}
sb.AppendLine("</script>");
return StringBuilderCache.ReturnAndFree(sb);
}
/// <summary>
/// Display a list of NavItem's
/// </summary>
public static string Nav(List<NavItem> navItems, NavOptions options)
{
if (navItems.IsEmpty())
return string.Empty;
var sb = StringBuilderCache.Allocate();
sb.Append("<div class=\"")
.Append(options.NavClass)
.AppendLine("\">");
foreach (var navItem in navItems)
{
NavLink(sb, navItem, options);
}
sb.AppendLine("</div>");
return sb.ToString();
}
/// <summary>
/// Display a `nav-link` nav-item
/// </summary>
public static string NavLink(NavItem navItem, NavOptions options)
{
var sb = StringBuilderCache.Allocate();
NavLink(sb, navItem, options);
return StringBuilderCache.ReturnAndFree(sb);
}
static string ActiveClass(NavItem navItem, string activePath) =>
navItem.Href != null && (navItem.Exact == true || activePath.Length <= 1
? activePath?.TrimEnd('/').EqualsIgnoreCase(navItem.Href?.TrimEnd('/')) == true
: activePath.TrimEnd('/').StartsWithIgnoreCase(navItem.Href?.TrimEnd('/')))
? " active"
: "";
/// <summary>
/// Display a `nav-link` nav-item
/// </summary>
public static void NavLink(StringBuilder sb, NavItem navItem, NavOptions options)
{
if (!navItem.ShowNav(options.Attributes))
return;
var hasChildren = navItem.Children?.Count > 0;
var navItemCls = hasChildren
? options.ChildNavItemClass
: options.NavItemClass;
var navLinkCls = hasChildren
? options.ChildNavLinkClass
: options.NavLinkClass;
var id = navItem.Id;
if (hasChildren && id == null)
id = navItem.Label.SafeVarName() + "MenuLink";
sb.Append("<li class=\"")
.Append(navItem.ClassName).Append(navItem.ClassName != null ? " " : "")
.Append(navItemCls)
.AppendLine("\">");
sb.Append(" <a href=\"")
.Append(options.BaseHref?.TrimEnd('/'))
.Append(navItem.Href)
.Append("\"");
sb.Append(" class=\"")
.Append(navLinkCls).Append(ActiveClass(navItem,options.ActivePath))
.Append("\"");
if (id != null)
sb.Append(" id=\"").Append(id).Append("\"");
if (hasChildren)
{
sb.Append(" role=\"button\" data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\"");
}
sb.Append(">")
.Append(navItem.Label)
.AppendLine("</a>");
if (hasChildren)
{
sb.Append(" <div class=\"")
.Append(options.ChildNavMenuClass)
.Append("\" aria-labelledby=\"").Append(id).AppendLine("\">");
foreach (var childNav in navItem.Children)
{
if (childNav.Label == "-")
{
sb.AppendLine(" <div class=\"dropdown-divider\"></div>");
}
else
{
sb.Append(" <a class=\"")
.Append(options.ChildNavMenuItemClass)
.Append(ActiveClass(childNav,options.ActivePath))
.Append("\"")
.Append(" href=\"")
.Append(options.BaseHref?.TrimEnd('/'))
.Append(childNav.Href)
.Append("\">")
.Append(childNav.Label)
.AppendLine("</a>");
}
}
sb.AppendLine("</div");
}
sb.Append("</lI>");
}
public static string NavButtonGroup(List<NavItem> navItems, NavOptions options)
{
if (navItems.IsEmpty())
return string.Empty;
var sb = StringBuilderCache.Allocate();
sb.Append("<div class=\"")
.Append(options.NavClass)
.AppendLine("\">");
foreach (var navItem in navItems)
{
NavLinkButton(sb, navItem, options);
}
sb.AppendLine("</div>");
return sb.ToString();
}
public static string NavButtonGroup(NavItem navItem, NavOptions options)
{
var sb = StringBuilderCache.Allocate();
NavLinkButton(sb, navItem, options);
return StringBuilderCache.ReturnAndFree(sb);
}
public static void NavLinkButton(StringBuilder sb, NavItem navItem, NavOptions options)
{
if (!navItem.ShowNav(options.Attributes))
return;
sb.Append("<a href=\"")
.Append(options.BaseHref?.TrimEnd('/'))
.Append(navItem.Href)
.Append("\"");
sb.Append(" class=\"")
.Append(navItem.ClassName).Append(navItem.ClassName != null ? " " : "")
.Append(options.NavItemClass).Append(ActiveClass(navItem, options.ActivePath))
.Append("\"");
if (navItem.Id != null)
sb.Append(" id=\"").Append(navItem.Id).Append("\"");
sb.Append(">")
.Append(!string.IsNullOrEmpty(navItem.IconClass)
? $"<i class=\"{navItem.IconClass}\"></i>" : "")
.Append(navItem.Label)
.AppendLine("</a>");
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsNull(object test) => test == null || test == JsNull.Value;
public static CultureInfo GetDefaultCulture(this DefaultScripts defaultScripts) =>
defaultScripts?.Context?.Args[ScriptConstants.DefaultCulture] as CultureInfo ?? ScriptConfig.DefaultCulture;
public static string GetDefaultTableClassName(this DefaultScripts defaultScripts) =>
defaultScripts?.Context?.Args[ScriptConstants.DefaultTableClassName] as string;
public static string TextDump(this object target) => DefaultScripts.TextDump(target, null);
public static string TextDump(this object target, TextDumpOptions options) => DefaultScripts.TextDump(target, options);
public static string DumpTable(this object target) => DefaultScripts.TextDump(target, null);
public static string DumpTable(this object target, TextDumpOptions options) => DefaultScripts.TextDump(target, options);
public static string HtmlDump(object target) => HtmlScripts.HtmlDump(target, null);
public static string HtmlDump(object target, HtmlDumpOptions options) => HtmlScripts.HtmlDump(target, options);
public static string StyleText(string text, TextStyle textStyle)
{
if (text == null) return null;
switch (textStyle)
{
case TextStyle.SplitCase:
return DefaultScripts.splitCase(text);
case TextStyle.Humanize:
return DefaultScripts.humanize(text);
case TextStyle.TitleCase:
return DefaultScripts.titleCase(text);
case TextStyle.PascalCase:
return DefaultScripts.pascalCase(text);
case TextStyle.CamelCase:
return DefaultScripts.camelCase(text);
}
return text;
}
/// <summary>
/// Emit HTML hidden input field for each specified Key/Value pair entry
/// </summary>
public static string HtmlHiddenInputs(IEnumerable<KeyValuePair<string,object>> inputValues)
{
if (inputValues != null)
{
var sb = StringBuilderCache.Allocate();
foreach (var entry in inputValues)
{
sb.AppendLine($"<input type=\"hidden\" name=\"{entry.Key.HtmlEncode()}\" value=\"{entry.Value?.ToString().HtmlEncode()}\">");
}
return StringBuilderCache.ReturnAndFree(sb);
}
return null;
}
internal static object GetItem(this IRequest httpReq, string key)
{
if (httpReq == null) return null;
httpReq.Items.TryGetValue(key, out var value);
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ResponseStatus GetErrorStatus(IRequest req) =>
req.GetItem("__errorStatus") as ResponseStatus; // Keywords.ErrorStatus
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool HasErrorStatus(IRequest req) => GetErrorStatus(req) != null;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string FormQuery(IRequest req, string name) => req.FormData[name] ?? req.QueryString[name];
public static string[] FormQueryValues(IRequest req, string name)
{
var values = req.Verb == HttpMethods.Post
? req.FormData.GetValues(name)
: req.QueryString.GetValues(name);
return values?.Length == 1 // if it's only a single item can be returned in comma-delimited list
? values[0].Split(',')
: values ?? TypeConstants.EmptyStringArray;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string FormValue(IRequest req, string name) => FormValue(req, name, null);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string FormValue(IRequest req, string name, string defaultValue) => HasErrorStatus(req)
? FormQuery(req, name)
: defaultValue;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string[] FormValues(IRequest req, string name) => HasErrorStatus(req)
? FormQueryValues(req, name)
: null;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool FormCheckValue(IRequest req, string name)
{
var value = FormValue(req, name);
return value == "true" || value == "True" || value == "t" || value == "on" || value == "1";
}
public static string GetParam(IRequest req, string name) //sync with IRequest.GetParam()
{
string value;
if ((value = req.Headers[HttpHeaders.XParamOverridePrefix + name]) != null) return value;
if ((value = req.QueryString[name]) != null) return value;
if ((value = req.FormData[name]) != null) return value;
//IIS will assign null to params without a name: .../?some_value can be retrieved as req.Params[null]
//TryGetValue is not happy with null dictionary keys, so we should bail out here
if (string.IsNullOrEmpty(name)) return null;
if (req.Cookies.TryGetValue(name, out var cookie)) return cookie.Value;
if (req.Items.TryGetValue(name, out var oValue)) return oValue.ToString();
return null;
}
/// <summary>
/// Comma delimited field names
/// </summary>
public static List<string> ToVarNames(string fieldNames) =>
fieldNames.Split(',').Map(x => x.Trim());
public static IEnumerable<string> ToStrings(string filterName, object arg)
{
if (arg == null)
return TypeConstants.EmptyStringArray;
var strings = arg is IEnumerable<string> ls
? ls
: arg is string s
? (IEnumerable<string>)new [] { s }
: arg is IEnumerable<object> e
? e.Map(x => x.AsString())
: throw new NotSupportedException($"{filterName} expected a collection of strings but was '{arg.GetType().Name}'");
return strings;
}
/// <summary>
/// Show validation summary error message unless there's an error in exceptFor list of fields
/// as validation errors will be displayed along side the field instead
/// </summary>
public static string ValidationSummary(ResponseStatus errorStatus, string exceptFor) =>
ValidationSummary(errorStatus, ToVarNames(exceptFor), null);
public static string ValidationSummary(ResponseStatus errorStatus, ICollection<string> exceptFields, Dictionary<string,object> divAttrs)
{
var errorSummaryMsg = exceptFields != null
? ErrorResponseExcept(errorStatus, exceptFields)
: ErrorResponseSummary(errorStatus);
if (string.IsNullOrEmpty(errorSummaryMsg))
return null;
if (divAttrs == null)
divAttrs = new Dictionary<string, object>();
if (!divAttrs.ContainsKey("class") && !divAttrs.ContainsKey("className"))
divAttrs["class"] = ValidationSummaryCssClassNames;
return HtmlScripts.htmlDiv(errorSummaryMsg, divAttrs).ToRawString();
}
public static string ValidationSummaryCssClassNames = "alert alert-danger";
public static string ValidationSuccessCssClassNames = "alert alert-success";
/// <summary>
/// Display a "Success Alert Box"
/// </summary>
public static string ValidationSuccess(string message, Dictionary<string,object> divAttrs)
{
if (divAttrs == null)
divAttrs = new Dictionary<string, object>();
if (!divAttrs.ContainsKey("class") && !divAttrs.ContainsKey("className"))
divAttrs["class"] = ValidationSuccessCssClassNames;
return HtmlScripts.htmlDiv(message, divAttrs).ToRawString();
}
/// <summary>
/// Return an error message unless there's an error in fieldNames
/// </summary>
public static string ErrorResponseExcept(ResponseStatus errorStatus, string fieldNames) =>
ErrorResponseExcept(errorStatus, ToVarNames(fieldNames));
public static string ErrorResponseExcept(ResponseStatus errorStatus, ICollection<string> fieldNames)
{
if (errorStatus == null)
return null;
var fieldNamesLookup = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var fieldName in fieldNames)
{
fieldNamesLookup.Add(fieldName);
}
if (!fieldNames.IsEmpty() && !errorStatus.Errors.IsEmpty())
{
foreach (var fieldError in errorStatus.Errors)
{
if (fieldNamesLookup.Contains(fieldError.FieldName))
return null;
}
var firstFieldError = errorStatus.Errors[0];
return firstFieldError.Message ?? firstFieldError.ErrorCode;
}
return errorStatus.Message ?? errorStatus.ErrorCode;
}
/// <summary>
/// Return an error message unless there are field errors
/// </summary>
public static string ErrorResponseSummary(ResponseStatus errorStatus)
{
if (errorStatus == null)
return null;
return errorStatus.Errors.IsEmpty()
? errorStatus.Message ?? errorStatus.ErrorCode
: null;
}
/// <summary>
/// Return an error for the specified field (if any)
/// </summary>
public static string ErrorResponse(ResponseStatus errorStatus, string fieldName)
{
if (fieldName == null)
return ErrorResponseSummary(errorStatus);
if (errorStatus == null || errorStatus.Errors.IsEmpty())
return null;
foreach (var fieldError in errorStatus.Errors)
{
if (fieldName.EqualsIgnoreCase(fieldError.FieldName))
return fieldError.Message ?? fieldError.ErrorCode;
}
return null;
}
public static List<KeyValuePair<string, string>> ToKeyValues(object values)
{
var to = new List<KeyValuePair<string, string>>();
if (values != null)
{
if (values is IEnumerable<KeyValuePair<string, object>> kvps)
foreach (var kvp in kvps) to.Add(new KeyValuePair<string,string>(kvp.Key, kvp.Value?.ToString()));
else if (values is IEnumerable<KeyValuePair<string, string>> kvpsStr)
foreach (var kvp in kvpsStr) to.Add(new KeyValuePair<string,string>(kvp.Key, kvp.Value));
else if (values is IEnumerable<object> list)
to.AddRange(from string item in list select item.AsString() into s select new KeyValuePair<string, string>(s, s));
}
return to;
}
public static List<string> SplitStringList(IEnumerable strings) => strings is null
? TypeConstants.EmptyStringList
: strings is List<string> strList
? strList
: strings is IEnumerable<string> strEnum
? strEnum.ToList()
: strings is IEnumerable<object> objEnum
? objEnum.Map(x => x.AsString())
: strings is string strFields
? strFields.Split(',').Map(x => x.Trim())
: throw new NotSupportedException($"Cannot convert '{strings.GetType().Name}' to List<string>");
public static List<string> ToStringList(IEnumerable strings) => strings is List<string> l ? l
: strings is string s
? new List<string> { s }
: strings is IEnumerable<string> e
? new List<string>(e)
: strings.Map(x => x.AsString());
public static string FormControl(IRequest req, Dictionary<string,object> args, string tagName, InputOptions inputOptions)
{
if (tagName == null)
tagName = "input";
var options = inputOptions ?? new InputOptions();
string id = null;
string type = null;
string name = null;
string label = null;
string size = options.Size;
bool inline = options.Inline;
if (args.TryGetValue("type", out var oType))
type = oType as string;
else
args["type"] = type = "text";
var notInput = tagName != "input";
if (notInput)
{
type = tagName;
args.RemoveKey("type");
}
var inputClass = "form-control";
var labelClass = "form-label";
var helpClass = "text-muted";
var isCheck = type == "checkbox" || type == "radio";
if (isCheck)
{
inputClass = "form-check-input";
labelClass = "form-check-label";
if (!args.ContainsKey("value"))
args["value"] = "true";
}
else if (type == "range")
{
inputClass = "form-control-range";
}
if (options.LabelClass != null)
labelClass = options.LabelClass;
if (args.TryGetValue("id", out var oId))
{
if (!args.ContainsKey("name"))
args["name"] = id = oId as string;
if (args.TryGetValue("name", out var oName))
name = oName as string;
}
string help = options.Help;
string helpId = help != null ? (id ?? name) + "-help" : null;
if (helpId != null)
args["aria-describedby"] = helpId;
if (options.Label != null)
{
label = options.Label;
if (!args.ContainsKey("placeholder"))
args["placeholder"] = label;
}
var values = options.Values;
var isSingleCheck = isCheck && values == null;
object oValue = null;
string formValue = null;
var isGet = req.Verb == HttpMethods.Get;
var preserveValue = options.PreserveValue;
if (preserveValue)
{
var strValue = args.TryGetValue("value", out oValue) ? oValue as string : null;
formValue = FormValue(req, name, strValue);
if (!isGet || !string.IsNullOrEmpty(formValue)) //only override value if POST or GET queryString has value
{
if (!isCheck)
args["value"] = formValue;
else if (isSingleCheck)
args["checked"] = formValue == "true";
}
}
else if (!isGet)
{
if (!isCheck)
{
args["value"] = null;
}
}
var className = args.TryGetValue("class", out var oCls) || args.TryGetValue("className", out oCls)
? HtmlScripts.htmlClassList(oCls)
: "";
className = HtmlScripts.htmlAddClass(className, inputClass);
if (size != null)
className = HtmlScripts.htmlAddClass(className, inputClass + "-" + size);