-
-
Notifications
You must be signed in to change notification settings - Fork 139
/
Main.hs
87 lines (75 loc) · 2.12 KB
/
Main.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
module Main where
import Miso hiding (asyncCallback)
import Miso.String
import Control.Concurrent.MVar
import GHCJS.Types
import GHCJS.Foreign.Callback
-- | Model
data Model
= Model
{ info :: MisoString
} deriving (Eq, Show)
-- | Action
data Action
= ReadFile
| NoOp
| SetContent MisoString
deriving (Show, Eq)
-- | Main entry point
main :: IO ()
main = do
startApp App { model = Model ""
, initialAction = NoOp
, ..
}
where
mountPoint = Nothing
update = updateModel
events = defaultEvents
subs = []
view = viewModel
logLevel = Off
-- | Update your model
updateModel :: Action -> Model -> Effect Action Model
updateModel ReadFile m = m <# do
fileReaderInput <- getElementById "fileReader"
file <- getFile fileReaderInput
reader <- newReader
mvar <- newEmptyMVar
setOnLoad reader =<< do
asyncCallback $ do
r <- getResult reader
putMVar mvar r
readText reader file
SetContent <$> readMVar mvar
updateModel (SetContent c) m = noEff m { info = c }
updateModel NoOp m = noEff m
-- | View function, with routing
viewModel :: Model -> View Action
viewModel Model {..} = view
where
view = div_ [] [
"FileReader API example"
, input_ [ id_ "fileReader"
, type_ "file"
, onChange (const ReadFile)
]
, div_ [] [ text info ]
]
foreign import javascript unsafe "$r = new FileReader();"
newReader :: IO JSVal
foreign import javascript unsafe "$r = $1.files[0];"
getFile :: JSVal -> IO JSVal
foreign import javascript unsafe "$1.onload = $2;"
setOnLoad :: JSVal -> Callback (IO ()) -> IO ()
foreign import javascript unsafe "$r = $1.result;"
getResult :: JSVal -> IO MisoString
foreign import javascript unsafe "$1.readAsText($2);"
readText :: JSVal -> JSVal -> IO ()