PurpleKingdomGames / tyrian

Elm-inspired Scala UI library.
https://tyrian.indigoengine.io/
MIT License
346 stars 26 forks source link

Text file converting to URI on read #233

Closed sloshy closed 8 months ago

sloshy commented 10 months ago

Was implementing a file upload functionality for a web app I'm working on in Tyrian, and thought I'd use the FileReader.readText built-in to read the file. This did not work exactly as I expected because my code after the upload was failing to parse the file. It seems that the implementation has some code-reuse by using the browser built-in FileReader#readAsDataUrl, which returns a URL suitable for linking or including as part of a web page but not for parsing.

This would be fine for that use case but I expected the behavior to be more like FileReader#readAsText which returns the raw text of the file. I implemented a helper that does something similar in my own program for reference:

private def uploadTextFile(fileId: String, f: String => Msg): Cmd[IO, Msg] =
  Cmd.Run {
    IO.fromFuture(IO {
      val fr = org.scalajs.dom.FileReader()
      val el = dom.document.getElementById(fileId).asInstanceOf[dom.html.Input]
      val file = el.files.item(0)
      val p = scala.concurrent.Promise[Msg]()
      fr.addEventListener(
        "load",
        { _ =>
          p.success(f(fr.result.asInstanceOf[String]))
        },
        false
      )
      fr.readAsText(file)
      p.future
    })
  }

Would be happy to contribute for this issue

davesmith00000 commented 10 months ago

Hey @sloshy!

Thanks for reporting. I'll always welcome a contribution if you'd like to! :grin:

Otherwise, I think I'm building up a few issues on Tyrian that need attention, so I expect I'll get around to this and other issues in the not to distant future.

davesmith00000 commented 8 months ago

I believe I've coincidentally fixed this in this PR: https://github.com/PurpleKingdomGames/tyrian/pull/239

davesmith00000 commented 8 months ago

Merged, will be fixed in the next release.

sloshy commented 8 months ago

Thanks a bunch @davesmith00000! I never did get around to working on this but I greatly appreciate the fix!