-
Notifications
You must be signed in to change notification settings - Fork 63
/
drag.elm
134 lines (92 loc) · 2.09 KB
/
drag.elm
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import Browser.Mouse as Mouse
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
-- MAIN
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
-- MODEL
type Model =
{ x : Int
, y : Int
, dragState : DragState
}
type DragState
= Static
| Moving Int Int Int Int
init : () -> (Model, Cmd Msg)
init _ =
( Model 100 100 Static
, Cmd.none
)
-- UPDATE
type Msg
= Start Int Int
| Move Int Int
| Stop Int Int
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
Start x y ->
( { model | dragState = Moving x y x y }
, Cmd.none
)
Move x y ->
case model.dragState of
Static ->
( model, Cmd.none )
Moving startX startY _ _ ->
( { model | dragState = Moving startX startY x y }
)
Stop x y ->
case model.dragState of
Static ->
( model, Cmd.none )
Moving startX startY _ _ ->
( Model (model.x + startX - x) (model.y + startY - y) Static
, Cmd.none
)
-- VIEW
view : Model -> Html Msg
view model =
let
(x, y) = getPosition model
in
div
[ style "background-color" "rgb(104,216,239)"
, style "position" "absolute"
, style "top" (String.fromInt x ++ "px")
, style "left" (String.fromInt y ++ "px")
, style "width" "100px"
, style "height" "100px"
, on "mousedown" (D.map2 Start pageX pageY)
, on "mouseup" (D.map2 Stop pageX pageY)
]
[ text "Drag me!"
]
getPosition : Model -> (Int, Int)
getPosition model =
case model.dragState of
Static ->
(model.x, model.y)
Moving startX startY endX endY ->
(x + startX - endX, y + startY - endY)
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
case model.dragState of
Static ->
Sub.none
Moving _ _ _ _ ->
Mouse.moves (D.map2 Move pageX pageY)
pageX : D.Decoder Int
pageX =
D.field "pageX" D.int
pageY : D.Decoder Int
pageY =
D.field "pageY" D.int