├── .config └── dotnet-tools.json ├── .editorconfig ├── .gitignore ├── Api.fs ├── DataAccess.fs ├── Domain.fs ├── Program.fs ├── README.md ├── View.fs ├── fshtmx.fsproj ├── fshtmx.sln └── global.json /.config/dotnet-tools.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "isRoot": true, 4 | "tools": { 5 | "fantomas": { 6 | "version": "6.1.2", 7 | "commands": [ 8 | "fantomas" 9 | ] 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 4 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = false 9 | 10 | [*.{fs,fsx,fsi}] 11 | fsharp_multiline_bracket_style = stroustrup 12 | fsharp_newline_before_multiline_computation_expression = false -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | 400 | /.idea/ 401 | /.vscode/ -------------------------------------------------------------------------------- /Api.fs: -------------------------------------------------------------------------------- 1 | [] 2 | module Api 3 | 4 | open FsToolkit.ErrorHandling 5 | open Domain 6 | open Giraffe 7 | 8 | open Microsoft.AspNetCore.Http 9 | 10 | /// Finds destinations to suggest. 11 | let suggestDestinations next (ctx: HttpContext) = taskOption { 12 | let! request = 13 | ctx.BindModelAsync() 14 | |> Task.map SearchRequest.OfRawSearchRequest 15 | 16 | let destinations = DataAccess.findDestinations request.SearchInput 17 | return! htmlView (View.createCountriesSuggestions destinations) next ctx 18 | } 19 | 20 | /// Gets all energy reports using the query information supplied in the body. 21 | let findEnergyReports next (ctx: HttpContext) = task { 22 | let! request = 23 | ctx.BindModelAsync() 24 | |> Task.map SearchRequest.OfRawSearchRequest 25 | 26 | let reports = 27 | match request.SearchInput with 28 | | None -> DataAccess.findReportsByCountries request.Sort "" 29 | | Some searchInput -> 30 | DataAccess.tryExactMatchReport request.Sort searchInput 31 | |> Option.defaultWith (fun () -> DataAccess.findReportsByCountries request.Sort searchInput) 32 | 33 | return! htmlView (View.createReportsTable request.Sort reports) next ctx 34 | } -------------------------------------------------------------------------------- /DataAccess.fs: -------------------------------------------------------------------------------- 1 | [] 2 | module DataAccess 3 | 4 | open Domain 5 | open FSharp.Data 6 | open FsToolkit.ErrorHandling 7 | open Microsoft.Extensions.Caching.Memory 8 | open Polly 9 | open Polly.Caching.Memory 10 | open System 11 | 12 | let cachePolicy = 13 | let memoryCacheProvider = 14 | let memoryCache = new MemoryCache(MemoryCacheOptions()) 15 | MemoryCacheProvider memoryCache 16 | 17 | Policy.Cache(memoryCacheProvider, TimeSpan.FromMinutes 5) 18 | 19 | type private CountryCodesWiki = HtmlProvider<"https://en.m.wikipedia.org/wiki/List_of_ISO_3166_country_codes"> 20 | 21 | let private tryGetCountryIsoCode = 22 | let lookup = 23 | readOnlyDict [ 24 | for row in CountryCodesWiki.GetSample().Tables.``Current ISO 3166 country codesEdit``.Rows do 25 | row.``ISO 3166-1[2] - Alpha-3 code[5]``, row.``ISO 3166-1[2] - Alpha-2 code[5]`` 26 | ] 27 | 28 | fun value -> lookup |> Option.tryGetValue value |> Option.map (fun r -> r.ToLower()) 29 | 30 | let private ctx = WorldBankData.GetDataContext() 31 | let private allCountries = ctx.Countries |> Seq.toList 32 | let private allRegions = ctx.Regions |> Seq.toList 33 | 34 | let private countriesAndRegions = 35 | let countries = allCountries |> List.map (fun country -> country.Name.Trim()) 36 | let regions = allRegions |> List.map (fun region -> region.Name.Trim()) 37 | countries @ regions 38 | 39 | let private containsText (text: string) (v: string) = 40 | v.Trim().Contains(text.Trim(), StringComparison.CurrentCultureIgnoreCase) 41 | 42 | let private matches (text: string) (v: string) = 43 | v.Trim().Equals(text.Trim(), StringComparison.CurrentCultureIgnoreCase) 44 | 45 | let tryCreateReport country = 46 | let actualQuery (country: WorldBankData.ServiceTypes.Country) = option { 47 | let! nuclear = 48 | country.Indicators.``Alternative and nuclear energy (% of total energy use)``.Values 49 | |> Seq.tryLast 50 | 51 | let! imports = 52 | country.Indicators.``Energy imports, net (% of energy use)``.Values 53 | |> Seq.tryLast 54 | 55 | let! renewables = 56 | country.Indicators.``Renewable energy consumption (% of total final energy consumption)``.Values 57 | |> Seq.tryLast 58 | 59 | let! fossils = 60 | country.Indicators.``Fossil fuel energy consumption (% of total)``.Values 61 | |> Seq.tryLast 62 | 63 | return { 64 | Country = country.Name 65 | Code = tryGetCountryIsoCode country.Code 66 | Nuclear = nuclear 67 | EnergyImports = imports 68 | RenewableEnergyConsumption = renewables 69 | FossilFuelEnergyConsumption = fossils 70 | } 71 | } 72 | 73 | cachePolicy.Execute((fun ctx -> actualQuery country), Context $"{country.Code}") 74 | 75 | /// Gets the top ten destinations that contain the supplied text. 76 | let findDestinations (text: string option) = 77 | match text with 78 | | None -> countriesAndRegions 79 | | Some text -> countriesAndRegions |> List.filter (containsText text) 80 | |> List.truncate 10 81 | 82 | /// Finds all country-level reports that contain the supplied text. 83 | let findReportsByCountries sortParameters (text: string) = 84 | allCountries 85 | |> Seq.filter (fun country -> country.Name |> containsText text) 86 | |> Seq.choose tryCreateReport 87 | |> Seq.pickSort sortParameters 88 | |> Seq.toList 89 | 90 | /// Looks for an exact match of a country or region based on the text supplied. Tries a country first; if no match, 91 | /// check for a region - if that matches, all countries within that region are returned. 92 | let tryExactMatchReport sortParameters (text: string) = 93 | let matchingCountry = allCountries |> List.tryFind (fun c -> c.Name |> matches text) 94 | 95 | match matchingCountry with 96 | | Some country -> tryCreateReport country |> Option.map List.singleton 97 | | None -> 98 | allRegions 99 | |> List.tryFind (fun region -> region.Name |> matches text) 100 | |> Option.map (fun region -> 101 | region.Countries 102 | |> Seq.choose tryCreateReport 103 | |> Seq.pickSort sortParameters 104 | |> Seq.toList) -------------------------------------------------------------------------------- /Domain.fs: -------------------------------------------------------------------------------- 1 | namespace Domain 2 | 3 | open FsToolkit.ErrorHandling 4 | 5 | /// The input search request parameters. 6 | [] 7 | type RawSearchRequest = { 8 | SearchInput: string 9 | SortColumn: string 10 | SortDirection: string 11 | } 12 | 13 | /// Represents a report for a specific country. 14 | type CountryReport = { 15 | Country: string 16 | Code: string option 17 | Nuclear: float 18 | EnergyImports: float 19 | RenewableEnergyConsumption: float 20 | FossilFuelEnergyConsumption: float 21 | } 22 | 23 | type NumericColumn = 24 | | Renewables 25 | | Imports 26 | | Fossil 27 | | Nuclear 28 | 29 | type TextColumn = Country 30 | 31 | /// The sort column to use. 32 | type SortColumn = 33 | | TextColumn of TextColumn 34 | | NumericColumn of NumericColumn 35 | 36 | member this.AsString = 37 | match this with 38 | | TextColumn Country -> "Country" 39 | | NumericColumn Renewables -> "Renewables" 40 | | NumericColumn Imports -> "Imports" 41 | | NumericColumn Fossil -> "Fossil" 42 | | NumericColumn Nuclear -> "Nuclear" 43 | 44 | static member TryOfString v = 45 | match v with 46 | | "Country" -> Some(TextColumn Country) 47 | | "Renewables" -> Some(NumericColumn Renewables) 48 | | "Imports" -> Some(NumericColumn Imports) 49 | | "Fossil" -> Some(NumericColumn Fossil) 50 | | "Nuclear" -> Some(NumericColumn Nuclear) 51 | | _ -> None 52 | 53 | type SortDirection = 54 | | Ascending 55 | | Descending 56 | 57 | member this.AsString = 58 | match this with 59 | | Ascending -> "Ascending" 60 | | Descending -> "Descending" 61 | 62 | static member TryOfString v = 63 | match v with 64 | | "Ascending" -> Some Ascending 65 | | "Descending" -> Some Descending 66 | | _ -> None 67 | 68 | type Sort = SortColumn * SortDirection 69 | 70 | type SearchRequest = { 71 | SearchInput: string option 72 | Sort: Sort 73 | } with 74 | 75 | static member OfRawSearchRequest(request: RawSearchRequest) = { 76 | SearchInput = request.SearchInput |> Option.ofObj 77 | Sort = 78 | let userSort = option { 79 | let! col = SortColumn.TryOfString request.SortColumn 80 | let! dir = SortDirection.TryOfString request.SortDirection 81 | return col, dir 82 | } 83 | 84 | userSort |> Option.defaultValue (TextColumn Country, Ascending) 85 | } 86 | 87 | module Seq = 88 | /// Sorts the supplied reports using the specified sort column. 89 | let pickSort (column, direction) = 90 | match column with 91 | | TextColumn Country -> 92 | match direction with 93 | | Ascending -> Seq.sortBy (fun c -> c.Country) 94 | | Descending -> Seq.sortByDescending (fun c -> c.Country) 95 | | NumericColumn column -> 96 | let column = 97 | match column with 98 | | Imports -> fun c -> c.EnergyImports 99 | | Fossil -> fun c -> c.FossilFuelEnergyConsumption 100 | | Nuclear -> fun c -> c.Nuclear 101 | | Renewables -> fun c -> c.RenewableEnergyConsumption 102 | 103 | match direction with 104 | | Ascending -> Seq.sortBy column 105 | | Descending -> Seq.sortByDescending column -------------------------------------------------------------------------------- /Program.fs: -------------------------------------------------------------------------------- 1 | open Saturn 2 | 3 | let allRoutes = router { 4 | get "/" View.startingPage 5 | post "/search-suggestions" Api.suggestDestinations 6 | post "/do-search" Api.findEnergyReports 7 | } 8 | 9 | let app = application { use_router allRoutes } 10 | 11 | run app -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # htmx-demo 2 | 3 | A demo application using HTMX with an ASP .NET back-end using Saturn and Giraffe. 4 | 5 | 1. dotnet tool restore 6 | 2. dotnet run 7 | -------------------------------------------------------------------------------- /View.fs: -------------------------------------------------------------------------------- 1 | [] 2 | module View 3 | 4 | open Domain 5 | open Giraffe 6 | open Giraffe.Htmx 7 | open Giraffe.ViewEngine 8 | open Giraffe.ViewEngine.Htmx 9 | 10 | module private Helpers = 11 | let buildTable children = 12 | div [ _class "page" ] [ 13 | div [ _class "page-wrapper" ] [ 14 | div [ _class "page-body" ] [ 15 | div [ _class "container-xl" ] [ 16 | div [ _class "row row-cards" ] [ div [ _class "col-12" ] children ] 17 | ] 18 | ] 19 | ] 20 | ] 21 | 22 | module private Header = 23 | let linksAndScripts = [ 24 | link [ 25 | _rel "stylesheet" 26 | _href "https://cdn.jsdelivr.net/npm/@tabler/core@latest/dist/css/tabler.min.css" 27 | ] 28 | link [ 29 | _rel "stylesheet" 30 | _href "https://cdn.jsdelivr.net/npm/@tabler/core@latest/dist/css/tabler-flags.min.css" 31 | ] 32 | script [ 33 | _src "https://cdn.jsdelivr.net/npm/@tabler/core@latest/dist/js/tabler.min.js" 34 | ] [] 35 | ] 36 | 37 | module private SearchElements = 38 | let input = 39 | div [ _class "row" ] [ 40 | div [] [ 41 | label [ _for "search-input"; _class "form-label" ] [ str "Search Term" ] 42 | datalist [ _id "search-suggestions" ] [] 43 | div [ _class "input-icon mb-3" ] [ 44 | input [ 45 | _id "search-input" 46 | _class "form-control" 47 | _list "search-suggestions" 48 | _name "searchinput" 49 | _placeholder "Enter an exact or partial country, or a region." 50 | _type "search" 51 | 52 | _hxTrigger "keyup changed delay:500ms" 53 | _hxPost "/search-suggestions" 54 | _hxTarget "#search-suggestions" 55 | _hxSwap HxSwap.OuterHtml 56 | ] 57 | span [ _id "spinner"; _class "htmx-indicator input-icon-addon" ] [ 58 | div [ _class "spinner-border spinner-border-sm"; attr "role" "status" ] [] 59 | ] 60 | ] 61 | ] 62 | ] 63 | 64 | let button = 65 | button [ 66 | _class "btn btn-primary" 67 | _id "search-button" 68 | _name "searchButton" 69 | _type "submit" 70 | 71 | _hxPost "/do-search" 72 | _hxInclude "#search-input" 73 | _hxTarget "#search-results" 74 | _hxIndicator "#spinner" 75 | ] [ str " Search!" ] 76 | 77 | let title = 78 | h4 [ _class "card-title" ] [ 79 | str "World Bank Energy Statistics" 80 | span [ _class "card-subtitle" ] [ str "F#, HTMX and Tabler demonstrator" ] 81 | ] 82 | 83 | /// The initial start page of the application. 84 | let startingPage: HttpHandler = 85 | html [] [ 86 | head [] Header.linksAndScripts 87 | Script.minified 88 | body [ _class "theme-light" ] [ 89 | div [ _class "page" ] [ 90 | div [ _class "page-wrapper" ] [ 91 | div [ _class "page-body" ] [ 92 | div [ _class "container-xl" ] [ 93 | div [ _class "row row-cards" ] [ 94 | div [ _class "col-12" ] [ 95 | form [ _class "card" ] [ 96 | div [ _class "card-header card-header-light" ] [ SearchElements.title ] 97 | div [ _class "card-body" ] [ SearchElements.input ] 98 | div [ _class "card-footer d-flex" ] [ SearchElements.button ] 99 | ] 100 | div [ _id "search-results"; _class "mt-3" ] [] 101 | ] 102 | ] 103 | ] 104 | ] 105 | ] 106 | ] 107 | ] 108 | ] 109 | |> htmlView 110 | 111 | /// Builds a table based on all reports. 112 | let createReportsTable sort reports = 113 | let pickCellColour (success, warning) value = 114 | [ "success", success; "warning", warning ] 115 | |> List.tryFind (fun (_, f) -> f value) 116 | |> Option.map fst 117 | |> Option.defaultValue "danger" 118 | |> sprintf "bg-%s" 119 | 120 | let buildProgressBarCell value pickers = 121 | let colour = value |> pickCellColour pickers 122 | 123 | td [] [ 124 | div [ _class "row align-items-center" ] [ 125 | div [ _class "col-12 col-lg-auto" ] [ 126 | div [ _class "progress"; _style "width: 5rem" ] [ 127 | div [ 128 | _class $"progress-bar {colour}" 129 | _style $"width: {value}%%" 130 | attr "role" "progressbar" 131 | ] [] 132 | ] 133 | ] 134 | div [ _class "col" ] [ str $"%.2f{value}%%" ] 135 | ] 136 | ] 137 | 138 | let higherIsBetter = (fun x -> x > 40.), (fun x -> x > 10.) 139 | let lowerIsBetter = (fun x -> x < 25.), (fun x -> x < 50.) 140 | 141 | div [ _class "card" ] [ 142 | div [ _id "table-default"; _class "table-responsive" ] [ 143 | table [ _class "table card-table table-striped datatable" ] [ 144 | thead [] [ 145 | tr [] [ 146 | let makeTh value (column: SortColumn) = 147 | th [] [ 148 | button [ 149 | let nextDirection, sortHeader = 150 | match sort with 151 | | currentColumn, Ascending when column = currentColumn -> Descending, "asc" 152 | | currentColumn, Descending when column = currentColumn -> Ascending, "desc" 153 | | _ -> Ascending, "" 154 | 155 | _class $"table-sort {sortHeader}" 156 | 157 | _hxInclude "#search-input" 158 | _hxTarget "#search-results" 159 | _hxPost "/do-search" 160 | _hxTrigger "click" 161 | 162 | _hxVals 163 | $"{{ \"sortColumn\" : \"{column.AsString}\", \"sortDirection\" : \"{nextDirection.AsString}\" }}" 164 | ] [ str value ] 165 | ] 166 | 167 | makeTh "Country" (TextColumn Country) 168 | makeTh "Energy Imports (% of total)" (NumericColumn Imports) 169 | makeTh "Renewables (% of total)" (NumericColumn Renewables) 170 | makeTh "Fossil Fuels (% of total)" (NumericColumn Fossil) 171 | makeTh "Nuclear & Other (% of total)" (NumericColumn Nuclear) 172 | ] 173 | ] 174 | tbody [ _class "table-group-divider" ] [ 175 | for report in reports do 176 | tr [] [ 177 | td [] [ 178 | match report.Code with 179 | | Some code -> span [ _class $"flag flag-country-{code}" ] [] 180 | | None -> () 181 | str $" {report.Country} " 182 | ] 183 | buildProgressBarCell report.EnergyImports lowerIsBetter 184 | buildProgressBarCell report.RenewableEnergyConsumption higherIsBetter 185 | buildProgressBarCell report.FossilFuelEnergyConsumption lowerIsBetter 186 | buildProgressBarCell report.Nuclear higherIsBetter 187 | ] 188 | ] 189 | ] 190 | ] 191 | ] 192 | 193 | /// Creates a datalist for the supplied countries. 194 | let createCountriesSuggestions destinations = 195 | datalist [ _id "search-suggestions" ] [ 196 | for destination: string in destinations do 197 | option [ _value destination ] [] 198 | ] -------------------------------------------------------------------------------- /fshtmx.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net6.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /fshtmx.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.6.33829.357 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "fshtmx", "fshtmx.fsproj", "{6B81D76F-9556-4C92-BB93-703692B4BE6C}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {6B81D76F-9556-4C92-BB93-703692B4BE6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {6B81D76F-9556-4C92-BB93-703692B4BE6C}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {6B81D76F-9556-4C92-BB93-703692B4BE6C}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {6B81D76F-9556-4C92-BB93-703692B4BE6C}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {FB1E3DAC-4794-4E6E-9A45-23DD950A34AE} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "6.0.0", 4 | "rollForward": "latestMinor" 5 | } 6 | } --------------------------------------------------------------------------------