├── .github └── workflows │ └── main.yml ├── .gitignore ├── Blazor.FileSystem.sln ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── docs └── icon.png ├── samples ├── KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks │ ├── BenchmarkRenderer.cs │ ├── Benchmarks │ │ ├── JsonConstants.cs │ │ └── NodePresenterBenchmark.cs │ ├── KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks.csproj │ ├── Program.cs │ └── RenderedComponent{T}.cs └── KristofferStrube.Blazor.FileSystem.WasmExample │ ├── App.razor │ ├── KristofferStrube.Blazor.FileSystem.WasmExample.csproj │ ├── Pages │ ├── DirectoryExplorer.razor │ ├── Index.razor │ ├── SearchMastodon.razor │ └── Status.razor │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── Search │ ├── AlphabetExtensions.cs │ ├── EditOperation.cs │ ├── NaiveSuffixTree.cs │ ├── Node.cs │ └── SamLine.cs │ ├── Shared │ ├── ElementExplorer.razor │ ├── ElementExplorer.razor.cs │ ├── MainLayout.razor │ ├── MainLayout.razor.css │ ├── NavMenu.razor │ ├── NavMenu.razor.css │ └── NotePresenter.razor │ ├── _Imports.razor │ └── wwwroot │ ├── 404.html │ ├── css │ ├── app.css │ ├── bootstrap │ │ ├── bootstrap.min.css │ │ └── bootstrap.min.css.map │ └── open-iconic │ │ ├── FONT-LICENSE │ │ ├── ICON-LICENSE │ │ ├── README.md │ │ └── font │ │ ├── css │ │ └── open-iconic-bootstrap.min.css │ │ └── fonts │ │ ├── open-iconic.eot │ │ ├── open-iconic.otf │ │ ├── open-iconic.svg │ │ ├── open-iconic.ttf │ │ └── open-iconic.woff │ └── index.html └── src └── KristofferStrube.Blazor.FileSystem ├── BaseJSWrapper.cs ├── Converters └── BlobConverter.cs ├── EnumDescriptionConverter.cs ├── Enums ├── FileSystemCreateWritableOptions.cs ├── FileSystemHandleKind.cs └── WriteCommandType.cs ├── Extensions ├── IJSRuntimeExtensions.cs └── IServiceCollectionExtensions.cs ├── FileSystemDirectoryHandle.InProcess.cs ├── FileSystemDirectoryHandle.cs ├── FileSystemFileHandle.InProcess.cs ├── FileSystemFileHandle.cs ├── FileSystemHandle.InProcess.cs ├── FileSystemHandle.cs ├── FileSystemWritableFileStream.InProcess.cs ├── FileSystemWritableFileStream.cs ├── IFileSystemHandle.InProcess.cs ├── IFileSystemHandle.cs ├── IStorageManagerService.InProcess.cs ├── IStorageManagerService.cs ├── KristofferStrube.Blazor.FileSystem.csproj ├── Options ├── FileSystemGetDirectoryOptions.cs ├── FileSystemGetFileOptions.cs ├── FileSystemOptions.cs ├── FileSystemRemoveOptions.cs └── WriteParams.cs ├── StorageManagerService.InProcess.cs ├── StorageManagerService.cs └── wwwroot └── KristofferStrube.Blazor.FileSystem.js /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: 'Publish application' 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths-ignore: 8 | - '**/README.md' 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | # Checkout the code 15 | - uses: actions/checkout@v2 16 | 17 | # Install .NET 7.0 SDK 18 | - name: Setup .NET 7 preview 19 | uses: actions/setup-dotnet@v1 20 | with: 21 | dotnet-version: '7.0.x' 22 | include-prerelease: true 23 | 24 | # Generate the website 25 | - name: Publish 26 | run: dotnet publish samples/KristofferStrube.Blazor.FileSystem.WasmExample/KristofferStrube.Blazor.FileSystem.WasmExample.csproj --configuration Release --output build 27 | 28 | # Publish the website 29 | - name: GitHub Pages action 30 | if: ${{ github.ref == 'refs/heads/main' }} # Publish only when the push is on main 31 | uses: peaceiris/actions-gh-pages@v3.6.1 32 | with: 33 | github_token: ${{ secrets.PUBLISH_TOKEN }} 34 | publish_branch: gh-pages 35 | publish_dir: build/wwwroot 36 | allow_empty_commit: false 37 | keep_files: false 38 | force_orphan: true 39 | -------------------------------------------------------------------------------- /.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/master/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 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /Blazor.FileSystem.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KristofferStrube.Blazor.FileSystem", "src\KristofferStrube.Blazor.FileSystem\KristofferStrube.Blazor.FileSystem.csproj", "{0FB54CE2-FF43-4DED-89E4-3D720C1073E9}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KristofferStrube.Blazor.FileSystem.WasmExample", "samples\KristofferStrube.Blazor.FileSystem.WasmExample\KristofferStrube.Blazor.FileSystem.WasmExample.csproj", "{BE27A4A4-BFBB-4CA1-8610-7D9EE89FDF97}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks", "samples\KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks\KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks.csproj", "{3F999E53-0683-4E00-B0A6-5DA81C356987}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {0FB54CE2-FF43-4DED-89E4-3D720C1073E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {0FB54CE2-FF43-4DED-89E4-3D720C1073E9}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {0FB54CE2-FF43-4DED-89E4-3D720C1073E9}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {0FB54CE2-FF43-4DED-89E4-3D720C1073E9}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {BE27A4A4-BFBB-4CA1-8610-7D9EE89FDF97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {BE27A4A4-BFBB-4CA1-8610-7D9EE89FDF97}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {BE27A4A4-BFBB-4CA1-8610-7D9EE89FDF97}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {BE27A4A4-BFBB-4CA1-8610-7D9EE89FDF97}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {3F999E53-0683-4E00-B0A6-5DA81C356987}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {3F999E53-0683-4E00-B0A6-5DA81C356987}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {3F999E53-0683-4E00-B0A6-5DA81C356987}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {3F999E53-0683-4E00-B0A6-5DA81C356987}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {31FE56B4-5C4F-4FAE-9CFC-CE343847423C} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | 9 | ## [0.3.1] - 2023-10-19 10 | ### Fixed 11 | - Fixed that writing `WriteParams` with a `Blob` used the wrong JS helper reference. 12 | 13 | ## [0.3.0] - 2023-03-16 14 | ### Changed 15 | - Changed .NET version to `7.0`. 16 | - Changed the version of Blazor.FileAPI to use the newest version which is `0.3.0`. 17 | ### Added 18 | - Added the generation of a documentation file packaging all XML comments with the package. 19 | 20 | ## [0.2.0] - 2023-01-25 21 | ### Added 22 | - Added interfaces `IFileSystemHandle` and `IFileSystemHandleInProcess`. 23 | ### Changed 24 | - Changed `FileSystemHandle.IsSameEntryAsync` to take `IFileSystemHandle` instead of `FileSystemHandle`. 25 | - Changed `FileSystemDirectoryHandle.ResolveAsync` to take `IFileSystemHandle` instead of `FileSystemHandle`. 26 | - Changed `FileSystemDirectoryHandle.ValuesAsync` to return `IFileSystemHandle` instead of `FileSystemHandle`. 27 | - Changed `FileSystemDirectoryHandleInProcess.ValuesAsync` to return `IFileSystemHandleInProcess` instead of `FileSystemHandleInProcess`. -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | Contributing includes many different actions. It is not only writing code. Contributions like discussing solutions in open issues are easily as valuable as contributing code as we can then find the best solution with the perspective of multiple people. 3 | 4 | ## Bugs and feature requests 5 | If you find any bugs in the project or have requests for features, then please [Open a new Issue](https://github.com/KristofferStrube/Blazor.FileSystem/issues/new). 6 | 7 | ## Contributing Code and Samples 8 | Before you contribute to the project, you will need to get confirmation from the library author that the contribution is welcome. 9 | This can help align the scope of the contribution so that you and the author agree on the solution and how you ensure the change is maintainable with the existing users in mind. 10 | Once you are ready to start coding try to follow these code guidelines: 11 | - Make a fork of the current `main` branch. 12 | - Follow the existing coding conventions used in the project. This includes tab style, naming conventions, etc. 13 | - If your contribution is a new feature, try to add a demo that demonstrates how this will be used in the sample project. 14 | - Any code or sample you share as a part of the resulting Pull Request should fall under the MIT license agreement. 15 | - You don't need to update the version number of the project as the maintainer will do this when making the next release after the Pull Request has been merged. 16 | - Keep your Pull Request to the point. I.e., if your Pull Request is related to fixing a bug then try not to touch any other files than the ones related to that issue as this will make the chance of the PR being merged without change requests more likely. 17 | 18 | ## Submitting a Pull Request 19 | If you don't know what a pull request is, read this article: https://help.github.com/articles/using-pull-requests. Make sure the repository can be built and that the related sample project still works as intended. It is also a good idea to familiarize yourself with the project workflow and our coding conventions. 20 | 21 | ## Ensuring that your contribution will be accepted 22 | You might also read these two blog posts on contributing code: [Open Source Contribution Etiquette](http://tirania.org/blog/archive/2010/Dec-31.html) by Miguel de Icaza and [Don't "Push" Your Pull Requests](https://www.igvita.com/2011/12/19/dont-push-your-pull-requests/) by Ilya Grigorik. These blog posts highlight good open-source collaboration etiquette and help align expectations between you and us. 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Kristoffer Strube 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](/LICENSE.md) 2 | [![GitHub issues](https://img.shields.io/github/issues/KristofferStrube/Blazor.FileSystem)](https://github.com/KristofferStrube/Blazor.FileSystem/issues) 3 | [![GitHub forks](https://img.shields.io/github/forks/KristofferStrube/Blazor.FileSystem)](https://github.com/KristofferStrube/Blazor.FileSystem/network/members) 4 | [![GitHub stars](https://img.shields.io/github/stars/KristofferStrube/Blazor.FileSystem)](https://github.com/KristofferStrube/Blazor.FileSystem/stargazers) 5 | [![NuGet Downloads (official NuGet)](https://img.shields.io/nuget/dt/KristofferStrube.Blazor.FileSystem?label=NuGet%20Downloads)](https://www.nuget.org/packages/KristofferStrube.Blazor.FileSystem/) 6 | 7 | # Introduction 8 | A Blazor wrapper for the [File System](https://fs.spec.whatwg.org/) browser API. 9 | 10 | The API standardizes ways to handle files and directories. It also enables access to the **origin private file system** which is a virtual sandboxed file system. This project implements a wrapper around the API for Blazor so that we can easily and safely interact with it from Blazor. 11 | 12 | # Demo 13 | The sample project can be demoed at https://kristofferstrube.github.io/Blazor.FileSystem/ 14 | 15 | On each page you can find the corresponding code for the example in the top right corner. 16 | 17 | On the [API Coverage Status](https://kristofferstrube.github.io/Blazor.FileSystem/Status) you can see how much of the WebIDL specs this wrapper has covered. 18 | 19 | # Getting Started 20 | ## Prerequisites 21 | You need to install .NET 7.0 or newer to use the library. 22 | 23 | [Download .NET 7](https://dotnet.microsoft.com/download/dotnet/7.0) 24 | 25 | ## Installation 26 | You can install the package via Nuget with the Package Manager in your IDE or alternatively using the command line: 27 | ```bash 28 | dotnet add package KristofferStrube.Blazor.FileSystem 29 | ``` 30 | 31 | # Usage 32 | The package can be used in Blazor WebAssembly and Blazor Server projects. (Note that streaming of big files is not supported in Blazor Server due to bandwidth problems.) 33 | ## Import 34 | You need to reference the package in order to use it in your pages. This can be done in `_Import.razor` by adding the following. 35 | ```razor 36 | @using KristofferStrube.Blazor.FileSystem 37 | ``` 38 | ## Add to service collection 39 | The library has one service which is the `IStorageManagerService` which can be used to get access to the **origin private file system**. An easy way to make the service available in all your pages is by registering it in the `IServiceCollection` so that it can be dependency injected in the pages that need it. This is done in `Program.cs` by adding the following before you build the host and run it. 40 | ```csharp 41 | var builder = WebAssemblyHostBuilder.CreateDefault(args); 42 | builder.RootComponents.Add("#app"); 43 | builder.RootComponents.Add("head::after"); 44 | 45 | // Other services are added. 46 | 47 | builder.Services.AddStorageManagerService(); 48 | 49 | await builder.Build().RunAsync(); 50 | ``` 51 | ## Inject in page 52 | Then the service can be injected in a page like so: 53 | ```razor 54 | @inject IStorageManagerService StorageManagerService; 55 | ``` 56 | Then you can use `IStorageManagerService` to get a directory handle for the **origin private file system** and read/create a file in it like this: 57 | ```razor 58 | 59 | 60 | @code { 61 | private async Task OpenAndReadFile() 62 | { 63 | FileSystemDirectoryHandle directoryHandle = await StorageManagerService.GetOriginPrivateDirectoryAsync(); 64 | FileSystemFileHandle fileHandle = await directoryHandle.GetFileHandleAsync("file.txt", new() { Create = true }); 65 | FileAPI.File file = await fileHandle.GetFileAsync(); 66 | // Do something with the file. 67 | } 68 | } 69 | ``` 70 | 71 | The counterpart to getting a `File` via the `GetFileAsync()` method is getting a `FileSystemWritableFileStream` via the `CreateWritableAsync()` method which can be used to write to the file referenced with the `FileSystemFileHandle` like this: 72 | ```csharp 73 | FileSystemFileHandle fileHandle; // Some file handle 74 | FileSystemWritableFileStream writable = await fileHandle.CreateWritableAsync(); 75 | await writable.WriteAsync("some text"); 76 | await writable.CloseAsync(); 77 | ``` 78 | You need to close the `FileSystemWritableFileStream` to commit the written text. You can either do so explicitly as seen above or you can use it in a using statement like this: 79 | ```csharp 80 | FileSystemFileHandle fileHandle; // Some file handle 81 | await using FileSystemWritableFileStream writable = await fileHandle.CreateWritableAsync(); 82 | await writable.WriteAsync(new byte[] { 0, 1, 2, 3, 4, 5 }); 83 | ``` 84 | This will automatically await the close when you get to the end of the current scope. 85 | 86 | # Issues 87 | Feel free to open issues on the repository if you find any errors with the package or have wishes for features. 88 | 89 | # Related repositories 90 | This project uses the *Blazor.FileAPI* package to return a rich `File` from the `GetFileAsync` method on a `FileSystemFileHandle` and when writing a `Blob` to a `FileSystemWritableFileSystem`. 91 | - https://github.com/KristofferStrube/Blazor.FileAPI 92 | 93 | This project is used in the *Blazor.FileSystemAccess* package as a basis for the file handles that it uses in its methods and extends on. 94 | - https://github.com/KristofferStrube/Blazor.FileSystemAccess 95 | 96 | # Related articles 97 | This repository was build with inspiration and help from the following series of articles: 98 | 99 | - [Wrapping JavaScript libraries in Blazor WebAssembly/WASM](https://blog.elmah.io/wrapping-javascript-libraries-in-blazor-webassembly-wasm/) 100 | - [Call anonymous C# functions from JS in Blazor WASM](https://blog.elmah.io/call-anonymous-c-functions-from-js-in-blazor-wasm/) 101 | - [Using JS Object References in Blazor WASM to wrap JS libraries](https://blog.elmah.io/using-js-object-references-in-blazor-wasm-to-wrap-js-libraries/) 102 | - [Blazor WASM 404 error and fix for GitHub Pages](https://blog.elmah.io/blazor-wasm-404-error-and-fix-for-github-pages/) 103 | - [How to fix Blazor WASM base path problems](https://blog.elmah.io/how-to-fix-blazor-wasm-base-path-problems/) 104 | -------------------------------------------------------------------------------- /docs/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.FileSystem/718d8d36c44a7c61d994ff19a54b98ce4386a29a/docs/icon.png -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks/BenchmarkRenderer.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Components.RenderTree; 2 | using Microsoft.AspNetCore.Components; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Logging.Abstractions; 5 | using Microsoft.Extensions.Logging; 6 | 7 | namespace KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks; 8 | 9 | /// 10 | /// Taken from: https://github.com/egil/Benchmark.Blazor/blob/main/Rendering/BenchmarkRenderer.cs 11 | /// 12 | #pragma warning disable BL0006 // Do not use RenderTree types 13 | internal class BenchmarkRenderer : Renderer 14 | { 15 | private readonly List rootComponentIds = new(); 16 | 17 | /// 18 | public override Dispatcher Dispatcher { get; } = Dispatcher.CreateDefault(); 19 | 20 | /// 21 | /// Any unhandled exceptions thrown by the Blazor Renderer after 22 | /// a call to or 23 | /// . 24 | /// 25 | /// 26 | /// This is reset after each call to or 27 | /// . 28 | /// 29 | public Exception? UnhandledException { get; private set; } 30 | 31 | /// 32 | /// The number of times the render tree has been undated, e.g. 33 | /// when a render cycle has happened (the ) 34 | /// has been called. 35 | /// 36 | public int RenderCount { get; private set; } 37 | 38 | /// 39 | /// Create an instance of the . This is a minimal 40 | /// that just allows the rendering of a component. 41 | /// 42 | /// 43 | /// An optional that can be used to inject 44 | /// services into the component being rendered. 45 | /// Default is an empty . 46 | /// 47 | /// 48 | /// An optional that will collect logs from the . 49 | /// Default is . 50 | /// 51 | public BenchmarkRenderer(IServiceProvider? serviceProvider = null, ILoggerFactory? loggerFactory = null) 52 | : base(serviceProvider ?? new ServiceCollection().BuildServiceProvider(), loggerFactory ?? NullLoggerFactory.Instance) 53 | { 54 | } 55 | 56 | /// 57 | /// Renders a component of type with the 58 | /// provided . 59 | /// 60 | /// 61 | /// Any unhandled exceptions during the first render is captured in the 62 | /// property. 63 | /// 64 | /// The type of the component to render. 65 | /// 66 | /// The parameters to pass to the during 67 | /// first render. Use to pass no parameters. 68 | /// The instance of the . 69 | public Task> RenderAsync(ParameterView parameters) 70 | where TComponent : IComponent 71 | { 72 | UnhandledException = null; 73 | 74 | var result = Dispatcher.InvokeAsync(async () => 75 | { 76 | var component = (TComponent)InstantiateComponent(typeof(TComponent)); 77 | var componentId = AssignRootComponentId(component); 78 | rootComponentIds.Add(componentId); 79 | await RenderRootComponentAsync(componentId, parameters).ConfigureAwait(false); 80 | return new RenderedComponent(component, componentId, this); 81 | }); 82 | 83 | return result; 84 | } 85 | 86 | /// 87 | /// Remove all component from the render tree(s) and clean up resources 88 | /// allocated to them in the . 89 | /// 90 | /// This also calls the and/or 91 | /// methods, if it 92 | /// components implements either of those interfaces. 93 | /// 94 | public void RemoveComponents() 95 | { 96 | Dispatcher.InvokeAsync(() => 97 | { 98 | foreach (var componentId in rootComponentIds) 99 | { 100 | RemoveRootComponent(componentId); 101 | } 102 | }); 103 | 104 | rootComponentIds.Clear(); 105 | } 106 | 107 | internal void RemoveComponent(int componentId) 108 | { 109 | Dispatcher.InvokeAsync(() => RemoveRootComponent(componentId)); 110 | } 111 | 112 | protected override void HandleException(Exception exception) 113 | => UnhandledException = exception; 114 | 115 | protected override Task UpdateDisplayAsync(in RenderBatch renderBatch) 116 | { 117 | // This is called after every render and 118 | // contains the changes/updates to the render tree. 119 | RenderCount++; 120 | return Task.CompletedTask; 121 | } 122 | } 123 | #pragma warning restore BL0006 // Do not use RenderTree types -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks/Benchmarks/JsonConstants.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks.Benchmarks; 8 | 9 | public class JsonConstants 10 | { 11 | public const string imageNote = """ 12 | { 13 | "attachment": { 14 | "url": "https://media.hachyderm.io/media_attachments/files/109/653/814/247/186/480/original/8c051dcca0e0b60a.png", 15 | "type": "Document", 16 | "mediaType": "image/png", 17 | "blurhash": "UbB2R9t7wUWBn.jsfifQwBWBfgoeoOa|a_j[", 18 | "width": 1220, 19 | "height": 1058 20 | }, 21 | "attributedTo": { 22 | "outbox": "https://hachyderm.io/users/KristofferStrube/outbox", 23 | "inbox": "https://hachyderm.io/users/KristofferStrube/inbox", 24 | "followers": "https://hachyderm.io/users/KristofferStrube/followers", 25 | "following": "https://hachyderm.io/users/KristofferStrube/following", 26 | "preferredUsername": "KristofferStrube", 27 | "endpoints": { 28 | "sharedInbox": "https://hachyderm.io/inbox" 29 | }, 30 | "attachment": [ 31 | { 32 | "type": [ 33 | "PropertyValue", 34 | "Object" 35 | ], 36 | "name": "Website", 37 | "value": "https://kristoffer-strube.dk" 38 | }, 39 | { 40 | "type": [ 41 | "PropertyValue", 42 | "Object" 43 | ], 44 | "name": "GitHub", 45 | "value": "https://github.com/KristofferStrube" 46 | } 47 | ], 48 | "icon": { 49 | "url": "https://media.hachyderm.io/accounts/avatars/109/364/675/065/868/952/original/8b34316439e5e2ef.png", 50 | "type": "Image", 51 | "mediaType": "image/png" 52 | }, 53 | "image": { 54 | "url": "https://media.hachyderm.io/accounts/headers/109/364/675/065/868/952/original/8875a598d5103901.jpg", 55 | "type": "Image", 56 | "mediaType": "image/jpeg" 57 | }, 58 | "tag": [ 59 | 60 | ], 61 | "url": "https://hachyderm.io/@KristofferStrube", 62 | "published": "2022-11-18T00:00:00Z", 63 | "summary": "

.NET developer, Comp.-Sci. MSc., and Blazor enthusiast.

", 64 | "@context": [ 65 | "https://www.w3.org/ns/activitystreams", 66 | "https://w3id.org/security/v1", 67 | { 68 | 69 | } 70 | ], 71 | "id": "https://hachyderm.io/users/KristofferStrube", 72 | "type": "Person", 73 | "name": "Kristoffer Strube", 74 | "featured": "https://hachyderm.io/users/KristofferStrube/collections/featured", 75 | "featuredTags": "https://hachyderm.io/users/KristofferStrube/collections/tags", 76 | "manuallyApprovesFollowers": false, 77 | "discoverable": true, 78 | "devices": "https://hachyderm.io/users/KristofferStrube/collections/devices", 79 | "publicKey": { 80 | "id": "https://hachyderm.io/users/KristofferStrube#main-key", 81 | "owner": "https://hachyderm.io/users/KristofferStrube", 82 | "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyhLtxhQyI3tohkFJfdZS\n2T3fgfdVKhmZr3wMeYtmJLQZ01RZMMEBulKXpXiqNfvGPpiOnSFQEMJplqt8albx\nN8o529on9T5V7TKe23HDib0w0vVumw5R6Jv2JZaR6pMRnm93keAUR8K1+zcsAeYr\n/TwzWLNwXMB+e8vwMp5yvW4h3S1rauXQZeStOEiQ4joBEB/X3EKhjW+doz/KgcIl\n8cXN/J6BN8EGY6GFUESEZeMOrxayOE13MHKeauQ8EL/94n9n9gbSZBNym4i6gW8w\nMDfBtChokcV6JxLkbDE769FmleCbibCtYiYGTplhyDu4IVOr7zU6nGBhIw6FkFDv\n4QIDAQAB\n-----END PUBLIC KEY-----\n" 83 | } 84 | }, 85 | "cc": "https://hachyderm.io/users/KristofferStrube/followers", 86 | "inReplyTo": "https://hachyderm.io/users/KristofferStrube/statuses/109653690759437526", 87 | "replies": { 88 | "first": { 89 | "partOf": "https://hachyderm.io/users/KristofferStrube/statuses/109653814740274431/replies", 90 | "next": "https://hachyderm.io/users/KristofferStrube/statuses/109653814740274431/replies?only_other_accounts=true&page=true", 91 | "items": [ 92 | 93 | ], 94 | "type": "CollectionPage" 95 | }, 96 | "id": "https://hachyderm.io/users/KristofferStrube/statuses/109653814740274431/replies", 97 | "type": "Collection" 98 | }, 99 | "tag": [ 100 | 101 | ], 102 | "to": "https://www.w3.org/ns/activitystreams#Public", 103 | "url": "https://hachyderm.io/@KristofferStrube/109653814740274431", 104 | "content": "

I'm getting some pretty nice results from this together with some other timers.

", 105 | "contentMap": { 106 | "en": "

I'm getting some pretty nice results from this together with some other timers.

" 107 | }, 108 | "published": "2023-01-08T13:27:09Z", 109 | "id": "https://hachyderm.io/users/KristofferStrube/statuses/109653814740274431", 110 | "type": "Note", 111 | "sensitive": false, 112 | "atomUri": "https://hachyderm.io/users/KristofferStrube/statuses/109653814740274431", 113 | "inReplyToAtomUri": "https://hachyderm.io/users/KristofferStrube/statuses/109653690759437526", 114 | "conversation": "tag:hachyderm.io,2023-01-08:objectId=17100601:objectType=Conversation" 115 | } 116 | """; 117 | 118 | public const string videoNote = """ 119 | { 120 | "attachment": { 121 | "url": "https://media.hachyderm.io/media_attachments/files/109/654/626/071/694/548/original/29d6bd160e3e07bf.mp4", 122 | "type": "Document", 123 | "name": "Searching through Mastodon posts in a Blazor application.", 124 | "mediaType": "video/mp4", 125 | "blurhash": "UnQT4N004n9FRjkCkBofWBj[fPj[offQWBju", 126 | "focalPoint": [ 127 | 0.0, 128 | 0.0 129 | ], 130 | "width": 1702, 131 | "height": 958 132 | }, 133 | "attributedTo": { 134 | "outbox": "https://hachyderm.io/users/KristofferStrube/outbox", 135 | "inbox": "https://hachyderm.io/users/KristofferStrube/inbox", 136 | "followers": "https://hachyderm.io/users/KristofferStrube/followers", 137 | "following": "https://hachyderm.io/users/KristofferStrube/following", 138 | "preferredUsername": "KristofferStrube", 139 | "endpoints": { 140 | "sharedInbox": "https://hachyderm.io/inbox" 141 | }, 142 | "attachment": [ 143 | { 144 | "type": [ 145 | "PropertyValue", 146 | "Object" 147 | ], 148 | "name": "Website", 149 | "value": "https://kristoffer-strube.dk" 150 | }, 151 | { 152 | "type": [ 153 | "PropertyValue", 154 | "Object" 155 | ], 156 | "name": "GitHub", 157 | "value": "https://github.com/KristofferStrube" 158 | } 159 | ], 160 | "icon": { 161 | "url": "https://media.hachyderm.io/accounts/avatars/109/364/675/065/868/952/original/8b34316439e5e2ef.png", 162 | "type": "Image", 163 | "mediaType": "image/png" 164 | }, 165 | "image": { 166 | "url": "https://media.hachyderm.io/accounts/headers/109/364/675/065/868/952/original/8875a598d5103901.jpg", 167 | "type": "Image", 168 | "mediaType": "image/jpeg" 169 | }, 170 | "tag": [ 171 | 172 | ], 173 | "url": "https://hachyderm.io/@KristofferStrube", 174 | "published": "2022-11-18T00:00:00Z", 175 | "summary": "

.NET developer, Comp.-Sci. MSc., and Blazor enthusiast.

", 176 | "@context": [ 177 | "https://www.w3.org/ns/activitystreams", 178 | "https://w3id.org/security/v1", 179 | { 180 | 181 | } 182 | ], 183 | "id": "https://hachyderm.io/users/KristofferStrube", 184 | "type": "Person", 185 | "name": "Kristoffer Strube", 186 | "featured": "https://hachyderm.io/users/KristofferStrube/collections/featured", 187 | "featuredTags": "https://hachyderm.io/users/KristofferStrube/collections/tags", 188 | "manuallyApprovesFollowers": false, 189 | "discoverable": true, 190 | "devices": "https://hachyderm.io/users/KristofferStrube/collections/devices", 191 | "publicKey": { 192 | "id": "https://hachyderm.io/users/KristofferStrube#main-key", 193 | "owner": "https://hachyderm.io/users/KristofferStrube", 194 | "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyhLtxhQyI3tohkFJfdZS\n2T3fgfdVKhmZr3wMeYtmJLQZ01RZMMEBulKXpXiqNfvGPpiOnSFQEMJplqt8albx\nN8o529on9T5V7TKe23HDib0w0vVumw5R6Jv2JZaR6pMRnm93keAUR8K1+zcsAeYr\n/TwzWLNwXMB+e8vwMp5yvW4h3S1rauXQZeStOEiQ4joBEB/X3EKhjW+doz/KgcIl\n8cXN/J6BN8EGY6GFUESEZeMOrxayOE13MHKeauQ8EL/94n9n9gbSZBNym4i6gW8w\nMDfBtChokcV6JxLkbDE769FmleCbibCtYiYGTplhyDu4IVOr7zU6nGBhIw6FkFDv\n4QIDAQAB\n-----END PUBLIC KEY-----\n" 195 | } 196 | }, 197 | "cc": "https://hachyderm.io/users/KristofferStrube/followers", 198 | "replies": { 199 | "first": { 200 | "partOf": "https://hachyderm.io/users/KristofferStrube/statuses/109654643609724194/replies", 201 | "next": "https://hachyderm.io/users/KristofferStrube/statuses/109654643609724194/replies?only_other_accounts=true&page=true", 202 | "items": [ 203 | 204 | ], 205 | "type": "CollectionPage" 206 | }, 207 | "id": "https://hachyderm.io/users/KristofferStrube/statuses/109654643609724194/replies", 208 | "type": "Collection" 209 | }, 210 | "tag": [ 211 | ], 212 | "to": "https://www.w3.org/ns/activitystreams#Public", 213 | "url": "https://hachyderm.io/@KristofferStrube/109654643609724194", 214 | "content": "

My weekend project has been another demo for my Blazor File System wrapper. With this demo I can search in posts from Mastodon and save the search trees used for searching in the Origin Private File System to spare rebuilding them on reloads.
Also got to use an old project which was the naive implementation of the search tree itself.
#blazor #dotnet #csharp #search #filesystemapi #activitystreams #activitypub
Project: https://github.com/KristofferStrube/Blazor.FileSystem
Demo: https://kristofferstrube.github.io/Blazor.FileSystem/SearchMastodon

", 215 | "contentMap": { 216 | "en": "

My weekend project has been another demo for my Blazor File System wrapper. With this demo I can search in posts from Mastodon and save the search trees used for searching in the Origin Private File System to spare rebuilding them on reloads.
Also got to use an old project which was the naive implementation of the search tree itself.
#blazor #dotnet #csharp #search #filesystemapi #activitystreams #activitypub
Project: https://github.com/KristofferStrube/Blazor.FileSystem
Demo: https://kristofferstrube.github.io/Blazor.FileSystem/SearchMastodon

" 217 | }, 218 | "published": "2023-01-08T16:57:56Z", 219 | "id": "https://hachyderm.io/users/KristofferStrube/statuses/109654643609724194", 220 | "type": "Note", 221 | "sensitive": false, 222 | "atomUri": "https://hachyderm.io/users/KristofferStrube/statuses/109654643609724194", 223 | "inReplyToAtomUri": null, 224 | "conversation": "tag:hachyderm.io,2023-01-08:objectId=17150450:objectType=Conversation" 225 | } 226 | """; 227 | 228 | public const string onlyContentNote = """ 229 | { 230 | "attachment": [ 231 | 232 | ], 233 | "attributedTo": { 234 | "outbox": "https://hachyderm.io/users/KristofferStrube/outbox", 235 | "inbox": "https://hachyderm.io/users/KristofferStrube/inbox", 236 | "followers": "https://hachyderm.io/users/KristofferStrube/followers", 237 | "following": "https://hachyderm.io/users/KristofferStrube/following", 238 | "preferredUsername": "KristofferStrube", 239 | "endpoints": { 240 | "sharedInbox": "https://hachyderm.io/inbox" 241 | }, 242 | "attachment": [ 243 | { 244 | "type": [ 245 | "PropertyValue", 246 | "Object" 247 | ], 248 | "name": "Website", 249 | "value": "https://kristoffer-strube.dk" 250 | }, 251 | { 252 | "type": [ 253 | "PropertyValue", 254 | "Object" 255 | ], 256 | "name": "GitHub", 257 | "value": "https://github.com/KristofferStrube" 258 | } 259 | ], 260 | "icon": { 261 | "url": "https://media.hachyderm.io/accounts/avatars/109/364/675/065/868/952/original/8b34316439e5e2ef.png", 262 | "type": "Image", 263 | "mediaType": "image/png" 264 | }, 265 | "image": { 266 | "url": "https://media.hachyderm.io/accounts/headers/109/364/675/065/868/952/original/8875a598d5103901.jpg", 267 | "type": "Image", 268 | "mediaType": "image/jpeg" 269 | }, 270 | "tag": [ 271 | 272 | ], 273 | "url": "https://hachyderm.io/@KristofferStrube", 274 | "published": "2022-11-18T00:00:00Z", 275 | "summary": "

.NET developer, Comp.-Sci. MSc., and Blazor enthusiast.

", 276 | "@context": [ 277 | "https://www.w3.org/ns/activitystreams", 278 | "https://w3id.org/security/v1", 279 | { 280 | 281 | } 282 | ], 283 | "id": "https://hachyderm.io/users/KristofferStrube", 284 | "type": "Person", 285 | "name": "Kristoffer Strube", 286 | "featured": "https://hachyderm.io/users/KristofferStrube/collections/featured", 287 | "featuredTags": "https://hachyderm.io/users/KristofferStrube/collections/tags", 288 | "manuallyApprovesFollowers": false, 289 | "discoverable": true, 290 | "devices": "https://hachyderm.io/users/KristofferStrube/collections/devices", 291 | "publicKey": { 292 | "id": "https://hachyderm.io/users/KristofferStrube#main-key", 293 | "owner": "https://hachyderm.io/users/KristofferStrube", 294 | "publicKeyPem": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyhLtxhQyI3tohkFJfdZS\n2T3fgfdVKhmZr3wMeYtmJLQZ01RZMMEBulKXpXiqNfvGPpiOnSFQEMJplqt8albx\nN8o529on9T5V7TKe23HDib0w0vVumw5R6Jv2JZaR6pMRnm93keAUR8K1+zcsAeYr\n/TwzWLNwXMB+e8vwMp5yvW4h3S1rauXQZeStOEiQ4joBEB/X3EKhjW+doz/KgcIl\n8cXN/J6BN8EGY6GFUESEZeMOrxayOE13MHKeauQ8EL/94n9n9gbSZBNym4i6gW8w\nMDfBtChokcV6JxLkbDE769FmleCbibCtYiYGTplhyDu4IVOr7zU6nGBhIw6FkFDv\n4QIDAQAB\n-----END PUBLIC KEY-----\n" 295 | } 296 | }, 297 | "cc": [ 298 | "https://www.w3.org/ns/activitystreams#Public", 299 | "https://hachyderm.io/users/Martindotnet" 300 | ], 301 | "inReplyTo": "https://hachyderm.io/users/Martindotnet/statuses/109653770131293781", 302 | "replies": { 303 | "first": { 304 | "partOf": "https://hachyderm.io/users/KristofferStrube/statuses/109653812419954691/replies", 305 | "next": "https://hachyderm.io/users/KristofferStrube/statuses/109653812419954691/replies?only_other_accounts=true&page=true", 306 | "items": [ 307 | 308 | ], 309 | "type": "CollectionPage" 310 | }, 311 | "id": "https://hachyderm.io/users/KristofferStrube/statuses/109653812419954691/replies", 312 | "type": "Collection" 313 | }, 314 | "tag": { 315 | "href": "https://hachyderm.io/users/Martindotnet", 316 | "type": "Mention", 317 | "name": "@Martindotnet" 318 | }, 319 | "to": "https://hachyderm.io/users/KristofferStrube/followers", 320 | "url": "https://hachyderm.io/@KristofferStrube/109653812419954691", 321 | "content": "

@Martindotnet Awesome!

", 322 | "contentMap": { 323 | "en": "

@Martindotnet Awesome!

" 324 | }, 325 | "published": "2023-01-08T13:26:33Z", 326 | "id": "https://hachyderm.io/users/KristofferStrube/statuses/109653812419954691", 327 | "type": "Note", 328 | "sensitive": false, 329 | "atomUri": "https://hachyderm.io/users/KristofferStrube/statuses/109653812419954691", 330 | "inReplyToAtomUri": "https://hachyderm.io/users/Martindotnet/statuses/109653770131293781", 331 | "conversation": "tag:hachyderm.io,2023-01-08:objectId=17100601:objectType=Conversation" 332 | } 333 | """; 334 | } 335 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks/Benchmarks/NodePresenterBenchmark.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Attributes; 2 | using KristofferStrube.ActivityStreams; 3 | using KristofferStrube.Blazor.FileSystem.WasmExample.Search; 4 | using KristofferStrube.Blazor.FileSystem.WasmExample.Shared; 5 | using Microsoft.AspNetCore.Components; 6 | using Microsoft.Extensions.DependencyInjection; 7 | using static System.Text.Json.JsonSerializer; 8 | 9 | namespace KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks.Benchmarks; 10 | 11 | public class NodePresenterBenchmark 12 | { 13 | private BenchmarkRenderer renderer = default!; 14 | 15 | private Note videoNote = null!; 16 | private Note imageNote = null!; 17 | private Note onlyContentNote = null!; 18 | 19 | [GlobalSetup] 20 | public void GlobalSetup() 21 | { 22 | var services = new ServiceCollection(); 23 | 24 | // Add services to inject into components 25 | // rendered with the renderer here, e.g.: 26 | // services.AddSingleton(); 27 | 28 | renderer = new BenchmarkRenderer(services.BuildServiceProvider()); 29 | 30 | imageNote = Deserialize(JsonConstants.imageNote)!; 31 | videoNote = Deserialize(JsonConstants.videoNote)!; 32 | onlyContentNote = Deserialize(JsonConstants.onlyContentNote)!; 33 | } 34 | 35 | [GlobalCleanup] 36 | #pragma warning disable BL0006 // Do not use RenderTree types 37 | public void GlobalCleanup() => renderer.Dispose(); 38 | #pragma warning restore BL0006 // Do not use RenderTree types 39 | 40 | [Benchmark] 41 | public async Task RenderImageNote() 42 | { 43 | // Render a component 44 | var parameters = new Dictionary() { { "Note", imageNote } }; 45 | var component = await renderer.RenderAsync(ParameterView.FromDictionary(parameters)); 46 | 47 | // Remove the component again from the render tree. Stops the 48 | // renderer from tracking the component. 49 | component.RemoveComponent(); 50 | 51 | return renderer.RenderCount; 52 | } 53 | 54 | [Benchmark] 55 | public async Task RenderVideoNote() 56 | { 57 | // Render a component 58 | var parameters = new Dictionary() { { "Note", videoNote } }; 59 | var component = await renderer.RenderAsync(ParameterView.FromDictionary(parameters)); 60 | 61 | // Remove the component again from the render tree. Stops the 62 | // renderer from tracking the component. 63 | component.RemoveComponent(); 64 | 65 | return renderer.RenderCount; 66 | } 67 | 68 | [Benchmark] 69 | public async Task RenderOnlyContentNote() 70 | { 71 | // Render a component 72 | var parameters = new Dictionary() { { "Note", onlyContentNote } }; 73 | var component = await renderer.RenderAsync(ParameterView.FromDictionary(parameters)); 74 | 75 | // Remove the component again from the render tree. Stops the 76 | // renderer from tracking the component. 77 | component.RemoveComponent(); 78 | 79 | return renderer.RenderCount; 80 | } 81 | } 82 | 83 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks/KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net7.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks/Program.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Running; 2 | 3 | BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks/RenderedComponent{T}.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Components; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem.WasmExample.Benchmarks; 4 | 5 | internal class RenderedComponent where TComponent : IComponent 6 | { 7 | private readonly int componentId; 8 | private readonly BenchmarkRenderer renderer; 9 | 10 | public TComponent Instance { get; } 11 | 12 | internal RenderedComponent(TComponent instance, int componentId, BenchmarkRenderer renderer) 13 | { 14 | Instance = instance; 15 | this.componentId = componentId; 16 | this.renderer = renderer; 17 | } 18 | 19 | /// 20 | /// Pass the provided to the component. 21 | /// For normal components that inherit from this causes 22 | /// the component to go through all its life cycle methods. 23 | /// 24 | /// The parameters to pass to the component. Use to pass no parameters and just trigger a re-render. 25 | /// A task that completes when the 26 | /// method completes. 27 | public Task SetParametersAsync(ParameterView parameters) 28 | => renderer.Dispatcher.InvokeAsync(() => 29 | { 30 | return Instance.SetParametersAsync(parameters).ConfigureAwait(false); 31 | }); 32 | 33 | /// 34 | /// Remove the component from the render tree and clean up resources 35 | /// allocated to it in the . This 36 | /// also calls the and/or 37 | /// methods, if it 38 | /// implements either of those interfaces. 39 | /// 40 | public void RemoveComponent() 41 | { 42 | renderer.RemoveComponent(componentId); 43 | } 44 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/App.razor: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | Not found 8 | 9 |

Sorry, there's nothing at this address.

10 |
11 |
12 |
13 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/KristofferStrube.Blazor.FileSystem.WasmExample.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net7.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | true 26 | PreserveNewest 27 | 28 | 29 | true 30 | PreserveNewest 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Pages/DirectoryExplorer.razor: -------------------------------------------------------------------------------- 1 | @page "/DirectoryExplorer" 2 | @using static KristofferStrube.Blazor.FileSystem.WasmExample.Shared.ElementExplorer; 3 | 4 | @inject IStorageManagerServiceInProcess StorageManagerService 5 | 6 | File System - Directory 7 | 8 |

Directory Explorer

9 |

10 | In this sample we go through all directories and files in the Origin Private File System recursively and enable you to delete files and directories. 11 |

12 | 13 |
14 |
15 |
16 | 17 |
18 |
19 |
20 | @if (editFileHandle is not null) 21 | { 22 | 23 | } 24 |
25 |
26 | 27 | @code { 28 | string? text = null; 29 | FileSystemFileHandle? editFileHandle; 30 | IFileSystemHandleInProcess? OPFS; 31 | 32 | protected override async Task OnInitializedAsync() 33 | { 34 | OPFS = await StorageManagerService.GetOriginPrivateDirectoryAsync(); 35 | } 36 | 37 | async Task TextAreaChanged(ChangeEventArgs eventArgs) 38 | { 39 | if (editFileHandle is not null && eventArgs.Value is string value) 40 | { 41 | await using var writable = await editFileHandle.CreateWritableAsync(); 42 | await writable.WriteAsync(value); 43 | } 44 | } 45 | 46 | async Task Edit(FileSystemFileHandle fileHandle) 47 | { 48 | this.editFileHandle = fileHandle; 49 | var file = await fileHandle.GetFileAsync(); 50 | text = await file.TextAsync(); 51 | StateHasChanged(); 52 | } 53 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Pages/Index.razor: -------------------------------------------------------------------------------- 1 | @page "/" 2 | 3 | @inject IStorageManagerService StorageManagerService 4 | @inject NavigationManager NavigationManager 5 | 6 | File System - Minimal Viable Example 7 | 8 |

Minimal Viable Example

9 |

10 | Using the Blazor.FileSystem library we can handle and store references to files. 11 | The file handles can be supplied from multiple other APIs (like File System Access or Web App Launch Handler). 12 |

13 |

14 | Alternatively you can read, write, create, and delete files and folders in a sandboxed environment called the Origin Private File System which is made available through the StorageManagerService (or StorageManagerServiceInProcess for WASM) in this library. 15 |

16 |

17 | Below we see a sample of a file called file.txt that has been opened from your Origin Private File System. The file is local to this domain in your browser, but is persisted accross page loads. 18 | Try writing in the textarea and then reload this page. 19 |

20 | 21 | @if (text is not null) 22 | { 23 | 24 | } 25 | 26 | @code { 27 | string? text = null; 28 | FileSystemFileHandle? fileHandle; 29 | 30 | protected override async Task OnInitializedAsync() 31 | { 32 | var directoryHandle = await StorageManagerService.GetOriginPrivateDirectoryAsync(); 33 | fileHandle = await directoryHandle.GetFileHandleAsync("file.txt", new() { Create = true }); 34 | var file = await fileHandle.GetFileAsync(); 35 | text = await file.TextAsync(); 36 | } 37 | 38 | async Task TextAreaChanged(ChangeEventArgs eventArgs) 39 | { 40 | if (fileHandle is not null && eventArgs.Value is string value) 41 | { 42 | var writable = await fileHandle.CreateWritableAsync(); 43 | await writable.WriteAsync(value); 44 | await writable.CloseAsync(); 45 | } 46 | } 47 | 48 | void Reload() 49 | { 50 | NavigationManager.NavigateTo("./", true); 51 | } 52 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Pages/SearchMastodon.razor: -------------------------------------------------------------------------------- 1 | @page "/SearchMastodon" 2 | 3 | @using KristofferStrube.ActivityStreams; 4 | @using KristofferStrube.Blazor.FileSystem.WasmExample.Search; 5 | @using static System.Text.Json.JsonSerializer; 6 | @using System.Reactive.Linq; 7 | @using System.Reactive.Subjects; 8 | @using System.Diagnostics; 9 | 10 | @inject IStorageManagerService StorageManagerService 11 | @inject NavigationManager NavigationManager 12 | @inject HttpClient HttpClient 13 | 14 | File System - Search Mastodon 15 | 16 |

Search Mastodon

17 |

18 | This sample page uses Blazor.FileSystem together with KristofferStrube/ActivityStream to load a Mastodon user's posts, create search trees of their content, and store these search trees in the Origin Private File System so that they can be re-used on reloads or recurring searches. 19 |

20 | @if (OriginPrivateDirectoryHandle is null) 21 | { 22 |

23 | The File System API is only supported on few browsers, but most major vendors have committed to support it in the near future. So you might need to install alpha/beta release of your browser for this to work. This demo will run without using it in this case as your browser does not support it. 😢 24 |

25 | } 26 |

27 | You can make full text searches in my blog posts which I also expose through my private ActivityStreams bot (AcitivityPubBotDotNet) once they have been downloaded. You can also download the posts of another user by typing in their identifier. It downloads these posts and check in the file system if we have already created a suffix search tree for the post and uses that instead of creating a new one if available. The suffix tree can do a fuzzy search efficiently which allows small errors in the written search query. 28 |

29 | 30 |
31 | 32 | 🐘 33 |
34 |
35 |
36 | @if (profileFeedback is string feedback) 37 | { 38 | @feedback 39 | } 40 | 41 | @if (downloading) 42 | { 43 | 44 | } 45 | 46 |
47 |
48 | @if (profileFeedback is null) 49 | { 50 |
51 |
Loaded (@suffixTrees.Count()/@notes.Length) Notes
52 |
53 |
54 | 55 | 🔍 56 |
57 | 58 | @if (results.Count() > 0 && results.First().Matches.Length > 0) 59 | { 60 |
61 |
62 | 63 | Found @results.Count() results 64 | 65 | @if (results.Count() > 10) 66 | { 67 | (only showing 10) 68 | } 69 | @if (resultTime is long time) 70 | { 71 | in @time (ms) 72 | } 73 | 74 | (@results.Count(result => result.Matches.Any(match => !match.Cigar.Contains('I') && !match.Cigar.Contains('D') && !match.Cigar.Contains('Q'))) were perfect matches) 75 | 76 |
77 |
78 | } 79 | } 80 | 81 | @foreach (var result in results.Take(10)) 82 | { 83 | var note = notes.Single(note => note.Id == result.Resource); 84 | 85 | } 86 | 87 | @code { 88 | string profile = "@bot@kristoffer-strube.dk"; 89 | string search = ""; 90 | string? profileFeedback; 91 | FileSystemDirectoryHandle? OriginPrivateDirectoryHandle; 92 | IObject[] notes = Array.Empty(); 93 | List<(string Resource, SamLine[] Matches)> results = new(); 94 | Dictionary suffixTrees = new(); 95 | CancellationTokenSource downloadCancellationSource = new CancellationTokenSource(); 96 | CancellationTokenSource searchCancellationSource = new CancellationTokenSource(); 97 | long? resultTime = null; 98 | bool downloading = false; 99 | 100 | Stopwatch renderWatch = Stopwatch.StartNew(); 101 | 102 | protected override async Task OnInitializedAsync() 103 | { 104 | try 105 | { 106 | OriginPrivateDirectoryHandle = await StorageManagerService.GetOriginPrivateDirectoryAsync(); 107 | } 108 | catch 109 | { 110 | OriginPrivateDirectoryHandle = null; 111 | } 112 | } 113 | 114 | protected override bool ShouldRender() 115 | { 116 | var should = base.ShouldRender(); 117 | if (should) 118 | { 119 | renderWatch = Stopwatch.StartNew(); 120 | } 121 | return should; 122 | } 123 | 124 | protected override async Task OnAfterRenderAsync(bool firstRender) 125 | { 126 | renderWatch.Stop(); 127 | Console.WriteLine($"Took {renderWatch.ElapsedMilliseconds} (ms) to render."); 128 | 129 | if (!firstRender) return; 130 | 131 | await DownloadNewestPostsAsync(profile); 132 | } 133 | 134 | protected async Task DownloadNewestPostsAsync(string profile) 135 | { 136 | searchCancellationSource.Cancel(); 137 | searchCancellationSource = new CancellationTokenSource(); 138 | var searchCancellationToken = searchCancellationSource.Token; 139 | 140 | results = new(); 141 | notes = Array.Empty(); 142 | suffixTrees = new(); 143 | downloading = false; 144 | search = ""; 145 | 146 | if (string.IsNullOrWhiteSpace(profile)) 147 | { 148 | await Task.CompletedTask; 149 | profileFeedback = ""; 150 | StateHasChanged(); 151 | return; 152 | } 153 | 154 | Console.WriteLine("Started download."); 155 | downloading = true; 156 | HttpResponseMessage? outboxResponse = null; 157 | 158 | try 159 | { 160 | outboxResponse = await HttpClient.GetAsync($"https://kristoffer-strube.dk/API/mastodon/Outbox/{profile}", searchCancellationToken)!; 161 | downloading = false; 162 | } 163 | catch 164 | { 165 | profileFeedback = "Could not reach domain."; 166 | downloading = false; 167 | await Task.CompletedTask; 168 | return; 169 | } 170 | 171 | if (!outboxResponse?.IsSuccessStatusCode is true) 172 | { 173 | profileFeedback = await outboxResponse!.Content.ReadFromJsonAsync(cancellationToken: searchCancellationToken); 174 | profileFeedback ??= "Could not reach domain."; 175 | await Task.CompletedTask; 176 | return; 177 | } 178 | 179 | StateHasChanged(); 180 | 181 | Console.WriteLine("Finished download."); 182 | 183 | var outbox = await outboxResponse!.Content.ReadFromJsonAsync(cancellationToken: searchCancellationToken); 184 | // We have to check the response. 185 | 186 | if (outbox is not IObjectOrLink[] outboxObjects) 187 | { 188 | profileFeedback = "Server Error occured."; 189 | await Task.CompletedTask; 190 | return; 191 | } 192 | 193 | notes = outboxObjects 194 | .Where(item => item is Create create && create.Object.Count() > 0 && create.Object.First() is IObject) 195 | .Select(item => (IObject)((Create)item).Object.First()!) 196 | .ToArray(); 197 | 198 | profileFeedback = null; 199 | 200 | StateHasChanged(); 201 | 202 | foreach (IObject note in notes) 203 | { 204 | StateHasChanged(); 205 | await Task.Delay(1); 206 | if (searchCancellationToken.IsCancellationRequested) 207 | { 208 | Console.WriteLine($"Canceled indexing progress ({notes.ToList().IndexOf(note)}/{notes.Count()})"); 209 | await Task.FromCanceled(searchCancellationToken); 210 | return; 211 | } 212 | if (suffixTrees.ContainsKey(note.Id)) 213 | { 214 | continue; 215 | } 216 | 217 | if (OriginPrivateDirectoryHandle is not null) 218 | { 219 | // Calculate hash of note content. 220 | using System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography.SHA1.Create(); 221 | byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(note.Content.First()); 222 | byte[] hashBytes = sha1.ComputeHash(inputBytes); 223 | var fileName = Convert.ToHexString(hashBytes) + ".msgpack.json"; 224 | 225 | // Check if we have suffix tree for the note in 226 | var mastodonDirectory = await OriginPrivateDirectoryHandle.GetDirectoryHandleAsync("MastodonSearchIndexes", new() { Create = true }); 227 | var profileDirectory = await mastodonDirectory.GetDirectoryHandleAsync(profile.Split('@')[1].ToLower(), new() { Create = true }); 228 | var fileHandle = await profileDirectory.GetFileHandleAsync(fileName, new() { Create = true }); 229 | var file = await fileHandle.GetFileAsync(); 230 | if (await file.GetSizeAsync() > 0) 231 | { 232 | suffixTrees.Add(note.Id, MessagePack.MessagePackSerializer.Deserialize(await file.ArrayBufferAsync())!); 233 | Console.WriteLine("We hit something we had already built."); 234 | continue; 235 | } 236 | 237 | // Create Suffix Tree. 238 | var suffixTree = new NaiveSuffixTree(note.Content.First().ToLower()); 239 | 240 | // Setup file. 241 | var writer = await fileHandle.CreateWritableAsync(new() { KeepExistingData = false }); 242 | 243 | // Write Suffix Tree. 244 | await writer.WriteAsync(MessagePack.MessagePackSerializer.Serialize(suffixTree)); 245 | await writer.CloseAsync(); 246 | suffixTrees.Add(note.Id, suffixTree); 247 | } 248 | else 249 | { 250 | // Create Suffix Tree. 251 | var suffixTree = new NaiveSuffixTree(note.Content.First().ToLower()); 252 | suffixTrees.Add(note.Id, suffixTree); 253 | } 254 | 255 | Console.WriteLine("We hit something new."); 256 | } 257 | 258 | Console.WriteLine("Finished building trees."); 259 | 260 | if (searchCancellationToken.IsCancellationRequested) 261 | { 262 | await Task.FromCanceled(searchCancellationToken); 263 | return; 264 | } 265 | 266 | await SearchAsync(search); 267 | StateHasChanged(); 268 | 269 | Console.WriteLine("Finished search."); 270 | } 271 | 272 | protected async Task SearchAsync(string search) 273 | { 274 | searchCancellationSource.Cancel(); 275 | searchCancellationSource = new CancellationTokenSource(); 276 | var searchCancellationToken = searchCancellationSource.Token; 277 | 278 | var stopwatch = Stopwatch.StartNew(); 279 | 280 | var newResults = new List<(string Resource, SamLine[] Matches)>(suffixTrees.Count()); 281 | 282 | if (string.IsNullOrWhiteSpace(search)) 283 | { 284 | foreach (var suffixTreeKey in suffixTrees.Keys) 285 | { 286 | newResults.Add((suffixTreeKey, Array.Empty())); 287 | if (searchCancellationToken.IsCancellationRequested) 288 | { 289 | await Task.FromCanceled(searchCancellationToken); 290 | return; 291 | } 292 | } 293 | results = newResults; 294 | stopwatch.Stop(); 295 | resultTime = null; 296 | Console.WriteLine($"Took {stopwatch.ElapsedMilliseconds} (ms) to search for \"{search}\""); 297 | await Task.CompletedTask; 298 | return; 299 | } 300 | 301 | foreach (var suffixTree in suffixTrees) 302 | { 303 | await Task.Delay(1); 304 | if (searchCancellationToken.IsCancellationRequested) 305 | { 306 | Console.WriteLine($"Canceled search progress ({suffixTrees.ToList().IndexOf(suffixTree)}/{suffixTrees.Count()}) for \"{search}\""); 307 | await Task.FromCanceled(searchCancellationToken); 308 | return; 309 | } 310 | var searchResult = suffixTree.Value.SearchForAllApproximateOccurences(suffixTree.Key, "simple", search.ToLower(), 1).Reverse().ToArray(); 311 | if (searchResult.Length > 0) 312 | { 313 | newResults.Add((Resource: suffixTree.Key, Matches: searchResult)); 314 | } 315 | } 316 | results = newResults 317 | .OrderByDescending(result => result.Matches.Any(match => !match.Cigar.Contains('I') && !match.Cigar.Contains('D') && !match.Cigar.Contains('Q'))) 318 | .ThenByDescending(result => result.Matches.Length) 319 | .ToList(); 320 | 321 | stopwatch.Stop(); 322 | resultTime = stopwatch.ElapsedMilliseconds; 323 | Console.WriteLine($"Took {resultTime} (ms) to search for \"{search}\""); 324 | } 325 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Pages/Status.razor: -------------------------------------------------------------------------------- 1 | @page "/Status" 2 | 3 | @using HtmlAgilityPack; 4 | 5 | @inject HttpClient HttpClient 6 | @inject IJSRuntime JSRuntime 7 | 8 | File System - Status 9 | 10 | @if (compareText is not null) 11 | { 12 |

 13 |             @((MarkupString)compareText)
 14 |     
15 | } 16 | else 17 | { 18 | Loading WebIDL from specs ... 19 | } 20 | 21 | @code { 22 | private string? compareText; 23 | 24 | protected override async Task OnAfterRenderAsync(bool firstRender) 25 | { 26 | if (firstRender) 27 | { 28 | var domString = await HttpClient.GetStringAsync("https://fs.spec.whatwg.org/#idl-index"); 29 | 30 | var dom = new HtmlDocument(); 31 | dom.LoadHtml(domString); 32 | var idlIndexHeader = dom.GetElementbyId("idl-index"); 33 | var webIDLNode = idlIndexHeader.NextSibling.NextSibling; 34 | var webIDLText = webIDLNode.InnerText; 35 | // We normalize to indent with 4 spaces as that is inconsistent in the current WebIDL specs. 36 | var fetchedLines = webIDLText.Replace(" ", " ").Replace("\n ", "\n ").Split('\n'); 37 | var supportedLines = currentlySupportedWebIDL.Replace("<", "<").Split('\n'); 38 | var compareLines = new List(); 39 | var fetchedIndex = 0; 40 | var supportedIndex = 0; 41 | while (fetchedIndex < fetchedLines.Length || supportedIndex < supportedLines.Length) 42 | { 43 | var color = "pink"; 44 | if (fetchedIndex == fetchedLines.Length) 45 | { 46 | color = "cyan"; 47 | supportedIndex++; 48 | fetchedIndex--; 49 | } 50 | else if (supportedIndex == supportedLines.Length) 51 | { 52 | color = "lemonchiffon"; 53 | } 54 | else if (fetchedLines[fetchedIndex].Trim() == supportedLines[supportedIndex].Trim()) 55 | { 56 | color = "lightgreen"; 57 | supportedIndex++; 58 | } 59 | compareLines.Add($"""{fetchedLines[fetchedIndex++]}"""); 60 | } 61 | compareText = string.Join("", compareLines); 62 | StateHasChanged(); 63 | } 64 | } 65 | 66 | private const string currentlySupportedWebIDL = 67 | @"enum FileSystemHandleKind { 68 | ""file"", 69 | ""directory"", 70 | }; 71 | 72 | [Exposed=(Window,Worker), SecureContext, Serializable] 73 | interface FileSystemHandle { 74 | readonly attribute FileSystemHandleKind kind; 75 | readonly attribute USVString name; 76 | 77 | Promise isSameEntry(FileSystemHandle other); 78 | }; 79 | 80 | dictionary FileSystemCreateWritableOptions { 81 | boolean keepExistingData = false; 82 | }; 83 | 84 | [Exposed=(Window,Worker), SecureContext, Serializable] 85 | interface FileSystemFileHandle : FileSystemHandle { 86 | Promise getFile(); 87 | Promise createWritable(optional FileSystemCreateWritableOptions options = {}); 88 | [Exposed=DedicatedWorker] 89 | Promise createSyncAccessHandle(); 90 | }; 91 | 92 | dictionary FileSystemGetFileOptions { 93 | boolean create = false; 94 | }; 95 | 96 | dictionary FileSystemGetDirectoryOptions { 97 | boolean create = false; 98 | }; 99 | 100 | dictionary FileSystemRemoveOptions { 101 | boolean recursive = false; 102 | }; 103 | 104 | [Exposed=(Window,Worker), SecureContext, Serializable] 105 | interface FileSystemDirectoryHandle : FileSystemHandle { 106 | async iterable; 107 | 108 | Promise getFileHandle(USVString name, optional FileSystemGetFileOptions options = {}); 109 | Promise getDirectoryHandle(USVString name, optional FileSystemGetDirectoryOptions options = {}); 110 | 111 | Promise removeEntry(USVString name, optional FileSystemRemoveOptions options = {}); 112 | 113 | Promise?> resolve(FileSystemHandle possibleDescendant); 114 | }; 115 | 116 | enum WriteCommandType { 117 | ""write"", 118 | ""seek"", 119 | ""truncate"", 120 | }; 121 | 122 | dictionary WriteParams { 123 | required WriteCommandType type; 124 | unsigned long long? size; 125 | unsigned long long? position; 126 | (BufferSource or Blob or USVString)? data; 127 | }; 128 | 129 | typedef (BufferSource or Blob or USVString or WriteParams) FileSystemWriteChunkType; 130 | 131 | [Exposed=(Window,Worker), SecureContext] 132 | interface FileSystemWritableFileStream : WritableStream { 133 | Promise write(FileSystemWriteChunkType data); 134 | Promise seek(unsigned long long position); 135 | Promise truncate(unsigned long long size); 136 | }; 137 | 138 | [SecureContext] 139 | partial interface StorageManager { 140 | Promise getDirectory(); 141 | };"; 142 | 143 | } 144 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Components.Web; 2 | using Microsoft.AspNetCore.Components.WebAssembly.Hosting; 3 | using KristofferStrube.Blazor.FileSystem; 4 | using KristofferStrube.Blazor.FileSystem.WasmExample; 5 | using KristofferStrube.Blazor.FileAPI; 6 | using TG.Blazor.IndexedDB; 7 | 8 | var builder = WebAssemblyHostBuilder.CreateDefault(args); 9 | builder.RootComponents.Add("#app"); 10 | builder.RootComponents.Add("head::after"); 11 | 12 | builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); 13 | 14 | builder.Services.AddStorageManagerServiceInProcess(options => 15 | { 16 | // Configure with custom script path 17 | // options.BasePath = "content/"; 18 | // options.ScriptPath = $"custom-path/{FileSystemOptions.DefaultNamespace}.js"; 19 | }); 20 | 21 | builder.Services.AddURLServiceInProcess(); 22 | 23 | // Adding and configuring IndexedDB used for the IndexedDB sample. 24 | builder.Services.AddIndexedDB(dbStore => 25 | { 26 | dbStore.DbName = "FileSystem"; 27 | dbStore.Version = 1; 28 | 29 | dbStore.Stores.Add(new StoreSchema 30 | { 31 | Name = "FileReferences" 32 | }); 33 | }); 34 | 35 | await builder.Build().RunAsync(); 36 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "iisExpress": { 4 | "applicationUrl": "http://localhost:52596", 5 | "sslPort": 44327 6 | } 7 | }, 8 | "profiles": { 9 | "http": { 10 | "commandName": "Project", 11 | "dotnetRunMessages": true, 12 | "launchBrowser": true, 13 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 14 | "applicationUrl": "http://localhost:5284", 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | } 18 | }, 19 | "https": { 20 | "commandName": "Project", 21 | "dotnetRunMessages": true, 22 | "launchBrowser": true, 23 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 24 | "applicationUrl": "https://localhost:7209;http://localhost:5284", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | }, 29 | "IIS Express": { 30 | "commandName": "IISExpress", 31 | "launchBrowser": true, 32 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 33 | "environmentVariables": { 34 | "ASPNETCORE_ENVIRONMENT": "Development" 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Search/AlphabetExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.FileSystem.WasmExample.Search; 2 | 3 | public static class StringExtensions 4 | { 5 | public static (Dictionary CharToIndex, char[] IndexToChar) CreateAlphabet(this string input) 6 | { 7 | Dictionary charToIndex = new(); 8 | 9 | ISet set = input.ToHashSet(); 10 | List list = set.OrderBy(c => c).ToList(); 11 | char[] indexToChar = new char[list.Count + 1]; 12 | 13 | int count = 1; 14 | foreach (char c in list) 15 | { 16 | charToIndex[c] = count; 17 | indexToChar[count++] = c; 18 | } 19 | 20 | return (charToIndex, indexToChar); 21 | } 22 | 23 | public static int[] MapWithAlphabet(this string input, Dictionary CharToIndex) 24 | { 25 | int[] output = new int[input.Length + 1]; 26 | for (int i = 0; i < input.Length; i++) 27 | { 28 | if (!CharToIndex.ContainsKey(input[i])) 29 | throw new ArgumentException("character #" + i + " was not found in alphabet."); 30 | output[i] = CharToIndex[input[i]]; 31 | } 32 | output[input.Length] = 0; 33 | return output; 34 | } 35 | 36 | public static int[] MapWithAlphabetWithoutSentinel(this string input, Dictionary CharToIndex) 37 | { 38 | int[] output = new int[input.Length]; 39 | for (int i = 0; i < input.Length; i++) 40 | { 41 | if (!CharToIndex.ContainsKey(input[i])) 42 | throw new ArgumentException("character #" + i + " was not found in alphabet."); 43 | output[i] = CharToIndex[input[i]]; 44 | } 45 | return output; 46 | } 47 | 48 | public static int[] MapWithAlphabetWithoutSentinelAllowNewChars(this string input, Dictionary CharToIndex) 49 | { 50 | int[] output = new int[input.Length]; 51 | for (int i = 0; i < input.Length; i++) 52 | { 53 | output[i] = CharToIndex.GetValueOrDefault(input[i], CharToIndex.Count + 1); 54 | } 55 | return output; 56 | } 57 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Search/EditOperation.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.FileSystem.WasmExample.Search; 2 | 3 | 4 | enum EditOperation 5 | { 6 | M, 7 | I, 8 | D, 9 | None, 10 | Q //Q is only used for testing for mismatch 11 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Search/NaiveSuffixTree.cs: -------------------------------------------------------------------------------- 1 | using MessagePack; 2 | using System.Text; 3 | using System.Text.Json.Serialization; 4 | 5 | namespace KristofferStrube.Blazor.FileSystem.WasmExample.Search; 6 | 7 | /// 8 | /// This is taken from my groups project in the course Genome Scale Algorithms at Department of Bioinformatics at Aarhus University 9 | /// 10 | [MessagePackObject] 11 | public class NaiveSuffixTree 12 | { 13 | [Key(0)] 14 | public Node Root { get; set; } 15 | [Key(1)] 16 | public int AlphabetSize { get; set; } 17 | 18 | // These are the alphabet. 19 | [Key(2)] 20 | public Dictionary CharToIndex { get; set; } 21 | [Key(3)] 22 | public char[] IndexToChar { get; set; } 23 | 24 | [Key(4)] 25 | // Mapped Content 26 | public int[] MappedSequence { get; set; } 27 | 28 | public NaiveSuffixTree() 29 | { 30 | 31 | } 32 | 33 | public NaiveSuffixTree(string input) 34 | { 35 | (CharToIndex, IndexToChar) = input.CreateAlphabet(); 36 | MappedSequence = input.MapWithAlphabet(CharToIndex); 37 | AlphabetSize = IndexToChar.Length; 38 | 39 | Root = new Node(0, 0, AlphabetSize, null); 40 | int n = MappedSequence.Length; 41 | 42 | for (int i = 0; i < n; i++) 43 | { 44 | int from = i; 45 | Node node = Root; 46 | while (from < n) 47 | { 48 | Node newNode = null; 49 | if (node.Children[MappedSequence[from]] == null) 50 | { 51 | //Create new child node 52 | newNode = new Node(from, n, AlphabetSize, node, i); 53 | node.SetChild(MappedSequence[from], newNode); 54 | from = newNode.End; 55 | } 56 | else 57 | { 58 | //Search for edge match length, if completely matching go to next node, otherwise create new split node 59 | Node child = node.Children[MappedSequence[from]]; 60 | for (int j = 1; j < child.End - child.Start; j++) 61 | { 62 | if (MappedSequence[child.Start + j] != MappedSequence[from + j]) 63 | { 64 | newNode = InsertNodeOnEdge(node, child, j, from, MappedSequence, i); 65 | from = newNode.End; 66 | break; 67 | } 68 | } 69 | if (newNode == null) 70 | { 71 | newNode = child; 72 | from += newNode.End - newNode.Start; 73 | } 74 | } 75 | 76 | node = newNode; 77 | 78 | } 79 | } 80 | } 81 | 82 | public NaiveSuffixTree(int[] sa, int[] lcp, string input) 83 | { 84 | (CharToIndex, IndexToChar) = input.CreateAlphabet(); 85 | MappedSequence = input.MapWithAlphabet(CharToIndex); 86 | AlphabetSize = IndexToChar.Length; 87 | Root = new Node(0, 0, AlphabetSize, null); 88 | 89 | Node n = new Node(MappedSequence.Length - 1, MappedSequence.Length, AlphabetSize, Root, sa[0]); 90 | Root.Children[0] = n; 91 | 92 | int depth = 1; 93 | 94 | Stack stack = new(); 95 | stack.Push(Root); 96 | stack.Push(n); 97 | 98 | Node curr = n; 99 | 100 | for (int i = 1; i < MappedSequence.Length; i++) 101 | { 102 | 103 | while (depth - (curr.End - curr.Start) >= lcp[i] && (curr.End - curr.Start) != 0) 104 | { 105 | depth -= (curr.End - curr.Start); 106 | stack.Pop(); 107 | curr = stack.Peek(); 108 | } 109 | if (depth == lcp[i]) 110 | { 111 | Node newNode = new Node(sa[i] + lcp[i], MappedSequence.Length, AlphabetSize, curr, sa[i]); 112 | curr.Children[MappedSequence[newNode.Start]] = newNode; 113 | curr = newNode; 114 | depth += (curr.End - curr.Start); 115 | stack.Push(curr); 116 | } 117 | else 118 | { 119 | int splitnodeEnd = curr.Start + lcp[i] - (depth - (curr.End - curr.Start)); 120 | Node splitNode = new Node(curr.Start, splitnodeEnd, AlphabetSize, curr.Parent); 121 | curr.Parent.Children[MappedSequence[splitNode.Start]] = splitNode; 122 | curr.Start = splitnodeEnd; 123 | curr.Parent = splitNode; 124 | splitNode.Children[MappedSequence[curr.Start]] = curr; 125 | 126 | depth -= (curr.End - curr.Start); 127 | 128 | Node newNode = new Node(sa[i] + lcp[i], MappedSequence.Length, AlphabetSize, splitNode, sa[i]); 129 | splitNode.Children[MappedSequence[newNode.Start]] = newNode; 130 | 131 | depth += (newNode.End - newNode.Start); 132 | 133 | stack.Pop(); 134 | stack.Push(splitNode); 135 | stack.Push(newNode); 136 | 137 | curr = newNode; 138 | } 139 | } 140 | } 141 | 142 | public IEnumerable SearchForAllApproximateOccurences(string fastaName, string fastqName, string pattern, int edits) 143 | { 144 | List samlines = new List(); 145 | 146 | int[] mappedPattern = pattern.MapWithAlphabetWithoutSentinelAllowNewChars(CharToIndex); 147 | 148 | //(currNode, currPos on edge, edits left, position in pattern, lastEditOp) 149 | Stack<(Node, int, int, int, EditOperation)> stack = new(); 150 | stack.Push((Root, 0, edits, 0, EditOperation.None)); 151 | 152 | //Maybe this should be array 153 | Stack editOps = new(); 154 | 155 | while (stack.Count > 0) 156 | { 157 | (Node currNode, int currPosOnEdge, int editsLeft, int posInPattern, EditOperation lastEditOp) = stack.Pop(); 158 | 159 | //Check if we return from "recursive call" and need to pop from editOps 160 | if (currNode == null) 161 | { 162 | editOps.Pop(); 163 | continue; 164 | } 165 | 166 | //Push latest edit operation to stack 167 | if (lastEditOp != EditOperation.None) 168 | editOps.Push(lastEditOp); 169 | 170 | //checked if end of pattern 171 | if (posInPattern == mappedPattern.Length) 172 | { 173 | AddSubtreeToSamlines(samlines, editOps, currNode, fastqName, fastaName, pattern); 174 | 175 | stack.Push((null, 0, 0, 0, EditOperation.None)); 176 | continue; 177 | } 178 | 179 | //Add event that we have to pop Edit Operation from stack when "return" 180 | if (lastEditOp != EditOperation.None) 181 | stack.Push((null, 0, 0, 0, EditOperation.None)); 182 | 183 | 184 | if (currPosOnEdge == currNode.End - currNode.Start) 185 | { 186 | //Handles node as node (Start of next edge) 187 | 188 | for (int i = 0; i < currNode.Children.Length; i++) 189 | { 190 | if (currNode.Children[i] == null) continue; 191 | stack.Push((currNode.Children[i], 0, editsLeft, posInPattern, EditOperation.None)); 192 | } 193 | } 194 | else 195 | { 196 | //Handles node as an edge 197 | 198 | 199 | //Check for sentinel 200 | if (MappedSequence[currNode.Start + currPosOnEdge] == 0) 201 | { 202 | if (editsLeft >= mappedPattern.Length - posInPattern) 203 | { 204 | for (int i = 0; i < mappedPattern.Length - posInPattern; i++) 205 | { 206 | editOps.Push(EditOperation.I); 207 | } 208 | 209 | AddSubtreeToSamlines(samlines, editOps, currNode, fastqName, fastaName, pattern); 210 | 211 | for (int i = 0; i < mappedPattern.Length - posInPattern; i++) 212 | { 213 | editOps.Pop(); 214 | } 215 | } 216 | continue; 217 | } 218 | 219 | //Match/mismatch 220 | if (mappedPattern[posInPattern] == MappedSequence[currNode.Start + currPosOnEdge]) 221 | { 222 | //If match 223 | stack.Push((currNode, currPosOnEdge + 1, editsLeft, posInPattern + 1, EditOperation.M)); 224 | } 225 | else 226 | { 227 | //if mismatch 228 | if (editsLeft > 0) 229 | stack.Push((currNode, currPosOnEdge + 1, editsLeft - 1, posInPattern + 1, EditOperation.Q)); 230 | } 231 | 232 | if (editsLeft > 0) 233 | { 234 | //Delete 235 | stack.Push((currNode, currPosOnEdge + 1, editsLeft - 1, posInPattern, EditOperation.D)); 236 | 237 | //Insert 238 | stack.Push((currNode, currPosOnEdge, editsLeft - 1, posInPattern + 1, EditOperation.I)); 239 | } 240 | 241 | } 242 | } 243 | 244 | return samlines; 245 | } 246 | 247 | private void AddSubtreeToSamlines(List samlines, Stack editOps, Node currNode, string fastqName, string fastaName, string pattern) 248 | { 249 | //traverse all children in the subtree 250 | string cigar = CreateCigar(editOps); 251 | if (cigar[1] == 'D') 252 | return; 253 | 254 | 255 | Queue toTraverse = new Queue(); 256 | toTraverse.Enqueue(currNode); 257 | while (toTraverse.Count > 0) 258 | { 259 | var node = toTraverse.Dequeue(); 260 | if (node.Label.HasValue) 261 | { 262 | samlines.Add(new SamLine(fastqName, 0, fastaName, node.Label.Value, 0, cigar, "*", 0, 0, pattern)); 263 | } 264 | else 265 | { 266 | foreach (var c in node.Children) 267 | { 268 | if (c != null) 269 | { 270 | toTraverse.Enqueue(c); 271 | } 272 | } 273 | } 274 | } 275 | } 276 | 277 | private string CreateCigar(Stack editOps) 278 | { 279 | StringBuilder sb = new StringBuilder(); 280 | 281 | var enumerator = editOps.GetEnumerator(); 282 | Stack stringStack = new(); 283 | //Assume cigar not empty 284 | enumerator.MoveNext(); 285 | EditOperation currEditOp = enumerator.Current; 286 | int c = 1; 287 | 288 | while (enumerator.MoveNext()) 289 | { 290 | if (enumerator.Current == EditOperation.None) continue; 291 | if (enumerator.Current != currEditOp) 292 | { 293 | stringStack.Push(currEditOp.ToString()); 294 | stringStack.Push(c.ToString()); 295 | c = 1; 296 | currEditOp = enumerator.Current; 297 | } 298 | else 299 | { 300 | c++; 301 | } 302 | } 303 | 304 | stringStack.Push(currEditOp.ToString()); 305 | stringStack.Push(c.ToString()); 306 | 307 | foreach (string s in stringStack) 308 | sb.Append(s); 309 | 310 | return sb.ToString(); 311 | } 312 | 313 | public (int[] sa, int[] lcp) ComputeSaAndLcp() 314 | { 315 | Stack nodeStack = new(); 316 | Stack lcpCounterStack = new(); 317 | Stack pathDepthStack = new(); 318 | nodeStack.Push(Root); 319 | lcpCounterStack.Push(0); 320 | pathDepthStack.Push(0); 321 | var sa = new int[MappedSequence.Length]; 322 | int[] lcp = new int[MappedSequence.Length]; 323 | var progress = 0; 324 | while (nodeStack.Count > 0) 325 | { 326 | var node = nodeStack.Pop(); 327 | int lcpCounter = lcpCounterStack.Pop(); 328 | int pathDepth = pathDepthStack.Pop(); 329 | if (node.Label.HasValue) 330 | { 331 | lcp[progress] = pathDepth - lcpCounter; 332 | sa[progress++] = node.Label.Value; 333 | continue; 334 | } 335 | int noOfChildren = 0; 336 | for (int i = AlphabetSize - 1; i >= 0; i--) 337 | { 338 | Node child = node.Children[i]; 339 | if (child is not null) 340 | { 341 | 342 | nodeStack.Push(child); 343 | pathDepthStack.Push(pathDepth + (child.End - child.Start)); 344 | noOfChildren++; 345 | } 346 | } 347 | if (noOfChildren != 0) 348 | { 349 | for (int i = AlphabetSize - 1; i >= 0; i--) 350 | { 351 | Node child = node.Children[i]; 352 | if (child != null) 353 | { 354 | if (noOfChildren > 1) 355 | { 356 | noOfChildren--; 357 | lcpCounterStack.Push(child.End - child.Start); 358 | } 359 | else 360 | { 361 | lcpCounterStack.Push(lcpCounter + (child.End - child.Start)); 362 | } 363 | } 364 | 365 | } 366 | } 367 | } 368 | return (sa, lcp); 369 | } 370 | 371 | 372 | /// 373 | /// 374 | /// 375 | /// 376 | /// 377 | /// Indexed from 0 at the start of the edge to edgelength 378 | /// Index of new path at edge start 379 | /// 380 | private Node InsertNodeOnEdge(Node node, Node child, int splitIndex, int startindexNewPath, int[] mappedInput, int newLabel) 381 | { 382 | Node splitNode = new Node(child.Start, child.Start + splitIndex, AlphabetSize, node); 383 | node.SetChild(mappedInput[splitNode.Start], splitNode); 384 | child.Start = splitNode.End; 385 | splitNode.SetChild(mappedInput[splitNode.End], child); 386 | Node newPathNode = new Node(startindexNewPath + splitIndex, mappedInput.Length, AlphabetSize, splitNode, newLabel); 387 | splitNode.SetChild(mappedInput[startindexNewPath + splitIndex], newPathNode); 388 | return newPathNode; 389 | } 390 | 391 | public int SeachForFirstOccurence(string pattern) 392 | { 393 | int[] mappedPattern; 394 | 395 | try 396 | { 397 | mappedPattern = pattern.MapWithAlphabetWithoutSentinel(CharToIndex); 398 | } 399 | catch 400 | { 401 | return -1; 402 | } 403 | 404 | Node curr = Root; 405 | int indexInPattern = 0; 406 | 407 | while (indexInPattern < mappedPattern.Length) 408 | { 409 | if (curr.Children[mappedPattern[indexInPattern]] == null) return -1; 410 | Node child = curr.Children[mappedPattern[indexInPattern]]; 411 | for (int i = child.Start; i < child.End; i++) 412 | { 413 | if (mappedPattern[i - child.Start + indexInPattern] != MappedSequence[i]) return -1; 414 | if (i == mappedPattern.Length - 1 + child.Start - indexInPattern) 415 | { 416 | return i - mappedPattern.Length + 1; 417 | } 418 | } 419 | indexInPattern += child.End - child.Start; 420 | curr = child; 421 | } 422 | 423 | return -1; 424 | } 425 | 426 | public IEnumerable SearchForAllOccurences(string fastaName, string fastqName, string pattern) 427 | { 428 | string cigar = pattern.Length + "M"; //Should add the proper cigar handling in later assignments 429 | 430 | List samlines = new List(); 431 | 432 | int[] mappedPattern; 433 | try 434 | { 435 | mappedPattern = pattern.MapWithAlphabetWithoutSentinel(CharToIndex); 436 | } 437 | catch 438 | { 439 | return samlines; 440 | } 441 | 442 | Node curr = Root; 443 | int indexInPattern = 0; 444 | 445 | while (indexInPattern < mappedPattern.Length) 446 | { 447 | if (curr.Children[mappedPattern[indexInPattern]] == null) return samlines; 448 | Node child = curr.Children[mappedPattern[indexInPattern]]; 449 | for (int i = child.Start; i < child.End; i++) 450 | { 451 | if (mappedPattern[i - child.Start + indexInPattern] != MappedSequence[i]) return samlines; 452 | if (i == mappedPattern.Length - 1 + child.Start - indexInPattern) 453 | { 454 | Queue toTraverse = new Queue(); 455 | toTraverse.Enqueue(child); 456 | while (toTraverse.Count > 0) 457 | { 458 | var node = toTraverse.Dequeue(); 459 | if (node.Label.HasValue) 460 | { 461 | samlines.Add(new SamLine(fastqName, 0, fastaName, node.Label.Value, 0, cigar, "*", 0, 0, pattern)); 462 | } 463 | else 464 | { 465 | foreach (var c in node.Children) 466 | { 467 | if (c != null) 468 | { 469 | toTraverse.Enqueue(c); 470 | } 471 | } 472 | } 473 | } 474 | return samlines; 475 | } 476 | } 477 | indexInPattern += child.End - child.Start; 478 | curr = child; 479 | } 480 | 481 | return samlines; 482 | } 483 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Search/Node.cs: -------------------------------------------------------------------------------- 1 | using MessagePack; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem.WasmExample.Search; 4 | 5 | [MessagePackObject] 6 | public class Node 7 | { 8 | [SerializationConstructor] 9 | public Node(int start, int end, Node?[] children, int? label) 10 | { 11 | Start = start; 12 | End = end; 13 | foreach (Node? node in children) 14 | { 15 | if (node is null) continue; 16 | node.Parent = this; 17 | } 18 | Children = children; 19 | Label = label; 20 | } 21 | 22 | public Node(int start, int end, int alphabetSize, Node parent, int? label = null) 23 | { 24 | Start = start; 25 | End = end; 26 | Label = label; 27 | Parent = parent; 28 | Children = new Node[alphabetSize]; 29 | } 30 | 31 | [Key(0)] 32 | public int Start { get; set; } 33 | [Key(1)] 34 | public int End { get; set; } 35 | 36 | [Key(2)] 37 | public Node?[] Children { get; set; } 38 | 39 | [IgnoreMember] 40 | public Node? Parent { get; set; } 41 | 42 | [Key(3)] 43 | public int? Label { get; set; } 44 | 45 | public void SetChild(int startMappedCharacter, Node child) 46 | { 47 | Children[startMappedCharacter] = child; 48 | child.Parent = this; 49 | } 50 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Search/SamLine.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.FileSystem.WasmExample.Search; 2 | 3 | public record SamLine(string QName, int Flag, string RName, int Pos, int MapQ, string Cigar, string RNext, int PNext, int TLen, string Seq); 4 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Shared/ElementExplorer.razor: -------------------------------------------------------------------------------- 1 | @if (Element is FileSystemFileHandle fileHandle) 2 | { 3 | 4 | 🗒 @Element.Name 5 |
6 | } 7 | else if (Element is FileSystemDirectoryHandle) 8 | { 9 | 10 | 11 | if (@Element.Name is not "") 12 | { 13 | 📁 @Element.Name 14 | } 15 | @foreach (var child in children) 16 | { 17 | if (child.Name is "MastodonSearchIndexes" || child.Name.EndsWith(".crswap")) continue; 18 |
19 | 20 | 21 |
22 | } 23 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Shared/ElementExplorer.razor.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Components; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem.WasmExample.Shared; 4 | 5 | public partial class ElementExplorer 6 | { 7 | private List children = new(); 8 | [Parameter, EditorRequired] 9 | public IFileSystemHandleInProcess Element { get; set; } = default!; 10 | [Parameter, EditorRequired] 11 | public Func EditAction { get; set; } = default!; 12 | protected override async Task OnParametersSetAsync() 13 | { 14 | if (Element is not FileSystemDirectoryHandleInProcess directoryHandle) 15 | return; 16 | children = (await directoryHandle.ValuesAsync()).ToList(); 17 | } 18 | 19 | async Task Remove(IFileSystemHandleInProcess element) 20 | { 21 | if (Element is not FileSystemDirectoryHandleInProcess { } directoryHandle 22 | || (await directoryHandle.ResolveAsync(element))!.Length is 0) return; 23 | await directoryHandle.RemoveEntryAsync(element.Name, new() { Recursive = true }); 24 | children.Remove(element); 25 | } 26 | 27 | async Task AddFile() 28 | { 29 | if (Element is not FileSystemDirectoryHandleInProcess directoryHandle) return; 30 | children.Add(await directoryHandle.GetFileHandleAsync($"{Guid.NewGuid().ToString()[..4]}.txt", new() { Create = true })); 31 | } 32 | 33 | async Task AddDirectory() 34 | { 35 | if (Element is not FileSystemDirectoryHandleInProcess directoryHandle) return; 36 | children.Add(await directoryHandle.GetDirectoryHandleAsync(Guid.NewGuid().ToString()[..4], new() { Create = true })); 37 | } 38 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Shared/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 | @inject NavigationManager NavigationManager 3 | 4 |
5 | 8 | 9 |
10 |
11 | 12 | 13 | 14 |
15 | 16 |
17 | @Body 18 |
19 |
20 |
21 | 22 | @code { 23 | private string relativeUri => NavigationManager.ToBaseRelativePath(NavigationManager.Uri); 24 | 25 | protected string page => (string.IsNullOrEmpty(relativeUri) ? "Index" : relativeUri) + ".razor"; 26 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Shared/MainLayout.razor.css: -------------------------------------------------------------------------------- 1 | .page { 2 | position: relative; 3 | display: flex; 4 | flex-direction: column; 5 | } 6 | 7 | main { 8 | flex: 1; 9 | } 10 | 11 | .sidebar { 12 | background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%); 13 | } 14 | 15 | .top-row { 16 | background-color: #f7f7f7; 17 | border-bottom: 1px solid #d6d5d5; 18 | justify-content: flex-end; 19 | height: 3.5rem; 20 | display: flex; 21 | align-items: center; 22 | } 23 | 24 | .top-row ::deep a, .top-row ::deep .btn-link { 25 | white-space: nowrap; 26 | margin-left: 1.5rem; 27 | text-decoration: none; 28 | } 29 | 30 | .top-row ::deep a:hover, .top-row ::deep .btn-link:hover { 31 | text-decoration: underline; 32 | } 33 | 34 | .top-row ::deep a:first-child { 35 | overflow: hidden; 36 | text-overflow: ellipsis; 37 | } 38 | 39 | @media (max-width: 640.98px) { 40 | .top-row:not(.auth) { 41 | display: none; 42 | } 43 | 44 | .top-row.auth { 45 | justify-content: space-between; 46 | } 47 | 48 | .top-row ::deep a, .top-row ::deep .btn-link { 49 | margin-left: 0; 50 | } 51 | } 52 | 53 | @media (min-width: 641px) { 54 | .page { 55 | flex-direction: row; 56 | } 57 | 58 | .sidebar { 59 | width: 250px; 60 | height: 100vh; 61 | position: sticky; 62 | top: 0; 63 | } 64 | 65 | .top-row { 66 | position: sticky; 67 | top: 0; 68 | z-index: 1; 69 | } 70 | 71 | .top-row.auth ::deep a:first-child { 72 | flex: 1; 73 | text-align: right; 74 | width: 0; 75 | } 76 | 77 | .top-row, article { 78 | padding-left: 2rem !important; 79 | padding-right: 1.5rem !important; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Shared/NavMenu.razor: -------------------------------------------------------------------------------- 1 |  9 | 10 |
11 | 33 |
34 | 35 | @code { 36 | private bool collapseNavMenu = true; 37 | 38 | private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null; 39 | 40 | private void ToggleNavMenu() 41 | { 42 | collapseNavMenu = !collapseNavMenu; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Shared/NavMenu.razor.css: -------------------------------------------------------------------------------- 1 | .navbar-toggler { 2 | background-color: rgba(255, 255, 255, 0.1); 3 | } 4 | 5 | .top-row { 6 | height: 3.5rem; 7 | background-color: rgba(0,0,0,0.4); 8 | } 9 | 10 | .navbar-brand { 11 | font-size: 1.1rem; 12 | } 13 | 14 | .oi { 15 | width: 2rem; 16 | font-size: 1.1rem; 17 | vertical-align: text-top; 18 | top: -2px; 19 | } 20 | 21 | .nav-item { 22 | font-size: 0.9rem; 23 | padding-bottom: 0.5rem; 24 | } 25 | 26 | .nav-item:first-of-type { 27 | padding-top: 1rem; 28 | } 29 | 30 | .nav-item:last-of-type { 31 | padding-bottom: 1rem; 32 | } 33 | 34 | .nav-item ::deep a { 35 | color: #d7d7d7; 36 | border-radius: 4px; 37 | height: 3rem; 38 | display: flex; 39 | align-items: center; 40 | line-height: 3rem; 41 | } 42 | 43 | .nav-item ::deep a.active { 44 | background-color: rgba(255,255,255,0.25); 45 | color: white; 46 | } 47 | 48 | .nav-item ::deep a:hover { 49 | background-color: rgba(255,255,255,0.1); 50 | color: white; 51 | } 52 | 53 | @media (min-width: 641px) { 54 | .navbar-toggler { 55 | display: none; 56 | } 57 | 58 | .collapse { 59 | /* Never collapse the sidebar for wide screens */ 60 | display: block; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/Shared/NotePresenter.razor: -------------------------------------------------------------------------------- 1 | @using KristofferStrube.ActivityStreams; 2 | 3 |
4 |
5 | @if (Note.AttributedTo?.First() is Person profile) 6 | { 7 |
8 | @if (Note.InReplyTo?.First() is Link { Href: { } replyToHref }) 9 | { 10 | in reply to @replyToHref.Segments.Last() 11 | } 12 |
13 | @if (profile.Icon?.First() is Image profilePicture && profilePicture.Url?.First() is Link { Href: { } profilePictureHref }) 14 | { 15 |
16 | 17 |
18 | } 19 |
20 |
@((MarkupString)(profile.Tag?.Aggregate(profile.Name?.First() ?? "", (acc, cur) => cur is KristofferStrube.ActivityStreams.Object obj && cur.Type.Contains("Emoji") ? acc.Replace(obj.Name.First(), obj.Icon.First() is IObject image ? $"" : "") : acc) ?? ""))
21 | @if (profile.Url?.First() is Link { Href: { } profileHref }) 22 | { 23 | @@@profile.PreferredUsername 24 | } 25 |
26 |
27 |
28 |
29 | @Note.Published?.ToShortTimeString() : @Note.Published?.ToShortDateString() 30 |
31 | } 32 |
33 | @((MarkupString)(Note.Content!.First())) 34 | @if (Note.Attachment?.FirstOrDefault(attactment => attactment is Document && attactment.MediaType?.StartsWith("image") is true) is Document { } image && image.Url?.FirstOrDefault() is Link { Href: { } imageHref }) 35 | { 36 |
37 | @image.Name?.First() 38 |
39 | } 40 | @if (Note.Attachment?.FirstOrDefault(attactment => attactment is Document && attactment.MediaType?.StartsWith("video") is true) is Document { } video && video.Url?.FirstOrDefault() is Link { Href: { } videoHref }) 41 | { 42 |
43 | 47 |
48 | } 49 | Open on mastodon 50 |
51 | 52 | @code { 53 | [Parameter, EditorRequired] 54 | public IObject Note { get; set; } 55 | } 56 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using System.Net.Http 2 | @using System.Net.Http.Json 3 | @using Microsoft.AspNetCore.Components.Routing 4 | @using Microsoft.AspNetCore.Components.Web 5 | @using Microsoft.AspNetCore.Components.Web.Virtualization 6 | @using Microsoft.AspNetCore.Components.WebAssembly.Http 7 | @using Microsoft.JSInterop 8 | @using KristofferStrube.Blazor.FileAPI 9 | @using KristofferStrube.Blazor.FileSystem 10 | @using KristofferStrube.Blazor.FileSystem.WasmExample 11 | @using KristofferStrube.Blazor.FileSystem.WasmExample.Shared 12 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/404.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Blazor File System 6 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/css/app.css: -------------------------------------------------------------------------------- 1 | @import url('open-iconic/font/css/open-iconic-bootstrap.min.css'); 2 | 3 | html { 4 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 5 | } 6 | 7 | html, body, #app, .page, main { 8 | height: 100%; 9 | } 10 | 11 | .body-article { 12 | height: calc(100% - 56px); 13 | padding-bottom:1.1rem; 14 | overflow-y:scroll; 15 | } 16 | 17 | h1:focus { 18 | outline: none; 19 | } 20 | 21 | a, .btn-link { 22 | color: #0071c1; 23 | } 24 | 25 | .btn-primary { 26 | color: #fff; 27 | background-color: #1b6ec2; 28 | border-color: #1861ac; 29 | } 30 | 31 | .content { 32 | padding-top: 1.1rem; 33 | overflow-x:hidden; 34 | } 35 | 36 | .valid.modified:not([type=checkbox]) { 37 | outline: 1px solid #26b050; 38 | } 39 | 40 | .invalid { 41 | outline: 1px solid red; 42 | } 43 | 44 | .invisible { 45 | display: inline-block; 46 | width: 0px; 47 | } 48 | 49 | .ellipsis::after {content: '…'} 50 | 51 | .validation-message { 52 | color: red; 53 | } 54 | 55 | #blazor-error-ui { 56 | background: lightyellow; 57 | bottom: 0; 58 | box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); 59 | display: none; 60 | left: 0; 61 | padding: 0.6rem 1.25rem 0.7rem 1.25rem; 62 | position: fixed; 63 | width: 100%; 64 | z-index: 1000; 65 | } 66 | 67 | #blazor-error-ui .dismiss { 68 | cursor: pointer; 69 | position: absolute; 70 | right: 0.75rem; 71 | top: 0.5rem; 72 | } 73 | 74 | .blazor-error-boundary { 75 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; 76 | padding: 1rem 1rem 1rem 3.7rem; 77 | color: white; 78 | } 79 | 80 | .blazor-error-boundary::after { 81 | content: "An error has occurred." 82 | } 83 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/css/open-iconic/FONT-LICENSE: -------------------------------------------------------------------------------- 1 | SIL OPEN FONT LICENSE Version 1.1 2 | 3 | Copyright (c) 2014 Waybury 4 | 5 | PREAMBLE 6 | The goals of the Open Font License (OFL) are to stimulate worldwide 7 | development of collaborative font projects, to support the font creation 8 | efforts of academic and linguistic communities, and to provide a free and 9 | open framework in which fonts may be shared and improved in partnership 10 | with others. 11 | 12 | The OFL allows the licensed fonts to be used, studied, modified and 13 | redistributed freely as long as they are not sold by themselves. The 14 | fonts, including any derivative works, can be bundled, embedded, 15 | redistributed and/or sold with any software provided that any reserved 16 | names are not used by derivative works. The fonts and derivatives, 17 | however, cannot be released under any other type of license. The 18 | requirement for fonts to remain under this license does not apply 19 | to any document created using the fonts or their derivatives. 20 | 21 | DEFINITIONS 22 | "Font Software" refers to the set of files released by the Copyright 23 | Holder(s) under this license and clearly marked as such. This may 24 | include source files, build scripts and documentation. 25 | 26 | "Reserved Font Name" refers to any names specified as such after the 27 | copyright statement(s). 28 | 29 | "Original Version" refers to the collection of Font Software components as 30 | distributed by the Copyright Holder(s). 31 | 32 | "Modified Version" refers to any derivative made by adding to, deleting, 33 | or substituting -- in part or in whole -- any of the components of the 34 | Original Version, by changing formats or by porting the Font Software to a 35 | new environment. 36 | 37 | "Author" refers to any designer, engineer, programmer, technical 38 | writer or other person who contributed to the Font Software. 39 | 40 | PERMISSION & CONDITIONS 41 | Permission is hereby granted, free of charge, to any person obtaining 42 | a copy of the Font Software, to use, study, copy, merge, embed, modify, 43 | redistribute, and sell modified and unmodified copies of the Font 44 | Software, subject to the following conditions: 45 | 46 | 1) Neither the Font Software nor any of its individual components, 47 | in Original or Modified Versions, may be sold by itself. 48 | 49 | 2) Original or Modified Versions of the Font Software may be bundled, 50 | redistributed and/or sold with any software, provided that each copy 51 | contains the above copyright notice and this license. These can be 52 | included either as stand-alone text files, human-readable headers or 53 | in the appropriate machine-readable metadata fields within text or 54 | binary files as long as those fields can be easily viewed by the user. 55 | 56 | 3) No Modified Version of the Font Software may use the Reserved Font 57 | Name(s) unless explicit written permission is granted by the corresponding 58 | Copyright Holder. This restriction only applies to the primary font name as 59 | presented to the users. 60 | 61 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font 62 | Software shall not be used to promote, endorse or advertise any 63 | Modified Version, except to acknowledge the contribution(s) of the 64 | Copyright Holder(s) and the Author(s) or with their explicit written 65 | permission. 66 | 67 | 5) The Font Software, modified or unmodified, in part or in whole, 68 | must be distributed entirely under this license, and must not be 69 | distributed under any other license. The requirement for fonts to 70 | remain under this license does not apply to any document created 71 | using the Font Software. 72 | 73 | TERMINATION 74 | This license becomes null and void if any of the above conditions are 75 | not met. 76 | 77 | DISCLAIMER 78 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 79 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 80 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 81 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 82 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 83 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 84 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 85 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM 86 | OTHER DEALINGS IN THE FONT SOFTWARE. 87 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/css/open-iconic/ICON-LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Waybury 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/css/open-iconic/README.md: -------------------------------------------------------------------------------- 1 | [Open Iconic v1.1.1](http://useiconic.com/open) 2 | =========== 3 | 4 | ### Open Iconic is the open source sibling of [Iconic](http://useiconic.com). It is a hyper-legible collection of 223 icons with a tiny footprint—ready to use with Bootstrap and Foundation. [View the collection](http://useiconic.com/open#icons) 5 | 6 | 7 | 8 | ## What's in Open Iconic? 9 | 10 | * 223 icons designed to be legible down to 8 pixels 11 | * Super-light SVG files - 61.8 for the entire set 12 | * SVG sprite—the modern replacement for icon fonts 13 | * Webfont (EOT, OTF, SVG, TTF, WOFF), PNG and WebP formats 14 | * Webfont stylesheets (including versions for Bootstrap and Foundation) in CSS, LESS, SCSS and Stylus formats 15 | * PNG and WebP raster images in 8px, 16px, 24px, 32px, 48px and 64px. 16 | 17 | 18 | ## Getting Started 19 | 20 | #### For code samples and everything else you need to get started with Open Iconic, check out our [Icons](http://useiconic.com/open#icons) and [Reference](http://useiconic.com/open#reference) sections. 21 | 22 | ### General Usage 23 | 24 | #### Using Open Iconic's SVGs 25 | 26 | We like SVGs and we think they're the way to display icons on the web. Since Open Iconic are just basic SVGs, we suggest you display them like you would any other image (don't forget the `alt` attribute). 27 | 28 | ``` 29 | icon name 30 | ``` 31 | 32 | #### Using Open Iconic's SVG Sprite 33 | 34 | Open Iconic also comes in a SVG sprite which allows you to display all the icons in the set with a single request. It's like an icon font, without being a hack. 35 | 36 | Adding an icon from an SVG sprite is a little different than what you're used to, but it's still a piece of cake. *Tip: To make your icons easily style able, we suggest adding a general class to the* `` *tag and a unique class name for each different icon in the* `` *tag.* 37 | 38 | ``` 39 | 40 | 41 | 42 | ``` 43 | 44 | Sizing icons only needs basic CSS. All the icons are in a square format, so just set the `` tag with equal width and height dimensions. 45 | 46 | ``` 47 | .icon { 48 | width: 16px; 49 | height: 16px; 50 | } 51 | ``` 52 | 53 | Coloring icons is even easier. All you need to do is set the `fill` rule on the `` tag. 54 | 55 | ``` 56 | .icon-account-login { 57 | fill: #f00; 58 | } 59 | ``` 60 | 61 | To learn more about SVG Sprites, read [Chris Coyier's guide](http://css-tricks.com/svg-sprites-use-better-icon-fonts/). 62 | 63 | #### Using Open Iconic's Icon Font... 64 | 65 | 66 | ##### …with Bootstrap 67 | 68 | You can find our Bootstrap stylesheets in `font/css/open-iconic-bootstrap.{css, less, scss, styl}` 69 | 70 | 71 | ``` 72 | 73 | ``` 74 | 75 | 76 | ``` 77 | 78 | ``` 79 | 80 | ##### …with Foundation 81 | 82 | You can find our Foundation stylesheets in `font/css/open-iconic-foundation.{css, less, scss, styl}` 83 | 84 | ``` 85 | 86 | ``` 87 | 88 | 89 | ``` 90 | 91 | ``` 92 | 93 | ##### …on its own 94 | 95 | You can find our default stylesheets in `font/css/open-iconic.{css, less, scss, styl}` 96 | 97 | ``` 98 | 99 | ``` 100 | 101 | ``` 102 | 103 | ``` 104 | 105 | 106 | ## License 107 | 108 | ### Icons 109 | 110 | All code (including SVG markup) is under the [MIT License](http://opensource.org/licenses/MIT). 111 | 112 | ### Fonts 113 | 114 | All fonts are under the [SIL Licensed](http://scripts.sil.org/cms/scripts/page.php?item_id=OFL_web). 115 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/css/open-iconic/font/css/open-iconic-bootstrap.min.css: -------------------------------------------------------------------------------- 1 | @font-face{font-family:Icons;src:url(../fonts/open-iconic.eot);src:url(../fonts/open-iconic.eot?#iconic-sm) format('embedded-opentype'),url(../fonts/open-iconic.woff) format('woff'),url(../fonts/open-iconic.ttf) format('truetype'),url(../fonts/open-iconic.otf) format('opentype'),url(../fonts/open-iconic.svg#iconic-sm) format('svg');font-weight:400;font-style:normal}.oi{position:relative;top:1px;display:inline-block;speak:none;font-family:Icons;font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.oi:empty:before{width:1em;text-align:center;box-sizing:content-box}.oi.oi-align-center:before{text-align:center}.oi.oi-align-left:before{text-align:left}.oi.oi-align-right:before{text-align:right}.oi.oi-flip-horizontal:before{-webkit-transform:scale(-1,1);-ms-transform:scale(-1,1);transform:scale(-1,1)}.oi.oi-flip-vertical:before{-webkit-transform:scale(1,-1);-ms-transform:scale(-1,1);transform:scale(1,-1)}.oi.oi-flip-horizontal-vertical:before{-webkit-transform:scale(-1,-1);-ms-transform:scale(-1,1);transform:scale(-1,-1)}.oi-account-login:before{content:'\e000'}.oi-account-logout:before{content:'\e001'}.oi-action-redo:before{content:'\e002'}.oi-action-undo:before{content:'\e003'}.oi-align-center:before{content:'\e004'}.oi-align-left:before{content:'\e005'}.oi-align-right:before{content:'\e006'}.oi-aperture:before{content:'\e007'}.oi-arrow-bottom:before{content:'\e008'}.oi-arrow-circle-bottom:before{content:'\e009'}.oi-arrow-circle-left:before{content:'\e00a'}.oi-arrow-circle-right:before{content:'\e00b'}.oi-arrow-circle-top:before{content:'\e00c'}.oi-arrow-left:before{content:'\e00d'}.oi-arrow-right:before{content:'\e00e'}.oi-arrow-thick-bottom:before{content:'\e00f'}.oi-arrow-thick-left:before{content:'\e010'}.oi-arrow-thick-right:before{content:'\e011'}.oi-arrow-thick-top:before{content:'\e012'}.oi-arrow-top:before{content:'\e013'}.oi-audio-spectrum:before{content:'\e014'}.oi-audio:before{content:'\e015'}.oi-badge:before{content:'\e016'}.oi-ban:before{content:'\e017'}.oi-bar-chart:before{content:'\e018'}.oi-basket:before{content:'\e019'}.oi-battery-empty:before{content:'\e01a'}.oi-battery-full:before{content:'\e01b'}.oi-beaker:before{content:'\e01c'}.oi-bell:before{content:'\e01d'}.oi-bluetooth:before{content:'\e01e'}.oi-bold:before{content:'\e01f'}.oi-bolt:before{content:'\e020'}.oi-book:before{content:'\e021'}.oi-bookmark:before{content:'\e022'}.oi-box:before{content:'\e023'}.oi-briefcase:before{content:'\e024'}.oi-british-pound:before{content:'\e025'}.oi-browser:before{content:'\e026'}.oi-brush:before{content:'\e027'}.oi-bug:before{content:'\e028'}.oi-bullhorn:before{content:'\e029'}.oi-calculator:before{content:'\e02a'}.oi-calendar:before{content:'\e02b'}.oi-camera-slr:before{content:'\e02c'}.oi-caret-bottom:before{content:'\e02d'}.oi-caret-left:before{content:'\e02e'}.oi-caret-right:before{content:'\e02f'}.oi-caret-top:before{content:'\e030'}.oi-cart:before{content:'\e031'}.oi-chat:before{content:'\e032'}.oi-check:before{content:'\e033'}.oi-chevron-bottom:before{content:'\e034'}.oi-chevron-left:before{content:'\e035'}.oi-chevron-right:before{content:'\e036'}.oi-chevron-top:before{content:'\e037'}.oi-circle-check:before{content:'\e038'}.oi-circle-x:before{content:'\e039'}.oi-clipboard:before{content:'\e03a'}.oi-clock:before{content:'\e03b'}.oi-cloud-download:before{content:'\e03c'}.oi-cloud-upload:before{content:'\e03d'}.oi-cloud:before{content:'\e03e'}.oi-cloudy:before{content:'\e03f'}.oi-code:before{content:'\e040'}.oi-cog:before{content:'\e041'}.oi-collapse-down:before{content:'\e042'}.oi-collapse-left:before{content:'\e043'}.oi-collapse-right:before{content:'\e044'}.oi-collapse-up:before{content:'\e045'}.oi-command:before{content:'\e046'}.oi-comment-square:before{content:'\e047'}.oi-compass:before{content:'\e048'}.oi-contrast:before{content:'\e049'}.oi-copywriting:before{content:'\e04a'}.oi-credit-card:before{content:'\e04b'}.oi-crop:before{content:'\e04c'}.oi-dashboard:before{content:'\e04d'}.oi-data-transfer-download:before{content:'\e04e'}.oi-data-transfer-upload:before{content:'\e04f'}.oi-delete:before{content:'\e050'}.oi-dial:before{content:'\e051'}.oi-document:before{content:'\e052'}.oi-dollar:before{content:'\e053'}.oi-double-quote-sans-left:before{content:'\e054'}.oi-double-quote-sans-right:before{content:'\e055'}.oi-double-quote-serif-left:before{content:'\e056'}.oi-double-quote-serif-right:before{content:'\e057'}.oi-droplet:before{content:'\e058'}.oi-eject:before{content:'\e059'}.oi-elevator:before{content:'\e05a'}.oi-ellipses:before{content:'\e05b'}.oi-envelope-closed:before{content:'\e05c'}.oi-envelope-open:before{content:'\e05d'}.oi-euro:before{content:'\e05e'}.oi-excerpt:before{content:'\e05f'}.oi-expand-down:before{content:'\e060'}.oi-expand-left:before{content:'\e061'}.oi-expand-right:before{content:'\e062'}.oi-expand-up:before{content:'\e063'}.oi-external-link:before{content:'\e064'}.oi-eye:before{content:'\e065'}.oi-eyedropper:before{content:'\e066'}.oi-file:before{content:'\e067'}.oi-fire:before{content:'\e068'}.oi-flag:before{content:'\e069'}.oi-flash:before{content:'\e06a'}.oi-folder:before{content:'\e06b'}.oi-fork:before{content:'\e06c'}.oi-fullscreen-enter:before{content:'\e06d'}.oi-fullscreen-exit:before{content:'\e06e'}.oi-globe:before{content:'\e06f'}.oi-graph:before{content:'\e070'}.oi-grid-four-up:before{content:'\e071'}.oi-grid-three-up:before{content:'\e072'}.oi-grid-two-up:before{content:'\e073'}.oi-hard-drive:before{content:'\e074'}.oi-header:before{content:'\e075'}.oi-headphones:before{content:'\e076'}.oi-heart:before{content:'\e077'}.oi-home:before{content:'\e078'}.oi-image:before{content:'\e079'}.oi-inbox:before{content:'\e07a'}.oi-infinity:before{content:'\e07b'}.oi-info:before{content:'\e07c'}.oi-italic:before{content:'\e07d'}.oi-justify-center:before{content:'\e07e'}.oi-justify-left:before{content:'\e07f'}.oi-justify-right:before{content:'\e080'}.oi-key:before{content:'\e081'}.oi-laptop:before{content:'\e082'}.oi-layers:before{content:'\e083'}.oi-lightbulb:before{content:'\e084'}.oi-link-broken:before{content:'\e085'}.oi-link-intact:before{content:'\e086'}.oi-list-rich:before{content:'\e087'}.oi-list:before{content:'\e088'}.oi-location:before{content:'\e089'}.oi-lock-locked:before{content:'\e08a'}.oi-lock-unlocked:before{content:'\e08b'}.oi-loop-circular:before{content:'\e08c'}.oi-loop-square:before{content:'\e08d'}.oi-loop:before{content:'\e08e'}.oi-magnifying-glass:before{content:'\e08f'}.oi-map-marker:before{content:'\e090'}.oi-map:before{content:'\e091'}.oi-media-pause:before{content:'\e092'}.oi-media-play:before{content:'\e093'}.oi-media-record:before{content:'\e094'}.oi-media-skip-backward:before{content:'\e095'}.oi-media-skip-forward:before{content:'\e096'}.oi-media-step-backward:before{content:'\e097'}.oi-media-step-forward:before{content:'\e098'}.oi-media-stop:before{content:'\e099'}.oi-medical-cross:before{content:'\e09a'}.oi-menu:before{content:'\e09b'}.oi-microphone:before{content:'\e09c'}.oi-minus:before{content:'\e09d'}.oi-monitor:before{content:'\e09e'}.oi-moon:before{content:'\e09f'}.oi-move:before{content:'\e0a0'}.oi-musical-note:before{content:'\e0a1'}.oi-paperclip:before{content:'\e0a2'}.oi-pencil:before{content:'\e0a3'}.oi-people:before{content:'\e0a4'}.oi-person:before{content:'\e0a5'}.oi-phone:before{content:'\e0a6'}.oi-pie-chart:before{content:'\e0a7'}.oi-pin:before{content:'\e0a8'}.oi-play-circle:before{content:'\e0a9'}.oi-plus:before{content:'\e0aa'}.oi-power-standby:before{content:'\e0ab'}.oi-print:before{content:'\e0ac'}.oi-project:before{content:'\e0ad'}.oi-pulse:before{content:'\e0ae'}.oi-puzzle-piece:before{content:'\e0af'}.oi-question-mark:before{content:'\e0b0'}.oi-rain:before{content:'\e0b1'}.oi-random:before{content:'\e0b2'}.oi-reload:before{content:'\e0b3'}.oi-resize-both:before{content:'\e0b4'}.oi-resize-height:before{content:'\e0b5'}.oi-resize-width:before{content:'\e0b6'}.oi-rss-alt:before{content:'\e0b7'}.oi-rss:before{content:'\e0b8'}.oi-script:before{content:'\e0b9'}.oi-share-boxed:before{content:'\e0ba'}.oi-share:before{content:'\e0bb'}.oi-shield:before{content:'\e0bc'}.oi-signal:before{content:'\e0bd'}.oi-signpost:before{content:'\e0be'}.oi-sort-ascending:before{content:'\e0bf'}.oi-sort-descending:before{content:'\e0c0'}.oi-spreadsheet:before{content:'\e0c1'}.oi-star:before{content:'\e0c2'}.oi-sun:before{content:'\e0c3'}.oi-tablet:before{content:'\e0c4'}.oi-tag:before{content:'\e0c5'}.oi-tags:before{content:'\e0c6'}.oi-target:before{content:'\e0c7'}.oi-task:before{content:'\e0c8'}.oi-terminal:before{content:'\e0c9'}.oi-text:before{content:'\e0ca'}.oi-thumb-down:before{content:'\e0cb'}.oi-thumb-up:before{content:'\e0cc'}.oi-timer:before{content:'\e0cd'}.oi-transfer:before{content:'\e0ce'}.oi-trash:before{content:'\e0cf'}.oi-underline:before{content:'\e0d0'}.oi-vertical-align-bottom:before{content:'\e0d1'}.oi-vertical-align-center:before{content:'\e0d2'}.oi-vertical-align-top:before{content:'\e0d3'}.oi-video:before{content:'\e0d4'}.oi-volume-high:before{content:'\e0d5'}.oi-volume-low:before{content:'\e0d6'}.oi-volume-off:before{content:'\e0d7'}.oi-warning:before{content:'\e0d8'}.oi-wifi:before{content:'\e0d9'}.oi-wrench:before{content:'\e0da'}.oi-x:before{content:'\e0db'}.oi-yen:before{content:'\e0dc'}.oi-zoom-in:before{content:'\e0dd'}.oi-zoom-out:before{content:'\e0de'} -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.FileSystem/718d8d36c44a7c61d994ff19a54b98ce4386a29a/samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.eot -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.FileSystem/718d8d36c44a7c61d994ff19a54b98ce4386a29a/samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.otf -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.FileSystem/718d8d36c44a7c61d994ff19a54b98ce4386a29a/samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.ttf -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.FileSystem/718d8d36c44a7c61d994ff19a54b98ce4386a29a/samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.woff -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileSystem.WasmExample/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | KristofferStrube.Blazor.FileSystem.WasmExample 8 | 9 | 10 | 32 | 43 | 49 | 50 | 51 | 52 | 53 | 54 | 55 |
Loading...
56 | 57 |
58 | An unhandled error has occurred. 59 | Reload 60 | 🗙 61 |
62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/BaseJSWrapper.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.FileSystem.Extensions; 2 | using Microsoft.JSInterop; 3 | 4 | namespace KristofferStrube.Blazor.FileSystem; 5 | 6 | public abstract class BaseJSWrapper : IAsyncDisposable 7 | { 8 | protected readonly Lazy> helperTask; 9 | protected readonly IJSRuntime jSRuntime; 10 | protected readonly FileSystemOptions options; 11 | 12 | /// 13 | /// Constructs a wrapper instance for an equivalent JS instance. 14 | /// 15 | /// An instance. 16 | /// A JS reference to an existing JS instance that should be wrapped. 17 | internal BaseJSWrapper(IJSRuntime jSRuntime, IJSObjectReference jSReference, FileSystemOptions options) 18 | { 19 | this.options = options; 20 | helperTask = new(async () => await jSRuntime.GetHelperAsync(options)); 21 | JSReference = jSReference; 22 | this.jSRuntime = jSRuntime; 23 | } 24 | 25 | public IJSObjectReference JSReference { get; } 26 | 27 | public async ValueTask DisposeAsync() 28 | { 29 | if (helperTask.IsValueCreated) 30 | { 31 | IJSObjectReference module = await helperTask.Value; 32 | await module.DisposeAsync(); 33 | } 34 | GC.SuppressFinalize(this); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/Converters/BlobConverter.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.FileAPI; 2 | using System.Text.Json; 3 | using System.Text.Json.Serialization; 4 | 5 | namespace KristofferStrube.Blazor.FileSystem.Converters; 6 | 7 | internal class BlobConverter : JsonConverter 8 | { 9 | public override Blob Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 10 | { 11 | throw new NotSupportedException("Does not support deserializing Blobs"); 12 | } 13 | 14 | public override void Write(Utf8JsonWriter writer, Blob value, JsonSerializerOptions options) 15 | { 16 | JsonSerializer.Serialize(writer, value.JSReference, options); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/EnumDescriptionConverter.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Reflection; 3 | using System.Text.Json; 4 | using System.Text.Json.Serialization; 5 | 6 | namespace KristofferStrube.Blazor.FileSystem; 7 | 8 | #pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. 9 | #pragma warning disable CS8603 // Possible null reference return. 10 | #pragma warning disable CS8604 // Possible null reference argument. 11 | #pragma warning disable CS8602 // Dereference of a possibly null reference. 12 | internal class EnumDescriptionConverter : JsonConverter where T : IComparable, IFormattable, IConvertible 13 | { 14 | public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 15 | { 16 | string jsonValue = reader.GetString(); 17 | 18 | foreach (FieldInfo? fi in typeToConvert.GetFields()) 19 | { 20 | DescriptionAttribute description = (DescriptionAttribute)fi.GetCustomAttribute(typeof(DescriptionAttribute), false); 21 | 22 | if (description != null) 23 | { 24 | if (description.Description == jsonValue) 25 | { 26 | return (T)fi.GetValue(null); 27 | } 28 | } 29 | } 30 | throw new JsonException($"string {jsonValue} was not found as a description in the enum {typeToConvert}"); 31 | } 32 | 33 | public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) 34 | { 35 | FieldInfo fi = value.GetType().GetField(value.ToString()); 36 | 37 | DescriptionAttribute description = (DescriptionAttribute)fi.GetCustomAttribute(typeof(DescriptionAttribute), false); 38 | 39 | writer.WriteStringValue(description.Description); 40 | } 41 | } 42 | #pragma warning restore CS8602 // Dereference of a possibly null reference. 43 | #pragma warning restore CS8604 // Possible null reference argument. 44 | #pragma warning restore CS8603 // Possible null reference return. 45 | #pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type. -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/Enums/FileSystemCreateWritableOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem; 4 | 5 | /// 6 | /// FileSystemCreateWritableOptions browser specs 7 | /// 8 | public class FileSystemCreateWritableOptions 9 | { 10 | [JsonPropertyName("keepExistingData")] 11 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] 12 | public bool KeepExistingData { get; set; } 13 | } 14 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/Enums/FileSystemHandleKind.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace KristofferStrube.Blazor.FileSystem; 5 | 6 | /// 7 | /// FileSystemHandleKind browser specs 8 | /// 9 | [JsonConverter(typeof(EnumDescriptionConverter))] 10 | public enum FileSystemHandleKind 11 | { 12 | [Description("file")] 13 | File, 14 | [Description("directory")] 15 | Directory, 16 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/Enums/WriteCommandType.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace KristofferStrube.Blazor.FileSystem; 5 | 6 | /// 7 | /// WriteCommandType browser specs 8 | /// 9 | [JsonConverter(typeof(EnumDescriptionConverter))] 10 | public enum WriteCommandType 11 | { 12 | [Description("write")] 13 | Write, 14 | [Description("seek")] 15 | Seek, 16 | [Description("truncate")] 17 | Truncate, 18 | } 19 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/Extensions/IJSRuntimeExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem.Extensions; 4 | 5 | internal static class IJSRuntimeExtensions 6 | { 7 | internal static async Task GetHelperAsync(this IJSRuntime jSRuntime, FileSystemOptions options) 8 | { 9 | return await GetHelperAsync(jSRuntime, options); 10 | } 11 | 12 | internal static async Task GetInProcessHelperAsync(this IJSRuntime jSRuntime, FileSystemOptions options) 13 | { 14 | return await GetHelperAsync(jSRuntime, options); 15 | } 16 | 17 | private static async Task GetHelperAsync(IJSRuntime jSRuntime, FileSystemOptions options) 18 | { 19 | return await jSRuntime.InvokeAsync("import", GetScriptPath(options)); 20 | } 21 | 22 | private static string GetScriptPath(FileSystemOptions options) 23 | { 24 | return options.FullScriptPath; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/Extensions/IServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem; 4 | 5 | public static class IServiceCollectionExtensions 6 | { 7 | public static IServiceCollection AddStorageManagerService(this IServiceCollection serviceCollection) 8 | { 9 | return AddStorageManagerService(serviceCollection, null); 10 | } 11 | 12 | public static IServiceCollection AddStorageManagerService(this IServiceCollection serviceCollection, Action? configure) 13 | { 14 | ConfigureFsOptions(serviceCollection, configure); 15 | 16 | return serviceCollection.AddScoped(); 17 | } 18 | 19 | public static IServiceCollection AddStorageManagerServiceInProcess(this IServiceCollection serviceCollection) 20 | { 21 | return AddStorageManagerServiceInProcess(serviceCollection, null); 22 | } 23 | 24 | public static IServiceCollection AddStorageManagerServiceInProcess(this IServiceCollection serviceCollection, Action? configure) 25 | { 26 | ConfigureFsOptions(serviceCollection, configure); 27 | 28 | return serviceCollection 29 | .AddScoped() 30 | .AddScoped(sp => 31 | { 32 | IStorageManagerServiceInProcess service = sp.GetRequiredService(); 33 | return (IStorageManagerService)service; 34 | }); 35 | } 36 | 37 | private static void ConfigureFsOptions(IServiceCollection services, Action? configure) 38 | { 39 | if (configure is null) { return; } 40 | 41 | services.Configure(configure); 42 | configure(FileSystemOptions.DefaultInstance); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/FileSystemDirectoryHandle.InProcess.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.FileSystem.Extensions; 2 | using Microsoft.JSInterop; 3 | 4 | namespace KristofferStrube.Blazor.FileSystem; 5 | 6 | /// 7 | /// FileSystemDirectoryHandle browser specs 8 | /// 9 | public class FileSystemDirectoryHandleInProcess : FileSystemDirectoryHandle, IFileSystemHandleInProcess 10 | { 11 | public new IJSInProcessObjectReference JSReference; 12 | protected readonly IJSInProcessObjectReference inProcessHelper; 13 | 14 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference) 15 | { 16 | return await CreateAsync(jSRuntime, jSReference, FileSystemOptions.DefaultInstance); 17 | } 18 | 19 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference, FileSystemOptions options) 20 | { 21 | IJSInProcessObjectReference inProcessHelper = await jSRuntime.GetInProcessHelperAsync(options); 22 | return new FileSystemDirectoryHandleInProcess(jSRuntime, inProcessHelper, jSReference, options); 23 | } 24 | 25 | internal FileSystemDirectoryHandleInProcess(IJSRuntime jSRuntime, IJSInProcessObjectReference inProcessHelper, IJSInProcessObjectReference jSReference, FileSystemOptions options) : base(jSRuntime, jSReference, options) 26 | { 27 | this.inProcessHelper = inProcessHelper; 28 | JSReference = jSReference; 29 | } 30 | 31 | public FileSystemHandleKind Kind => inProcessHelper.Invoke("getAttribute", JSReference, "kind"); 32 | 33 | public string Name => inProcessHelper.Invoke("getAttribute", JSReference, "name"); 34 | 35 | public new async Task ValuesAsync() 36 | { 37 | IJSObjectReference helper = await helperTask.Value; 38 | IJSObjectReference jSValues = await JSReference.InvokeAsync("values"); 39 | IJSObjectReference jSEntries = await helper.InvokeAsync("arrayFrom", jSValues); 40 | int length = await helper.InvokeAsync("size", jSEntries); 41 | return await Task.WhenAll( 42 | Enumerable 43 | .Range(0, length) 44 | .Select>(async i => 45 | { 46 | var fileSystemHandle = await FileSystemHandleInProcess.CreateAsync( 47 | jSRuntime, 48 | await jSEntries.InvokeAsync("at", i), 49 | options); 50 | return (fileSystemHandle.Kind is FileSystemHandleKind.File) 51 | ? await FileSystemFileHandleInProcess.CreateAsync(jSRuntime, fileSystemHandle.JSReference, options) 52 | : await FileSystemDirectoryHandleInProcess.CreateAsync(jSRuntime, fileSystemHandle.JSReference, options); 53 | } 54 | ) 55 | .ToArray() 56 | ); 57 | } 58 | 59 | public new async Task GetFileHandleAsync(string name, FileSystemGetFileOptions? options = null) 60 | { 61 | IJSInProcessObjectReference jSFileSystemFileHandle = await JSReference.InvokeAsync("getFileHandle", name, options); 62 | return new FileSystemFileHandleInProcess(jSRuntime, inProcessHelper, jSFileSystemFileHandle, this.options); 63 | } 64 | 65 | public new async Task GetDirectoryHandleAsync(string name, FileSystemGetDirectoryOptions? options = null) 66 | { 67 | IJSInProcessObjectReference jSFileSystemDirectoryHandle = await JSReference.InvokeAsync("getDirectoryHandle", name, options); 68 | return new FileSystemDirectoryHandleInProcess(jSRuntime, inProcessHelper, jSFileSystemDirectoryHandle, this.options); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/FileSystemDirectoryHandle.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem; 4 | 5 | /// 6 | /// FileSystemDirectoryHandle browser specs 7 | /// 8 | public class FileSystemDirectoryHandle : FileSystemHandle 9 | { 10 | public static new FileSystemDirectoryHandle Create(IJSRuntime jSRuntime, IJSObjectReference jSReference) 11 | { 12 | return Create(jSRuntime, jSReference, FileSystemOptions.DefaultInstance); 13 | } 14 | 15 | public static new FileSystemDirectoryHandle Create(IJSRuntime jSRuntime, IJSObjectReference jSReference, FileSystemOptions options) 16 | { 17 | return new(jSRuntime, jSReference, options); 18 | } 19 | 20 | internal FileSystemDirectoryHandle(IJSRuntime jSRuntime, IJSObjectReference jSReference, FileSystemOptions options) : base(jSRuntime, jSReference, options) { } 21 | 22 | public async Task ValuesAsync() 23 | { 24 | IJSObjectReference helper = await helperTask.Value; 25 | IJSObjectReference jSValues = await JSReference.InvokeAsync("values"); 26 | IJSObjectReference jSEntries = await helper.InvokeAsync("arrayFrom", jSValues); 27 | int length = await helper.InvokeAsync("size", jSEntries); 28 | return await Task.WhenAll( 29 | Enumerable 30 | .Range(0, length) 31 | .Select>(async i => 32 | { 33 | var fileSystemHandle = new FileSystemHandle( 34 | jSRuntime, 35 | await jSEntries.InvokeAsync("at", i), 36 | options); 37 | return (await fileSystemHandle.GetKindAsync() is FileSystemHandleKind.File) 38 | ? FileSystemFileHandle.Create(jSRuntime, fileSystemHandle.JSReference, options) 39 | : FileSystemDirectoryHandle.Create(jSRuntime, fileSystemHandle.JSReference, options); 40 | } 41 | ) 42 | .ToArray() 43 | ); 44 | } 45 | 46 | public async Task GetFileHandleAsync(string name, FileSystemGetFileOptions? options = null) 47 | { 48 | IJSObjectReference jSFileSystemFileHandle = await JSReference.InvokeAsync("getFileHandle", name, options); 49 | return new FileSystemFileHandle(jSRuntime, jSFileSystemFileHandle, this.options); 50 | } 51 | 52 | public async Task GetDirectoryHandleAsync(string name, FileSystemGetDirectoryOptions? options = null) 53 | { 54 | IJSObjectReference jSFileSystemDirectoryHandle = await JSReference.InvokeAsync("getDirectoryHandle", name, options); 55 | return new FileSystemDirectoryHandle(jSRuntime, jSFileSystemDirectoryHandle, this.options); 56 | } 57 | 58 | public async Task RemoveEntryAsync(string name, FileSystemRemoveOptions? options = null) 59 | { 60 | await JSReference.InvokeVoidAsync("removeEntry", name, options); 61 | } 62 | 63 | public async Task ResolveAsync(IFileSystemHandle possibleDescendant) 64 | { 65 | return await JSReference.InvokeAsync("resolve", possibleDescendant.JSReference); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/FileSystemFileHandle.InProcess.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.FileAPI; 2 | using KristofferStrube.Blazor.FileSystem.Extensions; 3 | using Microsoft.JSInterop; 4 | 5 | namespace KristofferStrube.Blazor.FileSystem; 6 | 7 | /// 8 | /// FileSystemFileHandle browser specs 9 | /// 10 | public class FileSystemFileHandleInProcess : FileSystemFileHandle, IFileSystemHandleInProcess 11 | { 12 | public new IJSInProcessObjectReference JSReference; 13 | protected readonly IJSInProcessObjectReference inProcessHelper; 14 | 15 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference) 16 | { 17 | return await CreateAsync(jSRuntime, jSReference, FileSystemOptions.DefaultInstance); 18 | } 19 | 20 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference, FileSystemOptions options) 21 | { 22 | IJSInProcessObjectReference inProcessHelper = await jSRuntime.GetInProcessHelperAsync(options); 23 | return new FileSystemFileHandleInProcess(jSRuntime, inProcessHelper, jSReference, options); 24 | } 25 | 26 | internal FileSystemFileHandleInProcess(IJSRuntime jSRuntime, IJSInProcessObjectReference inProcessHelper, IJSInProcessObjectReference jSReference, FileSystemOptions options) : base(jSRuntime, jSReference, options) 27 | { 28 | this.inProcessHelper = inProcessHelper; 29 | JSReference = jSReference; 30 | } 31 | 32 | public FileSystemHandleKind Kind => inProcessHelper.Invoke("getAttribute", JSReference, "kind"); 33 | 34 | public string Name => inProcessHelper.Invoke("getAttribute", JSReference, "name"); 35 | 36 | public new async Task GetFileAsync() 37 | { 38 | IJSInProcessObjectReference jSFile = await JSReference.InvokeAsync("getFile"); 39 | return await FileInProcess.CreateAsync(jSRuntime, jSFile); 40 | } 41 | 42 | public new async Task CreateWritableAsync(FileSystemCreateWritableOptions? fileSystemCreateWritableOptions = null) 43 | { 44 | IJSInProcessObjectReference jSFileSystemWritableFileStream = await JSReference.InvokeAsync("createWritable", fileSystemCreateWritableOptions); 45 | return new FileSystemWritableFileStreamInProcess(jSRuntime, inProcessHelper, jSFileSystemWritableFileStream); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/FileSystemFileHandle.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem; 4 | 5 | /// 6 | /// FileSystemFileHandle browser specs 7 | /// 8 | public class FileSystemFileHandle : FileSystemHandle 9 | { 10 | public static new FileSystemFileHandle Create(IJSRuntime jSRuntime, IJSObjectReference jSReference) 11 | { 12 | return Create(jSRuntime, jSReference, FileSystemOptions.DefaultInstance); 13 | } 14 | 15 | public static new FileSystemFileHandle Create(IJSRuntime jSRuntime, IJSObjectReference jSReference, FileSystemOptions options) 16 | { 17 | return new(jSRuntime, jSReference, options); 18 | } 19 | 20 | internal FileSystemFileHandle(IJSRuntime jSRuntime, IJSObjectReference jSReference, FileSystemOptions options) : base(jSRuntime, jSReference, options) { } 21 | 22 | public async Task GetFileAsync() 23 | { 24 | IJSObjectReference jSFile = await JSReference.InvokeAsync("getFile"); 25 | return FileAPI.File.Create(jSRuntime, jSFile); 26 | } 27 | 28 | public async Task CreateWritableAsync(FileSystemCreateWritableOptions? fileSystemCreateWritableOptions = null) 29 | { 30 | IJSObjectReference jSFileSystemWritableFileStream = await JSReference.InvokeAsync("createWritable", fileSystemCreateWritableOptions); 31 | return await FileSystemWritableFileStream.CreateAsync(jSRuntime, jSFileSystemWritableFileStream); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/FileSystemHandle.InProcess.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.FileSystem.Extensions; 2 | using Microsoft.JSInterop; 3 | 4 | namespace KristofferStrube.Blazor.FileSystem; 5 | 6 | /// 7 | /// FileSystemHandle browser specs 8 | /// 9 | public class FileSystemHandleInProcess : FileSystemHandle, IFileSystemHandleInProcess 10 | { 11 | public new IJSInProcessObjectReference JSReference; 12 | protected readonly IJSInProcessObjectReference inProcessHelper; 13 | 14 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference) 15 | { 16 | return await CreateAsync(jSRuntime, jSReference, FileSystemOptions.DefaultInstance); 17 | } 18 | 19 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference, FileSystemOptions options) 20 | { 21 | IJSInProcessObjectReference inProcessHelper = await jSRuntime.GetInProcessHelperAsync(options); 22 | return new FileSystemHandleInProcess(jSRuntime, inProcessHelper, jSReference, options); 23 | } 24 | 25 | internal FileSystemHandleInProcess(IJSRuntime jSRuntime, IJSInProcessObjectReference inProcessHelper, IJSInProcessObjectReference jSReference, FileSystemOptions options) : base(jSRuntime, jSReference, options) 26 | { 27 | this.inProcessHelper = inProcessHelper; 28 | JSReference = jSReference; 29 | } 30 | 31 | public FileSystemHandleKind Kind => inProcessHelper.Invoke("getAttribute", JSReference, "kind"); 32 | 33 | public string Name => inProcessHelper.Invoke("getAttribute", JSReference, "name"); 34 | } 35 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/FileSystemHandle.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem; 4 | 5 | /// 6 | /// FileSystemHandle browser specs 7 | /// 8 | public class FileSystemHandle : BaseJSWrapper, IFileSystemHandle 9 | { 10 | public static FileSystemHandle Create(IJSRuntime jSRuntime, IJSObjectReference jSReference) 11 | { 12 | return Create(jSRuntime, jSReference, FileSystemOptions.DefaultInstance); 13 | } 14 | 15 | public static FileSystemHandle Create(IJSRuntime jSRuntime, IJSObjectReference jSReference, FileSystemOptions options) 16 | { 17 | return new(jSRuntime, jSReference, options); 18 | } 19 | 20 | internal FileSystemHandle(IJSRuntime jSRuntime, IJSObjectReference jSReference, FileSystemOptions options) : base(jSRuntime, jSReference, options) { } 21 | 22 | public async Task GetKindAsync() 23 | { 24 | IJSObjectReference helper = await helperTask.Value; 25 | return await helper.InvokeAsync("getAttribute", JSReference, "kind"); 26 | } 27 | 28 | public async Task GetNameAsync() 29 | { 30 | IJSObjectReference helper = await helperTask.Value; 31 | return await helper.InvokeAsync("getAttribute", JSReference, "name"); 32 | } 33 | 34 | public async Task IsSameEntryAsync(IFileSystemHandle other) 35 | { 36 | return await JSReference.InvokeAsync("isSameEntry", other.JSReference); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/FileSystemWritableFileStream.InProcess.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.FileSystem.Extensions; 2 | using Microsoft.JSInterop; 3 | 4 | namespace KristofferStrube.Blazor.FileSystem; 5 | 6 | /// 7 | /// FileSystemWritableFileStream browser specs 8 | /// 9 | public class FileSystemWritableFileStreamInProcess : FileSystemWritableFileStream 10 | { 11 | public new IJSInProcessObjectReference JSReference; 12 | protected readonly IJSInProcessObjectReference inProcessHelper; 13 | 14 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference) 15 | { 16 | return await CreateAsync(jSRuntime, jSReference, FileSystemOptions.DefaultInstance); 17 | } 18 | 19 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference, FileSystemOptions options) 20 | { 21 | IJSInProcessObjectReference inProcessHelper = await jSRuntime.GetInProcessHelperAsync(options); 22 | return new FileSystemWritableFileStreamInProcess(jSRuntime, inProcessHelper, jSReference); 23 | } 24 | 25 | internal FileSystemWritableFileStreamInProcess(IJSRuntime jSRuntime, IJSInProcessObjectReference inProcessHelper, IJSInProcessObjectReference jSReference) : base(jSRuntime, jSReference) 26 | { 27 | this.inProcessHelper = inProcessHelper; 28 | JSReference = jSReference; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/FileSystemWritableFileStream.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.FileAPI; 2 | using KristofferStrube.Blazor.FileSystem.Extensions; 3 | using KristofferStrube.Blazor.Streams; 4 | using Microsoft.JSInterop; 5 | 6 | namespace KristofferStrube.Blazor.FileSystem; 7 | 8 | /// 9 | /// FileSystemWritableFileStream browser specs 10 | /// 11 | public class FileSystemWritableFileStream : WritableStream 12 | { 13 | /// 14 | /// A lazily evaluated task that gives access to helper methods for the File System API. 15 | /// 16 | protected readonly Lazy> fileSystemHelperTask; 17 | 18 | public override bool CanSeek => true; 19 | 20 | public override long Position { get; set; } 21 | 22 | [Obsolete("This will be removed in the next major release as all creator methods should be asynchronous for uniformity. Use CreateAsync instead.")] 23 | public static new FileSystemWritableFileStream Create(IJSRuntime jSRuntime, IJSObjectReference jSReference) 24 | { 25 | return new FileSystemWritableFileStream(jSRuntime, jSReference); 26 | } 27 | 28 | public static new Task CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference) 29 | { 30 | return Task.FromResult(new FileSystemWritableFileStream(jSRuntime, jSReference)); 31 | } 32 | 33 | protected FileSystemWritableFileStream(IJSRuntime jSRuntime, IJSObjectReference jSReference) : base(jSRuntime, jSReference) 34 | { 35 | fileSystemHelperTask = new(() => jSRuntime.GetHelperAsync(FileSystemOptions.DefaultInstance)); 36 | } 37 | 38 | public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) 39 | { 40 | await JSReference.InvokeVoidAsync("write", buffer.ToArray()); 41 | } 42 | 43 | public async Task WriteAsync(string data) 44 | { 45 | await JSReference.InvokeVoidAsync("write", data); 46 | } 47 | 48 | public async Task WriteAsync(byte[] data) 49 | { 50 | await JSReference.InvokeVoidAsync("write", data); 51 | } 52 | 53 | public async Task WriteAsync(Blob data) 54 | { 55 | await JSReference.InvokeVoidAsync("write", data.JSReference); 56 | } 57 | 58 | public async Task WriteAsync(BlobWriteParams data) 59 | { 60 | await JSReference.InvokeVoidAsync("write", data); 61 | } 62 | 63 | public async Task WriteAsync(StringWriteParams data) 64 | { 65 | await JSReference.InvokeVoidAsync("write", data); 66 | } 67 | 68 | public async Task WriteAsync(ByteArrayWriteParams data) 69 | { 70 | await JSReference.InvokeVoidAsync("write", data); 71 | } 72 | 73 | public async Task SeekAsync(ulong position) 74 | { 75 | Position = (long)position; 76 | await JSReference.InvokeVoidAsync("seek", position); 77 | } 78 | 79 | public async Task TruncateAsync(ulong size) 80 | { 81 | await JSReference.InvokeVoidAsync("truncate", size); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/IFileSystemHandle.InProcess.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.FileSystem; 2 | 3 | public interface IFileSystemHandleInProcess : IFileSystemHandle 4 | { 5 | FileSystemHandleKind Kind { get; } 6 | string Name { get; } 7 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/IFileSystemHandle.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem; 4 | 5 | public interface IFileSystemHandle 6 | { 7 | public IJSObjectReference JSReference { get; } 8 | Task GetKindAsync(); 9 | Task GetNameAsync(); 10 | Task IsSameEntryAsync(IFileSystemHandle other); 11 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/IStorageManagerService.InProcess.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.FileSystem; 2 | 3 | public interface IStorageManagerServiceInProcess : IStorageManagerService 4 | { 5 | new Task GetOriginPrivateDirectoryAsync(); 6 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/IStorageManagerService.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.FileSystem; 2 | 3 | public interface IStorageManagerService 4 | { 5 | Task GetOriginPrivateDirectoryAsync(); 6 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/KristofferStrube.Blazor.FileSystem.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | enable 6 | enable 7 | Blazor File System API wrapper 8 | File System API wrapper implementation for Blazor. 9 | KristofferStrube.Blazor.FileSystem 10 | Blazor;Wasm;Wrapper;FileSystemAPI;FileSystem;File;JSInterop 11 | https://github.com/KristofferStrube/Blazor.FileSystem 12 | git 13 | MIT 14 | 0.3.1 15 | Kristoffer Strube 16 | README.md 17 | icon.png 18 | true 19 | 20 | 21 | 22 | 23 | True 24 | \ 25 | 26 | 27 | True 28 | \ 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/Options/FileSystemGetDirectoryOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem; 4 | 5 | /// 6 | /// FileSystemGetDirectoryOptions browser specs 7 | /// 8 | public class FileSystemGetDirectoryOptions 9 | { 10 | [JsonPropertyName("create")] 11 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] 12 | public bool Create { get; set; } 13 | } 14 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/Options/FileSystemGetFileOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem; 4 | 5 | /// 6 | /// FileSystemGetFileOptions browser specs 7 | /// 8 | public class FileSystemGetFileOptions 9 | { 10 | [JsonPropertyName("create")] 11 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] 12 | public bool Create { get; set; } 13 | } 14 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/Options/FileSystemOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem; 4 | 5 | public class FileSystemOptions 6 | { 7 | public const string DefaultBasePath = "./_content/"; 8 | public static readonly string DefaultNamespace = Assembly.GetExecutingAssembly().GetName().Name ?? "KristofferStrube.Blazor.FileSystem"; 9 | public static readonly string DefaultScriptPath = $"{DefaultNamespace}/{DefaultNamespace}.js"; 10 | 11 | public string BasePath { get; set; } = DefaultBasePath; 12 | public string ScriptPath { get; set; } = DefaultScriptPath; 13 | 14 | public string FullScriptPath => Path.Combine(this.BasePath, this.ScriptPath); 15 | 16 | internal static FileSystemOptions DefaultInstance = new(); 17 | 18 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/Options/FileSystemRemoveOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem; 4 | 5 | /// 6 | /// FileSystemRemoveOptions browser specs 7 | /// 8 | public class FileSystemRemoveOptions 9 | { 10 | [JsonPropertyName("recursive")] 11 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] 12 | public bool Recursive { get; set; } 13 | } 14 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/Options/WriteParams.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.FileAPI; 2 | using KristofferStrube.Blazor.FileSystem.Converters; 3 | using System.Text.Json.Serialization; 4 | 5 | namespace KristofferStrube.Blazor.FileSystem; 6 | 7 | public class BlobWriteParams : BaseWriteParams 8 | { 9 | public BlobWriteParams(WriteCommandType type) 10 | { 11 | Type = type; 12 | } 13 | 14 | [JsonPropertyName("data")] 15 | [JsonConverter(typeof(BlobConverter))] 16 | public Blob? Data { get; set; } 17 | } 18 | 19 | public class StringWriteParams : BaseWriteParams 20 | { 21 | public StringWriteParams(WriteCommandType type) 22 | { 23 | Type = type; 24 | } 25 | 26 | [JsonPropertyName("data")] 27 | public string? Data { get; set; } 28 | } 29 | 30 | public class ByteArrayWriteParams : BaseWriteParams 31 | { 32 | public ByteArrayWriteParams(WriteCommandType type) 33 | { 34 | Type = type; 35 | } 36 | 37 | [JsonPropertyName("data")] 38 | public byte[]? Data { get; set; } 39 | } 40 | 41 | public abstract class BaseWriteParams 42 | { 43 | [JsonPropertyName("type")] 44 | public WriteCommandType Type { get; init; } 45 | 46 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] 47 | [JsonPropertyName("size")] 48 | public ulong Size { get; set; } 49 | 50 | [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] 51 | [JsonPropertyName("position")] 52 | public ulong Position { get; set; } 53 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/StorageManagerService.InProcess.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.FileSystem; 4 | 5 | public class StorageManagerServiceInProcess : StorageManagerService, IStorageManagerServiceInProcess 6 | { 7 | public StorageManagerServiceInProcess(IJSRuntime jSRuntime) : base(jSRuntime) { } 8 | 9 | /// 10 | /// getDirectory() for StorageManager browser specs 11 | /// 12 | /// 13 | public new async Task GetOriginPrivateDirectoryAsync() 14 | { 15 | return await GetOriginPrivateDirectoryAsync(FileSystemOptions.DefaultInstance); 16 | } 17 | 18 | /// 19 | /// getDirectory() for StorageManager browser specs 20 | /// 21 | /// 22 | public new async Task GetOriginPrivateDirectoryAsync(FileSystemOptions options) 23 | { 24 | IJSInProcessObjectReference directoryHandle = await jSRuntime.InvokeAsync("navigator.storage.getDirectory"); 25 | return await FileSystemDirectoryHandleInProcess.CreateAsync(jSRuntime, directoryHandle, options); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/StorageManagerService.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.FileSystem.Extensions; 2 | using Microsoft.Extensions.Options; 3 | using Microsoft.JSInterop; 4 | 5 | namespace KristofferStrube.Blazor.FileSystem; 6 | 7 | public class StorageManagerService : IStorageManagerService 8 | { 9 | protected readonly Lazy> helperTask; 10 | protected readonly IJSRuntime jSRuntime; 11 | 12 | public StorageManagerService(IJSRuntime jSRuntime) 13 | { 14 | helperTask = new(() => jSRuntime.GetHelperAsync(FileSystemOptions.DefaultInstance)); 15 | this.jSRuntime = jSRuntime; 16 | } 17 | 18 | /// 19 | /// getDirectory() for StorageManager browser specs 20 | /// 21 | /// 22 | public async Task GetOriginPrivateDirectoryAsync() 23 | { 24 | return await GetOriginPrivateDirectoryAsync(FileSystemOptions.DefaultInstance); 25 | } 26 | 27 | /// 28 | /// getDirectory() for StorageManager browser specs 29 | /// 30 | /// 31 | public async Task GetOriginPrivateDirectoryAsync(FileSystemOptions options) 32 | { 33 | IJSObjectReference directoryHandle = await jSRuntime.InvokeAsync("navigator.storage.getDirectory"); 34 | return new FileSystemDirectoryHandle(jSRuntime, directoryHandle, options); 35 | } 36 | 37 | public async ValueTask DisposeAsync() 38 | { 39 | if (helperTask.IsValueCreated) 40 | { 41 | IJSObjectReference module = await helperTask.Value; 42 | await module.DisposeAsync(); 43 | } 44 | GC.SuppressFinalize(this); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileSystem/wwwroot/KristofferStrube.Blazor.FileSystem.js: -------------------------------------------------------------------------------- 1 | export function size(array) { return array.length; } 2 | 3 | export function getAttribute(object, attribute) { return object[attribute]; } 4 | 5 | export async function arrayFrom(values) { 6 | var res = [] 7 | for await (let value of values) { 8 | res.push(value); 9 | } 10 | return res; 11 | } 12 | 13 | export async function arrayBuffer(blob) { 14 | var buffer = await blob.arrayBuffer(); 15 | var bytes = new Uint8Array(buffer); 16 | return bytes; 17 | } --------------------------------------------------------------------------------