Skip to content

Instantly share code, notes, and snippets.

@newton-migosi
Created June 10, 2021 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save newton-migosi/988450dff99185703c5d6934f9d4364a to your computer and use it in GitHub Desktop.
Save newton-migosi/988450dff99185703c5d6934f9d4364a to your computer and use it in GitHub Desktop.
Purescript Video Component
module App.Video (component) where
-- import Control.Monad (class Bind)
import DOM.HTML.Indexed.InputAcceptType (InputAcceptType, InputAcceptTypeAtom(..))
import Data.Foldable (traverse_)
import Data.Maybe (Maybe(..))
import Data.MediaType (MediaType(..))
import Data.Traversable (for_)
import Effect.Aff.Class (class MonadAff)
import Halogen as H
import Halogen.HTML as HH
import Halogen.HTML.Events as HE
import Halogen.HTML.Properties as HP
import Prelude (Unit, bind, const, discard, pure, unit, ($), (=<<), (>>=))
import Web.Event.Event as Event
import Web.Event.Internal.Types (Event)
import Web.File.File as File
import Web.File.FileList as FileList
import Web.File.FileReader.Aff as FileReaderAff
import Web.HTML.HTMLInputElement as InputElement
data Action = HandleFileUpload Event
type State =
{ videoUrl :: Maybe String }
component :: forall q i o m. MonadAff m => H.Component q i o m
component =
H.mkComponent
{ initialState
, render
, eval: H.mkEval $ H.defaultEval { handleAction = handleAction }
}
initialState :: forall i. i -> State
initialState _ =
{ videoUrl : Nothing
}
render :: forall m slots. State -> H.ComponentHTML Action slots m
render state =
case state.videoUrl of
Nothing -> blank_player
Just url -> video_player url
supported_formats :: InputAcceptType
supported_formats =
HP.InputAcceptType
[ AcceptMediaType (MediaType "video/mp4")
, AcceptMediaType (MediaType "video/webm")
]
blank_player :: forall w. HH.HTML w Action
blank_player =
HH.div_ [
HH.span_ [HH.text "Choose file to upload"],
HH.input
[ HP.type_ HP.InputFile
, HP.accept supported_formats
, HP.value "Select Video..."
, HE.onChange HandleFileUpload
]
]
video_player :: forall w i. String -> HH.HTML w i
video_player url =
HH.div_ [
HH.video [HP.src url] []
]
handleAction :: forall m slots o. MonadAff m => Action -> H.HalogenM State Action slots o m Unit
handleAction = case _ of
HandleFileUpload ev → do
traverse_ handleFileUpload (InputElement.fromEventTarget =<< Event.target ev)
handleFileUpload :: forall m slots o. MonadAff m => InputElement.HTMLInputElement -> H.HalogenM State Action slots o m Unit
handleFileUpload inputEl = do
H.liftEffect (InputElement.files inputEl) >>= traverse_ \files ->
for_ (FileList.item 0 files) \file → do
video_url ← H.liftAff $ FileReaderAff.readAsDataURL (File.toBlob file)
H.modify_ (const { videoUrl : Just video_url})
pure unit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment