entities
listlengths 1
2.22k
| max_stars_repo_path
stringlengths 6
98
| max_stars_repo_name
stringlengths 9
55
| max_stars_count
int64 0
8.27k
| content
stringlengths 93
965k
| id
stringlengths 2
5
| new_content
stringlengths 85
964k
| modified
bool 1
class | references
stringlengths 98
970k
| language
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
[
{
"context": " input_user_name : UserName\n , input_password : Password\n , m_player : Maybe Player\n , players : Pla",
"end": 943,
"score": 0.9981837273,
"start": 935,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "ntId events\n , organizer_user_name = p.user_name\n , millis = pe.millis\n ",
"end": 4985,
"score": 0.5600952506,
"start": 4981,
"tag": "USERNAME",
"value": "user"
},
{
"context": "events\n , organizer_user_name = p.user_name\n , millis = pe.millis\n , ti",
"end": 4990,
"score": 0.5139844418,
"start": 4986,
"tag": "USERNAME",
"value": "name"
},
{
"context": "\nstartingPlayers =\n Dict.fromList\n [ ( \"Charlie\", newPlayer \"Charlie\" )\n , ( \"Jim\", newPla",
"end": 5347,
"score": 0.9991986752,
"start": 5340,
"tag": "NAME",
"value": "Charlie"
},
{
"context": " Dict.fromList\n [ ( \"Charlie\", newPlayer \"Charlie\" )\n , ( \"Jim\", newPlayer \"Jim\" )\n ,",
"end": 5368,
"score": 0.9993900657,
"start": 5361,
"tag": "NAME",
"value": "Charlie"
},
{
"context": "[ ( \"Charlie\", newPlayer \"Charlie\" )\n , ( \"Jim\", newPlayer \"Jim\" )\n , ( \"Bones\", newPlaye",
"end": 5388,
"score": 0.999807775,
"start": 5385,
"tag": "NAME",
"value": "Jim"
},
{
"context": "wPlayer \"Charlie\" )\n , ( \"Jim\", newPlayer \"Jim\" )\n , ( \"Bones\", newPlayer \"Bones\" )\n ",
"end": 5405,
"score": 0.9997023344,
"start": 5402,
"tag": "NAME",
"value": "Jim"
},
{
"context": " , { id = 1\n , organizer_user_name = \"Charlie\"\n , millis = 1595999011722\n ",
"end": 5682,
"score": 0.99949646,
"start": 5675,
"tag": "NAME",
"value": "Charlie"
},
{
"context": " Dict.fromList\n [ ( \"Jim\"\n , { for_user_name = \"Jim\"\n",
"end": 6052,
"score": 0.9997738004,
"start": 6049,
"tag": "NAME",
"value": "Jim"
},
{
"context": " \"Jim\"\n , { for_user_name = \"Jim\"\n , status = Pending\n ",
"end": 6100,
"score": 0.9996606708,
"start": 6097,
"tag": "NAME",
"value": "Jim"
},
{
"context": "Bones\"\n , { for_user_name = \"Bones\"\n , status = Accepted\n ",
"end": 6275,
"score": 0.9872348309,
"start": 6270,
"tag": "NAME",
"value": "Bones"
},
{
"context": " , { id = 2\n , organizer_user_name = \"Solo\"\n , millis = 1595999011722\n ",
"end": 6495,
"score": 0.983229816,
"start": 6491,
"tag": "USERNAME",
"value": "Solo"
},
{
"context": " Dict.fromList\n [ ( \"Jade\"\n , { for_user_name = \"Jade\"",
"end": 6842,
"score": 0.9940958023,
"start": 6838,
"tag": "NAME",
"value": "Jade"
},
{
"context": "\"Jade\"\n , { for_user_name = \"Jade\"\n , status = Declined\n ",
"end": 6891,
"score": 0.9972299933,
"start": 6887,
"tag": "NAME",
"value": "Jade"
},
{
"context": "\n )\n , ( \"Badger\"\n , { for_user_name = \"Badge",
"end": 7018,
"score": 0.9928580523,
"start": 7012,
"tag": "NAME",
"value": "Badger"
},
{
"context": "adger\"\n , { for_user_name = \"Badger\"\n , status = Pending\n ",
"end": 7069,
"score": 0.9868289232,
"start": 7063,
"tag": "NAME",
"value": "Badger"
},
{
"context": "\n )\n , ( \"Jim\"\n , { for_user_name = \"Jim\"\n",
"end": 7192,
"score": 0.9987056851,
"start": 7189,
"tag": "NAME",
"value": "Jim"
},
{
"context": " \"Jim\"\n , { for_user_name = \"Jim\"\n , status = Accepted\n ",
"end": 7240,
"score": 0.9990624785,
"start": 7237,
"tag": "NAME",
"value": "Jim"
},
{
"context": " , { id = 3\n , organizer_user_name = \"Jim\"\n , millis = 1599999011722\n ",
"end": 7459,
"score": 0.9982076883,
"start": 7456,
"tag": "NAME",
"value": "Jim"
},
{
"context": "\"Solo\"\n , { for_user_name = \"Solo\"\n , status = Pending\n ",
"end": 7878,
"score": 0.9456086755,
"start": 7874,
"tag": "NAME",
"value": "Solo"
},
{
"context": " )\n , ( \"Bones\"\n , { for_user_name = \"Bones",
"end": 8003,
"score": 0.838085413,
"start": 7999,
"tag": "NAME",
"value": "ones"
},
{
"context": "Bones\"\n , { for_user_name = \"Bones\"\n , status = Accepted\n ",
"end": 8053,
"score": 0.9308869839,
"start": 8048,
"tag": "NAME",
"value": "Bones"
},
{
"context": "\n )\n , ( \"Badger\"\n , { for_user_name = \"Badge",
"end": 8180,
"score": 0.9109756947,
"start": 8174,
"tag": "NAME",
"value": "Badger"
},
{
"context": "adger\"\n , { for_user_name = \"Badger\"\n , status = Pending\n ",
"end": 8231,
"score": 0.9255554676,
"start": 8225,
"tag": "NAME",
"value": "Badger"
},
{
"context": "\n )\n , ( \"Jade\"\n , { for_user_name = \"Jade\"",
"end": 8355,
"score": 0.9962049723,
"start": 8351,
"tag": "NAME",
"value": "Jade"
},
{
"context": "\"Jade\"\n , { for_user_name = \"Jade\"\n , status = Declined\n ",
"end": 8404,
"score": 0.9984767437,
"start": 8400,
"tag": "NAME",
"value": "Jade"
}
] | src/DataModel.elm | xeticode/shallweplay | 0 | module DataModel exposing (Event, EventId, EventStatus(..), Events, Invite, InviteStatus(..), Invites, LoginField(..), Model, Password, Player, PlayerPosition, Players, PossibleEvent, PossibleEventSetter(..), UserName, amITheOrganizer, clearPossibleEventInfo, defaultMillisForPossibleEvent, defaultModel, emptyPlayerPosition, eventsByPlayer, eventsForPlayer, isMaybeVec2WithinMaybeDomElement, isThisMe, maybeEventFromPossibleEvent, newInvite, newPlayer, newPossibleEvent, nextEventId, nextInviteStatusForInvite, nextInviteStatusForStatus, playerEvents, primePossibleEventWithMillis, saveAndClearPossibleEvent, startingEvents, startingPlayers, toggleEventStatus, toggleEventStatusById, toggleInviteStatusByEventId)
import Browser.Dom as Dom
import Dict exposing (Dict)
import Draggable as D
import List.Extra as LE
import Math.Vector2 as M
--
-- Model
--
type alias Model =
{ input_user_name : UserName
, input_password : Password
, m_player : Maybe Player
, players : Players
, events : Events
, m_possible_event : Maybe PossibleEvent
, m_poss_event_elem_info : Maybe Dom.Element
, login_offset : Float
, login_field_with_tab_index : LoginField
, dragged_player_position : PlayerPosition
, drag : D.State UserName
}
-- Player
type alias UserName =
String
type alias Password =
String
type alias PlayerPosition =
( Maybe UserName, Maybe M.Vec2 )
type alias Player =
{ user_name : UserName
, member_since : Int
}
type alias Players =
Dict UserName Player
-- Event
type alias EventId =
Int
type EventStatus
= Canceled
| Scheduled
type alias Event =
{ id : EventId
, organizer_user_name : UserName
, millis : Int
, title : String
, description : String
, venue : String
, status : EventStatus
, invites : Invites
}
type alias Events =
Dict Int Event
-- Invite
type InviteStatus
= Pending
| Accepted
| Declined
type alias Invite =
{ for_user_name : UserName
, status : InviteStatus
}
type alias Invites =
Dict UserName Invite
-- Possible Event
type alias PossibleEvent =
{ millis : Int
, title : String
, description : String
, venue : String
, invites : Invites
}
{-|
How do you update a single record property via Msg? We could have a separate
Msg variant for each property, but that would not be a good separation of
concerns between the Msg type and specific record details. We could have single Msg
where we pass a setter function along with the value, but that makes the Msg and update
handling more opaque during debugging.
I believe the most idiomatic approach is to create a type with variants for each
set operation driven by Msg, then have a single Msg that takes this type and a value
and then pattern match in a case statement on the setter type.
It's not much more verbose than passing a setter function, and keeps the Msg and
update handling completely transparent.
-}
type PossibleEventSetter
= MillisUp
| MillisDown
| Title
| Description
| Venue
-- Login Field
type LoginField
= UserNameField
| PasswordField
| NoField
--
-- Default Data - should go away once the DB is hooked up
--
defaultModel : Model
defaultModel =
{ input_user_name = ""
, input_password = ""
, m_player = Nothing
, players = startingPlayers
, events = startingEvents
, m_possible_event = Nothing
, m_poss_event_elem_info = Nothing
, login_offset = 0.0
, login_field_with_tab_index = UserNameField
, dragged_player_position = emptyPlayerPosition
, drag = D.init
}
emptyPlayerPosition : PlayerPosition
emptyPlayerPosition =
( Nothing, Nothing )
newPlayer : UserName -> Player
newPlayer user_name =
Player user_name 0
newInvite : UserName -> Invite
newInvite user_name =
Invite user_name Pending
defaultMillisForPossibleEvent : Int
defaultMillisForPossibleEvent =
0
newPossibleEvent : Int -> PossibleEvent
newPossibleEvent millis =
{ millis = millis
, title = ""
, description = ""
, venue = ""
, invites = Dict.empty
}
primePossibleEventWithMillis : Int -> PossibleEvent -> PossibleEvent
primePossibleEventWithMillis millis poss_event =
if defaultMillisForPossibleEvent == poss_event.millis then
{ poss_event | millis = millis }
else
poss_event
clearPossibleEventInfo : Model -> Model
clearPossibleEventInfo model =
{ model
| m_possible_event = Nothing
, m_poss_event_elem_info = Nothing
, dragged_player_position = emptyPlayerPosition
, drag = D.init
}
maybeEventFromPossibleEvent : Maybe Player -> Events -> Maybe PossibleEvent -> Maybe Event
maybeEventFromPossibleEvent m_player events m_possible_event =
Maybe.map2
(\p pe ->
{ id = nextEventId events
, organizer_user_name = p.user_name
, millis = pe.millis
, title = pe.title
, description = pe.description
, status = Scheduled
, venue = pe.venue
, invites = pe.invites
}
)
m_player
m_possible_event
startingPlayers : Players
startingPlayers =
Dict.fromList
[ ( "Charlie", newPlayer "Charlie" )
, ( "Jim", newPlayer "Jim" )
, ( "Bones", newPlayer "Bones" )
, ( "Solo", newPlayer "Solo" )
, ( "Badger", newPlayer "Badger" )
]
startingEvents : Events
startingEvents =
Dict.fromList
[ ( 1
, { id = 1
, organizer_user_name = "Charlie"
, millis = 1595999011722
, title = "Sierra Game Club Meeting #220"
, description = "On the schedule for this evening is Axis and Allies. If you bring a hat, you get free food."
, venue = "Charlie's House"
, status = Scheduled
, invites =
Dict.fromList
[ ( "Jim"
, { for_user_name = "Jim"
, status = Pending
}
)
, ( "Bones"
, { for_user_name = "Bones"
, status = Accepted
}
)
]
}
)
, ( 2
, { id = 2
, organizer_user_name = "Solo"
, millis = 1595999011722
, title = "Kepler Family Game Night"
, description = "Lets play 'Draw for your Life' over Zoom!"
, venue = "Online. Here are the details: <link goes here>"
, status = Scheduled
, invites =
Dict.fromList
[ ( "Jade"
, { for_user_name = "Jade"
, status = Declined
}
)
, ( "Badger"
, { for_user_name = "Badger"
, status = Pending
}
)
, ( "Jim"
, { for_user_name = "Jim"
, status = Accepted
}
)
]
}
)
, ( 3
, { id = 3
, organizer_user_name = "Jim"
, millis = 1599999011722
, title = "South Pacific Game Convention"
, description = "Come join me at the convention so we can meet new people and play some new games!"
, venue = "Anaheim Convention Center"
, status = Canceled
, invites =
Dict.fromList
[ ( "Solo"
, { for_user_name = "Solo"
, status = Pending
}
)
, ( "Bones"
, { for_user_name = "Bones"
, status = Accepted
}
)
, ( "Badger"
, { for_user_name = "Badger"
, status = Pending
}
)
, ( "Jade"
, { for_user_name = "Jade"
, status = Declined
}
)
]
}
)
]
--
-- Model Logic
--
nextEventId : Events -> EventId
nextEventId events =
Dict.keys events
|> LE.last
|> Maybe.withDefault 0
|> (+) 1
isMaybeVec2WithinMaybeDomElement : Maybe M.Vec2 -> Maybe Dom.Element -> Bool
isMaybeVec2WithinMaybeDomElement m_vec2 m_elem_info =
case Maybe.map2 (\vec2 elem_info -> ( vec2, elem_info )) m_vec2 m_elem_info of
Just ( v2, ei ) ->
let
threshold =
20
x =
M.getX v2
y =
M.getY v2
el =
ei.element
in
x > 0 - threshold && x < el.width - threshold && y > 0 - threshold && y < el.height - threshold
Nothing ->
False
isThisMe : Player -> Player -> Bool
isThisMe player me =
player.user_name == me.user_name
amITheOrganizer : Event -> Player -> Bool
amITheOrganizer event me =
event.organizer_user_name == me.user_name
saveAndClearPossibleEvent : Model -> Model
saveAndClearPossibleEvent ({ m_player, events, m_possible_event } as model) =
case maybeEventFromPossibleEvent m_player events m_possible_event of
Just event ->
{ model
| events = Dict.insert event.id event model.events
, m_possible_event = Nothing
}
Nothing ->
{ model | m_possible_event = Nothing }
playerEvents : Events -> Player -> List Event
playerEvents events player =
let
event_list =
Dict.toList events
in
eventsByPlayer event_list player ++ eventsForPlayer event_list player
eventsByPlayer : List ( Int, Event ) -> Player -> List Event
eventsByPlayer event_list player =
List.filterMap
(\( _, e ) ->
if amITheOrganizer e player then
Just e
else
Nothing
)
event_list
eventsForPlayer : List ( Int, Event ) -> Player -> List Event
eventsForPlayer event_list player =
List.filterMap
(\( _, e ) ->
if List.any (\( _, i ) -> i.for_user_name == player.user_name) (Dict.toList e.invites) then
Just e
else
Nothing
)
event_list
toggleEventStatusById : EventId -> Events -> Events
toggleEventStatusById event_id events =
let
m_event =
Dict.get event_id events
in
case m_event of
Just event ->
Dict.insert event_id (toggleEventStatus event) events
Nothing ->
events
toggleEventStatus : Event -> Event
toggleEventStatus event =
case event.status of
Canceled ->
{ event | status = Scheduled }
Scheduled ->
{ event | status = Canceled }
toggleInviteStatusByEventId : UserName -> EventId -> Events -> Events
toggleInviteStatusByEventId for_user_name event_id events =
case Dict.get event_id events of
Just event ->
case Dict.get for_user_name event.invites of
Just invite ->
let
new_invite =
{ invite | status = nextInviteStatusForInvite invite }
new_event =
{ event | invites = Dict.insert for_user_name new_invite event.invites }
in
Dict.insert event_id new_event events
Nothing ->
events
Nothing ->
events
nextInviteStatusForInvite : Invite -> InviteStatus
nextInviteStatusForInvite invite =
nextInviteStatusForStatus invite.status
nextInviteStatusForStatus : InviteStatus -> InviteStatus
nextInviteStatusForStatus status =
case status of
Pending ->
Accepted
Accepted ->
Declined
Declined ->
Pending
| 7972 | module DataModel exposing (Event, EventId, EventStatus(..), Events, Invite, InviteStatus(..), Invites, LoginField(..), Model, Password, Player, PlayerPosition, Players, PossibleEvent, PossibleEventSetter(..), UserName, amITheOrganizer, clearPossibleEventInfo, defaultMillisForPossibleEvent, defaultModel, emptyPlayerPosition, eventsByPlayer, eventsForPlayer, isMaybeVec2WithinMaybeDomElement, isThisMe, maybeEventFromPossibleEvent, newInvite, newPlayer, newPossibleEvent, nextEventId, nextInviteStatusForInvite, nextInviteStatusForStatus, playerEvents, primePossibleEventWithMillis, saveAndClearPossibleEvent, startingEvents, startingPlayers, toggleEventStatus, toggleEventStatusById, toggleInviteStatusByEventId)
import Browser.Dom as Dom
import Dict exposing (Dict)
import Draggable as D
import List.Extra as LE
import Math.Vector2 as M
--
-- Model
--
type alias Model =
{ input_user_name : UserName
, input_password : <PASSWORD>
, m_player : Maybe Player
, players : Players
, events : Events
, m_possible_event : Maybe PossibleEvent
, m_poss_event_elem_info : Maybe Dom.Element
, login_offset : Float
, login_field_with_tab_index : LoginField
, dragged_player_position : PlayerPosition
, drag : D.State UserName
}
-- Player
type alias UserName =
String
type alias Password =
String
type alias PlayerPosition =
( Maybe UserName, Maybe M.Vec2 )
type alias Player =
{ user_name : UserName
, member_since : Int
}
type alias Players =
Dict UserName Player
-- Event
type alias EventId =
Int
type EventStatus
= Canceled
| Scheduled
type alias Event =
{ id : EventId
, organizer_user_name : UserName
, millis : Int
, title : String
, description : String
, venue : String
, status : EventStatus
, invites : Invites
}
type alias Events =
Dict Int Event
-- Invite
type InviteStatus
= Pending
| Accepted
| Declined
type alias Invite =
{ for_user_name : UserName
, status : InviteStatus
}
type alias Invites =
Dict UserName Invite
-- Possible Event
type alias PossibleEvent =
{ millis : Int
, title : String
, description : String
, venue : String
, invites : Invites
}
{-|
How do you update a single record property via Msg? We could have a separate
Msg variant for each property, but that would not be a good separation of
concerns between the Msg type and specific record details. We could have single Msg
where we pass a setter function along with the value, but that makes the Msg and update
handling more opaque during debugging.
I believe the most idiomatic approach is to create a type with variants for each
set operation driven by Msg, then have a single Msg that takes this type and a value
and then pattern match in a case statement on the setter type.
It's not much more verbose than passing a setter function, and keeps the Msg and
update handling completely transparent.
-}
type PossibleEventSetter
= MillisUp
| MillisDown
| Title
| Description
| Venue
-- Login Field
type LoginField
= UserNameField
| PasswordField
| NoField
--
-- Default Data - should go away once the DB is hooked up
--
defaultModel : Model
defaultModel =
{ input_user_name = ""
, input_password = ""
, m_player = Nothing
, players = startingPlayers
, events = startingEvents
, m_possible_event = Nothing
, m_poss_event_elem_info = Nothing
, login_offset = 0.0
, login_field_with_tab_index = UserNameField
, dragged_player_position = emptyPlayerPosition
, drag = D.init
}
emptyPlayerPosition : PlayerPosition
emptyPlayerPosition =
( Nothing, Nothing )
newPlayer : UserName -> Player
newPlayer user_name =
Player user_name 0
newInvite : UserName -> Invite
newInvite user_name =
Invite user_name Pending
defaultMillisForPossibleEvent : Int
defaultMillisForPossibleEvent =
0
newPossibleEvent : Int -> PossibleEvent
newPossibleEvent millis =
{ millis = millis
, title = ""
, description = ""
, venue = ""
, invites = Dict.empty
}
primePossibleEventWithMillis : Int -> PossibleEvent -> PossibleEvent
primePossibleEventWithMillis millis poss_event =
if defaultMillisForPossibleEvent == poss_event.millis then
{ poss_event | millis = millis }
else
poss_event
clearPossibleEventInfo : Model -> Model
clearPossibleEventInfo model =
{ model
| m_possible_event = Nothing
, m_poss_event_elem_info = Nothing
, dragged_player_position = emptyPlayerPosition
, drag = D.init
}
maybeEventFromPossibleEvent : Maybe Player -> Events -> Maybe PossibleEvent -> Maybe Event
maybeEventFromPossibleEvent m_player events m_possible_event =
Maybe.map2
(\p pe ->
{ id = nextEventId events
, organizer_user_name = p.user_name
, millis = pe.millis
, title = pe.title
, description = pe.description
, status = Scheduled
, venue = pe.venue
, invites = pe.invites
}
)
m_player
m_possible_event
startingPlayers : Players
startingPlayers =
Dict.fromList
[ ( "<NAME>", newPlayer "<NAME>" )
, ( "<NAME>", newPlayer "<NAME>" )
, ( "Bones", newPlayer "Bones" )
, ( "Solo", newPlayer "Solo" )
, ( "Badger", newPlayer "Badger" )
]
startingEvents : Events
startingEvents =
Dict.fromList
[ ( 1
, { id = 1
, organizer_user_name = "<NAME>"
, millis = 1595999011722
, title = "Sierra Game Club Meeting #220"
, description = "On the schedule for this evening is Axis and Allies. If you bring a hat, you get free food."
, venue = "Charlie's House"
, status = Scheduled
, invites =
Dict.fromList
[ ( "<NAME>"
, { for_user_name = "<NAME>"
, status = Pending
}
)
, ( "Bones"
, { for_user_name = "<NAME>"
, status = Accepted
}
)
]
}
)
, ( 2
, { id = 2
, organizer_user_name = "Solo"
, millis = 1595999011722
, title = "Kepler Family Game Night"
, description = "Lets play 'Draw for your Life' over Zoom!"
, venue = "Online. Here are the details: <link goes here>"
, status = Scheduled
, invites =
Dict.fromList
[ ( "<NAME>"
, { for_user_name = "<NAME>"
, status = Declined
}
)
, ( "<NAME>"
, { for_user_name = "<NAME>"
, status = Pending
}
)
, ( "<NAME>"
, { for_user_name = "<NAME>"
, status = Accepted
}
)
]
}
)
, ( 3
, { id = 3
, organizer_user_name = "<NAME>"
, millis = 1599999011722
, title = "South Pacific Game Convention"
, description = "Come join me at the convention so we can meet new people and play some new games!"
, venue = "Anaheim Convention Center"
, status = Canceled
, invites =
Dict.fromList
[ ( "Solo"
, { for_user_name = "<NAME>"
, status = Pending
}
)
, ( "B<NAME>"
, { for_user_name = "<NAME>"
, status = Accepted
}
)
, ( "<NAME>"
, { for_user_name = "<NAME>"
, status = Pending
}
)
, ( "<NAME>"
, { for_user_name = "<NAME>"
, status = Declined
}
)
]
}
)
]
--
-- Model Logic
--
nextEventId : Events -> EventId
nextEventId events =
Dict.keys events
|> LE.last
|> Maybe.withDefault 0
|> (+) 1
isMaybeVec2WithinMaybeDomElement : Maybe M.Vec2 -> Maybe Dom.Element -> Bool
isMaybeVec2WithinMaybeDomElement m_vec2 m_elem_info =
case Maybe.map2 (\vec2 elem_info -> ( vec2, elem_info )) m_vec2 m_elem_info of
Just ( v2, ei ) ->
let
threshold =
20
x =
M.getX v2
y =
M.getY v2
el =
ei.element
in
x > 0 - threshold && x < el.width - threshold && y > 0 - threshold && y < el.height - threshold
Nothing ->
False
isThisMe : Player -> Player -> Bool
isThisMe player me =
player.user_name == me.user_name
amITheOrganizer : Event -> Player -> Bool
amITheOrganizer event me =
event.organizer_user_name == me.user_name
saveAndClearPossibleEvent : Model -> Model
saveAndClearPossibleEvent ({ m_player, events, m_possible_event } as model) =
case maybeEventFromPossibleEvent m_player events m_possible_event of
Just event ->
{ model
| events = Dict.insert event.id event model.events
, m_possible_event = Nothing
}
Nothing ->
{ model | m_possible_event = Nothing }
playerEvents : Events -> Player -> List Event
playerEvents events player =
let
event_list =
Dict.toList events
in
eventsByPlayer event_list player ++ eventsForPlayer event_list player
eventsByPlayer : List ( Int, Event ) -> Player -> List Event
eventsByPlayer event_list player =
List.filterMap
(\( _, e ) ->
if amITheOrganizer e player then
Just e
else
Nothing
)
event_list
eventsForPlayer : List ( Int, Event ) -> Player -> List Event
eventsForPlayer event_list player =
List.filterMap
(\( _, e ) ->
if List.any (\( _, i ) -> i.for_user_name == player.user_name) (Dict.toList e.invites) then
Just e
else
Nothing
)
event_list
toggleEventStatusById : EventId -> Events -> Events
toggleEventStatusById event_id events =
let
m_event =
Dict.get event_id events
in
case m_event of
Just event ->
Dict.insert event_id (toggleEventStatus event) events
Nothing ->
events
toggleEventStatus : Event -> Event
toggleEventStatus event =
case event.status of
Canceled ->
{ event | status = Scheduled }
Scheduled ->
{ event | status = Canceled }
toggleInviteStatusByEventId : UserName -> EventId -> Events -> Events
toggleInviteStatusByEventId for_user_name event_id events =
case Dict.get event_id events of
Just event ->
case Dict.get for_user_name event.invites of
Just invite ->
let
new_invite =
{ invite | status = nextInviteStatusForInvite invite }
new_event =
{ event | invites = Dict.insert for_user_name new_invite event.invites }
in
Dict.insert event_id new_event events
Nothing ->
events
Nothing ->
events
nextInviteStatusForInvite : Invite -> InviteStatus
nextInviteStatusForInvite invite =
nextInviteStatusForStatus invite.status
nextInviteStatusForStatus : InviteStatus -> InviteStatus
nextInviteStatusForStatus status =
case status of
Pending ->
Accepted
Accepted ->
Declined
Declined ->
Pending
| true | module DataModel exposing (Event, EventId, EventStatus(..), Events, Invite, InviteStatus(..), Invites, LoginField(..), Model, Password, Player, PlayerPosition, Players, PossibleEvent, PossibleEventSetter(..), UserName, amITheOrganizer, clearPossibleEventInfo, defaultMillisForPossibleEvent, defaultModel, emptyPlayerPosition, eventsByPlayer, eventsForPlayer, isMaybeVec2WithinMaybeDomElement, isThisMe, maybeEventFromPossibleEvent, newInvite, newPlayer, newPossibleEvent, nextEventId, nextInviteStatusForInvite, nextInviteStatusForStatus, playerEvents, primePossibleEventWithMillis, saveAndClearPossibleEvent, startingEvents, startingPlayers, toggleEventStatus, toggleEventStatusById, toggleInviteStatusByEventId)
import Browser.Dom as Dom
import Dict exposing (Dict)
import Draggable as D
import List.Extra as LE
import Math.Vector2 as M
--
-- Model
--
type alias Model =
{ input_user_name : UserName
, input_password : PI:PASSWORD:<PASSWORD>END_PI
, m_player : Maybe Player
, players : Players
, events : Events
, m_possible_event : Maybe PossibleEvent
, m_poss_event_elem_info : Maybe Dom.Element
, login_offset : Float
, login_field_with_tab_index : LoginField
, dragged_player_position : PlayerPosition
, drag : D.State UserName
}
-- Player
type alias UserName =
String
type alias Password =
String
type alias PlayerPosition =
( Maybe UserName, Maybe M.Vec2 )
type alias Player =
{ user_name : UserName
, member_since : Int
}
type alias Players =
Dict UserName Player
-- Event
type alias EventId =
Int
type EventStatus
= Canceled
| Scheduled
type alias Event =
{ id : EventId
, organizer_user_name : UserName
, millis : Int
, title : String
, description : String
, venue : String
, status : EventStatus
, invites : Invites
}
type alias Events =
Dict Int Event
-- Invite
type InviteStatus
= Pending
| Accepted
| Declined
type alias Invite =
{ for_user_name : UserName
, status : InviteStatus
}
type alias Invites =
Dict UserName Invite
-- Possible Event
type alias PossibleEvent =
{ millis : Int
, title : String
, description : String
, venue : String
, invites : Invites
}
{-|
How do you update a single record property via Msg? We could have a separate
Msg variant for each property, but that would not be a good separation of
concerns between the Msg type and specific record details. We could have single Msg
where we pass a setter function along with the value, but that makes the Msg and update
handling more opaque during debugging.
I believe the most idiomatic approach is to create a type with variants for each
set operation driven by Msg, then have a single Msg that takes this type and a value
and then pattern match in a case statement on the setter type.
It's not much more verbose than passing a setter function, and keeps the Msg and
update handling completely transparent.
-}
type PossibleEventSetter
= MillisUp
| MillisDown
| Title
| Description
| Venue
-- Login Field
type LoginField
= UserNameField
| PasswordField
| NoField
--
-- Default Data - should go away once the DB is hooked up
--
defaultModel : Model
defaultModel =
{ input_user_name = ""
, input_password = ""
, m_player = Nothing
, players = startingPlayers
, events = startingEvents
, m_possible_event = Nothing
, m_poss_event_elem_info = Nothing
, login_offset = 0.0
, login_field_with_tab_index = UserNameField
, dragged_player_position = emptyPlayerPosition
, drag = D.init
}
emptyPlayerPosition : PlayerPosition
emptyPlayerPosition =
( Nothing, Nothing )
newPlayer : UserName -> Player
newPlayer user_name =
Player user_name 0
newInvite : UserName -> Invite
newInvite user_name =
Invite user_name Pending
defaultMillisForPossibleEvent : Int
defaultMillisForPossibleEvent =
0
newPossibleEvent : Int -> PossibleEvent
newPossibleEvent millis =
{ millis = millis
, title = ""
, description = ""
, venue = ""
, invites = Dict.empty
}
primePossibleEventWithMillis : Int -> PossibleEvent -> PossibleEvent
primePossibleEventWithMillis millis poss_event =
if defaultMillisForPossibleEvent == poss_event.millis then
{ poss_event | millis = millis }
else
poss_event
clearPossibleEventInfo : Model -> Model
clearPossibleEventInfo model =
{ model
| m_possible_event = Nothing
, m_poss_event_elem_info = Nothing
, dragged_player_position = emptyPlayerPosition
, drag = D.init
}
maybeEventFromPossibleEvent : Maybe Player -> Events -> Maybe PossibleEvent -> Maybe Event
maybeEventFromPossibleEvent m_player events m_possible_event =
Maybe.map2
(\p pe ->
{ id = nextEventId events
, organizer_user_name = p.user_name
, millis = pe.millis
, title = pe.title
, description = pe.description
, status = Scheduled
, venue = pe.venue
, invites = pe.invites
}
)
m_player
m_possible_event
startingPlayers : Players
startingPlayers =
Dict.fromList
[ ( "PI:NAME:<NAME>END_PI", newPlayer "PI:NAME:<NAME>END_PI" )
, ( "PI:NAME:<NAME>END_PI", newPlayer "PI:NAME:<NAME>END_PI" )
, ( "Bones", newPlayer "Bones" )
, ( "Solo", newPlayer "Solo" )
, ( "Badger", newPlayer "Badger" )
]
startingEvents : Events
startingEvents =
Dict.fromList
[ ( 1
, { id = 1
, organizer_user_name = "PI:NAME:<NAME>END_PI"
, millis = 1595999011722
, title = "Sierra Game Club Meeting #220"
, description = "On the schedule for this evening is Axis and Allies. If you bring a hat, you get free food."
, venue = "Charlie's House"
, status = Scheduled
, invites =
Dict.fromList
[ ( "PI:NAME:<NAME>END_PI"
, { for_user_name = "PI:NAME:<NAME>END_PI"
, status = Pending
}
)
, ( "Bones"
, { for_user_name = "PI:NAME:<NAME>END_PI"
, status = Accepted
}
)
]
}
)
, ( 2
, { id = 2
, organizer_user_name = "Solo"
, millis = 1595999011722
, title = "Kepler Family Game Night"
, description = "Lets play 'Draw for your Life' over Zoom!"
, venue = "Online. Here are the details: <link goes here>"
, status = Scheduled
, invites =
Dict.fromList
[ ( "PI:NAME:<NAME>END_PI"
, { for_user_name = "PI:NAME:<NAME>END_PI"
, status = Declined
}
)
, ( "PI:NAME:<NAME>END_PI"
, { for_user_name = "PI:NAME:<NAME>END_PI"
, status = Pending
}
)
, ( "PI:NAME:<NAME>END_PI"
, { for_user_name = "PI:NAME:<NAME>END_PI"
, status = Accepted
}
)
]
}
)
, ( 3
, { id = 3
, organizer_user_name = "PI:NAME:<NAME>END_PI"
, millis = 1599999011722
, title = "South Pacific Game Convention"
, description = "Come join me at the convention so we can meet new people and play some new games!"
, venue = "Anaheim Convention Center"
, status = Canceled
, invites =
Dict.fromList
[ ( "Solo"
, { for_user_name = "PI:NAME:<NAME>END_PI"
, status = Pending
}
)
, ( "BPI:NAME:<NAME>END_PI"
, { for_user_name = "PI:NAME:<NAME>END_PI"
, status = Accepted
}
)
, ( "PI:NAME:<NAME>END_PI"
, { for_user_name = "PI:NAME:<NAME>END_PI"
, status = Pending
}
)
, ( "PI:NAME:<NAME>END_PI"
, { for_user_name = "PI:NAME:<NAME>END_PI"
, status = Declined
}
)
]
}
)
]
--
-- Model Logic
--
nextEventId : Events -> EventId
nextEventId events =
Dict.keys events
|> LE.last
|> Maybe.withDefault 0
|> (+) 1
isMaybeVec2WithinMaybeDomElement : Maybe M.Vec2 -> Maybe Dom.Element -> Bool
isMaybeVec2WithinMaybeDomElement m_vec2 m_elem_info =
case Maybe.map2 (\vec2 elem_info -> ( vec2, elem_info )) m_vec2 m_elem_info of
Just ( v2, ei ) ->
let
threshold =
20
x =
M.getX v2
y =
M.getY v2
el =
ei.element
in
x > 0 - threshold && x < el.width - threshold && y > 0 - threshold && y < el.height - threshold
Nothing ->
False
isThisMe : Player -> Player -> Bool
isThisMe player me =
player.user_name == me.user_name
amITheOrganizer : Event -> Player -> Bool
amITheOrganizer event me =
event.organizer_user_name == me.user_name
saveAndClearPossibleEvent : Model -> Model
saveAndClearPossibleEvent ({ m_player, events, m_possible_event } as model) =
case maybeEventFromPossibleEvent m_player events m_possible_event of
Just event ->
{ model
| events = Dict.insert event.id event model.events
, m_possible_event = Nothing
}
Nothing ->
{ model | m_possible_event = Nothing }
playerEvents : Events -> Player -> List Event
playerEvents events player =
let
event_list =
Dict.toList events
in
eventsByPlayer event_list player ++ eventsForPlayer event_list player
eventsByPlayer : List ( Int, Event ) -> Player -> List Event
eventsByPlayer event_list player =
List.filterMap
(\( _, e ) ->
if amITheOrganizer e player then
Just e
else
Nothing
)
event_list
eventsForPlayer : List ( Int, Event ) -> Player -> List Event
eventsForPlayer event_list player =
List.filterMap
(\( _, e ) ->
if List.any (\( _, i ) -> i.for_user_name == player.user_name) (Dict.toList e.invites) then
Just e
else
Nothing
)
event_list
toggleEventStatusById : EventId -> Events -> Events
toggleEventStatusById event_id events =
let
m_event =
Dict.get event_id events
in
case m_event of
Just event ->
Dict.insert event_id (toggleEventStatus event) events
Nothing ->
events
toggleEventStatus : Event -> Event
toggleEventStatus event =
case event.status of
Canceled ->
{ event | status = Scheduled }
Scheduled ->
{ event | status = Canceled }
toggleInviteStatusByEventId : UserName -> EventId -> Events -> Events
toggleInviteStatusByEventId for_user_name event_id events =
case Dict.get event_id events of
Just event ->
case Dict.get for_user_name event.invites of
Just invite ->
let
new_invite =
{ invite | status = nextInviteStatusForInvite invite }
new_event =
{ event | invites = Dict.insert for_user_name new_invite event.invites }
in
Dict.insert event_id new_event events
Nothing ->
events
Nothing ->
events
nextInviteStatusForInvite : Invite -> InviteStatus
nextInviteStatusForInvite invite =
nextInviteStatusForStatus invite.status
nextInviteStatusForStatus : InviteStatus -> InviteStatus
nextInviteStatusForStatus status =
case status of
Pending ->
Accepted
Accepted ->
Declined
Declined ->
Pending
| elm |
[
{
"context": "s\" ]\n << position YOffset [ pName \"jitter\", pQuant ]\n in\n toVegaLite [ heightStep 50,",
"end": 3257,
"score": 0.9531624317,
"start": 3251,
"tag": "NAME",
"value": "jitter"
}
] | examples/tests/src/PositionTests.elm | gicentre/elm-vegaLite | 1 | port module PositionTests exposing (elmToJS)
import Browser
import Dict
import Html exposing (Html)
import Html.Attributes
import Html.Events
import Json.Encode
import VegaLite exposing (..)
path : String
path =
"https://cdn.jsdelivr.net/npm/vega-datasets@2.2/data/"
emptyData : List DataColumn -> Data
emptyData =
dataFromColumns []
<< dataColumn "empty" (nums [ 0 ])
data : List DataColumn -> Data
data =
dataFromColumns []
<< dataColumn "cat" (nums [ 1, 2, 3, 4, 5 ])
<< dataColumn "val" (nums [ 10, 20, 30, 20, 10 ])
position1 : Spec
position1 =
toVegaLite [ emptyData [], circle [ maX 150, maY 150, maSize 200 ] ]
position2 : Spec
position2 =
toVegaLite [ emptyData [], bar [ maX 150, maY 150 ] ]
position3 : Spec
position3 =
toVegaLite [ emptyData [], bar [ maX 150, maY 150, maX2 200 ] ]
position4 : Spec
position4 =
toVegaLite [ emptyData [], bar [ maX 150, maY 150, maY2 200 ] ]
position5 : Spec
position5 =
toVegaLite [ emptyData [], bar [ maX 150, maY 150, maX2 200, maY2 200 ] ]
position6 : Spec
position6 =
let
enc =
encoding
<< position X [ pName "cat", pOrdinal ]
<< position Y [ pName "val", pQuant ]
in
toVegaLite [ width 300, data [], enc [], bar [ maWidth 20 ] ]
position7 : Spec
position7 =
let
enc =
encoding
<< position X [ pName "val", pQuant ]
<< position Y [ pName "cat", pOrdinal ]
in
toVegaLite [ height 300, data [], enc [], bar [ maHeight 20 ] ]
barAlign : Float -> Spec
barAlign x =
let
enc =
encoding
<< position X
[ pName "cat"
, pOrdinal
, pScale [ scAlign x, scPaddingInner 0.5 ]
]
<< position Y [ pName "val", pQuant ]
in
toVegaLite [ width 400, data [], enc [], bar [] ]
position8 : Spec
position8 =
barAlign 0
position9 : Spec
position9 =
barAlign 0.3
position10 : Spec
position10 =
barAlign 0.5
position11 : Spec
position11 =
barAlign 0.7
position12 : Spec
position12 =
barAlign 1
position13 : Spec
position13 =
let
data2 =
dataFromColumns []
<< dataColumn "category" (strs [ "A", "A", "A", "B", "B", "B", "C", "C", "C" ])
<< dataColumn "group" (strs [ "x", "y", "z", "x", "y", "z", "x", "y", "z" ])
<< dataColumn "value" (nums [ 0.1, 0.6, 0.9, 0.7, 0.2, 0.1, 0.6, 0.1, 0.2 ])
enc =
encoding
<< position X [ pName "category" ]
<< position Y [ pName "value", pQuant ]
<< position XOffset [ pName "group" ]
<< color [ mName "group" ]
in
toVegaLite [ data2 [], enc [], bar [] ]
position14 : Spec
position14 =
let
data2 =
dataFromUrl (path ++ "cars.json") []
trans =
transform
<< calculateAs "random()" "jitter"
enc =
encoding
<< position X [ pName "Horsepower", pQuant ]
<< position Y [ pName "Cylinders" ]
<< position YOffset [ pName "jitter", pQuant ]
in
toVegaLite [ heightStep 50, data2, trans [], enc [], point [] ]
{- Ids and specifications to be provided to the Vega-Lite runtime. -}
specs : List ( String, Spec )
specs =
[ ( "position1", position1 )
, ( "position2", position2 )
, ( "position3", position3 )
, ( "position4", position4 )
, ( "position5", position5 )
, ( "position6", position6 )
, ( "position7", position7 )
, ( "position8", position8 )
, ( "position9", position9 )
, ( "position10", position10 )
, ( "position11", position11 )
, ( "position12", position12 )
, ( "position13", position13 )
, ( "position14", position14 )
]
{- ---------------------------------------------------------------------------
BOILERPLATE: NO NEED TO EDIT
The code below creates an Elm module that opens an outgoing port to Javascript
and sends both the specs and DOM node to it.
It allows the source code of any of the generated specs to be selected from
a drop-down list. Useful for viewing specs that might generate invalid Vega-Lite.
-}
type Msg
= NewSource String
main : Program () Spec Msg
main =
Browser.element
{ init = always ( Json.Encode.null, specs |> combineSpecs |> elmToJS )
, view = view
, update = update
, subscriptions = always Sub.none
}
view : Spec -> Html Msg
view spec =
Html.div []
[ Html.select [ Html.Events.onInput NewSource ]
(( "Select source", Json.Encode.null )
:: specs
|> List.map (\( s, _ ) -> Html.option [ Html.Attributes.value s ] [ Html.text s ])
)
, Html.div [ Html.Attributes.id "specSource" ] []
, if spec == Json.Encode.null then
Html.div [] []
else
Html.pre [] [ Html.text (Json.Encode.encode 2 spec) ]
]
update : Msg -> Spec -> ( Spec, Cmd Msg )
update msg _ =
case msg of
NewSource srcName ->
( specs |> Dict.fromList |> Dict.get srcName |> Maybe.withDefault Json.Encode.null, Cmd.none )
port elmToJS : Spec -> Cmd msg
| 46640 | port module PositionTests exposing (elmToJS)
import Browser
import Dict
import Html exposing (Html)
import Html.Attributes
import Html.Events
import Json.Encode
import VegaLite exposing (..)
path : String
path =
"https://cdn.jsdelivr.net/npm/vega-datasets@2.2/data/"
emptyData : List DataColumn -> Data
emptyData =
dataFromColumns []
<< dataColumn "empty" (nums [ 0 ])
data : List DataColumn -> Data
data =
dataFromColumns []
<< dataColumn "cat" (nums [ 1, 2, 3, 4, 5 ])
<< dataColumn "val" (nums [ 10, 20, 30, 20, 10 ])
position1 : Spec
position1 =
toVegaLite [ emptyData [], circle [ maX 150, maY 150, maSize 200 ] ]
position2 : Spec
position2 =
toVegaLite [ emptyData [], bar [ maX 150, maY 150 ] ]
position3 : Spec
position3 =
toVegaLite [ emptyData [], bar [ maX 150, maY 150, maX2 200 ] ]
position4 : Spec
position4 =
toVegaLite [ emptyData [], bar [ maX 150, maY 150, maY2 200 ] ]
position5 : Spec
position5 =
toVegaLite [ emptyData [], bar [ maX 150, maY 150, maX2 200, maY2 200 ] ]
position6 : Spec
position6 =
let
enc =
encoding
<< position X [ pName "cat", pOrdinal ]
<< position Y [ pName "val", pQuant ]
in
toVegaLite [ width 300, data [], enc [], bar [ maWidth 20 ] ]
position7 : Spec
position7 =
let
enc =
encoding
<< position X [ pName "val", pQuant ]
<< position Y [ pName "cat", pOrdinal ]
in
toVegaLite [ height 300, data [], enc [], bar [ maHeight 20 ] ]
barAlign : Float -> Spec
barAlign x =
let
enc =
encoding
<< position X
[ pName "cat"
, pOrdinal
, pScale [ scAlign x, scPaddingInner 0.5 ]
]
<< position Y [ pName "val", pQuant ]
in
toVegaLite [ width 400, data [], enc [], bar [] ]
position8 : Spec
position8 =
barAlign 0
position9 : Spec
position9 =
barAlign 0.3
position10 : Spec
position10 =
barAlign 0.5
position11 : Spec
position11 =
barAlign 0.7
position12 : Spec
position12 =
barAlign 1
position13 : Spec
position13 =
let
data2 =
dataFromColumns []
<< dataColumn "category" (strs [ "A", "A", "A", "B", "B", "B", "C", "C", "C" ])
<< dataColumn "group" (strs [ "x", "y", "z", "x", "y", "z", "x", "y", "z" ])
<< dataColumn "value" (nums [ 0.1, 0.6, 0.9, 0.7, 0.2, 0.1, 0.6, 0.1, 0.2 ])
enc =
encoding
<< position X [ pName "category" ]
<< position Y [ pName "value", pQuant ]
<< position XOffset [ pName "group" ]
<< color [ mName "group" ]
in
toVegaLite [ data2 [], enc [], bar [] ]
position14 : Spec
position14 =
let
data2 =
dataFromUrl (path ++ "cars.json") []
trans =
transform
<< calculateAs "random()" "jitter"
enc =
encoding
<< position X [ pName "Horsepower", pQuant ]
<< position Y [ pName "Cylinders" ]
<< position YOffset [ pName "<NAME>", pQuant ]
in
toVegaLite [ heightStep 50, data2, trans [], enc [], point [] ]
{- Ids and specifications to be provided to the Vega-Lite runtime. -}
specs : List ( String, Spec )
specs =
[ ( "position1", position1 )
, ( "position2", position2 )
, ( "position3", position3 )
, ( "position4", position4 )
, ( "position5", position5 )
, ( "position6", position6 )
, ( "position7", position7 )
, ( "position8", position8 )
, ( "position9", position9 )
, ( "position10", position10 )
, ( "position11", position11 )
, ( "position12", position12 )
, ( "position13", position13 )
, ( "position14", position14 )
]
{- ---------------------------------------------------------------------------
BOILERPLATE: NO NEED TO EDIT
The code below creates an Elm module that opens an outgoing port to Javascript
and sends both the specs and DOM node to it.
It allows the source code of any of the generated specs to be selected from
a drop-down list. Useful for viewing specs that might generate invalid Vega-Lite.
-}
type Msg
= NewSource String
main : Program () Spec Msg
main =
Browser.element
{ init = always ( Json.Encode.null, specs |> combineSpecs |> elmToJS )
, view = view
, update = update
, subscriptions = always Sub.none
}
view : Spec -> Html Msg
view spec =
Html.div []
[ Html.select [ Html.Events.onInput NewSource ]
(( "Select source", Json.Encode.null )
:: specs
|> List.map (\( s, _ ) -> Html.option [ Html.Attributes.value s ] [ Html.text s ])
)
, Html.div [ Html.Attributes.id "specSource" ] []
, if spec == Json.Encode.null then
Html.div [] []
else
Html.pre [] [ Html.text (Json.Encode.encode 2 spec) ]
]
update : Msg -> Spec -> ( Spec, Cmd Msg )
update msg _ =
case msg of
NewSource srcName ->
( specs |> Dict.fromList |> Dict.get srcName |> Maybe.withDefault Json.Encode.null, Cmd.none )
port elmToJS : Spec -> Cmd msg
| true | port module PositionTests exposing (elmToJS)
import Browser
import Dict
import Html exposing (Html)
import Html.Attributes
import Html.Events
import Json.Encode
import VegaLite exposing (..)
path : String
path =
"https://cdn.jsdelivr.net/npm/vega-datasets@2.2/data/"
emptyData : List DataColumn -> Data
emptyData =
dataFromColumns []
<< dataColumn "empty" (nums [ 0 ])
data : List DataColumn -> Data
data =
dataFromColumns []
<< dataColumn "cat" (nums [ 1, 2, 3, 4, 5 ])
<< dataColumn "val" (nums [ 10, 20, 30, 20, 10 ])
position1 : Spec
position1 =
toVegaLite [ emptyData [], circle [ maX 150, maY 150, maSize 200 ] ]
position2 : Spec
position2 =
toVegaLite [ emptyData [], bar [ maX 150, maY 150 ] ]
position3 : Spec
position3 =
toVegaLite [ emptyData [], bar [ maX 150, maY 150, maX2 200 ] ]
position4 : Spec
position4 =
toVegaLite [ emptyData [], bar [ maX 150, maY 150, maY2 200 ] ]
position5 : Spec
position5 =
toVegaLite [ emptyData [], bar [ maX 150, maY 150, maX2 200, maY2 200 ] ]
position6 : Spec
position6 =
let
enc =
encoding
<< position X [ pName "cat", pOrdinal ]
<< position Y [ pName "val", pQuant ]
in
toVegaLite [ width 300, data [], enc [], bar [ maWidth 20 ] ]
position7 : Spec
position7 =
let
enc =
encoding
<< position X [ pName "val", pQuant ]
<< position Y [ pName "cat", pOrdinal ]
in
toVegaLite [ height 300, data [], enc [], bar [ maHeight 20 ] ]
barAlign : Float -> Spec
barAlign x =
let
enc =
encoding
<< position X
[ pName "cat"
, pOrdinal
, pScale [ scAlign x, scPaddingInner 0.5 ]
]
<< position Y [ pName "val", pQuant ]
in
toVegaLite [ width 400, data [], enc [], bar [] ]
position8 : Spec
position8 =
barAlign 0
position9 : Spec
position9 =
barAlign 0.3
position10 : Spec
position10 =
barAlign 0.5
position11 : Spec
position11 =
barAlign 0.7
position12 : Spec
position12 =
barAlign 1
position13 : Spec
position13 =
let
data2 =
dataFromColumns []
<< dataColumn "category" (strs [ "A", "A", "A", "B", "B", "B", "C", "C", "C" ])
<< dataColumn "group" (strs [ "x", "y", "z", "x", "y", "z", "x", "y", "z" ])
<< dataColumn "value" (nums [ 0.1, 0.6, 0.9, 0.7, 0.2, 0.1, 0.6, 0.1, 0.2 ])
enc =
encoding
<< position X [ pName "category" ]
<< position Y [ pName "value", pQuant ]
<< position XOffset [ pName "group" ]
<< color [ mName "group" ]
in
toVegaLite [ data2 [], enc [], bar [] ]
position14 : Spec
position14 =
let
data2 =
dataFromUrl (path ++ "cars.json") []
trans =
transform
<< calculateAs "random()" "jitter"
enc =
encoding
<< position X [ pName "Horsepower", pQuant ]
<< position Y [ pName "Cylinders" ]
<< position YOffset [ pName "PI:NAME:<NAME>END_PI", pQuant ]
in
toVegaLite [ heightStep 50, data2, trans [], enc [], point [] ]
{- Ids and specifications to be provided to the Vega-Lite runtime. -}
specs : List ( String, Spec )
specs =
[ ( "position1", position1 )
, ( "position2", position2 )
, ( "position3", position3 )
, ( "position4", position4 )
, ( "position5", position5 )
, ( "position6", position6 )
, ( "position7", position7 )
, ( "position8", position8 )
, ( "position9", position9 )
, ( "position10", position10 )
, ( "position11", position11 )
, ( "position12", position12 )
, ( "position13", position13 )
, ( "position14", position14 )
]
{- ---------------------------------------------------------------------------
BOILERPLATE: NO NEED TO EDIT
The code below creates an Elm module that opens an outgoing port to Javascript
and sends both the specs and DOM node to it.
It allows the source code of any of the generated specs to be selected from
a drop-down list. Useful for viewing specs that might generate invalid Vega-Lite.
-}
type Msg
= NewSource String
main : Program () Spec Msg
main =
Browser.element
{ init = always ( Json.Encode.null, specs |> combineSpecs |> elmToJS )
, view = view
, update = update
, subscriptions = always Sub.none
}
view : Spec -> Html Msg
view spec =
Html.div []
[ Html.select [ Html.Events.onInput NewSource ]
(( "Select source", Json.Encode.null )
:: specs
|> List.map (\( s, _ ) -> Html.option [ Html.Attributes.value s ] [ Html.text s ])
)
, Html.div [ Html.Attributes.id "specSource" ] []
, if spec == Json.Encode.null then
Html.div [] []
else
Html.pre [] [ Html.text (Json.Encode.encode 2 spec) ]
]
update : Msg -> Spec -> ( Spec, Cmd Msg )
update msg _ =
case msg of
NewSource srcName ->
( specs |> Dict.fromList |> Dict.get srcName |> Maybe.withDefault Json.Encode.null, Cmd.none )
port elmToJS : Spec -> Cmd msg
| elm |
[
{
"context": "{-\n Swaggy Jenkins\n Jenkins API clients generated from Swagger / O",
"end": 20,
"score": 0.999019742,
"start": 6,
"tag": "NAME",
"value": "Swaggy Jenkins"
},
{
"context": "cation\n\n OpenAPI spec version: 1.1.1\n Contact: blah@cliffano.com\n\n NOTE: This file is auto generated by the open",
"end": 153,
"score": 0.9999149442,
"start": 136,
"tag": "EMAIL",
"value": "blah@cliffano.com"
},
{
"context": "d by the openapi-generator.\n https://github.com/openapitools/openapi-generator.git\n Do not edit this file ma",
"end": 252,
"score": 0.9996570349,
"start": 240,
"tag": "USERNAME",
"value": "openapitools"
}
] | clients/elm/generated/src/Data/GithubFile.elm | PankTrue/swaggy-jenkins | 23 | {-
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification
OpenAPI spec version: 1.1.1
Contact: blah@cliffano.com
NOTE: This file is auto generated by the openapi-generator.
https://github.com/openapitools/openapi-generator.git
Do not edit this file manually.
-}
module Data.GithubFile exposing (GithubFile, githubFileDecoder, githubFileEncoder)
import Data.GithubContent exposing (GithubContent, githubContentDecoder, githubContentEncoder)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing (decode, optional, required)
import Json.Encode as Encode
import Maybe exposing (map, withDefault)
type alias GithubFile =
{ content : Maybe GithubContent
, class : Maybe String
}
githubFileDecoder : Decoder GithubFile
githubFileDecoder =
decode GithubFile
|> optional "content" (Decode.nullable githubContentDecoder) Nothing
|> optional "_class" (Decode.nullable Decode.string) Nothing
githubFileEncoder : GithubFile -> Encode.Value
githubFileEncoder model =
Encode.object
[ ( "content", withDefault Encode.null (map githubContentEncoder model.content) )
, ( "_class", withDefault Encode.null (map Encode.string model.class) )
]
| 18244 | {-
<NAME>
Jenkins API clients generated from Swagger / Open API specification
OpenAPI spec version: 1.1.1
Contact: <EMAIL>
NOTE: This file is auto generated by the openapi-generator.
https://github.com/openapitools/openapi-generator.git
Do not edit this file manually.
-}
module Data.GithubFile exposing (GithubFile, githubFileDecoder, githubFileEncoder)
import Data.GithubContent exposing (GithubContent, githubContentDecoder, githubContentEncoder)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing (decode, optional, required)
import Json.Encode as Encode
import Maybe exposing (map, withDefault)
type alias GithubFile =
{ content : Maybe GithubContent
, class : Maybe String
}
githubFileDecoder : Decoder GithubFile
githubFileDecoder =
decode GithubFile
|> optional "content" (Decode.nullable githubContentDecoder) Nothing
|> optional "_class" (Decode.nullable Decode.string) Nothing
githubFileEncoder : GithubFile -> Encode.Value
githubFileEncoder model =
Encode.object
[ ( "content", withDefault Encode.null (map githubContentEncoder model.content) )
, ( "_class", withDefault Encode.null (map Encode.string model.class) )
]
| true | {-
PI:NAME:<NAME>END_PI
Jenkins API clients generated from Swagger / Open API specification
OpenAPI spec version: 1.1.1
Contact: PI:EMAIL:<EMAIL>END_PI
NOTE: This file is auto generated by the openapi-generator.
https://github.com/openapitools/openapi-generator.git
Do not edit this file manually.
-}
module Data.GithubFile exposing (GithubFile, githubFileDecoder, githubFileEncoder)
import Data.GithubContent exposing (GithubContent, githubContentDecoder, githubContentEncoder)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing (decode, optional, required)
import Json.Encode as Encode
import Maybe exposing (map, withDefault)
type alias GithubFile =
{ content : Maybe GithubContent
, class : Maybe String
}
githubFileDecoder : Decoder GithubFile
githubFileDecoder =
decode GithubFile
|> optional "content" (Decode.nullable githubContentDecoder) Nothing
|> optional "_class" (Decode.nullable Decode.string) Nothing
githubFileEncoder : GithubFile -> Encode.Value
githubFileEncoder model =
Encode.object
[ ( "content", withDefault Encode.null (map githubContentEncoder model.content) )
, ( "_class", withDefault Encode.null (map Encode.string model.class) )
]
| elm |
[
{
"context": "8c0-.902-.292-1.726-.918-2.352zM29.07\n 23.365c.108.107.167.25.167.402 0 .15-.06.295-.167.4l-1.534\n 1.54c-.11",
"end": 5022,
"score": 0.9966050982,
"start": 5008,
"tag": "IP_ADDRESS",
"value": "108.107.167.25"
}
] | source/Ui/Icons.elm | nodew/elm-ui | 1,041 | module Ui.Icons exposing (..)
{-| This module contains icons for the components.
# Icons
@docs icon, close, checkmark, chevronRight, chevronLeft, plus, search
@docs starFull, starEmpty, backspace, calendar
-}
import Svg.Attributes exposing (d, width, height, viewBox)
import Svg exposing (svg, path)
import Html
{-| Calendar icon.
-}
calendar : List (Html.Attribute msg) -> Html.Html msg
calendar =
icon
"""
M9 0C7.578 0 6.428 1.15 6.428 2.572v2.57c0 1.423 1.15 2.573 2.572 2.573
1.422 0 2.572-1.15 2.572-2.572v-2.57C11.572 1.15 10.422 0 9 0zm18 0c-1.422
0-2.572 1.15-2.572 2.572v2.57c0 1.423 1.15 2.573 2.572 2.573 1.422 0
2.572-1.15 2.572-2.572v-2.57C29.572 1.15 28.422 0 27 0zM.643 2.572c-.354
0-.643.29-.643.643v32.142c0 .354.29.643.643.643h34.714c.354 0
.643-.29.643-.643V3.215c0-.354-.29-.643-.643-.643h-4.5v3.27C30.857 7.65
28.993 9 27.064 9c-1.928 0-3.92-1.35-3.92-3.158v-3.27H12.856v3.27C12.857
7.65 10.93 9 9 9 7.07 9 5.143 7.65 5.143 5.842v-3.27h-4.5zm3.214
9h28.286v20.57H3.857v-20.57z
"""
{-| Empty star icon.
-}
starEmpty : List (Html.Attribute msg) -> Html.Html msg
starEmpty =
icon
"""
M36 13.937l-12.945-1.11L18 .89l-5.056 11.936L0 13.936l9.82 8.513-2.944
12.66L18 28.397l11.123 6.71L26.18 22.45 36 13.937zm-16.527 12.02L18
25.066l-1.473.89-5.345 3.224 1.415-6.085.39-1.674-1.3-1.125L6.965
16.2l6.223-.533 1.71-.147.67-1.582L18 8.2l2.43 5.738.67 1.582 1.712.147
6.223.534-4.722 4.095-1.3 1.126.39 1.675 1.415 6.086-5.345-3.224z
"""
{-| Full star icon.
-}
starFull : List (Html.Attribute msg) -> Html.Html msg
starFull =
icon
"""
M23.055 12.826L18 .89l-5.056 11.936L0 13.936l9.82 8.514-2.944 12.66L18
28.397l11.123 6.71L26.18 22.45 36 13.937
"""
{-| Search icon.
-}
search : List (Html.Attribute msg) -> Html.Html msg
search =
icon
"""
M35.72 30.245l-7.95-8.05c1.293-2.26 1.968-4.77 1.968-7.302C29.738
6.683 23.063 0 14.868 0 6.676 0 0 6.683 0 14.893s6.675 14.893 14.87
14.893c2.614 0 5.202-.722 7.508-2.1l7.913
8.023c.18.178.432.29.685.29.253 0
.506-.103.684-.29l4.06-4.106c.374-.384.374-.984 0-1.36zM14.87
5.802c5.005 0 9.074 4.077 9.074 9.09 0 5.015-4.07 9.092-9.075
9.092-5.008 0-9.076-4.077-9.076-9.09 0-5.015 4.068-9.092 9.075-9.092z
"""
{-| Plus icon.
-}
plus : List (Html.Attribute msg) -> Html.Html msg
plus =
icon "M0 21h15v15h6V21h15v-6H21V0h-6v15H0"
{-| Close icon.
-}
close : List (Html.Attribute msg) -> Html.Html msg
close =
icon
"""
M35.592 30.256l-12.3-12.34L35.62 5.736c.507-.507.507-1.332
0-1.838L32.114.375C31.87.13 31.542 0 31.194 0c-.346
0-.674.14-.917.375L18.005 12.518 5.715.384C5.47.14 5.14.01
4.794.01c-.347 0-.675.14-.918.374L.38 3.907c-.507.506-.507
1.33 0 1.837l12.328 12.18L.418 30.257c-.245.244-.385.572-.385.918
0 .347.13.675.384.92l3.506 3.522c.254.253.582.384.92.384.327 0
.665-.122.918-.384l12.245-12.294 12.253
12.284c.253.253.58.385.92.385.327 0
.664-.12.917-.384l3.507-3.523c.243-.243.384-.57.384-.918-.01-.337-.15-.665-.394-.91z
"""
{-| Right chevron icon.
-}
chevronRight : List (Html.Attribute msg) -> Html.Html msg
chevronRight =
icon
"""
M21.403 17.996L7.963 4c-.34-.345-.33-.916.015-1.27L10.382.27c.345-.353.908-.36
1.246-.016l16.415 17.1c.177.176.257.417.24.65.01.24-.07.474-.24.65L11.628
35.747c-.338.345-.9.337-1.246-.016l-2.404-2.46c-.346-.354-.354-.925-.016-1.27l13.44-14.004z
"""
{-| Left chevron icon.
-}
chevronLeft : List (Html.Attribute msg) -> Html.Html msg
chevronLeft =
icon
"""
M14.597 17.996L28.037
4c.34-.345.33-.916-.015-1.27L25.618.27c-.345-.353-.908-.36-1.246-.016L7.957
17.344c-.177.178-.257.42-.24.652-.01.24.07.474.24.65l16.415
17.1c.338.345.9.337 1.246-.016l2.404-2.46c.346-.354.354-.925.016-1.27l-13.44-14.004z
"""
{-| Checkmark icon.
-}
checkmark : List (Html.Attribute msg) -> Html.Html msg
checkmark =
icon
"""
M35.792 5.332L31.04 1.584c-.147-.12-.33-.208-.537-.208-.207
0-.398.087-.545.217l-17.286 22.21S5.877 17.27 5.687
17.08c-.19-.19-.442-.51-.822-.51-.38 0-.554.268-.753.467-.148.156-2.57
2.7-3.766 3.964-.07.077-.112.12-.173.18-.104.148-.173.313-.173.494 0
.19.07.347.173.494l.242.225s12.058 11.582 12.257 11.78c.2.2.442.45.797.45.345
0 .63-.37.795-.536l21.562-27.7c.104-.146.173-.31.173-.5 0-.217-.087-.4-.208-.555z
"""
{-| Base for all icons.
-}
icon : String -> List (Html.Attribute msg) -> Html.Html msg
icon iconPath attributes =
svg
([ width "36", height "36", viewBox "0 0 36 36" ] ++ attributes)
[ path [ d iconPath ] [] ]
{-| Backspace icon.
-}
backspace : List (Html.Attribute msg) -> Html.Html msg
backspace =
icon
"""
M35.082 6.578c-.626-.626-1.424-.953-2.325-.953H11.813c-1.71
0-3.074.66-4.058 2L0 17.995 7.763 28.3l.012.017.013.016c.486.624 1.014
1.105 1.617 1.437.712.392 1.522.608 2.407.608h20.954c1.84 0 3.234-1.565
3.234-3.445v-18c0-.902-.292-1.726-.918-2.352zM29.07
23.365c.108.107.167.25.167.402 0 .15-.06.295-.167.4l-1.534
1.54c-.11.113-.255.168-.4.168-.146 0-.29-.055-.4-.167l-5.36-5.376-5.36
5.376c-.11.112-.256.167-.4.167-.146
0-.29-.055-.4-.167l-1.536-1.54c-.107-.106-.167-.25-.167-.4
0-.152.06-.296.167-.403L19.062 18l-5.396-5.365c-.22-.22-.22-.58
0-.803l1.533-1.54c.106-.108.25-.167.4-.167.15 0 .294.06.4.166l5.375 5.312
5.375-5.31c.106-.108.25-.167.4-.167.15 0 .294.06.4.166l1.534
1.542c.222.222.222.582 0 .803L23.69 18l5.38 5.365z
"""
| 19252 | module Ui.Icons exposing (..)
{-| This module contains icons for the components.
# Icons
@docs icon, close, checkmark, chevronRight, chevronLeft, plus, search
@docs starFull, starEmpty, backspace, calendar
-}
import Svg.Attributes exposing (d, width, height, viewBox)
import Svg exposing (svg, path)
import Html
{-| Calendar icon.
-}
calendar : List (Html.Attribute msg) -> Html.Html msg
calendar =
icon
"""
M9 0C7.578 0 6.428 1.15 6.428 2.572v2.57c0 1.423 1.15 2.573 2.572 2.573
1.422 0 2.572-1.15 2.572-2.572v-2.57C11.572 1.15 10.422 0 9 0zm18 0c-1.422
0-2.572 1.15-2.572 2.572v2.57c0 1.423 1.15 2.573 2.572 2.573 1.422 0
2.572-1.15 2.572-2.572v-2.57C29.572 1.15 28.422 0 27 0zM.643 2.572c-.354
0-.643.29-.643.643v32.142c0 .354.29.643.643.643h34.714c.354 0
.643-.29.643-.643V3.215c0-.354-.29-.643-.643-.643h-4.5v3.27C30.857 7.65
28.993 9 27.064 9c-1.928 0-3.92-1.35-3.92-3.158v-3.27H12.856v3.27C12.857
7.65 10.93 9 9 9 7.07 9 5.143 7.65 5.143 5.842v-3.27h-4.5zm3.214
9h28.286v20.57H3.857v-20.57z
"""
{-| Empty star icon.
-}
starEmpty : List (Html.Attribute msg) -> Html.Html msg
starEmpty =
icon
"""
M36 13.937l-12.945-1.11L18 .89l-5.056 11.936L0 13.936l9.82 8.513-2.944
12.66L18 28.397l11.123 6.71L26.18 22.45 36 13.937zm-16.527 12.02L18
25.066l-1.473.89-5.345 3.224 1.415-6.085.39-1.674-1.3-1.125L6.965
16.2l6.223-.533 1.71-.147.67-1.582L18 8.2l2.43 5.738.67 1.582 1.712.147
6.223.534-4.722 4.095-1.3 1.126.39 1.675 1.415 6.086-5.345-3.224z
"""
{-| Full star icon.
-}
starFull : List (Html.Attribute msg) -> Html.Html msg
starFull =
icon
"""
M23.055 12.826L18 .89l-5.056 11.936L0 13.936l9.82 8.514-2.944 12.66L18
28.397l11.123 6.71L26.18 22.45 36 13.937
"""
{-| Search icon.
-}
search : List (Html.Attribute msg) -> Html.Html msg
search =
icon
"""
M35.72 30.245l-7.95-8.05c1.293-2.26 1.968-4.77 1.968-7.302C29.738
6.683 23.063 0 14.868 0 6.676 0 0 6.683 0 14.893s6.675 14.893 14.87
14.893c2.614 0 5.202-.722 7.508-2.1l7.913
8.023c.18.178.432.29.685.29.253 0
.506-.103.684-.29l4.06-4.106c.374-.384.374-.984 0-1.36zM14.87
5.802c5.005 0 9.074 4.077 9.074 9.09 0 5.015-4.07 9.092-9.075
9.092-5.008 0-9.076-4.077-9.076-9.09 0-5.015 4.068-9.092 9.075-9.092z
"""
{-| Plus icon.
-}
plus : List (Html.Attribute msg) -> Html.Html msg
plus =
icon "M0 21h15v15h6V21h15v-6H21V0h-6v15H0"
{-| Close icon.
-}
close : List (Html.Attribute msg) -> Html.Html msg
close =
icon
"""
M35.592 30.256l-12.3-12.34L35.62 5.736c.507-.507.507-1.332
0-1.838L32.114.375C31.87.13 31.542 0 31.194 0c-.346
0-.674.14-.917.375L18.005 12.518 5.715.384C5.47.14 5.14.01
4.794.01c-.347 0-.675.14-.918.374L.38 3.907c-.507.506-.507
1.33 0 1.837l12.328 12.18L.418 30.257c-.245.244-.385.572-.385.918
0 .347.13.675.384.92l3.506 3.522c.254.253.582.384.92.384.327 0
.665-.122.918-.384l12.245-12.294 12.253
12.284c.253.253.58.385.92.385.327 0
.664-.12.917-.384l3.507-3.523c.243-.243.384-.57.384-.918-.01-.337-.15-.665-.394-.91z
"""
{-| Right chevron icon.
-}
chevronRight : List (Html.Attribute msg) -> Html.Html msg
chevronRight =
icon
"""
M21.403 17.996L7.963 4c-.34-.345-.33-.916.015-1.27L10.382.27c.345-.353.908-.36
1.246-.016l16.415 17.1c.177.176.257.417.24.65.01.24-.07.474-.24.65L11.628
35.747c-.338.345-.9.337-1.246-.016l-2.404-2.46c-.346-.354-.354-.925-.016-1.27l13.44-14.004z
"""
{-| Left chevron icon.
-}
chevronLeft : List (Html.Attribute msg) -> Html.Html msg
chevronLeft =
icon
"""
M14.597 17.996L28.037
4c.34-.345.33-.916-.015-1.27L25.618.27c-.345-.353-.908-.36-1.246-.016L7.957
17.344c-.177.178-.257.42-.24.652-.01.24.07.474.24.65l16.415
17.1c.338.345.9.337 1.246-.016l2.404-2.46c.346-.354.354-.925.016-1.27l-13.44-14.004z
"""
{-| Checkmark icon.
-}
checkmark : List (Html.Attribute msg) -> Html.Html msg
checkmark =
icon
"""
M35.792 5.332L31.04 1.584c-.147-.12-.33-.208-.537-.208-.207
0-.398.087-.545.217l-17.286 22.21S5.877 17.27 5.687
17.08c-.19-.19-.442-.51-.822-.51-.38 0-.554.268-.753.467-.148.156-2.57
2.7-3.766 3.964-.07.077-.112.12-.173.18-.104.148-.173.313-.173.494 0
.19.07.347.173.494l.242.225s12.058 11.582 12.257 11.78c.2.2.442.45.797.45.345
0 .63-.37.795-.536l21.562-27.7c.104-.146.173-.31.173-.5 0-.217-.087-.4-.208-.555z
"""
{-| Base for all icons.
-}
icon : String -> List (Html.Attribute msg) -> Html.Html msg
icon iconPath attributes =
svg
([ width "36", height "36", viewBox "0 0 36 36" ] ++ attributes)
[ path [ d iconPath ] [] ]
{-| Backspace icon.
-}
backspace : List (Html.Attribute msg) -> Html.Html msg
backspace =
icon
"""
M35.082 6.578c-.626-.626-1.424-.953-2.325-.953H11.813c-1.71
0-3.074.66-4.058 2L0 17.995 7.763 28.3l.012.017.013.016c.486.624 1.014
1.105 1.617 1.437.712.392 1.522.608 2.407.608h20.954c1.84 0 3.234-1.565
3.234-3.445v-18c0-.902-.292-1.726-.918-2.352zM29.07
23.365c.172.16.58.3.167.402 0 .15-.06.295-.167.4l-1.534
1.54c-.11.113-.255.168-.4.168-.146 0-.29-.055-.4-.167l-5.36-5.376-5.36
5.376c-.11.112-.256.167-.4.167-.146
0-.29-.055-.4-.167l-1.536-1.54c-.107-.106-.167-.25-.167-.4
0-.152.06-.296.167-.403L19.062 18l-5.396-5.365c-.22-.22-.22-.58
0-.803l1.533-1.54c.106-.108.25-.167.4-.167.15 0 .294.06.4.166l5.375 5.312
5.375-5.31c.106-.108.25-.167.4-.167.15 0 .294.06.4.166l1.534
1.542c.222.222.222.582 0 .803L23.69 18l5.38 5.365z
"""
| true | module Ui.Icons exposing (..)
{-| This module contains icons for the components.
# Icons
@docs icon, close, checkmark, chevronRight, chevronLeft, plus, search
@docs starFull, starEmpty, backspace, calendar
-}
import Svg.Attributes exposing (d, width, height, viewBox)
import Svg exposing (svg, path)
import Html
{-| Calendar icon.
-}
calendar : List (Html.Attribute msg) -> Html.Html msg
calendar =
icon
"""
M9 0C7.578 0 6.428 1.15 6.428 2.572v2.57c0 1.423 1.15 2.573 2.572 2.573
1.422 0 2.572-1.15 2.572-2.572v-2.57C11.572 1.15 10.422 0 9 0zm18 0c-1.422
0-2.572 1.15-2.572 2.572v2.57c0 1.423 1.15 2.573 2.572 2.573 1.422 0
2.572-1.15 2.572-2.572v-2.57C29.572 1.15 28.422 0 27 0zM.643 2.572c-.354
0-.643.29-.643.643v32.142c0 .354.29.643.643.643h34.714c.354 0
.643-.29.643-.643V3.215c0-.354-.29-.643-.643-.643h-4.5v3.27C30.857 7.65
28.993 9 27.064 9c-1.928 0-3.92-1.35-3.92-3.158v-3.27H12.856v3.27C12.857
7.65 10.93 9 9 9 7.07 9 5.143 7.65 5.143 5.842v-3.27h-4.5zm3.214
9h28.286v20.57H3.857v-20.57z
"""
{-| Empty star icon.
-}
starEmpty : List (Html.Attribute msg) -> Html.Html msg
starEmpty =
icon
"""
M36 13.937l-12.945-1.11L18 .89l-5.056 11.936L0 13.936l9.82 8.513-2.944
12.66L18 28.397l11.123 6.71L26.18 22.45 36 13.937zm-16.527 12.02L18
25.066l-1.473.89-5.345 3.224 1.415-6.085.39-1.674-1.3-1.125L6.965
16.2l6.223-.533 1.71-.147.67-1.582L18 8.2l2.43 5.738.67 1.582 1.712.147
6.223.534-4.722 4.095-1.3 1.126.39 1.675 1.415 6.086-5.345-3.224z
"""
{-| Full star icon.
-}
starFull : List (Html.Attribute msg) -> Html.Html msg
starFull =
icon
"""
M23.055 12.826L18 .89l-5.056 11.936L0 13.936l9.82 8.514-2.944 12.66L18
28.397l11.123 6.71L26.18 22.45 36 13.937
"""
{-| Search icon.
-}
search : List (Html.Attribute msg) -> Html.Html msg
search =
icon
"""
M35.72 30.245l-7.95-8.05c1.293-2.26 1.968-4.77 1.968-7.302C29.738
6.683 23.063 0 14.868 0 6.676 0 0 6.683 0 14.893s6.675 14.893 14.87
14.893c2.614 0 5.202-.722 7.508-2.1l7.913
8.023c.18.178.432.29.685.29.253 0
.506-.103.684-.29l4.06-4.106c.374-.384.374-.984 0-1.36zM14.87
5.802c5.005 0 9.074 4.077 9.074 9.09 0 5.015-4.07 9.092-9.075
9.092-5.008 0-9.076-4.077-9.076-9.09 0-5.015 4.068-9.092 9.075-9.092z
"""
{-| Plus icon.
-}
plus : List (Html.Attribute msg) -> Html.Html msg
plus =
icon "M0 21h15v15h6V21h15v-6H21V0h-6v15H0"
{-| Close icon.
-}
close : List (Html.Attribute msg) -> Html.Html msg
close =
icon
"""
M35.592 30.256l-12.3-12.34L35.62 5.736c.507-.507.507-1.332
0-1.838L32.114.375C31.87.13 31.542 0 31.194 0c-.346
0-.674.14-.917.375L18.005 12.518 5.715.384C5.47.14 5.14.01
4.794.01c-.347 0-.675.14-.918.374L.38 3.907c-.507.506-.507
1.33 0 1.837l12.328 12.18L.418 30.257c-.245.244-.385.572-.385.918
0 .347.13.675.384.92l3.506 3.522c.254.253.582.384.92.384.327 0
.665-.122.918-.384l12.245-12.294 12.253
12.284c.253.253.58.385.92.385.327 0
.664-.12.917-.384l3.507-3.523c.243-.243.384-.57.384-.918-.01-.337-.15-.665-.394-.91z
"""
{-| Right chevron icon.
-}
chevronRight : List (Html.Attribute msg) -> Html.Html msg
chevronRight =
icon
"""
M21.403 17.996L7.963 4c-.34-.345-.33-.916.015-1.27L10.382.27c.345-.353.908-.36
1.246-.016l16.415 17.1c.177.176.257.417.24.65.01.24-.07.474-.24.65L11.628
35.747c-.338.345-.9.337-1.246-.016l-2.404-2.46c-.346-.354-.354-.925-.016-1.27l13.44-14.004z
"""
{-| Left chevron icon.
-}
chevronLeft : List (Html.Attribute msg) -> Html.Html msg
chevronLeft =
icon
"""
M14.597 17.996L28.037
4c.34-.345.33-.916-.015-1.27L25.618.27c-.345-.353-.908-.36-1.246-.016L7.957
17.344c-.177.178-.257.42-.24.652-.01.24.07.474.24.65l16.415
17.1c.338.345.9.337 1.246-.016l2.404-2.46c.346-.354.354-.925.016-1.27l-13.44-14.004z
"""
{-| Checkmark icon.
-}
checkmark : List (Html.Attribute msg) -> Html.Html msg
checkmark =
icon
"""
M35.792 5.332L31.04 1.584c-.147-.12-.33-.208-.537-.208-.207
0-.398.087-.545.217l-17.286 22.21S5.877 17.27 5.687
17.08c-.19-.19-.442-.51-.822-.51-.38 0-.554.268-.753.467-.148.156-2.57
2.7-3.766 3.964-.07.077-.112.12-.173.18-.104.148-.173.313-.173.494 0
.19.07.347.173.494l.242.225s12.058 11.582 12.257 11.78c.2.2.442.45.797.45.345
0 .63-.37.795-.536l21.562-27.7c.104-.146.173-.31.173-.5 0-.217-.087-.4-.208-.555z
"""
{-| Base for all icons.
-}
icon : String -> List (Html.Attribute msg) -> Html.Html msg
icon iconPath attributes =
svg
([ width "36", height "36", viewBox "0 0 36 36" ] ++ attributes)
[ path [ d iconPath ] [] ]
{-| Backspace icon.
-}
backspace : List (Html.Attribute msg) -> Html.Html msg
backspace =
icon
"""
M35.082 6.578c-.626-.626-1.424-.953-2.325-.953H11.813c-1.71
0-3.074.66-4.058 2L0 17.995 7.763 28.3l.012.017.013.016c.486.624 1.014
1.105 1.617 1.437.712.392 1.522.608 2.407.608h20.954c1.84 0 3.234-1.565
3.234-3.445v-18c0-.902-.292-1.726-.918-2.352zM29.07
23.365c.PI:IP_ADDRESS:172.16.58.3END_PI.167.402 0 .15-.06.295-.167.4l-1.534
1.54c-.11.113-.255.168-.4.168-.146 0-.29-.055-.4-.167l-5.36-5.376-5.36
5.376c-.11.112-.256.167-.4.167-.146
0-.29-.055-.4-.167l-1.536-1.54c-.107-.106-.167-.25-.167-.4
0-.152.06-.296.167-.403L19.062 18l-5.396-5.365c-.22-.22-.22-.58
0-.803l1.533-1.54c.106-.108.25-.167.4-.167.15 0 .294.06.4.166l5.375 5.312
5.375-5.31c.106-.108.25-.167.4-.167.15 0 .294.06.4.166l1.534
1.542c.222.222.222.582 0 .803L23.69 18l5.38 5.365z
"""
| elm |
[
{
"context": "{--\n\nCopyright (c) 2016, William Whitacre\nAll rights reserved.\n\nRedistribution and use in s",
"end": 41,
"score": 0.9998443723,
"start": 25,
"tag": "NAME",
"value": "William Whitacre"
}
] | src/Pylon/Resource.elm | williamwhitacre/pylon | 4 | {--
Copyright (c) 2016, William Whitacre
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--}
module Pylon.Resource
( Resource(..)
, def, pending, undecided, unknown, void
, maybeOr, resultOr
, maybeKnown
, assumeIf, assumeIfNot, assumeInCase, deriveIf, deriveKnown
, otherwise
, therefore
, decideBy
, isUnknown, isNotUnknown
, isPending, isNotPending
, isUndecided, isNotUndecided
, isVoid, isNotVoid
, isKnown, isNotKnown
, isAny, isAll
) where
{-| Resource types and reductions. Heavily pruned from Scaffold predecessor to give only what has
been tested, used in practice, and proven useful.
# Resource Type
This type represents a single remote resource in such a way that it's state can be easily reduced
to a more abstract representation, either for another part of the system, or the user's view itself.
We export the tags as well so as to allow the user easy case destructuring.
@docs Resource
# Resource Constructors
@docs def, pending, undecided, void, unknown
# Predicate Composition
@docs isAll, isAny
# Predicates
@docs isKnown, isNotKnown, isPending, isNotPending, isNotUndecided, isNotUnknown, isNotVoid, isUndecided, isUnknown, isVoid
# Reduction
@docs therefore, otherwise, decideBy, assumeIf, assumeIfNot, assumeInCase, deriveIf, deriveKnown
# Interop with Result and Maybe
@docs maybeKnown, maybeOr, resultOr
-}
import Debug
{-| A resource item. -}
type Resource errortype v =
Unknown
| Pending
| Void
| Undecided (errortype)
| Known v
{-| True if the resource is unknown. -}
isUnknown : Resource errortype v -> Bool
isUnknown res =
case res of
Unknown -> True
_ -> False
{-| False if the resource is unknown. -}
isNotUnknown : Resource errortype v -> Bool
isNotUnknown = isUnknown >> not
{-| True if the resource is pending. -}
isPending : Resource errortype v -> Bool
isPending res =
case res of
Pending -> True
_ -> False
{-| False if the resource is pending. -}
isNotPending : Resource errortype v -> Bool
isNotPending = isPending >> not
{-| True if the resource is void. -}
isVoid : Resource errortype v -> Bool
isVoid res =
case res of
Void -> True
_ -> False
{-| False if the resource is void. -}
isNotVoid : Resource errortype v -> Bool
isNotVoid = isVoid >> not
{-| True if the resource is undecided. -}
isUndecided : Resource errortype v -> Bool
isUndecided res =
case res of
Undecided _ -> True
_ -> False
{-| False if the resource is undecided. -}
isNotUndecided : Resource errortype v -> Bool
isNotUndecided = isUndecided >> not
{-| True if the resource is known. -}
isKnown : Resource errortype v -> Bool
isKnown res =
case res of
Known _ -> True
_ -> False
{-| False if the resource is known. -}
isNotKnown : Resource errortype v -> Bool
isNotKnown = isKnown >> not
{-| True if _any_ of the given predicates is True, otherwise False. -}
isAny : List (Resource errortype v -> Bool) -> Resource errortype v -> Bool
isAny predicates res =
case predicates of
[] -> Debug.crash "Called Resource.isAny with an empty list!"
f :: [] -> f res
f :: fs' -> if f res then True else isAny fs' res
{-| True if _all_ of the given predicates is True, otherwise False. -}
isAll : List (Resource errortype v -> Bool) -> Resource errortype v -> Bool
isAll predicates res =
case predicates of
[] -> Debug.crash "Called Resource.isAllOf with an empty list!"
f :: [] -> f res
f :: fs' -> if not (f res) then False else isAll fs' res
{-| Given a resource of value type v, create a resource of value type v' by transforming the
known value or group using some function (v -> v'). NOTE that this will create an entirely new
resouce structure, and thus any pending changes will be integrated immediately. If you wish to
preserve deltas for the purpose of mirroring and efficient data flow, then one should be using
deltaTo in order to transform just the changes. -}
therefore : (v -> v') -> Resource errortype v -> Resource errortype v'
therefore xdcr =
deriveKnown (xdcr >> Known)
{-| If the resource is an undecided resource, then the given -}
decideBy : (errortype -> Resource errortype v) -> Resource errortype v -> Resource errortype v
decideBy decider res =
case res of
Undecided err' -> decider err'
_ -> res
{-| If the given predicate is satisfied, the result will be known to the the given value, otherwise
the given resource will be given unchanged. -}
assumeIf : (Resource errortype v -> Bool) -> v -> Resource errortype v -> Resource errortype v
assumeIf satisfies assume res =
if satisfies res then Known assume else res
{-| Negation of assumeIf. -}
assumeIfNot : (Resource errortype v -> Bool) -> v -> Resource errortype v -> Resource errortype v
assumeIfNot satisfies assume res =
assumeIf (satisfies >> not) assume res
{-| In the case that the provided function returns `Just x`, the resource shall be known as that
value, otherwise the Resource shall remain unchanged. -}
assumeInCase : (Resource errortype v -> Maybe v) -> Resource errortype v -> Resource errortype v
assumeInCase possibleAssumption res =
Maybe.map Known (possibleAssumption res)
|> Maybe.withDefault res
{-| If the predicate is true, apply the given transformation to get a new resource. -}
deriveIf : (Resource errortype v' -> Bool) -> (Resource errortype v' -> Resource errortype v') -> Resource errortype v' -> Resource errortype v'
deriveIf satisfies f res =
if satisfies res then f res else res
{-| If the resource is known, then use the given function to create an entirely new replacement resource,
otherwise carry the state to the new resource. This always transforms the type because no other states
carry the value type. -}
deriveKnown : (v -> Resource errortype v') -> Resource errortype v -> Resource errortype v'
deriveKnown xdcr res =
case res of
Unknown -> Unknown
Pending -> Pending
Void -> Void
Undecided err' -> Undecided err'
Known x' -> xdcr x'
{-| If a resource is known, then give Just it's value, otherwise Nothing. -}
maybeKnown : Resource errortype v' -> Maybe v'
maybeKnown res' =
case res' of
Known x' -> Just x'
_ -> Nothing
{-| In the event that the given resource is not a simple `def`, we replace it with a different simple
resource. -}
otherwise : v' -> Resource errortype v' -> v'
otherwise assumption res' =
case res' of
Known x' -> x'
_ -> assumption
{-| -}
unknown : Resource errortype v
unknown = Unknown
{-| -}
pending : Resource errortype v
pending = Pending
{-| -}
void : Resource errortype v
void = Void
{-| -}
undecided : errortype -> Resource errortype v
undecided = Undecided
{-| -}
def : v -> Resource errortype v
def = Known
{-| -}
resultOr : (errortype -> Resource errortype v) -> Result (errortype) v -> Resource errortype v
resultOr errorResource result =
case result of
Result.Ok data -> def data
Result.Err err' -> errorResource err'
{-| -}
maybeOr : Resource errortype v -> Maybe v -> Resource errortype v
maybeOr nothingResource maybeValue =
Maybe.map Known maybeValue
|> Maybe.withDefault nothingResource
| 51132 | {--
Copyright (c) 2016, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--}
module Pylon.Resource
( Resource(..)
, def, pending, undecided, unknown, void
, maybeOr, resultOr
, maybeKnown
, assumeIf, assumeIfNot, assumeInCase, deriveIf, deriveKnown
, otherwise
, therefore
, decideBy
, isUnknown, isNotUnknown
, isPending, isNotPending
, isUndecided, isNotUndecided
, isVoid, isNotVoid
, isKnown, isNotKnown
, isAny, isAll
) where
{-| Resource types and reductions. Heavily pruned from Scaffold predecessor to give only what has
been tested, used in practice, and proven useful.
# Resource Type
This type represents a single remote resource in such a way that it's state can be easily reduced
to a more abstract representation, either for another part of the system, or the user's view itself.
We export the tags as well so as to allow the user easy case destructuring.
@docs Resource
# Resource Constructors
@docs def, pending, undecided, void, unknown
# Predicate Composition
@docs isAll, isAny
# Predicates
@docs isKnown, isNotKnown, isPending, isNotPending, isNotUndecided, isNotUnknown, isNotVoid, isUndecided, isUnknown, isVoid
# Reduction
@docs therefore, otherwise, decideBy, assumeIf, assumeIfNot, assumeInCase, deriveIf, deriveKnown
# Interop with Result and Maybe
@docs maybeKnown, maybeOr, resultOr
-}
import Debug
{-| A resource item. -}
type Resource errortype v =
Unknown
| Pending
| Void
| Undecided (errortype)
| Known v
{-| True if the resource is unknown. -}
isUnknown : Resource errortype v -> Bool
isUnknown res =
case res of
Unknown -> True
_ -> False
{-| False if the resource is unknown. -}
isNotUnknown : Resource errortype v -> Bool
isNotUnknown = isUnknown >> not
{-| True if the resource is pending. -}
isPending : Resource errortype v -> Bool
isPending res =
case res of
Pending -> True
_ -> False
{-| False if the resource is pending. -}
isNotPending : Resource errortype v -> Bool
isNotPending = isPending >> not
{-| True if the resource is void. -}
isVoid : Resource errortype v -> Bool
isVoid res =
case res of
Void -> True
_ -> False
{-| False if the resource is void. -}
isNotVoid : Resource errortype v -> Bool
isNotVoid = isVoid >> not
{-| True if the resource is undecided. -}
isUndecided : Resource errortype v -> Bool
isUndecided res =
case res of
Undecided _ -> True
_ -> False
{-| False if the resource is undecided. -}
isNotUndecided : Resource errortype v -> Bool
isNotUndecided = isUndecided >> not
{-| True if the resource is known. -}
isKnown : Resource errortype v -> Bool
isKnown res =
case res of
Known _ -> True
_ -> False
{-| False if the resource is known. -}
isNotKnown : Resource errortype v -> Bool
isNotKnown = isKnown >> not
{-| True if _any_ of the given predicates is True, otherwise False. -}
isAny : List (Resource errortype v -> Bool) -> Resource errortype v -> Bool
isAny predicates res =
case predicates of
[] -> Debug.crash "Called Resource.isAny with an empty list!"
f :: [] -> f res
f :: fs' -> if f res then True else isAny fs' res
{-| True if _all_ of the given predicates is True, otherwise False. -}
isAll : List (Resource errortype v -> Bool) -> Resource errortype v -> Bool
isAll predicates res =
case predicates of
[] -> Debug.crash "Called Resource.isAllOf with an empty list!"
f :: [] -> f res
f :: fs' -> if not (f res) then False else isAll fs' res
{-| Given a resource of value type v, create a resource of value type v' by transforming the
known value or group using some function (v -> v'). NOTE that this will create an entirely new
resouce structure, and thus any pending changes will be integrated immediately. If you wish to
preserve deltas for the purpose of mirroring and efficient data flow, then one should be using
deltaTo in order to transform just the changes. -}
therefore : (v -> v') -> Resource errortype v -> Resource errortype v'
therefore xdcr =
deriveKnown (xdcr >> Known)
{-| If the resource is an undecided resource, then the given -}
decideBy : (errortype -> Resource errortype v) -> Resource errortype v -> Resource errortype v
decideBy decider res =
case res of
Undecided err' -> decider err'
_ -> res
{-| If the given predicate is satisfied, the result will be known to the the given value, otherwise
the given resource will be given unchanged. -}
assumeIf : (Resource errortype v -> Bool) -> v -> Resource errortype v -> Resource errortype v
assumeIf satisfies assume res =
if satisfies res then Known assume else res
{-| Negation of assumeIf. -}
assumeIfNot : (Resource errortype v -> Bool) -> v -> Resource errortype v -> Resource errortype v
assumeIfNot satisfies assume res =
assumeIf (satisfies >> not) assume res
{-| In the case that the provided function returns `Just x`, the resource shall be known as that
value, otherwise the Resource shall remain unchanged. -}
assumeInCase : (Resource errortype v -> Maybe v) -> Resource errortype v -> Resource errortype v
assumeInCase possibleAssumption res =
Maybe.map Known (possibleAssumption res)
|> Maybe.withDefault res
{-| If the predicate is true, apply the given transformation to get a new resource. -}
deriveIf : (Resource errortype v' -> Bool) -> (Resource errortype v' -> Resource errortype v') -> Resource errortype v' -> Resource errortype v'
deriveIf satisfies f res =
if satisfies res then f res else res
{-| If the resource is known, then use the given function to create an entirely new replacement resource,
otherwise carry the state to the new resource. This always transforms the type because no other states
carry the value type. -}
deriveKnown : (v -> Resource errortype v') -> Resource errortype v -> Resource errortype v'
deriveKnown xdcr res =
case res of
Unknown -> Unknown
Pending -> Pending
Void -> Void
Undecided err' -> Undecided err'
Known x' -> xdcr x'
{-| If a resource is known, then give Just it's value, otherwise Nothing. -}
maybeKnown : Resource errortype v' -> Maybe v'
maybeKnown res' =
case res' of
Known x' -> Just x'
_ -> Nothing
{-| In the event that the given resource is not a simple `def`, we replace it with a different simple
resource. -}
otherwise : v' -> Resource errortype v' -> v'
otherwise assumption res' =
case res' of
Known x' -> x'
_ -> assumption
{-| -}
unknown : Resource errortype v
unknown = Unknown
{-| -}
pending : Resource errortype v
pending = Pending
{-| -}
void : Resource errortype v
void = Void
{-| -}
undecided : errortype -> Resource errortype v
undecided = Undecided
{-| -}
def : v -> Resource errortype v
def = Known
{-| -}
resultOr : (errortype -> Resource errortype v) -> Result (errortype) v -> Resource errortype v
resultOr errorResource result =
case result of
Result.Ok data -> def data
Result.Err err' -> errorResource err'
{-| -}
maybeOr : Resource errortype v -> Maybe v -> Resource errortype v
maybeOr nothingResource maybeValue =
Maybe.map Known maybeValue
|> Maybe.withDefault nothingResource
| true | {--
Copyright (c) 2016, PI:NAME:<NAME>END_PI
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--}
module Pylon.Resource
( Resource(..)
, def, pending, undecided, unknown, void
, maybeOr, resultOr
, maybeKnown
, assumeIf, assumeIfNot, assumeInCase, deriveIf, deriveKnown
, otherwise
, therefore
, decideBy
, isUnknown, isNotUnknown
, isPending, isNotPending
, isUndecided, isNotUndecided
, isVoid, isNotVoid
, isKnown, isNotKnown
, isAny, isAll
) where
{-| Resource types and reductions. Heavily pruned from Scaffold predecessor to give only what has
been tested, used in practice, and proven useful.
# Resource Type
This type represents a single remote resource in such a way that it's state can be easily reduced
to a more abstract representation, either for another part of the system, or the user's view itself.
We export the tags as well so as to allow the user easy case destructuring.
@docs Resource
# Resource Constructors
@docs def, pending, undecided, void, unknown
# Predicate Composition
@docs isAll, isAny
# Predicates
@docs isKnown, isNotKnown, isPending, isNotPending, isNotUndecided, isNotUnknown, isNotVoid, isUndecided, isUnknown, isVoid
# Reduction
@docs therefore, otherwise, decideBy, assumeIf, assumeIfNot, assumeInCase, deriveIf, deriveKnown
# Interop with Result and Maybe
@docs maybeKnown, maybeOr, resultOr
-}
import Debug
{-| A resource item. -}
type Resource errortype v =
Unknown
| Pending
| Void
| Undecided (errortype)
| Known v
{-| True if the resource is unknown. -}
isUnknown : Resource errortype v -> Bool
isUnknown res =
case res of
Unknown -> True
_ -> False
{-| False if the resource is unknown. -}
isNotUnknown : Resource errortype v -> Bool
isNotUnknown = isUnknown >> not
{-| True if the resource is pending. -}
isPending : Resource errortype v -> Bool
isPending res =
case res of
Pending -> True
_ -> False
{-| False if the resource is pending. -}
isNotPending : Resource errortype v -> Bool
isNotPending = isPending >> not
{-| True if the resource is void. -}
isVoid : Resource errortype v -> Bool
isVoid res =
case res of
Void -> True
_ -> False
{-| False if the resource is void. -}
isNotVoid : Resource errortype v -> Bool
isNotVoid = isVoid >> not
{-| True if the resource is undecided. -}
isUndecided : Resource errortype v -> Bool
isUndecided res =
case res of
Undecided _ -> True
_ -> False
{-| False if the resource is undecided. -}
isNotUndecided : Resource errortype v -> Bool
isNotUndecided = isUndecided >> not
{-| True if the resource is known. -}
isKnown : Resource errortype v -> Bool
isKnown res =
case res of
Known _ -> True
_ -> False
{-| False if the resource is known. -}
isNotKnown : Resource errortype v -> Bool
isNotKnown = isKnown >> not
{-| True if _any_ of the given predicates is True, otherwise False. -}
isAny : List (Resource errortype v -> Bool) -> Resource errortype v -> Bool
isAny predicates res =
case predicates of
[] -> Debug.crash "Called Resource.isAny with an empty list!"
f :: [] -> f res
f :: fs' -> if f res then True else isAny fs' res
{-| True if _all_ of the given predicates is True, otherwise False. -}
isAll : List (Resource errortype v -> Bool) -> Resource errortype v -> Bool
isAll predicates res =
case predicates of
[] -> Debug.crash "Called Resource.isAllOf with an empty list!"
f :: [] -> f res
f :: fs' -> if not (f res) then False else isAll fs' res
{-| Given a resource of value type v, create a resource of value type v' by transforming the
known value or group using some function (v -> v'). NOTE that this will create an entirely new
resouce structure, and thus any pending changes will be integrated immediately. If you wish to
preserve deltas for the purpose of mirroring and efficient data flow, then one should be using
deltaTo in order to transform just the changes. -}
therefore : (v -> v') -> Resource errortype v -> Resource errortype v'
therefore xdcr =
deriveKnown (xdcr >> Known)
{-| If the resource is an undecided resource, then the given -}
decideBy : (errortype -> Resource errortype v) -> Resource errortype v -> Resource errortype v
decideBy decider res =
case res of
Undecided err' -> decider err'
_ -> res
{-| If the given predicate is satisfied, the result will be known to the the given value, otherwise
the given resource will be given unchanged. -}
assumeIf : (Resource errortype v -> Bool) -> v -> Resource errortype v -> Resource errortype v
assumeIf satisfies assume res =
if satisfies res then Known assume else res
{-| Negation of assumeIf. -}
assumeIfNot : (Resource errortype v -> Bool) -> v -> Resource errortype v -> Resource errortype v
assumeIfNot satisfies assume res =
assumeIf (satisfies >> not) assume res
{-| In the case that the provided function returns `Just x`, the resource shall be known as that
value, otherwise the Resource shall remain unchanged. -}
assumeInCase : (Resource errortype v -> Maybe v) -> Resource errortype v -> Resource errortype v
assumeInCase possibleAssumption res =
Maybe.map Known (possibleAssumption res)
|> Maybe.withDefault res
{-| If the predicate is true, apply the given transformation to get a new resource. -}
deriveIf : (Resource errortype v' -> Bool) -> (Resource errortype v' -> Resource errortype v') -> Resource errortype v' -> Resource errortype v'
deriveIf satisfies f res =
if satisfies res then f res else res
{-| If the resource is known, then use the given function to create an entirely new replacement resource,
otherwise carry the state to the new resource. This always transforms the type because no other states
carry the value type. -}
deriveKnown : (v -> Resource errortype v') -> Resource errortype v -> Resource errortype v'
deriveKnown xdcr res =
case res of
Unknown -> Unknown
Pending -> Pending
Void -> Void
Undecided err' -> Undecided err'
Known x' -> xdcr x'
{-| If a resource is known, then give Just it's value, otherwise Nothing. -}
maybeKnown : Resource errortype v' -> Maybe v'
maybeKnown res' =
case res' of
Known x' -> Just x'
_ -> Nothing
{-| In the event that the given resource is not a simple `def`, we replace it with a different simple
resource. -}
otherwise : v' -> Resource errortype v' -> v'
otherwise assumption res' =
case res' of
Known x' -> x'
_ -> assumption
{-| -}
unknown : Resource errortype v
unknown = Unknown
{-| -}
pending : Resource errortype v
pending = Pending
{-| -}
void : Resource errortype v
void = Void
{-| -}
undecided : errortype -> Resource errortype v
undecided = Undecided
{-| -}
def : v -> Resource errortype v
def = Known
{-| -}
resultOr : (errortype -> Resource errortype v) -> Result (errortype) v -> Resource errortype v
resultOr errorResource result =
case result of
Result.Ok data -> def data
Result.Err err' -> errorResource err'
{-| -}
maybeOr : Resource errortype v -> Maybe v -> Resource errortype v
maybeOr nothingResource maybeValue =
Maybe.map Known maybeValue
|> Maybe.withDefault nothingResource
| elm |
[
{
"context": "D 3-Clause)\n -- Copyright (c) 2017-present, Evan Czaplicki\n -- All rights reserved.\n let\n c",
"end": 3421,
"score": 0.9997671247,
"start": 3407,
"tag": "NAME",
"value": "Evan Czaplicki"
}
] | src/EnumParser.elm | jmbromley/elm-enums | 4 | module EnumParser exposing (parse)
import Enum exposing (Enum)
import Parser exposing ((|.), (|=), Parser)
import Set exposing (Set)
import Util
{-
Parser that takes input of the form:
enum Name1 =
[ Value1_1
, Value1_2
, ...
, Value1_X
]
enum Name2 =
[ Value2_1
, Value2_2
, ...
, Value2_Y
]
...
enum NameN =
[ ValueM_1
, ValueM_2
, ...
, ValueM_Z
]
and produces valid Elm custom types and accompanying JSON encoders/decoders in
an Enums module, thus:
module Enums
exposing
( Name1
, Name2
, Name...
, NameN
, encodeName1
, encodeName2
, encodeName...
, encodeNameN
, decodeName1
, decodeName2
, decodeName...
, decodeNameN
)
import Json.Decode
import Json.Encode
type Name1
= Value1_1
| Value1_2
| ...
| Value1_X
encodeName1 : Name1 -> Json.Encode.Value
encodeName1 =
...
decodeName1 : Json.Decode.Decoder Name1
decodeName1 =
...
type Name2
= ...
...
The following constraints are checked to ensure valid Elm results:
* All Names and Values must be unique.
* All Names and Values must begin with an uppercase character.
* Names and Values cannot be the same as the module or type names of any
default imports.
In addition:
* Elm-style comments are tolerated in the input.
* All indentation, carriage returns and whitespace are ignored in the input;
but the resulting generated code will conform to the style mandated by
elm-format.
-}
parse : String -> Result String String
parse input =
case Parser.run parseFile input of
Ok listEnums ->
Enum.compileToElm listEnums
Err error ->
Err (Util.deadEndsToString error)
parseFile : Parser (List Enum)
parseFile =
Parser.succeed identity
|. spacesOrComment
|= enumSequence
|. spacesOrComment
|. Parser.end
enumSequence : Parser (List Enum)
enumSequence =
let
helper entries =
Parser.oneOf
[ Parser.succeed (\entry -> Parser.Loop (entry :: entries))
|= enum
|. spacesOrComment
, Parser.succeed ()
|> Parser.map (\_ -> Parser.Done entries)
]
in
Parser.loop [] helper
enum : Parser Enum
enum =
Parser.succeed Enum.fromList
|. Parser.keyword "enum"
|. spacesOrComment
|= nameOrValue
|. spacesOrComment
|. Parser.symbol "="
|. spacesOrComment
|= Parser.sequence
{ start = "["
, separator = ","
, end = "]"
, spaces = spacesOrComment
, item = nameOrValue
, trailing = Parser.Forbidden
}
spacesOrComment : Parser ()
spacesOrComment =
-- Taken from example in elm/parser (published under BSD 3-Clause)
-- Copyright (c) 2017-present, Evan Czaplicki
-- All rights reserved.
let
checkOffset oldOffset newOffset =
if oldOffset == newOffset then
Parser.Done ()
else
Parser.Loop newOffset
ifProgress parser offset =
Parser.succeed identity
|. parser
|= Parser.getOffset
|> Parser.map (checkOffset offset)
in
Parser.loop 0 <|
ifProgress <|
Parser.oneOf
[ Parser.lineComment "--"
, Parser.multiComment "{-" "-}" Parser.Nestable
, Parser.spaces
]
nameOrValue : Parser String
nameOrValue =
Parser.variable
{ start = startTest
, inner = innerTest
, reserved = defaultImports
}
startTest : Char -> Bool
startTest =
-- FIXME: too restrictive
Char.isUpper
innerTest : Char -> Bool
innerTest =
-- FIXME: too restrictive
\c -> Char.isAlphaNum c || c == '_'
defaultImports : Set String
defaultImports =
Set.fromList
[ "Basics"
, "Int"
, "Float"
, "Order"
, "Bool"
, "Never"
, "List"
, "Maybe"
, "Just"
, "Nothing"
, "Result"
, "Err"
, "Ok"
, "String"
, "Char"
, "Tuple"
, "Debug"
, "Platform"
, "Program"
, "Cmd"
, "Sub"
]
| 8648 | module EnumParser exposing (parse)
import Enum exposing (Enum)
import Parser exposing ((|.), (|=), Parser)
import Set exposing (Set)
import Util
{-
Parser that takes input of the form:
enum Name1 =
[ Value1_1
, Value1_2
, ...
, Value1_X
]
enum Name2 =
[ Value2_1
, Value2_2
, ...
, Value2_Y
]
...
enum NameN =
[ ValueM_1
, ValueM_2
, ...
, ValueM_Z
]
and produces valid Elm custom types and accompanying JSON encoders/decoders in
an Enums module, thus:
module Enums
exposing
( Name1
, Name2
, Name...
, NameN
, encodeName1
, encodeName2
, encodeName...
, encodeNameN
, decodeName1
, decodeName2
, decodeName...
, decodeNameN
)
import Json.Decode
import Json.Encode
type Name1
= Value1_1
| Value1_2
| ...
| Value1_X
encodeName1 : Name1 -> Json.Encode.Value
encodeName1 =
...
decodeName1 : Json.Decode.Decoder Name1
decodeName1 =
...
type Name2
= ...
...
The following constraints are checked to ensure valid Elm results:
* All Names and Values must be unique.
* All Names and Values must begin with an uppercase character.
* Names and Values cannot be the same as the module or type names of any
default imports.
In addition:
* Elm-style comments are tolerated in the input.
* All indentation, carriage returns and whitespace are ignored in the input;
but the resulting generated code will conform to the style mandated by
elm-format.
-}
parse : String -> Result String String
parse input =
case Parser.run parseFile input of
Ok listEnums ->
Enum.compileToElm listEnums
Err error ->
Err (Util.deadEndsToString error)
parseFile : Parser (List Enum)
parseFile =
Parser.succeed identity
|. spacesOrComment
|= enumSequence
|. spacesOrComment
|. Parser.end
enumSequence : Parser (List Enum)
enumSequence =
let
helper entries =
Parser.oneOf
[ Parser.succeed (\entry -> Parser.Loop (entry :: entries))
|= enum
|. spacesOrComment
, Parser.succeed ()
|> Parser.map (\_ -> Parser.Done entries)
]
in
Parser.loop [] helper
enum : Parser Enum
enum =
Parser.succeed Enum.fromList
|. Parser.keyword "enum"
|. spacesOrComment
|= nameOrValue
|. spacesOrComment
|. Parser.symbol "="
|. spacesOrComment
|= Parser.sequence
{ start = "["
, separator = ","
, end = "]"
, spaces = spacesOrComment
, item = nameOrValue
, trailing = Parser.Forbidden
}
spacesOrComment : Parser ()
spacesOrComment =
-- Taken from example in elm/parser (published under BSD 3-Clause)
-- Copyright (c) 2017-present, <NAME>
-- All rights reserved.
let
checkOffset oldOffset newOffset =
if oldOffset == newOffset then
Parser.Done ()
else
Parser.Loop newOffset
ifProgress parser offset =
Parser.succeed identity
|. parser
|= Parser.getOffset
|> Parser.map (checkOffset offset)
in
Parser.loop 0 <|
ifProgress <|
Parser.oneOf
[ Parser.lineComment "--"
, Parser.multiComment "{-" "-}" Parser.Nestable
, Parser.spaces
]
nameOrValue : Parser String
nameOrValue =
Parser.variable
{ start = startTest
, inner = innerTest
, reserved = defaultImports
}
startTest : Char -> Bool
startTest =
-- FIXME: too restrictive
Char.isUpper
innerTest : Char -> Bool
innerTest =
-- FIXME: too restrictive
\c -> Char.isAlphaNum c || c == '_'
defaultImports : Set String
defaultImports =
Set.fromList
[ "Basics"
, "Int"
, "Float"
, "Order"
, "Bool"
, "Never"
, "List"
, "Maybe"
, "Just"
, "Nothing"
, "Result"
, "Err"
, "Ok"
, "String"
, "Char"
, "Tuple"
, "Debug"
, "Platform"
, "Program"
, "Cmd"
, "Sub"
]
| true | module EnumParser exposing (parse)
import Enum exposing (Enum)
import Parser exposing ((|.), (|=), Parser)
import Set exposing (Set)
import Util
{-
Parser that takes input of the form:
enum Name1 =
[ Value1_1
, Value1_2
, ...
, Value1_X
]
enum Name2 =
[ Value2_1
, Value2_2
, ...
, Value2_Y
]
...
enum NameN =
[ ValueM_1
, ValueM_2
, ...
, ValueM_Z
]
and produces valid Elm custom types and accompanying JSON encoders/decoders in
an Enums module, thus:
module Enums
exposing
( Name1
, Name2
, Name...
, NameN
, encodeName1
, encodeName2
, encodeName...
, encodeNameN
, decodeName1
, decodeName2
, decodeName...
, decodeNameN
)
import Json.Decode
import Json.Encode
type Name1
= Value1_1
| Value1_2
| ...
| Value1_X
encodeName1 : Name1 -> Json.Encode.Value
encodeName1 =
...
decodeName1 : Json.Decode.Decoder Name1
decodeName1 =
...
type Name2
= ...
...
The following constraints are checked to ensure valid Elm results:
* All Names and Values must be unique.
* All Names and Values must begin with an uppercase character.
* Names and Values cannot be the same as the module or type names of any
default imports.
In addition:
* Elm-style comments are tolerated in the input.
* All indentation, carriage returns and whitespace are ignored in the input;
but the resulting generated code will conform to the style mandated by
elm-format.
-}
parse : String -> Result String String
parse input =
case Parser.run parseFile input of
Ok listEnums ->
Enum.compileToElm listEnums
Err error ->
Err (Util.deadEndsToString error)
parseFile : Parser (List Enum)
parseFile =
Parser.succeed identity
|. spacesOrComment
|= enumSequence
|. spacesOrComment
|. Parser.end
enumSequence : Parser (List Enum)
enumSequence =
let
helper entries =
Parser.oneOf
[ Parser.succeed (\entry -> Parser.Loop (entry :: entries))
|= enum
|. spacesOrComment
, Parser.succeed ()
|> Parser.map (\_ -> Parser.Done entries)
]
in
Parser.loop [] helper
enum : Parser Enum
enum =
Parser.succeed Enum.fromList
|. Parser.keyword "enum"
|. spacesOrComment
|= nameOrValue
|. spacesOrComment
|. Parser.symbol "="
|. spacesOrComment
|= Parser.sequence
{ start = "["
, separator = ","
, end = "]"
, spaces = spacesOrComment
, item = nameOrValue
, trailing = Parser.Forbidden
}
spacesOrComment : Parser ()
spacesOrComment =
-- Taken from example in elm/parser (published under BSD 3-Clause)
-- Copyright (c) 2017-present, PI:NAME:<NAME>END_PI
-- All rights reserved.
let
checkOffset oldOffset newOffset =
if oldOffset == newOffset then
Parser.Done ()
else
Parser.Loop newOffset
ifProgress parser offset =
Parser.succeed identity
|. parser
|= Parser.getOffset
|> Parser.map (checkOffset offset)
in
Parser.loop 0 <|
ifProgress <|
Parser.oneOf
[ Parser.lineComment "--"
, Parser.multiComment "{-" "-}" Parser.Nestable
, Parser.spaces
]
nameOrValue : Parser String
nameOrValue =
Parser.variable
{ start = startTest
, inner = innerTest
, reserved = defaultImports
}
startTest : Char -> Bool
startTest =
-- FIXME: too restrictive
Char.isUpper
innerTest : Char -> Bool
innerTest =
-- FIXME: too restrictive
\c -> Char.isAlphaNum c || c == '_'
defaultImports : Set String
defaultImports =
Set.fromList
[ "Basics"
, "Int"
, "Float"
, "Order"
, "Bool"
, "Never"
, "List"
, "Maybe"
, "Just"
, "Nothing"
, "Result"
, "Err"
, "Ok"
, "String"
, "Char"
, "Tuple"
, "Debug"
, "Platform"
, "Program"
, "Cmd"
, "Sub"
]
| elm |
[
{
"context": "riders : List Servant\nriders =\n [ { name = \"Medusa\"\n , spoiler = Nothing\n , id = 23\n ",
"end": 922,
"score": 0.9692669511,
"start": 916,
"tag": "NAME",
"value": "Medusa"
},
{
"context": "inus, riding APlus]\n , phantasm = { name = \"Bellerophon\"\n , rank = APlus\n ",
"end": 2302,
"score": 0.9998331666,
"start": 2291,
"tag": "NAME",
"value": "Bellerophon"
},
{
"context": "), (PhoenixFeather, 13)]\n }\n , { name = \"Georgios\"\n , spoiler = Nothing\n , id = 24\n ",
"end": 3728,
"score": 0.9998752475,
"start": 3720,
"tag": "NAME",
"value": "Georgios"
},
{
"context": " }\n , skills = [ { name = \"Guardian Knight\"\n , rank = APlus\n ",
"end": 4147,
"score": 0.9965364337,
"start": 4132,
"tag": "NAME",
"value": "Guardian Knight"
},
{
"context": " }\n , { name = \"Martyr's Soul\"\n , rank = BPlus\n ",
"end": 4495,
"score": 0.9998175502,
"start": 4482,
"tag": "NAME",
"value": "Martyr's Soul"
},
{
"context": " }\n , { name = \"Battle Continuation\"\n , rank = A\n ",
"end": 4855,
"score": 0.9817183614,
"start": 4836,
"tag": "NAME",
"value": "Battle Continuation"
},
{
"context": "stance A, riding B]\n , phantasm = { name = \"Ascalon\"\n , rank = B\n ",
"end": 5175,
"score": 0.9997437596,
"start": 5168,
"tag": "NAME",
"value": "Ascalon"
},
{
"context": ", (MeteorHorseshoe, 12)]\n }\n , { name = \"Edward Teach\"\n , spoiler = Nothing\n , id = 25\n ",
"end": 6704,
"score": 0.9996567965,
"start": 6692,
"tag": "NAME",
"value": "Edward Teach"
},
{
"context": " }\n , skills = [ { name = \"Voyager of the Storm\"\n , rank = A\n ",
"end": 7131,
"score": 0.995800972,
"start": 7111,
"tag": "NAME",
"value": "Voyager of the Storm"
},
{
"context": " }\n , { name = \"Pirate's Glory\"\n , rank = B\n ",
"end": 7479,
"score": 0.999471426,
"start": 7465,
"tag": "NAME",
"value": "Pirate's Glory"
},
{
"context": " }\n , { name = \"Gentlemanly Love\"\n , rank = C\n ",
"end": 7904,
"score": 0.999614656,
"start": 7888,
"tag": "NAME",
"value": "Gentlemanly Love"
},
{
"context": "[magicResistance E]\n , phantasm = { name = \"Queen Anne's Revenge\"\n , rank = CPlusPlus\n ",
"end": 8405,
"score": 0.999794662,
"start": 8385,
"tag": "NAME",
"value": "Queen Anne's Revenge"
},
{
"context": " 9), (GhostLantern, 12)]\n }\n , { name = \"Boudica\"\n , spoiler = Nothing\n , id = 26\n ",
"end": 9920,
"score": 0.9998325706,
"start": 9913,
"tag": "NAME",
"value": "Boudica"
},
{
"context": " }\n , skills = [ { name = \"Vow to the Goddess\"\n , rank = B\n ",
"end": 10344,
"score": 0.9624657035,
"start": 10326,
"tag": "NAME",
"value": "Vow to the Goddess"
},
{
"context": " }\n , { name = \"Andraste's Protection\"\n , rank = A\n ",
"end": 10897,
"score": 0.999563992,
"start": 10876,
"tag": "NAME",
"value": "Andraste's Protection"
},
{
"context": "stance D, riding A]\n , phantasm = { name = \"Chariot of Boudica\"\n , rank = BPlusPlus\n ",
"end": 11224,
"score": 0.9995381236,
"start": 11206,
"tag": "NAME",
"value": "Chariot of Boudica"
},
{
"context": "l, 10), (VoidsDust, 32)]\n }\n , { name = \"Ushiwakamaru\"\n , spoiler = Nothing\n , id = 27\n ",
"end": 12753,
"score": 0.9997395873,
"start": 12741,
"tag": "NAME",
"value": "Ushiwakamaru"
},
{
"context": " }\n , skills = [ { name = \"Tengu's Strategy\"\n , rank = A\n ",
"end": 13173,
"score": 0.9949151874,
"start": 13157,
"tag": "NAME",
"value": "Tengu's Strategy"
},
{
"context": " }\n , { name = \"Charisma\"\n , rank = CPlus\n ",
"end": 13417,
"score": 0.9841777086,
"start": 13409,
"tag": "NAME",
"value": "Charisma"
},
{
"context": " }\n , { name = \"Art of the Swallow\"\n , rank = B\n ",
"end": 13679,
"score": 0.9937294126,
"start": 13661,
"tag": "NAME",
"value": "Art of the Swallow"
},
{
"context": "ce C, riding APlus]\n , phantasm = { name = \"Dan-No-Ura Eight-Boat Leap\"\n , rank = C\n ",
"end": 14111,
"score": 0.9930797815,
"start": 14085,
"tag": "NAME",
"value": "Dan-No-Ura Eight-Boat Leap"
},
{
"context": " (OctupletCrystals, 16)]\n }\n , { name = \"Alexander\"\n , spoiler = Nothing\n , id = 28\n ",
"end": 15554,
"score": 0.9993835688,
"start": 15545,
"tag": "NAME",
"value": "Alexander"
},
{
"context": " }\n , skills = [ { name = \"Charisma\"\n , rank = C\n ",
"end": 15966,
"score": 0.9967733026,
"start": 15958,
"tag": "NAME",
"value": "Charisma"
},
{
"context": " }\n , { name = \"Fair Youth\"\n , rank = B\n ",
"end": 16214,
"score": 0.9993814826,
"start": 16204,
"tag": "NAME",
"value": "Fair Youth"
},
{
"context": " }\n , { name = \"Omen of the Conqueror\"\n , rank = A\n ",
"end": 16492,
"score": 0.9984437823,
"start": 16471,
"tag": "NAME",
"value": "Omen of the Conqueror"
},
{
"context": "ty E, riding APlus]\n , phantasm = { name = \"Bucephalus\"\n , rank = BPlusPlus\n ",
"end": 16829,
"score": 0.999724865,
"start": 16819,
"tag": "NAME",
"value": "Bucephalus"
},
{
"context": ", 8), (ProofOfHero, 48)]\n }\n , { name = \"Marie Antoinette\"\n , spoiler = Nothing\n , id = 29\n ",
"end": 18299,
"score": 0.9998557568,
"start": 18283,
"tag": "NAME",
"value": "Marie Antoinette"
},
{
"context": " }\n , skills = [ { name = \"Siren Song\"\n , rank = C\n ",
"end": 18716,
"score": 0.9995138645,
"start": 18706,
"tag": "NAME",
"value": "Siren Song"
},
{
"context": " }\n , { name = \"Beautiful Princess\"\n , rank = A\n ",
"end": 18987,
"score": 0.9992144704,
"start": 18969,
"tag": "NAME",
"value": "Beautiful Princess"
},
{
"context": "ce C, riding APlus]\n , phantasm = { name = \"Guillotine Breaker\"\n , rank = APlus\n ",
"end": 19774,
"score": 0.9998555183,
"start": 19756,
"tag": "NAME",
"value": "Guillotine Breaker"
},
{
"context": "eartOfTheForeignGod, 6)]\n }\n , { name = \"Martha\"\n , spoiler = Nothing\n , id = 30\n ",
"end": 21366,
"score": 0.9992995262,
"start": 21360,
"tag": "NAME",
"value": "Martha"
},
{
"context": " }\n , { name = \"Miracle\"\n , rank = DPlus\n ",
"end": 22139,
"score": 0.9958244562,
"start": 22132,
"tag": "NAME",
"value": "Miracle"
},
{
"context": " }\n , { name = \"Oath of the Holy Maiden\"\n , rank",
"end": 22467,
"score": 0.8727304339,
"start": 22466,
"tag": "NAME",
"value": "O"
},
{
"context": "usPlus, divinity C]\n , phantasm = { name = \"Tarasque\"\n , rank = EX\n ",
"end": 22919,
"score": 0.9713723063,
"start": 22911,
"tag": "NAME",
"value": "Tarasque"
},
{
"context": "DragonsReverseScale, 8)]\n }\n , { name = \"Francis Drake\"\n , spoiler = Nothing\n , id = 65\n ",
"end": 24448,
"score": 0.9998049736,
"start": 24435,
"tag": "NAME",
"value": "Francis Drake"
},
{
"context": " }\n , skills = [ { name = \"Voyager of the Storm\"\n , rank = APlus\n ",
"end": 24877,
"score": 0.9814218879,
"start": 24857,
"tag": "NAME",
"value": "Voyager of the Storm"
},
{
"context": " }\n , { name = \"Golden Rule\"\n , rank = B\n ",
"end": 25230,
"score": 0.9924805164,
"start": 25219,
"tag": "NAME",
"value": "Golden Rule"
},
{
"context": " }\n , { name = \"Pioneer of the Stars\"\n , rank = EX\n ",
"end": 25485,
"score": 0.9851716161,
"start": 25465,
"tag": "NAME",
"value": "Pioneer of the Stars"
},
{
"context": "stance D, riding B]\n , phantasm = { name = \"Golden Wild Hunt\"\n , rank = APlus\n ",
"end": 25956,
"score": 0.9983468056,
"start": 25940,
"tag": "NAME",
"value": "Golden Wild Hunt"
},
{
"context": "artOfTheForeignGod, 10)]\n }\n , { name = \"Anne Bonny & Mary Read\"\n , spoiler = Nothing\n , id ",
"end": 27381,
"score": 0.9998611212,
"start": 27371,
"tag": "NAME",
"value": "Anne Bonny"
},
{
"context": "ignGod, 10)]\n }\n , { name = \"Anne Bonny & Mary Read\"\n , spoiler = Nothing\n , id = 66\n ",
"end": 27393,
"score": 0.9998661876,
"start": 27384,
"tag": "NAME",
"value": "Mary Read"
},
{
"context": " }\n , { name = \"Marksmanship\"\n , rank = B\n ",
"end": 28059,
"score": 0.9315622449,
"start": 28047,
"tag": "NAME",
"value": "Marksmanship"
},
{
"context": " }\n , { name = \"Combination\"\n , rank = C\n ",
"end": 28313,
"score": 0.9984955788,
"start": 28302,
"tag": "NAME",
"value": "Combination"
},
{
"context": "[magicResistance D]\n , phantasm = { name = \"Caribbean Free Bird\"\n , rank = CPlusPlus\n ",
"end": 28728,
"score": 0.9986682534,
"start": 28709,
"tag": "NAME",
"value": "Caribbean Free Bird"
},
{
"context": " 30), (ClawOfChaos, 12)]\n }\n , { name = \"Altria Pendragon (Santa Alter)\"\n , spoiler = Nothing\n , id",
"end": 30170,
"score": 0.9998912215,
"start": 30154,
"tag": "NAME",
"value": "Altria Pendragon"
},
{
"context": ", 12)]\n }\n , { name = \"Altria Pendragon (Santa Alter)\"\n , spoiler = Nothing\n , id = 73\n",
"end": 30183,
"score": 0.9997688532,
"start": 30172,
"tag": "NAME",
"value": "Santa Alter"
},
{
"context": " }\n , skills = [ { name = \"Saint's Gift\"\n , rank = EX\n ",
"end": 30606,
"score": 0.9996964335,
"start": 30594,
"tag": "NAME",
"value": "Saint's Gift"
},
{
"context": " }\n , { name = \"Intuition\"\n , rank = A\n ",
"end": 30941,
"score": 0.9997496605,
"start": 30932,
"tag": "NAME",
"value": "Intuition"
},
{
"context": " }\n , { name = \"Mana Burst\"\n , rank = AMinus\n ",
"end": 31182,
"score": 0.999876976,
"start": 31172,
"tag": "NAME",
"value": "Mana Burst"
},
{
"context": "stance A, riding A]\n , phantasm = { name = \"Excalibur Morgan\"\n , rank = APlusPlus\n ",
"end": 31515,
"score": 0.9998224378,
"start": 31499,
"tag": "NAME",
"value": "Excalibur Morgan"
},
{
"context": "eartOfTheForeignGod, 8)]\n }\n , { name = \"Astolfo\"\n , spoiler = Nothing\n , id = 94\n ",
"end": 32754,
"score": 0.9997799993,
"start": 32747,
"tag": "NAME",
"value": "Astolfo"
},
{
"context": " }\n , { name = \"Trap of Argalia\"\n , rank = D\n ",
"end": 33439,
"score": 0.9628996253,
"start": 33424,
"tag": "NAME",
"value": "Trap of Argalia"
},
{
"context": " }\n , { name = \"Evaporation of Reason\"\n , rank ",
"end": 33682,
"score": 0.7962089777,
"start": 33680,
"tag": "NAME",
"value": "Ev"
},
{
"context": "ndependentAction B]\n , phantasm = { name = \"Hippogriff\"\n , rank = BPlusPlus\n ",
"end": 34319,
"score": 0.9997717142,
"start": 34309,
"tag": "NAME",
"value": "Hippogriff"
},
{
"context": ", (SeedOfYggdrasil, 24)]\n }\n , { name = \"Queen Medb\"\n , spoiler = Nothing\n , id = 99\n ",
"end": 35877,
"score": 0.999700129,
"start": 35867,
"tag": "NAME",
"value": "Queen Medb"
},
{
"context": " }\n , { name = \"Queen's Discipline\"\n , rank = A\n ",
"end": 36732,
"score": 0.710324049,
"start": 36714,
"tag": "NAME",
"value": "Queen's Discipline"
},
{
"context": " }\n , { name = \"Siren Song\"\n , rank = C\n ",
"end": 37160,
"score": 0.9998775125,
"start": 37150,
"tag": "NAME",
"value": "Siren Song"
},
{
"context": "stance B, riding A]\n , phantasm = { name = \"Chariot My Love\"\n , rank = BPlus\n ",
"end": 37494,
"score": 0.9998312593,
"start": 37479,
"tag": "NAME",
"value": "Chariot My Love"
},
{
"context": "artOfTheForeignGod, 10)]\n }\n , { name = \"Iskandar\"\n , spoiler = Nothing\n , id = 108\n",
"end": 39067,
"score": 0.9998676181,
"start": 39059,
"tag": "NAME",
"value": "Iskandar"
},
{
"context": " }\n , skills = [ { name = \"Charisma\"\n , rank = A\n ",
"end": 39486,
"score": 0.9968833327,
"start": 39478,
"tag": "NAME",
"value": "Charisma"
},
{
"context": " }\n , { name = \"Tactics\"\n , rank = B\n ",
"end": 39732,
"score": 0.9964885116,
"start": 39725,
"tag": "NAME",
"value": "Tactics"
},
{
"context": " }\n , { name = \"Lightning Conqueror\"\n , rank = EX\n ",
"end": 39984,
"score": 0.9997453094,
"start": 39965,
"tag": "NAME",
"value": "Lightning Conqueror"
},
{
"context": " APlus, divinity C]\n , phantasm = { name = \"Ionioi Hetairoi\"\n , rank = EX\n ",
"end": 40423,
"score": 0.9998804927,
"start": 40408,
"tag": "NAME",
"value": "Ionioi Hetairoi"
},
{
"context": "d = Buster\n , kind = \"Anti-Army\"\n , hits = 8\n ",
"end": 40532,
"score": 0.9950349331,
"start": 40530,
"tag": "NAME",
"value": "my"
},
{
"context": "), (PhoenixFeather, 20)]\n }\n , { name = \"Sakata Kintoki (Rider)\"\n , spoiler = Nothing\n , id ",
"end": 42026,
"score": 0.9998163581,
"start": 42012,
"tag": "NAME",
"value": "Sakata Kintoki"
},
{
"context": "er, 20)]\n }\n , { name = \"Sakata Kintoki (Rider)\"\n , spoiler = Nothing\n , id = 115",
"end": 42033,
"score": 0.6870476007,
"start": 42028,
"tag": "NAME",
"value": "Rider"
},
{
"context": "ves = [divinity C]\n , phantasm = { name = \"Golden Drive, Good Night\"\n , rank = B\n ",
"end": 43482,
"score": 0.9666001797,
"start": 43458,
"tag": "NAME",
"value": "Golden Drive, Good Night"
},
{
"context": " (WarhorsesYoungHorn, 12)]\n }\n , { name = \"Ozymandias\"\n , spoiler = Nothing\n , id = 118\n",
"end": 44703,
"score": 0.999774158,
"start": 44693,
"tag": "NAME",
"value": "Ozymandias"
},
{
"context": " }\n , { name = \"Protection of the Sun God\"\n , rank = A\n ",
"end": 45828,
"score": 0.9880673289,
"start": 45803,
"tag": "NAME",
"value": "Protection of the Sun God"
},
{
"context": " APlus, divinity B]\n , phantasm = { name = \"Ramesseum Tentyris\"\n , rank = EX\n ",
"end": 46255,
"score": 0.9997822046,
"start": 46237,
"tag": "NAME",
"value": "Ramesseum Tentyris"
},
{
"context": "(LampOfEvilSealing, 15)]\n }\n , { name = \"Mordred (Rider)\"\n , spoiler = Nothing\n , id ",
"end": 47813,
"score": 0.9991958737,
"start": 47806,
"tag": "NAME",
"value": "Mordred"
},
{
"context": "lSealing, 15)]\n }\n , { name = \"Mordred (Rider)\"\n , spoiler = Nothing\n , id = 132",
"end": 47820,
"score": 0.8056626916,
"start": 47816,
"tag": "NAME",
"value": "ider"
},
{
"context": " }\n , skills = [ { name = \"Cerulean Ride\"\n , rank = A\n ",
"end": 48244,
"score": 0.9246578813,
"start": 48231,
"tag": "NAME",
"value": "Cerulean Ride"
},
{
"context": " }\n , { name = \"Rodeo Flip\"\n , rank = APlus\n ",
"end": 48496,
"score": 0.9907128215,
"start": 48486,
"tag": "NAME",
"value": "Rodeo Flip"
},
{
"context": " }\n , { name = \"Endless Summer\"\n , rank = B\n ",
"end": 48838,
"score": 0.9630735517,
"start": 48824,
"tag": "NAME",
"value": "Endless Summer"
},
{
"context": "tance B, surfing A]\n , phantasm = { name = \"Prydwen Tube Riding\"\n , rank = A\n ",
"end": 49253,
"score": 0.9949410558,
"start": 49241,
"tag": "NAME",
"value": "Prydwen Tube"
},
{
"context": " (TearstoneOfBlood, 12)]\n }\n , { name = \"Quetzalcoatl\"\n , spoiler = Nothing\n , id = 144\n",
"end": 50748,
"score": 0.9996525049,
"start": 50736,
"tag": "NAME",
"value": "Quetzalcoatl"
},
{
"context": "ter = 3, ex = 5 }\n , skills = [ { name = \"Charisma\"\n , rank = APlus\n ",
"end": 51445,
"score": 0.9640022516,
"start": 51437,
"tag": "NAME",
"value": "Charisma"
},
{
"context": " }\n , { name = \"Wisdom of the Benevolent God\"\n , r",
"end": 51693,
"score": 0.9895569086,
"start": 51690,
"tag": "NAME",
"value": "Wis"
},
{
"context": " }\n , { name = \"Lucha Libre\"\n , rank = EX\n ",
"end": 52082,
"score": 0.9998445511,
"start": 52071,
"tag": "NAME",
"value": "Lucha Libre"
},
{
"context": ", coreOfGoddess EX]\n , phantasm = { name = \"Xiuhcoatl\"\n , rank = A\n ",
"end": 52579,
"score": 0.999707818,
"start": 52570,
"tag": "NAME",
"value": "Xiuhcoatl"
},
{
"context": "rsedBeastGallstone, 10)]\n }\n , { name = \"Christopher Columbus\"\n , spoiler = Just \"Resistance\"\n , id ",
"end": 53858,
"score": 0.9998292923,
"start": 53838,
"tag": "NAME",
"value": "Christopher Columbus"
},
{
"context": "ter = 4, ex = 5 }\n , skills = [ { name = \"Voyager of the Storm\"\n , rank = B\n ",
"end": 54556,
"score": 0.9604691863,
"start": 54536,
"tag": "NAME",
"value": "Voyager of the Storm"
},
{
"context": " }\n , { name = \"Unyielding Will\"\n , rank = C\n ",
"end": 54905,
"score": 0.9909967184,
"start": 54890,
"tag": "NAME",
"value": "Unyielding Will"
},
{
"context": " }\n , { name = \"Conquistador\"\n , rank = EX\n ",
"end": 55250,
"score": 0.9991874695,
"start": 55238,
"tag": "NAME",
"value": "Conquistador"
},
{
"context": "stance D, riding B]\n , phantasm = { name = \"Santa María・Drop Anchor\"\n , rank = A\n ",
"end": 55671,
"score": 0.9972631335,
"start": 55660,
"tag": "NAME",
"value": "Santa María"
},
{
"context": "ding B]\n , phantasm = { name = \"Santa María・Drop Anchor\"\n , rank = A\n ",
"end": 55683,
"score": 0.7433303595,
"start": 55672,
"tag": "NAME",
"value": "Drop Anchor"
},
{
"context": "ursedBeastGallstone, 7)]\n }\n , { name = \"Altria Pendragon (Rider Alter)\"\n , spoiler = Nothing\n , id",
"end": 56896,
"score": 0.9998916388,
"start": 56880,
"tag": "NAME",
"value": "Altria Pendragon"
},
{
"context": " }\n , { name = \"Coaching\"\n , rank = A\n ",
"end": 57989,
"score": 0.9326233864,
"start": 57981,
"tag": "NAME",
"value": "Coaching"
},
{
"context": " }\n , { name = \"Reloaded\"\n , rank = C\n ",
"end": 58402,
"score": 0.9808930159,
"start": 58394,
"tag": "NAME",
"value": "Reloaded"
},
{
"context": "dependentAction EX]\n , phantasm = { name = \"Secace Morgan\"\n , rank = C\n ",
"end": 58758,
"score": 0.9997887611,
"start": 58745,
"tag": "NAME",
"value": "Secace Morgan"
},
{
"context": ", (MeteorHorseshoe, 24)]\n }\n , { name = \"Ishtar (Rider)\"\n , spoiler = Nothing\n , id ",
"end": 60050,
"score": 0.9994677901,
"start": 60044,
"tag": "NAME",
"value": "Ishtar"
},
{
"context": "rHorseshoe, 24)]\n }\n , { name = \"Ishtar (Rider)\"\n , spoiler = Nothing\n , id = 182",
"end": 60057,
"score": 0.933591783,
"start": 60052,
"tag": "NAME",
"value": "Rider"
},
{
"context": "ter = 5, ex = 3 }\n , skills = [ { name = \"Shining Water Robe\"\n , rank = A",
"end": 60743,
"score": 0.7954167724,
"start": 60741,
"tag": "NAME",
"value": "Sh"
},
{
"context": " }\n , { name = \"Accel Turn\"\n , rank = B\n ",
"end": 61197,
"score": 0.9843797684,
"start": 61187,
"tag": "NAME",
"value": "Accel Turn"
},
{
"context": " }\n , { name = \"Summer Breaker!\"\n , rank = A\n ",
"end": 61546,
"score": 0.9996352196,
"start": 61532,
"tag": "NAME",
"value": "Summer Breaker"
},
{
"context": "A, coreOfGoddess B]\n , phantasm = { name = \"An Gal Tā Seven Colors\"\n , rank = EX\n ",
"end": 62272,
"score": 0.9992762804,
"start": 62250,
"tag": "NAME",
"value": "An Gal Tā Seven Colors"
},
{
"context": "ysteriousDivineWine, 8)]\n }\n , { name = \"Ivan the Terrible\"\n , spoiler = Nothing\n , id = 205\n",
"end": 63229,
"score": 0.9998631477,
"start": 63212,
"tag": "NAME",
"value": "Ivan the Terrible"
},
{
"context": " }\n , { name = \"Emergency Prerogative\"\n , rank = A\n ",
"end": 64661,
"score": 0.78713727,
"start": 64640,
"tag": "NAME",
"value": "Emergency Prerogative"
},
{
"context": "tance D, riding EX]\n , phantasm = { name = \"Zveri Krestnyi Khod\"\n , rank = B\n ",
"end": 65147,
"score": 0.9998776317,
"start": 65128,
"tag": "NAME",
"value": "Zveri Krestnyi Khod"
},
{
"context": ", 44), (EternalIce, 24)]\n }\n , { name = \"Achilles\"\n , spoiler = Nothing\n , id = 206\n",
"end": 66432,
"score": 0.9997467995,
"start": 66424,
"tag": "NAME",
"value": "Achilles"
},
{
"context": "ter = 2, ex = 4 }\n , skills = [ { name = \"Drómos Komḗtēs\"\n , rank = APlus\n ",
"end": 67161,
"score": 0.9997761846,
"start": 67147,
"tag": "NAME",
"value": "Drómos Komḗtēs"
},
{
"context": " }\n , { name = \"Andreíos Amárantos\"\n , rank = B\n ",
"end": 67526,
"score": 0.9998826981,
"start": 67508,
"tag": "NAME",
"value": "Andreíos Amárantos"
},
{
"context": " }\n , { name = \"Diatrekhо̄n Astēr Lonkhē\"\n , rank = BPlus\n ",
"end": 67895,
"score": 0.9998684525,
"start": 67871,
"tag": "NAME",
"value": "Diatrekhо̄n Astēr Lonkhē"
},
{
"context": " APlus, divinity C]\n , phantasm = { name = \"Troias Tragо̄idia\"\n , rank = A\n ",
"end": 68403,
"score": 0.9998514652,
"start": 68386,
"tag": "NAME",
"value": "Troias Tragо̄idia"
}
] | src/Database/Servant/Rider.elm | jnbooth/chaldeas | 18 | module Database.Servant.Rider exposing (riders)
import Model.Attribute exposing (Attribute(..))
import Model.Card exposing (Card(..))
import Model.Class exposing (Class(..))
import Model.Deck exposing (Deck(..))
import Model.Material exposing (Material(..))
import Model.Trait exposing (Trait(..))
import Database.Passives exposing (..)
import Model.Servant exposing (Servant, Ascension(..), Reinforcement(..))
import Model.Skill.Amount exposing (Amount(..))
import Model.Skill.BuffEffect exposing (BuffEffect(..))
import Model.Skill.DebuffEffect exposing (DebuffEffect(..))
import Model.Skill.InstantEffect exposing (InstantEffect(..))
import Model.Skill.Rank exposing (Rank(..))
import Model.Skill.SkillEffect exposing (SkillEffect(..))
import Model.Skill.Special exposing (Special(..))
import Model.Skill.Target exposing (Target(..))
import Model.Icon as Icon
riders : List Servant
riders =
[ { name = "Medusa"
, spoiler = Nothing
, id = 23
, rarity = 3
, class = Rider
, attr = Earth
, deck = Deck Quick Quick Arts Arts Buster
, curve = 24
, stats = { base = { atk = 1337, hp = 1608 }
, max = { atk = 7200, hp = 8937 }
, grail = { atk = 9744, hp = 12117 }
}
, skills = [ { name = "Mystic Eyes"
, rank = APlus
, icon = Icon.Stun
, cd = 8
, effect = [ Chances 50 100 <| Debuff Enemy 1 Stun Full ]
}
, { name = "Monstrous Strength"
, rank = B
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Self 2 AttackUp <| Range 10 30 ]
}
, { name = "Blood Fort Andromeda"
, rank = B
, icon = Icon.Noble
, cd = 8
, effect = [ To Self GaugeUp <| Flat 20
, Grant Self 3 NPGen <| Range 20 30
]
}
]
, passives = [magicResistance B, independentAction C, divinity EMinus, riding APlus]
, phantasm = { name = "Bellerophon"
, rank = APlus
, card = Quick
, kind = "Anti-Army"
, hits = 1
, effect = [ To Enemies Damage <| Range 600 1000 ]
, over = [ Grant Party 3 StarUp <| Range 20 60 ]
, first = False
}
, gen = { starWeight = 194, starRate = 9, npAtk = 0.58, npDef = 3 }
, hits = { quick = 2, arts = 3, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, Divine]
, death = 35
, align = [Chaotic, Good]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (SerpentJewel, 4)]
[(Monument Rider, 4), (VoidsDust, 13), (MeteorHorseshoe, 4)]
[(Monument Rider, 8), (MeteorHorseshoe, 7), (PhoenixFeather, 7)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (VoidsDust, 7)]
[(SecretGemOf Rider, 4), (VoidsDust, 13)]
[(SecretGemOf Rider, 8), (SerpentJewel, 3)]
[(SerpentJewel, 6), (HeartOfTheForeignGod, 2)]
[(HeartOfTheForeignGod, 5), (PhoenixFeather, 13)]
}
, { name = "Georgios"
, spoiler = Nothing
, id = 24
, rarity = 2
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 2
, stats = { base = { atk = 929, hp = 1731 }
, max = { atk = 5236, hp = 9200 }
, grail = { atk = 7587, hp = 13278 }
}
, skills = [ { name = "Guardian Knight"
, rank = APlus
, icon = Icon.CrosshairUp
, cd = 7
, effect = [ Grant Self 3 Taunt Full
, Grant Self 3 DefenseUp <| Range 20 40
]
}
, { name = "Martyr's Soul"
, rank = BPlus
, icon = Icon.HoodUp
, cd = 7
, effect = [ Grant Self 3 MentalResist <| Range 50 100
, To Self Heal <| Range 750 2000
]
}
, { name = "Battle Continuation"
, rank = A
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Self 5 Guts <| Range 1000 2500 ]
}
]
, passives = [magicResistance A, riding B]
, phantasm = { name = "Ascalon"
, rank = B
, card = Arts
, kind = "Anti-Personnel"
, hits = 4
, effect = [ To Enemy (ApplyTrait Dragon) <| Flat 3
, To Enemy Damage <| Range 900 1500
]
, over = [ Grant Self 1 DefenseUp <| Range 20 40 ]
, first = False
}
, gen = { starWeight = 205, starRate = 8.9, npAtk = 0.85, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Male
, traits = [Humanoid, Riding, LovedOne, EnumaElish]
, death = 45
, align = [Lawful, Good]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 3)]
[(Piece Rider, 6), (ProofOfHero, 11)]
[(Monument Rider, 3), (PhoenixFeather, 4), (ForbiddenPage, 3)]
[(Monument Rider, 6), (ForbiddenPage, 5), (MeteorHorseshoe, 6)]
, skillUp = Reinforcement
[(GemOf Rider, 3)]
[(GemOf Rider, 6)]
[(MagicGemOf Rider, 3)]
[(MagicGemOf Rider, 6), (PhoenixFeather, 2)]
[(SecretGemOf Rider, 3), (PhoenixFeather, 4)]
[(SecretGemOf Rider, 6), (ProofOfHero, 8)]
[(ProofOfHero, 15), (EternalGear, 3)]
[(EternalGear, 9), (MeteorHorseshoe, 12)]
}
, { name = "Edward Teach"
, spoiler = Nothing
, id = 25
, rarity = 2
, class = Rider
, attr = Human
, deck = Deck Quick Arts Arts Buster Buster
, curve = 12
, stats = { base = { atk = 1097, hp = 1488 }
, max = { atk = 6188, hp = 7907 }
, grail = { atk = 8967, hp = 11411 }
}
, skills = [ { name = "Voyager of the Storm"
, rank = A
, icon = Icon.BeamUp
, cd = 7
, effect = [ Grant Party 1 NPUp <| Range 8 16
, Grant Party 1 AttackUp <| Range 8 16
]
}
, { name = "Pirate's Glory"
, rank = B
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Self 3 AttackUp <| Range 9 27
, Times 1 << Grant Self 0 Guts <| Flat 1
, Debuff Self 3 DebuffVuln <| Flat 50
]
}
, { name = "Gentlemanly Love"
, rank = C
, icon = Icon.Heal
, cd = 8
, effect = [ To Party Heal <| Range 1000 2000
, To (AlliesType Female) Heal <| Range 1000 2000
, To (AlliesType Nonbinary) Heal <| Range 1000 2000
]
}
]
, passives = [magicResistance E]
, phantasm = { name = "Queen Anne's Revenge"
, rank = CPlusPlus
, card = Buster
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemies Damage <| Range 300 500
, To Party GainStars <| Flat 5
]
, over = [ Chances 30 70 << To Enemies GaugeDown <| Flat 1 ]
, first = False
}
, gen = { starWeight = 198, starRate = 8.8, npAtk = 0.56, npDef = 3 }
, hits = { quick = 2, arts = 3, buster = 1, ex = 3 }
, gender = Male
, traits = [Humanoid, EnumaElish]
, death = 45
, align = [Chaotic, Evil]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 3)]
[(Piece Rider, 6), (EvilBone, 11)]
[(Monument Rider, 3), (OctupletCrystals, 5), (ForbiddenPage, 3)]
[(Monument Rider, 6), (ForbiddenPage, 5), (GhostLantern, 6)]
, skillUp = Reinforcement
[(GemOf Rider, 3)]
[(GemOf Rider, 6)]
[(MagicGemOf Rider, 3)]
[(MagicGemOf Rider, 6), (OctupletCrystals, 3)]
[(SecretGemOf Rider, 3), (OctupletCrystals, 5)]
[(SecretGemOf Rider, 6), (EvilBone, 8)]
[(EvilBone, 15), (HomunculusBaby, 3)]
[(HomunculusBaby, 9), (GhostLantern, 12)]
}
, { name = "Boudica"
, spoiler = Nothing
, id = 26
, rarity = 3
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 3
, stats = { base = { atk = 1168, hp = 1823 }
, max = { atk = 6289, hp = 10130 }
, grail = { atk = 8511, hp = 13735 }
}
, skills = [ { name = "Vow to the Goddess"
, rank = B
, icon = Icon.DamageUp
, cd = 7
, effect = [ Grant Self 3 (Special AttackUp <| VsTrait Roman) <| Range 40 60 ]
}
, { name = "Battle Continuation"
, rank = A
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Self 5 Guts <| Range 1000 2500 ]
}
, { name = "Andraste's Protection"
, rank = A
, icon = Icon.ArtsUp
, cd = 7
, effect = [ Grant Party 3 (CardUp Arts) <| Range 10 20 ]
}
]
, passives = [magicResistance D, riding A]
, phantasm = { name = "Chariot of Boudica"
, rank = BPlusPlus
, card = Arts
, kind = "Anti-Army"
, hits = 0
, effect = [ Grant Party 3 DefenseUp <| Range 10 20 ]
, over = [ Grant Party 1 DefenseUp <| Range 20 40
, Grant Party 3 AttackUp <| Range 20 40
]
, first = False
}
, gen = { starWeight = 196, starRate = 8.9, npAtk = 0.85, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, EnumaElish, King]
, death = 45
, align = [Neutral, Good]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (PhoenixFeather, 4)]
[(Monument Rider, 4), (EvilBone, 20), (MeteorHorseshoe, 4)]
[(Monument Rider, 8), (MeteorHorseshoe, 7), (VoidsDust, 16)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (EvilBone, 10)]
[(SecretGemOf Rider, 4), (EvilBone, 20)]
[(SecretGemOf Rider, 8), (PhoenixFeather, 3)]
[(PhoenixFeather, 6), (SerpentJewel, 4)]
[(SerpentJewel, 10), (VoidsDust, 32)]
}
, { name = "Ushiwakamaru"
, spoiler = Nothing
, id = 27
, rarity = 3
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 8
, stats = { base = { atk = 1314, hp = 1625 }
, max = { atk = 7076, hp = 9028 }
, grail = { atk = 9576, hp = 12240 }
}
, skills = [ { name = "Tengu's Strategy"
, rank = A
, icon = Icon.NobleUp
, cd = 7
, effect = [ Grant Party 3 NPGen <| Range 10 20 ]
}
, { name = "Charisma"
, rank = CPlus
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 8.5 17 ]
}
, { name = "Art of the Swallow"
, rank = B
, icon = Icon.Dodge
, cd = 8
, effect = [ Times 1 <| Grant Self 1 Evasion Full
, Grant Self 1 StarUp <| Range 50 100
]
}
]
, passives = [magicResistance C, riding APlus]
, phantasm = { name = "Dan-No-Ura Eight-Boat Leap"
, rank = C
, card = Quick
, kind = "Anti-Personnel"
, hits = 1
, effect = [ To Enemy Damage <| Range 1600 2400 ]
, over = [ Grant Self 3 StarUp <| Range 50 90 ]
, first = False
}
, gen = { starWeight = 204, starRate = 9.1, npAtk = 0.87, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, LovedOne, EnumaElish]
, death = 35
, align = [Chaotic, Balanced]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (ProofOfHero, 15)]
[(Monument Rider, 4), (MeteorHorseshoe, 7), (GhostLantern, 4)]
[(Monument Rider, 8), (GhostLantern, 7), (OctupletCrystals, 8)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (MeteorHorseshoe, 4)]
[(SecretGemOf Rider, 4), (MeteorHorseshoe, 7)]
[(SecretGemOf Rider, 8), (ProofOfHero, 10)]
[(ProofOfHero, 20), (EternalGear, 4)]
[(EternalGear, 12), (OctupletCrystals, 16)]
}
, { name = "Alexander"
, spoiler = Nothing
, id = 28
, rarity = 3
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 3
, stats = { base = { atk = 1366, hp = 1979 }
, max = { atk = 7356, hp = 8640 }
, grail = { atk = 9955, hp = 11714 }
}
, skills = [ { name = "Charisma"
, rank = C
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 8 16 ]
}
, { name = "Fair Youth"
, rank = B
, icon = Icon.Heart
, cd = 9
, effect = [ Chances 50 80 <| Debuff (EnemyType Humanoid) 1 Charm Full ]
}
, { name = "Omen of the Conqueror"
, rank = A
, icon = Icon.QuickUp
, cd = 7
, effect = [ Grant Party 3 (CardUp Quick) <| Range 10 20 ]
}
]
, passives = [magicResistance D, divinity E, riding APlus]
, phantasm = { name = "Bucephalus"
, rank = BPlusPlus
, card = Quick
, kind = "Anti-Army"
, hits = 1
, effect = [ To Enemies Damage <| Range 800 1200 ]
, over = [ To Party GainStars <| Range 15 35 ]
, first = False
}
, gen = { starWeight = 205, starRate = 9, npAtk = 0.86, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Male
, traits = [Humanoid, Riding, Divine, EnumaElish, GreekMythMale, King]
, death = 40
, align = [Neutral, Good]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (MeteorHorseshoe, 5)]
[(Monument Rider, 4), (PhoenixFeather, 3), (OctupletCrystals, 7)]
[(Monument Rider, 8), (PhoenixFeather, 6), (ProofOfHero, 24)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (OctupletCrystals, 4)]
[(SecretGemOf Rider, 4), (OctupletCrystals, 7)]
[(SecretGemOf Rider, 8), (MeteorHorseshoe, 4)]
[(ClawOfChaos, 3), (MeteorHorseshoe, 7)]
[(ClawOfChaos, 8), (ProofOfHero, 48)]
}
, { name = "Marie Antoinette"
, spoiler = Nothing
, id = 29
, rarity = 4
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 9
, stats = { base = { atk = 1382, hp = 1975 }
, max = { atk = 8293, hp = 12348 }
, grail = { atk = 10041, hp = 14972 }
}
, skills = [ { name = "Siren Song"
, rank = C
, icon = Icon.Heart
, cd = 9
, effect = [ Chances 50 80 <| Debuff (EnemyType Male) 1 Charm Full ]
}
, { name = "Beautiful Princess"
, rank = A
, icon = Icon.Shield
, cd = 8
, effect = [ Times 3 <| Grant Self 0 Invincibility Full
, Grant Self 5 HealPerTurn <| Range 200 600
]
}
, { name = "God's Grace"
, rank = B
, icon = Icon.StaffUp
, cd = 7
, effect = [ Grant Self 3 MentalSuccess <| Range 10 30
, To Self Heal <| Range 1000 2500
]
}
]
, passives = [magicResistance C, riding APlus]
, phantasm = { name = "Guillotine Breaker"
, rank = APlus
, card = Quick
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemies Damage <| Range 800 1200
, To Party RemoveDebuffs Full
, Grant Party 3 CritUp <| Flat 20
]
, over = [ To Party Heal <| Range 1000 3000 ]
, first = False
}
, gen = { starWeight = 201, starRate = 9, npAtk = 1, npDef = 3 }
, hits = { quick = 2, arts = 1, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, EnumaElish, King]
, death = 35
, align = [Lawful, Good]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (PhoenixFeather, 5)]
[(Monument Rider, 4), (MeteorHorseshoe, 4), (SerpentJewel, 7)]
[(Monument Rider, 10), (MeteorHorseshoe, 8), (EternalGear, 10)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (SerpentJewel, 4)]
[(SecretGemOf Rider, 4), (SerpentJewel, 7)]
[(SecretGemOf Rider, 10), (PhoenixFeather, 4)]
[(PhoenixFeather, 7), (HeartOfTheForeignGod, 2)]
[(EternalGear, 20), (HeartOfTheForeignGod, 6)]
}
, { name = "Martha"
, spoiler = Nothing
, id = 30
, rarity = 4
, class = Rider
, attr = Human
, deck = Deck Quick Arts Arts Arts Buster
, curve = 4
, stats = { base = { atk = 1335, hp = 2090 }
, max = { atk = 8014, hp = 13068 }
, grail = { atk = 9703, hp = 15845 }
}
, skills = [ { name = "Protection of the Faith"
, rank = A
, icon = Icon.HoodUp
, cd = 7
, effect = [ Grant Self 3 DebuffResist <| Range 50 100
, To Self Heal <| Range 1000 2500
]
}
, { name = "Miracle"
, rank = DPlus
, icon = Icon.Heal
, cd = 8
, effect = [ To Party Heal <| Range 1000 2000
, To Party RemoveDebuffs Full
]
}
, { name = "Oath of the Holy Maiden"
, rank = C
, icon = Icon.ShieldDown
, cd = 7
, effect = [ Debuff Enemy 3 DefenseDown <| Range 10 30
, To Enemy RemoveBuffs Full
]
}
]
, passives = [magicResistance A, riding APlusPlus, divinity C]
, phantasm = { name = "Tarasque"
, rank = EX
, card = Buster
, kind = "Anti-Army"
, hits = 1
, effect = [ Grant Self 1 (CardUp Buster) <| Flat 20
, To Enemies Damage <| Range 400 600 ]
, over = [ Debuff Enemies 3 DefenseDown <| Range 20 40 ]
, first = False
}
, gen = { starWeight = 205, starRate = 9, npAtk = 1.58, npDef = 3 }
, hits = { quick = 2, arts = 1, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, Divine, EnumaElish]
, death = 30
, align = [Lawful, Good]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (DragonFang, 15)]
[(Monument Rider, 4), (ClawOfChaos, 3), (SeedOfYggdrasil, 10)]
[(Monument Rider, 10), (ClawOfChaos, 5), (DragonsReverseScale, 4)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (SeedOfYggdrasil, 5)]
[(SecretGemOf Rider, 4), (SeedOfYggdrasil, 10)]
[(SecretGemOf Rider, 10), (DragonFang, 10)]
[(PhoenixFeather, 4), (DragonFang, 20)]
[(PhoenixFeather, 12), (DragonsReverseScale, 8)]
}
, { name = "Francis Drake"
, spoiler = Nothing
, id = 65
, rarity = 5
, class = Rider
, attr = Star
, deck = Deck Quick Arts Arts Buster Buster
, curve = 10
, stats = { base = { atk = 1750, hp = 1881 }
, max = { atk = 11326, hp = 12830 }
, grail = { atk = 12398, hp = 14056 }
}
, skills = [ { name = "Voyager of the Storm"
, rank = APlus
, icon = Icon.BeamUp
, cd = 7
, effect = [ Grant Party 1 NPUp <| Range 8.5 17
, Grant Party 1 AttackUp <| Range 8.5 17
]
}
, { name = "Golden Rule"
, rank = B
, icon = Icon.NobleUp
, cd = 8
, effect = [ Grant Self 3 NPGen <| Range 18 45 ]
}
, { name = "Pioneer of the Stars"
, rank = EX
, icon = Icon.Noble
, cd = 8
, effect = [ To Self GaugeUp <| Range 30 50
, Grant Self 3 IgnoreInvinc Full
, To Party GainStars <| Flat 10
]
}
]
, passives = [magicResistance D, riding B]
, phantasm = { name = "Golden Wild Hunt"
, rank = APlus
, card = Buster
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemies Damage <| Range 400 600 ]
, over = [ To Party GainStars <| Range 20 40 ]
, first = False
}
, gen = { starWeight = 208, starRate = 9, npAtk = 0.42, npDef = 3 }
, hits = { quick = 6, arts = 4, buster = 2, ex = 4 }
, gender = Female
, traits = [Humanoid, Riding]
, death = 50
, align = [Chaotic, Evil]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (EvilBone, 22)]
[(Monument Rider, 5), (DragonsReverseScale, 2), (DragonFang, 24)]
[( Monument Rider, 12), (DragonsReverseScale, 4), (HeartOfTheForeignGod, 5)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (DragonFang, 12)]
[(SecretGemOf Rider, 5), (DragonFang, 24)]
[(SecretGemOf Rider, 12), (EvilBone, 15)]
[(GhostLantern, 6), (EvilBone, 29)]
[(GhostLantern, 18), (HeartOfTheForeignGod, 10)]
}
, { name = "Anne Bonny & Mary Read"
, spoiler = Nothing
, id = 66
, rarity = 4
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 29
, stats = { base = { atk = 1504, hp = 1805 }
, max = { atk = 9029, hp = 11286 }
, grail = { atk = 10932, hp = 13684 }
}
, skills = [ { name = "Voyage"
, rank = A
, icon = Icon.StarHaloUp
, cd = 8
, effect = [ Grant Self 3 StarUp <| Range 30 50 ]
}
, { name = "Marksmanship"
, rank = B
, icon = Icon.ExclamationUp
, cd = 7
, effect = [ Grant Self 1 CritUp <| Range 50 100 ]
}
, { name = "Combination"
, rank = C
, icon = Icon.StarUp
, cd = 7
, effect = [ Grant Self 1 GatherUp <| Range 300 600
, Grant Self 1 AttackUp <| Range 20 30
]
}
]
, passives = [magicResistance D]
, phantasm = { name = "Caribbean Free Bird"
, rank = CPlusPlus
, card = Quick
, kind = "Anti-Personnel"
, hits = 6
, effect = [ To Enemy Damage <| Range 1600 2400 ]
, over = [ To Enemy LastStand <| Range 1200 2000 ]
, first = False
}
, gen = { starWeight = 200, starRate = 9.1, npAtk = 0.84, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 1 }
, gender = Female
, traits = [Humanoid, EnumaElish]
, death = 50
, align = [Chaotic, Evil, Chaotic, Balanced]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (HomunculusBaby, 6)]
[(Monument Rider, 4), (GhostLantern, 8), (EvilBone, 12)]
[(Monument Rider, 10), (ClawOfChaos, 6), (EvilBone, 24)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (GhostLantern, 4)]
[(SecretGemOf Rider, 4), (GhostLantern, 8)]
[(SecretGemOf Rider, 10), (HomunculusBaby, 4)]
[(VoidsDust, 10), (HomunculusBaby, 8)]
[(VoidsDust, 30), (ClawOfChaos, 12)]
}
, { name = "Altria Pendragon (Santa Alter)"
, spoiler = Nothing
, id = 73
, rarity = 4
, class = Rider
, attr = Human
, deck = Deck Quick Arts Arts Buster Buster
, curve = 29
, stats = { base = { atk = 1543, hp = 1805 }
, max = { atk = 9258, hp = 11286 }
, grail = { atk = 11209, hp = 13684 }
}
, skills = [ { name = "Saint's Gift"
, rank = EX
, icon = Icon.Heal
, cd = 7
, effect = [ To Ally Heal <| Range 1500 3500
, Grant Ally 3 StarUp <| Flat 30
]
}
, { name = "Intuition"
, rank = A
, icon = Icon.Star
, cd = 7
, effect = [ To Party GainStars <| Range 5 15 ]
}
, { name = "Mana Burst"
, rank = AMinus
, icon = Icon.BusterUp
, cd = 7
, effect = [ Grant Self 1 (CardUp Buster) <| Range 25 45 ]
}
]
, passives = [magicResistance A, riding A]
, phantasm = { name = "Excalibur Morgan"
, rank = APlusPlus
, card = Buster
, kind = "Anti-Army"
, hits = 3
, effect = [ To Enemies Damage <| Range 450 650 ]
, over = [ To Self GaugeUp <| Range 10 30 ]
, first = False
}
, gen = { starWeight = 204, starRate = 8.9, npAtk = 0.87, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Arthur, Dragon, Riding, Saberface, EnumaElish, King]
, death = 35
, align = [Lawful, Good]
, limited = True
, free = True
, ascendUp = Welfare "Bucket of Chicken"
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (DragonFang, 10)]
[(SecretGemOf Rider, 4), (DragonFang, 20)]
[(SecretGemOf Rider, 10), (MeteorHorseshoe, 4)]
[(MeteorHorseshoe, 8), (DragonsReverseScale, 2)]
[(DragonsReverseScale, 6), (HeartOfTheForeignGod, 8)]
}
, { name = "Astolfo"
, spoiler = Nothing
, id = 94
, rarity = 4
, class = Rider
, attr = Earth
, deck = Deck Quick Quick Quick Arts Buster
, curve = 24
, stats = { base = { atk = 1489, hp = 1787 }
, max = { atk = 8937, hp = 11172 }
, grail = { atk = 10821, hp = 13546 }
}
, skills = [ { name = "Monstrous Strength"
, rank = CMinus
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Self 1 AttackUp <| Range 8 28 ]
}
, { name = "Trap of Argalia"
, rank = D
, icon = Icon.Stun
, cd = 10
, effect = [ Chances 60 90 <| Debuff Enemy 1 Stun Full ]
}
, { name = "Evaporation of Reason"
, rank = DPlus
, icon = Icon.StarTurn
, cd = 10
, effect = [ Chance 65 << Grant Self 3 StarsPerTurn <| Range 5 10
, Chance 65 << Grant Self 3 StarUp <| Range 30 50
, Chance 65 << Grant Self 3 CritUp <| Range 20 40
, To Self GaugeUp <| Range 30 50
]
}
]
, passives = [magicResistance A, riding APlus, independentAction B]
, phantasm = { name = "Hippogriff"
, rank = BPlusPlus
, card = Quick
, kind = "Anti-Army"
, hits = 1
, effect = [ To Enemies DamageThruDef <| Range 800 1200
, Times 3 <| Grant Self 0 Evasion Full
]
, over = [ To Party GainStars <| Range 10 30 ]
, first = False
}
, gen = { starWeight = 205, starRate = 9, npAtk = 0.66, npDef = 1 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 4 }
, gender = Nonbinary
, traits = [Humanoid, Riding, EnumaElish]
, death = 40
, align = [Chaotic, Good]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (MeteorHorseshoe, 6)]
[(Monument Rider, 4), (OctupletCrystals, 8), (PhoenixFeather, 4)]
[(Monument Rider, 10), (ClawOfChaos, 6), (PhoenixFeather, 7)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (OctupletCrystals, 4)]
[(SecretGemOf Rider, 4), (OctupletCrystals, 8)]
[(SecretGemOf Rider, 10), (MeteorHorseshoe, 4)]
[(ForbiddenPage, 5), (MeteorHorseshoe, 8)]
[(ForbiddenPage, 15), (SeedOfYggdrasil, 24)]
}
, { name = "Queen Medb"
, spoiler = Nothing
, id = 99
, rarity = 5
, class = Rider
, attr = Earth
, deck = Deck Quick Arts Arts Buster Buster
, curve = 5
, stats = { base = { atk = 1591, hp = 2048 }
, max = { atk = 10296, hp = 13968 }
, grail = { atk = 11270, hp = 15303 }
}
, skills = [ { name = "Golden Rule (Body)"
, rank = A
, icon = Icon.HealTurn
, cd = 8
, effect = [ Grant Self 3 DebuffResist Full
, Grant Self 3 HealPerTurn <| Range 500 1000
, Grant Self 3 GaugePerTurn <| Flat 10
]
}
, { name = "Queen's Discipline"
, rank = A
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 10 20
, Grant (AlliesType Male) 3 AttackUp <| Range 10 20
, To Self Heal <| Range 1100 2000
]
}
, { name = "Siren Song"
, rank = C
, icon = Icon.Heart
, cd = 9
, effect = [ Chances 50 80 <| Debuff (EnemyType Male) 1 Charm Full ]
}
]
, passives = [magicResistance B, riding A]
, phantasm = { name = "Chariot My Love"
, rank = BPlus
, card = Buster
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemy Damage <| Range 800 1200 ]
, over = [ To Enemy (SpecialDamage <| VsTrait Male) <| Range 150 200
, Debuff Enemy 3 MentalVuln <| Range 20 60
]
, first = False
}
, gen = { starWeight = 208, starRate = 9, npAtk = 0.86, npDef = 3 }
, hits = { quick = 3, arts = 2, buster = 1, ex = 7 }
, gender = Female
, traits = [Humanoid, Riding, EnumaElish, King]
, death = 40
, align = [Chaotic, Evil]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (SerpentJewel, 6)]
[(Monument Rider, 5), (PhoenixFeather, 8), (MeteorHorseshoe, 5)]
[(Monument Rider, 12), (MeteorHorseshoe, 10), (WarhorsesYoungHorn, 8)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (PhoenixFeather, 4)]
[(SecretGemOf Rider, 5), (PhoenixFeather, 8)]
[(SecretGemOf Rider, 12), (SerpentJewel, 4)]
[(SerpentJewel, 8), (GhostLantern, 6)]
[(GhostLantern, 18), (HeartOfTheForeignGod, 10)]
}
, { name = "Iskandar"
, spoiler = Nothing
, id = 108
, rarity = 5
, class = Rider
, attr = Human
, deck = Deck Quick Arts Arts Buster Buster
, curve = 10
, stats = { base = { atk = 1786, hp = 1938 }
, max = { atk = 11560, hp = 13219 }
, grail = { atk = 12654, hp = 14482 }
}
, skills = [ { name = "Charisma"
, rank = A
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 10 20 ]
}
, { name = "Tactics"
, rank = B
, icon = Icon.BeamUp
, cd = 7
, effect = [ Grant Party 1 NPUp <| Range 9 18 ]
}
, { name = "Lightning Conqueror"
, rank = EX
, icon = Icon.BusterUp
, cd = 8
, effect = [ Grant Self 1 (CardUp Buster) <| Range 30 50
, Grant Self 1 StarUp <| Flat 50
]
}
]
, passives = [magicResistance D, riding APlus, divinity C]
, phantasm = { name = "Ionioi Hetairoi"
, rank = EX
, card = Buster
, kind = "Anti-Army"
, hits = 8
, effect = [ To Enemies Damage <| Range 400 600 ]
, over = [ Debuff Enemies 3 DefenseDown <| Range 10 30
, Debuff Enemies 3 CritChance <| Range 10 50
]
, first = False
}
, gen = { starWeight = 205, starRate = 8.8, npAtk = 0.66, npDef = 3 }
, hits = { quick = 3, arts = 2, buster = 1, ex = 6 }
, gender = Male
, traits = [Humanoid, LovedOne, Divine, GreekMythMale, King, Riding, EnumaElish]
, death = 40
, align = [Neutral, Good]
, limited = True
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (MeteorHorseshoe, 8)]
[(Monument Rider, 5), (ProofOfHero, 29), (OctupletCrystals, 5)]
[(Monument Rider, 12), (OctupletCrystals, 10), (WarhorsesYoungHorn, 8)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (ProofOfHero, 15)]
[(SecretGemOf Rider, 5), (ProofOfHero, 29)]
[(SecretGemOf Rider, 12), (MeteorHorseshoe, 5)]
[(MeteorHorseshoe, 10), (SeedOfYggdrasil, 8)]
[(SeedOfYggdrasil, 22), (PhoenixFeather, 20)]
}
, { name = "Sakata Kintoki (Rider)"
, spoiler = Nothing
, id = 115
, rarity = 4
, class = Rider
, attr = Earth
, deck = Deck Quick Quick Arts Buster Buster
, curve = 9
, stats = { base = { atk = 1636, hp = 1728 }
, max = { atk = 9819, hp = 10800 }
, grail = { atk = 11889, hp = 13095 }
}
, skills = [ { name = "Long-Distance Dash"
, rank = A
, icon = Icon.QuickUp
, cd = 7
, effect = [ Grant Self 3 (CardUp Quick) <| Range 20 30
, Grant Self 3 StarUp <| Range 30 50
]
}
, { name = "Animal Communication"
, rank = C
, icon = Icon.Noble
, cd = 8
, effect = [ To Self GaugeUp <| Range 30 50 ]
}
, { name = "Natural Body"
, rank = A
, icon = Icon.HoodUp
, cd = 7
, effect = [ Grant Self 3 OffensiveResist <| Range 60 120
, To Self Heal <| Range 1000 3000
]
}
]
, passives = [divinity C]
, phantasm = { name = "Golden Drive, Good Night"
, rank = B
, card = Quick
, kind = "Anti-Army"
, hits = 4
, effect = [ To Enemy Damage <| Range 1200 2000 ]
, over = [ Grant Self 1 (CardUp Quick) <| Range 10 90 ]
, first = False
}
, gen = { starWeight = 198, starRate = 9, npAtk = 1.15, npDef = 3 }
, hits = { quick = 4, arts = 2, buster = 1, ex = 5 }
, gender = Male
, traits = [Humanoid, LovedOne, Divine, EnumaElish]
, death = 40
, align = [Lawful, Good]
, limited = True
, free = True
, ascendUp = Welfare "Golden Bear Lighter"
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (OctupletCrystals, 4)]
[(SecretGemOf Rider, 4), (OctupletCrystals, 8)]
[(SecretGemOf Rider, 10), (SeedOfYggdrasil, 5)]
[(SeedOfYggdrasil, 10), (MeteorHorseshoe, 5)]
[(MeteorHorseshoe, 15), (WarhorsesYoungHorn, 12)]
}
, { name = "Ozymandias"
, spoiler = Nothing
, id = 118
, rarity = 5
, class = Rider
, attr = Sky
, deck = Deck Quick Arts Arts Buster Buster
, curve = 5
, stats = { base = { atk = 1850, hp = 1881 }
, max = { atk = 11971, hp = 12830 }
, grail = { atk = 13104, hp = 14056 }
}
, skills = [ { name = "Charisma"
, rank = B
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 9 18 ]
}
, { name = "Imperial Privilege"
, rank = A
, icon = Icon.Heal
, cd = 7
, effect = [ To Self Heal <| Range 1000 3000
, Chance 60 << Grant Self 3 AttackUp <| Range 20 40
, Chance 60 << Grant Self 3 DefenseUp <| Range 20 40
]
}
, { name = "Protection of the Sun God"
, rank = A
, icon = Icon.Noble
, cd = 8
, effect = [ To Party GaugeUp <| Flat 20
, Grant Party 1 BuffUp <| Range 20 40
]
}
]
, passives = [magicResistance B, riding APlus, divinity B]
, phantasm = { name = "Ramesseum Tentyris"
, rank = EX
, card = Buster
, kind = "Anti-Fortress"
, hits = 5
, effect = [ To Enemy Damage <| Range 600 1000
, Debuff Enemy 1 SealNP Full
]
, over = [ Debuff Enemy 3 DefenseDown <| Range 20 60 ]
, first = False
}
, gen = { starWeight = 205, starRate = 9, npAtk = 0.59, npDef = 3 }
, hits = { quick = 5, arts = 3, buster = 1, ex = 5 }
, gender = Male
, traits = [Humanoid, LovedOne, Divine, Riding, EnumaElish, King]
, death = 30
, align = [Chaotic, Balanced]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (FoolsChain, 22)]
[(Monument Rider, 5), (HeartOfTheForeignGod, 2), (SerpentJewel, 8)]
[(Monument Rider, 12), (HeartOfTheForeignGod, 4), (ScarabOfWisdom, 5)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (SerpentJewel, 4)]
[(SecretGemOf Rider, 5), (SerpentJewel, 8)]
[(SecretGemOf Rider, 12), (FoolsChain, 15)]
[(FoolsChain, 29), (ForbiddenPage, 6)]
[(ForbiddenPage, 18), (LampOfEvilSealing, 15)]
}
, { name = "Mordred (Rider)"
, spoiler = Nothing
, id = 132
, rarity = 4
, class = Rider
, attr = Earth
, deck = Deck Quick Quick Arts Arts Buster
, curve = 24
, stats = { base = { atk = 1535, hp = 1824 }
, max = { atk = 9212, hp = 11400 }
, grail = { atk = 11154, hp = 13822 }
}
, skills = [ { name = "Cerulean Ride"
, rank = A
, icon = Icon.ArtsUp
, cd = 7
, effect = [ Grant Self 3 (CardUp Arts) <| Range 20 30 ]
}
, { name = "Rodeo Flip"
, rank = APlus
, icon = Icon.Dodge
, cd = 9
, effect = [ Grant Self 1 Evasion Full
, Grant Self 1 StarUp <| Range 30 50
]
}
, { name = "Endless Summer"
, rank = B
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Self 3 Guts <| Flat 1000
, To Self GaugeUp <| Range 20 30
]
}
]
, passives = [magicResistance B, surfing A]
, phantasm = { name = "Prydwen Tube Riding"
, rank = A
, card = Arts
, kind = "Anti-Wave"
, hits = 5
, effect = [ To Enemies Damage <| Range 450 750 ]
, over = [ Chances 50 90 << To Enemies GaugeDown <| Flat 1 ]
, first = False
}
, gen = { starWeight = 204, starRate = 9.2, npAtk = 0.71, npDef = 3 }
, hits = { quick = 3, arts = 2, buster = 1, ex = 4 }
, gender = Female
, traits = [Humanoid, Dragon, Saberface, EnumaElish]
, death = 35
, align = [Chaotic, Good]
, limited = True
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (ShellOfReminiscence, 6)]
[(Monument Rider, 4), (GreatKnightMedal, 16), (DragonFang, 10)]
[(Monument Rider, 10), (DragonFang, 20), (DragonsReverseScale, 4)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (GreatKnightMedal, 8)]
[(SecretGemOf Rider, 4), (GreatKnightMedal, 16)]
[(SecretGemOf Rider, 10), (ShellOfReminiscence, 4)]
[(ShellOfReminiscence, 8), (HomunculusBaby, 5)]
[(HomunculusBaby, 15), (TearstoneOfBlood, 12)]
}
, { name = "Quetzalcoatl"
, spoiler = Nothing
, id = 144
, rarity = 5
, class = Rider
, stats = { base = { atk = 1854, hp = 1900 }
, max = { atk = 12001, hp = 12960 }
, grail = { atk = 13137, hp = 14198 }
}
, gen = { starWeight = 205, starRate = 9, npAtk = 0.9, npDef = 3 }
, death = 25
, curve = 5
, attr = Sky
, align = [Lawful, Good]
, gender = Female
, traits = [Humanoid, Divine, Riding, EnumaElish, King]
, deck = Deck Quick Arts Arts Buster Buster
, hits = { quick = 3, arts = 2, buster = 3, ex = 5 }
, skills = [ { name = "Charisma"
, rank = APlus
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 10.5 21 ]
}
, { name = "Wisdom of the Benevolent God"
, rank = APlus
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Ally 3 Guts <| Flat 1000
, Grant Ally 3 (CardUp Buster) <| Range 20 30
]
}
, { name = "Lucha Libre"
, rank = EX
, icon = Icon.StarUp
, cd = 8
, effect = [ Grant Self 1 GatherUp <| Range 300 600
, Grant Self 1 CritUp <| Range 30 50
, To Self GaugeUp <| Range 20 30
]
}
]
, passives = [magicResistance A, riding EX, coreOfGoddess EX]
, phantasm = { name = "Xiuhcoatl"
, rank = A
, card = Buster
, kind = "Anti-Army/Anti-Fortress"
, hits = 1
, effect = [ To Enemy Damage <| Range 600 1000
, Debuff Enemy 1 SealNP Full
]
, over = [ Debuff Enemy 5 Burn <| Range 1000 3000 ]
, first = False
}
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (DragonFang, 18)]
[(Monument Rider, 5), (SerpentJewel, 8), (DragonsReverseScale, 2)]
[(Monument Rider, 12), (DragonsReverseScale, 4), (PhoenixFeather, 10)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (SerpentJewel, 4)]
[(SecretGemOf Rider, 5), (SerpentJewel, 8)]
[(SecretGemOf Rider, 12), (DragonFang, 12)]
[(DragonFang, 24), (FoolsChain, 18)]
[(FoolsChain, 54), (CursedBeastGallstone, 10)]
}
, { name = "Christopher Columbus"
, spoiler = Just "Resistance"
, id = 172
, rarity = 3
, class = Rider
, stats = { base = { atk = 1216, hp = 1728 }
, max = { atk = 6552, hp = 9600 }
, grail = { atk = 8867, hp = 13016 }
}
, gen = { starWeight = 208, starRate = 8.9, npAtk = 0.55, npDef = 3 }
, death = 50
, curve = 13
, attr = Human
, align = [Neutral, Evil]
, gender = Male
, traits = [Humanoid, EnumaElish]
, deck = Deck Quick Arts Arts Buster Buster
, hits = { quick = 3, arts = 3, buster = 4, ex = 5 }
, skills = [ { name = "Voyager of the Storm"
, rank = B
, icon = Icon.BeamUp
, cd = 7
, effect = [ Grant Party 1 NPUp <| Range 7 14
, Grant Party 1 AttackUp <| Range 7 14
]
}
, { name = "Unyielding Will"
, rank = C
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Self 3 Guts <| Flat 1
, To Self GaugeUp <| Range 10 30
]
}
, { name = "Conquistador"
, rank = EX
, icon = Icon.BusterUp
, cd = 8
, effect = [ Grant Self 3 (CardUp Buster) <| Range 10 20
, To Party GainStars <| Range 5 15
]
}
]
, passives = [magicResistance D, riding B]
, phantasm = { name = "Santa María・Drop Anchor"
, rank = A
, card = Buster
, kind = "Anti-Army"
, hits = 4
, effect = [ To Enemies Damage <| Range 300 500 ]
, over = [ Debuff Enemies 3 CritChance <| Range 20 60 ]
, first = False
}
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (FoolsChain, 15)]
[(Monument Rider, 4), (MysteriousDivineWine, 3), (DeadlyPoisonousNeedle, 8)]
[(Monument Rider, 8), (DeadlyPoisonousNeedle, 16), (GhostLantern, 8)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (MysteriousDivineWine, 2)]
[(SecretGemOf Rider, 4), (MysteriousDivineWine, 3)]
[(SecretGemOf Rider, 8), (FoolsChain, 10)]
[(FoolsChain, 20), (MysticSpinalFluid, 12)]
[(MysticSpinalFluid, 36), (CursedBeastGallstone, 7)]
}
, { name = "Altria Pendragon (Rider Alter)"
, spoiler = Nothing
, id = 179
, rarity = 5
, class = Rider
, stats = { base = { atk = 1665, hp = 2090 }
, max = { atk = 10776, hp = 14256 }
, grail = { atk = 11796, hp = 15618 }
}
, gen = { starWeight = 200, starRate = 9, npAtk = 0.59, npDef = 3 }
, death = 30
, curve = 5
, attr = Human
, align = [Lawful, Evil]
, gender = Female
, traits = [Humanoid, Arthur, Dragon, Riding, Saberface, EnumaElish, King]
, deck = Deck Quick Quick Arts Arts Buster
, hits = { quick = 3, arts = 3, buster = 2, ex = 5 }
, skills = [ { name = "Summer Sweeper!"
, rank = A
, icon = Icon.SwordUp
, cd = 8
, effect = [ Grant Self 3 AttackUp <| Range 20 30
, Grant Party 3 (CardUp Quick) <| Range 10 20
]
}
, { name = "Coaching"
, rank = A
, icon = Icon.MagicLight
, cd = 8
, effect = [ To Ally ReduceCooldowns <| Flat 1
, Grant Self 3 StarUp <| Range 30 50
, To Ally DemeritHealth <| Flat 1000
]
}
, { name = "Reloaded"
, rank = C
, icon = Icon.QuickUp
, cd = 5
, effect = [ Times 1 << Grant Self 3 (CardUp Quick) <| Range 20 30 ]
}
]
, passives = [magicResistance B, riding B, independentAction EX]
, phantasm = { name = "Secace Morgan"
, rank = C
, card = Quick
, kind = "Anti-Army"
, hits = 6
, effect = [ To Enemy Damage <| Range 1200 2000
, To Self GaugeUp <| Flat 10
]
, over = [ Debuff Enemy 3 CritChance <| Range 30 70 ]
, first = False
}
, limited = True
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (GreatKnightMedal, 15)]
[(Monument Rider, 5), (DragonsReverseScale, 4), (ShellOfReminiscence, 5)]
[(Monument Rider, 12), (ShellOfReminiscence, 10), (CursedBeastGallstone, 5)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (DragonsReverseScale, 2)]
[(SecretGemOf Rider, 5), (DragonsReverseScale, 4)]
[(SecretGemOf Rider, 12), (GreatKnightMedal, 10)]
[(GreatKnightMedal, 20), (DragonFang, 15)]
[(DragonFang, 44), (MeteorHorseshoe, 24)]
}
, { name = "Ishtar (Rider)"
, spoiler = Nothing
, id = 182
, rarity = 4
, class = Rider
, stats = { base = { atk = 1600, hp = 1710 }
, max = { atk = 9603, hp = 10692 }
, grail = { atk = 11627, hp = 12964 }
}
, gen = { starWeight = 200, starRate = 9, npAtk = 0.68, npDef = 3 }
, death = 35
, curve = 9
, attr = Sky
, align = [Lawful, Good]
, gender = Female
, traits = [Humanoid, Divine, Riding, EnumaElish]
, deck = Deck Quick Quick Arts Arts Buster
, hits = { quick = 2, arts = 3, buster = 5, ex = 3 }
, skills = [ { name = "Shining Water Robe"
, rank = A
, icon = Icon.QuickBusterUp
, cd = 7
, effect = [ Grant Party 3 (CardUp Quick) <| Range 10 20
, Grant Party 3 (CardUp Buster) <| Range 10 20
, Grant Party 3 NPGen <| Range 10 20
]
}
, { name = "Accel Turn"
, rank = B
, icon = Icon.Dodge
, cd = 6
, effect = [ Grant Self 1 CritUp <| Range 30 50
, Times 1 <| Grant Self 1 Evasion Full
]
}
, { name = "Summer Breaker!"
, rank = A
, icon = Icon.Shield
, cd = 8
, effect = [ Grant Self 1 NPGen <| Range 30 50
, Grant Self 1 CritUp <| Range 30 50
, Grant Self 1 HealingReceived <| Range 30 50
, Grant Self 1 DebuffResist <| Range 30 50
, Grant Self 1 Invincibility Full
, After 1 <| Debuff Self 1 Stun Full
]
}
]
, passives = [riding EX, independentAction A, coreOfGoddess B]
, phantasm = { name = "An Gal Tā Seven Colors"
, rank = EX
, card = Quick
, kind = "Anti-Personnel"
, hits = 4
, effect = [ To Enemies Damage <| Range 600 1000 ]
, over = [ Grant Self 1 (CardUp Quick) <| Range 20 60 ]
, first = True
}
, limited = True
, free = True
, ascendUp = Welfare "Golden Reed"
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (ShellOfReminiscence, 4)]
[(SecretGemOf Rider, 4), (ShellOfReminiscence, 8)]
[(SecretGemOf Rider, 10), (PrimordialLanugo, 3)]
[(PrimordialLanugo, 5), (ScarabOfWisdom, 2)]
[(ScarabOfWisdom, 6), (MysteriousDivineWine, 8)]
}
, { name = "Ivan the Terrible"
, spoiler = Nothing
, id = 205
, rarity = 5
, class = Rider
, stats = { base = { atk = 1795, hp = 1948 }
, max = { atk = 11619, hp = 13284 }
, grail = { atk = 12719, hp = 14553 }
}
, gen = { starWeight = 200, starRate = 8.9, npAtk = 0.62, npDef = 3 }
, death = 40
, curve = 10
, attr = Human
, align = [Lawful, Evil]
, gender = Male
, traits = [Humanoid, WildBeast, King, Riding, EnumaElish]
, deck = Deck Quick Arts Arts Buster Buster
, hits = { quick = 4, arts = 3, buster = 2, ex = 4 }
, skills = [ { name = "Mental Schism"
, rank = A
, icon = Icon.NobleUp
, cd = 7
, effect = [ Grant Self 3 NPGen <| Range 30 50
, To Self RemoveDebuffs Full
]
}
, { name = "Innocent Monster (Foreign)"
, rank = A
, icon = Icon.StarTurn
, cd = 7
, effect = [ Grant Self 3 StarsPerTurn <| Range 5 10
, Grant Self 3 (CardUp Buster) <| Range 20 40
]
}
, { name = "Emergency Prerogative"
, rank = A
, icon = Icon.Shield
, cd = 8
, effect = [ Grant Self 1 Invincibility Full
, Debuff Enemies 3 AttackDown <| Range 10 20
, To Enemies RemoveBuffs Full
]
}
]
, passives = [magicResistance D, riding EX]
, phantasm = { name = "Zveri Krestnyi Khod"
, rank = B
, card = Buster
, kind = "Anti-Personnel"
, hits = 5
, effect = [ To Enemies Damage <| Range 300 500
, Debuff Enemies 3 (CardVuln Buster) <| Flat 20
]
, over = [ Grant Self 1 NPUp <| Range 30 70 ]
, first = True
}
, limited = True
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (EvilBone, 22)]
[(Monument Rider, 5), (MeteorHorseshoe, 10), (PrimordialLanugo, 3)]
[(Monument Rider, 12), (PrimordialLanugo, 6), (CursedBeastGallstone, 5)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 5), (MeteorHorseshoe, 5)]
[(SecretGemOf Rider, 5), (MeteorHorseshoe, 10)]
[(SecretGemOf Rider, 12), (EvilBone, 15)]
[(EvilBone, 29), (DeadlyPoisonousNeedle, 15)]
[(DeadlyPoisonousNeedle, 44), (EternalIce, 24)]
}
, { name = "Achilles"
, spoiler = Nothing
, id = 206
, rarity = 5
, class = Rider
, stats = { base = { atk = 1836, hp = 1938 }
, max = { atk = 11883, hp = 13219 }
, grail = { atk = 13008, hp = 14482 }
}
, gen = { starWeight = 196, starRate = 9.1, npAtk = 0.57, npDef = 3 }
, death = 40
, curve = 10
, attr = Earth
, align = [Lawful, Balanced]
, gender = Male
, traits = [Humanoid, Divine, Riding, LovedOne, GreekMythMale, EnumaElish]
, deck = Deck Quick Quick Arts Arts Buster
, hits = { quick = 4, arts = 3, buster = 2, ex = 4 }
, skills = [ { name = "Drómos Komḗtēs"
, rank = APlus
, icon = Icon.QuickUp
, cd = 7
, effect = [ Grant Self 3 (CardUp Quick) <| Range 20 30
, Grant Self 3 CritUp <| Range 20 30
]
}
, { name = "Andreíos Amárantos"
, rank = B
, icon = Icon.Shield
, cd = 7
, effect = [ Times 2 <| Grant Self 5 Invincibility Full
, Grant Self 3 DefenseUp <| Range 10 20
]
}
, { name = "Diatrekhо̄n Astēr Lonkhē"
, rank = BPlus
, icon = Icon.CrosshairUp
, cd = 8
, effect = [ Chance 500 <| Grant Self 1 Taunt Full
, Grant Self 1 NPGen <| Range 20 30
, To Self GaugeUp <| Range 20 30
]
}
]
, passives = [magicResistance C, riding APlus, divinity C]
, phantasm = { name = "Troias Tragо̄idia"
, rank = A
, card = Quick
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemies Damage <| Range 600 1000 ]
, over = [ Grant Self 1 (CardUp Quick) <| Range 20 60 ]
, first = True
}
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (ProofOfHero, 22)]
[(Monument Rider, 5), (EternalGear, 10), (WarhorsesYoungHorn, 3)]
[(Monument Rider, 12), (WarhorsesYoungHorn, 6), (PhoenixFeather, 10)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (EternalGear, 5)]
[(SecretGemOf Rider, 5), (EternalGear, 10)]
[(SecretGemOf Rider, 12), (ProofOfHero, 15)]
[(ProofOfHero, 29), (MeteorHorseshoe, 6)]
[(MeteorHorseshoe, 18), (HeartOfTheForeignGod, 10)]
}
]
| 29004 | module Database.Servant.Rider exposing (riders)
import Model.Attribute exposing (Attribute(..))
import Model.Card exposing (Card(..))
import Model.Class exposing (Class(..))
import Model.Deck exposing (Deck(..))
import Model.Material exposing (Material(..))
import Model.Trait exposing (Trait(..))
import Database.Passives exposing (..)
import Model.Servant exposing (Servant, Ascension(..), Reinforcement(..))
import Model.Skill.Amount exposing (Amount(..))
import Model.Skill.BuffEffect exposing (BuffEffect(..))
import Model.Skill.DebuffEffect exposing (DebuffEffect(..))
import Model.Skill.InstantEffect exposing (InstantEffect(..))
import Model.Skill.Rank exposing (Rank(..))
import Model.Skill.SkillEffect exposing (SkillEffect(..))
import Model.Skill.Special exposing (Special(..))
import Model.Skill.Target exposing (Target(..))
import Model.Icon as Icon
riders : List Servant
riders =
[ { name = "<NAME>"
, spoiler = Nothing
, id = 23
, rarity = 3
, class = Rider
, attr = Earth
, deck = Deck Quick Quick Arts Arts Buster
, curve = 24
, stats = { base = { atk = 1337, hp = 1608 }
, max = { atk = 7200, hp = 8937 }
, grail = { atk = 9744, hp = 12117 }
}
, skills = [ { name = "Mystic Eyes"
, rank = APlus
, icon = Icon.Stun
, cd = 8
, effect = [ Chances 50 100 <| Debuff Enemy 1 Stun Full ]
}
, { name = "Monstrous Strength"
, rank = B
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Self 2 AttackUp <| Range 10 30 ]
}
, { name = "Blood Fort Andromeda"
, rank = B
, icon = Icon.Noble
, cd = 8
, effect = [ To Self GaugeUp <| Flat 20
, Grant Self 3 NPGen <| Range 20 30
]
}
]
, passives = [magicResistance B, independentAction C, divinity EMinus, riding APlus]
, phantasm = { name = "<NAME>"
, rank = APlus
, card = Quick
, kind = "Anti-Army"
, hits = 1
, effect = [ To Enemies Damage <| Range 600 1000 ]
, over = [ Grant Party 3 StarUp <| Range 20 60 ]
, first = False
}
, gen = { starWeight = 194, starRate = 9, npAtk = 0.58, npDef = 3 }
, hits = { quick = 2, arts = 3, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, Divine]
, death = 35
, align = [Chaotic, Good]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (SerpentJewel, 4)]
[(Monument Rider, 4), (VoidsDust, 13), (MeteorHorseshoe, 4)]
[(Monument Rider, 8), (MeteorHorseshoe, 7), (PhoenixFeather, 7)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (VoidsDust, 7)]
[(SecretGemOf Rider, 4), (VoidsDust, 13)]
[(SecretGemOf Rider, 8), (SerpentJewel, 3)]
[(SerpentJewel, 6), (HeartOfTheForeignGod, 2)]
[(HeartOfTheForeignGod, 5), (PhoenixFeather, 13)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 24
, rarity = 2
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 2
, stats = { base = { atk = 929, hp = 1731 }
, max = { atk = 5236, hp = 9200 }
, grail = { atk = 7587, hp = 13278 }
}
, skills = [ { name = "<NAME>"
, rank = APlus
, icon = Icon.CrosshairUp
, cd = 7
, effect = [ Grant Self 3 Taunt Full
, Grant Self 3 DefenseUp <| Range 20 40
]
}
, { name = "<NAME>"
, rank = BPlus
, icon = Icon.HoodUp
, cd = 7
, effect = [ Grant Self 3 MentalResist <| Range 50 100
, To Self Heal <| Range 750 2000
]
}
, { name = "<NAME>"
, rank = A
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Self 5 Guts <| Range 1000 2500 ]
}
]
, passives = [magicResistance A, riding B]
, phantasm = { name = "<NAME>"
, rank = B
, card = Arts
, kind = "Anti-Personnel"
, hits = 4
, effect = [ To Enemy (ApplyTrait Dragon) <| Flat 3
, To Enemy Damage <| Range 900 1500
]
, over = [ Grant Self 1 DefenseUp <| Range 20 40 ]
, first = False
}
, gen = { starWeight = 205, starRate = 8.9, npAtk = 0.85, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Male
, traits = [Humanoid, Riding, LovedOne, EnumaElish]
, death = 45
, align = [Lawful, Good]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 3)]
[(Piece Rider, 6), (ProofOfHero, 11)]
[(Monument Rider, 3), (PhoenixFeather, 4), (ForbiddenPage, 3)]
[(Monument Rider, 6), (ForbiddenPage, 5), (MeteorHorseshoe, 6)]
, skillUp = Reinforcement
[(GemOf Rider, 3)]
[(GemOf Rider, 6)]
[(MagicGemOf Rider, 3)]
[(MagicGemOf Rider, 6), (PhoenixFeather, 2)]
[(SecretGemOf Rider, 3), (PhoenixFeather, 4)]
[(SecretGemOf Rider, 6), (ProofOfHero, 8)]
[(ProofOfHero, 15), (EternalGear, 3)]
[(EternalGear, 9), (MeteorHorseshoe, 12)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 25
, rarity = 2
, class = Rider
, attr = Human
, deck = Deck Quick Arts Arts Buster Buster
, curve = 12
, stats = { base = { atk = 1097, hp = 1488 }
, max = { atk = 6188, hp = 7907 }
, grail = { atk = 8967, hp = 11411 }
}
, skills = [ { name = "<NAME>"
, rank = A
, icon = Icon.BeamUp
, cd = 7
, effect = [ Grant Party 1 NPUp <| Range 8 16
, Grant Party 1 AttackUp <| Range 8 16
]
}
, { name = "<NAME>"
, rank = B
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Self 3 AttackUp <| Range 9 27
, Times 1 << Grant Self 0 Guts <| Flat 1
, Debuff Self 3 DebuffVuln <| Flat 50
]
}
, { name = "<NAME>"
, rank = C
, icon = Icon.Heal
, cd = 8
, effect = [ To Party Heal <| Range 1000 2000
, To (AlliesType Female) Heal <| Range 1000 2000
, To (AlliesType Nonbinary) Heal <| Range 1000 2000
]
}
]
, passives = [magicResistance E]
, phantasm = { name = "<NAME>"
, rank = CPlusPlus
, card = Buster
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemies Damage <| Range 300 500
, To Party GainStars <| Flat 5
]
, over = [ Chances 30 70 << To Enemies GaugeDown <| Flat 1 ]
, first = False
}
, gen = { starWeight = 198, starRate = 8.8, npAtk = 0.56, npDef = 3 }
, hits = { quick = 2, arts = 3, buster = 1, ex = 3 }
, gender = Male
, traits = [Humanoid, EnumaElish]
, death = 45
, align = [Chaotic, Evil]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 3)]
[(Piece Rider, 6), (EvilBone, 11)]
[(Monument Rider, 3), (OctupletCrystals, 5), (ForbiddenPage, 3)]
[(Monument Rider, 6), (ForbiddenPage, 5), (GhostLantern, 6)]
, skillUp = Reinforcement
[(GemOf Rider, 3)]
[(GemOf Rider, 6)]
[(MagicGemOf Rider, 3)]
[(MagicGemOf Rider, 6), (OctupletCrystals, 3)]
[(SecretGemOf Rider, 3), (OctupletCrystals, 5)]
[(SecretGemOf Rider, 6), (EvilBone, 8)]
[(EvilBone, 15), (HomunculusBaby, 3)]
[(HomunculusBaby, 9), (GhostLantern, 12)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 26
, rarity = 3
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 3
, stats = { base = { atk = 1168, hp = 1823 }
, max = { atk = 6289, hp = 10130 }
, grail = { atk = 8511, hp = 13735 }
}
, skills = [ { name = "<NAME>"
, rank = B
, icon = Icon.DamageUp
, cd = 7
, effect = [ Grant Self 3 (Special AttackUp <| VsTrait Roman) <| Range 40 60 ]
}
, { name = "Battle Continuation"
, rank = A
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Self 5 Guts <| Range 1000 2500 ]
}
, { name = "<NAME>"
, rank = A
, icon = Icon.ArtsUp
, cd = 7
, effect = [ Grant Party 3 (CardUp Arts) <| Range 10 20 ]
}
]
, passives = [magicResistance D, riding A]
, phantasm = { name = "<NAME>"
, rank = BPlusPlus
, card = Arts
, kind = "Anti-Army"
, hits = 0
, effect = [ Grant Party 3 DefenseUp <| Range 10 20 ]
, over = [ Grant Party 1 DefenseUp <| Range 20 40
, Grant Party 3 AttackUp <| Range 20 40
]
, first = False
}
, gen = { starWeight = 196, starRate = 8.9, npAtk = 0.85, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, EnumaElish, King]
, death = 45
, align = [Neutral, Good]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (PhoenixFeather, 4)]
[(Monument Rider, 4), (EvilBone, 20), (MeteorHorseshoe, 4)]
[(Monument Rider, 8), (MeteorHorseshoe, 7), (VoidsDust, 16)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (EvilBone, 10)]
[(SecretGemOf Rider, 4), (EvilBone, 20)]
[(SecretGemOf Rider, 8), (PhoenixFeather, 3)]
[(PhoenixFeather, 6), (SerpentJewel, 4)]
[(SerpentJewel, 10), (VoidsDust, 32)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 27
, rarity = 3
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 8
, stats = { base = { atk = 1314, hp = 1625 }
, max = { atk = 7076, hp = 9028 }
, grail = { atk = 9576, hp = 12240 }
}
, skills = [ { name = "<NAME>"
, rank = A
, icon = Icon.NobleUp
, cd = 7
, effect = [ Grant Party 3 NPGen <| Range 10 20 ]
}
, { name = "<NAME>"
, rank = CPlus
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 8.5 17 ]
}
, { name = "<NAME>"
, rank = B
, icon = Icon.Dodge
, cd = 8
, effect = [ Times 1 <| Grant Self 1 Evasion Full
, Grant Self 1 StarUp <| Range 50 100
]
}
]
, passives = [magicResistance C, riding APlus]
, phantasm = { name = "<NAME>"
, rank = C
, card = Quick
, kind = "Anti-Personnel"
, hits = 1
, effect = [ To Enemy Damage <| Range 1600 2400 ]
, over = [ Grant Self 3 StarUp <| Range 50 90 ]
, first = False
}
, gen = { starWeight = 204, starRate = 9.1, npAtk = 0.87, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, LovedOne, EnumaElish]
, death = 35
, align = [Chaotic, Balanced]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (ProofOfHero, 15)]
[(Monument Rider, 4), (MeteorHorseshoe, 7), (GhostLantern, 4)]
[(Monument Rider, 8), (GhostLantern, 7), (OctupletCrystals, 8)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (MeteorHorseshoe, 4)]
[(SecretGemOf Rider, 4), (MeteorHorseshoe, 7)]
[(SecretGemOf Rider, 8), (ProofOfHero, 10)]
[(ProofOfHero, 20), (EternalGear, 4)]
[(EternalGear, 12), (OctupletCrystals, 16)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 28
, rarity = 3
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 3
, stats = { base = { atk = 1366, hp = 1979 }
, max = { atk = 7356, hp = 8640 }
, grail = { atk = 9955, hp = 11714 }
}
, skills = [ { name = "<NAME>"
, rank = C
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 8 16 ]
}
, { name = "<NAME>"
, rank = B
, icon = Icon.Heart
, cd = 9
, effect = [ Chances 50 80 <| Debuff (EnemyType Humanoid) 1 Charm Full ]
}
, { name = "<NAME>"
, rank = A
, icon = Icon.QuickUp
, cd = 7
, effect = [ Grant Party 3 (CardUp Quick) <| Range 10 20 ]
}
]
, passives = [magicResistance D, divinity E, riding APlus]
, phantasm = { name = "<NAME>"
, rank = BPlusPlus
, card = Quick
, kind = "Anti-Army"
, hits = 1
, effect = [ To Enemies Damage <| Range 800 1200 ]
, over = [ To Party GainStars <| Range 15 35 ]
, first = False
}
, gen = { starWeight = 205, starRate = 9, npAtk = 0.86, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Male
, traits = [Humanoid, Riding, Divine, EnumaElish, GreekMythMale, King]
, death = 40
, align = [Neutral, Good]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (MeteorHorseshoe, 5)]
[(Monument Rider, 4), (PhoenixFeather, 3), (OctupletCrystals, 7)]
[(Monument Rider, 8), (PhoenixFeather, 6), (ProofOfHero, 24)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (OctupletCrystals, 4)]
[(SecretGemOf Rider, 4), (OctupletCrystals, 7)]
[(SecretGemOf Rider, 8), (MeteorHorseshoe, 4)]
[(ClawOfChaos, 3), (MeteorHorseshoe, 7)]
[(ClawOfChaos, 8), (ProofOfHero, 48)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 29
, rarity = 4
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 9
, stats = { base = { atk = 1382, hp = 1975 }
, max = { atk = 8293, hp = 12348 }
, grail = { atk = 10041, hp = 14972 }
}
, skills = [ { name = "<NAME>"
, rank = C
, icon = Icon.Heart
, cd = 9
, effect = [ Chances 50 80 <| Debuff (EnemyType Male) 1 Charm Full ]
}
, { name = "<NAME>"
, rank = A
, icon = Icon.Shield
, cd = 8
, effect = [ Times 3 <| Grant Self 0 Invincibility Full
, Grant Self 5 HealPerTurn <| Range 200 600
]
}
, { name = "God's Grace"
, rank = B
, icon = Icon.StaffUp
, cd = 7
, effect = [ Grant Self 3 MentalSuccess <| Range 10 30
, To Self Heal <| Range 1000 2500
]
}
]
, passives = [magicResistance C, riding APlus]
, phantasm = { name = "<NAME>"
, rank = APlus
, card = Quick
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemies Damage <| Range 800 1200
, To Party RemoveDebuffs Full
, Grant Party 3 CritUp <| Flat 20
]
, over = [ To Party Heal <| Range 1000 3000 ]
, first = False
}
, gen = { starWeight = 201, starRate = 9, npAtk = 1, npDef = 3 }
, hits = { quick = 2, arts = 1, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, EnumaElish, King]
, death = 35
, align = [Lawful, Good]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (PhoenixFeather, 5)]
[(Monument Rider, 4), (MeteorHorseshoe, 4), (SerpentJewel, 7)]
[(Monument Rider, 10), (MeteorHorseshoe, 8), (EternalGear, 10)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (SerpentJewel, 4)]
[(SecretGemOf Rider, 4), (SerpentJewel, 7)]
[(SecretGemOf Rider, 10), (PhoenixFeather, 4)]
[(PhoenixFeather, 7), (HeartOfTheForeignGod, 2)]
[(EternalGear, 20), (HeartOfTheForeignGod, 6)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 30
, rarity = 4
, class = Rider
, attr = Human
, deck = Deck Quick Arts Arts Arts Buster
, curve = 4
, stats = { base = { atk = 1335, hp = 2090 }
, max = { atk = 8014, hp = 13068 }
, grail = { atk = 9703, hp = 15845 }
}
, skills = [ { name = "Protection of the Faith"
, rank = A
, icon = Icon.HoodUp
, cd = 7
, effect = [ Grant Self 3 DebuffResist <| Range 50 100
, To Self Heal <| Range 1000 2500
]
}
, { name = "<NAME>"
, rank = DPlus
, icon = Icon.Heal
, cd = 8
, effect = [ To Party Heal <| Range 1000 2000
, To Party RemoveDebuffs Full
]
}
, { name = "<NAME>ath of the Holy Maiden"
, rank = C
, icon = Icon.ShieldDown
, cd = 7
, effect = [ Debuff Enemy 3 DefenseDown <| Range 10 30
, To Enemy RemoveBuffs Full
]
}
]
, passives = [magicResistance A, riding APlusPlus, divinity C]
, phantasm = { name = "<NAME>"
, rank = EX
, card = Buster
, kind = "Anti-Army"
, hits = 1
, effect = [ Grant Self 1 (CardUp Buster) <| Flat 20
, To Enemies Damage <| Range 400 600 ]
, over = [ Debuff Enemies 3 DefenseDown <| Range 20 40 ]
, first = False
}
, gen = { starWeight = 205, starRate = 9, npAtk = 1.58, npDef = 3 }
, hits = { quick = 2, arts = 1, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, Divine, EnumaElish]
, death = 30
, align = [Lawful, Good]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (DragonFang, 15)]
[(Monument Rider, 4), (ClawOfChaos, 3), (SeedOfYggdrasil, 10)]
[(Monument Rider, 10), (ClawOfChaos, 5), (DragonsReverseScale, 4)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (SeedOfYggdrasil, 5)]
[(SecretGemOf Rider, 4), (SeedOfYggdrasil, 10)]
[(SecretGemOf Rider, 10), (DragonFang, 10)]
[(PhoenixFeather, 4), (DragonFang, 20)]
[(PhoenixFeather, 12), (DragonsReverseScale, 8)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 65
, rarity = 5
, class = Rider
, attr = Star
, deck = Deck Quick Arts Arts Buster Buster
, curve = 10
, stats = { base = { atk = 1750, hp = 1881 }
, max = { atk = 11326, hp = 12830 }
, grail = { atk = 12398, hp = 14056 }
}
, skills = [ { name = "<NAME>"
, rank = APlus
, icon = Icon.BeamUp
, cd = 7
, effect = [ Grant Party 1 NPUp <| Range 8.5 17
, Grant Party 1 AttackUp <| Range 8.5 17
]
}
, { name = "<NAME>"
, rank = B
, icon = Icon.NobleUp
, cd = 8
, effect = [ Grant Self 3 NPGen <| Range 18 45 ]
}
, { name = "<NAME>"
, rank = EX
, icon = Icon.Noble
, cd = 8
, effect = [ To Self GaugeUp <| Range 30 50
, Grant Self 3 IgnoreInvinc Full
, To Party GainStars <| Flat 10
]
}
]
, passives = [magicResistance D, riding B]
, phantasm = { name = "<NAME>"
, rank = APlus
, card = Buster
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemies Damage <| Range 400 600 ]
, over = [ To Party GainStars <| Range 20 40 ]
, first = False
}
, gen = { starWeight = 208, starRate = 9, npAtk = 0.42, npDef = 3 }
, hits = { quick = 6, arts = 4, buster = 2, ex = 4 }
, gender = Female
, traits = [Humanoid, Riding]
, death = 50
, align = [Chaotic, Evil]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (EvilBone, 22)]
[(Monument Rider, 5), (DragonsReverseScale, 2), (DragonFang, 24)]
[( Monument Rider, 12), (DragonsReverseScale, 4), (HeartOfTheForeignGod, 5)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (DragonFang, 12)]
[(SecretGemOf Rider, 5), (DragonFang, 24)]
[(SecretGemOf Rider, 12), (EvilBone, 15)]
[(GhostLantern, 6), (EvilBone, 29)]
[(GhostLantern, 18), (HeartOfTheForeignGod, 10)]
}
, { name = "<NAME> & <NAME>"
, spoiler = Nothing
, id = 66
, rarity = 4
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 29
, stats = { base = { atk = 1504, hp = 1805 }
, max = { atk = 9029, hp = 11286 }
, grail = { atk = 10932, hp = 13684 }
}
, skills = [ { name = "Voyage"
, rank = A
, icon = Icon.StarHaloUp
, cd = 8
, effect = [ Grant Self 3 StarUp <| Range 30 50 ]
}
, { name = "<NAME>"
, rank = B
, icon = Icon.ExclamationUp
, cd = 7
, effect = [ Grant Self 1 CritUp <| Range 50 100 ]
}
, { name = "<NAME>"
, rank = C
, icon = Icon.StarUp
, cd = 7
, effect = [ Grant Self 1 GatherUp <| Range 300 600
, Grant Self 1 AttackUp <| Range 20 30
]
}
]
, passives = [magicResistance D]
, phantasm = { name = "<NAME>"
, rank = CPlusPlus
, card = Quick
, kind = "Anti-Personnel"
, hits = 6
, effect = [ To Enemy Damage <| Range 1600 2400 ]
, over = [ To Enemy LastStand <| Range 1200 2000 ]
, first = False
}
, gen = { starWeight = 200, starRate = 9.1, npAtk = 0.84, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 1 }
, gender = Female
, traits = [Humanoid, EnumaElish]
, death = 50
, align = [Chaotic, Evil, Chaotic, Balanced]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (HomunculusBaby, 6)]
[(Monument Rider, 4), (GhostLantern, 8), (EvilBone, 12)]
[(Monument Rider, 10), (ClawOfChaos, 6), (EvilBone, 24)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (GhostLantern, 4)]
[(SecretGemOf Rider, 4), (GhostLantern, 8)]
[(SecretGemOf Rider, 10), (HomunculusBaby, 4)]
[(VoidsDust, 10), (HomunculusBaby, 8)]
[(VoidsDust, 30), (ClawOfChaos, 12)]
}
, { name = "<NAME> (<NAME>)"
, spoiler = Nothing
, id = 73
, rarity = 4
, class = Rider
, attr = Human
, deck = Deck Quick Arts Arts Buster Buster
, curve = 29
, stats = { base = { atk = 1543, hp = 1805 }
, max = { atk = 9258, hp = 11286 }
, grail = { atk = 11209, hp = 13684 }
}
, skills = [ { name = "<NAME>"
, rank = EX
, icon = Icon.Heal
, cd = 7
, effect = [ To Ally Heal <| Range 1500 3500
, Grant Ally 3 StarUp <| Flat 30
]
}
, { name = "<NAME>"
, rank = A
, icon = Icon.Star
, cd = 7
, effect = [ To Party GainStars <| Range 5 15 ]
}
, { name = "<NAME>"
, rank = AMinus
, icon = Icon.BusterUp
, cd = 7
, effect = [ Grant Self 1 (CardUp Buster) <| Range 25 45 ]
}
]
, passives = [magicResistance A, riding A]
, phantasm = { name = "<NAME>"
, rank = APlusPlus
, card = Buster
, kind = "Anti-Army"
, hits = 3
, effect = [ To Enemies Damage <| Range 450 650 ]
, over = [ To Self GaugeUp <| Range 10 30 ]
, first = False
}
, gen = { starWeight = 204, starRate = 8.9, npAtk = 0.87, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Arthur, Dragon, Riding, Saberface, EnumaElish, King]
, death = 35
, align = [Lawful, Good]
, limited = True
, free = True
, ascendUp = Welfare "Bucket of Chicken"
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (DragonFang, 10)]
[(SecretGemOf Rider, 4), (DragonFang, 20)]
[(SecretGemOf Rider, 10), (MeteorHorseshoe, 4)]
[(MeteorHorseshoe, 8), (DragonsReverseScale, 2)]
[(DragonsReverseScale, 6), (HeartOfTheForeignGod, 8)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 94
, rarity = 4
, class = Rider
, attr = Earth
, deck = Deck Quick Quick Quick Arts Buster
, curve = 24
, stats = { base = { atk = 1489, hp = 1787 }
, max = { atk = 8937, hp = 11172 }
, grail = { atk = 10821, hp = 13546 }
}
, skills = [ { name = "Monstrous Strength"
, rank = CMinus
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Self 1 AttackUp <| Range 8 28 ]
}
, { name = "<NAME>"
, rank = D
, icon = Icon.Stun
, cd = 10
, effect = [ Chances 60 90 <| Debuff Enemy 1 Stun Full ]
}
, { name = "<NAME>aporation of Reason"
, rank = DPlus
, icon = Icon.StarTurn
, cd = 10
, effect = [ Chance 65 << Grant Self 3 StarsPerTurn <| Range 5 10
, Chance 65 << Grant Self 3 StarUp <| Range 30 50
, Chance 65 << Grant Self 3 CritUp <| Range 20 40
, To Self GaugeUp <| Range 30 50
]
}
]
, passives = [magicResistance A, riding APlus, independentAction B]
, phantasm = { name = "<NAME>"
, rank = BPlusPlus
, card = Quick
, kind = "Anti-Army"
, hits = 1
, effect = [ To Enemies DamageThruDef <| Range 800 1200
, Times 3 <| Grant Self 0 Evasion Full
]
, over = [ To Party GainStars <| Range 10 30 ]
, first = False
}
, gen = { starWeight = 205, starRate = 9, npAtk = 0.66, npDef = 1 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 4 }
, gender = Nonbinary
, traits = [Humanoid, Riding, EnumaElish]
, death = 40
, align = [Chaotic, Good]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (MeteorHorseshoe, 6)]
[(Monument Rider, 4), (OctupletCrystals, 8), (PhoenixFeather, 4)]
[(Monument Rider, 10), (ClawOfChaos, 6), (PhoenixFeather, 7)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (OctupletCrystals, 4)]
[(SecretGemOf Rider, 4), (OctupletCrystals, 8)]
[(SecretGemOf Rider, 10), (MeteorHorseshoe, 4)]
[(ForbiddenPage, 5), (MeteorHorseshoe, 8)]
[(ForbiddenPage, 15), (SeedOfYggdrasil, 24)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 99
, rarity = 5
, class = Rider
, attr = Earth
, deck = Deck Quick Arts Arts Buster Buster
, curve = 5
, stats = { base = { atk = 1591, hp = 2048 }
, max = { atk = 10296, hp = 13968 }
, grail = { atk = 11270, hp = 15303 }
}
, skills = [ { name = "Golden Rule (Body)"
, rank = A
, icon = Icon.HealTurn
, cd = 8
, effect = [ Grant Self 3 DebuffResist Full
, Grant Self 3 HealPerTurn <| Range 500 1000
, Grant Self 3 GaugePerTurn <| Flat 10
]
}
, { name = "<NAME>"
, rank = A
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 10 20
, Grant (AlliesType Male) 3 AttackUp <| Range 10 20
, To Self Heal <| Range 1100 2000
]
}
, { name = "<NAME>"
, rank = C
, icon = Icon.Heart
, cd = 9
, effect = [ Chances 50 80 <| Debuff (EnemyType Male) 1 Charm Full ]
}
]
, passives = [magicResistance B, riding A]
, phantasm = { name = "<NAME>"
, rank = BPlus
, card = Buster
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemy Damage <| Range 800 1200 ]
, over = [ To Enemy (SpecialDamage <| VsTrait Male) <| Range 150 200
, Debuff Enemy 3 MentalVuln <| Range 20 60
]
, first = False
}
, gen = { starWeight = 208, starRate = 9, npAtk = 0.86, npDef = 3 }
, hits = { quick = 3, arts = 2, buster = 1, ex = 7 }
, gender = Female
, traits = [Humanoid, Riding, EnumaElish, King]
, death = 40
, align = [Chaotic, Evil]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (SerpentJewel, 6)]
[(Monument Rider, 5), (PhoenixFeather, 8), (MeteorHorseshoe, 5)]
[(Monument Rider, 12), (MeteorHorseshoe, 10), (WarhorsesYoungHorn, 8)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (PhoenixFeather, 4)]
[(SecretGemOf Rider, 5), (PhoenixFeather, 8)]
[(SecretGemOf Rider, 12), (SerpentJewel, 4)]
[(SerpentJewel, 8), (GhostLantern, 6)]
[(GhostLantern, 18), (HeartOfTheForeignGod, 10)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 108
, rarity = 5
, class = Rider
, attr = Human
, deck = Deck Quick Arts Arts Buster Buster
, curve = 10
, stats = { base = { atk = 1786, hp = 1938 }
, max = { atk = 11560, hp = 13219 }
, grail = { atk = 12654, hp = 14482 }
}
, skills = [ { name = "<NAME>"
, rank = A
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 10 20 ]
}
, { name = "<NAME>"
, rank = B
, icon = Icon.BeamUp
, cd = 7
, effect = [ Grant Party 1 NPUp <| Range 9 18 ]
}
, { name = "<NAME>"
, rank = EX
, icon = Icon.BusterUp
, cd = 8
, effect = [ Grant Self 1 (CardUp Buster) <| Range 30 50
, Grant Self 1 StarUp <| Flat 50
]
}
]
, passives = [magicResistance D, riding APlus, divinity C]
, phantasm = { name = "<NAME>"
, rank = EX
, card = Buster
, kind = "Anti-Ar<NAME>"
, hits = 8
, effect = [ To Enemies Damage <| Range 400 600 ]
, over = [ Debuff Enemies 3 DefenseDown <| Range 10 30
, Debuff Enemies 3 CritChance <| Range 10 50
]
, first = False
}
, gen = { starWeight = 205, starRate = 8.8, npAtk = 0.66, npDef = 3 }
, hits = { quick = 3, arts = 2, buster = 1, ex = 6 }
, gender = Male
, traits = [Humanoid, LovedOne, Divine, GreekMythMale, King, Riding, EnumaElish]
, death = 40
, align = [Neutral, Good]
, limited = True
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (MeteorHorseshoe, 8)]
[(Monument Rider, 5), (ProofOfHero, 29), (OctupletCrystals, 5)]
[(Monument Rider, 12), (OctupletCrystals, 10), (WarhorsesYoungHorn, 8)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (ProofOfHero, 15)]
[(SecretGemOf Rider, 5), (ProofOfHero, 29)]
[(SecretGemOf Rider, 12), (MeteorHorseshoe, 5)]
[(MeteorHorseshoe, 10), (SeedOfYggdrasil, 8)]
[(SeedOfYggdrasil, 22), (PhoenixFeather, 20)]
}
, { name = "<NAME> (<NAME>)"
, spoiler = Nothing
, id = 115
, rarity = 4
, class = Rider
, attr = Earth
, deck = Deck Quick Quick Arts Buster Buster
, curve = 9
, stats = { base = { atk = 1636, hp = 1728 }
, max = { atk = 9819, hp = 10800 }
, grail = { atk = 11889, hp = 13095 }
}
, skills = [ { name = "Long-Distance Dash"
, rank = A
, icon = Icon.QuickUp
, cd = 7
, effect = [ Grant Self 3 (CardUp Quick) <| Range 20 30
, Grant Self 3 StarUp <| Range 30 50
]
}
, { name = "Animal Communication"
, rank = C
, icon = Icon.Noble
, cd = 8
, effect = [ To Self GaugeUp <| Range 30 50 ]
}
, { name = "Natural Body"
, rank = A
, icon = Icon.HoodUp
, cd = 7
, effect = [ Grant Self 3 OffensiveResist <| Range 60 120
, To Self Heal <| Range 1000 3000
]
}
]
, passives = [divinity C]
, phantasm = { name = "<NAME>"
, rank = B
, card = Quick
, kind = "Anti-Army"
, hits = 4
, effect = [ To Enemy Damage <| Range 1200 2000 ]
, over = [ Grant Self 1 (CardUp Quick) <| Range 10 90 ]
, first = False
}
, gen = { starWeight = 198, starRate = 9, npAtk = 1.15, npDef = 3 }
, hits = { quick = 4, arts = 2, buster = 1, ex = 5 }
, gender = Male
, traits = [Humanoid, LovedOne, Divine, EnumaElish]
, death = 40
, align = [Lawful, Good]
, limited = True
, free = True
, ascendUp = Welfare "Golden Bear Lighter"
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (OctupletCrystals, 4)]
[(SecretGemOf Rider, 4), (OctupletCrystals, 8)]
[(SecretGemOf Rider, 10), (SeedOfYggdrasil, 5)]
[(SeedOfYggdrasil, 10), (MeteorHorseshoe, 5)]
[(MeteorHorseshoe, 15), (WarhorsesYoungHorn, 12)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 118
, rarity = 5
, class = Rider
, attr = Sky
, deck = Deck Quick Arts Arts Buster Buster
, curve = 5
, stats = { base = { atk = 1850, hp = 1881 }
, max = { atk = 11971, hp = 12830 }
, grail = { atk = 13104, hp = 14056 }
}
, skills = [ { name = "Charisma"
, rank = B
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 9 18 ]
}
, { name = "Imperial Privilege"
, rank = A
, icon = Icon.Heal
, cd = 7
, effect = [ To Self Heal <| Range 1000 3000
, Chance 60 << Grant Self 3 AttackUp <| Range 20 40
, Chance 60 << Grant Self 3 DefenseUp <| Range 20 40
]
}
, { name = "<NAME>"
, rank = A
, icon = Icon.Noble
, cd = 8
, effect = [ To Party GaugeUp <| Flat 20
, Grant Party 1 BuffUp <| Range 20 40
]
}
]
, passives = [magicResistance B, riding APlus, divinity B]
, phantasm = { name = "<NAME>"
, rank = EX
, card = Buster
, kind = "Anti-Fortress"
, hits = 5
, effect = [ To Enemy Damage <| Range 600 1000
, Debuff Enemy 1 SealNP Full
]
, over = [ Debuff Enemy 3 DefenseDown <| Range 20 60 ]
, first = False
}
, gen = { starWeight = 205, starRate = 9, npAtk = 0.59, npDef = 3 }
, hits = { quick = 5, arts = 3, buster = 1, ex = 5 }
, gender = Male
, traits = [Humanoid, LovedOne, Divine, Riding, EnumaElish, King]
, death = 30
, align = [Chaotic, Balanced]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (FoolsChain, 22)]
[(Monument Rider, 5), (HeartOfTheForeignGod, 2), (SerpentJewel, 8)]
[(Monument Rider, 12), (HeartOfTheForeignGod, 4), (ScarabOfWisdom, 5)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (SerpentJewel, 4)]
[(SecretGemOf Rider, 5), (SerpentJewel, 8)]
[(SecretGemOf Rider, 12), (FoolsChain, 15)]
[(FoolsChain, 29), (ForbiddenPage, 6)]
[(ForbiddenPage, 18), (LampOfEvilSealing, 15)]
}
, { name = "<NAME> (R<NAME>)"
, spoiler = Nothing
, id = 132
, rarity = 4
, class = Rider
, attr = Earth
, deck = Deck Quick Quick Arts Arts Buster
, curve = 24
, stats = { base = { atk = 1535, hp = 1824 }
, max = { atk = 9212, hp = 11400 }
, grail = { atk = 11154, hp = 13822 }
}
, skills = [ { name = "<NAME>"
, rank = A
, icon = Icon.ArtsUp
, cd = 7
, effect = [ Grant Self 3 (CardUp Arts) <| Range 20 30 ]
}
, { name = "<NAME>"
, rank = APlus
, icon = Icon.Dodge
, cd = 9
, effect = [ Grant Self 1 Evasion Full
, Grant Self 1 StarUp <| Range 30 50
]
}
, { name = "<NAME>"
, rank = B
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Self 3 Guts <| Flat 1000
, To Self GaugeUp <| Range 20 30
]
}
]
, passives = [magicResistance B, surfing A]
, phantasm = { name = "<NAME> Riding"
, rank = A
, card = Arts
, kind = "Anti-Wave"
, hits = 5
, effect = [ To Enemies Damage <| Range 450 750 ]
, over = [ Chances 50 90 << To Enemies GaugeDown <| Flat 1 ]
, first = False
}
, gen = { starWeight = 204, starRate = 9.2, npAtk = 0.71, npDef = 3 }
, hits = { quick = 3, arts = 2, buster = 1, ex = 4 }
, gender = Female
, traits = [Humanoid, Dragon, Saberface, EnumaElish]
, death = 35
, align = [Chaotic, Good]
, limited = True
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (ShellOfReminiscence, 6)]
[(Monument Rider, 4), (GreatKnightMedal, 16), (DragonFang, 10)]
[(Monument Rider, 10), (DragonFang, 20), (DragonsReverseScale, 4)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (GreatKnightMedal, 8)]
[(SecretGemOf Rider, 4), (GreatKnightMedal, 16)]
[(SecretGemOf Rider, 10), (ShellOfReminiscence, 4)]
[(ShellOfReminiscence, 8), (HomunculusBaby, 5)]
[(HomunculusBaby, 15), (TearstoneOfBlood, 12)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 144
, rarity = 5
, class = Rider
, stats = { base = { atk = 1854, hp = 1900 }
, max = { atk = 12001, hp = 12960 }
, grail = { atk = 13137, hp = 14198 }
}
, gen = { starWeight = 205, starRate = 9, npAtk = 0.9, npDef = 3 }
, death = 25
, curve = 5
, attr = Sky
, align = [Lawful, Good]
, gender = Female
, traits = [Humanoid, Divine, Riding, EnumaElish, King]
, deck = Deck Quick Arts Arts Buster Buster
, hits = { quick = 3, arts = 2, buster = 3, ex = 5 }
, skills = [ { name = "<NAME>"
, rank = APlus
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 10.5 21 ]
}
, { name = "<NAME>dom of the Benevolent God"
, rank = APlus
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Ally 3 Guts <| Flat 1000
, Grant Ally 3 (CardUp Buster) <| Range 20 30
]
}
, { name = "<NAME>"
, rank = EX
, icon = Icon.StarUp
, cd = 8
, effect = [ Grant Self 1 GatherUp <| Range 300 600
, Grant Self 1 CritUp <| Range 30 50
, To Self GaugeUp <| Range 20 30
]
}
]
, passives = [magicResistance A, riding EX, coreOfGoddess EX]
, phantasm = { name = "<NAME>"
, rank = A
, card = Buster
, kind = "Anti-Army/Anti-Fortress"
, hits = 1
, effect = [ To Enemy Damage <| Range 600 1000
, Debuff Enemy 1 SealNP Full
]
, over = [ Debuff Enemy 5 Burn <| Range 1000 3000 ]
, first = False
}
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (DragonFang, 18)]
[(Monument Rider, 5), (SerpentJewel, 8), (DragonsReverseScale, 2)]
[(Monument Rider, 12), (DragonsReverseScale, 4), (PhoenixFeather, 10)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (SerpentJewel, 4)]
[(SecretGemOf Rider, 5), (SerpentJewel, 8)]
[(SecretGemOf Rider, 12), (DragonFang, 12)]
[(DragonFang, 24), (FoolsChain, 18)]
[(FoolsChain, 54), (CursedBeastGallstone, 10)]
}
, { name = "<NAME>"
, spoiler = Just "Resistance"
, id = 172
, rarity = 3
, class = Rider
, stats = { base = { atk = 1216, hp = 1728 }
, max = { atk = 6552, hp = 9600 }
, grail = { atk = 8867, hp = 13016 }
}
, gen = { starWeight = 208, starRate = 8.9, npAtk = 0.55, npDef = 3 }
, death = 50
, curve = 13
, attr = Human
, align = [Neutral, Evil]
, gender = Male
, traits = [Humanoid, EnumaElish]
, deck = Deck Quick Arts Arts Buster Buster
, hits = { quick = 3, arts = 3, buster = 4, ex = 5 }
, skills = [ { name = "<NAME>"
, rank = B
, icon = Icon.BeamUp
, cd = 7
, effect = [ Grant Party 1 NPUp <| Range 7 14
, Grant Party 1 AttackUp <| Range 7 14
]
}
, { name = "<NAME>"
, rank = C
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Self 3 Guts <| Flat 1
, To Self GaugeUp <| Range 10 30
]
}
, { name = "<NAME>"
, rank = EX
, icon = Icon.BusterUp
, cd = 8
, effect = [ Grant Self 3 (CardUp Buster) <| Range 10 20
, To Party GainStars <| Range 5 15
]
}
]
, passives = [magicResistance D, riding B]
, phantasm = { name = "<NAME>・<NAME>"
, rank = A
, card = Buster
, kind = "Anti-Army"
, hits = 4
, effect = [ To Enemies Damage <| Range 300 500 ]
, over = [ Debuff Enemies 3 CritChance <| Range 20 60 ]
, first = False
}
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (FoolsChain, 15)]
[(Monument Rider, 4), (MysteriousDivineWine, 3), (DeadlyPoisonousNeedle, 8)]
[(Monument Rider, 8), (DeadlyPoisonousNeedle, 16), (GhostLantern, 8)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (MysteriousDivineWine, 2)]
[(SecretGemOf Rider, 4), (MysteriousDivineWine, 3)]
[(SecretGemOf Rider, 8), (FoolsChain, 10)]
[(FoolsChain, 20), (MysticSpinalFluid, 12)]
[(MysticSpinalFluid, 36), (CursedBeastGallstone, 7)]
}
, { name = "<NAME> (Rider Alter)"
, spoiler = Nothing
, id = 179
, rarity = 5
, class = Rider
, stats = { base = { atk = 1665, hp = 2090 }
, max = { atk = 10776, hp = 14256 }
, grail = { atk = 11796, hp = 15618 }
}
, gen = { starWeight = 200, starRate = 9, npAtk = 0.59, npDef = 3 }
, death = 30
, curve = 5
, attr = Human
, align = [Lawful, Evil]
, gender = Female
, traits = [Humanoid, Arthur, Dragon, Riding, Saberface, EnumaElish, King]
, deck = Deck Quick Quick Arts Arts Buster
, hits = { quick = 3, arts = 3, buster = 2, ex = 5 }
, skills = [ { name = "Summer Sweeper!"
, rank = A
, icon = Icon.SwordUp
, cd = 8
, effect = [ Grant Self 3 AttackUp <| Range 20 30
, Grant Party 3 (CardUp Quick) <| Range 10 20
]
}
, { name = "<NAME>"
, rank = A
, icon = Icon.MagicLight
, cd = 8
, effect = [ To Ally ReduceCooldowns <| Flat 1
, Grant Self 3 StarUp <| Range 30 50
, To Ally DemeritHealth <| Flat 1000
]
}
, { name = "<NAME>"
, rank = C
, icon = Icon.QuickUp
, cd = 5
, effect = [ Times 1 << Grant Self 3 (CardUp Quick) <| Range 20 30 ]
}
]
, passives = [magicResistance B, riding B, independentAction EX]
, phantasm = { name = "<NAME>"
, rank = C
, card = Quick
, kind = "Anti-Army"
, hits = 6
, effect = [ To Enemy Damage <| Range 1200 2000
, To Self GaugeUp <| Flat 10
]
, over = [ Debuff Enemy 3 CritChance <| Range 30 70 ]
, first = False
}
, limited = True
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (GreatKnightMedal, 15)]
[(Monument Rider, 5), (DragonsReverseScale, 4), (ShellOfReminiscence, 5)]
[(Monument Rider, 12), (ShellOfReminiscence, 10), (CursedBeastGallstone, 5)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (DragonsReverseScale, 2)]
[(SecretGemOf Rider, 5), (DragonsReverseScale, 4)]
[(SecretGemOf Rider, 12), (GreatKnightMedal, 10)]
[(GreatKnightMedal, 20), (DragonFang, 15)]
[(DragonFang, 44), (MeteorHorseshoe, 24)]
}
, { name = "<NAME> (<NAME>)"
, spoiler = Nothing
, id = 182
, rarity = 4
, class = Rider
, stats = { base = { atk = 1600, hp = 1710 }
, max = { atk = 9603, hp = 10692 }
, grail = { atk = 11627, hp = 12964 }
}
, gen = { starWeight = 200, starRate = 9, npAtk = 0.68, npDef = 3 }
, death = 35
, curve = 9
, attr = Sky
, align = [Lawful, Good]
, gender = Female
, traits = [Humanoid, Divine, Riding, EnumaElish]
, deck = Deck Quick Quick Arts Arts Buster
, hits = { quick = 2, arts = 3, buster = 5, ex = 3 }
, skills = [ { name = "<NAME>ining Water Robe"
, rank = A
, icon = Icon.QuickBusterUp
, cd = 7
, effect = [ Grant Party 3 (CardUp Quick) <| Range 10 20
, Grant Party 3 (CardUp Buster) <| Range 10 20
, Grant Party 3 NPGen <| Range 10 20
]
}
, { name = "<NAME>"
, rank = B
, icon = Icon.Dodge
, cd = 6
, effect = [ Grant Self 1 CritUp <| Range 30 50
, Times 1 <| Grant Self 1 Evasion Full
]
}
, { name = "<NAME>!"
, rank = A
, icon = Icon.Shield
, cd = 8
, effect = [ Grant Self 1 NPGen <| Range 30 50
, Grant Self 1 CritUp <| Range 30 50
, Grant Self 1 HealingReceived <| Range 30 50
, Grant Self 1 DebuffResist <| Range 30 50
, Grant Self 1 Invincibility Full
, After 1 <| Debuff Self 1 Stun Full
]
}
]
, passives = [riding EX, independentAction A, coreOfGoddess B]
, phantasm = { name = "<NAME>"
, rank = EX
, card = Quick
, kind = "Anti-Personnel"
, hits = 4
, effect = [ To Enemies Damage <| Range 600 1000 ]
, over = [ Grant Self 1 (CardUp Quick) <| Range 20 60 ]
, first = True
}
, limited = True
, free = True
, ascendUp = Welfare "Golden Reed"
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (ShellOfReminiscence, 4)]
[(SecretGemOf Rider, 4), (ShellOfReminiscence, 8)]
[(SecretGemOf Rider, 10), (PrimordialLanugo, 3)]
[(PrimordialLanugo, 5), (ScarabOfWisdom, 2)]
[(ScarabOfWisdom, 6), (MysteriousDivineWine, 8)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 205
, rarity = 5
, class = Rider
, stats = { base = { atk = 1795, hp = 1948 }
, max = { atk = 11619, hp = 13284 }
, grail = { atk = 12719, hp = 14553 }
}
, gen = { starWeight = 200, starRate = 8.9, npAtk = 0.62, npDef = 3 }
, death = 40
, curve = 10
, attr = Human
, align = [Lawful, Evil]
, gender = Male
, traits = [Humanoid, WildBeast, King, Riding, EnumaElish]
, deck = Deck Quick Arts Arts Buster Buster
, hits = { quick = 4, arts = 3, buster = 2, ex = 4 }
, skills = [ { name = "Mental Schism"
, rank = A
, icon = Icon.NobleUp
, cd = 7
, effect = [ Grant Self 3 NPGen <| Range 30 50
, To Self RemoveDebuffs Full
]
}
, { name = "Innocent Monster (Foreign)"
, rank = A
, icon = Icon.StarTurn
, cd = 7
, effect = [ Grant Self 3 StarsPerTurn <| Range 5 10
, Grant Self 3 (CardUp Buster) <| Range 20 40
]
}
, { name = "<NAME>"
, rank = A
, icon = Icon.Shield
, cd = 8
, effect = [ Grant Self 1 Invincibility Full
, Debuff Enemies 3 AttackDown <| Range 10 20
, To Enemies RemoveBuffs Full
]
}
]
, passives = [magicResistance D, riding EX]
, phantasm = { name = "<NAME>"
, rank = B
, card = Buster
, kind = "Anti-Personnel"
, hits = 5
, effect = [ To Enemies Damage <| Range 300 500
, Debuff Enemies 3 (CardVuln Buster) <| Flat 20
]
, over = [ Grant Self 1 NPUp <| Range 30 70 ]
, first = True
}
, limited = True
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (EvilBone, 22)]
[(Monument Rider, 5), (MeteorHorseshoe, 10), (PrimordialLanugo, 3)]
[(Monument Rider, 12), (PrimordialLanugo, 6), (CursedBeastGallstone, 5)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 5), (MeteorHorseshoe, 5)]
[(SecretGemOf Rider, 5), (MeteorHorseshoe, 10)]
[(SecretGemOf Rider, 12), (EvilBone, 15)]
[(EvilBone, 29), (DeadlyPoisonousNeedle, 15)]
[(DeadlyPoisonousNeedle, 44), (EternalIce, 24)]
}
, { name = "<NAME>"
, spoiler = Nothing
, id = 206
, rarity = 5
, class = Rider
, stats = { base = { atk = 1836, hp = 1938 }
, max = { atk = 11883, hp = 13219 }
, grail = { atk = 13008, hp = 14482 }
}
, gen = { starWeight = 196, starRate = 9.1, npAtk = 0.57, npDef = 3 }
, death = 40
, curve = 10
, attr = Earth
, align = [Lawful, Balanced]
, gender = Male
, traits = [Humanoid, Divine, Riding, LovedOne, GreekMythMale, EnumaElish]
, deck = Deck Quick Quick Arts Arts Buster
, hits = { quick = 4, arts = 3, buster = 2, ex = 4 }
, skills = [ { name = "<NAME>"
, rank = APlus
, icon = Icon.QuickUp
, cd = 7
, effect = [ Grant Self 3 (CardUp Quick) <| Range 20 30
, Grant Self 3 CritUp <| Range 20 30
]
}
, { name = "<NAME>"
, rank = B
, icon = Icon.Shield
, cd = 7
, effect = [ Times 2 <| Grant Self 5 Invincibility Full
, Grant Self 3 DefenseUp <| Range 10 20
]
}
, { name = "<NAME>"
, rank = BPlus
, icon = Icon.CrosshairUp
, cd = 8
, effect = [ Chance 500 <| Grant Self 1 Taunt Full
, Grant Self 1 NPGen <| Range 20 30
, To Self GaugeUp <| Range 20 30
]
}
]
, passives = [magicResistance C, riding APlus, divinity C]
, phantasm = { name = "<NAME>"
, rank = A
, card = Quick
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemies Damage <| Range 600 1000 ]
, over = [ Grant Self 1 (CardUp Quick) <| Range 20 60 ]
, first = True
}
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (ProofOfHero, 22)]
[(Monument Rider, 5), (EternalGear, 10), (WarhorsesYoungHorn, 3)]
[(Monument Rider, 12), (WarhorsesYoungHorn, 6), (PhoenixFeather, 10)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (EternalGear, 5)]
[(SecretGemOf Rider, 5), (EternalGear, 10)]
[(SecretGemOf Rider, 12), (ProofOfHero, 15)]
[(ProofOfHero, 29), (MeteorHorseshoe, 6)]
[(MeteorHorseshoe, 18), (HeartOfTheForeignGod, 10)]
}
]
| true | module Database.Servant.Rider exposing (riders)
import Model.Attribute exposing (Attribute(..))
import Model.Card exposing (Card(..))
import Model.Class exposing (Class(..))
import Model.Deck exposing (Deck(..))
import Model.Material exposing (Material(..))
import Model.Trait exposing (Trait(..))
import Database.Passives exposing (..)
import Model.Servant exposing (Servant, Ascension(..), Reinforcement(..))
import Model.Skill.Amount exposing (Amount(..))
import Model.Skill.BuffEffect exposing (BuffEffect(..))
import Model.Skill.DebuffEffect exposing (DebuffEffect(..))
import Model.Skill.InstantEffect exposing (InstantEffect(..))
import Model.Skill.Rank exposing (Rank(..))
import Model.Skill.SkillEffect exposing (SkillEffect(..))
import Model.Skill.Special exposing (Special(..))
import Model.Skill.Target exposing (Target(..))
import Model.Icon as Icon
riders : List Servant
riders =
[ { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 23
, rarity = 3
, class = Rider
, attr = Earth
, deck = Deck Quick Quick Arts Arts Buster
, curve = 24
, stats = { base = { atk = 1337, hp = 1608 }
, max = { atk = 7200, hp = 8937 }
, grail = { atk = 9744, hp = 12117 }
}
, skills = [ { name = "Mystic Eyes"
, rank = APlus
, icon = Icon.Stun
, cd = 8
, effect = [ Chances 50 100 <| Debuff Enemy 1 Stun Full ]
}
, { name = "Monstrous Strength"
, rank = B
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Self 2 AttackUp <| Range 10 30 ]
}
, { name = "Blood Fort Andromeda"
, rank = B
, icon = Icon.Noble
, cd = 8
, effect = [ To Self GaugeUp <| Flat 20
, Grant Self 3 NPGen <| Range 20 30
]
}
]
, passives = [magicResistance B, independentAction C, divinity EMinus, riding APlus]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = APlus
, card = Quick
, kind = "Anti-Army"
, hits = 1
, effect = [ To Enemies Damage <| Range 600 1000 ]
, over = [ Grant Party 3 StarUp <| Range 20 60 ]
, first = False
}
, gen = { starWeight = 194, starRate = 9, npAtk = 0.58, npDef = 3 }
, hits = { quick = 2, arts = 3, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, Divine]
, death = 35
, align = [Chaotic, Good]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (SerpentJewel, 4)]
[(Monument Rider, 4), (VoidsDust, 13), (MeteorHorseshoe, 4)]
[(Monument Rider, 8), (MeteorHorseshoe, 7), (PhoenixFeather, 7)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (VoidsDust, 7)]
[(SecretGemOf Rider, 4), (VoidsDust, 13)]
[(SecretGemOf Rider, 8), (SerpentJewel, 3)]
[(SerpentJewel, 6), (HeartOfTheForeignGod, 2)]
[(HeartOfTheForeignGod, 5), (PhoenixFeather, 13)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 24
, rarity = 2
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 2
, stats = { base = { atk = 929, hp = 1731 }
, max = { atk = 5236, hp = 9200 }
, grail = { atk = 7587, hp = 13278 }
}
, skills = [ { name = "PI:NAME:<NAME>END_PI"
, rank = APlus
, icon = Icon.CrosshairUp
, cd = 7
, effect = [ Grant Self 3 Taunt Full
, Grant Self 3 DefenseUp <| Range 20 40
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = BPlus
, icon = Icon.HoodUp
, cd = 7
, effect = [ Grant Self 3 MentalResist <| Range 50 100
, To Self Heal <| Range 750 2000
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = A
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Self 5 Guts <| Range 1000 2500 ]
}
]
, passives = [magicResistance A, riding B]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = B
, card = Arts
, kind = "Anti-Personnel"
, hits = 4
, effect = [ To Enemy (ApplyTrait Dragon) <| Flat 3
, To Enemy Damage <| Range 900 1500
]
, over = [ Grant Self 1 DefenseUp <| Range 20 40 ]
, first = False
}
, gen = { starWeight = 205, starRate = 8.9, npAtk = 0.85, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Male
, traits = [Humanoid, Riding, LovedOne, EnumaElish]
, death = 45
, align = [Lawful, Good]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 3)]
[(Piece Rider, 6), (ProofOfHero, 11)]
[(Monument Rider, 3), (PhoenixFeather, 4), (ForbiddenPage, 3)]
[(Monument Rider, 6), (ForbiddenPage, 5), (MeteorHorseshoe, 6)]
, skillUp = Reinforcement
[(GemOf Rider, 3)]
[(GemOf Rider, 6)]
[(MagicGemOf Rider, 3)]
[(MagicGemOf Rider, 6), (PhoenixFeather, 2)]
[(SecretGemOf Rider, 3), (PhoenixFeather, 4)]
[(SecretGemOf Rider, 6), (ProofOfHero, 8)]
[(ProofOfHero, 15), (EternalGear, 3)]
[(EternalGear, 9), (MeteorHorseshoe, 12)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 25
, rarity = 2
, class = Rider
, attr = Human
, deck = Deck Quick Arts Arts Buster Buster
, curve = 12
, stats = { base = { atk = 1097, hp = 1488 }
, max = { atk = 6188, hp = 7907 }
, grail = { atk = 8967, hp = 11411 }
}
, skills = [ { name = "PI:NAME:<NAME>END_PI"
, rank = A
, icon = Icon.BeamUp
, cd = 7
, effect = [ Grant Party 1 NPUp <| Range 8 16
, Grant Party 1 AttackUp <| Range 8 16
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = B
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Self 3 AttackUp <| Range 9 27
, Times 1 << Grant Self 0 Guts <| Flat 1
, Debuff Self 3 DebuffVuln <| Flat 50
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = C
, icon = Icon.Heal
, cd = 8
, effect = [ To Party Heal <| Range 1000 2000
, To (AlliesType Female) Heal <| Range 1000 2000
, To (AlliesType Nonbinary) Heal <| Range 1000 2000
]
}
]
, passives = [magicResistance E]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = CPlusPlus
, card = Buster
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemies Damage <| Range 300 500
, To Party GainStars <| Flat 5
]
, over = [ Chances 30 70 << To Enemies GaugeDown <| Flat 1 ]
, first = False
}
, gen = { starWeight = 198, starRate = 8.8, npAtk = 0.56, npDef = 3 }
, hits = { quick = 2, arts = 3, buster = 1, ex = 3 }
, gender = Male
, traits = [Humanoid, EnumaElish]
, death = 45
, align = [Chaotic, Evil]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 3)]
[(Piece Rider, 6), (EvilBone, 11)]
[(Monument Rider, 3), (OctupletCrystals, 5), (ForbiddenPage, 3)]
[(Monument Rider, 6), (ForbiddenPage, 5), (GhostLantern, 6)]
, skillUp = Reinforcement
[(GemOf Rider, 3)]
[(GemOf Rider, 6)]
[(MagicGemOf Rider, 3)]
[(MagicGemOf Rider, 6), (OctupletCrystals, 3)]
[(SecretGemOf Rider, 3), (OctupletCrystals, 5)]
[(SecretGemOf Rider, 6), (EvilBone, 8)]
[(EvilBone, 15), (HomunculusBaby, 3)]
[(HomunculusBaby, 9), (GhostLantern, 12)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 26
, rarity = 3
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 3
, stats = { base = { atk = 1168, hp = 1823 }
, max = { atk = 6289, hp = 10130 }
, grail = { atk = 8511, hp = 13735 }
}
, skills = [ { name = "PI:NAME:<NAME>END_PI"
, rank = B
, icon = Icon.DamageUp
, cd = 7
, effect = [ Grant Self 3 (Special AttackUp <| VsTrait Roman) <| Range 40 60 ]
}
, { name = "Battle Continuation"
, rank = A
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Self 5 Guts <| Range 1000 2500 ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = A
, icon = Icon.ArtsUp
, cd = 7
, effect = [ Grant Party 3 (CardUp Arts) <| Range 10 20 ]
}
]
, passives = [magicResistance D, riding A]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = BPlusPlus
, card = Arts
, kind = "Anti-Army"
, hits = 0
, effect = [ Grant Party 3 DefenseUp <| Range 10 20 ]
, over = [ Grant Party 1 DefenseUp <| Range 20 40
, Grant Party 3 AttackUp <| Range 20 40
]
, first = False
}
, gen = { starWeight = 196, starRate = 8.9, npAtk = 0.85, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, EnumaElish, King]
, death = 45
, align = [Neutral, Good]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (PhoenixFeather, 4)]
[(Monument Rider, 4), (EvilBone, 20), (MeteorHorseshoe, 4)]
[(Monument Rider, 8), (MeteorHorseshoe, 7), (VoidsDust, 16)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (EvilBone, 10)]
[(SecretGemOf Rider, 4), (EvilBone, 20)]
[(SecretGemOf Rider, 8), (PhoenixFeather, 3)]
[(PhoenixFeather, 6), (SerpentJewel, 4)]
[(SerpentJewel, 10), (VoidsDust, 32)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 27
, rarity = 3
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 8
, stats = { base = { atk = 1314, hp = 1625 }
, max = { atk = 7076, hp = 9028 }
, grail = { atk = 9576, hp = 12240 }
}
, skills = [ { name = "PI:NAME:<NAME>END_PI"
, rank = A
, icon = Icon.NobleUp
, cd = 7
, effect = [ Grant Party 3 NPGen <| Range 10 20 ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = CPlus
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 8.5 17 ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = B
, icon = Icon.Dodge
, cd = 8
, effect = [ Times 1 <| Grant Self 1 Evasion Full
, Grant Self 1 StarUp <| Range 50 100
]
}
]
, passives = [magicResistance C, riding APlus]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = C
, card = Quick
, kind = "Anti-Personnel"
, hits = 1
, effect = [ To Enemy Damage <| Range 1600 2400 ]
, over = [ Grant Self 3 StarUp <| Range 50 90 ]
, first = False
}
, gen = { starWeight = 204, starRate = 9.1, npAtk = 0.87, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, LovedOne, EnumaElish]
, death = 35
, align = [Chaotic, Balanced]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (ProofOfHero, 15)]
[(Monument Rider, 4), (MeteorHorseshoe, 7), (GhostLantern, 4)]
[(Monument Rider, 8), (GhostLantern, 7), (OctupletCrystals, 8)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (MeteorHorseshoe, 4)]
[(SecretGemOf Rider, 4), (MeteorHorseshoe, 7)]
[(SecretGemOf Rider, 8), (ProofOfHero, 10)]
[(ProofOfHero, 20), (EternalGear, 4)]
[(EternalGear, 12), (OctupletCrystals, 16)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 28
, rarity = 3
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 3
, stats = { base = { atk = 1366, hp = 1979 }
, max = { atk = 7356, hp = 8640 }
, grail = { atk = 9955, hp = 11714 }
}
, skills = [ { name = "PI:NAME:<NAME>END_PI"
, rank = C
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 8 16 ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = B
, icon = Icon.Heart
, cd = 9
, effect = [ Chances 50 80 <| Debuff (EnemyType Humanoid) 1 Charm Full ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = A
, icon = Icon.QuickUp
, cd = 7
, effect = [ Grant Party 3 (CardUp Quick) <| Range 10 20 ]
}
]
, passives = [magicResistance D, divinity E, riding APlus]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = BPlusPlus
, card = Quick
, kind = "Anti-Army"
, hits = 1
, effect = [ To Enemies Damage <| Range 800 1200 ]
, over = [ To Party GainStars <| Range 15 35 ]
, first = False
}
, gen = { starWeight = 205, starRate = 9, npAtk = 0.86, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Male
, traits = [Humanoid, Riding, Divine, EnumaElish, GreekMythMale, King]
, death = 40
, align = [Neutral, Good]
, limited = False
, free = True
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (MeteorHorseshoe, 5)]
[(Monument Rider, 4), (PhoenixFeather, 3), (OctupletCrystals, 7)]
[(Monument Rider, 8), (PhoenixFeather, 6), (ProofOfHero, 24)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (OctupletCrystals, 4)]
[(SecretGemOf Rider, 4), (OctupletCrystals, 7)]
[(SecretGemOf Rider, 8), (MeteorHorseshoe, 4)]
[(ClawOfChaos, 3), (MeteorHorseshoe, 7)]
[(ClawOfChaos, 8), (ProofOfHero, 48)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 29
, rarity = 4
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 9
, stats = { base = { atk = 1382, hp = 1975 }
, max = { atk = 8293, hp = 12348 }
, grail = { atk = 10041, hp = 14972 }
}
, skills = [ { name = "PI:NAME:<NAME>END_PI"
, rank = C
, icon = Icon.Heart
, cd = 9
, effect = [ Chances 50 80 <| Debuff (EnemyType Male) 1 Charm Full ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = A
, icon = Icon.Shield
, cd = 8
, effect = [ Times 3 <| Grant Self 0 Invincibility Full
, Grant Self 5 HealPerTurn <| Range 200 600
]
}
, { name = "God's Grace"
, rank = B
, icon = Icon.StaffUp
, cd = 7
, effect = [ Grant Self 3 MentalSuccess <| Range 10 30
, To Self Heal <| Range 1000 2500
]
}
]
, passives = [magicResistance C, riding APlus]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = APlus
, card = Quick
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemies Damage <| Range 800 1200
, To Party RemoveDebuffs Full
, Grant Party 3 CritUp <| Flat 20
]
, over = [ To Party Heal <| Range 1000 3000 ]
, first = False
}
, gen = { starWeight = 201, starRate = 9, npAtk = 1, npDef = 3 }
, hits = { quick = 2, arts = 1, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, EnumaElish, King]
, death = 35
, align = [Lawful, Good]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (PhoenixFeather, 5)]
[(Monument Rider, 4), (MeteorHorseshoe, 4), (SerpentJewel, 7)]
[(Monument Rider, 10), (MeteorHorseshoe, 8), (EternalGear, 10)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (SerpentJewel, 4)]
[(SecretGemOf Rider, 4), (SerpentJewel, 7)]
[(SecretGemOf Rider, 10), (PhoenixFeather, 4)]
[(PhoenixFeather, 7), (HeartOfTheForeignGod, 2)]
[(EternalGear, 20), (HeartOfTheForeignGod, 6)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 30
, rarity = 4
, class = Rider
, attr = Human
, deck = Deck Quick Arts Arts Arts Buster
, curve = 4
, stats = { base = { atk = 1335, hp = 2090 }
, max = { atk = 8014, hp = 13068 }
, grail = { atk = 9703, hp = 15845 }
}
, skills = [ { name = "Protection of the Faith"
, rank = A
, icon = Icon.HoodUp
, cd = 7
, effect = [ Grant Self 3 DebuffResist <| Range 50 100
, To Self Heal <| Range 1000 2500
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = DPlus
, icon = Icon.Heal
, cd = 8
, effect = [ To Party Heal <| Range 1000 2000
, To Party RemoveDebuffs Full
]
}
, { name = "PI:NAME:<NAME>END_PIath of the Holy Maiden"
, rank = C
, icon = Icon.ShieldDown
, cd = 7
, effect = [ Debuff Enemy 3 DefenseDown <| Range 10 30
, To Enemy RemoveBuffs Full
]
}
]
, passives = [magicResistance A, riding APlusPlus, divinity C]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = EX
, card = Buster
, kind = "Anti-Army"
, hits = 1
, effect = [ Grant Self 1 (CardUp Buster) <| Flat 20
, To Enemies Damage <| Range 400 600 ]
, over = [ Debuff Enemies 3 DefenseDown <| Range 20 40 ]
, first = False
}
, gen = { starWeight = 205, starRate = 9, npAtk = 1.58, npDef = 3 }
, hits = { quick = 2, arts = 1, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Riding, Divine, EnumaElish]
, death = 30
, align = [Lawful, Good]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (DragonFang, 15)]
[(Monument Rider, 4), (ClawOfChaos, 3), (SeedOfYggdrasil, 10)]
[(Monument Rider, 10), (ClawOfChaos, 5), (DragonsReverseScale, 4)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (SeedOfYggdrasil, 5)]
[(SecretGemOf Rider, 4), (SeedOfYggdrasil, 10)]
[(SecretGemOf Rider, 10), (DragonFang, 10)]
[(PhoenixFeather, 4), (DragonFang, 20)]
[(PhoenixFeather, 12), (DragonsReverseScale, 8)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 65
, rarity = 5
, class = Rider
, attr = Star
, deck = Deck Quick Arts Arts Buster Buster
, curve = 10
, stats = { base = { atk = 1750, hp = 1881 }
, max = { atk = 11326, hp = 12830 }
, grail = { atk = 12398, hp = 14056 }
}
, skills = [ { name = "PI:NAME:<NAME>END_PI"
, rank = APlus
, icon = Icon.BeamUp
, cd = 7
, effect = [ Grant Party 1 NPUp <| Range 8.5 17
, Grant Party 1 AttackUp <| Range 8.5 17
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = B
, icon = Icon.NobleUp
, cd = 8
, effect = [ Grant Self 3 NPGen <| Range 18 45 ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = EX
, icon = Icon.Noble
, cd = 8
, effect = [ To Self GaugeUp <| Range 30 50
, Grant Self 3 IgnoreInvinc Full
, To Party GainStars <| Flat 10
]
}
]
, passives = [magicResistance D, riding B]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = APlus
, card = Buster
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemies Damage <| Range 400 600 ]
, over = [ To Party GainStars <| Range 20 40 ]
, first = False
}
, gen = { starWeight = 208, starRate = 9, npAtk = 0.42, npDef = 3 }
, hits = { quick = 6, arts = 4, buster = 2, ex = 4 }
, gender = Female
, traits = [Humanoid, Riding]
, death = 50
, align = [Chaotic, Evil]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (EvilBone, 22)]
[(Monument Rider, 5), (DragonsReverseScale, 2), (DragonFang, 24)]
[( Monument Rider, 12), (DragonsReverseScale, 4), (HeartOfTheForeignGod, 5)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (DragonFang, 12)]
[(SecretGemOf Rider, 5), (DragonFang, 24)]
[(SecretGemOf Rider, 12), (EvilBone, 15)]
[(GhostLantern, 6), (EvilBone, 29)]
[(GhostLantern, 18), (HeartOfTheForeignGod, 10)]
}
, { name = "PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 66
, rarity = 4
, class = Rider
, attr = Human
, deck = Deck Quick Quick Arts Arts Buster
, curve = 29
, stats = { base = { atk = 1504, hp = 1805 }
, max = { atk = 9029, hp = 11286 }
, grail = { atk = 10932, hp = 13684 }
}
, skills = [ { name = "Voyage"
, rank = A
, icon = Icon.StarHaloUp
, cd = 8
, effect = [ Grant Self 3 StarUp <| Range 30 50 ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = B
, icon = Icon.ExclamationUp
, cd = 7
, effect = [ Grant Self 1 CritUp <| Range 50 100 ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = C
, icon = Icon.StarUp
, cd = 7
, effect = [ Grant Self 1 GatherUp <| Range 300 600
, Grant Self 1 AttackUp <| Range 20 30
]
}
]
, passives = [magicResistance D]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = CPlusPlus
, card = Quick
, kind = "Anti-Personnel"
, hits = 6
, effect = [ To Enemy Damage <| Range 1600 2400 ]
, over = [ To Enemy LastStand <| Range 1200 2000 ]
, first = False
}
, gen = { starWeight = 200, starRate = 9.1, npAtk = 0.84, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 1 }
, gender = Female
, traits = [Humanoid, EnumaElish]
, death = 50
, align = [Chaotic, Evil, Chaotic, Balanced]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (HomunculusBaby, 6)]
[(Monument Rider, 4), (GhostLantern, 8), (EvilBone, 12)]
[(Monument Rider, 10), (ClawOfChaos, 6), (EvilBone, 24)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (GhostLantern, 4)]
[(SecretGemOf Rider, 4), (GhostLantern, 8)]
[(SecretGemOf Rider, 10), (HomunculusBaby, 4)]
[(VoidsDust, 10), (HomunculusBaby, 8)]
[(VoidsDust, 30), (ClawOfChaos, 12)]
}
, { name = "PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)"
, spoiler = Nothing
, id = 73
, rarity = 4
, class = Rider
, attr = Human
, deck = Deck Quick Arts Arts Buster Buster
, curve = 29
, stats = { base = { atk = 1543, hp = 1805 }
, max = { atk = 9258, hp = 11286 }
, grail = { atk = 11209, hp = 13684 }
}
, skills = [ { name = "PI:NAME:<NAME>END_PI"
, rank = EX
, icon = Icon.Heal
, cd = 7
, effect = [ To Ally Heal <| Range 1500 3500
, Grant Ally 3 StarUp <| Flat 30
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = A
, icon = Icon.Star
, cd = 7
, effect = [ To Party GainStars <| Range 5 15 ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = AMinus
, icon = Icon.BusterUp
, cd = 7
, effect = [ Grant Self 1 (CardUp Buster) <| Range 25 45 ]
}
]
, passives = [magicResistance A, riding A]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = APlusPlus
, card = Buster
, kind = "Anti-Army"
, hits = 3
, effect = [ To Enemies Damage <| Range 450 650 ]
, over = [ To Self GaugeUp <| Range 10 30 ]
, first = False
}
, gen = { starWeight = 204, starRate = 8.9, npAtk = 0.87, npDef = 3 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 3 }
, gender = Female
, traits = [Humanoid, Arthur, Dragon, Riding, Saberface, EnumaElish, King]
, death = 35
, align = [Lawful, Good]
, limited = True
, free = True
, ascendUp = Welfare "Bucket of Chicken"
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (DragonFang, 10)]
[(SecretGemOf Rider, 4), (DragonFang, 20)]
[(SecretGemOf Rider, 10), (MeteorHorseshoe, 4)]
[(MeteorHorseshoe, 8), (DragonsReverseScale, 2)]
[(DragonsReverseScale, 6), (HeartOfTheForeignGod, 8)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 94
, rarity = 4
, class = Rider
, attr = Earth
, deck = Deck Quick Quick Quick Arts Buster
, curve = 24
, stats = { base = { atk = 1489, hp = 1787 }
, max = { atk = 8937, hp = 11172 }
, grail = { atk = 10821, hp = 13546 }
}
, skills = [ { name = "Monstrous Strength"
, rank = CMinus
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Self 1 AttackUp <| Range 8 28 ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = D
, icon = Icon.Stun
, cd = 10
, effect = [ Chances 60 90 <| Debuff Enemy 1 Stun Full ]
}
, { name = "PI:NAME:<NAME>END_PIaporation of Reason"
, rank = DPlus
, icon = Icon.StarTurn
, cd = 10
, effect = [ Chance 65 << Grant Self 3 StarsPerTurn <| Range 5 10
, Chance 65 << Grant Self 3 StarUp <| Range 30 50
, Chance 65 << Grant Self 3 CritUp <| Range 20 40
, To Self GaugeUp <| Range 30 50
]
}
]
, passives = [magicResistance A, riding APlus, independentAction B]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = BPlusPlus
, card = Quick
, kind = "Anti-Army"
, hits = 1
, effect = [ To Enemies DamageThruDef <| Range 800 1200
, Times 3 <| Grant Self 0 Evasion Full
]
, over = [ To Party GainStars <| Range 10 30 ]
, first = False
}
, gen = { starWeight = 205, starRate = 9, npAtk = 0.66, npDef = 1 }
, hits = { quick = 2, arts = 2, buster = 1, ex = 4 }
, gender = Nonbinary
, traits = [Humanoid, Riding, EnumaElish]
, death = 40
, align = [Chaotic, Good]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (MeteorHorseshoe, 6)]
[(Monument Rider, 4), (OctupletCrystals, 8), (PhoenixFeather, 4)]
[(Monument Rider, 10), (ClawOfChaos, 6), (PhoenixFeather, 7)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (OctupletCrystals, 4)]
[(SecretGemOf Rider, 4), (OctupletCrystals, 8)]
[(SecretGemOf Rider, 10), (MeteorHorseshoe, 4)]
[(ForbiddenPage, 5), (MeteorHorseshoe, 8)]
[(ForbiddenPage, 15), (SeedOfYggdrasil, 24)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 99
, rarity = 5
, class = Rider
, attr = Earth
, deck = Deck Quick Arts Arts Buster Buster
, curve = 5
, stats = { base = { atk = 1591, hp = 2048 }
, max = { atk = 10296, hp = 13968 }
, grail = { atk = 11270, hp = 15303 }
}
, skills = [ { name = "Golden Rule (Body)"
, rank = A
, icon = Icon.HealTurn
, cd = 8
, effect = [ Grant Self 3 DebuffResist Full
, Grant Self 3 HealPerTurn <| Range 500 1000
, Grant Self 3 GaugePerTurn <| Flat 10
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = A
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 10 20
, Grant (AlliesType Male) 3 AttackUp <| Range 10 20
, To Self Heal <| Range 1100 2000
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = C
, icon = Icon.Heart
, cd = 9
, effect = [ Chances 50 80 <| Debuff (EnemyType Male) 1 Charm Full ]
}
]
, passives = [magicResistance B, riding A]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = BPlus
, card = Buster
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemy Damage <| Range 800 1200 ]
, over = [ To Enemy (SpecialDamage <| VsTrait Male) <| Range 150 200
, Debuff Enemy 3 MentalVuln <| Range 20 60
]
, first = False
}
, gen = { starWeight = 208, starRate = 9, npAtk = 0.86, npDef = 3 }
, hits = { quick = 3, arts = 2, buster = 1, ex = 7 }
, gender = Female
, traits = [Humanoid, Riding, EnumaElish, King]
, death = 40
, align = [Chaotic, Evil]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (SerpentJewel, 6)]
[(Monument Rider, 5), (PhoenixFeather, 8), (MeteorHorseshoe, 5)]
[(Monument Rider, 12), (MeteorHorseshoe, 10), (WarhorsesYoungHorn, 8)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (PhoenixFeather, 4)]
[(SecretGemOf Rider, 5), (PhoenixFeather, 8)]
[(SecretGemOf Rider, 12), (SerpentJewel, 4)]
[(SerpentJewel, 8), (GhostLantern, 6)]
[(GhostLantern, 18), (HeartOfTheForeignGod, 10)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 108
, rarity = 5
, class = Rider
, attr = Human
, deck = Deck Quick Arts Arts Buster Buster
, curve = 10
, stats = { base = { atk = 1786, hp = 1938 }
, max = { atk = 11560, hp = 13219 }
, grail = { atk = 12654, hp = 14482 }
}
, skills = [ { name = "PI:NAME:<NAME>END_PI"
, rank = A
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 10 20 ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = B
, icon = Icon.BeamUp
, cd = 7
, effect = [ Grant Party 1 NPUp <| Range 9 18 ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = EX
, icon = Icon.BusterUp
, cd = 8
, effect = [ Grant Self 1 (CardUp Buster) <| Range 30 50
, Grant Self 1 StarUp <| Flat 50
]
}
]
, passives = [magicResistance D, riding APlus, divinity C]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = EX
, card = Buster
, kind = "Anti-ArPI:NAME:<NAME>END_PI"
, hits = 8
, effect = [ To Enemies Damage <| Range 400 600 ]
, over = [ Debuff Enemies 3 DefenseDown <| Range 10 30
, Debuff Enemies 3 CritChance <| Range 10 50
]
, first = False
}
, gen = { starWeight = 205, starRate = 8.8, npAtk = 0.66, npDef = 3 }
, hits = { quick = 3, arts = 2, buster = 1, ex = 6 }
, gender = Male
, traits = [Humanoid, LovedOne, Divine, GreekMythMale, King, Riding, EnumaElish]
, death = 40
, align = [Neutral, Good]
, limited = True
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (MeteorHorseshoe, 8)]
[(Monument Rider, 5), (ProofOfHero, 29), (OctupletCrystals, 5)]
[(Monument Rider, 12), (OctupletCrystals, 10), (WarhorsesYoungHorn, 8)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (ProofOfHero, 15)]
[(SecretGemOf Rider, 5), (ProofOfHero, 29)]
[(SecretGemOf Rider, 12), (MeteorHorseshoe, 5)]
[(MeteorHorseshoe, 10), (SeedOfYggdrasil, 8)]
[(SeedOfYggdrasil, 22), (PhoenixFeather, 20)]
}
, { name = "PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)"
, spoiler = Nothing
, id = 115
, rarity = 4
, class = Rider
, attr = Earth
, deck = Deck Quick Quick Arts Buster Buster
, curve = 9
, stats = { base = { atk = 1636, hp = 1728 }
, max = { atk = 9819, hp = 10800 }
, grail = { atk = 11889, hp = 13095 }
}
, skills = [ { name = "Long-Distance Dash"
, rank = A
, icon = Icon.QuickUp
, cd = 7
, effect = [ Grant Self 3 (CardUp Quick) <| Range 20 30
, Grant Self 3 StarUp <| Range 30 50
]
}
, { name = "Animal Communication"
, rank = C
, icon = Icon.Noble
, cd = 8
, effect = [ To Self GaugeUp <| Range 30 50 ]
}
, { name = "Natural Body"
, rank = A
, icon = Icon.HoodUp
, cd = 7
, effect = [ Grant Self 3 OffensiveResist <| Range 60 120
, To Self Heal <| Range 1000 3000
]
}
]
, passives = [divinity C]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = B
, card = Quick
, kind = "Anti-Army"
, hits = 4
, effect = [ To Enemy Damage <| Range 1200 2000 ]
, over = [ Grant Self 1 (CardUp Quick) <| Range 10 90 ]
, first = False
}
, gen = { starWeight = 198, starRate = 9, npAtk = 1.15, npDef = 3 }
, hits = { quick = 4, arts = 2, buster = 1, ex = 5 }
, gender = Male
, traits = [Humanoid, LovedOne, Divine, EnumaElish]
, death = 40
, align = [Lawful, Good]
, limited = True
, free = True
, ascendUp = Welfare "Golden Bear Lighter"
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (OctupletCrystals, 4)]
[(SecretGemOf Rider, 4), (OctupletCrystals, 8)]
[(SecretGemOf Rider, 10), (SeedOfYggdrasil, 5)]
[(SeedOfYggdrasil, 10), (MeteorHorseshoe, 5)]
[(MeteorHorseshoe, 15), (WarhorsesYoungHorn, 12)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 118
, rarity = 5
, class = Rider
, attr = Sky
, deck = Deck Quick Arts Arts Buster Buster
, curve = 5
, stats = { base = { atk = 1850, hp = 1881 }
, max = { atk = 11971, hp = 12830 }
, grail = { atk = 13104, hp = 14056 }
}
, skills = [ { name = "Charisma"
, rank = B
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 9 18 ]
}
, { name = "Imperial Privilege"
, rank = A
, icon = Icon.Heal
, cd = 7
, effect = [ To Self Heal <| Range 1000 3000
, Chance 60 << Grant Self 3 AttackUp <| Range 20 40
, Chance 60 << Grant Self 3 DefenseUp <| Range 20 40
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = A
, icon = Icon.Noble
, cd = 8
, effect = [ To Party GaugeUp <| Flat 20
, Grant Party 1 BuffUp <| Range 20 40
]
}
]
, passives = [magicResistance B, riding APlus, divinity B]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = EX
, card = Buster
, kind = "Anti-Fortress"
, hits = 5
, effect = [ To Enemy Damage <| Range 600 1000
, Debuff Enemy 1 SealNP Full
]
, over = [ Debuff Enemy 3 DefenseDown <| Range 20 60 ]
, first = False
}
, gen = { starWeight = 205, starRate = 9, npAtk = 0.59, npDef = 3 }
, hits = { quick = 5, arts = 3, buster = 1, ex = 5 }
, gender = Male
, traits = [Humanoid, LovedOne, Divine, Riding, EnumaElish, King]
, death = 30
, align = [Chaotic, Balanced]
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (FoolsChain, 22)]
[(Monument Rider, 5), (HeartOfTheForeignGod, 2), (SerpentJewel, 8)]
[(Monument Rider, 12), (HeartOfTheForeignGod, 4), (ScarabOfWisdom, 5)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (SerpentJewel, 4)]
[(SecretGemOf Rider, 5), (SerpentJewel, 8)]
[(SecretGemOf Rider, 12), (FoolsChain, 15)]
[(FoolsChain, 29), (ForbiddenPage, 6)]
[(ForbiddenPage, 18), (LampOfEvilSealing, 15)]
}
, { name = "PI:NAME:<NAME>END_PI (RPI:NAME:<NAME>END_PI)"
, spoiler = Nothing
, id = 132
, rarity = 4
, class = Rider
, attr = Earth
, deck = Deck Quick Quick Arts Arts Buster
, curve = 24
, stats = { base = { atk = 1535, hp = 1824 }
, max = { atk = 9212, hp = 11400 }
, grail = { atk = 11154, hp = 13822 }
}
, skills = [ { name = "PI:NAME:<NAME>END_PI"
, rank = A
, icon = Icon.ArtsUp
, cd = 7
, effect = [ Grant Self 3 (CardUp Arts) <| Range 20 30 ]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = APlus
, icon = Icon.Dodge
, cd = 9
, effect = [ Grant Self 1 Evasion Full
, Grant Self 1 StarUp <| Range 30 50
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = B
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Self 3 Guts <| Flat 1000
, To Self GaugeUp <| Range 20 30
]
}
]
, passives = [magicResistance B, surfing A]
, phantasm = { name = "PI:NAME:<NAME>END_PI Riding"
, rank = A
, card = Arts
, kind = "Anti-Wave"
, hits = 5
, effect = [ To Enemies Damage <| Range 450 750 ]
, over = [ Chances 50 90 << To Enemies GaugeDown <| Flat 1 ]
, first = False
}
, gen = { starWeight = 204, starRate = 9.2, npAtk = 0.71, npDef = 3 }
, hits = { quick = 3, arts = 2, buster = 1, ex = 4 }
, gender = Female
, traits = [Humanoid, Dragon, Saberface, EnumaElish]
, death = 35
, align = [Chaotic, Good]
, limited = True
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 10), (ShellOfReminiscence, 6)]
[(Monument Rider, 4), (GreatKnightMedal, 16), (DragonFang, 10)]
[(Monument Rider, 10), (DragonFang, 20), (DragonsReverseScale, 4)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (GreatKnightMedal, 8)]
[(SecretGemOf Rider, 4), (GreatKnightMedal, 16)]
[(SecretGemOf Rider, 10), (ShellOfReminiscence, 4)]
[(ShellOfReminiscence, 8), (HomunculusBaby, 5)]
[(HomunculusBaby, 15), (TearstoneOfBlood, 12)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 144
, rarity = 5
, class = Rider
, stats = { base = { atk = 1854, hp = 1900 }
, max = { atk = 12001, hp = 12960 }
, grail = { atk = 13137, hp = 14198 }
}
, gen = { starWeight = 205, starRate = 9, npAtk = 0.9, npDef = 3 }
, death = 25
, curve = 5
, attr = Sky
, align = [Lawful, Good]
, gender = Female
, traits = [Humanoid, Divine, Riding, EnumaElish, King]
, deck = Deck Quick Arts Arts Buster Buster
, hits = { quick = 3, arts = 2, buster = 3, ex = 5 }
, skills = [ { name = "PI:NAME:<NAME>END_PI"
, rank = APlus
, icon = Icon.SwordUp
, cd = 7
, effect = [ Grant Party 3 AttackUp <| Range 10.5 21 ]
}
, { name = "PI:NAME:<NAME>END_PIdom of the Benevolent God"
, rank = APlus
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Ally 3 Guts <| Flat 1000
, Grant Ally 3 (CardUp Buster) <| Range 20 30
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = EX
, icon = Icon.StarUp
, cd = 8
, effect = [ Grant Self 1 GatherUp <| Range 300 600
, Grant Self 1 CritUp <| Range 30 50
, To Self GaugeUp <| Range 20 30
]
}
]
, passives = [magicResistance A, riding EX, coreOfGoddess EX]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = A
, card = Buster
, kind = "Anti-Army/Anti-Fortress"
, hits = 1
, effect = [ To Enemy Damage <| Range 600 1000
, Debuff Enemy 1 SealNP Full
]
, over = [ Debuff Enemy 5 Burn <| Range 1000 3000 ]
, first = False
}
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (DragonFang, 18)]
[(Monument Rider, 5), (SerpentJewel, 8), (DragonsReverseScale, 2)]
[(Monument Rider, 12), (DragonsReverseScale, 4), (PhoenixFeather, 10)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (SerpentJewel, 4)]
[(SecretGemOf Rider, 5), (SerpentJewel, 8)]
[(SecretGemOf Rider, 12), (DragonFang, 12)]
[(DragonFang, 24), (FoolsChain, 18)]
[(FoolsChain, 54), (CursedBeastGallstone, 10)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Just "Resistance"
, id = 172
, rarity = 3
, class = Rider
, stats = { base = { atk = 1216, hp = 1728 }
, max = { atk = 6552, hp = 9600 }
, grail = { atk = 8867, hp = 13016 }
}
, gen = { starWeight = 208, starRate = 8.9, npAtk = 0.55, npDef = 3 }
, death = 50
, curve = 13
, attr = Human
, align = [Neutral, Evil]
, gender = Male
, traits = [Humanoid, EnumaElish]
, deck = Deck Quick Arts Arts Buster Buster
, hits = { quick = 3, arts = 3, buster = 4, ex = 5 }
, skills = [ { name = "PI:NAME:<NAME>END_PI"
, rank = B
, icon = Icon.BeamUp
, cd = 7
, effect = [ Grant Party 1 NPUp <| Range 7 14
, Grant Party 1 AttackUp <| Range 7 14
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = C
, icon = Icon.Kneel
, cd = 9
, effect = [ Times 1 << Grant Self 3 Guts <| Flat 1
, To Self GaugeUp <| Range 10 30
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = EX
, icon = Icon.BusterUp
, cd = 8
, effect = [ Grant Self 3 (CardUp Buster) <| Range 10 20
, To Party GainStars <| Range 5 15
]
}
]
, passives = [magicResistance D, riding B]
, phantasm = { name = "PI:NAME:<NAME>END_PI・PI:NAME:<NAME>END_PI"
, rank = A
, card = Buster
, kind = "Anti-Army"
, hits = 4
, effect = [ To Enemies Damage <| Range 300 500 ]
, over = [ Debuff Enemies 3 CritChance <| Range 20 60 ]
, first = False
}
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 4)]
[(Piece Rider, 8), (FoolsChain, 15)]
[(Monument Rider, 4), (MysteriousDivineWine, 3), (DeadlyPoisonousNeedle, 8)]
[(Monument Rider, 8), (DeadlyPoisonousNeedle, 16), (GhostLantern, 8)]
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 8)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 8), (MysteriousDivineWine, 2)]
[(SecretGemOf Rider, 4), (MysteriousDivineWine, 3)]
[(SecretGemOf Rider, 8), (FoolsChain, 10)]
[(FoolsChain, 20), (MysticSpinalFluid, 12)]
[(MysticSpinalFluid, 36), (CursedBeastGallstone, 7)]
}
, { name = "PI:NAME:<NAME>END_PI (Rider Alter)"
, spoiler = Nothing
, id = 179
, rarity = 5
, class = Rider
, stats = { base = { atk = 1665, hp = 2090 }
, max = { atk = 10776, hp = 14256 }
, grail = { atk = 11796, hp = 15618 }
}
, gen = { starWeight = 200, starRate = 9, npAtk = 0.59, npDef = 3 }
, death = 30
, curve = 5
, attr = Human
, align = [Lawful, Evil]
, gender = Female
, traits = [Humanoid, Arthur, Dragon, Riding, Saberface, EnumaElish, King]
, deck = Deck Quick Quick Arts Arts Buster
, hits = { quick = 3, arts = 3, buster = 2, ex = 5 }
, skills = [ { name = "Summer Sweeper!"
, rank = A
, icon = Icon.SwordUp
, cd = 8
, effect = [ Grant Self 3 AttackUp <| Range 20 30
, Grant Party 3 (CardUp Quick) <| Range 10 20
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = A
, icon = Icon.MagicLight
, cd = 8
, effect = [ To Ally ReduceCooldowns <| Flat 1
, Grant Self 3 StarUp <| Range 30 50
, To Ally DemeritHealth <| Flat 1000
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = C
, icon = Icon.QuickUp
, cd = 5
, effect = [ Times 1 << Grant Self 3 (CardUp Quick) <| Range 20 30 ]
}
]
, passives = [magicResistance B, riding B, independentAction EX]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = C
, card = Quick
, kind = "Anti-Army"
, hits = 6
, effect = [ To Enemy Damage <| Range 1200 2000
, To Self GaugeUp <| Flat 10
]
, over = [ Debuff Enemy 3 CritChance <| Range 30 70 ]
, first = False
}
, limited = True
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (GreatKnightMedal, 15)]
[(Monument Rider, 5), (DragonsReverseScale, 4), (ShellOfReminiscence, 5)]
[(Monument Rider, 12), (ShellOfReminiscence, 10), (CursedBeastGallstone, 5)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (DragonsReverseScale, 2)]
[(SecretGemOf Rider, 5), (DragonsReverseScale, 4)]
[(SecretGemOf Rider, 12), (GreatKnightMedal, 10)]
[(GreatKnightMedal, 20), (DragonFang, 15)]
[(DragonFang, 44), (MeteorHorseshoe, 24)]
}
, { name = "PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)"
, spoiler = Nothing
, id = 182
, rarity = 4
, class = Rider
, stats = { base = { atk = 1600, hp = 1710 }
, max = { atk = 9603, hp = 10692 }
, grail = { atk = 11627, hp = 12964 }
}
, gen = { starWeight = 200, starRate = 9, npAtk = 0.68, npDef = 3 }
, death = 35
, curve = 9
, attr = Sky
, align = [Lawful, Good]
, gender = Female
, traits = [Humanoid, Divine, Riding, EnumaElish]
, deck = Deck Quick Quick Arts Arts Buster
, hits = { quick = 2, arts = 3, buster = 5, ex = 3 }
, skills = [ { name = "PI:NAME:<NAME>END_PIining Water Robe"
, rank = A
, icon = Icon.QuickBusterUp
, cd = 7
, effect = [ Grant Party 3 (CardUp Quick) <| Range 10 20
, Grant Party 3 (CardUp Buster) <| Range 10 20
, Grant Party 3 NPGen <| Range 10 20
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = B
, icon = Icon.Dodge
, cd = 6
, effect = [ Grant Self 1 CritUp <| Range 30 50
, Times 1 <| Grant Self 1 Evasion Full
]
}
, { name = "PI:NAME:<NAME>END_PI!"
, rank = A
, icon = Icon.Shield
, cd = 8
, effect = [ Grant Self 1 NPGen <| Range 30 50
, Grant Self 1 CritUp <| Range 30 50
, Grant Self 1 HealingReceived <| Range 30 50
, Grant Self 1 DebuffResist <| Range 30 50
, Grant Self 1 Invincibility Full
, After 1 <| Debuff Self 1 Stun Full
]
}
]
, passives = [riding EX, independentAction A, coreOfGoddess B]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = EX
, card = Quick
, kind = "Anti-Personnel"
, hits = 4
, effect = [ To Enemies Damage <| Range 600 1000 ]
, over = [ Grant Self 1 (CardUp Quick) <| Range 20 60 ]
, first = True
}
, limited = True
, free = True
, ascendUp = Welfare "Golden Reed"
, skillUp = Reinforcement
[(GemOf Rider, 4)]
[(GemOf Rider, 10)]
[(MagicGemOf Rider, 4)]
[(MagicGemOf Rider, 10), (ShellOfReminiscence, 4)]
[(SecretGemOf Rider, 4), (ShellOfReminiscence, 8)]
[(SecretGemOf Rider, 10), (PrimordialLanugo, 3)]
[(PrimordialLanugo, 5), (ScarabOfWisdom, 2)]
[(ScarabOfWisdom, 6), (MysteriousDivineWine, 8)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 205
, rarity = 5
, class = Rider
, stats = { base = { atk = 1795, hp = 1948 }
, max = { atk = 11619, hp = 13284 }
, grail = { atk = 12719, hp = 14553 }
}
, gen = { starWeight = 200, starRate = 8.9, npAtk = 0.62, npDef = 3 }
, death = 40
, curve = 10
, attr = Human
, align = [Lawful, Evil]
, gender = Male
, traits = [Humanoid, WildBeast, King, Riding, EnumaElish]
, deck = Deck Quick Arts Arts Buster Buster
, hits = { quick = 4, arts = 3, buster = 2, ex = 4 }
, skills = [ { name = "Mental Schism"
, rank = A
, icon = Icon.NobleUp
, cd = 7
, effect = [ Grant Self 3 NPGen <| Range 30 50
, To Self RemoveDebuffs Full
]
}
, { name = "Innocent Monster (Foreign)"
, rank = A
, icon = Icon.StarTurn
, cd = 7
, effect = [ Grant Self 3 StarsPerTurn <| Range 5 10
, Grant Self 3 (CardUp Buster) <| Range 20 40
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = A
, icon = Icon.Shield
, cd = 8
, effect = [ Grant Self 1 Invincibility Full
, Debuff Enemies 3 AttackDown <| Range 10 20
, To Enemies RemoveBuffs Full
]
}
]
, passives = [magicResistance D, riding EX]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = B
, card = Buster
, kind = "Anti-Personnel"
, hits = 5
, effect = [ To Enemies Damage <| Range 300 500
, Debuff Enemies 3 (CardVuln Buster) <| Flat 20
]
, over = [ Grant Self 1 NPUp <| Range 30 70 ]
, first = True
}
, limited = True
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (EvilBone, 22)]
[(Monument Rider, 5), (MeteorHorseshoe, 10), (PrimordialLanugo, 3)]
[(Monument Rider, 12), (PrimordialLanugo, 6), (CursedBeastGallstone, 5)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 5), (MeteorHorseshoe, 5)]
[(SecretGemOf Rider, 5), (MeteorHorseshoe, 10)]
[(SecretGemOf Rider, 12), (EvilBone, 15)]
[(EvilBone, 29), (DeadlyPoisonousNeedle, 15)]
[(DeadlyPoisonousNeedle, 44), (EternalIce, 24)]
}
, { name = "PI:NAME:<NAME>END_PI"
, spoiler = Nothing
, id = 206
, rarity = 5
, class = Rider
, stats = { base = { atk = 1836, hp = 1938 }
, max = { atk = 11883, hp = 13219 }
, grail = { atk = 13008, hp = 14482 }
}
, gen = { starWeight = 196, starRate = 9.1, npAtk = 0.57, npDef = 3 }
, death = 40
, curve = 10
, attr = Earth
, align = [Lawful, Balanced]
, gender = Male
, traits = [Humanoid, Divine, Riding, LovedOne, GreekMythMale, EnumaElish]
, deck = Deck Quick Quick Arts Arts Buster
, hits = { quick = 4, arts = 3, buster = 2, ex = 4 }
, skills = [ { name = "PI:NAME:<NAME>END_PI"
, rank = APlus
, icon = Icon.QuickUp
, cd = 7
, effect = [ Grant Self 3 (CardUp Quick) <| Range 20 30
, Grant Self 3 CritUp <| Range 20 30
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = B
, icon = Icon.Shield
, cd = 7
, effect = [ Times 2 <| Grant Self 5 Invincibility Full
, Grant Self 3 DefenseUp <| Range 10 20
]
}
, { name = "PI:NAME:<NAME>END_PI"
, rank = BPlus
, icon = Icon.CrosshairUp
, cd = 8
, effect = [ Chance 500 <| Grant Self 1 Taunt Full
, Grant Self 1 NPGen <| Range 20 30
, To Self GaugeUp <| Range 20 30
]
}
]
, passives = [magicResistance C, riding APlus, divinity C]
, phantasm = { name = "PI:NAME:<NAME>END_PI"
, rank = A
, card = Quick
, kind = "Anti-Army"
, hits = 5
, effect = [ To Enemies Damage <| Range 600 1000 ]
, over = [ Grant Self 1 (CardUp Quick) <| Range 20 60 ]
, first = True
}
, limited = False
, free = False
, ascendUp = Ascension
[(Piece Rider, 5)]
[(Piece Rider, 12), (ProofOfHero, 22)]
[(Monument Rider, 5), (EternalGear, 10), (WarhorsesYoungHorn, 3)]
[(Monument Rider, 12), (WarhorsesYoungHorn, 6), (PhoenixFeather, 10)]
, skillUp = Reinforcement
[(GemOf Rider, 5)]
[(GemOf Rider, 12)]
[(MagicGemOf Rider, 5)]
[(MagicGemOf Rider, 12), (EternalGear, 5)]
[(SecretGemOf Rider, 5), (EternalGear, 10)]
[(SecretGemOf Rider, 12), (ProofOfHero, 15)]
[(ProofOfHero, 29), (MeteorHorseshoe, 6)]
[(MeteorHorseshoe, 18), (HeartOfTheForeignGod, 10)]
}
]
| elm |
[
{
"context": "s Model =\n { username : String\n , password : String\n , showPassword : Bool\n , document : D.Valu",
"end": 971,
"score": 0.9864051342,
"start": 965,
"tag": "PASSWORD",
"value": "String"
},
{
"context": "initCmd =\n Cmd.none\n\n\n\n-- View\n-- I'll be using mdgriffith/elm-ui because its awesome!!\n\n\nview : Model -> Ht",
"end": 1583,
"score": 0.977634728,
"start": 1573,
"tag": "USERNAME",
"value": "mdgriffith"
},
{
"context": "el = Input.labelLeft [ width <| px 120 ] <| text \"User name\"\n }\n\n\npwdInput : Model -> Element Msg\npwdI",
"end": 2620,
"score": 0.8987704515,
"start": 2611,
"tag": "NAME",
"value": "User name"
},
{
"context": "gin username password =\n E.object\n [ ( \"username\", E.string username )\n , ( \"password\", E.s",
"end": 7262,
"score": 0.9974144101,
"start": 7254,
"tag": "USERNAME",
"value": "username"
},
{
"context": "rd =\n E.object\n [ ( \"username\", E.string username )\n , ( \"password\", E.string password )\n ",
"end": 7282,
"score": 0.642419219,
"start": 7274,
"tag": "USERNAME",
"value": "username"
},
{
"context": "string username )\n , ( \"password\", E.string password )\n ]\n\n\ntoken : String -> D.Value -> Maybe ",
"end": 7326,
"score": 0.5003009439,
"start": 7318,
"tag": "PASSWORD",
"value": "password"
}
] | frontend/src/App.elm | 3kyro/servant-auth-elm | 4 | module App exposing (..)
{-
An app showcasing XSRF authentication using Servant-Auth
-}
import Browser
import Element exposing (..)
import Element.Background as Background
import Element.Font as Font
import Element.Input as Input
import Html as Html
import Http as Http
import Http.XSRF as XSRF
import Json.Decode as D
import Json.Encode as E
-- main parametrised to D.Value to receive the document object
main : Program D.Value Model Msg
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- Initialize the elm runtime with the document object
init : D.Value -> ( Model, Cmd Msg )
init cookies =
-- initModel sets a value of Model containing document object
( initModel cookies
, Cmd.none
)
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- Types
type alias Model =
{ username : String
, password : String
, showPassword : Bool
, document : D.Value
, output : String
}
type Msg
= ChangeUsername String
| ChangePassword String
| ShowPassword Bool
| Login String String
| LoginResponse (Result Http.Error ())
| GetName
| GetEmail
| ReceivedName (Result Http.Error String)
| ReceivedEmail (Result Http.Error String)
initModel : D.Value -> Model
initModel document =
{ username = ""
, password = ""
, showPassword = False
, document = document
, output = ""
}
initCmd : Cmd Msg
initCmd =
Cmd.none
-- View
-- I'll be using mdgriffith/elm-ui because its awesome!!
view : Model -> Html.Html Msg
view model =
layout
[ width fill
, height fill
]
<|
viewEl model
viewEl : Model -> Element Msg
viewEl model =
column
[ centerX
, width <| px 500
, spacing 20
, paddingXY 0 20
]
[ usernameInput model
, pwdInput model
, showPassword model
, loginButton model
, cookieNotigfication model
, nameButton
, emailButton
, showOutput model
]
-- Common attrributes for all my buttons
buttonAttributes : List (Attribute Msg)
buttonAttributes =
[ width fill
, height <| px 50
, Background.color <| rgb255 200 200 200
, Font.center
]
usernameInput : Model -> Element Msg
usernameInput model =
Input.text
[ width fill ]
{ onChange = ChangeUsername
, text = model.username
, placeholder = Nothing
, label = Input.labelLeft [ width <| px 120 ] <| text "User name"
}
pwdInput : Model -> Element Msg
pwdInput model =
Input.newPassword
[ width fill ]
{ onChange = ChangePassword
, text = model.password
, placeholder = Nothing
, label = Input.labelLeft [ width <| px 120 ] <| text "Password"
, show = model.showPassword
}
showPassword : Model -> Element Msg
showPassword model =
Input.checkbox
[]
{ onChange = ShowPassword
, icon = Input.defaultCheckbox
, checked = model.showPassword
, label = Input.labelRight [] <| text "Show password"
}
loginButton : Model -> Element Msg
loginButton model =
Input.button
buttonAttributes
{ onPress = Just <| Login model.username model.password
, label = text "Login"
}
cookieNotigfication : Model -> Element Msg
cookieNotigfication model =
-- In a real app, you'd have a way to keep track if the user is
-- authenticated or not
case token "XSRF-TOKEN=" model.document of
Just _ ->
el
[ width fill
, height <| px 50
, Background.color <| rgb255 116 205 128
]
<|
el [ centerY, centerX ] <|
text "Authenticated"
Nothing ->
el
[ width fill
, height <| px 50
, Background.color <| rgb255 255 65 65
]
<|
el [ centerY, centerX ] <|
text "Not Authenticated"
nameButton : Element Msg
nameButton =
Input.button
buttonAttributes
{ onPress = Just <| GetName
, label = text "Get Name"
}
emailButton : Element Msg
emailButton =
Input.button
buttonAttributes
{ onPress = Just <| GetEmail
, label = text "Get Email"
}
showOutput : Model -> Element Msg
showOutput model =
el
[ width fill
, height <| px 50
, Background.color <| rgb255 252 153 131
]
<|
el [ centerY, centerX ] <|
text model.output
-- Update
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
ChangeUsername str ->
( { model | username = str }
, Cmd.none
)
ChangePassword str ->
( { model | password = str }
, Cmd.none
)
ShowPassword flag ->
( { model | showPassword = flag }
, Cmd.none
)
Login username password ->
( model
, login username password
)
LoginResponse _ ->
( { model
| username = ""
, password = ""
}
, Cmd.none
)
GetName ->
( model
, getNameRequest model
)
GetEmail ->
( model
, getEmailRequest model
)
ReceivedName rlt ->
case rlt of
Err err ->
( model, Cmd.none )
Ok name ->
( { model | output = name }, Cmd.none )
ReceivedEmail rlt ->
case rlt of
Err err ->
( model, Cmd.none )
Ok email ->
( { model | output = email }, Cmd.none )
-- Requests
-- Unprotected login request
-- Notice the use of Http.post for unprotected requests
login : String -> String -> Cmd Msg
login username password =
Http.post
{ url = "http://localhost:4000/login"
, body = Http.jsonBody <| encodeLogin username password
, expect = Http.expectWhatever LoginResponse
}
-- Protected request for the authenticated user's name
-- Notice the use of XSRF.get for protected requests
getNameRequest : Model -> Cmd Msg
getNameRequest model =
XSRF.get
{ url = "http://localhost:4000/name"
, expect = Http.expectJson ReceivedName D.string
, xsrfHeaderName = "X-XSRF-TOKEN"
, xsrfToken = token "XSRF-TOKEN=" model.document
}
-- Protected request for the authenticated user's email
getEmailRequest : Model -> Cmd Msg
getEmailRequest model =
XSRF.get
{ url = "http://localhost:4000/email"
, expect = Http.expectJson ReceivedEmail D.string
, xsrfHeaderName = "X-XSRF-TOKEN"
, xsrfToken = token "XSRF-TOKEN=" model.document
}
-- JSON
encodeLogin : String -> String -> E.Value
encodeLogin username password =
E.object
[ ( "username", E.string username )
, ( "password", E.string password )
]
token : String -> D.Value -> Maybe String
token name value =
let
decodeCookie =
D.field "cookie" D.string
str =
D.decodeValue decodeCookie value
split a =
String.split ";" a
filtered a =
List.filter (String.startsWith name) [ a ]
head a =
List.head <| filtered a
trimmed a =
Maybe.map (String.dropLeft (String.length name)) <| head a
in
case str of
Err err ->
Nothing
Ok cookie ->
trimmed cookie
| 7754 | module App exposing (..)
{-
An app showcasing XSRF authentication using Servant-Auth
-}
import Browser
import Element exposing (..)
import Element.Background as Background
import Element.Font as Font
import Element.Input as Input
import Html as Html
import Http as Http
import Http.XSRF as XSRF
import Json.Decode as D
import Json.Encode as E
-- main parametrised to D.Value to receive the document object
main : Program D.Value Model Msg
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- Initialize the elm runtime with the document object
init : D.Value -> ( Model, Cmd Msg )
init cookies =
-- initModel sets a value of Model containing document object
( initModel cookies
, Cmd.none
)
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- Types
type alias Model =
{ username : String
, password : <PASSWORD>
, showPassword : Bool
, document : D.Value
, output : String
}
type Msg
= ChangeUsername String
| ChangePassword String
| ShowPassword Bool
| Login String String
| LoginResponse (Result Http.Error ())
| GetName
| GetEmail
| ReceivedName (Result Http.Error String)
| ReceivedEmail (Result Http.Error String)
initModel : D.Value -> Model
initModel document =
{ username = ""
, password = ""
, showPassword = False
, document = document
, output = ""
}
initCmd : Cmd Msg
initCmd =
Cmd.none
-- View
-- I'll be using mdgriffith/elm-ui because its awesome!!
view : Model -> Html.Html Msg
view model =
layout
[ width fill
, height fill
]
<|
viewEl model
viewEl : Model -> Element Msg
viewEl model =
column
[ centerX
, width <| px 500
, spacing 20
, paddingXY 0 20
]
[ usernameInput model
, pwdInput model
, showPassword model
, loginButton model
, cookieNotigfication model
, nameButton
, emailButton
, showOutput model
]
-- Common attrributes for all my buttons
buttonAttributes : List (Attribute Msg)
buttonAttributes =
[ width fill
, height <| px 50
, Background.color <| rgb255 200 200 200
, Font.center
]
usernameInput : Model -> Element Msg
usernameInput model =
Input.text
[ width fill ]
{ onChange = ChangeUsername
, text = model.username
, placeholder = Nothing
, label = Input.labelLeft [ width <| px 120 ] <| text "<NAME>"
}
pwdInput : Model -> Element Msg
pwdInput model =
Input.newPassword
[ width fill ]
{ onChange = ChangePassword
, text = model.password
, placeholder = Nothing
, label = Input.labelLeft [ width <| px 120 ] <| text "Password"
, show = model.showPassword
}
showPassword : Model -> Element Msg
showPassword model =
Input.checkbox
[]
{ onChange = ShowPassword
, icon = Input.defaultCheckbox
, checked = model.showPassword
, label = Input.labelRight [] <| text "Show password"
}
loginButton : Model -> Element Msg
loginButton model =
Input.button
buttonAttributes
{ onPress = Just <| Login model.username model.password
, label = text "Login"
}
cookieNotigfication : Model -> Element Msg
cookieNotigfication model =
-- In a real app, you'd have a way to keep track if the user is
-- authenticated or not
case token "XSRF-TOKEN=" model.document of
Just _ ->
el
[ width fill
, height <| px 50
, Background.color <| rgb255 116 205 128
]
<|
el [ centerY, centerX ] <|
text "Authenticated"
Nothing ->
el
[ width fill
, height <| px 50
, Background.color <| rgb255 255 65 65
]
<|
el [ centerY, centerX ] <|
text "Not Authenticated"
nameButton : Element Msg
nameButton =
Input.button
buttonAttributes
{ onPress = Just <| GetName
, label = text "Get Name"
}
emailButton : Element Msg
emailButton =
Input.button
buttonAttributes
{ onPress = Just <| GetEmail
, label = text "Get Email"
}
showOutput : Model -> Element Msg
showOutput model =
el
[ width fill
, height <| px 50
, Background.color <| rgb255 252 153 131
]
<|
el [ centerY, centerX ] <|
text model.output
-- Update
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
ChangeUsername str ->
( { model | username = str }
, Cmd.none
)
ChangePassword str ->
( { model | password = str }
, Cmd.none
)
ShowPassword flag ->
( { model | showPassword = flag }
, Cmd.none
)
Login username password ->
( model
, login username password
)
LoginResponse _ ->
( { model
| username = ""
, password = ""
}
, Cmd.none
)
GetName ->
( model
, getNameRequest model
)
GetEmail ->
( model
, getEmailRequest model
)
ReceivedName rlt ->
case rlt of
Err err ->
( model, Cmd.none )
Ok name ->
( { model | output = name }, Cmd.none )
ReceivedEmail rlt ->
case rlt of
Err err ->
( model, Cmd.none )
Ok email ->
( { model | output = email }, Cmd.none )
-- Requests
-- Unprotected login request
-- Notice the use of Http.post for unprotected requests
login : String -> String -> Cmd Msg
login username password =
Http.post
{ url = "http://localhost:4000/login"
, body = Http.jsonBody <| encodeLogin username password
, expect = Http.expectWhatever LoginResponse
}
-- Protected request for the authenticated user's name
-- Notice the use of XSRF.get for protected requests
getNameRequest : Model -> Cmd Msg
getNameRequest model =
XSRF.get
{ url = "http://localhost:4000/name"
, expect = Http.expectJson ReceivedName D.string
, xsrfHeaderName = "X-XSRF-TOKEN"
, xsrfToken = token "XSRF-TOKEN=" model.document
}
-- Protected request for the authenticated user's email
getEmailRequest : Model -> Cmd Msg
getEmailRequest model =
XSRF.get
{ url = "http://localhost:4000/email"
, expect = Http.expectJson ReceivedEmail D.string
, xsrfHeaderName = "X-XSRF-TOKEN"
, xsrfToken = token "XSRF-TOKEN=" model.document
}
-- JSON
encodeLogin : String -> String -> E.Value
encodeLogin username password =
E.object
[ ( "username", E.string username )
, ( "password", E.string <PASSWORD> )
]
token : String -> D.Value -> Maybe String
token name value =
let
decodeCookie =
D.field "cookie" D.string
str =
D.decodeValue decodeCookie value
split a =
String.split ";" a
filtered a =
List.filter (String.startsWith name) [ a ]
head a =
List.head <| filtered a
trimmed a =
Maybe.map (String.dropLeft (String.length name)) <| head a
in
case str of
Err err ->
Nothing
Ok cookie ->
trimmed cookie
| true | module App exposing (..)
{-
An app showcasing XSRF authentication using Servant-Auth
-}
import Browser
import Element exposing (..)
import Element.Background as Background
import Element.Font as Font
import Element.Input as Input
import Html as Html
import Http as Http
import Http.XSRF as XSRF
import Json.Decode as D
import Json.Encode as E
-- main parametrised to D.Value to receive the document object
main : Program D.Value Model Msg
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- Initialize the elm runtime with the document object
init : D.Value -> ( Model, Cmd Msg )
init cookies =
-- initModel sets a value of Model containing document object
( initModel cookies
, Cmd.none
)
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- Types
type alias Model =
{ username : String
, password : PI:PASSWORD:<PASSWORD>END_PI
, showPassword : Bool
, document : D.Value
, output : String
}
type Msg
= ChangeUsername String
| ChangePassword String
| ShowPassword Bool
| Login String String
| LoginResponse (Result Http.Error ())
| GetName
| GetEmail
| ReceivedName (Result Http.Error String)
| ReceivedEmail (Result Http.Error String)
initModel : D.Value -> Model
initModel document =
{ username = ""
, password = ""
, showPassword = False
, document = document
, output = ""
}
initCmd : Cmd Msg
initCmd =
Cmd.none
-- View
-- I'll be using mdgriffith/elm-ui because its awesome!!
view : Model -> Html.Html Msg
view model =
layout
[ width fill
, height fill
]
<|
viewEl model
viewEl : Model -> Element Msg
viewEl model =
column
[ centerX
, width <| px 500
, spacing 20
, paddingXY 0 20
]
[ usernameInput model
, pwdInput model
, showPassword model
, loginButton model
, cookieNotigfication model
, nameButton
, emailButton
, showOutput model
]
-- Common attrributes for all my buttons
buttonAttributes : List (Attribute Msg)
buttonAttributes =
[ width fill
, height <| px 50
, Background.color <| rgb255 200 200 200
, Font.center
]
usernameInput : Model -> Element Msg
usernameInput model =
Input.text
[ width fill ]
{ onChange = ChangeUsername
, text = model.username
, placeholder = Nothing
, label = Input.labelLeft [ width <| px 120 ] <| text "PI:NAME:<NAME>END_PI"
}
pwdInput : Model -> Element Msg
pwdInput model =
Input.newPassword
[ width fill ]
{ onChange = ChangePassword
, text = model.password
, placeholder = Nothing
, label = Input.labelLeft [ width <| px 120 ] <| text "Password"
, show = model.showPassword
}
showPassword : Model -> Element Msg
showPassword model =
Input.checkbox
[]
{ onChange = ShowPassword
, icon = Input.defaultCheckbox
, checked = model.showPassword
, label = Input.labelRight [] <| text "Show password"
}
loginButton : Model -> Element Msg
loginButton model =
Input.button
buttonAttributes
{ onPress = Just <| Login model.username model.password
, label = text "Login"
}
cookieNotigfication : Model -> Element Msg
cookieNotigfication model =
-- In a real app, you'd have a way to keep track if the user is
-- authenticated or not
case token "XSRF-TOKEN=" model.document of
Just _ ->
el
[ width fill
, height <| px 50
, Background.color <| rgb255 116 205 128
]
<|
el [ centerY, centerX ] <|
text "Authenticated"
Nothing ->
el
[ width fill
, height <| px 50
, Background.color <| rgb255 255 65 65
]
<|
el [ centerY, centerX ] <|
text "Not Authenticated"
nameButton : Element Msg
nameButton =
Input.button
buttonAttributes
{ onPress = Just <| GetName
, label = text "Get Name"
}
emailButton : Element Msg
emailButton =
Input.button
buttonAttributes
{ onPress = Just <| GetEmail
, label = text "Get Email"
}
showOutput : Model -> Element Msg
showOutput model =
el
[ width fill
, height <| px 50
, Background.color <| rgb255 252 153 131
]
<|
el [ centerY, centerX ] <|
text model.output
-- Update
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
ChangeUsername str ->
( { model | username = str }
, Cmd.none
)
ChangePassword str ->
( { model | password = str }
, Cmd.none
)
ShowPassword flag ->
( { model | showPassword = flag }
, Cmd.none
)
Login username password ->
( model
, login username password
)
LoginResponse _ ->
( { model
| username = ""
, password = ""
}
, Cmd.none
)
GetName ->
( model
, getNameRequest model
)
GetEmail ->
( model
, getEmailRequest model
)
ReceivedName rlt ->
case rlt of
Err err ->
( model, Cmd.none )
Ok name ->
( { model | output = name }, Cmd.none )
ReceivedEmail rlt ->
case rlt of
Err err ->
( model, Cmd.none )
Ok email ->
( { model | output = email }, Cmd.none )
-- Requests
-- Unprotected login request
-- Notice the use of Http.post for unprotected requests
login : String -> String -> Cmd Msg
login username password =
Http.post
{ url = "http://localhost:4000/login"
, body = Http.jsonBody <| encodeLogin username password
, expect = Http.expectWhatever LoginResponse
}
-- Protected request for the authenticated user's name
-- Notice the use of XSRF.get for protected requests
getNameRequest : Model -> Cmd Msg
getNameRequest model =
XSRF.get
{ url = "http://localhost:4000/name"
, expect = Http.expectJson ReceivedName D.string
, xsrfHeaderName = "X-XSRF-TOKEN"
, xsrfToken = token "XSRF-TOKEN=" model.document
}
-- Protected request for the authenticated user's email
getEmailRequest : Model -> Cmd Msg
getEmailRequest model =
XSRF.get
{ url = "http://localhost:4000/email"
, expect = Http.expectJson ReceivedEmail D.string
, xsrfHeaderName = "X-XSRF-TOKEN"
, xsrfToken = token "XSRF-TOKEN=" model.document
}
-- JSON
encodeLogin : String -> String -> E.Value
encodeLogin username password =
E.object
[ ( "username", E.string username )
, ( "password", E.string PI:PASSWORD:<PASSWORD>END_PI )
]
token : String -> D.Value -> Maybe String
token name value =
let
decodeCookie =
D.field "cookie" D.string
str =
D.decodeValue decodeCookie value
split a =
String.split ";" a
filtered a =
List.filter (String.startsWith name) [ a ]
head a =
List.head <| filtered a
trimmed a =
Maybe.map (String.dropLeft (String.length name)) <| head a
in
case str of
Err err ->
Nothing
Ok cookie ->
trimmed cookie
| elm |
[
{
"context": " , wide =\n { jan = \"urtarrilak\"\n , feb = \"otsailak\"\n ",
"end": 4167,
"score": 0.7238361239,
"start": 4160,
"tag": "NAME",
"value": "arrilak"
},
{
"context": " , feb = \"otsailak\"\n , mar = \"martxoak\"\n , apr = \"apirilak\"\n ",
"end": 4245,
"score": 0.803881824,
"start": 4237,
"tag": "NAME",
"value": "martxoak"
},
{
"context": " , wide =\n { jan = \"urtarrila\"\n , feb = \"otsaila\"\n ",
"end": 5640,
"score": 0.7637029886,
"start": 5634,
"tag": "NAME",
"value": "arrila"
},
{
"context": " , feb = \"otsaila\"\n , mar = \"martxoa\"\n , apr = \"apirila\"\n ",
"end": 5716,
"score": 0.7527247071,
"start": 5709,
"tag": "NAME",
"value": "martxoa"
},
{
"context": "\", ad = \"K.o.\" }\n , wide = { bc = \"K.a.\", ad = \"Kristo ondoren\" }\n , narr",
"end": 8540,
"score": 0.7935140729,
"start": 8537,
"tag": "NAME",
"value": "K.a"
},
{
"context": " }\n , wide = { bc = \"K.a.\", ad = \"Kristo ondoren\" }\n , narrow = { bc = \"a\",",
"end": 8556,
"score": 0.7183010578,
"start": 8551,
"tag": "NAME",
"value": "risto"
},
{
"context": " , wide = { bc = \"K.a.\", ad = \"Kristo ondoren\" }\n , narrow = { bc = \"a\", ad = \"o",
"end": 8564,
"score": 0.6361588836,
"start": 8560,
"tag": "NAME",
"value": "oren"
}
] | src/Generated/Eu.elm | Enkidatron/elm-cldr | 3 | module Generated.Eu exposing (eu)
import Dict exposing (Dict)
import Internal.DayPeriodRule
import Internal.Locale exposing (DateTimeToken(..), LanguageId(..))
import Internal.Parse
import Tagged exposing (Tagged(..))
dayPeriods : Dict String (List Internal.DayPeriodRule.DayPeriodRule)
dayPeriods =
Dict.fromList
[ ( "eu"
, [ Internal.DayPeriodRule.FromBefore ( 12, 0 ) ( 14, 0 ) "afternoon1"
, Internal.DayPeriodRule.FromBefore ( 14, 0 ) ( 19, 0 ) "afternoon2"
, Internal.DayPeriodRule.FromBefore ( 19, 0 ) ( 21, 0 ) "evening1"
, Internal.DayPeriodRule.At ( 0, 0 ) "midnight"
, Internal.DayPeriodRule.FromBefore ( 0, 0 ) ( 6, 0 ) "morning1"
, Internal.DayPeriodRule.FromBefore ( 6, 0 ) ( 12, 0 ) "morning2"
, Internal.DayPeriodRule.FromBefore ( 21, 0 ) ( 24, 0 ) "night1"
]
)
]
{-| Date format strings:
- Short : yy/M/d
- Medium : y('e')'ko' MMM d('a')
- Long : y('e')'ko' MMMM'ren' d('a')
- Full : y('e')'ko' MMMM'ren' d('a'), EEEE
Time format strings:
- Short : HH:mm
- Medium : HH:mm:ss
- Long : HH:mm:ss (z)
- Full : HH:mm:ss (zzzz)
-}
eu : Internal.Locale.Locale
eu =
Maybe.withDefault
Internal.Locale.empty
(Internal.Parse.parse
dayPeriods
{ language = "eu"
, script = Nothing
, territory = Nothing
, variant = Nothing
, periodNames =
{ abbreviated =
{ am = "AM"
, pm = "PM"
, dayPeriods =
Dict.fromList
[ ( "afternoon1", "eguerd." )
, ( "afternoon2", "arrats." )
, ( "evening1", "iluntz." )
, ( "midnight", "gauerdia" )
, ( "morning1", "goizald." )
, ( "morning2", "goizeko" )
, ( "night1", "gaueko" )
]
}
, wide =
{ am = "AM"
, pm = "PM"
, dayPeriods =
Dict.fromList
[ ( "afternoon1", "eguerdiko" )
, ( "afternoon2", "arratsaldeko" )
, ( "evening1", "iluntzeko" )
, ( "midnight", "gauerdia" )
, ( "morning1", "goizaldeko" )
, ( "morning2", "goizeko" )
, ( "night1", "gaueko" )
]
}
, narrow =
{ am = "g"
, pm = "a"
, dayPeriods =
Dict.fromList
[ ( "afternoon1", "eguerd." )
, ( "afternoon2", "arrats." )
, ( "evening1", "iluntz." )
, ( "midnight", "gauerdia" )
, ( "morning1", "goizald." )
, ( "morning2", "goizeko" )
, ( "night1", "gaueko" )
]
}
}
, datePatterns =
{ short = "yy/M/d"
, medium = "y('e')'ko' MMM d('a')"
, long = "y('e')'ko' MMMM'ren' d('a')"
, full = "y('e')'ko' MMMM'ren' d('a'), EEEE"
}
, monthFormatNames =
{ abbreviated =
{ jan = "urt."
, feb = "ots."
, mar = "mar."
, apr = "api."
, may = "mai."
, jun = "eka."
, jul = "uzt."
, aug = "abu."
, sep = "ira."
, oct = "urr."
, nov = "aza."
, dec = "abe."
}
, wide =
{ jan = "urtarrilak"
, feb = "otsailak"
, mar = "martxoak"
, apr = "apirilak"
, may = "maiatzak"
, jun = "ekainak"
, jul = "uztailak"
, aug = "abuztuak"
, sep = "irailak"
, oct = "urriak"
, nov = "azaroak"
, dec = "abenduak"
}
, narrow =
{ jan = "U"
, feb = "O"
, mar = "M"
, apr = "A"
, may = "M"
, jun = "E"
, jul = "U"
, aug = "A"
, sep = "I"
, oct = "U"
, nov = "A"
, dec = "A"
}
}
, monthStandaloneNames =
{ abbreviated =
{ jan = "urt."
, feb = "ots."
, mar = "mar."
, apr = "api."
, may = "mai."
, jun = "eka."
, jul = "uzt."
, aug = "abu."
, sep = "ira."
, oct = "urr."
, nov = "aza."
, dec = "abe."
}
, wide =
{ jan = "urtarrila"
, feb = "otsaila"
, mar = "martxoa"
, apr = "apirila"
, may = "maiatza"
, jun = "ekaina"
, jul = "uztaila"
, aug = "abuztua"
, sep = "iraila"
, oct = "urria"
, nov = "azaroa"
, dec = "abendua"
}
, narrow =
{ jan = "U"
, feb = "O"
, mar = "M"
, apr = "A"
, may = "M"
, jun = "E"
, jul = "U"
, aug = "A"
, sep = "I"
, oct = "U"
, nov = "A"
, dec = "A"
}
}
, weekdayFormatNames =
{ abbreviated =
{ sun = "ig."
, mon = "al."
, tue = "ar."
, wed = "az."
, thu = "og."
, fri = "or."
, sat = "lr."
}
, wide =
{ sun = "igandea"
, mon = "astelehena"
, tue = "asteartea"
, wed = "asteazkena"
, thu = "osteguna"
, fri = "ostirala"
, sat = "larunbata"
}
, narrow =
{ sun = "I"
, mon = "A"
, tue = "A"
, wed = "A"
, thu = "O"
, fri = "O"
, sat = "L"
}
}
, weekdayStandaloneNames =
{ abbreviated =
{ sun = "ig."
, mon = "al."
, tue = "ar."
, wed = "az."
, thu = "og."
, fri = "or."
, sat = "lr."
}
, wide =
{ sun = "igandea"
, mon = "astelehena"
, tue = "asteartea"
, wed = "asteazkena"
, thu = "osteguna"
, fri = "ostirala"
, sat = "larunbata"
}
, narrow =
{ sun = "I"
, mon = "A"
, tue = "A"
, wed = "A"
, thu = "O"
, fri = "O"
, sat = "L"
}
}
, eraNames =
{ abbreviated = { bc = "K.a.", ad = "K.o." }
, wide = { bc = "K.a.", ad = "Kristo ondoren" }
, narrow = { bc = "a", ad = "o" }
}
, timePatterns =
{ short = "HH:mm"
, medium = "HH:mm:ss"
, long = "HH:mm:ss (z)"
, full = "HH:mm:ss (zzzz)"
}
, dateTimePatterns =
{ short = "{1} {0}"
, medium = "{1} {0}"
, long = "{1} {0}"
, full = "{1} {0}"
}
, availableFormats =
[ ( "Bh", "B h" )
, ( "Bhm", "B h:mm" )
, ( "Bhms", "B h:mm:ss" )
, ( "d", "d" )
, ( "E", "ccc" )
, ( "EBhm", "E B h:mm" )
, ( "EBhms", "E B h:mm:ss" )
, ( "Ed", "d, E" )
, ( "Ehm", "E h:mm a" )
, ( "EHm", "E HH:mm" )
, ( "Ehms", "E h:mm:ss a" )
, ( "EHms", "E HH:mm:ss" )
, ( "Gy", "G y" )
, ( "GyMd", "GGGGG y-MM-dd" )
, ( "GyMMM", "G y. 'urteko' MMM" )
, ( "GyMMMd", "G y. 'urteko' MMM d" )
, ( "GyMMMEd", "G y. 'urteko' MMM d, E" )
, ( "h", "h a" )
, ( "H", "HH" )
, ( "hm", "h:mm a" )
, ( "Hm", "HH:mm" )
, ( "hms", "h:mm:ss a" )
, ( "Hms", "HH:mm:ss" )
, ( "hmsv", "h:mm:ss a v" )
, ( "Hmsv", "HH:mm:ss v" )
, ( "hmv", "h:mm a v" )
, ( "Hmv", "HH:mm v" )
, ( "M", "L" )
, ( "Md", "M/d" )
, ( "MEd", "M/d, E" )
, ( "MMM", "LLL" )
, ( "MMMd", "MMM d" )
, ( "MMMEd", "MMM d, E" )
, ( "MMMMd", "MMMM d" )
, ( "MMMMW-count-one", "MMMM W. 'astea'" )
, ( "MMMMW-count-other", "MMMM W. 'astea'" )
, ( "ms", "mm:ss" )
, ( "y", "y" )
, ( "yM", "y/M" )
, ( "yMd", "y/M/d" )
, ( "yMEd", "y/M/d, E" )
, ( "yMMM", "y MMM" )
, ( "yMMMd", "y MMM d" )
, ( "yMMMEd", "y MMM d, E" )
, ( "yMMMM", "y('e')'ko' MMMM" )
, ( "yMMMMd", "y('e')'ko' MMMM'ren' d" )
, ( "yMMMMEd", "y('e')'ko' MMMM'k' d, E" )
, ( "yQQQ", "y('e')'ko' QQQ" )
, ( "yQQQQ", "y('e')'ko' QQQQ" )
, ( "yw-count-one", "Y. 'urteko' w. 'astea'" )
, ( "yw-count-other", "Y. 'urteko' w. 'astea'" )
]
, timeSkeletons =
{ short = "HHmm"
, medium = "HHmmss"
, long = "HHmmssz"
, full = "HHmmsszzzz"
}
}
)
| 22255 | module Generated.Eu exposing (eu)
import Dict exposing (Dict)
import Internal.DayPeriodRule
import Internal.Locale exposing (DateTimeToken(..), LanguageId(..))
import Internal.Parse
import Tagged exposing (Tagged(..))
dayPeriods : Dict String (List Internal.DayPeriodRule.DayPeriodRule)
dayPeriods =
Dict.fromList
[ ( "eu"
, [ Internal.DayPeriodRule.FromBefore ( 12, 0 ) ( 14, 0 ) "afternoon1"
, Internal.DayPeriodRule.FromBefore ( 14, 0 ) ( 19, 0 ) "afternoon2"
, Internal.DayPeriodRule.FromBefore ( 19, 0 ) ( 21, 0 ) "evening1"
, Internal.DayPeriodRule.At ( 0, 0 ) "midnight"
, Internal.DayPeriodRule.FromBefore ( 0, 0 ) ( 6, 0 ) "morning1"
, Internal.DayPeriodRule.FromBefore ( 6, 0 ) ( 12, 0 ) "morning2"
, Internal.DayPeriodRule.FromBefore ( 21, 0 ) ( 24, 0 ) "night1"
]
)
]
{-| Date format strings:
- Short : yy/M/d
- Medium : y('e')'ko' MMM d('a')
- Long : y('e')'ko' MMMM'ren' d('a')
- Full : y('e')'ko' MMMM'ren' d('a'), EEEE
Time format strings:
- Short : HH:mm
- Medium : HH:mm:ss
- Long : HH:mm:ss (z)
- Full : HH:mm:ss (zzzz)
-}
eu : Internal.Locale.Locale
eu =
Maybe.withDefault
Internal.Locale.empty
(Internal.Parse.parse
dayPeriods
{ language = "eu"
, script = Nothing
, territory = Nothing
, variant = Nothing
, periodNames =
{ abbreviated =
{ am = "AM"
, pm = "PM"
, dayPeriods =
Dict.fromList
[ ( "afternoon1", "eguerd." )
, ( "afternoon2", "arrats." )
, ( "evening1", "iluntz." )
, ( "midnight", "gauerdia" )
, ( "morning1", "goizald." )
, ( "morning2", "goizeko" )
, ( "night1", "gaueko" )
]
}
, wide =
{ am = "AM"
, pm = "PM"
, dayPeriods =
Dict.fromList
[ ( "afternoon1", "eguerdiko" )
, ( "afternoon2", "arratsaldeko" )
, ( "evening1", "iluntzeko" )
, ( "midnight", "gauerdia" )
, ( "morning1", "goizaldeko" )
, ( "morning2", "goizeko" )
, ( "night1", "gaueko" )
]
}
, narrow =
{ am = "g"
, pm = "a"
, dayPeriods =
Dict.fromList
[ ( "afternoon1", "eguerd." )
, ( "afternoon2", "arrats." )
, ( "evening1", "iluntz." )
, ( "midnight", "gauerdia" )
, ( "morning1", "goizald." )
, ( "morning2", "goizeko" )
, ( "night1", "gaueko" )
]
}
}
, datePatterns =
{ short = "yy/M/d"
, medium = "y('e')'ko' MMM d('a')"
, long = "y('e')'ko' MMMM'ren' d('a')"
, full = "y('e')'ko' MMMM'ren' d('a'), EEEE"
}
, monthFormatNames =
{ abbreviated =
{ jan = "urt."
, feb = "ots."
, mar = "mar."
, apr = "api."
, may = "mai."
, jun = "eka."
, jul = "uzt."
, aug = "abu."
, sep = "ira."
, oct = "urr."
, nov = "aza."
, dec = "abe."
}
, wide =
{ jan = "urt<NAME>"
, feb = "otsailak"
, mar = "<NAME>"
, apr = "apirilak"
, may = "maiatzak"
, jun = "ekainak"
, jul = "uztailak"
, aug = "abuztuak"
, sep = "irailak"
, oct = "urriak"
, nov = "azaroak"
, dec = "abenduak"
}
, narrow =
{ jan = "U"
, feb = "O"
, mar = "M"
, apr = "A"
, may = "M"
, jun = "E"
, jul = "U"
, aug = "A"
, sep = "I"
, oct = "U"
, nov = "A"
, dec = "A"
}
}
, monthStandaloneNames =
{ abbreviated =
{ jan = "urt."
, feb = "ots."
, mar = "mar."
, apr = "api."
, may = "mai."
, jun = "eka."
, jul = "uzt."
, aug = "abu."
, sep = "ira."
, oct = "urr."
, nov = "aza."
, dec = "abe."
}
, wide =
{ jan = "urt<NAME>"
, feb = "otsaila"
, mar = "<NAME>"
, apr = "apirila"
, may = "maiatza"
, jun = "ekaina"
, jul = "uztaila"
, aug = "abuztua"
, sep = "iraila"
, oct = "urria"
, nov = "azaroa"
, dec = "abendua"
}
, narrow =
{ jan = "U"
, feb = "O"
, mar = "M"
, apr = "A"
, may = "M"
, jun = "E"
, jul = "U"
, aug = "A"
, sep = "I"
, oct = "U"
, nov = "A"
, dec = "A"
}
}
, weekdayFormatNames =
{ abbreviated =
{ sun = "ig."
, mon = "al."
, tue = "ar."
, wed = "az."
, thu = "og."
, fri = "or."
, sat = "lr."
}
, wide =
{ sun = "igandea"
, mon = "astelehena"
, tue = "asteartea"
, wed = "asteazkena"
, thu = "osteguna"
, fri = "ostirala"
, sat = "larunbata"
}
, narrow =
{ sun = "I"
, mon = "A"
, tue = "A"
, wed = "A"
, thu = "O"
, fri = "O"
, sat = "L"
}
}
, weekdayStandaloneNames =
{ abbreviated =
{ sun = "ig."
, mon = "al."
, tue = "ar."
, wed = "az."
, thu = "og."
, fri = "or."
, sat = "lr."
}
, wide =
{ sun = "igandea"
, mon = "astelehena"
, tue = "asteartea"
, wed = "asteazkena"
, thu = "osteguna"
, fri = "ostirala"
, sat = "larunbata"
}
, narrow =
{ sun = "I"
, mon = "A"
, tue = "A"
, wed = "A"
, thu = "O"
, fri = "O"
, sat = "L"
}
}
, eraNames =
{ abbreviated = { bc = "K.a.", ad = "K.o." }
, wide = { bc = "<NAME>.", ad = "K<NAME> ond<NAME>" }
, narrow = { bc = "a", ad = "o" }
}
, timePatterns =
{ short = "HH:mm"
, medium = "HH:mm:ss"
, long = "HH:mm:ss (z)"
, full = "HH:mm:ss (zzzz)"
}
, dateTimePatterns =
{ short = "{1} {0}"
, medium = "{1} {0}"
, long = "{1} {0}"
, full = "{1} {0}"
}
, availableFormats =
[ ( "Bh", "B h" )
, ( "Bhm", "B h:mm" )
, ( "Bhms", "B h:mm:ss" )
, ( "d", "d" )
, ( "E", "ccc" )
, ( "EBhm", "E B h:mm" )
, ( "EBhms", "E B h:mm:ss" )
, ( "Ed", "d, E" )
, ( "Ehm", "E h:mm a" )
, ( "EHm", "E HH:mm" )
, ( "Ehms", "E h:mm:ss a" )
, ( "EHms", "E HH:mm:ss" )
, ( "Gy", "G y" )
, ( "GyMd", "GGGGG y-MM-dd" )
, ( "GyMMM", "G y. 'urteko' MMM" )
, ( "GyMMMd", "G y. 'urteko' MMM d" )
, ( "GyMMMEd", "G y. 'urteko' MMM d, E" )
, ( "h", "h a" )
, ( "H", "HH" )
, ( "hm", "h:mm a" )
, ( "Hm", "HH:mm" )
, ( "hms", "h:mm:ss a" )
, ( "Hms", "HH:mm:ss" )
, ( "hmsv", "h:mm:ss a v" )
, ( "Hmsv", "HH:mm:ss v" )
, ( "hmv", "h:mm a v" )
, ( "Hmv", "HH:mm v" )
, ( "M", "L" )
, ( "Md", "M/d" )
, ( "MEd", "M/d, E" )
, ( "MMM", "LLL" )
, ( "MMMd", "MMM d" )
, ( "MMMEd", "MMM d, E" )
, ( "MMMMd", "MMMM d" )
, ( "MMMMW-count-one", "MMMM W. 'astea'" )
, ( "MMMMW-count-other", "MMMM W. 'astea'" )
, ( "ms", "mm:ss" )
, ( "y", "y" )
, ( "yM", "y/M" )
, ( "yMd", "y/M/d" )
, ( "yMEd", "y/M/d, E" )
, ( "yMMM", "y MMM" )
, ( "yMMMd", "y MMM d" )
, ( "yMMMEd", "y MMM d, E" )
, ( "yMMMM", "y('e')'ko' MMMM" )
, ( "yMMMMd", "y('e')'ko' MMMM'ren' d" )
, ( "yMMMMEd", "y('e')'ko' MMMM'k' d, E" )
, ( "yQQQ", "y('e')'ko' QQQ" )
, ( "yQQQQ", "y('e')'ko' QQQQ" )
, ( "yw-count-one", "Y. 'urteko' w. 'astea'" )
, ( "yw-count-other", "Y. 'urteko' w. 'astea'" )
]
, timeSkeletons =
{ short = "HHmm"
, medium = "HHmmss"
, long = "HHmmssz"
, full = "HHmmsszzzz"
}
}
)
| true | module Generated.Eu exposing (eu)
import Dict exposing (Dict)
import Internal.DayPeriodRule
import Internal.Locale exposing (DateTimeToken(..), LanguageId(..))
import Internal.Parse
import Tagged exposing (Tagged(..))
dayPeriods : Dict String (List Internal.DayPeriodRule.DayPeriodRule)
dayPeriods =
Dict.fromList
[ ( "eu"
, [ Internal.DayPeriodRule.FromBefore ( 12, 0 ) ( 14, 0 ) "afternoon1"
, Internal.DayPeriodRule.FromBefore ( 14, 0 ) ( 19, 0 ) "afternoon2"
, Internal.DayPeriodRule.FromBefore ( 19, 0 ) ( 21, 0 ) "evening1"
, Internal.DayPeriodRule.At ( 0, 0 ) "midnight"
, Internal.DayPeriodRule.FromBefore ( 0, 0 ) ( 6, 0 ) "morning1"
, Internal.DayPeriodRule.FromBefore ( 6, 0 ) ( 12, 0 ) "morning2"
, Internal.DayPeriodRule.FromBefore ( 21, 0 ) ( 24, 0 ) "night1"
]
)
]
{-| Date format strings:
- Short : yy/M/d
- Medium : y('e')'ko' MMM d('a')
- Long : y('e')'ko' MMMM'ren' d('a')
- Full : y('e')'ko' MMMM'ren' d('a'), EEEE
Time format strings:
- Short : HH:mm
- Medium : HH:mm:ss
- Long : HH:mm:ss (z)
- Full : HH:mm:ss (zzzz)
-}
eu : Internal.Locale.Locale
eu =
Maybe.withDefault
Internal.Locale.empty
(Internal.Parse.parse
dayPeriods
{ language = "eu"
, script = Nothing
, territory = Nothing
, variant = Nothing
, periodNames =
{ abbreviated =
{ am = "AM"
, pm = "PM"
, dayPeriods =
Dict.fromList
[ ( "afternoon1", "eguerd." )
, ( "afternoon2", "arrats." )
, ( "evening1", "iluntz." )
, ( "midnight", "gauerdia" )
, ( "morning1", "goizald." )
, ( "morning2", "goizeko" )
, ( "night1", "gaueko" )
]
}
, wide =
{ am = "AM"
, pm = "PM"
, dayPeriods =
Dict.fromList
[ ( "afternoon1", "eguerdiko" )
, ( "afternoon2", "arratsaldeko" )
, ( "evening1", "iluntzeko" )
, ( "midnight", "gauerdia" )
, ( "morning1", "goizaldeko" )
, ( "morning2", "goizeko" )
, ( "night1", "gaueko" )
]
}
, narrow =
{ am = "g"
, pm = "a"
, dayPeriods =
Dict.fromList
[ ( "afternoon1", "eguerd." )
, ( "afternoon2", "arrats." )
, ( "evening1", "iluntz." )
, ( "midnight", "gauerdia" )
, ( "morning1", "goizald." )
, ( "morning2", "goizeko" )
, ( "night1", "gaueko" )
]
}
}
, datePatterns =
{ short = "yy/M/d"
, medium = "y('e')'ko' MMM d('a')"
, long = "y('e')'ko' MMMM'ren' d('a')"
, full = "y('e')'ko' MMMM'ren' d('a'), EEEE"
}
, monthFormatNames =
{ abbreviated =
{ jan = "urt."
, feb = "ots."
, mar = "mar."
, apr = "api."
, may = "mai."
, jun = "eka."
, jul = "uzt."
, aug = "abu."
, sep = "ira."
, oct = "urr."
, nov = "aza."
, dec = "abe."
}
, wide =
{ jan = "urtPI:NAME:<NAME>END_PI"
, feb = "otsailak"
, mar = "PI:NAME:<NAME>END_PI"
, apr = "apirilak"
, may = "maiatzak"
, jun = "ekainak"
, jul = "uztailak"
, aug = "abuztuak"
, sep = "irailak"
, oct = "urriak"
, nov = "azaroak"
, dec = "abenduak"
}
, narrow =
{ jan = "U"
, feb = "O"
, mar = "M"
, apr = "A"
, may = "M"
, jun = "E"
, jul = "U"
, aug = "A"
, sep = "I"
, oct = "U"
, nov = "A"
, dec = "A"
}
}
, monthStandaloneNames =
{ abbreviated =
{ jan = "urt."
, feb = "ots."
, mar = "mar."
, apr = "api."
, may = "mai."
, jun = "eka."
, jul = "uzt."
, aug = "abu."
, sep = "ira."
, oct = "urr."
, nov = "aza."
, dec = "abe."
}
, wide =
{ jan = "urtPI:NAME:<NAME>END_PI"
, feb = "otsaila"
, mar = "PI:NAME:<NAME>END_PI"
, apr = "apirila"
, may = "maiatza"
, jun = "ekaina"
, jul = "uztaila"
, aug = "abuztua"
, sep = "iraila"
, oct = "urria"
, nov = "azaroa"
, dec = "abendua"
}
, narrow =
{ jan = "U"
, feb = "O"
, mar = "M"
, apr = "A"
, may = "M"
, jun = "E"
, jul = "U"
, aug = "A"
, sep = "I"
, oct = "U"
, nov = "A"
, dec = "A"
}
}
, weekdayFormatNames =
{ abbreviated =
{ sun = "ig."
, mon = "al."
, tue = "ar."
, wed = "az."
, thu = "og."
, fri = "or."
, sat = "lr."
}
, wide =
{ sun = "igandea"
, mon = "astelehena"
, tue = "asteartea"
, wed = "asteazkena"
, thu = "osteguna"
, fri = "ostirala"
, sat = "larunbata"
}
, narrow =
{ sun = "I"
, mon = "A"
, tue = "A"
, wed = "A"
, thu = "O"
, fri = "O"
, sat = "L"
}
}
, weekdayStandaloneNames =
{ abbreviated =
{ sun = "ig."
, mon = "al."
, tue = "ar."
, wed = "az."
, thu = "og."
, fri = "or."
, sat = "lr."
}
, wide =
{ sun = "igandea"
, mon = "astelehena"
, tue = "asteartea"
, wed = "asteazkena"
, thu = "osteguna"
, fri = "ostirala"
, sat = "larunbata"
}
, narrow =
{ sun = "I"
, mon = "A"
, tue = "A"
, wed = "A"
, thu = "O"
, fri = "O"
, sat = "L"
}
}
, eraNames =
{ abbreviated = { bc = "K.a.", ad = "K.o." }
, wide = { bc = "PI:NAME:<NAME>END_PI.", ad = "KPI:NAME:<NAME>END_PI ondPI:NAME:<NAME>END_PI" }
, narrow = { bc = "a", ad = "o" }
}
, timePatterns =
{ short = "HH:mm"
, medium = "HH:mm:ss"
, long = "HH:mm:ss (z)"
, full = "HH:mm:ss (zzzz)"
}
, dateTimePatterns =
{ short = "{1} {0}"
, medium = "{1} {0}"
, long = "{1} {0}"
, full = "{1} {0}"
}
, availableFormats =
[ ( "Bh", "B h" )
, ( "Bhm", "B h:mm" )
, ( "Bhms", "B h:mm:ss" )
, ( "d", "d" )
, ( "E", "ccc" )
, ( "EBhm", "E B h:mm" )
, ( "EBhms", "E B h:mm:ss" )
, ( "Ed", "d, E" )
, ( "Ehm", "E h:mm a" )
, ( "EHm", "E HH:mm" )
, ( "Ehms", "E h:mm:ss a" )
, ( "EHms", "E HH:mm:ss" )
, ( "Gy", "G y" )
, ( "GyMd", "GGGGG y-MM-dd" )
, ( "GyMMM", "G y. 'urteko' MMM" )
, ( "GyMMMd", "G y. 'urteko' MMM d" )
, ( "GyMMMEd", "G y. 'urteko' MMM d, E" )
, ( "h", "h a" )
, ( "H", "HH" )
, ( "hm", "h:mm a" )
, ( "Hm", "HH:mm" )
, ( "hms", "h:mm:ss a" )
, ( "Hms", "HH:mm:ss" )
, ( "hmsv", "h:mm:ss a v" )
, ( "Hmsv", "HH:mm:ss v" )
, ( "hmv", "h:mm a v" )
, ( "Hmv", "HH:mm v" )
, ( "M", "L" )
, ( "Md", "M/d" )
, ( "MEd", "M/d, E" )
, ( "MMM", "LLL" )
, ( "MMMd", "MMM d" )
, ( "MMMEd", "MMM d, E" )
, ( "MMMMd", "MMMM d" )
, ( "MMMMW-count-one", "MMMM W. 'astea'" )
, ( "MMMMW-count-other", "MMMM W. 'astea'" )
, ( "ms", "mm:ss" )
, ( "y", "y" )
, ( "yM", "y/M" )
, ( "yMd", "y/M/d" )
, ( "yMEd", "y/M/d, E" )
, ( "yMMM", "y MMM" )
, ( "yMMMd", "y MMM d" )
, ( "yMMMEd", "y MMM d, E" )
, ( "yMMMM", "y('e')'ko' MMMM" )
, ( "yMMMMd", "y('e')'ko' MMMM'ren' d" )
, ( "yMMMMEd", "y('e')'ko' MMMM'k' d, E" )
, ( "yQQQ", "y('e')'ko' QQQ" )
, ( "yQQQQ", "y('e')'ko' QQQQ" )
, ( "yw-count-one", "Y. 'urteko' w. 'astea'" )
, ( "yw-count-other", "Y. 'urteko' w. 'astea'" )
]
, timeSkeletons =
{ short = "HHmm"
, medium = "HHmmss"
, long = "HHmmssz"
, full = "HHmmsszzzz"
}
}
)
| elm |
[
{
"context": " Traversal.some Traversal.list (\\p -> p.name == \"Jeff\")\n\n jeffsAges : Traversal (List Person) Int\n ",
"end": 556,
"score": 0.999673605,
"start": 552,
"tag": "NAME",
"value": "Jeff"
},
{
"context": "e Traversal.list (\\person -> person.firstName == 'Paul' )\n\n paulsHairColor : Traversal (List Person) ",
"end": 2347,
"score": 0.9997560978,
"start": 2343,
"tag": "NAME",
"value": "Paul"
},
{
"context": " pauls\n\n lightenPauls [\n { firstName = \"Paul\"\n , hairColor = \"brown\"\n },\n ",
"end": 2727,
"score": 0.9997370243,
"start": 2723,
"tag": "NAME",
"value": "Paul"
},
{
"context": "Color = \"brown\"\n },\n { firstName = \"Jake\"\n , hairColor = \"blond\"\n }\n ] ==",
"end": 2797,
"score": 0.9997581244,
"start": 2793,
"tag": "NAME",
"value": "Jake"
},
{
"context": "lond\"\n }\n ] == [\n { firstName = \"Paul\"\n , hairColor = \"light brown\"\n },\n ",
"end": 2877,
"score": 0.9997481108,
"start": 2873,
"tag": "NAME",
"value": "Paul"
},
{
"context": "= \"light brown\"\n },\n { firstName = \"Jake\"\n , hairColor = \"blond\"\n }\n ]\n\n-",
"end": 2953,
"score": 0.9997517467,
"start": 2949,
"tag": "NAME",
"value": "Jake"
}
] | src/Monocle/Traversal.elm | crianonim/elm-monocle | 165 | module Monocle.Traversal exposing
( Traversal
, list, array, some, modify
)
{-| A Traversal is like an Optional that may modify multiple sub-elements, keeping the overlaying structure as is.
# Definition
@docs Traversal
# Example
personsAge : Lens Person Int
personsAge =
let
get a =
a.age
set b a =
{ a | age = b }
in
Lens get set
jeffs : Traversal (List Person) Person
jeffs =
Traversal.some Traversal.list (\p -> p.name == "Jeff")
jeffsAges : Traversal (List Person) Int
jeffsAges =
jeffs
|> Compose.traversalWithLens personsAge
# Derived methods
@docs list, array, some, modify
-}
import Array exposing (Array)
{-| To create a Traversal, you just need to provide a function
that applies a transformation function to some or all elements
in the parent structure.
-}
type alias Traversal a b =
(b -> b) -> a -> a
{-| A basic traversal that affects all elements in a list
-}
list : Traversal (List a) a
list =
List.map
{-| A basic traversal that affects all elements in an array
-}
array : Traversal (Array a) a
array =
Array.map
{-| A traversal that, given another traversal as base, only affects
those traversed elements that satisfy a condition.
numbers : Traversal (List number) number
numbers =
Traversal.list
oddNumbers : Traversal (List number) number
oddNumbers =
Traversal.some numbers (\number -> remainderBy 2 number == 1)
evenNumbers : Traversal (List number) number
evenNumbers =
Traversal.some numbers (\number -> remainderBy 2 number == 0)
-}
some : Traversal a b -> (b -> Bool) -> Traversal a b
some traversal condition transformation =
let
conditionedTransformation value =
if condition value then
transformation value
else
value
in
traversal conditionedTransformation
{-| Modifies all elements traversed by `Traversal a b` using function
`(b -> b)` in structure `a`
personsHairColor : Lens Person String
personsHairColor =
Lens .hairColor (\b a-> { a | hairColor = b })
pauls : Traversal (List Person) Person
pauls =
Traversal.some Traversal.list (\person -> person.firstName == 'Paul' )
paulsHairColor : Traversal (List Person) String
paulsHairColor =
pauls
|> Compose.traversalWithLens personsHairColor
lighten : String -> String
lighten hairColor =
"light " ++ hairColor
lightenPauls : List Person -> List Person
lightenPauls =
Traversal.modify pauls
lightenPauls [
{ firstName = "Paul"
, hairColor = "brown"
},
{ firstName = "Jake"
, hairColor = "blond"
}
] == [
{ firstName = "Paul"
, hairColor = "light brown"
},
{ firstName = "Jake"
, hairColor = "blond"
}
]
-}
modify : Traversal a b -> (b -> b) -> a -> a
modify traversal =
traversal
| 29715 | module Monocle.Traversal exposing
( Traversal
, list, array, some, modify
)
{-| A Traversal is like an Optional that may modify multiple sub-elements, keeping the overlaying structure as is.
# Definition
@docs Traversal
# Example
personsAge : Lens Person Int
personsAge =
let
get a =
a.age
set b a =
{ a | age = b }
in
Lens get set
jeffs : Traversal (List Person) Person
jeffs =
Traversal.some Traversal.list (\p -> p.name == "<NAME>")
jeffsAges : Traversal (List Person) Int
jeffsAges =
jeffs
|> Compose.traversalWithLens personsAge
# Derived methods
@docs list, array, some, modify
-}
import Array exposing (Array)
{-| To create a Traversal, you just need to provide a function
that applies a transformation function to some or all elements
in the parent structure.
-}
type alias Traversal a b =
(b -> b) -> a -> a
{-| A basic traversal that affects all elements in a list
-}
list : Traversal (List a) a
list =
List.map
{-| A basic traversal that affects all elements in an array
-}
array : Traversal (Array a) a
array =
Array.map
{-| A traversal that, given another traversal as base, only affects
those traversed elements that satisfy a condition.
numbers : Traversal (List number) number
numbers =
Traversal.list
oddNumbers : Traversal (List number) number
oddNumbers =
Traversal.some numbers (\number -> remainderBy 2 number == 1)
evenNumbers : Traversal (List number) number
evenNumbers =
Traversal.some numbers (\number -> remainderBy 2 number == 0)
-}
some : Traversal a b -> (b -> Bool) -> Traversal a b
some traversal condition transformation =
let
conditionedTransformation value =
if condition value then
transformation value
else
value
in
traversal conditionedTransformation
{-| Modifies all elements traversed by `Traversal a b` using function
`(b -> b)` in structure `a`
personsHairColor : Lens Person String
personsHairColor =
Lens .hairColor (\b a-> { a | hairColor = b })
pauls : Traversal (List Person) Person
pauls =
Traversal.some Traversal.list (\person -> person.firstName == '<NAME>' )
paulsHairColor : Traversal (List Person) String
paulsHairColor =
pauls
|> Compose.traversalWithLens personsHairColor
lighten : String -> String
lighten hairColor =
"light " ++ hairColor
lightenPauls : List Person -> List Person
lightenPauls =
Traversal.modify pauls
lightenPauls [
{ firstName = "<NAME>"
, hairColor = "brown"
},
{ firstName = "<NAME>"
, hairColor = "blond"
}
] == [
{ firstName = "<NAME>"
, hairColor = "light brown"
},
{ firstName = "<NAME>"
, hairColor = "blond"
}
]
-}
modify : Traversal a b -> (b -> b) -> a -> a
modify traversal =
traversal
| true | module Monocle.Traversal exposing
( Traversal
, list, array, some, modify
)
{-| A Traversal is like an Optional that may modify multiple sub-elements, keeping the overlaying structure as is.
# Definition
@docs Traversal
# Example
personsAge : Lens Person Int
personsAge =
let
get a =
a.age
set b a =
{ a | age = b }
in
Lens get set
jeffs : Traversal (List Person) Person
jeffs =
Traversal.some Traversal.list (\p -> p.name == "PI:NAME:<NAME>END_PI")
jeffsAges : Traversal (List Person) Int
jeffsAges =
jeffs
|> Compose.traversalWithLens personsAge
# Derived methods
@docs list, array, some, modify
-}
import Array exposing (Array)
{-| To create a Traversal, you just need to provide a function
that applies a transformation function to some or all elements
in the parent structure.
-}
type alias Traversal a b =
(b -> b) -> a -> a
{-| A basic traversal that affects all elements in a list
-}
list : Traversal (List a) a
list =
List.map
{-| A basic traversal that affects all elements in an array
-}
array : Traversal (Array a) a
array =
Array.map
{-| A traversal that, given another traversal as base, only affects
those traversed elements that satisfy a condition.
numbers : Traversal (List number) number
numbers =
Traversal.list
oddNumbers : Traversal (List number) number
oddNumbers =
Traversal.some numbers (\number -> remainderBy 2 number == 1)
evenNumbers : Traversal (List number) number
evenNumbers =
Traversal.some numbers (\number -> remainderBy 2 number == 0)
-}
some : Traversal a b -> (b -> Bool) -> Traversal a b
some traversal condition transformation =
let
conditionedTransformation value =
if condition value then
transformation value
else
value
in
traversal conditionedTransformation
{-| Modifies all elements traversed by `Traversal a b` using function
`(b -> b)` in structure `a`
personsHairColor : Lens Person String
personsHairColor =
Lens .hairColor (\b a-> { a | hairColor = b })
pauls : Traversal (List Person) Person
pauls =
Traversal.some Traversal.list (\person -> person.firstName == 'PI:NAME:<NAME>END_PI' )
paulsHairColor : Traversal (List Person) String
paulsHairColor =
pauls
|> Compose.traversalWithLens personsHairColor
lighten : String -> String
lighten hairColor =
"light " ++ hairColor
lightenPauls : List Person -> List Person
lightenPauls =
Traversal.modify pauls
lightenPauls [
{ firstName = "PI:NAME:<NAME>END_PI"
, hairColor = "brown"
},
{ firstName = "PI:NAME:<NAME>END_PI"
, hairColor = "blond"
}
] == [
{ firstName = "PI:NAME:<NAME>END_PI"
, hairColor = "light brown"
},
{ firstName = "PI:NAME:<NAME>END_PI"
, hairColor = "blond"
}
]
-}
modify : Traversal a b -> (b -> b) -> a -> a
modify traversal =
traversal
| elm |
[
{
"context": "lename}} {{lastname}}!\"}\"\"\"\n \"Hello Joe Bob Bloggs!\"\n (\\translations -> Translations.",
"end": 782,
"score": 0.9996370077,
"start": 768,
"tag": "NAME",
"value": "Joe Bob Bloggs"
},
{
"context": "ons -> Translations.helloWithParams translations \"Joe\" \"Bob\" \"Bloggs\")\n , test \"Handles message ",
"end": 865,
"score": 0.999814868,
"start": 862,
"tag": "NAME",
"value": "Joe"
},
{
"context": " Translations.helloWithParams translations \"Joe\" \"Bob\" \"Bloggs\")\n , test \"Handles message with p",
"end": 871,
"score": 0.9977278113,
"start": 868,
"tag": "NAME",
"value": "Bob"
},
{
"context": "lations.helloWithParams translations \"Joe\" \"Bob\" \"Bloggs\")\n , test \"Handles message with placeholde",
"end": 880,
"score": 0.9721936584,
"start": 874,
"tag": "NAME",
"value": "Bloggs"
},
{
"context": "greetName\": \"Hi {{name}}\"}}\"\"\"\n \"Hi Peter\"\n (\\translations -> Translations.G",
"end": 1049,
"score": 0.9996964335,
"start": 1044,
"tag": "NAME",
"value": "Peter"
},
{
"context": "-> Translations.Greetings.greetName translations \"Peter\")\n ]\n\n\nrunTest : String -> String -> (I18N",
"end": 1137,
"score": 0.9991886616,
"start": 1132,
"tag": "NAME",
"value": "Peter"
}
] | elm-sandbox/tests/TestTranslations.elm | AircastDev/elm-i18next-gen | 19 | module TestTranslations exposing (..)
import Expect exposing (Expectation)
import I18Next
import Json.Decode as JD
import Test exposing (..)
import Translations
import Translations.Greetings
suite : Test
suite =
describe "Translations"
[ test "Handles message with no placeholder in top-level module" <|
runTest """{"hello": "Hello"}""" "Hello" Translations.hello
, test "Handles message with no placeholder in nested module" <|
runTest """{"greetings": {"goodDay": "Good day."}}""" "Good day." Translations.Greetings.goodDay
, test "Handles message with placeholders in top-level module" <|
runTest """{"helloWithParams": "Hello {{firstname}} {{middlename}} {{lastname}}!"}"""
"Hello Joe Bob Bloggs!"
(\translations -> Translations.helloWithParams translations "Joe" "Bob" "Bloggs")
, test "Handles message with placeholders in nested module" <|
runTest """{"greetings": {"greetName": "Hi {{name}}"}}"""
"Hi Peter"
(\translations -> Translations.Greetings.greetName translations "Peter")
]
runTest : String -> String -> (I18Next.Translations -> String) -> (() -> Expectation)
runTest json expected translationFn =
\_ -> Expect.equal expected (translationFn (jsonToTranslations json))
jsonToTranslations : String -> I18Next.Translations
jsonToTranslations json =
JD.decodeString I18Next.translationsDecoder json
|> Result.withDefault I18Next.initialTranslations
| 26258 | module TestTranslations exposing (..)
import Expect exposing (Expectation)
import I18Next
import Json.Decode as JD
import Test exposing (..)
import Translations
import Translations.Greetings
suite : Test
suite =
describe "Translations"
[ test "Handles message with no placeholder in top-level module" <|
runTest """{"hello": "Hello"}""" "Hello" Translations.hello
, test "Handles message with no placeholder in nested module" <|
runTest """{"greetings": {"goodDay": "Good day."}}""" "Good day." Translations.Greetings.goodDay
, test "Handles message with placeholders in top-level module" <|
runTest """{"helloWithParams": "Hello {{firstname}} {{middlename}} {{lastname}}!"}"""
"Hello <NAME>!"
(\translations -> Translations.helloWithParams translations "<NAME>" "<NAME>" "<NAME>")
, test "Handles message with placeholders in nested module" <|
runTest """{"greetings": {"greetName": "Hi {{name}}"}}"""
"Hi <NAME>"
(\translations -> Translations.Greetings.greetName translations "<NAME>")
]
runTest : String -> String -> (I18Next.Translations -> String) -> (() -> Expectation)
runTest json expected translationFn =
\_ -> Expect.equal expected (translationFn (jsonToTranslations json))
jsonToTranslations : String -> I18Next.Translations
jsonToTranslations json =
JD.decodeString I18Next.translationsDecoder json
|> Result.withDefault I18Next.initialTranslations
| true | module TestTranslations exposing (..)
import Expect exposing (Expectation)
import I18Next
import Json.Decode as JD
import Test exposing (..)
import Translations
import Translations.Greetings
suite : Test
suite =
describe "Translations"
[ test "Handles message with no placeholder in top-level module" <|
runTest """{"hello": "Hello"}""" "Hello" Translations.hello
, test "Handles message with no placeholder in nested module" <|
runTest """{"greetings": {"goodDay": "Good day."}}""" "Good day." Translations.Greetings.goodDay
, test "Handles message with placeholders in top-level module" <|
runTest """{"helloWithParams": "Hello {{firstname}} {{middlename}} {{lastname}}!"}"""
"Hello PI:NAME:<NAME>END_PI!"
(\translations -> Translations.helloWithParams translations "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI")
, test "Handles message with placeholders in nested module" <|
runTest """{"greetings": {"greetName": "Hi {{name}}"}}"""
"Hi PI:NAME:<NAME>END_PI"
(\translations -> Translations.Greetings.greetName translations "PI:NAME:<NAME>END_PI")
]
runTest : String -> String -> (I18Next.Translations -> String) -> (() -> Expectation)
runTest json expected translationFn =
\_ -> Expect.equal expected (translationFn (jsonToTranslations json))
jsonToTranslations : String -> I18Next.Translations
jsonToTranslations json =
JD.decodeString I18Next.translationsDecoder json
|> Result.withDefault I18Next.initialTranslations
| elm |
[
{
"context": "auto-generated by Graphqelm\n-- https://github.com/dillonkearns/graphqelm\n\n\nmodule Api.Enum.UserOrderByInput expo",
"end": 104,
"score": 0.9995831847,
"start": 92,
"tag": "USERNAME",
"value": "dillonkearns"
},
{
"context": "email_DESC\"\n\n Password_ASC ->\n \"password_ASC\"\n\n Password_DESC ->\n \"password_",
"end": 3558,
"score": 0.6825945377,
"start": 3546,
"tag": "PASSWORD",
"value": "password_ASC"
},
{
"context": "sword_ASC\"\n\n Password_DESC ->\n \"password_DESC\"\n\n ResetToken_ASC ->\n \"resetTok",
"end": 3612,
"score": 0.7006413341,
"start": 3599,
"tag": "PASSWORD",
"value": "password_DESC"
}
] | src/api/Api/Enum/UserOrderByInput.elm | wking-io/watchword | 1 | -- Do not manually edit this file, it was auto-generated by Graphqelm
-- https://github.com/dillonkearns/graphqelm
module Api.Enum.UserOrderByInput exposing (..)
import Json.Decode as Decode exposing (Decoder)
{-|
- Id_ASC -
- Id_DESC -
- CreatedAt_ASC -
- CreatedAt_DESC -
- UpdatedAt_ASC -
- UpdatedAt_DESC -
- Name_ASC -
- Name_DESC -
- Email_ASC -
- Email_DESC -
- Password_ASC -
- Password_DESC -
- ResetToken_ASC -
- ResetToken_DESC -
- ResetExpires_ASC -
- ResetExpires_DESC -
- Role_ASC -
- Role_DESC -
-}
type UserOrderByInput
= Id_ASC
| Id_DESC
| CreatedAt_ASC
| CreatedAt_DESC
| UpdatedAt_ASC
| UpdatedAt_DESC
| Name_ASC
| Name_DESC
| Email_ASC
| Email_DESC
| Password_ASC
| Password_DESC
| ResetToken_ASC
| ResetToken_DESC
| ResetExpires_ASC
| ResetExpires_DESC
| Role_ASC
| Role_DESC
decoder : Decoder UserOrderByInput
decoder =
Decode.string
|> Decode.andThen
(\string ->
case string of
"id_ASC" ->
Decode.succeed Id_ASC
"id_DESC" ->
Decode.succeed Id_DESC
"createdAt_ASC" ->
Decode.succeed CreatedAt_ASC
"createdAt_DESC" ->
Decode.succeed CreatedAt_DESC
"updatedAt_ASC" ->
Decode.succeed UpdatedAt_ASC
"updatedAt_DESC" ->
Decode.succeed UpdatedAt_DESC
"name_ASC" ->
Decode.succeed Name_ASC
"name_DESC" ->
Decode.succeed Name_DESC
"email_ASC" ->
Decode.succeed Email_ASC
"email_DESC" ->
Decode.succeed Email_DESC
"password_ASC" ->
Decode.succeed Password_ASC
"password_DESC" ->
Decode.succeed Password_DESC
"resetToken_ASC" ->
Decode.succeed ResetToken_ASC
"resetToken_DESC" ->
Decode.succeed ResetToken_DESC
"resetExpires_ASC" ->
Decode.succeed ResetExpires_ASC
"resetExpires_DESC" ->
Decode.succeed ResetExpires_DESC
"role_ASC" ->
Decode.succeed Role_ASC
"role_DESC" ->
Decode.succeed Role_DESC
_ ->
Decode.fail ("Invalid UserOrderByInput type, " ++ string ++ " try re-running the graphqelm CLI ")
)
{-| Convert from the union type representating the Enum to a string that the GraphQL server will recognize.
-}
toString : UserOrderByInput -> String
toString enum =
case enum of
Id_ASC ->
"id_ASC"
Id_DESC ->
"id_DESC"
CreatedAt_ASC ->
"createdAt_ASC"
CreatedAt_DESC ->
"createdAt_DESC"
UpdatedAt_ASC ->
"updatedAt_ASC"
UpdatedAt_DESC ->
"updatedAt_DESC"
Name_ASC ->
"name_ASC"
Name_DESC ->
"name_DESC"
Email_ASC ->
"email_ASC"
Email_DESC ->
"email_DESC"
Password_ASC ->
"password_ASC"
Password_DESC ->
"password_DESC"
ResetToken_ASC ->
"resetToken_ASC"
ResetToken_DESC ->
"resetToken_DESC"
ResetExpires_ASC ->
"resetExpires_ASC"
ResetExpires_DESC ->
"resetExpires_DESC"
Role_ASC ->
"role_ASC"
Role_DESC ->
"role_DESC"
| 35319 | -- Do not manually edit this file, it was auto-generated by Graphqelm
-- https://github.com/dillonkearns/graphqelm
module Api.Enum.UserOrderByInput exposing (..)
import Json.Decode as Decode exposing (Decoder)
{-|
- Id_ASC -
- Id_DESC -
- CreatedAt_ASC -
- CreatedAt_DESC -
- UpdatedAt_ASC -
- UpdatedAt_DESC -
- Name_ASC -
- Name_DESC -
- Email_ASC -
- Email_DESC -
- Password_ASC -
- Password_DESC -
- ResetToken_ASC -
- ResetToken_DESC -
- ResetExpires_ASC -
- ResetExpires_DESC -
- Role_ASC -
- Role_DESC -
-}
type UserOrderByInput
= Id_ASC
| Id_DESC
| CreatedAt_ASC
| CreatedAt_DESC
| UpdatedAt_ASC
| UpdatedAt_DESC
| Name_ASC
| Name_DESC
| Email_ASC
| Email_DESC
| Password_ASC
| Password_DESC
| ResetToken_ASC
| ResetToken_DESC
| ResetExpires_ASC
| ResetExpires_DESC
| Role_ASC
| Role_DESC
decoder : Decoder UserOrderByInput
decoder =
Decode.string
|> Decode.andThen
(\string ->
case string of
"id_ASC" ->
Decode.succeed Id_ASC
"id_DESC" ->
Decode.succeed Id_DESC
"createdAt_ASC" ->
Decode.succeed CreatedAt_ASC
"createdAt_DESC" ->
Decode.succeed CreatedAt_DESC
"updatedAt_ASC" ->
Decode.succeed UpdatedAt_ASC
"updatedAt_DESC" ->
Decode.succeed UpdatedAt_DESC
"name_ASC" ->
Decode.succeed Name_ASC
"name_DESC" ->
Decode.succeed Name_DESC
"email_ASC" ->
Decode.succeed Email_ASC
"email_DESC" ->
Decode.succeed Email_DESC
"password_ASC" ->
Decode.succeed Password_ASC
"password_DESC" ->
Decode.succeed Password_DESC
"resetToken_ASC" ->
Decode.succeed ResetToken_ASC
"resetToken_DESC" ->
Decode.succeed ResetToken_DESC
"resetExpires_ASC" ->
Decode.succeed ResetExpires_ASC
"resetExpires_DESC" ->
Decode.succeed ResetExpires_DESC
"role_ASC" ->
Decode.succeed Role_ASC
"role_DESC" ->
Decode.succeed Role_DESC
_ ->
Decode.fail ("Invalid UserOrderByInput type, " ++ string ++ " try re-running the graphqelm CLI ")
)
{-| Convert from the union type representating the Enum to a string that the GraphQL server will recognize.
-}
toString : UserOrderByInput -> String
toString enum =
case enum of
Id_ASC ->
"id_ASC"
Id_DESC ->
"id_DESC"
CreatedAt_ASC ->
"createdAt_ASC"
CreatedAt_DESC ->
"createdAt_DESC"
UpdatedAt_ASC ->
"updatedAt_ASC"
UpdatedAt_DESC ->
"updatedAt_DESC"
Name_ASC ->
"name_ASC"
Name_DESC ->
"name_DESC"
Email_ASC ->
"email_ASC"
Email_DESC ->
"email_DESC"
Password_ASC ->
"<PASSWORD>"
Password_DESC ->
"<PASSWORD>"
ResetToken_ASC ->
"resetToken_ASC"
ResetToken_DESC ->
"resetToken_DESC"
ResetExpires_ASC ->
"resetExpires_ASC"
ResetExpires_DESC ->
"resetExpires_DESC"
Role_ASC ->
"role_ASC"
Role_DESC ->
"role_DESC"
| true | -- Do not manually edit this file, it was auto-generated by Graphqelm
-- https://github.com/dillonkearns/graphqelm
module Api.Enum.UserOrderByInput exposing (..)
import Json.Decode as Decode exposing (Decoder)
{-|
- Id_ASC -
- Id_DESC -
- CreatedAt_ASC -
- CreatedAt_DESC -
- UpdatedAt_ASC -
- UpdatedAt_DESC -
- Name_ASC -
- Name_DESC -
- Email_ASC -
- Email_DESC -
- Password_ASC -
- Password_DESC -
- ResetToken_ASC -
- ResetToken_DESC -
- ResetExpires_ASC -
- ResetExpires_DESC -
- Role_ASC -
- Role_DESC -
-}
type UserOrderByInput
= Id_ASC
| Id_DESC
| CreatedAt_ASC
| CreatedAt_DESC
| UpdatedAt_ASC
| UpdatedAt_DESC
| Name_ASC
| Name_DESC
| Email_ASC
| Email_DESC
| Password_ASC
| Password_DESC
| ResetToken_ASC
| ResetToken_DESC
| ResetExpires_ASC
| ResetExpires_DESC
| Role_ASC
| Role_DESC
decoder : Decoder UserOrderByInput
decoder =
Decode.string
|> Decode.andThen
(\string ->
case string of
"id_ASC" ->
Decode.succeed Id_ASC
"id_DESC" ->
Decode.succeed Id_DESC
"createdAt_ASC" ->
Decode.succeed CreatedAt_ASC
"createdAt_DESC" ->
Decode.succeed CreatedAt_DESC
"updatedAt_ASC" ->
Decode.succeed UpdatedAt_ASC
"updatedAt_DESC" ->
Decode.succeed UpdatedAt_DESC
"name_ASC" ->
Decode.succeed Name_ASC
"name_DESC" ->
Decode.succeed Name_DESC
"email_ASC" ->
Decode.succeed Email_ASC
"email_DESC" ->
Decode.succeed Email_DESC
"password_ASC" ->
Decode.succeed Password_ASC
"password_DESC" ->
Decode.succeed Password_DESC
"resetToken_ASC" ->
Decode.succeed ResetToken_ASC
"resetToken_DESC" ->
Decode.succeed ResetToken_DESC
"resetExpires_ASC" ->
Decode.succeed ResetExpires_ASC
"resetExpires_DESC" ->
Decode.succeed ResetExpires_DESC
"role_ASC" ->
Decode.succeed Role_ASC
"role_DESC" ->
Decode.succeed Role_DESC
_ ->
Decode.fail ("Invalid UserOrderByInput type, " ++ string ++ " try re-running the graphqelm CLI ")
)
{-| Convert from the union type representating the Enum to a string that the GraphQL server will recognize.
-}
toString : UserOrderByInput -> String
toString enum =
case enum of
Id_ASC ->
"id_ASC"
Id_DESC ->
"id_DESC"
CreatedAt_ASC ->
"createdAt_ASC"
CreatedAt_DESC ->
"createdAt_DESC"
UpdatedAt_ASC ->
"updatedAt_ASC"
UpdatedAt_DESC ->
"updatedAt_DESC"
Name_ASC ->
"name_ASC"
Name_DESC ->
"name_DESC"
Email_ASC ->
"email_ASC"
Email_DESC ->
"email_DESC"
Password_ASC ->
"PI:PASSWORD:<PASSWORD>END_PI"
Password_DESC ->
"PI:PASSWORD:<PASSWORD>END_PI"
ResetToken_ASC ->
"resetToken_ASC"
ResetToken_DESC ->
"resetToken_DESC"
ResetExpires_ASC ->
"resetExpires_ASC"
ResetExpires_DESC ->
"resetExpires_DESC"
Role_ASC ->
"role_ASC"
Role_DESC ->
"role_DESC"
| elm |
[
{
"context": "using DevRandom module.\n-- Copyright (c) 2017-2018 Bill St. Clair <billstclair@gmail.com>\n-- Some rights reserved.\n",
"end": 192,
"score": 0.9998609424,
"start": 178,
"tag": "NAME",
"value": "Bill St. Clair"
},
{
"context": "odule.\n-- Copyright (c) 2017-2018 Bill St. Clair <billstclair@gmail.com>\n-- Some rights reserved.\n-- Distributed under th",
"end": 215,
"score": 0.9999276996,
"start": 194,
"tag": "EMAIL",
"value": "billstclair@gmail.com"
},
{
"context": "ode: \"\n , a [ href \"https://github.com/billstclair/elm-dev-random\" ]\n [ text \"github.",
"end": 30765,
"score": 0.9975352287,
"start": 30754,
"tag": "USERNAME",
"value": "billstclair"
},
{
"context": "-dev-random\" ]\n [ text \"github.com/billstclair/elm-dev-random\" ]\n , br\n , ",
"end": 30830,
"score": 0.9988017082,
"start": 30819,
"tag": "USERNAME",
"value": "billstclair"
},
{
"context": " , br\n , text \"Copyright 2017-2018 Bill St. Clair\"\n ]\n ]\n\n\nnumberSelector : Int -",
"end": 30920,
"score": 0.9996038675,
"start": 30906,
"tag": "NAME",
"value": "Bill St. Clair"
}
] | example/Main.elm | billstclair/elm-dev-random | 3 | ---------------------------------------------------------------------
--
-- Main.elm
-- User interface for Diceware example of using DevRandom module.
-- Copyright (c) 2017-2018 Bill St. Clair <billstclair@gmail.com>
-- Some rights reserved.
-- Distributed under the MIT License
-- See LICENSE.txt
--
----------------------------------------------------------------------
port module Main exposing
( Model
, Msg(..)
, init
, update
, view
)
import Array exposing (Array)
import Browser
import Char
import Cmd.Extra exposing (addCmd, addCmds, withCmd, withCmds, withNoCmd)
import Debug exposing (log)
import DicewareStrings
import Dict exposing (Dict)
import Html
exposing
( Attribute
, Html
, a
, button
, div
, h2
, h3
, img
, input
, label
, li
, option
, p
, select
, span
, text
, ul
)
import Html.Attributes
exposing
( alt
, checked
, href
, maxlength
, readonly
, selected
, size
, src
, style
, title
, type_
, value
)
import Html.Events exposing (keyCode, on, onClick, onInput)
import Json.Decode as JD
import Json.Encode as JE exposing (Value)
import List.Extra as LE
import NewDicewareStrings
import PortFunnel exposing (FunnelSpec, GenericMessage, ModuleDesc, StateAccessors)
import PortFunnel.DevRandom as DevRandom
import ShortDicewareStrings
import Time
port cmdPort : Value -> Cmd msg
port subPort : (Value -> msg) -> Sub msg
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.batch
[ subPort Process
, if model.startup then
Time.every 250 Init
else
Sub.none
]
simulatedCmdPort : Value -> Cmd Msg
simulatedCmdPort =
DevRandom.makeSimulatedCmdPort Process
getCmdPort : Model -> (Value -> Cmd Msg)
getCmdPort model =
if model.useSimulator then
simulatedCmdPort
else
cmdPort
type DicewareTable
= OldTable
| NewTable
| ShortTable
type alias Modifications =
{ spaces : Bool
, showTotalLength : Bool
, totalLength : Int
, uppercase : Int
, numbers : Int
, specialChars : Int
}
defaultModifications : Modifications
defaultModifications =
{ spaces = True
, showTotalLength = False
, totalLength = 30
, uppercase = 0
, numbers = 0
, specialChars = 0
}
type RandomReason
= RandomPassphrase
| RandomNumber
type alias FunnelState =
{ random : DevRandom.State }
type alias Model =
{ startup : Bool
, funnelState : FunnelState
, useSimulator : Bool
, randomReason : RandomReason
, countString : String
, count : Int
, strings : List String
, isSecure : Bool
, whichTable : DicewareTable
, diceString : String
, enableModifications : Bool
, modifications : Modifications
, randomMaxString : String
, randomMax : Int
, randomNumber : Int
, error : Maybe String
}
makeInitialModel : Int -> Model
makeInitialModel count =
let
model =
{ startup = True
, funnelState =
{ random = DevRandom.initialState 0 }
, useSimulator = True
, randomReason = RandomPassphrase
, countString = String.fromInt count
, count = count
, strings = []
, isSecure = True
, whichTable = ShortTable
, diceString = ""
, enableModifications = False
, modifications = defaultModifications
, randomMaxString = "100"
, randomMax = 0
, randomNumber = 10
, error = Nothing
}
in
model
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
init : () -> ( Model, Cmd Msg )
init _ =
let
count =
6
model =
makeInitialModel count
in
model |> withNoCmd
generatePassphrase : Model -> ( Model, Cmd Msg )
generatePassphrase model =
{ model | randomReason = RandomPassphrase }
|> withCmd
(DevRandom.GenerateInt (getCount model)
|> DevRandom.send (getCmdPort model)
)
generateNumber : Model -> ( Model, Cmd Msg )
generateNumber model =
{ model | randomReason = RandomNumber }
|> withCmd
(DevRandom.GenerateInt model.randomMax
|> DevRandom.send (getCmdPort model)
)
getDiceCount : Model -> Int
getDiceCount model =
case model.whichTable of
NewTable ->
5
OldTable ->
5
ShortTable ->
4
getCount : Model -> Int
getCount model =
case model.whichTable of
NewTable ->
NewDicewareStrings.count
OldTable ->
DicewareStrings.count
ShortTable ->
ShortDicewareStrings.count
getArray : Model -> Array String
getArray model =
case model.whichTable of
NewTable ->
NewDicewareStrings.array
OldTable ->
DicewareStrings.array
ShortTable ->
ShortDicewareStrings.array
entropyPerDie : DicewareTable -> Float
entropyPerDie table =
case table of
NewTable ->
12.9
OldTable ->
12.9
ShortTable ->
10.3
getEntropy : Model -> Float
getEntropy model =
(toFloat <| List.length model.strings) * entropyPerDie model.whichTable
randomAccessors : StateAccessors FunnelState DevRandom.State
randomAccessors =
StateAccessors .random (\substate state -> { state | random = substate })
type alias AppFunnel substate message response =
FunnelSpec FunnelState substate message response Model Msg
type Funnel
= RandomFunnel (AppFunnel DevRandom.State DevRandom.Message DevRandom.Response)
emptyCommander : (GenericMessage -> Cmd msg) -> response -> Cmd msg
emptyCommander _ _ =
Cmd.none
funnels : Dict String Funnel
funnels =
Dict.fromList
[ ( DevRandom.moduleName
, RandomFunnel <|
FunnelSpec randomAccessors
DevRandom.moduleDesc
emptyCommander
randomHandler
)
]
doIsLoaded : Model -> ( Model, Cmd Msg )
doIsLoaded model =
if model.useSimulator && DevRandom.isLoaded model.funnelState.random then
{ model
| useSimulator = False
, strings = []
}
|> generatePassphrase
else
model |> withNoCmd
randomHandler : DevRandom.Response -> FunnelState -> Model -> ( Model, Cmd Msg )
randomHandler response state mdl =
let
( model, cmd ) =
doIsLoaded
{ mdl | funnelState = state }
in
case response of
DevRandom.RandomIntResponse { isSecure, int } ->
case model.randomReason of
RandomNumber ->
{ model
| isSecure = isSecure
, randomNumber = int + 1
}
|> withCmd cmd
RandomPassphrase ->
let
string =
case Array.get int <| getArray model of
Nothing ->
"a"
Just s ->
s
strings =
string :: model.strings
in
{ model
| strings = strings
, isSecure = isSecure
}
|> (if List.length strings >= model.count then
withCmd cmd
else
generatePassphrase
)
_ ->
model |> withCmd cmd
type Msg
= Init Time.Posix
| UpdateCount String
| UpdateDice String
| DiceKeydown Int
| Generate
| Clear
| Process Value
| LookupDice
| ChangeTable String
| ToggleModifications
| ToggleSpaces
| ToggleShowTotalLength
| UpdateTotalLength String
| UpdateUpperCase String
| UpdateNumbers String
| UpdateSpecialChars String
| RandomMaxDown Int
| UpdateRandomMaxString String
| GenerateRandomNumber
stringToInt : String -> Result String Int
stringToInt string =
case String.toInt string of
Just int ->
Ok int
Nothing ->
Err "invalid integer string"
update : Msg -> Model -> ( Model, Cmd Msg )
update msg modl =
let
model =
{ modl | error = Nothing }
modifications =
model.modifications
in
case msg of
Init _ ->
{ model | startup = False }
|> (if model.useSimulator then
generatePassphrase
else
withNoCmd
)
UpdateCount countString ->
( { model
| countString = countString
, count =
case stringToInt countString of
Ok count ->
max 0 (min count 20)
Err _ ->
0
}
, Cmd.none
)
UpdateDice string ->
( { model
| diceString = string
}
, Cmd.none
)
DiceKeydown keycode ->
( if keycode == 13 then
lookupDice model
else
model
, Cmd.none
)
Generate ->
case model.count of
0 ->
( { model | strings = [] }
, Cmd.none
)
_ ->
{ model | strings = [] }
|> generatePassphrase
Clear ->
( { model
| strings = []
, isSecure = True
}
, Cmd.none
)
Process value ->
case
PortFunnel.processValue funnels
appTrampoline
value
model.funnelState
model
of
Err error ->
{ model | error = Just error } |> withNoCmd
Ok res ->
res
LookupDice ->
( lookupDice model
, Cmd.none
)
ChangeTable table ->
let
oldTable =
model.whichTable
newTable =
stringToTable table
count =
newRollCount newTable model
mdl =
{ model
| whichTable = stringToTable table
, count = count
, countString = String.fromInt count
, strings = []
, diceString = ""
, randomReason = RandomPassphrase
}
in
generatePassphrase mdl
ToggleModifications ->
( { model | enableModifications = not model.enableModifications }
, Cmd.none
)
ToggleSpaces ->
( { model
| modifications =
{ modifications
| spaces = not modifications.spaces
}
}
, Cmd.none
)
ToggleShowTotalLength ->
( { model
| modifications =
{ modifications
| showTotalLength = not modifications.showTotalLength
}
}
, Cmd.none
)
UpdateTotalLength string ->
updateModificationsInt
(if string == "" then
"0"
else
string
)
(\int -> { modifications | totalLength = int })
model
UpdateUpperCase string ->
updateModificationsInt string
(\int -> { modifications | uppercase = int })
model
UpdateNumbers string ->
updateModificationsInt string
(\int -> { modifications | numbers = int })
model
UpdateSpecialChars string ->
updateModificationsInt string
(\int -> { modifications | specialChars = int })
model
-- TODO
RandomMaxDown keycode ->
if keycode == 13 then
update GenerateRandomNumber model
else
model |> withNoCmd
UpdateRandomMaxString string ->
{ model | randomMaxString = string }
|> withNoCmd
GenerateRandomNumber ->
let
mdl =
{ model | randomNumber = 0 }
in
case String.toInt model.randomMaxString of
Nothing ->
mdl |> withNoCmd
Just max ->
if max <= 0 then
mdl |> withNoCmd
else
{ mdl
| randomMax = max
, randomNumber = 0
}
|> generateNumber
appTrampoline : GenericMessage -> Funnel -> FunnelState -> Model -> Result String ( Model, Cmd Msg )
appTrampoline genericMessage funnel state model =
let
theCmdPort =
getCmdPort model
in
case funnel of
RandomFunnel randomFunnel ->
PortFunnel.appProcess theCmdPort
genericMessage
randomFunnel
state
model
updateModificationsInt : String -> (Int -> Modifications) -> Model -> ( Model, Cmd Msg )
updateModificationsInt string setter model =
case stringToInt string of
Err _ ->
model |> withNoCmd
Ok int ->
{ model | modifications = setter int }
|> withNoCmd
newRollCount : DicewareTable -> Model -> Int
newRollCount newTable model =
let
count =
toFloat model.count
perDie =
entropyPerDie model.whichTable
oldEntropy =
count * perDie
newPerDie =
entropyPerDie newTable
in
round <| (oldEntropy / newPerDie)
stringToTable : String -> DicewareTable
stringToTable table =
case table of
"old" ->
OldTable
"new" ->
NewTable
_ ->
ShortTable
dieNum : String -> Int
dieNum string =
case stringToInt string of
Err _ ->
0
Ok n ->
if n < 0 || n > 6 then
0
else
n
computeUserDice : Model -> Maybe (List Int)
computeUserDice model =
let
diceNumber =
getDiceCount model
digits =
List.map String.fromChar <| String.toList model.diceString
in
if diceNumber /= List.length digits then
Nothing
else
Just <|
List.map dieNum digits
lookupDice : Model -> Model
lookupDice model =
case computeUserDice model of
Nothing ->
model
Just dice ->
case LE.find (\x -> x == 0) dice of
Just _ ->
model
Nothing ->
let
count =
model.count
strings =
model.strings
stringsTail =
List.drop
(List.length strings - count + 1)
strings
idx =
List.foldl
(\x y -> (6 * y) + x - 1)
0
dice
string =
case Array.get idx <| getArray model of
Nothing ->
"a"
Just x ->
x
in
{ model
| strings = List.append stringsTail [ string ]
, isSecure = True
, diceString = ""
}
nbsp : String
nbsp =
String.fromList [ Char.fromCode 160 ]
br : Html Msg
br =
Html.br [] []
onKeyDown : (Int -> msg) -> Attribute msg
onKeyDown tagger =
on "keydown" (JD.map tagger keyCode)
checkbox : Bool -> msg -> String -> Html msg
checkbox isChecked msg name =
label []
[ input
[ type_ "checkbox"
, checked isChecked
, onClick msg
]
[]
, text name
]
{-| [Oracle list of special characters](https://docs.oracle.com/cd/E11223_01/doc.910/e11197/app_special_char.htm#MCMAD416)
-}
specialChars : String
specialChars =
"!@#$%"
numbers : String
numbers =
"1234567890"
modifyStrings : Model -> String
modifyStrings model =
if not model.enableModifications then
String.join " " model.strings
else
let
mods =
model.modifications
count =
List.length model.strings
spaces =
count - 1
changes1 =
String.left mods.numbers numbers
++ String.left mods.specialChars specialChars
added =
String.length changes1
length =
List.foldl (\s sum -> sum + String.length s) 0 model.strings
trim =
if mods.showTotalLength then
max 0 <| length + added - mods.totalLength
else
0
strings1 =
trimStrings trim model.strings
strings =
addUppercase mods.uppercase strings1
newlen =
length + added - trim
addspaces1 =
if mods.showTotalLength then
max 0 (min (spaces - added) (mods.totalLength - newlen))
else
max 0 (spaces - added)
addspaces =
if addspaces1 < spaces - added then
0
else
addspaces1
changes =
changes1 ++ String.repeat addspaces " "
res =
distributeChanges changes strings
in
if not mods.spaces then
String.filter ((/=) ' ') res
else
res
trim1 : List String -> ( List String, Bool )
trim1 strings =
let
maxlen =
List.foldl (\s res -> max res (String.length s)) 0 strings
in
if maxlen <= 1 then
( strings, False )
else
let
loop ss res =
case ss of
[] ->
-- can't happen
( List.reverse res, False )
s :: tail ->
if String.length s == maxlen then
( List.concat
[ List.reverse res
, [ String.dropRight 1 s ]
, tail
]
, True
)
else
loop tail (s :: res)
in
loop strings []
trimStrings : Int -> List String -> List String
trimStrings trim strings =
if trim <= 0 then
strings
else
let
loop len ss =
if len <= 0 then
ss
else
let
( ss2, changed ) =
trim1 ss
in
if changed then
loop (len - 1) ss2
else
ss2
in
loop trim strings
upcase1 : String -> ( String, Bool )
upcase1 string =
let
loop chars res =
case chars of
[] ->
( res, False )
c :: tail ->
if Char.isLower c then
( res
++ (String.fromChar <| Char.toUpper c)
++ String.fromList tail
, True
)
else
loop tail <| res ++ String.fromChar c
in
loop (String.toList string) ""
addUppercase : Int -> List String -> List String
addUppercase count strings =
let
loop cnt stringsTail changed res =
if cnt <= 0 then
List.concat [ List.reverse res, stringsTail ]
else
case stringsTail of
[] ->
if changed then
loop cnt (List.reverse res) False []
else
List.reverse res
s :: tail ->
let
( s2, ch ) =
upcase1 s
cnt2 =
if ch then
cnt - 1
else
cnt
in
loop cnt2
tail
(changed || ch)
(s2 :: res)
in
loop count strings False []
distributeChanges : String -> List String -> String
distributeChanges changes strings =
let
loop ch ss res =
if ch == "" then
res ++ String.concat ss
else
case ss of
[] ->
res ++ ch
s :: tail ->
loop (String.dropLeft 1 ch)
tail
(res ++ s ++ String.left 1 ch)
in
loop changes strings ""
view : Model -> Html Msg
view model =
let
string =
modifyStrings model
in
div
[ style "width" "40em"
, style "margin-left" "2em"
]
[ h2 [] [ text "Diceware Passphrase Generator" ]
, p []
[ text "This page generates passphrases using JavaScript running in your web browser, using the browser's cryptographically secure random number generator. See below for instructions."
, case model.error of
Just s ->
span [ style "color" "red" ] [ br, text s ]
Nothing ->
text ""
]
, p []
[ select [ onInput ChangeTable ]
[ option
[ value "short"
, selected <| model.whichTable == ShortTable
]
[ text "EFF Short List" ]
, option
[ value "new"
, selected <| model.whichTable == NewTable
]
[ text "EFF Long List" ]
, option
[ value "old"
, selected <| model.whichTable == OldTable
]
[ text "Traditional List" ]
]
, text " Words: "
, input
[ size 3
, onInput UpdateCount
, value model.countString
]
[]
, text " "
, button [ onClick Generate ] [ text "Generate" ]
, text " "
, button [ onClick Clear ] [ text "Clear" ]
, text <|
" Entropy: "
++ (String.fromInt <| round <| getEntropy model)
++ " bits"
]
, div []
[ input
[ size <| String.length string + 2
, value string
, style "margin-left" "1em"
, style "font-size" "150%"
, style "padding-left" "0.5em"
, style "color"
(if model.isSecure then
"black"
else
"red"
)
]
[]
]
, h3 []
[ text "Roll Your Own Dice" ]
, p []
[ input
(let
count =
getDiceCount model
in
[ size count
, maxlength count
, onKeyDown DiceKeydown
, onInput <| UpdateDice
, value model.diceString
]
)
[]
, text " "
, button [ onClick LookupDice ] [ text "Lookup" ]
]
, p []
[ checkbox model.enableModifications
ToggleModifications
"modifications"
, if model.enableModifications then
renderModifications (String.length string) model
else
text ""
]
, h3 []
[ text "Generate a Random Number" ]
, p []
[ Html.b [] [ text "N: " ]
, input
[ size 8
, maxlength 8
, onKeyDown RandomMaxDown
, onInput UpdateRandomMaxString
, value model.randomMaxString
]
[]
, text " "
, button [ onClick GenerateRandomNumber ] [ text "Random from 1 to N" ]
]
, p []
(if model.randomMax <= 0 then
[]
else
[ p []
[ Html.b []
[ text
("Random number from 1 to "
++ String.fromInt model.randomMax
++ ": "
)
]
]
, p
[ style "margin-left" "1em"
, style "font-size" "150%"
, style "padding-left" "0.5em"
, style "color"
(if model.isSecure then
"black"
else
"red"
)
]
[ text <| String.fromInt model.randomNumber ]
]
)
, p []
[ text "To generate a passphrase, choose which of the three lists to use from the selector (initially \"EFF Short List\"), fill in \"Words\" with the number of words to generate, and click the \"Generate\" button. To clear the word string, click \"Clear\"."
]
, p []
[ text "If the passphrase is black, then cryptographically-secure random number generation was used. If it is red, then the random number generation was NOT cryptographically secure, because "
, text <|
if model.useSimulator then
"you are running the pure Elm version of the code."
else
"your browser does not support it."
]
, p []
[ text "If you prefer rolling your own dice to using your computer's random number generator, you can type into the box to the left of the \"Lookup\" button four or five numbers (from 1-6) from four or five six-sided dice rolls, then click that button (four dice rolls for the \"EFF Short List\" or five for the other two). It will add one word to the end of the list."
]
, p []
[ text "If you check the \"modifications\" box, you can choose whether to put spaces between the words, the maximum password length, and how many upper case, numeric, and special characters to put in the result. This allows you to easily satisfy the most common password requirements from people who don't understand that length is the only password property that really matters for security." ]
, p []
[ text "If you enter \"N\" and click \"Random from 1 to N\", a random number between 1 and N will be printed below that line." ]
, p []
[ text "The three lists are as follows:"
, ul []
[ li []
[ text "EFF Short List"
, br
, text "The first short list from the "
, effListLink
, text "."
]
, li []
[ text "EFF Long List"
, br
, text "The long list from the "
, effListLink
, text "."
]
, li []
[ text "Traditional List"
, br
, text "The original Diceware word list."
]
]
]
, p []
[ text "For more information about Diceware, see "
, a [ href "http://diceware.com/" ]
[ text "Diceware.com" ]
, text ". "
, text "The classic XKCD cartoon about Diceware is at "
, a [ href "https://xkcd.com/936/" ]
[ text "xkcd.com/936" ]
, text "."
]
, p []
[ text "A five-word Diceware passphrase (from one of the long lists) has 6^5^5 possibilities, over 64 bits. A ten-word Diceware passphrase (again, from one of the long lists) has 6^5^10 possibilities, over 129 bits."
]
, p []
[ text "Source code: "
, a [ href "https://github.com/billstclair/elm-dev-random" ]
[ text "github.com/billstclair/elm-dev-random" ]
, br
, text "Copyright 2017-2018 Bill St. Clair"
]
]
numberSelector : Int -> Int -> (String -> Msg) -> Html Msg
numberSelector current max wrapper =
let
intOption i =
option
[ value <| String.fromInt i
, selected (i == current)
]
[ text <|
if i == 0 then
"none"
else
String.fromInt i
]
in
select [ onInput wrapper ] <|
List.map intOption <|
List.range 0 max
renderModifications : Int -> Model -> Html Msg
renderModifications length model =
let
modifications =
model.modifications
in
div [ style "margin-left" "1em" ]
[ checkbox modifications.spaces ToggleSpaces "spaces"
, br
, checkbox modifications.showTotalLength
ToggleShowTotalLength
(if modifications.showTotalLength then
"limit length: "
else
"limit length"
)
, if not modifications.showTotalLength then
text ""
else
span []
[ input
[ size 3
, onInput UpdateTotalLength
, value <| String.fromInt modifications.totalLength
]
[]
, if length > modifications.totalLength then
span [ style "color" "red" ]
[ text " too short" ]
else
text ""
]
, br
, text "uppercase letters: "
, numberSelector modifications.uppercase 5 UpdateUpperCase
, br
, text "numbers: "
, numberSelector modifications.numbers 5 UpdateNumbers
, br
, text "special chars: "
, numberSelector modifications.specialChars 5 UpdateSpecialChars
]
effListLink : Html msg
effListLink =
span []
[ text "EFF's July 2016 \""
, a
[ href
"https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases"
]
[ text "New Wordlists for Random Passphrases" ]
, text "\""
]
| 29518 | ---------------------------------------------------------------------
--
-- Main.elm
-- User interface for Diceware example of using DevRandom module.
-- Copyright (c) 2017-2018 <NAME> <<EMAIL>>
-- Some rights reserved.
-- Distributed under the MIT License
-- See LICENSE.txt
--
----------------------------------------------------------------------
port module Main exposing
( Model
, Msg(..)
, init
, update
, view
)
import Array exposing (Array)
import Browser
import Char
import Cmd.Extra exposing (addCmd, addCmds, withCmd, withCmds, withNoCmd)
import Debug exposing (log)
import DicewareStrings
import Dict exposing (Dict)
import Html
exposing
( Attribute
, Html
, a
, button
, div
, h2
, h3
, img
, input
, label
, li
, option
, p
, select
, span
, text
, ul
)
import Html.Attributes
exposing
( alt
, checked
, href
, maxlength
, readonly
, selected
, size
, src
, style
, title
, type_
, value
)
import Html.Events exposing (keyCode, on, onClick, onInput)
import Json.Decode as JD
import Json.Encode as JE exposing (Value)
import List.Extra as LE
import NewDicewareStrings
import PortFunnel exposing (FunnelSpec, GenericMessage, ModuleDesc, StateAccessors)
import PortFunnel.DevRandom as DevRandom
import ShortDicewareStrings
import Time
port cmdPort : Value -> Cmd msg
port subPort : (Value -> msg) -> Sub msg
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.batch
[ subPort Process
, if model.startup then
Time.every 250 Init
else
Sub.none
]
simulatedCmdPort : Value -> Cmd Msg
simulatedCmdPort =
DevRandom.makeSimulatedCmdPort Process
getCmdPort : Model -> (Value -> Cmd Msg)
getCmdPort model =
if model.useSimulator then
simulatedCmdPort
else
cmdPort
type DicewareTable
= OldTable
| NewTable
| ShortTable
type alias Modifications =
{ spaces : Bool
, showTotalLength : Bool
, totalLength : Int
, uppercase : Int
, numbers : Int
, specialChars : Int
}
defaultModifications : Modifications
defaultModifications =
{ spaces = True
, showTotalLength = False
, totalLength = 30
, uppercase = 0
, numbers = 0
, specialChars = 0
}
type RandomReason
= RandomPassphrase
| RandomNumber
type alias FunnelState =
{ random : DevRandom.State }
type alias Model =
{ startup : Bool
, funnelState : FunnelState
, useSimulator : Bool
, randomReason : RandomReason
, countString : String
, count : Int
, strings : List String
, isSecure : Bool
, whichTable : DicewareTable
, diceString : String
, enableModifications : Bool
, modifications : Modifications
, randomMaxString : String
, randomMax : Int
, randomNumber : Int
, error : Maybe String
}
makeInitialModel : Int -> Model
makeInitialModel count =
let
model =
{ startup = True
, funnelState =
{ random = DevRandom.initialState 0 }
, useSimulator = True
, randomReason = RandomPassphrase
, countString = String.fromInt count
, count = count
, strings = []
, isSecure = True
, whichTable = ShortTable
, diceString = ""
, enableModifications = False
, modifications = defaultModifications
, randomMaxString = "100"
, randomMax = 0
, randomNumber = 10
, error = Nothing
}
in
model
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
init : () -> ( Model, Cmd Msg )
init _ =
let
count =
6
model =
makeInitialModel count
in
model |> withNoCmd
generatePassphrase : Model -> ( Model, Cmd Msg )
generatePassphrase model =
{ model | randomReason = RandomPassphrase }
|> withCmd
(DevRandom.GenerateInt (getCount model)
|> DevRandom.send (getCmdPort model)
)
generateNumber : Model -> ( Model, Cmd Msg )
generateNumber model =
{ model | randomReason = RandomNumber }
|> withCmd
(DevRandom.GenerateInt model.randomMax
|> DevRandom.send (getCmdPort model)
)
getDiceCount : Model -> Int
getDiceCount model =
case model.whichTable of
NewTable ->
5
OldTable ->
5
ShortTable ->
4
getCount : Model -> Int
getCount model =
case model.whichTable of
NewTable ->
NewDicewareStrings.count
OldTable ->
DicewareStrings.count
ShortTable ->
ShortDicewareStrings.count
getArray : Model -> Array String
getArray model =
case model.whichTable of
NewTable ->
NewDicewareStrings.array
OldTable ->
DicewareStrings.array
ShortTable ->
ShortDicewareStrings.array
entropyPerDie : DicewareTable -> Float
entropyPerDie table =
case table of
NewTable ->
12.9
OldTable ->
12.9
ShortTable ->
10.3
getEntropy : Model -> Float
getEntropy model =
(toFloat <| List.length model.strings) * entropyPerDie model.whichTable
randomAccessors : StateAccessors FunnelState DevRandom.State
randomAccessors =
StateAccessors .random (\substate state -> { state | random = substate })
type alias AppFunnel substate message response =
FunnelSpec FunnelState substate message response Model Msg
type Funnel
= RandomFunnel (AppFunnel DevRandom.State DevRandom.Message DevRandom.Response)
emptyCommander : (GenericMessage -> Cmd msg) -> response -> Cmd msg
emptyCommander _ _ =
Cmd.none
funnels : Dict String Funnel
funnels =
Dict.fromList
[ ( DevRandom.moduleName
, RandomFunnel <|
FunnelSpec randomAccessors
DevRandom.moduleDesc
emptyCommander
randomHandler
)
]
doIsLoaded : Model -> ( Model, Cmd Msg )
doIsLoaded model =
if model.useSimulator && DevRandom.isLoaded model.funnelState.random then
{ model
| useSimulator = False
, strings = []
}
|> generatePassphrase
else
model |> withNoCmd
randomHandler : DevRandom.Response -> FunnelState -> Model -> ( Model, Cmd Msg )
randomHandler response state mdl =
let
( model, cmd ) =
doIsLoaded
{ mdl | funnelState = state }
in
case response of
DevRandom.RandomIntResponse { isSecure, int } ->
case model.randomReason of
RandomNumber ->
{ model
| isSecure = isSecure
, randomNumber = int + 1
}
|> withCmd cmd
RandomPassphrase ->
let
string =
case Array.get int <| getArray model of
Nothing ->
"a"
Just s ->
s
strings =
string :: model.strings
in
{ model
| strings = strings
, isSecure = isSecure
}
|> (if List.length strings >= model.count then
withCmd cmd
else
generatePassphrase
)
_ ->
model |> withCmd cmd
type Msg
= Init Time.Posix
| UpdateCount String
| UpdateDice String
| DiceKeydown Int
| Generate
| Clear
| Process Value
| LookupDice
| ChangeTable String
| ToggleModifications
| ToggleSpaces
| ToggleShowTotalLength
| UpdateTotalLength String
| UpdateUpperCase String
| UpdateNumbers String
| UpdateSpecialChars String
| RandomMaxDown Int
| UpdateRandomMaxString String
| GenerateRandomNumber
stringToInt : String -> Result String Int
stringToInt string =
case String.toInt string of
Just int ->
Ok int
Nothing ->
Err "invalid integer string"
update : Msg -> Model -> ( Model, Cmd Msg )
update msg modl =
let
model =
{ modl | error = Nothing }
modifications =
model.modifications
in
case msg of
Init _ ->
{ model | startup = False }
|> (if model.useSimulator then
generatePassphrase
else
withNoCmd
)
UpdateCount countString ->
( { model
| countString = countString
, count =
case stringToInt countString of
Ok count ->
max 0 (min count 20)
Err _ ->
0
}
, Cmd.none
)
UpdateDice string ->
( { model
| diceString = string
}
, Cmd.none
)
DiceKeydown keycode ->
( if keycode == 13 then
lookupDice model
else
model
, Cmd.none
)
Generate ->
case model.count of
0 ->
( { model | strings = [] }
, Cmd.none
)
_ ->
{ model | strings = [] }
|> generatePassphrase
Clear ->
( { model
| strings = []
, isSecure = True
}
, Cmd.none
)
Process value ->
case
PortFunnel.processValue funnels
appTrampoline
value
model.funnelState
model
of
Err error ->
{ model | error = Just error } |> withNoCmd
Ok res ->
res
LookupDice ->
( lookupDice model
, Cmd.none
)
ChangeTable table ->
let
oldTable =
model.whichTable
newTable =
stringToTable table
count =
newRollCount newTable model
mdl =
{ model
| whichTable = stringToTable table
, count = count
, countString = String.fromInt count
, strings = []
, diceString = ""
, randomReason = RandomPassphrase
}
in
generatePassphrase mdl
ToggleModifications ->
( { model | enableModifications = not model.enableModifications }
, Cmd.none
)
ToggleSpaces ->
( { model
| modifications =
{ modifications
| spaces = not modifications.spaces
}
}
, Cmd.none
)
ToggleShowTotalLength ->
( { model
| modifications =
{ modifications
| showTotalLength = not modifications.showTotalLength
}
}
, Cmd.none
)
UpdateTotalLength string ->
updateModificationsInt
(if string == "" then
"0"
else
string
)
(\int -> { modifications | totalLength = int })
model
UpdateUpperCase string ->
updateModificationsInt string
(\int -> { modifications | uppercase = int })
model
UpdateNumbers string ->
updateModificationsInt string
(\int -> { modifications | numbers = int })
model
UpdateSpecialChars string ->
updateModificationsInt string
(\int -> { modifications | specialChars = int })
model
-- TODO
RandomMaxDown keycode ->
if keycode == 13 then
update GenerateRandomNumber model
else
model |> withNoCmd
UpdateRandomMaxString string ->
{ model | randomMaxString = string }
|> withNoCmd
GenerateRandomNumber ->
let
mdl =
{ model | randomNumber = 0 }
in
case String.toInt model.randomMaxString of
Nothing ->
mdl |> withNoCmd
Just max ->
if max <= 0 then
mdl |> withNoCmd
else
{ mdl
| randomMax = max
, randomNumber = 0
}
|> generateNumber
appTrampoline : GenericMessage -> Funnel -> FunnelState -> Model -> Result String ( Model, Cmd Msg )
appTrampoline genericMessage funnel state model =
let
theCmdPort =
getCmdPort model
in
case funnel of
RandomFunnel randomFunnel ->
PortFunnel.appProcess theCmdPort
genericMessage
randomFunnel
state
model
updateModificationsInt : String -> (Int -> Modifications) -> Model -> ( Model, Cmd Msg )
updateModificationsInt string setter model =
case stringToInt string of
Err _ ->
model |> withNoCmd
Ok int ->
{ model | modifications = setter int }
|> withNoCmd
newRollCount : DicewareTable -> Model -> Int
newRollCount newTable model =
let
count =
toFloat model.count
perDie =
entropyPerDie model.whichTable
oldEntropy =
count * perDie
newPerDie =
entropyPerDie newTable
in
round <| (oldEntropy / newPerDie)
stringToTable : String -> DicewareTable
stringToTable table =
case table of
"old" ->
OldTable
"new" ->
NewTable
_ ->
ShortTable
dieNum : String -> Int
dieNum string =
case stringToInt string of
Err _ ->
0
Ok n ->
if n < 0 || n > 6 then
0
else
n
computeUserDice : Model -> Maybe (List Int)
computeUserDice model =
let
diceNumber =
getDiceCount model
digits =
List.map String.fromChar <| String.toList model.diceString
in
if diceNumber /= List.length digits then
Nothing
else
Just <|
List.map dieNum digits
lookupDice : Model -> Model
lookupDice model =
case computeUserDice model of
Nothing ->
model
Just dice ->
case LE.find (\x -> x == 0) dice of
Just _ ->
model
Nothing ->
let
count =
model.count
strings =
model.strings
stringsTail =
List.drop
(List.length strings - count + 1)
strings
idx =
List.foldl
(\x y -> (6 * y) + x - 1)
0
dice
string =
case Array.get idx <| getArray model of
Nothing ->
"a"
Just x ->
x
in
{ model
| strings = List.append stringsTail [ string ]
, isSecure = True
, diceString = ""
}
nbsp : String
nbsp =
String.fromList [ Char.fromCode 160 ]
br : Html Msg
br =
Html.br [] []
onKeyDown : (Int -> msg) -> Attribute msg
onKeyDown tagger =
on "keydown" (JD.map tagger keyCode)
checkbox : Bool -> msg -> String -> Html msg
checkbox isChecked msg name =
label []
[ input
[ type_ "checkbox"
, checked isChecked
, onClick msg
]
[]
, text name
]
{-| [Oracle list of special characters](https://docs.oracle.com/cd/E11223_01/doc.910/e11197/app_special_char.htm#MCMAD416)
-}
specialChars : String
specialChars =
"!@#$%"
numbers : String
numbers =
"1234567890"
modifyStrings : Model -> String
modifyStrings model =
if not model.enableModifications then
String.join " " model.strings
else
let
mods =
model.modifications
count =
List.length model.strings
spaces =
count - 1
changes1 =
String.left mods.numbers numbers
++ String.left mods.specialChars specialChars
added =
String.length changes1
length =
List.foldl (\s sum -> sum + String.length s) 0 model.strings
trim =
if mods.showTotalLength then
max 0 <| length + added - mods.totalLength
else
0
strings1 =
trimStrings trim model.strings
strings =
addUppercase mods.uppercase strings1
newlen =
length + added - trim
addspaces1 =
if mods.showTotalLength then
max 0 (min (spaces - added) (mods.totalLength - newlen))
else
max 0 (spaces - added)
addspaces =
if addspaces1 < spaces - added then
0
else
addspaces1
changes =
changes1 ++ String.repeat addspaces " "
res =
distributeChanges changes strings
in
if not mods.spaces then
String.filter ((/=) ' ') res
else
res
trim1 : List String -> ( List String, Bool )
trim1 strings =
let
maxlen =
List.foldl (\s res -> max res (String.length s)) 0 strings
in
if maxlen <= 1 then
( strings, False )
else
let
loop ss res =
case ss of
[] ->
-- can't happen
( List.reverse res, False )
s :: tail ->
if String.length s == maxlen then
( List.concat
[ List.reverse res
, [ String.dropRight 1 s ]
, tail
]
, True
)
else
loop tail (s :: res)
in
loop strings []
trimStrings : Int -> List String -> List String
trimStrings trim strings =
if trim <= 0 then
strings
else
let
loop len ss =
if len <= 0 then
ss
else
let
( ss2, changed ) =
trim1 ss
in
if changed then
loop (len - 1) ss2
else
ss2
in
loop trim strings
upcase1 : String -> ( String, Bool )
upcase1 string =
let
loop chars res =
case chars of
[] ->
( res, False )
c :: tail ->
if Char.isLower c then
( res
++ (String.fromChar <| Char.toUpper c)
++ String.fromList tail
, True
)
else
loop tail <| res ++ String.fromChar c
in
loop (String.toList string) ""
addUppercase : Int -> List String -> List String
addUppercase count strings =
let
loop cnt stringsTail changed res =
if cnt <= 0 then
List.concat [ List.reverse res, stringsTail ]
else
case stringsTail of
[] ->
if changed then
loop cnt (List.reverse res) False []
else
List.reverse res
s :: tail ->
let
( s2, ch ) =
upcase1 s
cnt2 =
if ch then
cnt - 1
else
cnt
in
loop cnt2
tail
(changed || ch)
(s2 :: res)
in
loop count strings False []
distributeChanges : String -> List String -> String
distributeChanges changes strings =
let
loop ch ss res =
if ch == "" then
res ++ String.concat ss
else
case ss of
[] ->
res ++ ch
s :: tail ->
loop (String.dropLeft 1 ch)
tail
(res ++ s ++ String.left 1 ch)
in
loop changes strings ""
view : Model -> Html Msg
view model =
let
string =
modifyStrings model
in
div
[ style "width" "40em"
, style "margin-left" "2em"
]
[ h2 [] [ text "Diceware Passphrase Generator" ]
, p []
[ text "This page generates passphrases using JavaScript running in your web browser, using the browser's cryptographically secure random number generator. See below for instructions."
, case model.error of
Just s ->
span [ style "color" "red" ] [ br, text s ]
Nothing ->
text ""
]
, p []
[ select [ onInput ChangeTable ]
[ option
[ value "short"
, selected <| model.whichTable == ShortTable
]
[ text "EFF Short List" ]
, option
[ value "new"
, selected <| model.whichTable == NewTable
]
[ text "EFF Long List" ]
, option
[ value "old"
, selected <| model.whichTable == OldTable
]
[ text "Traditional List" ]
]
, text " Words: "
, input
[ size 3
, onInput UpdateCount
, value model.countString
]
[]
, text " "
, button [ onClick Generate ] [ text "Generate" ]
, text " "
, button [ onClick Clear ] [ text "Clear" ]
, text <|
" Entropy: "
++ (String.fromInt <| round <| getEntropy model)
++ " bits"
]
, div []
[ input
[ size <| String.length string + 2
, value string
, style "margin-left" "1em"
, style "font-size" "150%"
, style "padding-left" "0.5em"
, style "color"
(if model.isSecure then
"black"
else
"red"
)
]
[]
]
, h3 []
[ text "Roll Your Own Dice" ]
, p []
[ input
(let
count =
getDiceCount model
in
[ size count
, maxlength count
, onKeyDown DiceKeydown
, onInput <| UpdateDice
, value model.diceString
]
)
[]
, text " "
, button [ onClick LookupDice ] [ text "Lookup" ]
]
, p []
[ checkbox model.enableModifications
ToggleModifications
"modifications"
, if model.enableModifications then
renderModifications (String.length string) model
else
text ""
]
, h3 []
[ text "Generate a Random Number" ]
, p []
[ Html.b [] [ text "N: " ]
, input
[ size 8
, maxlength 8
, onKeyDown RandomMaxDown
, onInput UpdateRandomMaxString
, value model.randomMaxString
]
[]
, text " "
, button [ onClick GenerateRandomNumber ] [ text "Random from 1 to N" ]
]
, p []
(if model.randomMax <= 0 then
[]
else
[ p []
[ Html.b []
[ text
("Random number from 1 to "
++ String.fromInt model.randomMax
++ ": "
)
]
]
, p
[ style "margin-left" "1em"
, style "font-size" "150%"
, style "padding-left" "0.5em"
, style "color"
(if model.isSecure then
"black"
else
"red"
)
]
[ text <| String.fromInt model.randomNumber ]
]
)
, p []
[ text "To generate a passphrase, choose which of the three lists to use from the selector (initially \"EFF Short List\"), fill in \"Words\" with the number of words to generate, and click the \"Generate\" button. To clear the word string, click \"Clear\"."
]
, p []
[ text "If the passphrase is black, then cryptographically-secure random number generation was used. If it is red, then the random number generation was NOT cryptographically secure, because "
, text <|
if model.useSimulator then
"you are running the pure Elm version of the code."
else
"your browser does not support it."
]
, p []
[ text "If you prefer rolling your own dice to using your computer's random number generator, you can type into the box to the left of the \"Lookup\" button four or five numbers (from 1-6) from four or five six-sided dice rolls, then click that button (four dice rolls for the \"EFF Short List\" or five for the other two). It will add one word to the end of the list."
]
, p []
[ text "If you check the \"modifications\" box, you can choose whether to put spaces between the words, the maximum password length, and how many upper case, numeric, and special characters to put in the result. This allows you to easily satisfy the most common password requirements from people who don't understand that length is the only password property that really matters for security." ]
, p []
[ text "If you enter \"N\" and click \"Random from 1 to N\", a random number between 1 and N will be printed below that line." ]
, p []
[ text "The three lists are as follows:"
, ul []
[ li []
[ text "EFF Short List"
, br
, text "The first short list from the "
, effListLink
, text "."
]
, li []
[ text "EFF Long List"
, br
, text "The long list from the "
, effListLink
, text "."
]
, li []
[ text "Traditional List"
, br
, text "The original Diceware word list."
]
]
]
, p []
[ text "For more information about Diceware, see "
, a [ href "http://diceware.com/" ]
[ text "Diceware.com" ]
, text ". "
, text "The classic XKCD cartoon about Diceware is at "
, a [ href "https://xkcd.com/936/" ]
[ text "xkcd.com/936" ]
, text "."
]
, p []
[ text "A five-word Diceware passphrase (from one of the long lists) has 6^5^5 possibilities, over 64 bits. A ten-word Diceware passphrase (again, from one of the long lists) has 6^5^10 possibilities, over 129 bits."
]
, p []
[ text "Source code: "
, a [ href "https://github.com/billstclair/elm-dev-random" ]
[ text "github.com/billstclair/elm-dev-random" ]
, br
, text "Copyright 2017-2018 <NAME>"
]
]
numberSelector : Int -> Int -> (String -> Msg) -> Html Msg
numberSelector current max wrapper =
let
intOption i =
option
[ value <| String.fromInt i
, selected (i == current)
]
[ text <|
if i == 0 then
"none"
else
String.fromInt i
]
in
select [ onInput wrapper ] <|
List.map intOption <|
List.range 0 max
renderModifications : Int -> Model -> Html Msg
renderModifications length model =
let
modifications =
model.modifications
in
div [ style "margin-left" "1em" ]
[ checkbox modifications.spaces ToggleSpaces "spaces"
, br
, checkbox modifications.showTotalLength
ToggleShowTotalLength
(if modifications.showTotalLength then
"limit length: "
else
"limit length"
)
, if not modifications.showTotalLength then
text ""
else
span []
[ input
[ size 3
, onInput UpdateTotalLength
, value <| String.fromInt modifications.totalLength
]
[]
, if length > modifications.totalLength then
span [ style "color" "red" ]
[ text " too short" ]
else
text ""
]
, br
, text "uppercase letters: "
, numberSelector modifications.uppercase 5 UpdateUpperCase
, br
, text "numbers: "
, numberSelector modifications.numbers 5 UpdateNumbers
, br
, text "special chars: "
, numberSelector modifications.specialChars 5 UpdateSpecialChars
]
effListLink : Html msg
effListLink =
span []
[ text "EFF's July 2016 \""
, a
[ href
"https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases"
]
[ text "New Wordlists for Random Passphrases" ]
, text "\""
]
| true | ---------------------------------------------------------------------
--
-- Main.elm
-- User interface for Diceware example of using DevRandom module.
-- Copyright (c) 2017-2018 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
-- Some rights reserved.
-- Distributed under the MIT License
-- See LICENSE.txt
--
----------------------------------------------------------------------
port module Main exposing
( Model
, Msg(..)
, init
, update
, view
)
import Array exposing (Array)
import Browser
import Char
import Cmd.Extra exposing (addCmd, addCmds, withCmd, withCmds, withNoCmd)
import Debug exposing (log)
import DicewareStrings
import Dict exposing (Dict)
import Html
exposing
( Attribute
, Html
, a
, button
, div
, h2
, h3
, img
, input
, label
, li
, option
, p
, select
, span
, text
, ul
)
import Html.Attributes
exposing
( alt
, checked
, href
, maxlength
, readonly
, selected
, size
, src
, style
, title
, type_
, value
)
import Html.Events exposing (keyCode, on, onClick, onInput)
import Json.Decode as JD
import Json.Encode as JE exposing (Value)
import List.Extra as LE
import NewDicewareStrings
import PortFunnel exposing (FunnelSpec, GenericMessage, ModuleDesc, StateAccessors)
import PortFunnel.DevRandom as DevRandom
import ShortDicewareStrings
import Time
port cmdPort : Value -> Cmd msg
port subPort : (Value -> msg) -> Sub msg
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.batch
[ subPort Process
, if model.startup then
Time.every 250 Init
else
Sub.none
]
simulatedCmdPort : Value -> Cmd Msg
simulatedCmdPort =
DevRandom.makeSimulatedCmdPort Process
getCmdPort : Model -> (Value -> Cmd Msg)
getCmdPort model =
if model.useSimulator then
simulatedCmdPort
else
cmdPort
type DicewareTable
= OldTable
| NewTable
| ShortTable
type alias Modifications =
{ spaces : Bool
, showTotalLength : Bool
, totalLength : Int
, uppercase : Int
, numbers : Int
, specialChars : Int
}
defaultModifications : Modifications
defaultModifications =
{ spaces = True
, showTotalLength = False
, totalLength = 30
, uppercase = 0
, numbers = 0
, specialChars = 0
}
type RandomReason
= RandomPassphrase
| RandomNumber
type alias FunnelState =
{ random : DevRandom.State }
type alias Model =
{ startup : Bool
, funnelState : FunnelState
, useSimulator : Bool
, randomReason : RandomReason
, countString : String
, count : Int
, strings : List String
, isSecure : Bool
, whichTable : DicewareTable
, diceString : String
, enableModifications : Bool
, modifications : Modifications
, randomMaxString : String
, randomMax : Int
, randomNumber : Int
, error : Maybe String
}
makeInitialModel : Int -> Model
makeInitialModel count =
let
model =
{ startup = True
, funnelState =
{ random = DevRandom.initialState 0 }
, useSimulator = True
, randomReason = RandomPassphrase
, countString = String.fromInt count
, count = count
, strings = []
, isSecure = True
, whichTable = ShortTable
, diceString = ""
, enableModifications = False
, modifications = defaultModifications
, randomMaxString = "100"
, randomMax = 0
, randomNumber = 10
, error = Nothing
}
in
model
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
init : () -> ( Model, Cmd Msg )
init _ =
let
count =
6
model =
makeInitialModel count
in
model |> withNoCmd
generatePassphrase : Model -> ( Model, Cmd Msg )
generatePassphrase model =
{ model | randomReason = RandomPassphrase }
|> withCmd
(DevRandom.GenerateInt (getCount model)
|> DevRandom.send (getCmdPort model)
)
generateNumber : Model -> ( Model, Cmd Msg )
generateNumber model =
{ model | randomReason = RandomNumber }
|> withCmd
(DevRandom.GenerateInt model.randomMax
|> DevRandom.send (getCmdPort model)
)
getDiceCount : Model -> Int
getDiceCount model =
case model.whichTable of
NewTable ->
5
OldTable ->
5
ShortTable ->
4
getCount : Model -> Int
getCount model =
case model.whichTable of
NewTable ->
NewDicewareStrings.count
OldTable ->
DicewareStrings.count
ShortTable ->
ShortDicewareStrings.count
getArray : Model -> Array String
getArray model =
case model.whichTable of
NewTable ->
NewDicewareStrings.array
OldTable ->
DicewareStrings.array
ShortTable ->
ShortDicewareStrings.array
entropyPerDie : DicewareTable -> Float
entropyPerDie table =
case table of
NewTable ->
12.9
OldTable ->
12.9
ShortTable ->
10.3
getEntropy : Model -> Float
getEntropy model =
(toFloat <| List.length model.strings) * entropyPerDie model.whichTable
randomAccessors : StateAccessors FunnelState DevRandom.State
randomAccessors =
StateAccessors .random (\substate state -> { state | random = substate })
type alias AppFunnel substate message response =
FunnelSpec FunnelState substate message response Model Msg
type Funnel
= RandomFunnel (AppFunnel DevRandom.State DevRandom.Message DevRandom.Response)
emptyCommander : (GenericMessage -> Cmd msg) -> response -> Cmd msg
emptyCommander _ _ =
Cmd.none
funnels : Dict String Funnel
funnels =
Dict.fromList
[ ( DevRandom.moduleName
, RandomFunnel <|
FunnelSpec randomAccessors
DevRandom.moduleDesc
emptyCommander
randomHandler
)
]
doIsLoaded : Model -> ( Model, Cmd Msg )
doIsLoaded model =
if model.useSimulator && DevRandom.isLoaded model.funnelState.random then
{ model
| useSimulator = False
, strings = []
}
|> generatePassphrase
else
model |> withNoCmd
randomHandler : DevRandom.Response -> FunnelState -> Model -> ( Model, Cmd Msg )
randomHandler response state mdl =
let
( model, cmd ) =
doIsLoaded
{ mdl | funnelState = state }
in
case response of
DevRandom.RandomIntResponse { isSecure, int } ->
case model.randomReason of
RandomNumber ->
{ model
| isSecure = isSecure
, randomNumber = int + 1
}
|> withCmd cmd
RandomPassphrase ->
let
string =
case Array.get int <| getArray model of
Nothing ->
"a"
Just s ->
s
strings =
string :: model.strings
in
{ model
| strings = strings
, isSecure = isSecure
}
|> (if List.length strings >= model.count then
withCmd cmd
else
generatePassphrase
)
_ ->
model |> withCmd cmd
type Msg
= Init Time.Posix
| UpdateCount String
| UpdateDice String
| DiceKeydown Int
| Generate
| Clear
| Process Value
| LookupDice
| ChangeTable String
| ToggleModifications
| ToggleSpaces
| ToggleShowTotalLength
| UpdateTotalLength String
| UpdateUpperCase String
| UpdateNumbers String
| UpdateSpecialChars String
| RandomMaxDown Int
| UpdateRandomMaxString String
| GenerateRandomNumber
stringToInt : String -> Result String Int
stringToInt string =
case String.toInt string of
Just int ->
Ok int
Nothing ->
Err "invalid integer string"
update : Msg -> Model -> ( Model, Cmd Msg )
update msg modl =
let
model =
{ modl | error = Nothing }
modifications =
model.modifications
in
case msg of
Init _ ->
{ model | startup = False }
|> (if model.useSimulator then
generatePassphrase
else
withNoCmd
)
UpdateCount countString ->
( { model
| countString = countString
, count =
case stringToInt countString of
Ok count ->
max 0 (min count 20)
Err _ ->
0
}
, Cmd.none
)
UpdateDice string ->
( { model
| diceString = string
}
, Cmd.none
)
DiceKeydown keycode ->
( if keycode == 13 then
lookupDice model
else
model
, Cmd.none
)
Generate ->
case model.count of
0 ->
( { model | strings = [] }
, Cmd.none
)
_ ->
{ model | strings = [] }
|> generatePassphrase
Clear ->
( { model
| strings = []
, isSecure = True
}
, Cmd.none
)
Process value ->
case
PortFunnel.processValue funnels
appTrampoline
value
model.funnelState
model
of
Err error ->
{ model | error = Just error } |> withNoCmd
Ok res ->
res
LookupDice ->
( lookupDice model
, Cmd.none
)
ChangeTable table ->
let
oldTable =
model.whichTable
newTable =
stringToTable table
count =
newRollCount newTable model
mdl =
{ model
| whichTable = stringToTable table
, count = count
, countString = String.fromInt count
, strings = []
, diceString = ""
, randomReason = RandomPassphrase
}
in
generatePassphrase mdl
ToggleModifications ->
( { model | enableModifications = not model.enableModifications }
, Cmd.none
)
ToggleSpaces ->
( { model
| modifications =
{ modifications
| spaces = not modifications.spaces
}
}
, Cmd.none
)
ToggleShowTotalLength ->
( { model
| modifications =
{ modifications
| showTotalLength = not modifications.showTotalLength
}
}
, Cmd.none
)
UpdateTotalLength string ->
updateModificationsInt
(if string == "" then
"0"
else
string
)
(\int -> { modifications | totalLength = int })
model
UpdateUpperCase string ->
updateModificationsInt string
(\int -> { modifications | uppercase = int })
model
UpdateNumbers string ->
updateModificationsInt string
(\int -> { modifications | numbers = int })
model
UpdateSpecialChars string ->
updateModificationsInt string
(\int -> { modifications | specialChars = int })
model
-- TODO
RandomMaxDown keycode ->
if keycode == 13 then
update GenerateRandomNumber model
else
model |> withNoCmd
UpdateRandomMaxString string ->
{ model | randomMaxString = string }
|> withNoCmd
GenerateRandomNumber ->
let
mdl =
{ model | randomNumber = 0 }
in
case String.toInt model.randomMaxString of
Nothing ->
mdl |> withNoCmd
Just max ->
if max <= 0 then
mdl |> withNoCmd
else
{ mdl
| randomMax = max
, randomNumber = 0
}
|> generateNumber
appTrampoline : GenericMessage -> Funnel -> FunnelState -> Model -> Result String ( Model, Cmd Msg )
appTrampoline genericMessage funnel state model =
let
theCmdPort =
getCmdPort model
in
case funnel of
RandomFunnel randomFunnel ->
PortFunnel.appProcess theCmdPort
genericMessage
randomFunnel
state
model
updateModificationsInt : String -> (Int -> Modifications) -> Model -> ( Model, Cmd Msg )
updateModificationsInt string setter model =
case stringToInt string of
Err _ ->
model |> withNoCmd
Ok int ->
{ model | modifications = setter int }
|> withNoCmd
newRollCount : DicewareTable -> Model -> Int
newRollCount newTable model =
let
count =
toFloat model.count
perDie =
entropyPerDie model.whichTable
oldEntropy =
count * perDie
newPerDie =
entropyPerDie newTable
in
round <| (oldEntropy / newPerDie)
stringToTable : String -> DicewareTable
stringToTable table =
case table of
"old" ->
OldTable
"new" ->
NewTable
_ ->
ShortTable
dieNum : String -> Int
dieNum string =
case stringToInt string of
Err _ ->
0
Ok n ->
if n < 0 || n > 6 then
0
else
n
computeUserDice : Model -> Maybe (List Int)
computeUserDice model =
let
diceNumber =
getDiceCount model
digits =
List.map String.fromChar <| String.toList model.diceString
in
if diceNumber /= List.length digits then
Nothing
else
Just <|
List.map dieNum digits
lookupDice : Model -> Model
lookupDice model =
case computeUserDice model of
Nothing ->
model
Just dice ->
case LE.find (\x -> x == 0) dice of
Just _ ->
model
Nothing ->
let
count =
model.count
strings =
model.strings
stringsTail =
List.drop
(List.length strings - count + 1)
strings
idx =
List.foldl
(\x y -> (6 * y) + x - 1)
0
dice
string =
case Array.get idx <| getArray model of
Nothing ->
"a"
Just x ->
x
in
{ model
| strings = List.append stringsTail [ string ]
, isSecure = True
, diceString = ""
}
nbsp : String
nbsp =
String.fromList [ Char.fromCode 160 ]
br : Html Msg
br =
Html.br [] []
onKeyDown : (Int -> msg) -> Attribute msg
onKeyDown tagger =
on "keydown" (JD.map tagger keyCode)
checkbox : Bool -> msg -> String -> Html msg
checkbox isChecked msg name =
label []
[ input
[ type_ "checkbox"
, checked isChecked
, onClick msg
]
[]
, text name
]
{-| [Oracle list of special characters](https://docs.oracle.com/cd/E11223_01/doc.910/e11197/app_special_char.htm#MCMAD416)
-}
specialChars : String
specialChars =
"!@#$%"
numbers : String
numbers =
"1234567890"
modifyStrings : Model -> String
modifyStrings model =
if not model.enableModifications then
String.join " " model.strings
else
let
mods =
model.modifications
count =
List.length model.strings
spaces =
count - 1
changes1 =
String.left mods.numbers numbers
++ String.left mods.specialChars specialChars
added =
String.length changes1
length =
List.foldl (\s sum -> sum + String.length s) 0 model.strings
trim =
if mods.showTotalLength then
max 0 <| length + added - mods.totalLength
else
0
strings1 =
trimStrings trim model.strings
strings =
addUppercase mods.uppercase strings1
newlen =
length + added - trim
addspaces1 =
if mods.showTotalLength then
max 0 (min (spaces - added) (mods.totalLength - newlen))
else
max 0 (spaces - added)
addspaces =
if addspaces1 < spaces - added then
0
else
addspaces1
changes =
changes1 ++ String.repeat addspaces " "
res =
distributeChanges changes strings
in
if not mods.spaces then
String.filter ((/=) ' ') res
else
res
trim1 : List String -> ( List String, Bool )
trim1 strings =
let
maxlen =
List.foldl (\s res -> max res (String.length s)) 0 strings
in
if maxlen <= 1 then
( strings, False )
else
let
loop ss res =
case ss of
[] ->
-- can't happen
( List.reverse res, False )
s :: tail ->
if String.length s == maxlen then
( List.concat
[ List.reverse res
, [ String.dropRight 1 s ]
, tail
]
, True
)
else
loop tail (s :: res)
in
loop strings []
trimStrings : Int -> List String -> List String
trimStrings trim strings =
if trim <= 0 then
strings
else
let
loop len ss =
if len <= 0 then
ss
else
let
( ss2, changed ) =
trim1 ss
in
if changed then
loop (len - 1) ss2
else
ss2
in
loop trim strings
upcase1 : String -> ( String, Bool )
upcase1 string =
let
loop chars res =
case chars of
[] ->
( res, False )
c :: tail ->
if Char.isLower c then
( res
++ (String.fromChar <| Char.toUpper c)
++ String.fromList tail
, True
)
else
loop tail <| res ++ String.fromChar c
in
loop (String.toList string) ""
addUppercase : Int -> List String -> List String
addUppercase count strings =
let
loop cnt stringsTail changed res =
if cnt <= 0 then
List.concat [ List.reverse res, stringsTail ]
else
case stringsTail of
[] ->
if changed then
loop cnt (List.reverse res) False []
else
List.reverse res
s :: tail ->
let
( s2, ch ) =
upcase1 s
cnt2 =
if ch then
cnt - 1
else
cnt
in
loop cnt2
tail
(changed || ch)
(s2 :: res)
in
loop count strings False []
distributeChanges : String -> List String -> String
distributeChanges changes strings =
let
loop ch ss res =
if ch == "" then
res ++ String.concat ss
else
case ss of
[] ->
res ++ ch
s :: tail ->
loop (String.dropLeft 1 ch)
tail
(res ++ s ++ String.left 1 ch)
in
loop changes strings ""
view : Model -> Html Msg
view model =
let
string =
modifyStrings model
in
div
[ style "width" "40em"
, style "margin-left" "2em"
]
[ h2 [] [ text "Diceware Passphrase Generator" ]
, p []
[ text "This page generates passphrases using JavaScript running in your web browser, using the browser's cryptographically secure random number generator. See below for instructions."
, case model.error of
Just s ->
span [ style "color" "red" ] [ br, text s ]
Nothing ->
text ""
]
, p []
[ select [ onInput ChangeTable ]
[ option
[ value "short"
, selected <| model.whichTable == ShortTable
]
[ text "EFF Short List" ]
, option
[ value "new"
, selected <| model.whichTable == NewTable
]
[ text "EFF Long List" ]
, option
[ value "old"
, selected <| model.whichTable == OldTable
]
[ text "Traditional List" ]
]
, text " Words: "
, input
[ size 3
, onInput UpdateCount
, value model.countString
]
[]
, text " "
, button [ onClick Generate ] [ text "Generate" ]
, text " "
, button [ onClick Clear ] [ text "Clear" ]
, text <|
" Entropy: "
++ (String.fromInt <| round <| getEntropy model)
++ " bits"
]
, div []
[ input
[ size <| String.length string + 2
, value string
, style "margin-left" "1em"
, style "font-size" "150%"
, style "padding-left" "0.5em"
, style "color"
(if model.isSecure then
"black"
else
"red"
)
]
[]
]
, h3 []
[ text "Roll Your Own Dice" ]
, p []
[ input
(let
count =
getDiceCount model
in
[ size count
, maxlength count
, onKeyDown DiceKeydown
, onInput <| UpdateDice
, value model.diceString
]
)
[]
, text " "
, button [ onClick LookupDice ] [ text "Lookup" ]
]
, p []
[ checkbox model.enableModifications
ToggleModifications
"modifications"
, if model.enableModifications then
renderModifications (String.length string) model
else
text ""
]
, h3 []
[ text "Generate a Random Number" ]
, p []
[ Html.b [] [ text "N: " ]
, input
[ size 8
, maxlength 8
, onKeyDown RandomMaxDown
, onInput UpdateRandomMaxString
, value model.randomMaxString
]
[]
, text " "
, button [ onClick GenerateRandomNumber ] [ text "Random from 1 to N" ]
]
, p []
(if model.randomMax <= 0 then
[]
else
[ p []
[ Html.b []
[ text
("Random number from 1 to "
++ String.fromInt model.randomMax
++ ": "
)
]
]
, p
[ style "margin-left" "1em"
, style "font-size" "150%"
, style "padding-left" "0.5em"
, style "color"
(if model.isSecure then
"black"
else
"red"
)
]
[ text <| String.fromInt model.randomNumber ]
]
)
, p []
[ text "To generate a passphrase, choose which of the three lists to use from the selector (initially \"EFF Short List\"), fill in \"Words\" with the number of words to generate, and click the \"Generate\" button. To clear the word string, click \"Clear\"."
]
, p []
[ text "If the passphrase is black, then cryptographically-secure random number generation was used. If it is red, then the random number generation was NOT cryptographically secure, because "
, text <|
if model.useSimulator then
"you are running the pure Elm version of the code."
else
"your browser does not support it."
]
, p []
[ text "If you prefer rolling your own dice to using your computer's random number generator, you can type into the box to the left of the \"Lookup\" button four or five numbers (from 1-6) from four or five six-sided dice rolls, then click that button (four dice rolls for the \"EFF Short List\" or five for the other two). It will add one word to the end of the list."
]
, p []
[ text "If you check the \"modifications\" box, you can choose whether to put spaces between the words, the maximum password length, and how many upper case, numeric, and special characters to put in the result. This allows you to easily satisfy the most common password requirements from people who don't understand that length is the only password property that really matters for security." ]
, p []
[ text "If you enter \"N\" and click \"Random from 1 to N\", a random number between 1 and N will be printed below that line." ]
, p []
[ text "The three lists are as follows:"
, ul []
[ li []
[ text "EFF Short List"
, br
, text "The first short list from the "
, effListLink
, text "."
]
, li []
[ text "EFF Long List"
, br
, text "The long list from the "
, effListLink
, text "."
]
, li []
[ text "Traditional List"
, br
, text "The original Diceware word list."
]
]
]
, p []
[ text "For more information about Diceware, see "
, a [ href "http://diceware.com/" ]
[ text "Diceware.com" ]
, text ". "
, text "The classic XKCD cartoon about Diceware is at "
, a [ href "https://xkcd.com/936/" ]
[ text "xkcd.com/936" ]
, text "."
]
, p []
[ text "A five-word Diceware passphrase (from one of the long lists) has 6^5^5 possibilities, over 64 bits. A ten-word Diceware passphrase (again, from one of the long lists) has 6^5^10 possibilities, over 129 bits."
]
, p []
[ text "Source code: "
, a [ href "https://github.com/billstclair/elm-dev-random" ]
[ text "github.com/billstclair/elm-dev-random" ]
, br
, text "Copyright 2017-2018 PI:NAME:<NAME>END_PI"
]
]
numberSelector : Int -> Int -> (String -> Msg) -> Html Msg
numberSelector current max wrapper =
let
intOption i =
option
[ value <| String.fromInt i
, selected (i == current)
]
[ text <|
if i == 0 then
"none"
else
String.fromInt i
]
in
select [ onInput wrapper ] <|
List.map intOption <|
List.range 0 max
renderModifications : Int -> Model -> Html Msg
renderModifications length model =
let
modifications =
model.modifications
in
div [ style "margin-left" "1em" ]
[ checkbox modifications.spaces ToggleSpaces "spaces"
, br
, checkbox modifications.showTotalLength
ToggleShowTotalLength
(if modifications.showTotalLength then
"limit length: "
else
"limit length"
)
, if not modifications.showTotalLength then
text ""
else
span []
[ input
[ size 3
, onInput UpdateTotalLength
, value <| String.fromInt modifications.totalLength
]
[]
, if length > modifications.totalLength then
span [ style "color" "red" ]
[ text " too short" ]
else
text ""
]
, br
, text "uppercase letters: "
, numberSelector modifications.uppercase 5 UpdateUpperCase
, br
, text "numbers: "
, numberSelector modifications.numbers 5 UpdateNumbers
, br
, text "special chars: "
, numberSelector modifications.specialChars 5 UpdateSpecialChars
]
effListLink : Html msg
effListLink =
span []
[ text "EFF's July 2016 \""
, a
[ href
"https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases"
]
[ text "New Wordlists for Random Passphrases" ]
, text "\""
]
| elm |
[
{
"context": "accent ]\n [ Attributes.href <| \"mailto:ellie@tba.sh\" ]\n [ Html.text \"ellie@tba.sh\" ]\n ",
"end": 3544,
"score": 0.9999291301,
"start": 3532,
"tag": "EMAIL",
"value": "ellie@tba.sh"
},
{
"context": " \"mailto:ellie@tba.sh\" ]\n [ Html.text \"ellie@tba.sh\" ]\n , Html.text \". See our \"\n , Htm",
"end": 3585,
"score": 0.9999265075,
"start": 3573,
"tag": "EMAIL",
"value": "ellie@tba.sh"
}
] | assets/src/Pages/Editor/Views/Setup.elm | HenkPoley/ellie | 377 | module Pages.Editor.Views.Setup exposing
( Stage(..)
, view
)
import Css exposing (..)
import Ellie.Ui.Button as Button
import Ellie.Ui.Icon as Icon
import Ellie.Ui.Logo as Logo
import Ellie.Ui.Theme as Theme
import Html.Styled as Html exposing (Html)
import Html.Styled.Attributes as Attributes exposing (css)
type Stage msg
= Authenticating
| Attaching
| AcceptingTerms { termsVersion : Int, onAccept : msg }
| Loading
| Failure
| Opening
view : Stage msg -> Html msg
view loadingStage =
Html.div
[ css
[ displayFlex
, alignItems center
, justifyContent center
, flexDirection column
, height (pct 100)
, position relative
]
]
<|
case loadingStage of
AcceptingTerms state ->
terms state
Failure ->
failure
_ ->
[ Html.styled Html.div
[ width (pct 80)
, maxWidth (px 500)
, position relative
]
[]
[ Logo.animated ]
]
failure : List (Html msg)
failure =
[ Html.styled Html.div
[ width (pct 80)
, maxWidth (px 500)
, position relative
, color Theme.secondaryForeground
, marginBottom (px 24)
]
[]
[ Logo.flat ]
, Html.styled Html.div
[ width (pct 80)
, maxWidth (px 500)
, color Theme.primaryForeground
, fontSize (px 24)
]
[]
[ Html.text "Something went wrong while setting up Ellie! Things may work if you reload and try again, but in case they don't this issue has been reported to the maintainers automatically." ]
]
terms : { termsVersion : Int, onAccept : msg } -> List (Html msg)
terms state =
[ Html.styled Html.div
[ padding (px 16)
, color Theme.primaryForeground
, fontSize (px 24)
, textAlign center
]
[]
[ Html.text "Please accept Ellie's "
, Html.styled Html.a
[ color Theme.accent ]
[ Attributes.href <| "/a/terms/" ++ String.fromInt state.termsVersion
, Attributes.target "_blank"
]
[ Html.text "Terms of Service" ]
, Html.text " to continue."
]
, Html.styled Html.div
[ width (px 700)
, maxWidth (pct 100)
, position relative
, padding (px 16)
]
[]
[ Html.styled Html.iframe
[ border zero
, backgroundColor (hex "#fff")
, width (pct 100)
, position relative
, height (px 400)
]
[ Attributes.src <| "/a/terms/" ++ String.fromInt state.termsVersion
]
[]
]
, Html.styled Html.div
[ padding (px 16)
, color Theme.primaryForeground
, fontSize (px 18)
, textAlign center
, width (px 700)
, maxWidth (pct 100)
]
[]
[ Html.text "Ellie does not collect any personal information. All code posted to Ellie is public, licensed MIT. "
, Html.text "Do not post proprietary or personally identifiable information on Ellie. "
, Html.text "Report abuse or request removal of personal information at "
, Html.styled Html.a
[ color Theme.accent ]
[ Attributes.href <| "mailto:ellie@tba.sh" ]
[ Html.text "ellie@tba.sh" ]
, Html.text ". See our "
, Html.styled Html.a
[ color Theme.accent ]
[ Attributes.href <| "/a/terms/" ++ String.fromInt state.termsVersion ++ "#privacy"
, Attributes.target "_blank"
]
[ Html.text "Privacy Policy" ]
, Html.text " for more details."
]
, Html.div []
[ Button.view
{ icon = Just Icon.Success
, label = "Accept Terms"
, action = Button.click state.onAccept
}
]
]
| 39628 | module Pages.Editor.Views.Setup exposing
( Stage(..)
, view
)
import Css exposing (..)
import Ellie.Ui.Button as Button
import Ellie.Ui.Icon as Icon
import Ellie.Ui.Logo as Logo
import Ellie.Ui.Theme as Theme
import Html.Styled as Html exposing (Html)
import Html.Styled.Attributes as Attributes exposing (css)
type Stage msg
= Authenticating
| Attaching
| AcceptingTerms { termsVersion : Int, onAccept : msg }
| Loading
| Failure
| Opening
view : Stage msg -> Html msg
view loadingStage =
Html.div
[ css
[ displayFlex
, alignItems center
, justifyContent center
, flexDirection column
, height (pct 100)
, position relative
]
]
<|
case loadingStage of
AcceptingTerms state ->
terms state
Failure ->
failure
_ ->
[ Html.styled Html.div
[ width (pct 80)
, maxWidth (px 500)
, position relative
]
[]
[ Logo.animated ]
]
failure : List (Html msg)
failure =
[ Html.styled Html.div
[ width (pct 80)
, maxWidth (px 500)
, position relative
, color Theme.secondaryForeground
, marginBottom (px 24)
]
[]
[ Logo.flat ]
, Html.styled Html.div
[ width (pct 80)
, maxWidth (px 500)
, color Theme.primaryForeground
, fontSize (px 24)
]
[]
[ Html.text "Something went wrong while setting up Ellie! Things may work if you reload and try again, but in case they don't this issue has been reported to the maintainers automatically." ]
]
terms : { termsVersion : Int, onAccept : msg } -> List (Html msg)
terms state =
[ Html.styled Html.div
[ padding (px 16)
, color Theme.primaryForeground
, fontSize (px 24)
, textAlign center
]
[]
[ Html.text "Please accept Ellie's "
, Html.styled Html.a
[ color Theme.accent ]
[ Attributes.href <| "/a/terms/" ++ String.fromInt state.termsVersion
, Attributes.target "_blank"
]
[ Html.text "Terms of Service" ]
, Html.text " to continue."
]
, Html.styled Html.div
[ width (px 700)
, maxWidth (pct 100)
, position relative
, padding (px 16)
]
[]
[ Html.styled Html.iframe
[ border zero
, backgroundColor (hex "#fff")
, width (pct 100)
, position relative
, height (px 400)
]
[ Attributes.src <| "/a/terms/" ++ String.fromInt state.termsVersion
]
[]
]
, Html.styled Html.div
[ padding (px 16)
, color Theme.primaryForeground
, fontSize (px 18)
, textAlign center
, width (px 700)
, maxWidth (pct 100)
]
[]
[ Html.text "Ellie does not collect any personal information. All code posted to Ellie is public, licensed MIT. "
, Html.text "Do not post proprietary or personally identifiable information on Ellie. "
, Html.text "Report abuse or request removal of personal information at "
, Html.styled Html.a
[ color Theme.accent ]
[ Attributes.href <| "mailto:<EMAIL>" ]
[ Html.text "<EMAIL>" ]
, Html.text ". See our "
, Html.styled Html.a
[ color Theme.accent ]
[ Attributes.href <| "/a/terms/" ++ String.fromInt state.termsVersion ++ "#privacy"
, Attributes.target "_blank"
]
[ Html.text "Privacy Policy" ]
, Html.text " for more details."
]
, Html.div []
[ Button.view
{ icon = Just Icon.Success
, label = "Accept Terms"
, action = Button.click state.onAccept
}
]
]
| true | module Pages.Editor.Views.Setup exposing
( Stage(..)
, view
)
import Css exposing (..)
import Ellie.Ui.Button as Button
import Ellie.Ui.Icon as Icon
import Ellie.Ui.Logo as Logo
import Ellie.Ui.Theme as Theme
import Html.Styled as Html exposing (Html)
import Html.Styled.Attributes as Attributes exposing (css)
type Stage msg
= Authenticating
| Attaching
| AcceptingTerms { termsVersion : Int, onAccept : msg }
| Loading
| Failure
| Opening
view : Stage msg -> Html msg
view loadingStage =
Html.div
[ css
[ displayFlex
, alignItems center
, justifyContent center
, flexDirection column
, height (pct 100)
, position relative
]
]
<|
case loadingStage of
AcceptingTerms state ->
terms state
Failure ->
failure
_ ->
[ Html.styled Html.div
[ width (pct 80)
, maxWidth (px 500)
, position relative
]
[]
[ Logo.animated ]
]
failure : List (Html msg)
failure =
[ Html.styled Html.div
[ width (pct 80)
, maxWidth (px 500)
, position relative
, color Theme.secondaryForeground
, marginBottom (px 24)
]
[]
[ Logo.flat ]
, Html.styled Html.div
[ width (pct 80)
, maxWidth (px 500)
, color Theme.primaryForeground
, fontSize (px 24)
]
[]
[ Html.text "Something went wrong while setting up Ellie! Things may work if you reload and try again, but in case they don't this issue has been reported to the maintainers automatically." ]
]
terms : { termsVersion : Int, onAccept : msg } -> List (Html msg)
terms state =
[ Html.styled Html.div
[ padding (px 16)
, color Theme.primaryForeground
, fontSize (px 24)
, textAlign center
]
[]
[ Html.text "Please accept Ellie's "
, Html.styled Html.a
[ color Theme.accent ]
[ Attributes.href <| "/a/terms/" ++ String.fromInt state.termsVersion
, Attributes.target "_blank"
]
[ Html.text "Terms of Service" ]
, Html.text " to continue."
]
, Html.styled Html.div
[ width (px 700)
, maxWidth (pct 100)
, position relative
, padding (px 16)
]
[]
[ Html.styled Html.iframe
[ border zero
, backgroundColor (hex "#fff")
, width (pct 100)
, position relative
, height (px 400)
]
[ Attributes.src <| "/a/terms/" ++ String.fromInt state.termsVersion
]
[]
]
, Html.styled Html.div
[ padding (px 16)
, color Theme.primaryForeground
, fontSize (px 18)
, textAlign center
, width (px 700)
, maxWidth (pct 100)
]
[]
[ Html.text "Ellie does not collect any personal information. All code posted to Ellie is public, licensed MIT. "
, Html.text "Do not post proprietary or personally identifiable information on Ellie. "
, Html.text "Report abuse or request removal of personal information at "
, Html.styled Html.a
[ color Theme.accent ]
[ Attributes.href <| "mailto:PI:EMAIL:<EMAIL>END_PI" ]
[ Html.text "PI:EMAIL:<EMAIL>END_PI" ]
, Html.text ". See our "
, Html.styled Html.a
[ color Theme.accent ]
[ Attributes.href <| "/a/terms/" ++ String.fromInt state.termsVersion ++ "#privacy"
, Attributes.target "_blank"
]
[ Html.text "Privacy Policy" ]
, Html.text " for more details."
]
, Html.div []
[ Button.view
{ icon = Just Icon.Success
, label = "Accept Terms"
, action = Button.click state.onAccept
}
]
]
| elm |
[
{
"context": "e int =\n case int of\n 0 ->\n \"Lance\"\n 1 ->\n \"Gorman\"\n 2 ->\n ",
"end": 6071,
"score": 0.9995137453,
"start": 6066,
"tag": "NAME",
"value": "Lance"
},
{
"context": " ->\n \"Lance\"\n 1 ->\n \"Gorman\"\n 2 ->\n \"Doherty\"\n 3 ->\n",
"end": 6105,
"score": 0.9997665286,
"start": 6099,
"tag": "NAME",
"value": "Gorman"
},
{
"context": "->\n \"Gorman\"\n 2 ->\n \"Doherty\"\n 3 ->\n \"Blair\"\n _ ->\n ",
"end": 6140,
"score": 0.9997901917,
"start": 6133,
"tag": "NAME",
"value": "Doherty"
},
{
"context": ">\n \"Doherty\"\n 3 ->\n \"Blair\"\n _ ->\n \"Dummy\"\n\n\nchooseCmdMsgF",
"end": 6173,
"score": 0.9997637272,
"start": 6168,
"tag": "NAME",
"value": "Blair"
},
{
"context": " ]\n [ text \"Lance\" ],\n button [ onClick (StartGameMe",
"end": 15664,
"score": 0.9993481636,
"start": 15659,
"tag": "NAME",
"value": "Lance"
},
{
"context": " ]\n [ text \"Gorman\" ],\n button [ onClick (StartGameMe",
"end": 16184,
"score": 0.9996795058,
"start": 16178,
"tag": "NAME",
"value": "Gorman"
},
{
"context": " ]\n [ text \"Doherty\" ],\n button [ onClick (StartGameMe",
"end": 16705,
"score": 0.9995689988,
"start": 16698,
"tag": "NAME",
"value": "Doherty"
},
{
"context": " ]\n [ text \"Blair\" ]\n ]\n }\n in\n ",
"end": 17224,
"score": 0.999630332,
"start": 17219,
"tag": "NAME",
"value": "Blair"
}
] | src/Update.elm | lllllcf/Frotun-Chase | 0 | module Update exposing (..)
import Browser.Dom exposing (getViewport)
import List.Extra exposing (getAt)
import Model exposing (initPerspective)
import Random
import Delay exposing (TimeUnit(..))
import List.Extra exposing (..)
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (style)
import Html.Styled.Events exposing (onClick)
import List.Extra exposing (getAt)
import Map exposing (..)
import Round
import Style exposing (..)
import Debug exposing (..)
import Definition exposing (..)
import Phase.Prepare exposing (..)
import Phase.Move exposing (..)
import Animation exposing (..)
import Phase.Implementation exposing (..)
import Phase.End exposing (..)
import Task
--Update---------------------------------------------------------------
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case model.state of
Play ->
play msg model
Win ->
win msg model
Lose ->
lose msg model
Over100 ->
over100 msg model
over100: Msg -> Model -> ( Model, Cmd Msg )
over100 _ model =
let
winner = get model.winnerIndex model.players
viewPopUp1 =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Win!"
, descriptionText = "Under your wise leadership and hard work, we have defeated all the enemies and regained the leadership of the town. A new road is ahead!"
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "God bless us!" ]
]
}
viewPopUp2 =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Lose"
, descriptionText = (name model.winnerIndex) ++ "'s power in the town obviously overthrew us. We had to choose to retreat. The car to the East is ready."
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "I'll be back one day!" ]
]
}
in
if winner.isHuman then
({model | viewPopUp = viewPopUp1, showPopUp = True, state = Play }, Cmd.none)
else
({model | viewPopUp = viewPopUp2, showPopUp = True, state = Play }, Cmd.none)
lose: Msg -> Model -> ( Model, Cmd Msg )
lose msg model =
let
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Lose"
, descriptionText = "The enemy's power in the town obviously overthrew us. We had to choose to retreat. The car to the East is ready."
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "I'll be back one day!" ]
]
}
in
({model | viewPopUp = viewPopUp, showPopUp = True, state = Play }, Cmd.none)
win: Msg -> Model -> ( Model, Cmd Msg )
win msg model =
let
winner = get model.winnerIndex model.players
viewPopUp1 =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Win!"
, descriptionText = "Under your wise leadership and hard work, we have defeated all the enemies and regained the leadership of the town. A new road is ahead!"
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "God bless us!" ]
]
}
viewPopUp2 =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Lose"
, descriptionText = (name model.winnerIndex) ++ "'s power in the town obviously overthrew us. We had to choose to retreat. The car to the East is ready."
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "I'll be back one day!" ]
]
}
in
if winner.isHuman then
({model | viewPopUp = viewPopUp1, showPopUp = True, state = Play }, Cmd.none)
else
({model | viewPopUp = viewPopUp2, showPopUp = True, state = Play }, Cmd.none)
name: Int -> String
name int =
case int of
0 ->
"Lance"
1 ->
"Gorman"
2 ->
"Doherty"
3 ->
"Blair"
_ ->
"Dummy"
chooseCmdMsgForImp: SubRoundPhase -> Cmd Msg
chooseCmdMsgForImp subRoundPhase =
if subRoundPhase == (UseActionDice MoveDice 0) || subRoundPhase == (UseActionDice MoveDice 1) || subRoundPhase == (UseActionDice MoveDice 2) then
Cmd.batch [ Random.generate SpecialMoveNewFace (Random.int 1 6)
, Delay.after 3 Second SpecialMoveStopRoll
]
else
Cmd.batch [ Random.generate RandomNumber (Random.int 1 100)]
randomNumber: Cmd Msg
randomNumber = Cmd.batch [ Random.generate RandomNumber (Random.int 1 100)]
chooseMsgForInit: SubRoundPhase -> ClickState -> Cmd Msg
chooseMsgForInit subPhase clickState =
if subPhase == LetUsStart && (clickState == Click3 || clickState == Click4 ||clickState == Click5 || clickState == Click6) then
Cmd.batch [ Task.perform GetSize getViewport, Random.generate RandomNumber (Random.int 1 100) ]
else
Cmd.batch [ Random.generate RandomNumber (Random.int 1 100) ]
play: Msg -> Model -> ( Model, Cmd Msg )
play msg model =
let movedModel = checkMap model
in
case msg of
StartGameMessage phase subPhase clickState->
case phase of
PreparationPhase ->
(preparePhase movedModel subPhase clickState, chooseMsgForInit subPhase clickState)
MovePhase ->
(movePhase movedModel subPhase clickState, Cmd.batch [ Random.generate RandomNumber (Random.int 1 100),Random.generate AiRandomNumber (Random.list 10000 (Random.int 1 6))])
ImplementationPhase ->
(implementPhase movedModel subPhase clickState, chooseCmdMsgForImp subPhase)
EndPhase ->
(endPhase movedModel subPhase clickState, Cmd.batch [ Random.generate AiRandomNumber (Random.list 100 (Random.int 1 6))])
Roll ->
({ movedModel | canClick = False, showDice = RollingDice }, Cmd.batch [ Random.generate NewFace (Random.int 1 6), Delay.after 3 Second StopRoll ])
NewFace newFace ->
({ movedModel | dice = newFace, players = playerDice movedModel }, randomNumber)
StopRoll ->
({ movedModel | moveSE = True, players = changeDice (updatePlayer movedModel) movedModel, isMoving = True, showDice = FinalDice }, Delay.after 2 Second (StartGameMessage MovePhase Move NotClick))
RollAction ->
({ movedModel | canClick = False, showDice = RollingMoreDice, showActionDiceRespectively = [True, True, True] }, Cmd.batch [ Random.generate NewFaceAction (Random.int 1 216) , Delay.after 3 Second StopRollAction ])
NewFaceAction newFace ->
({ movedModel | dice = newFace }, randomNumber)
StopRollAction ->
let
newModel = handleDiceForAction movedModel
in
({ newModel | isMoving = True, showDice = FinalMoreDice, showActionDice = True, showEndButton = True, canClickEndAction = True }, Cmd.none)
Side ->
if movedModel.sideState == NoSide || movedModel.sideState == HideSide then
({ movedModel | sideState = ShowSide }, randomNumber)
else
({ movedModel | sideState = HideSide }, randomNumber)
Top ->
if movedModel.topState == NoTop || movedModel.topState == HideTop then
({ movedModel | topState = ShowTop }, randomNumber)
else
({ movedModel | topState = HideTop }, randomNumber)
SpecialMoveNewFace newFace ->
({ movedModel | dice = newFace }, randomNumber)
SpecialMoveStopRoll ->
({ movedModel | players = updatePlayer movedModel, isMoving = True, showDice = FinalDice }, Delay.after 2 Second (StartGameMessage ImplementationPhase (UseActionDice NoActionDice 10) Click6))
AddKey value ->
({ movedModel | control = [value] }, randomNumber)
RemoveKey _ ->
({ movedModel | control = [] }, randomNumber)
SelectTile tileIndex buttonNumber->
( selectTile model tileIndex buttonNumber, randomNumber)
ReselectTile tileIndex buttonNumber indicator->
( reselectTile model tileIndex buttonNumber indicator, randomNumber)
RandomNumber number ->
({model | randomNumber = number}, Cmd.none)
GetSize viewport ->
let
gotSizeModel = { movedModel | windowSize = (round viewport.viewport.width, round viewport.viewport.height) }
x = gotSizeModel |> initPerspective |> Tuple.first
y = gotSizeModel |> initPerspective |> Tuple.second
in
({ gotSizeModel | mapMoveX = x, mapMoveY = y }, Cmd.none)
UpdateSize w h ->
({ movedModel | windowSize = (w, h) }, Cmd.none)
ViewDetailedTile index->
({ movedModel | viewDetailed = True, detailTileIndex = index }, Cmd.none)
NoDetail ->
({ movedModel | viewDetailed = False }, Cmd.none)
EndAction ->
({model | showActionDiceRespectively = [False, False, False], viewPopUp = endPopUp model, showPopUp = True, showEndButton = False},randomNumber)
AiRandomNumber list ->
({model | aiRandomNumber = list}, Cmd.none)
Restart ->
(restart model, Cmd.none)
OnJailCount ->
(onJailCount movedModel, randomNumber)
LoadNextRound ->
({ movedModel | viewPopUp = loading, showEndButton = False }, Cmd.batch [Delay.after 2 Second (StartGameMessage EndPhase CountWealth Click1) ])
_ ->
(movedModel, Cmd.none)
changeDice: List Player -> Model -> List Player
changeDice players model =
List.map (\player -> {player | dice = model.dice}) players
loading =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Loading"
, descriptionText = "Load next round."
, buttons = []
}
playerDice: Model -> List Player
playerDice model =
let
players = model.players
newPlayers = List.map (\player -> {player | dice = model.dice}) players
in
newPlayers
onJailCount: Model -> Model
onJailCount model =
let
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Count Wealth"
, descriptionText = "Income: \n Protection fee: " ++ Round.round 0 (Phase.Implementation.calculatePF model) ++ " \n Expenditure: familyCost: -" ++ Round.round 0 ((familyCost (get model.currentPlayer model.players)) / 3) ++ " \n Bribe: -" ++ toString (policeReduceCost (get model.currentPlayer model.players))
++ " " ++ Phase.Implementation.prestigeCount model ++ Phase.Implementation.policeAttentionCount model ++ Phase.Implementation.popularWillCount model ++ Phase.Implementation.policeAttentionBribe model
, buttons = [
button [ onClick (StartGameMessage EndPhase CountWealth Click1)
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "OK" ]
]
}
in
{model | viewPopUp = viewPopUp, showPopUp = True }
endPopUp: Model -> ViewPopUp
endPopUp model=
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Count Wealth"
, descriptionText = "Income: \n Protection fee: " ++ Round.round 0 (Phase.Implementation.calculatePF model) ++ " \n Expenditure: Family cost: -" ++ Round.round 0 ((familyCost (get model.currentPlayer model.players)) / 3) ++ " \n Bribe: -" ++ toString (policeReduceCost (get model.currentPlayer model.players))
++ " " ++ Phase.Implementation.prestigeCount model ++ Phase.Implementation.policeAttentionCount model ++ Phase.Implementation.popularWillCount model ++ Phase.Implementation.policeAttentionBribe model
, buttons = [
button [ onClick LoadNextRound
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "OK" ]
]
}
restart: Model -> Model
restart model =
let
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Restart"
, descriptionText = "Which family do you want to choose?"
, buttons = [
button [ onClick (StartGameMessage PreparationPhase LetUsStart Click3)
, style "width" "20%"
, style "height" "10%"
, style "left" "4%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "Lance" ],
button [ onClick (StartGameMessage PreparationPhase LetUsStart Click4)
, style "width" "20%"
, style "height" "10%"
, style "left" "28%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "Gorman" ],
button [ onClick (StartGameMessage PreparationPhase LetUsStart Click5)
, style "width" "20%"
, style "height" "10%"
, style "left" "52%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "Doherty" ],
button [ onClick (StartGameMessage PreparationPhase LetUsStart Click6)
, style "width" "20%"
, style "height" "10%"
, style "left" "76%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "Blair" ]
]
}
in
{model | viewPopUp = viewPopUp, showPopUp = True}
reselectTile: Model -> Int -> Int -> String -> Model
reselectTile model tileIndex buttonNumber indicator=
let
addOrFight =
if (get buttonNumber model.actionDice) == FightDice then
"fight"
else
"add"
title =
case addOrFight of
"fight" -> "Can't launch a battle here."
"add" -> "Can't send members here."
_ -> " "
description =
case indicator of
"policeStation" -> "You can't select police station to add member or fight."
"jail" -> "You can't select jail to add member pr fight."
"noOthers" -> "No one can fight with you here!"
"noMember" -> "You have no member here."
_ -> " "
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = title
, descriptionText = description ++ " Click to give up."
, buttons = [
button [ if (get buttonNumber model.actionDice) == FightDice then onClick (StartGameMessage ImplementationPhase (UseActionDice FightDice buttonNumber) Click5)
else onClick (StartGameMessage ImplementationPhase (UseActionDice AddDice buttonNumber) Click5)
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "OK" ]
]
}
in
{model | viewPopUp = viewPopUp, canSelectTile = False, showPopUp = True, selectedTileIndex = tileIndex}
selectTile: Model -> Int -> Int -> Model
selectTile model tileIndex buttonNumber=
let
playerIndex = model.currentPlayer
tile = get tileIndex model.map
preTile = get (modBy (List.length model.map) (tileIndex - 1)) model.map
nextTile = get (modBy (List.length model.map) (tileIndex + 1)) model.map
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Do you want to select this tile?"
, descriptionText = "Click to confirm or give up."
, buttons = [
button [ if (get buttonNumber model.actionDice) == FightDice then onClick (StartGameMessage ImplementationPhase (UseActionDice FightDice buttonNumber) Click4)
else onClick (StartGameMessage ImplementationPhase (UseActionDice AddDice buttonNumber) Click4)
, style "width" "20%"
, style "height" "10%"
, style "left" "30%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "Yes" ],
button [ if (get buttonNumber model.actionDice) == FightDice then onClick (StartGameMessage ImplementationPhase (UseActionDice FightDice buttonNumber) Click5)
else onClick (StartGameMessage ImplementationPhase (UseActionDice AddDice buttonNumber) Click5)
, style "width" "20%"
, style "height" "10%"
, style "left" "50%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "No" ]
]
}
viewPopUpCanNotAdd =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Can't send members here"
, descriptionText = "You can't send family to this tile since we don't have enough influence around there."
, buttons = [
button [onClick (StartGameMessage ImplementationPhase (UseActionDice AddDice buttonNumber) Click5)
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "Oh..." ]
]
}
judgeCanAdd = ((get playerIndex preTile.familyMember) + (get playerIndex nextTile.familyMember) + (get playerIndex tile.familyMember)) /= 0
in
if ((get buttonNumber model.actionDice) == AddDice && judgeCanAdd ) || ((get buttonNumber model.actionDice) == FightDice) then
{model | viewPopUp = viewPopUp, canSelectTile = False, showPopUp = True, selectedTileIndex = tileIndex}
else
{model | viewPopUp = viewPopUpCanNotAdd, canSelectTile = False, showPopUp = True, selectedTileIndex = tileIndex}
updatePlayer : Model -> List Player
updatePlayer model =
let
currentPlayer = getCurrentPlayer model
modList =
let
fun : Int -> Int
fun num =
modBy (List.length model.map) num
in
List.map fun (List.range currentPlayer.currentIndex (currentPlayer.currentIndex + model.dice))
frameList = convertToFrame (modList) model.map
newIndex = modBy (List.length model.map) (currentPlayer.currentIndex + model.dice)
newPos = Maybe.withDefault (0, 0) (getAt newIndex (List.map (\this -> this.position) model.map))
updated = { currentPlayer | currentIndex = newIndex, frameList = frameList, currentPos = newPos }
in
(List.take model.currentPlayer model.players) ++ [updated] ++ (List.drop (model.currentPlayer + 1) model.players) | 53629 | module Update exposing (..)
import Browser.Dom exposing (getViewport)
import List.Extra exposing (getAt)
import Model exposing (initPerspective)
import Random
import Delay exposing (TimeUnit(..))
import List.Extra exposing (..)
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (style)
import Html.Styled.Events exposing (onClick)
import List.Extra exposing (getAt)
import Map exposing (..)
import Round
import Style exposing (..)
import Debug exposing (..)
import Definition exposing (..)
import Phase.Prepare exposing (..)
import Phase.Move exposing (..)
import Animation exposing (..)
import Phase.Implementation exposing (..)
import Phase.End exposing (..)
import Task
--Update---------------------------------------------------------------
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case model.state of
Play ->
play msg model
Win ->
win msg model
Lose ->
lose msg model
Over100 ->
over100 msg model
over100: Msg -> Model -> ( Model, Cmd Msg )
over100 _ model =
let
winner = get model.winnerIndex model.players
viewPopUp1 =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Win!"
, descriptionText = "Under your wise leadership and hard work, we have defeated all the enemies and regained the leadership of the town. A new road is ahead!"
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "God bless us!" ]
]
}
viewPopUp2 =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Lose"
, descriptionText = (name model.winnerIndex) ++ "'s power in the town obviously overthrew us. We had to choose to retreat. The car to the East is ready."
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "I'll be back one day!" ]
]
}
in
if winner.isHuman then
({model | viewPopUp = viewPopUp1, showPopUp = True, state = Play }, Cmd.none)
else
({model | viewPopUp = viewPopUp2, showPopUp = True, state = Play }, Cmd.none)
lose: Msg -> Model -> ( Model, Cmd Msg )
lose msg model =
let
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Lose"
, descriptionText = "The enemy's power in the town obviously overthrew us. We had to choose to retreat. The car to the East is ready."
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "I'll be back one day!" ]
]
}
in
({model | viewPopUp = viewPopUp, showPopUp = True, state = Play }, Cmd.none)
win: Msg -> Model -> ( Model, Cmd Msg )
win msg model =
let
winner = get model.winnerIndex model.players
viewPopUp1 =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Win!"
, descriptionText = "Under your wise leadership and hard work, we have defeated all the enemies and regained the leadership of the town. A new road is ahead!"
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "God bless us!" ]
]
}
viewPopUp2 =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Lose"
, descriptionText = (name model.winnerIndex) ++ "'s power in the town obviously overthrew us. We had to choose to retreat. The car to the East is ready."
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "I'll be back one day!" ]
]
}
in
if winner.isHuman then
({model | viewPopUp = viewPopUp1, showPopUp = True, state = Play }, Cmd.none)
else
({model | viewPopUp = viewPopUp2, showPopUp = True, state = Play }, Cmd.none)
name: Int -> String
name int =
case int of
0 ->
"<NAME>"
1 ->
"<NAME>"
2 ->
"<NAME>"
3 ->
"<NAME>"
_ ->
"Dummy"
chooseCmdMsgForImp: SubRoundPhase -> Cmd Msg
chooseCmdMsgForImp subRoundPhase =
if subRoundPhase == (UseActionDice MoveDice 0) || subRoundPhase == (UseActionDice MoveDice 1) || subRoundPhase == (UseActionDice MoveDice 2) then
Cmd.batch [ Random.generate SpecialMoveNewFace (Random.int 1 6)
, Delay.after 3 Second SpecialMoveStopRoll
]
else
Cmd.batch [ Random.generate RandomNumber (Random.int 1 100)]
randomNumber: Cmd Msg
randomNumber = Cmd.batch [ Random.generate RandomNumber (Random.int 1 100)]
chooseMsgForInit: SubRoundPhase -> ClickState -> Cmd Msg
chooseMsgForInit subPhase clickState =
if subPhase == LetUsStart && (clickState == Click3 || clickState == Click4 ||clickState == Click5 || clickState == Click6) then
Cmd.batch [ Task.perform GetSize getViewport, Random.generate RandomNumber (Random.int 1 100) ]
else
Cmd.batch [ Random.generate RandomNumber (Random.int 1 100) ]
play: Msg -> Model -> ( Model, Cmd Msg )
play msg model =
let movedModel = checkMap model
in
case msg of
StartGameMessage phase subPhase clickState->
case phase of
PreparationPhase ->
(preparePhase movedModel subPhase clickState, chooseMsgForInit subPhase clickState)
MovePhase ->
(movePhase movedModel subPhase clickState, Cmd.batch [ Random.generate RandomNumber (Random.int 1 100),Random.generate AiRandomNumber (Random.list 10000 (Random.int 1 6))])
ImplementationPhase ->
(implementPhase movedModel subPhase clickState, chooseCmdMsgForImp subPhase)
EndPhase ->
(endPhase movedModel subPhase clickState, Cmd.batch [ Random.generate AiRandomNumber (Random.list 100 (Random.int 1 6))])
Roll ->
({ movedModel | canClick = False, showDice = RollingDice }, Cmd.batch [ Random.generate NewFace (Random.int 1 6), Delay.after 3 Second StopRoll ])
NewFace newFace ->
({ movedModel | dice = newFace, players = playerDice movedModel }, randomNumber)
StopRoll ->
({ movedModel | moveSE = True, players = changeDice (updatePlayer movedModel) movedModel, isMoving = True, showDice = FinalDice }, Delay.after 2 Second (StartGameMessage MovePhase Move NotClick))
RollAction ->
({ movedModel | canClick = False, showDice = RollingMoreDice, showActionDiceRespectively = [True, True, True] }, Cmd.batch [ Random.generate NewFaceAction (Random.int 1 216) , Delay.after 3 Second StopRollAction ])
NewFaceAction newFace ->
({ movedModel | dice = newFace }, randomNumber)
StopRollAction ->
let
newModel = handleDiceForAction movedModel
in
({ newModel | isMoving = True, showDice = FinalMoreDice, showActionDice = True, showEndButton = True, canClickEndAction = True }, Cmd.none)
Side ->
if movedModel.sideState == NoSide || movedModel.sideState == HideSide then
({ movedModel | sideState = ShowSide }, randomNumber)
else
({ movedModel | sideState = HideSide }, randomNumber)
Top ->
if movedModel.topState == NoTop || movedModel.topState == HideTop then
({ movedModel | topState = ShowTop }, randomNumber)
else
({ movedModel | topState = HideTop }, randomNumber)
SpecialMoveNewFace newFace ->
({ movedModel | dice = newFace }, randomNumber)
SpecialMoveStopRoll ->
({ movedModel | players = updatePlayer movedModel, isMoving = True, showDice = FinalDice }, Delay.after 2 Second (StartGameMessage ImplementationPhase (UseActionDice NoActionDice 10) Click6))
AddKey value ->
({ movedModel | control = [value] }, randomNumber)
RemoveKey _ ->
({ movedModel | control = [] }, randomNumber)
SelectTile tileIndex buttonNumber->
( selectTile model tileIndex buttonNumber, randomNumber)
ReselectTile tileIndex buttonNumber indicator->
( reselectTile model tileIndex buttonNumber indicator, randomNumber)
RandomNumber number ->
({model | randomNumber = number}, Cmd.none)
GetSize viewport ->
let
gotSizeModel = { movedModel | windowSize = (round viewport.viewport.width, round viewport.viewport.height) }
x = gotSizeModel |> initPerspective |> Tuple.first
y = gotSizeModel |> initPerspective |> Tuple.second
in
({ gotSizeModel | mapMoveX = x, mapMoveY = y }, Cmd.none)
UpdateSize w h ->
({ movedModel | windowSize = (w, h) }, Cmd.none)
ViewDetailedTile index->
({ movedModel | viewDetailed = True, detailTileIndex = index }, Cmd.none)
NoDetail ->
({ movedModel | viewDetailed = False }, Cmd.none)
EndAction ->
({model | showActionDiceRespectively = [False, False, False], viewPopUp = endPopUp model, showPopUp = True, showEndButton = False},randomNumber)
AiRandomNumber list ->
({model | aiRandomNumber = list}, Cmd.none)
Restart ->
(restart model, Cmd.none)
OnJailCount ->
(onJailCount movedModel, randomNumber)
LoadNextRound ->
({ movedModel | viewPopUp = loading, showEndButton = False }, Cmd.batch [Delay.after 2 Second (StartGameMessage EndPhase CountWealth Click1) ])
_ ->
(movedModel, Cmd.none)
changeDice: List Player -> Model -> List Player
changeDice players model =
List.map (\player -> {player | dice = model.dice}) players
loading =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Loading"
, descriptionText = "Load next round."
, buttons = []
}
playerDice: Model -> List Player
playerDice model =
let
players = model.players
newPlayers = List.map (\player -> {player | dice = model.dice}) players
in
newPlayers
onJailCount: Model -> Model
onJailCount model =
let
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Count Wealth"
, descriptionText = "Income: \n Protection fee: " ++ Round.round 0 (Phase.Implementation.calculatePF model) ++ " \n Expenditure: familyCost: -" ++ Round.round 0 ((familyCost (get model.currentPlayer model.players)) / 3) ++ " \n Bribe: -" ++ toString (policeReduceCost (get model.currentPlayer model.players))
++ " " ++ Phase.Implementation.prestigeCount model ++ Phase.Implementation.policeAttentionCount model ++ Phase.Implementation.popularWillCount model ++ Phase.Implementation.policeAttentionBribe model
, buttons = [
button [ onClick (StartGameMessage EndPhase CountWealth Click1)
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "OK" ]
]
}
in
{model | viewPopUp = viewPopUp, showPopUp = True }
endPopUp: Model -> ViewPopUp
endPopUp model=
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Count Wealth"
, descriptionText = "Income: \n Protection fee: " ++ Round.round 0 (Phase.Implementation.calculatePF model) ++ " \n Expenditure: Family cost: -" ++ Round.round 0 ((familyCost (get model.currentPlayer model.players)) / 3) ++ " \n Bribe: -" ++ toString (policeReduceCost (get model.currentPlayer model.players))
++ " " ++ Phase.Implementation.prestigeCount model ++ Phase.Implementation.policeAttentionCount model ++ Phase.Implementation.popularWillCount model ++ Phase.Implementation.policeAttentionBribe model
, buttons = [
button [ onClick LoadNextRound
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "OK" ]
]
}
restart: Model -> Model
restart model =
let
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Restart"
, descriptionText = "Which family do you want to choose?"
, buttons = [
button [ onClick (StartGameMessage PreparationPhase LetUsStart Click3)
, style "width" "20%"
, style "height" "10%"
, style "left" "4%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "<NAME>" ],
button [ onClick (StartGameMessage PreparationPhase LetUsStart Click4)
, style "width" "20%"
, style "height" "10%"
, style "left" "28%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "<NAME>" ],
button [ onClick (StartGameMessage PreparationPhase LetUsStart Click5)
, style "width" "20%"
, style "height" "10%"
, style "left" "52%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "<NAME>" ],
button [ onClick (StartGameMessage PreparationPhase LetUsStart Click6)
, style "width" "20%"
, style "height" "10%"
, style "left" "76%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "<NAME>" ]
]
}
in
{model | viewPopUp = viewPopUp, showPopUp = True}
reselectTile: Model -> Int -> Int -> String -> Model
reselectTile model tileIndex buttonNumber indicator=
let
addOrFight =
if (get buttonNumber model.actionDice) == FightDice then
"fight"
else
"add"
title =
case addOrFight of
"fight" -> "Can't launch a battle here."
"add" -> "Can't send members here."
_ -> " "
description =
case indicator of
"policeStation" -> "You can't select police station to add member or fight."
"jail" -> "You can't select jail to add member pr fight."
"noOthers" -> "No one can fight with you here!"
"noMember" -> "You have no member here."
_ -> " "
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = title
, descriptionText = description ++ " Click to give up."
, buttons = [
button [ if (get buttonNumber model.actionDice) == FightDice then onClick (StartGameMessage ImplementationPhase (UseActionDice FightDice buttonNumber) Click5)
else onClick (StartGameMessage ImplementationPhase (UseActionDice AddDice buttonNumber) Click5)
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "OK" ]
]
}
in
{model | viewPopUp = viewPopUp, canSelectTile = False, showPopUp = True, selectedTileIndex = tileIndex}
selectTile: Model -> Int -> Int -> Model
selectTile model tileIndex buttonNumber=
let
playerIndex = model.currentPlayer
tile = get tileIndex model.map
preTile = get (modBy (List.length model.map) (tileIndex - 1)) model.map
nextTile = get (modBy (List.length model.map) (tileIndex + 1)) model.map
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Do you want to select this tile?"
, descriptionText = "Click to confirm or give up."
, buttons = [
button [ if (get buttonNumber model.actionDice) == FightDice then onClick (StartGameMessage ImplementationPhase (UseActionDice FightDice buttonNumber) Click4)
else onClick (StartGameMessage ImplementationPhase (UseActionDice AddDice buttonNumber) Click4)
, style "width" "20%"
, style "height" "10%"
, style "left" "30%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "Yes" ],
button [ if (get buttonNumber model.actionDice) == FightDice then onClick (StartGameMessage ImplementationPhase (UseActionDice FightDice buttonNumber) Click5)
else onClick (StartGameMessage ImplementationPhase (UseActionDice AddDice buttonNumber) Click5)
, style "width" "20%"
, style "height" "10%"
, style "left" "50%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "No" ]
]
}
viewPopUpCanNotAdd =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Can't send members here"
, descriptionText = "You can't send family to this tile since we don't have enough influence around there."
, buttons = [
button [onClick (StartGameMessage ImplementationPhase (UseActionDice AddDice buttonNumber) Click5)
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "Oh..." ]
]
}
judgeCanAdd = ((get playerIndex preTile.familyMember) + (get playerIndex nextTile.familyMember) + (get playerIndex tile.familyMember)) /= 0
in
if ((get buttonNumber model.actionDice) == AddDice && judgeCanAdd ) || ((get buttonNumber model.actionDice) == FightDice) then
{model | viewPopUp = viewPopUp, canSelectTile = False, showPopUp = True, selectedTileIndex = tileIndex}
else
{model | viewPopUp = viewPopUpCanNotAdd, canSelectTile = False, showPopUp = True, selectedTileIndex = tileIndex}
updatePlayer : Model -> List Player
updatePlayer model =
let
currentPlayer = getCurrentPlayer model
modList =
let
fun : Int -> Int
fun num =
modBy (List.length model.map) num
in
List.map fun (List.range currentPlayer.currentIndex (currentPlayer.currentIndex + model.dice))
frameList = convertToFrame (modList) model.map
newIndex = modBy (List.length model.map) (currentPlayer.currentIndex + model.dice)
newPos = Maybe.withDefault (0, 0) (getAt newIndex (List.map (\this -> this.position) model.map))
updated = { currentPlayer | currentIndex = newIndex, frameList = frameList, currentPos = newPos }
in
(List.take model.currentPlayer model.players) ++ [updated] ++ (List.drop (model.currentPlayer + 1) model.players) | true | module Update exposing (..)
import Browser.Dom exposing (getViewport)
import List.Extra exposing (getAt)
import Model exposing (initPerspective)
import Random
import Delay exposing (TimeUnit(..))
import List.Extra exposing (..)
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (style)
import Html.Styled.Events exposing (onClick)
import List.Extra exposing (getAt)
import Map exposing (..)
import Round
import Style exposing (..)
import Debug exposing (..)
import Definition exposing (..)
import Phase.Prepare exposing (..)
import Phase.Move exposing (..)
import Animation exposing (..)
import Phase.Implementation exposing (..)
import Phase.End exposing (..)
import Task
--Update---------------------------------------------------------------
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case model.state of
Play ->
play msg model
Win ->
win msg model
Lose ->
lose msg model
Over100 ->
over100 msg model
over100: Msg -> Model -> ( Model, Cmd Msg )
over100 _ model =
let
winner = get model.winnerIndex model.players
viewPopUp1 =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Win!"
, descriptionText = "Under your wise leadership and hard work, we have defeated all the enemies and regained the leadership of the town. A new road is ahead!"
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "God bless us!" ]
]
}
viewPopUp2 =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Lose"
, descriptionText = (name model.winnerIndex) ++ "'s power in the town obviously overthrew us. We had to choose to retreat. The car to the East is ready."
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "I'll be back one day!" ]
]
}
in
if winner.isHuman then
({model | viewPopUp = viewPopUp1, showPopUp = True, state = Play }, Cmd.none)
else
({model | viewPopUp = viewPopUp2, showPopUp = True, state = Play }, Cmd.none)
lose: Msg -> Model -> ( Model, Cmd Msg )
lose msg model =
let
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Lose"
, descriptionText = "The enemy's power in the town obviously overthrew us. We had to choose to retreat. The car to the East is ready."
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "I'll be back one day!" ]
]
}
in
({model | viewPopUp = viewPopUp, showPopUp = True, state = Play }, Cmd.none)
win: Msg -> Model -> ( Model, Cmd Msg )
win msg model =
let
winner = get model.winnerIndex model.players
viewPopUp1 =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Win!"
, descriptionText = "Under your wise leadership and hard work, we have defeated all the enemies and regained the leadership of the town. A new road is ahead!"
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "God bless us!" ]
]
}
viewPopUp2 =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Lose"
, descriptionText = (name model.winnerIndex) ++ "'s power in the town obviously overthrew us. We had to choose to retreat. The car to the East is ready."
, buttons = [
button [ onClick Restart
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "I'll be back one day!" ]
]
}
in
if winner.isHuman then
({model | viewPopUp = viewPopUp1, showPopUp = True, state = Play }, Cmd.none)
else
({model | viewPopUp = viewPopUp2, showPopUp = True, state = Play }, Cmd.none)
name: Int -> String
name int =
case int of
0 ->
"PI:NAME:<NAME>END_PI"
1 ->
"PI:NAME:<NAME>END_PI"
2 ->
"PI:NAME:<NAME>END_PI"
3 ->
"PI:NAME:<NAME>END_PI"
_ ->
"Dummy"
chooseCmdMsgForImp: SubRoundPhase -> Cmd Msg
chooseCmdMsgForImp subRoundPhase =
if subRoundPhase == (UseActionDice MoveDice 0) || subRoundPhase == (UseActionDice MoveDice 1) || subRoundPhase == (UseActionDice MoveDice 2) then
Cmd.batch [ Random.generate SpecialMoveNewFace (Random.int 1 6)
, Delay.after 3 Second SpecialMoveStopRoll
]
else
Cmd.batch [ Random.generate RandomNumber (Random.int 1 100)]
randomNumber: Cmd Msg
randomNumber = Cmd.batch [ Random.generate RandomNumber (Random.int 1 100)]
chooseMsgForInit: SubRoundPhase -> ClickState -> Cmd Msg
chooseMsgForInit subPhase clickState =
if subPhase == LetUsStart && (clickState == Click3 || clickState == Click4 ||clickState == Click5 || clickState == Click6) then
Cmd.batch [ Task.perform GetSize getViewport, Random.generate RandomNumber (Random.int 1 100) ]
else
Cmd.batch [ Random.generate RandomNumber (Random.int 1 100) ]
play: Msg -> Model -> ( Model, Cmd Msg )
play msg model =
let movedModel = checkMap model
in
case msg of
StartGameMessage phase subPhase clickState->
case phase of
PreparationPhase ->
(preparePhase movedModel subPhase clickState, chooseMsgForInit subPhase clickState)
MovePhase ->
(movePhase movedModel subPhase clickState, Cmd.batch [ Random.generate RandomNumber (Random.int 1 100),Random.generate AiRandomNumber (Random.list 10000 (Random.int 1 6))])
ImplementationPhase ->
(implementPhase movedModel subPhase clickState, chooseCmdMsgForImp subPhase)
EndPhase ->
(endPhase movedModel subPhase clickState, Cmd.batch [ Random.generate AiRandomNumber (Random.list 100 (Random.int 1 6))])
Roll ->
({ movedModel | canClick = False, showDice = RollingDice }, Cmd.batch [ Random.generate NewFace (Random.int 1 6), Delay.after 3 Second StopRoll ])
NewFace newFace ->
({ movedModel | dice = newFace, players = playerDice movedModel }, randomNumber)
StopRoll ->
({ movedModel | moveSE = True, players = changeDice (updatePlayer movedModel) movedModel, isMoving = True, showDice = FinalDice }, Delay.after 2 Second (StartGameMessage MovePhase Move NotClick))
RollAction ->
({ movedModel | canClick = False, showDice = RollingMoreDice, showActionDiceRespectively = [True, True, True] }, Cmd.batch [ Random.generate NewFaceAction (Random.int 1 216) , Delay.after 3 Second StopRollAction ])
NewFaceAction newFace ->
({ movedModel | dice = newFace }, randomNumber)
StopRollAction ->
let
newModel = handleDiceForAction movedModel
in
({ newModel | isMoving = True, showDice = FinalMoreDice, showActionDice = True, showEndButton = True, canClickEndAction = True }, Cmd.none)
Side ->
if movedModel.sideState == NoSide || movedModel.sideState == HideSide then
({ movedModel | sideState = ShowSide }, randomNumber)
else
({ movedModel | sideState = HideSide }, randomNumber)
Top ->
if movedModel.topState == NoTop || movedModel.topState == HideTop then
({ movedModel | topState = ShowTop }, randomNumber)
else
({ movedModel | topState = HideTop }, randomNumber)
SpecialMoveNewFace newFace ->
({ movedModel | dice = newFace }, randomNumber)
SpecialMoveStopRoll ->
({ movedModel | players = updatePlayer movedModel, isMoving = True, showDice = FinalDice }, Delay.after 2 Second (StartGameMessage ImplementationPhase (UseActionDice NoActionDice 10) Click6))
AddKey value ->
({ movedModel | control = [value] }, randomNumber)
RemoveKey _ ->
({ movedModel | control = [] }, randomNumber)
SelectTile tileIndex buttonNumber->
( selectTile model tileIndex buttonNumber, randomNumber)
ReselectTile tileIndex buttonNumber indicator->
( reselectTile model tileIndex buttonNumber indicator, randomNumber)
RandomNumber number ->
({model | randomNumber = number}, Cmd.none)
GetSize viewport ->
let
gotSizeModel = { movedModel | windowSize = (round viewport.viewport.width, round viewport.viewport.height) }
x = gotSizeModel |> initPerspective |> Tuple.first
y = gotSizeModel |> initPerspective |> Tuple.second
in
({ gotSizeModel | mapMoveX = x, mapMoveY = y }, Cmd.none)
UpdateSize w h ->
({ movedModel | windowSize = (w, h) }, Cmd.none)
ViewDetailedTile index->
({ movedModel | viewDetailed = True, detailTileIndex = index }, Cmd.none)
NoDetail ->
({ movedModel | viewDetailed = False }, Cmd.none)
EndAction ->
({model | showActionDiceRespectively = [False, False, False], viewPopUp = endPopUp model, showPopUp = True, showEndButton = False},randomNumber)
AiRandomNumber list ->
({model | aiRandomNumber = list}, Cmd.none)
Restart ->
(restart model, Cmd.none)
OnJailCount ->
(onJailCount movedModel, randomNumber)
LoadNextRound ->
({ movedModel | viewPopUp = loading, showEndButton = False }, Cmd.batch [Delay.after 2 Second (StartGameMessage EndPhase CountWealth Click1) ])
_ ->
(movedModel, Cmd.none)
changeDice: List Player -> Model -> List Player
changeDice players model =
List.map (\player -> {player | dice = model.dice}) players
loading =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Loading"
, descriptionText = "Load next round."
, buttons = []
}
playerDice: Model -> List Player
playerDice model =
let
players = model.players
newPlayers = List.map (\player -> {player | dice = model.dice}) players
in
newPlayers
onJailCount: Model -> Model
onJailCount model =
let
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Count Wealth"
, descriptionText = "Income: \n Protection fee: " ++ Round.round 0 (Phase.Implementation.calculatePF model) ++ " \n Expenditure: familyCost: -" ++ Round.round 0 ((familyCost (get model.currentPlayer model.players)) / 3) ++ " \n Bribe: -" ++ toString (policeReduceCost (get model.currentPlayer model.players))
++ " " ++ Phase.Implementation.prestigeCount model ++ Phase.Implementation.policeAttentionCount model ++ Phase.Implementation.popularWillCount model ++ Phase.Implementation.policeAttentionBribe model
, buttons = [
button [ onClick (StartGameMessage EndPhase CountWealth Click1)
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "OK" ]
]
}
in
{model | viewPopUp = viewPopUp, showPopUp = True }
endPopUp: Model -> ViewPopUp
endPopUp model=
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Count Wealth"
, descriptionText = "Income: \n Protection fee: " ++ Round.round 0 (Phase.Implementation.calculatePF model) ++ " \n Expenditure: Family cost: -" ++ Round.round 0 ((familyCost (get model.currentPlayer model.players)) / 3) ++ " \n Bribe: -" ++ toString (policeReduceCost (get model.currentPlayer model.players))
++ " " ++ Phase.Implementation.prestigeCount model ++ Phase.Implementation.policeAttentionCount model ++ Phase.Implementation.popularWillCount model ++ Phase.Implementation.policeAttentionBribe model
, buttons = [
button [ onClick LoadNextRound
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "OK" ]
]
}
restart: Model -> Model
restart model =
let
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Restart"
, descriptionText = "Which family do you want to choose?"
, buttons = [
button [ onClick (StartGameMessage PreparationPhase LetUsStart Click3)
, style "width" "20%"
, style "height" "10%"
, style "left" "4%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "PI:NAME:<NAME>END_PI" ],
button [ onClick (StartGameMessage PreparationPhase LetUsStart Click4)
, style "width" "20%"
, style "height" "10%"
, style "left" "28%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "PI:NAME:<NAME>END_PI" ],
button [ onClick (StartGameMessage PreparationPhase LetUsStart Click5)
, style "width" "20%"
, style "height" "10%"
, style "left" "52%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "PI:NAME:<NAME>END_PI" ],
button [ onClick (StartGameMessage PreparationPhase LetUsStart Click6)
, style "width" "20%"
, style "height" "10%"
, style "left" "76%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "PI:NAME:<NAME>END_PI" ]
]
}
in
{model | viewPopUp = viewPopUp, showPopUp = True}
reselectTile: Model -> Int -> Int -> String -> Model
reselectTile model tileIndex buttonNumber indicator=
let
addOrFight =
if (get buttonNumber model.actionDice) == FightDice then
"fight"
else
"add"
title =
case addOrFight of
"fight" -> "Can't launch a battle here."
"add" -> "Can't send members here."
_ -> " "
description =
case indicator of
"policeStation" -> "You can't select police station to add member or fight."
"jail" -> "You can't select jail to add member pr fight."
"noOthers" -> "No one can fight with you here!"
"noMember" -> "You have no member here."
_ -> " "
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = title
, descriptionText = description ++ " Click to give up."
, buttons = [
button [ if (get buttonNumber model.actionDice) == FightDice then onClick (StartGameMessage ImplementationPhase (UseActionDice FightDice buttonNumber) Click5)
else onClick (StartGameMessage ImplementationPhase (UseActionDice AddDice buttonNumber) Click5)
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "OK" ]
]
}
in
{model | viewPopUp = viewPopUp, canSelectTile = False, showPopUp = True, selectedTileIndex = tileIndex}
selectTile: Model -> Int -> Int -> Model
selectTile model tileIndex buttonNumber=
let
playerIndex = model.currentPlayer
tile = get tileIndex model.map
preTile = get (modBy (List.length model.map) (tileIndex - 1)) model.map
nextTile = get (modBy (List.length model.map) (tileIndex + 1)) model.map
viewPopUp =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Do you want to select this tile?"
, descriptionText = "Click to confirm or give up."
, buttons = [
button [ if (get buttonNumber model.actionDice) == FightDice then onClick (StartGameMessage ImplementationPhase (UseActionDice FightDice buttonNumber) Click4)
else onClick (StartGameMessage ImplementationPhase (UseActionDice AddDice buttonNumber) Click4)
, style "width" "20%"
, style "height" "10%"
, style "left" "30%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "Yes" ],
button [ if (get buttonNumber model.actionDice) == FightDice then onClick (StartGameMessage ImplementationPhase (UseActionDice FightDice buttonNumber) Click5)
else onClick (StartGameMessage ImplementationPhase (UseActionDice AddDice buttonNumber) Click5)
, style "width" "20%"
, style "height" "10%"
, style "left" "50%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonNo
]
[ text "No" ]
]
}
viewPopUpCanNotAdd =
{ backgroundImage = "url(./src/image/event.jpg)"
, title = "Can't send members here"
, descriptionText = "You can't send family to this tile since we don't have enough influence around there."
, buttons = [
button [onClick (StartGameMessage ImplementationPhase (UseActionDice AddDice buttonNumber) Click5)
, style "width" "20%"
, style "height" "10%"
, style "left" "40%"
, style "top" "80%"
, style "position" "absolute"
, style "font-size" "1vw"
, style "font-weight" "bold"
, buttonYes
]
[ text "Oh..." ]
]
}
judgeCanAdd = ((get playerIndex preTile.familyMember) + (get playerIndex nextTile.familyMember) + (get playerIndex tile.familyMember)) /= 0
in
if ((get buttonNumber model.actionDice) == AddDice && judgeCanAdd ) || ((get buttonNumber model.actionDice) == FightDice) then
{model | viewPopUp = viewPopUp, canSelectTile = False, showPopUp = True, selectedTileIndex = tileIndex}
else
{model | viewPopUp = viewPopUpCanNotAdd, canSelectTile = False, showPopUp = True, selectedTileIndex = tileIndex}
updatePlayer : Model -> List Player
updatePlayer model =
let
currentPlayer = getCurrentPlayer model
modList =
let
fun : Int -> Int
fun num =
modBy (List.length model.map) num
in
List.map fun (List.range currentPlayer.currentIndex (currentPlayer.currentIndex + model.dice))
frameList = convertToFrame (modList) model.map
newIndex = modBy (List.length model.map) (currentPlayer.currentIndex + model.dice)
newPos = Maybe.withDefault (0, 0) (getAt newIndex (List.map (\this -> this.position) model.map))
updated = { currentPlayer | currentIndex = newIndex, frameList = frameList, currentPos = newPos }
in
(List.take model.currentPlayer model.players) ++ [updated] ++ (List.drop (model.currentPlayer + 1) model.players) | elm |
[
{
"context": "put UpdateFormName\n , placeholder \"Name\"\n , type_ \"text\"\n ,",
"end": 6980,
"score": 0.9905667901,
"start": 6976,
"tag": "NAME",
"value": "Name"
}
] | ui/src/Page/Configs.elm | lifesum/configsum | 4 | module Page.Configs exposing (Model, Msg, init, initBase, update, view)
import Date exposing (Date)
import Dict exposing (Dict)
import Html
exposing
( Html
, div
, h1
, input
, label
, option
, section
, select
, span
, strong
, table
, tbody
, td
, text
, th
, thead
, tr
)
import Html.Attributes
exposing
( checked
, class
, classList
, colspan
, id
, for
, placeholder
, value
, type_
)
import Html.Events exposing (on, onCheck, onClick, onInput, targetValue)
import Http
import Json.Decode as Json
import String
import Task exposing (Task)
import Time exposing (Time)
import Api.Client
import Api.Config as Api
import Data.Client exposing (Client)
import Data.Config exposing (Config)
import Data.Parameter exposing (Parameter(..))
import Page.Errored exposing (PageLoadError, pageLoadError)
import Route
import View.Date
import View.Error
import View.Parameter
-- MODEL
type alias Model =
{ clients : List Client
, config : Maybe Config
, configs : List Config
, error : Maybe Http.Error
, formClientId : String
, formName : String
, newParameter : Parameter
, now : Time
, showAddConfig : Bool
, showAddParameter : Bool
}
initModel : Time -> List Client -> Maybe Config -> List Config -> Model
initModel now clients config configs =
Model clients config configs Nothing "" "" (BoolParameter "" False) now False False
init : Time -> Task PageLoadError Model
init now =
let
model clients configs =
initModel now clients Nothing configs
in
Api.listBase
|> Http.toTask
|> Task.map2 model (Api.Client.list |> Http.toTask)
|> Task.mapError (\err -> pageLoadError "Configs" err)
initBase : Time -> String -> Task PageLoadError Model
initBase now id =
Api.getBase id
|> Http.toTask
|> Task.map (\config -> initModel now [] (Just config) [])
|> Task.mapError (\err -> pageLoadError "Configs" err)
initParameter : String -> String -> Parameter
initParameter name typeName =
case typeName of
"bool" ->
BoolParameter name False
"number" ->
NumberParameter name 0
"numbers" ->
NumbersParameter name []
"string" ->
StringParameter name ""
"strings" ->
StringsParameter name []
_ ->
BoolParameter name False
-- UPDATE
type Msg
= ConfigLoaded (Result Http.Error Config)
| FormSubmit
| FormSubmitted (Result Http.Error Config)
| ParameterFormSubmit Config
| ParameterFormSubmitted (Result Http.Error Config)
| SelectConfig String
| ToggleAddConfig
| ToggleAddParameter
| UpdateFormClientId String
| UpdateFormName String
| UpdateParameterName String
| UpdateParameterType String
| UpdateValueBool Bool
| UpdateValueNumber Int
| UpdateValueNumbers (List Int)
| UpdateValueString String
| UpdateValueStrings (List String)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
let
name =
View.Parameter.name model.newParameter
in
case (Debug.log "CONFIG MSG" msg) of
ConfigLoaded (Err error) ->
( { model | error = Just error }, Cmd.none )
ConfigLoaded (Ok config) ->
( { model | config = Just config, error = Nothing }, Cmd.none )
FormSubmit ->
( { model | error = Nothing }
, Api.createBase model.formClientId model.formName
|> Http.send FormSubmitted
)
FormSubmitted (Err error) ->
( { model | error = Just error }, Cmd.none )
FormSubmitted (Ok config) ->
( initModel model.now model.clients Nothing (List.append model.configs [ config ]), Cmd.none )
ParameterFormSubmit config ->
( model
, Api.addParameter config.id (List.append config.parameters [ model.newParameter ])
|> Http.send ParameterFormSubmitted
)
ParameterFormSubmitted (Err error) ->
( { model | error = Just error }, Cmd.none )
ParameterFormSubmitted (Ok config) ->
( initModel model.now model.clients (Just config) [], Cmd.none )
SelectConfig id ->
( model, Route.navigate (Route.ConfigBase id) )
ToggleAddConfig ->
let
clientId =
case (List.head model.clients) of
Just client ->
client.id
Nothing ->
""
in
( { model | formClientId = clientId, showAddConfig = not model.showAddConfig }, Cmd.none )
ToggleAddParameter ->
( { model | showAddParameter = not model.showAddParameter }, Cmd.none )
UpdateFormName formName ->
( { model | formName = formName }, Cmd.none )
UpdateFormClientId id ->
( { model | formClientId = id }, Cmd.none )
UpdateParameterName name ->
( { model | newParameter = paramUpdateName name model.newParameter }, Cmd.none )
UpdateParameterType selectedType ->
( { model | newParameter = (initParameter name selectedType) }, Cmd.none )
UpdateValueBool val ->
( { model | newParameter = (BoolParameter name val) }, Cmd.none )
UpdateValueNumber val ->
( { model | newParameter = (NumberParameter name val) }, Cmd.none )
UpdateValueNumbers vals ->
( { model | newParameter = (NumbersParameter name vals) }, Cmd.none )
UpdateValueString val ->
( { model | newParameter = (StringParameter name val) }, Cmd.none )
UpdateValueStrings vals ->
( { model | newParameter = (StringsParameter name vals) }, Cmd.none )
-- VIEW
view : Model -> Html Msg
view model =
case model.config of
Just config ->
viewConfig model.now config model.showAddParameter model.newParameter model.error
Nothing ->
viewList model
viewAdd : Int -> String -> Msg -> Html Msg
viewAdd tdSpan labelText msg =
tr [ class "add", onClick msg ]
[ td [ class "type", colspan tdSpan ] [ text labelText ]
]
viewAddConfigForm : String -> List Client -> List (Html Msg)
viewAddConfigForm name clients =
[ tr [ class "form" ]
[ td [ class "name" ]
[ input
[ onInput UpdateFormName
, placeholder "Name"
, type_ "text"
, value name
]
[]
]
, td []
[ select
[ on "change" (Json.map UpdateFormClientId targetValue) ]
(List.map (\c -> viewOption c.name c.id) clients)
]
, td []
[]
, td []
[]
]
, tr [ class "save", onClick FormSubmit ]
[ td [ class "type", colspan 4 ] [ text "save config" ]
]
]
viewCard : ( String, String ) -> Html Msg
viewCard ( key, value ) =
div [ class "card" ]
[ span [] [ text key ]
, strong [] [ text value ]
]
viewConfig : Time -> Config -> Bool -> Parameter -> Maybe Http.Error -> Html Msg
viewConfig now config showAdd parameter error =
let
action =
if showAdd then
viewParameterForm config parameter
else
[ viewAdd 3 "add parameter" ToggleAddParameter ]
in
div []
[ h1 []
[ text "Configs/Base/"
, strong [ class "highlight" ] [ text config.name ]
]
, View.Error.view error
, viewMeta config now
, View.Parameter.viewTable action config.parameters
]
viewItem : Dict String Client -> Config -> Html Msg
viewItem clients config =
let
client =
case (Dict.get config.clientId clients) of
Just client ->
client.name
Nothing ->
config.clientId
in
tr
[ class "action"
, (Route.href (Route.ConfigBase config.id))
, onClick (SelectConfig config.id)
]
[ td [] [ text config.name ]
, td [] [ text client ]
, td [] [ text config.id ]
, td [] [ text (toString (List.length config.parameters)) ]
]
viewList : Model -> Html Msg
viewList model =
let
action =
if model.showAddConfig then
viewAddConfigForm model.formName model.clients
else
[ viewAdd 4 "add config" ToggleAddConfig
]
clients =
Dict.fromList (List.map (\c -> ( c.id, c )) model.clients)
in
div []
[ h1 []
[ text "Configs/"
, strong [] [ text "Base" ]
]
, View.Error.view model.error
, table []
[ thead []
[ tr []
[ th [ class "name" ] [ text "name" ]
, th [ class "client" ] [ text "client" ]
, th [ class "id" ] [ text "id" ]
, th [] [ text "parameters" ]
]
]
, tbody [] (List.append (List.map (viewItem clients) model.configs) action)
]
]
viewMeta : Config -> Time -> Html Msg
viewMeta config now =
let
cards =
[ ( "id", config.id )
, ( "client", config.clientId )
, ( "created", (View.Date.short config.createdAt) )
, ( "updated", (View.Date.pretty now config.updatedAt) )
]
in
section [ class "meta" ] (List.map viewCard cards)
viewOption : String -> String -> Html Msg
viewOption name val =
option [ value val ] [ text name ]
viewParameterForm : Config -> Parameter -> List (Html Msg)
viewParameterForm config parameter =
let
options =
[ "bool"
, "number"
, "string"
-- "numbers"
-- "strings"
]
in
[ tr [ class "form" ]
[ td [ class "name" ]
[ input
[ onInput UpdateParameterName
, placeholder "Name"
, type_ "text"
, value (View.Parameter.name parameter)
]
[]
]
, td []
[ select [ on "change" (Json.map UpdateParameterType targetValue) ] (List.map (\o -> viewOption o o) options)
]
, td [ class "value" ] [ viewParameterFormValue parameter ]
]
, tr [ class "save", onClick (ParameterFormSubmit config) ]
[ td [ classList [ ( "type", True ) ], colspan 3 ] [ text "save parameter" ]
]
]
viewParameterFormValue : Parameter -> Html Msg
viewParameterFormValue parameter =
case parameter of
BoolParameter _ v ->
div []
[ input
[ checked v
, id "new-bool"
, onCheck UpdateValueBool
, type_ "checkbox"
]
[]
, label [ for "new-bool" ] []
]
NumberParameter _ v ->
input
[ on "input" (Json.map UpdateValueNumber targetNumber)
, placeholder "Value"
, type_ "text"
, value (paramValue parameter)
]
[]
NumbersParameter _ v ->
input
[ on "input" (Json.map UpdateValueNumbers targetNumbers)
, placeholder "Value"
, type_ "text"
, value (paramValue parameter)
]
[]
StringParameter _ v ->
input
[ onInput UpdateValueString
, placeholder "Value"
, type_ "text"
, value v
]
[]
StringsParameter _ v ->
input
[ on "input" (Json.map UpdateValueStrings targetStrings)
, placeholder "Value"
, type_ "text"
, value (paramValue parameter)
]
[]
-- HELPER
paramUpdateName : String -> Parameter -> Parameter
paramUpdateName name parameter =
case parameter of
BoolParameter _ value ->
BoolParameter name value
NumberParameter _ value ->
NumberParameter name value
NumbersParameter _ value ->
NumbersParameter name value
StringParameter _ value ->
StringParameter name value
StringsParameter _ value ->
StringsParameter name value
paramValue : Parameter -> String
paramValue parameter =
case parameter of
BoolParameter _ val ->
case val of
True ->
"True"
False ->
"False"
NumberParameter _ val ->
toString val
NumbersParameter _ vals ->
String.join " " (List.map (\v -> toString v) vals)
StringParameter _ val ->
val
StringsParameter _ vals ->
String.join " " vals
toInt : String -> Int
toInt input =
case (String.toInt input) of
Err err ->
0
Ok v ->
v
targetNumber : Json.Decoder Int
targetNumber =
Json.map toInt (Json.at [ "target", "value" ] Json.string)
targetNumbers : Json.Decoder (List Int)
targetNumbers =
let
toInts input =
List.map (\v -> toInt v) (String.split " " input)
in
Json.map toInts (Json.at [ "target", "value" ] Json.string)
targetStrings : Json.Decoder (List String)
targetStrings =
let
toStrings input =
String.split " " input
in
Json.map toStrings (Json.at [ "target", "value" ] Json.string)
| 58542 | module Page.Configs exposing (Model, Msg, init, initBase, update, view)
import Date exposing (Date)
import Dict exposing (Dict)
import Html
exposing
( Html
, div
, h1
, input
, label
, option
, section
, select
, span
, strong
, table
, tbody
, td
, text
, th
, thead
, tr
)
import Html.Attributes
exposing
( checked
, class
, classList
, colspan
, id
, for
, placeholder
, value
, type_
)
import Html.Events exposing (on, onCheck, onClick, onInput, targetValue)
import Http
import Json.Decode as Json
import String
import Task exposing (Task)
import Time exposing (Time)
import Api.Client
import Api.Config as Api
import Data.Client exposing (Client)
import Data.Config exposing (Config)
import Data.Parameter exposing (Parameter(..))
import Page.Errored exposing (PageLoadError, pageLoadError)
import Route
import View.Date
import View.Error
import View.Parameter
-- MODEL
type alias Model =
{ clients : List Client
, config : Maybe Config
, configs : List Config
, error : Maybe Http.Error
, formClientId : String
, formName : String
, newParameter : Parameter
, now : Time
, showAddConfig : Bool
, showAddParameter : Bool
}
initModel : Time -> List Client -> Maybe Config -> List Config -> Model
initModel now clients config configs =
Model clients config configs Nothing "" "" (BoolParameter "" False) now False False
init : Time -> Task PageLoadError Model
init now =
let
model clients configs =
initModel now clients Nothing configs
in
Api.listBase
|> Http.toTask
|> Task.map2 model (Api.Client.list |> Http.toTask)
|> Task.mapError (\err -> pageLoadError "Configs" err)
initBase : Time -> String -> Task PageLoadError Model
initBase now id =
Api.getBase id
|> Http.toTask
|> Task.map (\config -> initModel now [] (Just config) [])
|> Task.mapError (\err -> pageLoadError "Configs" err)
initParameter : String -> String -> Parameter
initParameter name typeName =
case typeName of
"bool" ->
BoolParameter name False
"number" ->
NumberParameter name 0
"numbers" ->
NumbersParameter name []
"string" ->
StringParameter name ""
"strings" ->
StringsParameter name []
_ ->
BoolParameter name False
-- UPDATE
type Msg
= ConfigLoaded (Result Http.Error Config)
| FormSubmit
| FormSubmitted (Result Http.Error Config)
| ParameterFormSubmit Config
| ParameterFormSubmitted (Result Http.Error Config)
| SelectConfig String
| ToggleAddConfig
| ToggleAddParameter
| UpdateFormClientId String
| UpdateFormName String
| UpdateParameterName String
| UpdateParameterType String
| UpdateValueBool Bool
| UpdateValueNumber Int
| UpdateValueNumbers (List Int)
| UpdateValueString String
| UpdateValueStrings (List String)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
let
name =
View.Parameter.name model.newParameter
in
case (Debug.log "CONFIG MSG" msg) of
ConfigLoaded (Err error) ->
( { model | error = Just error }, Cmd.none )
ConfigLoaded (Ok config) ->
( { model | config = Just config, error = Nothing }, Cmd.none )
FormSubmit ->
( { model | error = Nothing }
, Api.createBase model.formClientId model.formName
|> Http.send FormSubmitted
)
FormSubmitted (Err error) ->
( { model | error = Just error }, Cmd.none )
FormSubmitted (Ok config) ->
( initModel model.now model.clients Nothing (List.append model.configs [ config ]), Cmd.none )
ParameterFormSubmit config ->
( model
, Api.addParameter config.id (List.append config.parameters [ model.newParameter ])
|> Http.send ParameterFormSubmitted
)
ParameterFormSubmitted (Err error) ->
( { model | error = Just error }, Cmd.none )
ParameterFormSubmitted (Ok config) ->
( initModel model.now model.clients (Just config) [], Cmd.none )
SelectConfig id ->
( model, Route.navigate (Route.ConfigBase id) )
ToggleAddConfig ->
let
clientId =
case (List.head model.clients) of
Just client ->
client.id
Nothing ->
""
in
( { model | formClientId = clientId, showAddConfig = not model.showAddConfig }, Cmd.none )
ToggleAddParameter ->
( { model | showAddParameter = not model.showAddParameter }, Cmd.none )
UpdateFormName formName ->
( { model | formName = formName }, Cmd.none )
UpdateFormClientId id ->
( { model | formClientId = id }, Cmd.none )
UpdateParameterName name ->
( { model | newParameter = paramUpdateName name model.newParameter }, Cmd.none )
UpdateParameterType selectedType ->
( { model | newParameter = (initParameter name selectedType) }, Cmd.none )
UpdateValueBool val ->
( { model | newParameter = (BoolParameter name val) }, Cmd.none )
UpdateValueNumber val ->
( { model | newParameter = (NumberParameter name val) }, Cmd.none )
UpdateValueNumbers vals ->
( { model | newParameter = (NumbersParameter name vals) }, Cmd.none )
UpdateValueString val ->
( { model | newParameter = (StringParameter name val) }, Cmd.none )
UpdateValueStrings vals ->
( { model | newParameter = (StringsParameter name vals) }, Cmd.none )
-- VIEW
view : Model -> Html Msg
view model =
case model.config of
Just config ->
viewConfig model.now config model.showAddParameter model.newParameter model.error
Nothing ->
viewList model
viewAdd : Int -> String -> Msg -> Html Msg
viewAdd tdSpan labelText msg =
tr [ class "add", onClick msg ]
[ td [ class "type", colspan tdSpan ] [ text labelText ]
]
viewAddConfigForm : String -> List Client -> List (Html Msg)
viewAddConfigForm name clients =
[ tr [ class "form" ]
[ td [ class "name" ]
[ input
[ onInput UpdateFormName
, placeholder "<NAME>"
, type_ "text"
, value name
]
[]
]
, td []
[ select
[ on "change" (Json.map UpdateFormClientId targetValue) ]
(List.map (\c -> viewOption c.name c.id) clients)
]
, td []
[]
, td []
[]
]
, tr [ class "save", onClick FormSubmit ]
[ td [ class "type", colspan 4 ] [ text "save config" ]
]
]
viewCard : ( String, String ) -> Html Msg
viewCard ( key, value ) =
div [ class "card" ]
[ span [] [ text key ]
, strong [] [ text value ]
]
viewConfig : Time -> Config -> Bool -> Parameter -> Maybe Http.Error -> Html Msg
viewConfig now config showAdd parameter error =
let
action =
if showAdd then
viewParameterForm config parameter
else
[ viewAdd 3 "add parameter" ToggleAddParameter ]
in
div []
[ h1 []
[ text "Configs/Base/"
, strong [ class "highlight" ] [ text config.name ]
]
, View.Error.view error
, viewMeta config now
, View.Parameter.viewTable action config.parameters
]
viewItem : Dict String Client -> Config -> Html Msg
viewItem clients config =
let
client =
case (Dict.get config.clientId clients) of
Just client ->
client.name
Nothing ->
config.clientId
in
tr
[ class "action"
, (Route.href (Route.ConfigBase config.id))
, onClick (SelectConfig config.id)
]
[ td [] [ text config.name ]
, td [] [ text client ]
, td [] [ text config.id ]
, td [] [ text (toString (List.length config.parameters)) ]
]
viewList : Model -> Html Msg
viewList model =
let
action =
if model.showAddConfig then
viewAddConfigForm model.formName model.clients
else
[ viewAdd 4 "add config" ToggleAddConfig
]
clients =
Dict.fromList (List.map (\c -> ( c.id, c )) model.clients)
in
div []
[ h1 []
[ text "Configs/"
, strong [] [ text "Base" ]
]
, View.Error.view model.error
, table []
[ thead []
[ tr []
[ th [ class "name" ] [ text "name" ]
, th [ class "client" ] [ text "client" ]
, th [ class "id" ] [ text "id" ]
, th [] [ text "parameters" ]
]
]
, tbody [] (List.append (List.map (viewItem clients) model.configs) action)
]
]
viewMeta : Config -> Time -> Html Msg
viewMeta config now =
let
cards =
[ ( "id", config.id )
, ( "client", config.clientId )
, ( "created", (View.Date.short config.createdAt) )
, ( "updated", (View.Date.pretty now config.updatedAt) )
]
in
section [ class "meta" ] (List.map viewCard cards)
viewOption : String -> String -> Html Msg
viewOption name val =
option [ value val ] [ text name ]
viewParameterForm : Config -> Parameter -> List (Html Msg)
viewParameterForm config parameter =
let
options =
[ "bool"
, "number"
, "string"
-- "numbers"
-- "strings"
]
in
[ tr [ class "form" ]
[ td [ class "name" ]
[ input
[ onInput UpdateParameterName
, placeholder "Name"
, type_ "text"
, value (View.Parameter.name parameter)
]
[]
]
, td []
[ select [ on "change" (Json.map UpdateParameterType targetValue) ] (List.map (\o -> viewOption o o) options)
]
, td [ class "value" ] [ viewParameterFormValue parameter ]
]
, tr [ class "save", onClick (ParameterFormSubmit config) ]
[ td [ classList [ ( "type", True ) ], colspan 3 ] [ text "save parameter" ]
]
]
viewParameterFormValue : Parameter -> Html Msg
viewParameterFormValue parameter =
case parameter of
BoolParameter _ v ->
div []
[ input
[ checked v
, id "new-bool"
, onCheck UpdateValueBool
, type_ "checkbox"
]
[]
, label [ for "new-bool" ] []
]
NumberParameter _ v ->
input
[ on "input" (Json.map UpdateValueNumber targetNumber)
, placeholder "Value"
, type_ "text"
, value (paramValue parameter)
]
[]
NumbersParameter _ v ->
input
[ on "input" (Json.map UpdateValueNumbers targetNumbers)
, placeholder "Value"
, type_ "text"
, value (paramValue parameter)
]
[]
StringParameter _ v ->
input
[ onInput UpdateValueString
, placeholder "Value"
, type_ "text"
, value v
]
[]
StringsParameter _ v ->
input
[ on "input" (Json.map UpdateValueStrings targetStrings)
, placeholder "Value"
, type_ "text"
, value (paramValue parameter)
]
[]
-- HELPER
paramUpdateName : String -> Parameter -> Parameter
paramUpdateName name parameter =
case parameter of
BoolParameter _ value ->
BoolParameter name value
NumberParameter _ value ->
NumberParameter name value
NumbersParameter _ value ->
NumbersParameter name value
StringParameter _ value ->
StringParameter name value
StringsParameter _ value ->
StringsParameter name value
paramValue : Parameter -> String
paramValue parameter =
case parameter of
BoolParameter _ val ->
case val of
True ->
"True"
False ->
"False"
NumberParameter _ val ->
toString val
NumbersParameter _ vals ->
String.join " " (List.map (\v -> toString v) vals)
StringParameter _ val ->
val
StringsParameter _ vals ->
String.join " " vals
toInt : String -> Int
toInt input =
case (String.toInt input) of
Err err ->
0
Ok v ->
v
targetNumber : Json.Decoder Int
targetNumber =
Json.map toInt (Json.at [ "target", "value" ] Json.string)
targetNumbers : Json.Decoder (List Int)
targetNumbers =
let
toInts input =
List.map (\v -> toInt v) (String.split " " input)
in
Json.map toInts (Json.at [ "target", "value" ] Json.string)
targetStrings : Json.Decoder (List String)
targetStrings =
let
toStrings input =
String.split " " input
in
Json.map toStrings (Json.at [ "target", "value" ] Json.string)
| true | module Page.Configs exposing (Model, Msg, init, initBase, update, view)
import Date exposing (Date)
import Dict exposing (Dict)
import Html
exposing
( Html
, div
, h1
, input
, label
, option
, section
, select
, span
, strong
, table
, tbody
, td
, text
, th
, thead
, tr
)
import Html.Attributes
exposing
( checked
, class
, classList
, colspan
, id
, for
, placeholder
, value
, type_
)
import Html.Events exposing (on, onCheck, onClick, onInput, targetValue)
import Http
import Json.Decode as Json
import String
import Task exposing (Task)
import Time exposing (Time)
import Api.Client
import Api.Config as Api
import Data.Client exposing (Client)
import Data.Config exposing (Config)
import Data.Parameter exposing (Parameter(..))
import Page.Errored exposing (PageLoadError, pageLoadError)
import Route
import View.Date
import View.Error
import View.Parameter
-- MODEL
type alias Model =
{ clients : List Client
, config : Maybe Config
, configs : List Config
, error : Maybe Http.Error
, formClientId : String
, formName : String
, newParameter : Parameter
, now : Time
, showAddConfig : Bool
, showAddParameter : Bool
}
initModel : Time -> List Client -> Maybe Config -> List Config -> Model
initModel now clients config configs =
Model clients config configs Nothing "" "" (BoolParameter "" False) now False False
init : Time -> Task PageLoadError Model
init now =
let
model clients configs =
initModel now clients Nothing configs
in
Api.listBase
|> Http.toTask
|> Task.map2 model (Api.Client.list |> Http.toTask)
|> Task.mapError (\err -> pageLoadError "Configs" err)
initBase : Time -> String -> Task PageLoadError Model
initBase now id =
Api.getBase id
|> Http.toTask
|> Task.map (\config -> initModel now [] (Just config) [])
|> Task.mapError (\err -> pageLoadError "Configs" err)
initParameter : String -> String -> Parameter
initParameter name typeName =
case typeName of
"bool" ->
BoolParameter name False
"number" ->
NumberParameter name 0
"numbers" ->
NumbersParameter name []
"string" ->
StringParameter name ""
"strings" ->
StringsParameter name []
_ ->
BoolParameter name False
-- UPDATE
type Msg
= ConfigLoaded (Result Http.Error Config)
| FormSubmit
| FormSubmitted (Result Http.Error Config)
| ParameterFormSubmit Config
| ParameterFormSubmitted (Result Http.Error Config)
| SelectConfig String
| ToggleAddConfig
| ToggleAddParameter
| UpdateFormClientId String
| UpdateFormName String
| UpdateParameterName String
| UpdateParameterType String
| UpdateValueBool Bool
| UpdateValueNumber Int
| UpdateValueNumbers (List Int)
| UpdateValueString String
| UpdateValueStrings (List String)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
let
name =
View.Parameter.name model.newParameter
in
case (Debug.log "CONFIG MSG" msg) of
ConfigLoaded (Err error) ->
( { model | error = Just error }, Cmd.none )
ConfigLoaded (Ok config) ->
( { model | config = Just config, error = Nothing }, Cmd.none )
FormSubmit ->
( { model | error = Nothing }
, Api.createBase model.formClientId model.formName
|> Http.send FormSubmitted
)
FormSubmitted (Err error) ->
( { model | error = Just error }, Cmd.none )
FormSubmitted (Ok config) ->
( initModel model.now model.clients Nothing (List.append model.configs [ config ]), Cmd.none )
ParameterFormSubmit config ->
( model
, Api.addParameter config.id (List.append config.parameters [ model.newParameter ])
|> Http.send ParameterFormSubmitted
)
ParameterFormSubmitted (Err error) ->
( { model | error = Just error }, Cmd.none )
ParameterFormSubmitted (Ok config) ->
( initModel model.now model.clients (Just config) [], Cmd.none )
SelectConfig id ->
( model, Route.navigate (Route.ConfigBase id) )
ToggleAddConfig ->
let
clientId =
case (List.head model.clients) of
Just client ->
client.id
Nothing ->
""
in
( { model | formClientId = clientId, showAddConfig = not model.showAddConfig }, Cmd.none )
ToggleAddParameter ->
( { model | showAddParameter = not model.showAddParameter }, Cmd.none )
UpdateFormName formName ->
( { model | formName = formName }, Cmd.none )
UpdateFormClientId id ->
( { model | formClientId = id }, Cmd.none )
UpdateParameterName name ->
( { model | newParameter = paramUpdateName name model.newParameter }, Cmd.none )
UpdateParameterType selectedType ->
( { model | newParameter = (initParameter name selectedType) }, Cmd.none )
UpdateValueBool val ->
( { model | newParameter = (BoolParameter name val) }, Cmd.none )
UpdateValueNumber val ->
( { model | newParameter = (NumberParameter name val) }, Cmd.none )
UpdateValueNumbers vals ->
( { model | newParameter = (NumbersParameter name vals) }, Cmd.none )
UpdateValueString val ->
( { model | newParameter = (StringParameter name val) }, Cmd.none )
UpdateValueStrings vals ->
( { model | newParameter = (StringsParameter name vals) }, Cmd.none )
-- VIEW
view : Model -> Html Msg
view model =
case model.config of
Just config ->
viewConfig model.now config model.showAddParameter model.newParameter model.error
Nothing ->
viewList model
viewAdd : Int -> String -> Msg -> Html Msg
viewAdd tdSpan labelText msg =
tr [ class "add", onClick msg ]
[ td [ class "type", colspan tdSpan ] [ text labelText ]
]
viewAddConfigForm : String -> List Client -> List (Html Msg)
viewAddConfigForm name clients =
[ tr [ class "form" ]
[ td [ class "name" ]
[ input
[ onInput UpdateFormName
, placeholder "PI:NAME:<NAME>END_PI"
, type_ "text"
, value name
]
[]
]
, td []
[ select
[ on "change" (Json.map UpdateFormClientId targetValue) ]
(List.map (\c -> viewOption c.name c.id) clients)
]
, td []
[]
, td []
[]
]
, tr [ class "save", onClick FormSubmit ]
[ td [ class "type", colspan 4 ] [ text "save config" ]
]
]
viewCard : ( String, String ) -> Html Msg
viewCard ( key, value ) =
div [ class "card" ]
[ span [] [ text key ]
, strong [] [ text value ]
]
viewConfig : Time -> Config -> Bool -> Parameter -> Maybe Http.Error -> Html Msg
viewConfig now config showAdd parameter error =
let
action =
if showAdd then
viewParameterForm config parameter
else
[ viewAdd 3 "add parameter" ToggleAddParameter ]
in
div []
[ h1 []
[ text "Configs/Base/"
, strong [ class "highlight" ] [ text config.name ]
]
, View.Error.view error
, viewMeta config now
, View.Parameter.viewTable action config.parameters
]
viewItem : Dict String Client -> Config -> Html Msg
viewItem clients config =
let
client =
case (Dict.get config.clientId clients) of
Just client ->
client.name
Nothing ->
config.clientId
in
tr
[ class "action"
, (Route.href (Route.ConfigBase config.id))
, onClick (SelectConfig config.id)
]
[ td [] [ text config.name ]
, td [] [ text client ]
, td [] [ text config.id ]
, td [] [ text (toString (List.length config.parameters)) ]
]
viewList : Model -> Html Msg
viewList model =
let
action =
if model.showAddConfig then
viewAddConfigForm model.formName model.clients
else
[ viewAdd 4 "add config" ToggleAddConfig
]
clients =
Dict.fromList (List.map (\c -> ( c.id, c )) model.clients)
in
div []
[ h1 []
[ text "Configs/"
, strong [] [ text "Base" ]
]
, View.Error.view model.error
, table []
[ thead []
[ tr []
[ th [ class "name" ] [ text "name" ]
, th [ class "client" ] [ text "client" ]
, th [ class "id" ] [ text "id" ]
, th [] [ text "parameters" ]
]
]
, tbody [] (List.append (List.map (viewItem clients) model.configs) action)
]
]
viewMeta : Config -> Time -> Html Msg
viewMeta config now =
let
cards =
[ ( "id", config.id )
, ( "client", config.clientId )
, ( "created", (View.Date.short config.createdAt) )
, ( "updated", (View.Date.pretty now config.updatedAt) )
]
in
section [ class "meta" ] (List.map viewCard cards)
viewOption : String -> String -> Html Msg
viewOption name val =
option [ value val ] [ text name ]
viewParameterForm : Config -> Parameter -> List (Html Msg)
viewParameterForm config parameter =
let
options =
[ "bool"
, "number"
, "string"
-- "numbers"
-- "strings"
]
in
[ tr [ class "form" ]
[ td [ class "name" ]
[ input
[ onInput UpdateParameterName
, placeholder "Name"
, type_ "text"
, value (View.Parameter.name parameter)
]
[]
]
, td []
[ select [ on "change" (Json.map UpdateParameterType targetValue) ] (List.map (\o -> viewOption o o) options)
]
, td [ class "value" ] [ viewParameterFormValue parameter ]
]
, tr [ class "save", onClick (ParameterFormSubmit config) ]
[ td [ classList [ ( "type", True ) ], colspan 3 ] [ text "save parameter" ]
]
]
viewParameterFormValue : Parameter -> Html Msg
viewParameterFormValue parameter =
case parameter of
BoolParameter _ v ->
div []
[ input
[ checked v
, id "new-bool"
, onCheck UpdateValueBool
, type_ "checkbox"
]
[]
, label [ for "new-bool" ] []
]
NumberParameter _ v ->
input
[ on "input" (Json.map UpdateValueNumber targetNumber)
, placeholder "Value"
, type_ "text"
, value (paramValue parameter)
]
[]
NumbersParameter _ v ->
input
[ on "input" (Json.map UpdateValueNumbers targetNumbers)
, placeholder "Value"
, type_ "text"
, value (paramValue parameter)
]
[]
StringParameter _ v ->
input
[ onInput UpdateValueString
, placeholder "Value"
, type_ "text"
, value v
]
[]
StringsParameter _ v ->
input
[ on "input" (Json.map UpdateValueStrings targetStrings)
, placeholder "Value"
, type_ "text"
, value (paramValue parameter)
]
[]
-- HELPER
paramUpdateName : String -> Parameter -> Parameter
paramUpdateName name parameter =
case parameter of
BoolParameter _ value ->
BoolParameter name value
NumberParameter _ value ->
NumberParameter name value
NumbersParameter _ value ->
NumbersParameter name value
StringParameter _ value ->
StringParameter name value
StringsParameter _ value ->
StringsParameter name value
paramValue : Parameter -> String
paramValue parameter =
case parameter of
BoolParameter _ val ->
case val of
True ->
"True"
False ->
"False"
NumberParameter _ val ->
toString val
NumbersParameter _ vals ->
String.join " " (List.map (\v -> toString v) vals)
StringParameter _ val ->
val
StringsParameter _ vals ->
String.join " " vals
toInt : String -> Int
toInt input =
case (String.toInt input) of
Err err ->
0
Ok v ->
v
targetNumber : Json.Decoder Int
targetNumber =
Json.map toInt (Json.at [ "target", "value" ] Json.string)
targetNumbers : Json.Decoder (List Int)
targetNumbers =
let
toInts input =
List.map (\v -> toInt v) (String.split " " input)
in
Json.map toInts (Json.at [ "target", "value" ] Json.string)
targetStrings : Json.Decoder (List String)
targetStrings =
let
toStrings input =
String.split " " input
in
Json.map toStrings (Json.at [ "target", "value" ] Json.string)
| elm |
[
{
"context": "\n ],\n text \"Alexander Sadovnikov\"\n ],\n p [] [\n ",
"end": 667,
"score": 0.999832809,
"start": 647,
"tag": "NAME",
"value": "Alexander Sadovnikov"
},
{
"context": " [\n a [href \"http://github.com/sad0vnikov/radish\"] [\n i [class \"fa f",
"end": 768,
"score": 0.998770237,
"start": 758,
"tag": "USERNAME",
"value": "sad0vnikov"
}
] | html/src/elm/View/AboutModal.elm | sad0vnikov/radish | 2 | module View.AboutModal exposing (view)
import Model.Model exposing (Model, availableKeyTypes, keyTypeName, keyTypeAlias, KeyType)
import Update.Msg exposing (Msg(..))
import Html exposing (..)
import Html.Attributes exposing (..)
import Dialog
view : Model -> Maybe (Dialog.Config Msg)
view model =
Just {
closeMessage = Just AboutWindowClose,
containerClass = Nothing,
header = Just (text <| "Radish " ++ model.appInfo.version),
body = Just (
div [] [
p [] [
strong [] [
text "Author: "
],
text "Alexander Sadovnikov"
],
p [] [
a [href "http://github.com/sad0vnikov/radish"] [
i [class "fa fa-2x fa-github"] []
]
]
]
),
footer = Nothing
}
| 38806 | module View.AboutModal exposing (view)
import Model.Model exposing (Model, availableKeyTypes, keyTypeName, keyTypeAlias, KeyType)
import Update.Msg exposing (Msg(..))
import Html exposing (..)
import Html.Attributes exposing (..)
import Dialog
view : Model -> Maybe (Dialog.Config Msg)
view model =
Just {
closeMessage = Just AboutWindowClose,
containerClass = Nothing,
header = Just (text <| "Radish " ++ model.appInfo.version),
body = Just (
div [] [
p [] [
strong [] [
text "Author: "
],
text "<NAME>"
],
p [] [
a [href "http://github.com/sad0vnikov/radish"] [
i [class "fa fa-2x fa-github"] []
]
]
]
),
footer = Nothing
}
| true | module View.AboutModal exposing (view)
import Model.Model exposing (Model, availableKeyTypes, keyTypeName, keyTypeAlias, KeyType)
import Update.Msg exposing (Msg(..))
import Html exposing (..)
import Html.Attributes exposing (..)
import Dialog
view : Model -> Maybe (Dialog.Config Msg)
view model =
Just {
closeMessage = Just AboutWindowClose,
containerClass = Nothing,
header = Just (text <| "Radish " ++ model.appInfo.version),
body = Just (
div [] [
p [] [
strong [] [
text "Author: "
],
text "PI:NAME:<NAME>END_PI"
],
p [] [
a [href "http://github.com/sad0vnikov/radish"] [
i [class "fa fa-2x fa-github"] []
]
]
]
),
footer = Nothing
}
| elm |
[
{
"context": " \n [ { key = (White, Just Red) ",
"end": 2358,
"score": 0.5787440538,
"start": 2355,
"tag": "NAME",
"value": "Red"
},
{
"context": " \n [ { key = (White, Just Red) ",
"end": 6057,
"score": 0.7550233006,
"start": 6054,
"tag": "NAME",
"value": "Red"
},
{
"context": " \n [ { key = (White, Just Red) ",
"end": 9836,
"score": 0.5787352324,
"start": 9833,
"tag": "NAME",
"value": "Red"
}
] | Turing/src/GameBase/Data/LevelsData/TasksBlock1Data.elm | JetBrains/programmer-games | 7 | module GameBase.Data.LevelsData.TasksBlock1Data exposing
(basketsNumb1_1, machine1_1, input1_1, transTable1_1,
expectedResult1_1, expectedPos1_1, usedCats1_1, usedBalls1_1,
basketsNumb1_2, machine1_2, input1_2, transTable1_2,
expectedResult1_2, expectedPos1_2, usedCats1_2, usedBalls1_2,
basketsNumb1_3, machine1_3, input1_3, transTable1_3,
expectedResult1_3, expectedPos1_3, usedCats1_3, usedBalls1_3)
import TuringMachine.TuringTypes exposing ( Direction(..), Machine,
UserTransTable, Cell(..))
import TuringMachine.RunTuring exposing (transFunc)
import GameBase.Data.GameTypes exposing (BallOfWool(..), Kitten(..))
import GameBase.UI.MainObjects.Basket exposing (nineBaskets)
--(fourBaskets, sevenBaskets)
import Array exposing (Array, fromList)
-- BLOCK 1 : Head movement and addition balls at the end of input word---------
-- 1_1 - Put blue ball at the right end of word
basketsNumb1_1 : Int
basketsNumb1_1 = nineBaskets --fourBaskets
machine1_1 : Machine BallOfWool Kitten
machine1_1 =
{ transition = (transFunc (fromList []) (Violet, Nothing, MoveLeft))
, initHeadPosForDraw = 4 --1
, initHeadPosForMach = 0
, startState = White
, acceptState = Orange
, rejectState = Violet
}
transTable1_1 : UserTransTable BallOfWool Kitten
transTable1_1 =
fromList
[ { key = (White, Just Red)
, value = { state = EmptyCell
, symb = StableCell (Just Red)
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
, { key = (White, Nothing)
, value = { state = StableCell (Orange)
, symb = EmptyCell
, dir = StableCell (MoveLeft)
}
, clickNum = 0
}
]
input1_1 : List (Maybe BallOfWool)
input1_1 =
[Just Red]
expectedResult1_1 : List (Maybe BallOfWool)
expectedResult1_1 =
[Just Red, Just Blue]
expectedPos1_1 : Int
expectedPos1_1 = 4 --1
usedCats1_1 : Array (Cell Kitten)
usedCats1_1 = fromList [UserCell White, UserCell LightGrey, UserCell Grey,
UserCell Brown, UserCell DarkBrown]
usedBalls1_1 : Array (Cell (Maybe BallOfWool))
usedBalls1_1 = fromList [UserCell (Just Red), UserCell (Just Yellow),
UserCell (Just Green), UserCell (Just Blue), UserCell Nothing]
-- 1_2 - Put blue ball at the left end of word
basketsNumb1_2 : Int
basketsNumb1_2 = nineBaskets --fourBaskets
machine1_2 : Machine BallOfWool Kitten
machine1_2 =
{ transition = (transFunc (fromList []) (Violet, Nothing, MoveLeft))
, initHeadPosForDraw = 3 --1
, initHeadPosForMach = 1
, startState = White
, acceptState = Orange
, rejectState = Violet
}
transTable1_2 : UserTransTable BallOfWool Kitten
transTable1_2 =
fromList
[ { key = (White, Just Red)
, value = { state = StableCell (White)
, symb = StableCell (Just Red)
, dir = EmptyCell
}
, clickNum = 0
}
, { key = (White, Nothing)
, value = { state = StableCell (Orange)
, symb = EmptyCell
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
]
input1_2 : List (Maybe BallOfWool)
input1_2 =
[Nothing, Just Red]
expectedResult1_2 : List (Maybe BallOfWool)
expectedResult1_2 =
[Just Blue, Just Red]
expectedPos1_2 : Int
expectedPos1_2 = 4 --2
usedCats1_2 : Array (Cell Kitten)
usedCats1_2 = fromList [UserCell White, UserCell LightGrey, UserCell Grey,
UserCell Brown, UserCell DarkBrown]
usedBalls1_2 : Array (Cell (Maybe BallOfWool))
usedBalls1_2 = fromList [UserCell (Just Red), UserCell (Just Yellow),
UserCell (Just Green), UserCell (Just Blue), UserCell Nothing]
-- 1_3 - Put blue balls at the both ends of word
basketsNumb1_3 : Int
basketsNumb1_3 = nineBaskets --sevenBaskets
machine1_3 : Machine BallOfWool Kitten
machine1_3 =
{ transition = (transFunc (fromList []) (Violet, Nothing, MoveLeft))
, initHeadPosForDraw = 2 --1
, initHeadPosForMach = 1
, startState = White
, acceptState = Orange
, rejectState = Violet
}
transTable1_3 : UserTransTable BallOfWool Kitten
transTable1_3 =
fromList
[ { key = (White, Just Red)
, value = { state = StableCell (White)
, symb = StableCell (Just Red)
, dir = EmptyCell
}
, clickNum = 0
}
, { key = (White, Just Yellow)
, value = { state = StableCell (White)
, symb = StableCell (Just Yellow)
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
, { key = (White, Just Green)
, value = { state = StableCell (White)
, symb = StableCell (Just Green)
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
, { key = (White, Nothing)
, value = { state = EmptyCell
, symb = StableCell (Just Blue)
, dir = EmptyCell
}
, clickNum = 0
}
, { key = (LightGrey, Just Red)
, value = { state = StableCell (LightGrey)
, symb = StableCell (Just Red)
, dir = StableCell (MoveLeft)
}
, clickNum = 0
}
, { key = (LightGrey, Just Yellow)
, value = { state = StableCell (LightGrey)
, symb = StableCell (Just Yellow)
, dir = StableCell (MoveLeft)
}
, clickNum = 0
}
, { key = (LightGrey, Just Green)
, value = { state = StableCell (LightGrey)
, symb = StableCell (Just Green)
, dir = StableCell (MoveLeft)
}
, clickNum = 0
}
, { key = (LightGrey, Nothing)
, value = { state = StableCell (Orange)
, symb = StableCell (Just Blue)
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
]
input1_3 : List (Maybe BallOfWool)
input1_3 =
[Nothing, Just Red, Just Yellow, Just Green]
expectedResult1_3 : List (Maybe BallOfWool)
expectedResult1_3 =
[Just Blue, Just Red, Just Yellow, Just Green, Just Blue]
expectedPos1_3 : Int
expectedPos1_3 = 3 --2
usedCats1_3 : Array (Cell Kitten)
usedCats1_3 = fromList [UserCell White, UserCell LightGrey, UserCell Grey,
UserCell Brown, UserCell DarkBrown]
usedBalls1_3 : Array (Cell (Maybe BallOfWool))
usedBalls1_3 = fromList [UserCell (Just Red), UserCell (Just Yellow),
UserCell (Just Green), UserCell (Just Blue), UserCell Nothing]
-------------------------------------------------------------------------------
| 725 | module GameBase.Data.LevelsData.TasksBlock1Data exposing
(basketsNumb1_1, machine1_1, input1_1, transTable1_1,
expectedResult1_1, expectedPos1_1, usedCats1_1, usedBalls1_1,
basketsNumb1_2, machine1_2, input1_2, transTable1_2,
expectedResult1_2, expectedPos1_2, usedCats1_2, usedBalls1_2,
basketsNumb1_3, machine1_3, input1_3, transTable1_3,
expectedResult1_3, expectedPos1_3, usedCats1_3, usedBalls1_3)
import TuringMachine.TuringTypes exposing ( Direction(..), Machine,
UserTransTable, Cell(..))
import TuringMachine.RunTuring exposing (transFunc)
import GameBase.Data.GameTypes exposing (BallOfWool(..), Kitten(..))
import GameBase.UI.MainObjects.Basket exposing (nineBaskets)
--(fourBaskets, sevenBaskets)
import Array exposing (Array, fromList)
-- BLOCK 1 : Head movement and addition balls at the end of input word---------
-- 1_1 - Put blue ball at the right end of word
basketsNumb1_1 : Int
basketsNumb1_1 = nineBaskets --fourBaskets
machine1_1 : Machine BallOfWool Kitten
machine1_1 =
{ transition = (transFunc (fromList []) (Violet, Nothing, MoveLeft))
, initHeadPosForDraw = 4 --1
, initHeadPosForMach = 0
, startState = White
, acceptState = Orange
, rejectState = Violet
}
transTable1_1 : UserTransTable BallOfWool Kitten
transTable1_1 =
fromList
[ { key = (White, Just <NAME>)
, value = { state = EmptyCell
, symb = StableCell (Just Red)
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
, { key = (White, Nothing)
, value = { state = StableCell (Orange)
, symb = EmptyCell
, dir = StableCell (MoveLeft)
}
, clickNum = 0
}
]
input1_1 : List (Maybe BallOfWool)
input1_1 =
[Just Red]
expectedResult1_1 : List (Maybe BallOfWool)
expectedResult1_1 =
[Just Red, Just Blue]
expectedPos1_1 : Int
expectedPos1_1 = 4 --1
usedCats1_1 : Array (Cell Kitten)
usedCats1_1 = fromList [UserCell White, UserCell LightGrey, UserCell Grey,
UserCell Brown, UserCell DarkBrown]
usedBalls1_1 : Array (Cell (Maybe BallOfWool))
usedBalls1_1 = fromList [UserCell (Just Red), UserCell (Just Yellow),
UserCell (Just Green), UserCell (Just Blue), UserCell Nothing]
-- 1_2 - Put blue ball at the left end of word
basketsNumb1_2 : Int
basketsNumb1_2 = nineBaskets --fourBaskets
machine1_2 : Machine BallOfWool Kitten
machine1_2 =
{ transition = (transFunc (fromList []) (Violet, Nothing, MoveLeft))
, initHeadPosForDraw = 3 --1
, initHeadPosForMach = 1
, startState = White
, acceptState = Orange
, rejectState = Violet
}
transTable1_2 : UserTransTable BallOfWool Kitten
transTable1_2 =
fromList
[ { key = (White, Just <NAME>)
, value = { state = StableCell (White)
, symb = StableCell (Just Red)
, dir = EmptyCell
}
, clickNum = 0
}
, { key = (White, Nothing)
, value = { state = StableCell (Orange)
, symb = EmptyCell
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
]
input1_2 : List (Maybe BallOfWool)
input1_2 =
[Nothing, Just Red]
expectedResult1_2 : List (Maybe BallOfWool)
expectedResult1_2 =
[Just Blue, Just Red]
expectedPos1_2 : Int
expectedPos1_2 = 4 --2
usedCats1_2 : Array (Cell Kitten)
usedCats1_2 = fromList [UserCell White, UserCell LightGrey, UserCell Grey,
UserCell Brown, UserCell DarkBrown]
usedBalls1_2 : Array (Cell (Maybe BallOfWool))
usedBalls1_2 = fromList [UserCell (Just Red), UserCell (Just Yellow),
UserCell (Just Green), UserCell (Just Blue), UserCell Nothing]
-- 1_3 - Put blue balls at the both ends of word
basketsNumb1_3 : Int
basketsNumb1_3 = nineBaskets --sevenBaskets
machine1_3 : Machine BallOfWool Kitten
machine1_3 =
{ transition = (transFunc (fromList []) (Violet, Nothing, MoveLeft))
, initHeadPosForDraw = 2 --1
, initHeadPosForMach = 1
, startState = White
, acceptState = Orange
, rejectState = Violet
}
transTable1_3 : UserTransTable BallOfWool Kitten
transTable1_3 =
fromList
[ { key = (White, Just <NAME>)
, value = { state = StableCell (White)
, symb = StableCell (Just Red)
, dir = EmptyCell
}
, clickNum = 0
}
, { key = (White, Just Yellow)
, value = { state = StableCell (White)
, symb = StableCell (Just Yellow)
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
, { key = (White, Just Green)
, value = { state = StableCell (White)
, symb = StableCell (Just Green)
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
, { key = (White, Nothing)
, value = { state = EmptyCell
, symb = StableCell (Just Blue)
, dir = EmptyCell
}
, clickNum = 0
}
, { key = (LightGrey, Just Red)
, value = { state = StableCell (LightGrey)
, symb = StableCell (Just Red)
, dir = StableCell (MoveLeft)
}
, clickNum = 0
}
, { key = (LightGrey, Just Yellow)
, value = { state = StableCell (LightGrey)
, symb = StableCell (Just Yellow)
, dir = StableCell (MoveLeft)
}
, clickNum = 0
}
, { key = (LightGrey, Just Green)
, value = { state = StableCell (LightGrey)
, symb = StableCell (Just Green)
, dir = StableCell (MoveLeft)
}
, clickNum = 0
}
, { key = (LightGrey, Nothing)
, value = { state = StableCell (Orange)
, symb = StableCell (Just Blue)
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
]
input1_3 : List (Maybe BallOfWool)
input1_3 =
[Nothing, Just Red, Just Yellow, Just Green]
expectedResult1_3 : List (Maybe BallOfWool)
expectedResult1_3 =
[Just Blue, Just Red, Just Yellow, Just Green, Just Blue]
expectedPos1_3 : Int
expectedPos1_3 = 3 --2
usedCats1_3 : Array (Cell Kitten)
usedCats1_3 = fromList [UserCell White, UserCell LightGrey, UserCell Grey,
UserCell Brown, UserCell DarkBrown]
usedBalls1_3 : Array (Cell (Maybe BallOfWool))
usedBalls1_3 = fromList [UserCell (Just Red), UserCell (Just Yellow),
UserCell (Just Green), UserCell (Just Blue), UserCell Nothing]
-------------------------------------------------------------------------------
| true | module GameBase.Data.LevelsData.TasksBlock1Data exposing
(basketsNumb1_1, machine1_1, input1_1, transTable1_1,
expectedResult1_1, expectedPos1_1, usedCats1_1, usedBalls1_1,
basketsNumb1_2, machine1_2, input1_2, transTable1_2,
expectedResult1_2, expectedPos1_2, usedCats1_2, usedBalls1_2,
basketsNumb1_3, machine1_3, input1_3, transTable1_3,
expectedResult1_3, expectedPos1_3, usedCats1_3, usedBalls1_3)
import TuringMachine.TuringTypes exposing ( Direction(..), Machine,
UserTransTable, Cell(..))
import TuringMachine.RunTuring exposing (transFunc)
import GameBase.Data.GameTypes exposing (BallOfWool(..), Kitten(..))
import GameBase.UI.MainObjects.Basket exposing (nineBaskets)
--(fourBaskets, sevenBaskets)
import Array exposing (Array, fromList)
-- BLOCK 1 : Head movement and addition balls at the end of input word---------
-- 1_1 - Put blue ball at the right end of word
basketsNumb1_1 : Int
basketsNumb1_1 = nineBaskets --fourBaskets
machine1_1 : Machine BallOfWool Kitten
machine1_1 =
{ transition = (transFunc (fromList []) (Violet, Nothing, MoveLeft))
, initHeadPosForDraw = 4 --1
, initHeadPosForMach = 0
, startState = White
, acceptState = Orange
, rejectState = Violet
}
transTable1_1 : UserTransTable BallOfWool Kitten
transTable1_1 =
fromList
[ { key = (White, Just PI:NAME:<NAME>END_PI)
, value = { state = EmptyCell
, symb = StableCell (Just Red)
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
, { key = (White, Nothing)
, value = { state = StableCell (Orange)
, symb = EmptyCell
, dir = StableCell (MoveLeft)
}
, clickNum = 0
}
]
input1_1 : List (Maybe BallOfWool)
input1_1 =
[Just Red]
expectedResult1_1 : List (Maybe BallOfWool)
expectedResult1_1 =
[Just Red, Just Blue]
expectedPos1_1 : Int
expectedPos1_1 = 4 --1
usedCats1_1 : Array (Cell Kitten)
usedCats1_1 = fromList [UserCell White, UserCell LightGrey, UserCell Grey,
UserCell Brown, UserCell DarkBrown]
usedBalls1_1 : Array (Cell (Maybe BallOfWool))
usedBalls1_1 = fromList [UserCell (Just Red), UserCell (Just Yellow),
UserCell (Just Green), UserCell (Just Blue), UserCell Nothing]
-- 1_2 - Put blue ball at the left end of word
basketsNumb1_2 : Int
basketsNumb1_2 = nineBaskets --fourBaskets
machine1_2 : Machine BallOfWool Kitten
machine1_2 =
{ transition = (transFunc (fromList []) (Violet, Nothing, MoveLeft))
, initHeadPosForDraw = 3 --1
, initHeadPosForMach = 1
, startState = White
, acceptState = Orange
, rejectState = Violet
}
transTable1_2 : UserTransTable BallOfWool Kitten
transTable1_2 =
fromList
[ { key = (White, Just PI:NAME:<NAME>END_PI)
, value = { state = StableCell (White)
, symb = StableCell (Just Red)
, dir = EmptyCell
}
, clickNum = 0
}
, { key = (White, Nothing)
, value = { state = StableCell (Orange)
, symb = EmptyCell
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
]
input1_2 : List (Maybe BallOfWool)
input1_2 =
[Nothing, Just Red]
expectedResult1_2 : List (Maybe BallOfWool)
expectedResult1_2 =
[Just Blue, Just Red]
expectedPos1_2 : Int
expectedPos1_2 = 4 --2
usedCats1_2 : Array (Cell Kitten)
usedCats1_2 = fromList [UserCell White, UserCell LightGrey, UserCell Grey,
UserCell Brown, UserCell DarkBrown]
usedBalls1_2 : Array (Cell (Maybe BallOfWool))
usedBalls1_2 = fromList [UserCell (Just Red), UserCell (Just Yellow),
UserCell (Just Green), UserCell (Just Blue), UserCell Nothing]
-- 1_3 - Put blue balls at the both ends of word
basketsNumb1_3 : Int
basketsNumb1_3 = nineBaskets --sevenBaskets
machine1_3 : Machine BallOfWool Kitten
machine1_3 =
{ transition = (transFunc (fromList []) (Violet, Nothing, MoveLeft))
, initHeadPosForDraw = 2 --1
, initHeadPosForMach = 1
, startState = White
, acceptState = Orange
, rejectState = Violet
}
transTable1_3 : UserTransTable BallOfWool Kitten
transTable1_3 =
fromList
[ { key = (White, Just PI:NAME:<NAME>END_PI)
, value = { state = StableCell (White)
, symb = StableCell (Just Red)
, dir = EmptyCell
}
, clickNum = 0
}
, { key = (White, Just Yellow)
, value = { state = StableCell (White)
, symb = StableCell (Just Yellow)
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
, { key = (White, Just Green)
, value = { state = StableCell (White)
, symb = StableCell (Just Green)
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
, { key = (White, Nothing)
, value = { state = EmptyCell
, symb = StableCell (Just Blue)
, dir = EmptyCell
}
, clickNum = 0
}
, { key = (LightGrey, Just Red)
, value = { state = StableCell (LightGrey)
, symb = StableCell (Just Red)
, dir = StableCell (MoveLeft)
}
, clickNum = 0
}
, { key = (LightGrey, Just Yellow)
, value = { state = StableCell (LightGrey)
, symb = StableCell (Just Yellow)
, dir = StableCell (MoveLeft)
}
, clickNum = 0
}
, { key = (LightGrey, Just Green)
, value = { state = StableCell (LightGrey)
, symb = StableCell (Just Green)
, dir = StableCell (MoveLeft)
}
, clickNum = 0
}
, { key = (LightGrey, Nothing)
, value = { state = StableCell (Orange)
, symb = StableCell (Just Blue)
, dir = StableCell (MoveRight)
}
, clickNum = 0
}
]
input1_3 : List (Maybe BallOfWool)
input1_3 =
[Nothing, Just Red, Just Yellow, Just Green]
expectedResult1_3 : List (Maybe BallOfWool)
expectedResult1_3 =
[Just Blue, Just Red, Just Yellow, Just Green, Just Blue]
expectedPos1_3 : Int
expectedPos1_3 = 3 --2
usedCats1_3 : Array (Cell Kitten)
usedCats1_3 = fromList [UserCell White, UserCell LightGrey, UserCell Grey,
UserCell Brown, UserCell DarkBrown]
usedBalls1_3 : Array (Cell (Maybe BallOfWool))
usedBalls1_3 = fromList [UserCell (Just Red), UserCell (Just Yellow),
UserCell (Just Green), UserCell (Just Blue), UserCell Nothing]
-------------------------------------------------------------------------------
| elm |
[
{
"context": " Just user ->\n { username = user.username\n , bio = user.bio |> Maybe.withDefault",
"end": 1316,
"score": 0.9787785411,
"start": 1308,
"tag": "USERNAME",
"value": "username"
},
{
"context": "rams =\n { username = model.username\n , email = model.email\n ",
"end": 2811,
"score": 0.90129143,
"start": 2803,
"tag": "USERNAME",
"value": "username"
},
{
"context": "odel.email\n , oldPassword = model.oldPassword\n , newPassword = model.new",
"end": 2915,
"score": 0.9471037388,
"start": 2898,
"tag": "PASSWORD",
"value": "model.oldPassword"
},
{
"context": "ldPassword\n , newPassword = model.newPassword\n , bio = model.bio\n ",
"end": 2973,
"score": 0.8799481392,
"start": 2956,
"tag": "PASSWORD",
"value": "model.newPassword"
},
{
"context": " text = model.username\n , label = \"Your Username\"\n , onChange = Updated Us",
"end": 3825,
"score": 0.8336205482,
"start": 3821,
"tag": "NAME",
"value": "Your"
},
{
"context": "t = model.username\n , label = \"Your Username\"\n , onChange = Updated Username\n ",
"end": 3834,
"score": 0.6632144451,
"start": 3826,
"tag": "NAME",
"value": "Username"
}
] | src/Pages/Settings.elm | Orasund/lamdera-up | 0 | module Pages.Settings exposing (Model, Msg(..), page)
import Bridge exposing (..)
import Config.View
import Data.Response exposing (Response)
import Data.User exposing (User)
import Effect exposing (Effect)
import Element
import Element.Border as Border
import Element.Input as Input
import Html exposing (..)
import Html.Attributes exposing (class, value)
import Page
import Request exposing (Request)
import Shared
import Utils.Maybe
import View exposing (View)
import View.Color as Color
import View.ErrorList
import View.Input
import Widget
import Widget.Customize as Customize
import Widget.Material as Material
import Widget.Material.Typography as Typography
page : Shared.Model -> Request -> Page.With Model Msg
page shared _ =
Page.protected.advanced
(\user ->
{ init = init shared
, update = update
, subscriptions = subscriptions
, view = view user
}
)
-- INIT
type alias Model =
{ username : String
, bio : String
, email : String
, oldPassword : Maybe String
, newPassword : Maybe String
, message : Maybe String
, errors : List String
}
init : Shared.Model -> ( Model, Effect Msg )
init shared =
( case shared.user of
Just user ->
{ username = user.username
, bio = user.bio |> Maybe.withDefault ""
, email = user.email
, oldPassword = Nothing
, newPassword = Nothing
, message = Nothing
, errors = []
}
Nothing ->
{ username = ""
, bio = ""
, email = ""
, newPassword = Nothing
, oldPassword = Nothing
, message = Nothing
, errors = []
}
, Effect.none
)
-- UPDATE
type Msg
= Updated Field String
| SubmittedForm User
| GotUser (Response User)
type Field
= Username
| Bio
| Email
| NewPassword
| OldPassword
update : Msg -> Model -> ( Model, Effect Msg )
update msg model =
case msg of
Updated Username value ->
( { model | username = value }, Effect.none )
Updated Bio value ->
( { model | bio = value }, Effect.none )
Updated Email value ->
( { model | email = value }, Effect.none )
Updated OldPassword value ->
( { model | oldPassword = Just value }, Effect.none )
Updated NewPassword value ->
( { model | newPassword = Just value }, Effect.none )
SubmittedForm _ ->
( { model | message = Nothing, errors = [] }
, (Effect.fromCmd << sendToBackend) <|
UserUpdate_Settings
{ params =
{ username = model.username
, email = model.email
, oldPassword = model.oldPassword
, newPassword = model.newPassword
, bio = model.bio
}
}
)
GotUser (Data.Response.Success user) ->
( { model | message = Just "User updated!" }
, Effect.fromShared (Shared.SignedInUser user)
)
GotUser (Data.Response.Failure reasons) ->
( { model | errors = reasons }
, Effect.none
)
GotUser _ ->
( model, Effect.none )
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
-- VIEW
view : User -> Model -> View Msg
view user model =
{ title = "Settings"
, body =
[ Element.text "Your Settings"
|> Element.el (Typography.h2 ++ [ Element.centerX ])
, [ View.Input.textInput
{ text = model.username
, label = "Your Username"
, onChange = Updated Username
}
|> View.Input.withLabel "Your Username"
, View.Input.multiLineInput
{ text = model.bio
, label = "Short bio about you"
, onChange = Updated Bio
}
|> View.Input.withLabel "Short bio about you"
, View.Input.textInput
{ text = model.email
, label = "Email"
, onChange = Updated Email
}
|> View.Input.withLabel "Email"
, [ Widget.currentPasswordInputV2
(Material.passwordInput Color.palette
|> Customize.elementRow [ Element.width Element.fill ]
)
{ text = Maybe.withDefault "" model.oldPassword
, placeholder =
"Old Password"
|> Element.text
|> Input.placeholder []
|> Just
, label = "Old Password"
, onChange = Updated OldPassword
, show = False
}
, Widget.newPasswordInputV2
(Material.passwordInput Color.palette
|> Customize.elementRow [ Element.width Element.fill ]
)
{ text = Maybe.withDefault "" model.newPassword
, placeholder =
"New Password"
|> Element.text
|> Input.placeholder []
|> Just
, label = "New Password"
, onChange = Updated NewPassword
, show = False
}
]
|> Element.column
[ Element.spacing Config.View.spacing
, Element.width Element.fill
]
|> View.Input.withLabel "Change Password"
, View.ErrorList.view model.errors |> Element.html
, (\message ->
p [ class "text-success" ] [ text message ]
)
|> Utils.Maybe.view model.message
|> Element.html
, Widget.textButton (Material.containedButton Color.palette)
{ text = "Update Settings"
, onPress = Just <| SubmittedForm user
}
|> Element.el [ Element.alignRight ]
]
|> Element.column
[ Element.spacing Config.View.spacing
, Element.width Element.fill
]
]
|> Element.column
(Material.cardAttributes Color.palette
++ [ Element.spacing Config.View.spacing
, Border.rounded Config.View.rounded
, Element.padding Config.View.padding
, Element.width Element.shrink
, Element.centerX
, Element.centerY
, Element.width <| Element.maximum 1024 <| Element.fill
]
)
}
| 50382 | module Pages.Settings exposing (Model, Msg(..), page)
import Bridge exposing (..)
import Config.View
import Data.Response exposing (Response)
import Data.User exposing (User)
import Effect exposing (Effect)
import Element
import Element.Border as Border
import Element.Input as Input
import Html exposing (..)
import Html.Attributes exposing (class, value)
import Page
import Request exposing (Request)
import Shared
import Utils.Maybe
import View exposing (View)
import View.Color as Color
import View.ErrorList
import View.Input
import Widget
import Widget.Customize as Customize
import Widget.Material as Material
import Widget.Material.Typography as Typography
page : Shared.Model -> Request -> Page.With Model Msg
page shared _ =
Page.protected.advanced
(\user ->
{ init = init shared
, update = update
, subscriptions = subscriptions
, view = view user
}
)
-- INIT
type alias Model =
{ username : String
, bio : String
, email : String
, oldPassword : Maybe String
, newPassword : Maybe String
, message : Maybe String
, errors : List String
}
init : Shared.Model -> ( Model, Effect Msg )
init shared =
( case shared.user of
Just user ->
{ username = user.username
, bio = user.bio |> Maybe.withDefault ""
, email = user.email
, oldPassword = Nothing
, newPassword = Nothing
, message = Nothing
, errors = []
}
Nothing ->
{ username = ""
, bio = ""
, email = ""
, newPassword = Nothing
, oldPassword = Nothing
, message = Nothing
, errors = []
}
, Effect.none
)
-- UPDATE
type Msg
= Updated Field String
| SubmittedForm User
| GotUser (Response User)
type Field
= Username
| Bio
| Email
| NewPassword
| OldPassword
update : Msg -> Model -> ( Model, Effect Msg )
update msg model =
case msg of
Updated Username value ->
( { model | username = value }, Effect.none )
Updated Bio value ->
( { model | bio = value }, Effect.none )
Updated Email value ->
( { model | email = value }, Effect.none )
Updated OldPassword value ->
( { model | oldPassword = Just value }, Effect.none )
Updated NewPassword value ->
( { model | newPassword = Just value }, Effect.none )
SubmittedForm _ ->
( { model | message = Nothing, errors = [] }
, (Effect.fromCmd << sendToBackend) <|
UserUpdate_Settings
{ params =
{ username = model.username
, email = model.email
, oldPassword = <PASSWORD>
, newPassword = <PASSWORD>
, bio = model.bio
}
}
)
GotUser (Data.Response.Success user) ->
( { model | message = Just "User updated!" }
, Effect.fromShared (Shared.SignedInUser user)
)
GotUser (Data.Response.Failure reasons) ->
( { model | errors = reasons }
, Effect.none
)
GotUser _ ->
( model, Effect.none )
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
-- VIEW
view : User -> Model -> View Msg
view user model =
{ title = "Settings"
, body =
[ Element.text "Your Settings"
|> Element.el (Typography.h2 ++ [ Element.centerX ])
, [ View.Input.textInput
{ text = model.username
, label = "<NAME> <NAME>"
, onChange = Updated Username
}
|> View.Input.withLabel "Your Username"
, View.Input.multiLineInput
{ text = model.bio
, label = "Short bio about you"
, onChange = Updated Bio
}
|> View.Input.withLabel "Short bio about you"
, View.Input.textInput
{ text = model.email
, label = "Email"
, onChange = Updated Email
}
|> View.Input.withLabel "Email"
, [ Widget.currentPasswordInputV2
(Material.passwordInput Color.palette
|> Customize.elementRow [ Element.width Element.fill ]
)
{ text = Maybe.withDefault "" model.oldPassword
, placeholder =
"Old Password"
|> Element.text
|> Input.placeholder []
|> Just
, label = "Old Password"
, onChange = Updated OldPassword
, show = False
}
, Widget.newPasswordInputV2
(Material.passwordInput Color.palette
|> Customize.elementRow [ Element.width Element.fill ]
)
{ text = Maybe.withDefault "" model.newPassword
, placeholder =
"New Password"
|> Element.text
|> Input.placeholder []
|> Just
, label = "New Password"
, onChange = Updated NewPassword
, show = False
}
]
|> Element.column
[ Element.spacing Config.View.spacing
, Element.width Element.fill
]
|> View.Input.withLabel "Change Password"
, View.ErrorList.view model.errors |> Element.html
, (\message ->
p [ class "text-success" ] [ text message ]
)
|> Utils.Maybe.view model.message
|> Element.html
, Widget.textButton (Material.containedButton Color.palette)
{ text = "Update Settings"
, onPress = Just <| SubmittedForm user
}
|> Element.el [ Element.alignRight ]
]
|> Element.column
[ Element.spacing Config.View.spacing
, Element.width Element.fill
]
]
|> Element.column
(Material.cardAttributes Color.palette
++ [ Element.spacing Config.View.spacing
, Border.rounded Config.View.rounded
, Element.padding Config.View.padding
, Element.width Element.shrink
, Element.centerX
, Element.centerY
, Element.width <| Element.maximum 1024 <| Element.fill
]
)
}
| true | module Pages.Settings exposing (Model, Msg(..), page)
import Bridge exposing (..)
import Config.View
import Data.Response exposing (Response)
import Data.User exposing (User)
import Effect exposing (Effect)
import Element
import Element.Border as Border
import Element.Input as Input
import Html exposing (..)
import Html.Attributes exposing (class, value)
import Page
import Request exposing (Request)
import Shared
import Utils.Maybe
import View exposing (View)
import View.Color as Color
import View.ErrorList
import View.Input
import Widget
import Widget.Customize as Customize
import Widget.Material as Material
import Widget.Material.Typography as Typography
page : Shared.Model -> Request -> Page.With Model Msg
page shared _ =
Page.protected.advanced
(\user ->
{ init = init shared
, update = update
, subscriptions = subscriptions
, view = view user
}
)
-- INIT
type alias Model =
{ username : String
, bio : String
, email : String
, oldPassword : Maybe String
, newPassword : Maybe String
, message : Maybe String
, errors : List String
}
init : Shared.Model -> ( Model, Effect Msg )
init shared =
( case shared.user of
Just user ->
{ username = user.username
, bio = user.bio |> Maybe.withDefault ""
, email = user.email
, oldPassword = Nothing
, newPassword = Nothing
, message = Nothing
, errors = []
}
Nothing ->
{ username = ""
, bio = ""
, email = ""
, newPassword = Nothing
, oldPassword = Nothing
, message = Nothing
, errors = []
}
, Effect.none
)
-- UPDATE
type Msg
= Updated Field String
| SubmittedForm User
| GotUser (Response User)
type Field
= Username
| Bio
| Email
| NewPassword
| OldPassword
update : Msg -> Model -> ( Model, Effect Msg )
update msg model =
case msg of
Updated Username value ->
( { model | username = value }, Effect.none )
Updated Bio value ->
( { model | bio = value }, Effect.none )
Updated Email value ->
( { model | email = value }, Effect.none )
Updated OldPassword value ->
( { model | oldPassword = Just value }, Effect.none )
Updated NewPassword value ->
( { model | newPassword = Just value }, Effect.none )
SubmittedForm _ ->
( { model | message = Nothing, errors = [] }
, (Effect.fromCmd << sendToBackend) <|
UserUpdate_Settings
{ params =
{ username = model.username
, email = model.email
, oldPassword = PI:PASSWORD:<PASSWORD>END_PI
, newPassword = PI:PASSWORD:<PASSWORD>END_PI
, bio = model.bio
}
}
)
GotUser (Data.Response.Success user) ->
( { model | message = Just "User updated!" }
, Effect.fromShared (Shared.SignedInUser user)
)
GotUser (Data.Response.Failure reasons) ->
( { model | errors = reasons }
, Effect.none
)
GotUser _ ->
( model, Effect.none )
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
-- VIEW
view : User -> Model -> View Msg
view user model =
{ title = "Settings"
, body =
[ Element.text "Your Settings"
|> Element.el (Typography.h2 ++ [ Element.centerX ])
, [ View.Input.textInput
{ text = model.username
, label = "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
, onChange = Updated Username
}
|> View.Input.withLabel "Your Username"
, View.Input.multiLineInput
{ text = model.bio
, label = "Short bio about you"
, onChange = Updated Bio
}
|> View.Input.withLabel "Short bio about you"
, View.Input.textInput
{ text = model.email
, label = "Email"
, onChange = Updated Email
}
|> View.Input.withLabel "Email"
, [ Widget.currentPasswordInputV2
(Material.passwordInput Color.palette
|> Customize.elementRow [ Element.width Element.fill ]
)
{ text = Maybe.withDefault "" model.oldPassword
, placeholder =
"Old Password"
|> Element.text
|> Input.placeholder []
|> Just
, label = "Old Password"
, onChange = Updated OldPassword
, show = False
}
, Widget.newPasswordInputV2
(Material.passwordInput Color.palette
|> Customize.elementRow [ Element.width Element.fill ]
)
{ text = Maybe.withDefault "" model.newPassword
, placeholder =
"New Password"
|> Element.text
|> Input.placeholder []
|> Just
, label = "New Password"
, onChange = Updated NewPassword
, show = False
}
]
|> Element.column
[ Element.spacing Config.View.spacing
, Element.width Element.fill
]
|> View.Input.withLabel "Change Password"
, View.ErrorList.view model.errors |> Element.html
, (\message ->
p [ class "text-success" ] [ text message ]
)
|> Utils.Maybe.view model.message
|> Element.html
, Widget.textButton (Material.containedButton Color.palette)
{ text = "Update Settings"
, onPress = Just <| SubmittedForm user
}
|> Element.el [ Element.alignRight ]
]
|> Element.column
[ Element.spacing Config.View.spacing
, Element.width Element.fill
]
]
|> Element.column
(Material.cardAttributes Color.palette
++ [ Element.spacing Config.View.spacing
, Border.rounded Config.View.rounded
, Element.padding Config.View.padding
, Element.width Element.shrink
, Element.centerX
, Element.centerY
, Element.width <| Element.maximum 1024 <| Element.fill
]
)
}
| elm |
[
{
"context": "g username )\n , ( \"password\", JE.string password )\n ]\n )\n\n\n\n-- CMD response DECO",
"end": 1543,
"score": 0.796184063,
"start": 1535,
"tag": "PASSWORD",
"value": "password"
}
] | web/static/elm/Commands.elm | meilab/meilab_blog | 0 | module Commands exposing (authRequest, getPostList)
import Http exposing (..)
import Json.Decode as JD exposing (at)
import Json.Encode as JE
import Json.Decode.Pipeline exposing (decode, required, optional)
import Messages exposing (..)
import Types exposing (AuthResponse, PostList, PostMetaInfo)
import Helpers exposing (tokenHeader)
import Maybe
authRequest : Maybe String -> String -> String -> String -> Cmd Msg
authRequest token api_url username password =
Http.request
{ method = "POST"
, headers = [ (tokenHeader token) ]
, url = authRequestUrl api_url
, body = authBody username password
, expect = authResponseExpect
, timeout = Nothing
, withCredentials = False
}
|> Http.send OnAuthCmdResponse
authRequestUrl : String -> String
authRequestUrl api_url =
api_url ++ "/auth"
getPostList : Maybe String -> String -> Cmd Msg
getPostList token api_url =
Http.request
{ method = "GET"
, headers = [ (tokenHeader token) ]
, url = getPostListUrl api_url
, body = emptyBody
, expect = postlistExpect
, timeout = Nothing
, withCredentials = False
}
|> Http.send OnPostListResponse
getPostListUrl : String -> String
getPostListUrl api_url =
api_url ++ "/posts"
-- CMD encoder
authBody : String -> String -> Body
authBody username password =
jsonBody
(JE.object
[ ( "username", JE.string username )
, ( "password", JE.string password )
]
)
-- CMD response DECODERS
authResponseExpect : Expect AuthResponse
authResponseExpect =
expectJson collectionDecoder
collectionDecoder : JD.Decoder AuthResponse
collectionDecoder =
decode AuthResponse
|> required "code" JD.string
|> required "token" JD.string
postlistExpect : Expect PostList
postlistExpect =
expectJson postlistDecoder
postlistDecoder : JD.Decoder PostList
postlistDecoder =
JD.list postMetaInfoDecoder
postMetaInfoDecoder : JD.Decoder PostMetaInfo
postMetaInfoDecoder =
decode PostMetaInfo
|> required "slug" JD.string
|> required "author" JD.string
|> required "title" JD.string
|> required "description" JD.string
|> required "date" JD.string
|> required "tags" (JD.list JD.string)
|> required "headerimg" JD.string
|> required "pinned" JD.bool
|> required "published" JD.bool
| 34794 | module Commands exposing (authRequest, getPostList)
import Http exposing (..)
import Json.Decode as JD exposing (at)
import Json.Encode as JE
import Json.Decode.Pipeline exposing (decode, required, optional)
import Messages exposing (..)
import Types exposing (AuthResponse, PostList, PostMetaInfo)
import Helpers exposing (tokenHeader)
import Maybe
authRequest : Maybe String -> String -> String -> String -> Cmd Msg
authRequest token api_url username password =
Http.request
{ method = "POST"
, headers = [ (tokenHeader token) ]
, url = authRequestUrl api_url
, body = authBody username password
, expect = authResponseExpect
, timeout = Nothing
, withCredentials = False
}
|> Http.send OnAuthCmdResponse
authRequestUrl : String -> String
authRequestUrl api_url =
api_url ++ "/auth"
getPostList : Maybe String -> String -> Cmd Msg
getPostList token api_url =
Http.request
{ method = "GET"
, headers = [ (tokenHeader token) ]
, url = getPostListUrl api_url
, body = emptyBody
, expect = postlistExpect
, timeout = Nothing
, withCredentials = False
}
|> Http.send OnPostListResponse
getPostListUrl : String -> String
getPostListUrl api_url =
api_url ++ "/posts"
-- CMD encoder
authBody : String -> String -> Body
authBody username password =
jsonBody
(JE.object
[ ( "username", JE.string username )
, ( "password", JE.string <PASSWORD> )
]
)
-- CMD response DECODERS
authResponseExpect : Expect AuthResponse
authResponseExpect =
expectJson collectionDecoder
collectionDecoder : JD.Decoder AuthResponse
collectionDecoder =
decode AuthResponse
|> required "code" JD.string
|> required "token" JD.string
postlistExpect : Expect PostList
postlistExpect =
expectJson postlistDecoder
postlistDecoder : JD.Decoder PostList
postlistDecoder =
JD.list postMetaInfoDecoder
postMetaInfoDecoder : JD.Decoder PostMetaInfo
postMetaInfoDecoder =
decode PostMetaInfo
|> required "slug" JD.string
|> required "author" JD.string
|> required "title" JD.string
|> required "description" JD.string
|> required "date" JD.string
|> required "tags" (JD.list JD.string)
|> required "headerimg" JD.string
|> required "pinned" JD.bool
|> required "published" JD.bool
| true | module Commands exposing (authRequest, getPostList)
import Http exposing (..)
import Json.Decode as JD exposing (at)
import Json.Encode as JE
import Json.Decode.Pipeline exposing (decode, required, optional)
import Messages exposing (..)
import Types exposing (AuthResponse, PostList, PostMetaInfo)
import Helpers exposing (tokenHeader)
import Maybe
authRequest : Maybe String -> String -> String -> String -> Cmd Msg
authRequest token api_url username password =
Http.request
{ method = "POST"
, headers = [ (tokenHeader token) ]
, url = authRequestUrl api_url
, body = authBody username password
, expect = authResponseExpect
, timeout = Nothing
, withCredentials = False
}
|> Http.send OnAuthCmdResponse
authRequestUrl : String -> String
authRequestUrl api_url =
api_url ++ "/auth"
getPostList : Maybe String -> String -> Cmd Msg
getPostList token api_url =
Http.request
{ method = "GET"
, headers = [ (tokenHeader token) ]
, url = getPostListUrl api_url
, body = emptyBody
, expect = postlistExpect
, timeout = Nothing
, withCredentials = False
}
|> Http.send OnPostListResponse
getPostListUrl : String -> String
getPostListUrl api_url =
api_url ++ "/posts"
-- CMD encoder
authBody : String -> String -> Body
authBody username password =
jsonBody
(JE.object
[ ( "username", JE.string username )
, ( "password", JE.string PI:PASSWORD:<PASSWORD>END_PI )
]
)
-- CMD response DECODERS
authResponseExpect : Expect AuthResponse
authResponseExpect =
expectJson collectionDecoder
collectionDecoder : JD.Decoder AuthResponse
collectionDecoder =
decode AuthResponse
|> required "code" JD.string
|> required "token" JD.string
postlistExpect : Expect PostList
postlistExpect =
expectJson postlistDecoder
postlistDecoder : JD.Decoder PostList
postlistDecoder =
JD.list postMetaInfoDecoder
postMetaInfoDecoder : JD.Decoder PostMetaInfo
postMetaInfoDecoder =
decode PostMetaInfo
|> required "slug" JD.string
|> required "author" JD.string
|> required "title" JD.string
|> required "description" JD.string
|> required "date" JD.string
|> required "tags" (JD.list JD.string)
|> required "headerimg" JD.string
|> required "pinned" JD.bool
|> required "published" JD.bool
| elm |
[
{
"context": "t _ =\n ( { templates =\n [ { name = \"Trousers\"\n , color = \"darkkhaki\"\n ",
"end": 1703,
"score": 0.9182984829,
"start": 1695,
"tag": "NAME",
"value": "Trousers"
},
{
"context": "arkkhaki\"\n }\n , { name = \"Stuff\"\n , color = \"darkgoldenrod\"\n ",
"end": 1786,
"score": 0.8909261227,
"start": 1781,
"tag": "NAME",
"value": "Stuff"
},
{
"context": "oldenrod\"\n }\n , { name = \"Thing\"\n , color = \"darkgray\"\n ",
"end": 1873,
"score": 0.9507609606,
"start": 1868,
"tag": "NAME",
"value": "Thing"
}
] | client/src/Main.elm | deeph00n/graphy | 0 | module Main exposing (..)
import Browser
import Color
import Html exposing (..)
import Html.Attributes exposing (..)
-- VIEW
view : Model -> Html Msg
view model =
layout [ text "Hello, World!" ] [] [ templateList model.templates ]
layout : List (Html Msg) -> List (Html Msg) -> List (Html Msg) -> Html Msg
layout head content menu =
div
[ style "font-family" "arial"
, style "height" "600px"
]
[ div
[ style "color" Color.secondary
, style "background-color" Color.primary
, style "padding" "1rem"
]
head
, div
[ style "width" "200px"
, style "background-color" Color.tertiary
, style "height" "100%"
, style "float" "left"
]
menu
, div
[ style "margin-left" "200px"
, style "height" "100%"
]
content
]
templateList : List Template -> Html Msg
templateList templates =
div [] (List.map templateView templates)
templateView : Template -> Html Msg
templateView template =
div
[ style "color" Color.secondary
, style "padding" "0.5rem"
, style "margin" "0.5rem"
, style "background-color" template.color
, style "cursor" "grab"
]
[ text template.name ]
-- MODEL
type alias Template =
{ name : String
, color : String
}
type alias Node =
{ name : String
, template : Template
}
type alias Model =
{ templates : List Template
, nodes : List Node
}
init : () -> ( Model, Cmd Msg )
init _ =
( { templates =
[ { name = "Trousers"
, color = "darkkhaki"
}
, { name = "Stuff"
, color = "darkgoldenrod"
}
, { name = "Thing"
, color = "darkgray"
}
]
, nodes = []
}
, Cmd.none
)
-- UPDATE
type alias Msg
= Int
update : Msg -> Model -> ( Model, Cmd Msg )
update _ model =
( model, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
-- MAIN
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
| 29022 | module Main exposing (..)
import Browser
import Color
import Html exposing (..)
import Html.Attributes exposing (..)
-- VIEW
view : Model -> Html Msg
view model =
layout [ text "Hello, World!" ] [] [ templateList model.templates ]
layout : List (Html Msg) -> List (Html Msg) -> List (Html Msg) -> Html Msg
layout head content menu =
div
[ style "font-family" "arial"
, style "height" "600px"
]
[ div
[ style "color" Color.secondary
, style "background-color" Color.primary
, style "padding" "1rem"
]
head
, div
[ style "width" "200px"
, style "background-color" Color.tertiary
, style "height" "100%"
, style "float" "left"
]
menu
, div
[ style "margin-left" "200px"
, style "height" "100%"
]
content
]
templateList : List Template -> Html Msg
templateList templates =
div [] (List.map templateView templates)
templateView : Template -> Html Msg
templateView template =
div
[ style "color" Color.secondary
, style "padding" "0.5rem"
, style "margin" "0.5rem"
, style "background-color" template.color
, style "cursor" "grab"
]
[ text template.name ]
-- MODEL
type alias Template =
{ name : String
, color : String
}
type alias Node =
{ name : String
, template : Template
}
type alias Model =
{ templates : List Template
, nodes : List Node
}
init : () -> ( Model, Cmd Msg )
init _ =
( { templates =
[ { name = "<NAME>"
, color = "darkkhaki"
}
, { name = "<NAME>"
, color = "darkgoldenrod"
}
, { name = "<NAME>"
, color = "darkgray"
}
]
, nodes = []
}
, Cmd.none
)
-- UPDATE
type alias Msg
= Int
update : Msg -> Model -> ( Model, Cmd Msg )
update _ model =
( model, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
-- MAIN
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
| true | module Main exposing (..)
import Browser
import Color
import Html exposing (..)
import Html.Attributes exposing (..)
-- VIEW
view : Model -> Html Msg
view model =
layout [ text "Hello, World!" ] [] [ templateList model.templates ]
layout : List (Html Msg) -> List (Html Msg) -> List (Html Msg) -> Html Msg
layout head content menu =
div
[ style "font-family" "arial"
, style "height" "600px"
]
[ div
[ style "color" Color.secondary
, style "background-color" Color.primary
, style "padding" "1rem"
]
head
, div
[ style "width" "200px"
, style "background-color" Color.tertiary
, style "height" "100%"
, style "float" "left"
]
menu
, div
[ style "margin-left" "200px"
, style "height" "100%"
]
content
]
templateList : List Template -> Html Msg
templateList templates =
div [] (List.map templateView templates)
templateView : Template -> Html Msg
templateView template =
div
[ style "color" Color.secondary
, style "padding" "0.5rem"
, style "margin" "0.5rem"
, style "background-color" template.color
, style "cursor" "grab"
]
[ text template.name ]
-- MODEL
type alias Template =
{ name : String
, color : String
}
type alias Node =
{ name : String
, template : Template
}
type alias Model =
{ templates : List Template
, nodes : List Node
}
init : () -> ( Model, Cmd Msg )
init _ =
( { templates =
[ { name = "PI:NAME:<NAME>END_PI"
, color = "darkkhaki"
}
, { name = "PI:NAME:<NAME>END_PI"
, color = "darkgoldenrod"
}
, { name = "PI:NAME:<NAME>END_PI"
, color = "darkgray"
}
]
, nodes = []
}
, Cmd.none
)
-- UPDATE
type alias Msg
= Int
update : Msg -> Model -> ( Model, Cmd Msg )
update _ model =
( model, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
-- MAIN
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
| elm |
[
{
"context": " , a\n [ href \"https://github.com/woolfson-group/isambard\" ]\n [ img\n ",
"end": 3136,
"score": 0.9993374348,
"start": 3122,
"tag": "USERNAME",
"value": "woolfson-group"
},
{
"context": "/github.\"\n ++ \"com/woolfson-group/isambard).\"\n )\n ",
"end": 7304,
"score": 0.9984092116,
"start": 7290,
"tag": "USERNAME",
"value": "woolfson-group"
},
{
"context": "/github.\"\n ++ \"com/woolfson-group/isambard).\"\n )\n ",
"end": 8019,
"score": 0.997587204,
"start": 8005,
"tag": "USERNAME",
"value": "woolfson-group"
},
{
"context": "please\neither create an issue on GitHub or contact chris.wood@bris.ac.uk.\n\n### Citation\n\n[Wood CW and Woolfson DN (2017) C",
"end": 21314,
"score": 0.9999170303,
"start": 21293,
"tag": "EMAIL",
"value": "chris.wood@bris.ac.uk"
}
] | web/ccbmk2/elm-src/Views.elm | woolfson-group/ccbuilder2 | 1 | module Views exposing (..)
import BuilderCss exposing (CssClasses(..), cssNamespace, panelStyling)
import BuildPanel
import Css
import Css.Colors
import Dict
import ExamplesPanel
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Html.CssHelpers
import Model exposing (..)
import Markdown
import Types
exposing
( Msg(..)
, ParameterRecord
, HistoryID
, HistoryEntry
, ParametersDict
, Parameter(..)
, HelixType(..)
, BuildMode(..)
, OptStatus(..)
, Panel(..)
, Representation
, RepOption(..)
, InfoBoxID(..)
, optStatusToString
, emptyParameterRecord
)
{ class, classList, id } =
Html.CssHelpers.withNamespace cssNamespace
styles : List Css.Mixin -> Attribute msg
styles =
Css.asPairs >> Html.Attributes.style
view : Model -> Html Msg
view model =
div [ id "viewer", styles viewerStyling ] [ overlayPanels model ]
viewerStyling : List Css.Mixin
viewerStyling =
[ Css.position Css.fixed
, Css.bottom (Css.px 0)
, Css.top (Css.px 0)
, Css.left (Css.px 0)
, Css.right (Css.px 0)
]
overlayPanels : Model -> Html Msg
overlayPanels model =
let
panelDivs =
[ siteHeader
, topLeftToggles
, topRightToggles
, bottomRightToggles
, BuildPanel.buildPanel
model.helixType
model.buildMode
model.parameters
model.currentInput
model.building
model.panelVisibility.buildPanel
, optimisePanel model
, ExamplesPanel.examplesPanel
model.building
model.panelVisibility.examplesPanel
, buildingStatusPanel model.building
, buildHistoryPanel
model.modelHistory
model.building
model.panelVisibility.buildHistoryPanel
, viewerPanel model.panelVisibility.viewerPanel
, modelInfoGroup model
, aboutPanel model.panelVisibility.aboutPanel
]
++ (List.length model.optJobs
|> List.range 1
|> List.map2 optJobStatus model.optJobs
)
in
div [] panelDivs
siteHeader : Html msg
siteHeader =
div
[ class [ FlexContainerCss ]
, id [ AppHeaderPanel ]
, styles <| headerStyling ++ panelStyling
]
[ header [ styles [ Css.width (Css.pct 50) ] ] [ h1 [] [ text "CCBuilder 2.0" ] ]
, div
[ styles
[ Css.width (Css.pct 50)
, Css.textAlign Css.right
, Css.paddingRight (Css.px 10)
]
]
[ h3
[ styles
[ Css.position Css.absolute
, Css.right (Css.px 50)
]
]
[ text "Powered by" ]
, a
[ href "https://github.com/woolfson-group/isambard" ]
[ img
[ styles
[ Css.height (Css.pct 80)
, Css.position Css.absolute
, Css.top (Css.pct 10)
, Css.right (Css.px 3)
, Css.borderRadius (Css.px 3)
]
, src "static/images/logo_small.png"
]
[]
]
]
]
headerStyling : List Css.Mixin
headerStyling =
[ Css.position Css.absolute
, Css.lineHeight (Css.px 50)
, Css.top (Css.px 0)
, Css.left (Css.px 0)
, Css.width (Css.pct 100)
]
topLeftToggles : Html Msg
topLeftToggles =
div [ styles topLeftTogglesStyling ]
[ BuildPanel.toggleBuildPanel
, ExamplesPanel.toggleExamplesPanel
, toggleOptimisePanel
]
topLeftTogglesStyling : List Css.Mixin
topLeftTogglesStyling =
[ Css.top (Css.px 60)
, Css.left (Css.px 0)
, Css.zIndex (Css.int 2)
, Css.position Css.absolute
]
topRightToggles : Html Msg
topRightToggles =
div [ styles topRightTogglesStyling ]
[ toggleBuildHistoryPanel
, toggleViewerPanel
]
topRightTogglesStyling : List Css.Mixin
topRightTogglesStyling =
[ Css.top (Css.px 60)
, Css.right (Css.px 0)
, Css.zIndex (Css.int 2)
, Css.position Css.absolute
, Css.width (Css.px 30)
]
bottomRightToggles : Html Msg
bottomRightToggles =
div [ styles bottomRightTogglesStyling ]
[ toggleAboutPanel
]
bottomRightTogglesStyling : List Css.Mixin
bottomRightTogglesStyling =
[ Css.bottom (Css.px 20)
, Css.right (Css.px 0)
, Css.zIndex (Css.int 2)
, Css.position Css.absolute
, Css.width (Css.px 30)
]
-- Optimise Panel
optimisePanel : Model -> Html Msg
optimisePanel model =
let
visible =
model.panelVisibility.optimisePanel
advancedBuild =
case model.buildMode of
Basic ->
False
Advanced ->
True
optimising =
if List.length model.optJobs > 0 then
True
else
False
totalResidueCount =
Dict.values model.parameters
|> List.map .sequence
|> List.map (Maybe.withDefault "")
|> List.map String.length
|> List.sum
aboveResLimit =
if totalResidueCount > 240 then
True
else
False
disabledOpt =
advancedBuild || optimising || aboveResLimit
in
div
[ class [ OverlayPanelCss ]
, styles <| panelStyling ++ optimisePanelStyling
, hidden <| not visible
]
([ h3 [] [ text "Optimise Parameters" ]
, hr [] []
{- Removing until fix
, text "Heat"
, br [] []
, input
[ type_ "range"
, Html.Attributes.min "0"
, Html.Attributes.max "2000"
, value (toString model.heat)
, onInput SetHeat
]
[]
, br [] []
-}
]
++ [ button
[ onClick Optimise, disabled disabledOpt ]
[ text "Optimise Model" ]
]
++ (if advancedBuild then
[ hr [] []
, h3 [] [ text "Warning" ]
, Markdown.toHtml
[ styles [ Css.color (Css.Colors.red) ]
]
("Optimisation cannot be performed in advanced mode"
++ ". If you'd like to run larger more complex"
++ " optimisations, please "
++ "consider using [ISAMBARD](https://github."
++ "com/woolfson-group/isambard)."
)
]
else if aboveResLimit then
[ hr [] []
, h3 [] [ text "Warning" ]
, Markdown.toHtml
[ styles [ Css.color (Css.Colors.red) ]
]
("Due to available compute, only models with 240 "
++ "or less residues can be optimised. If you'd"
++ " like to run larger optimisations, please "
++ "consider using [ISAMBARD](https://github."
++ "com/woolfson-group/isambard)."
)
]
else
[]
)
)
optimisePanelStyling : List Css.Mixin
optimisePanelStyling =
[ Css.top (Css.px 60)
, Css.left (Css.px 35)
, Css.maxWidth (Css.pct 30)
]
toggleOptimisePanel : Html Msg
toggleOptimisePanel =
div
[ class [ OverlayPanelCss, LeftPanelToggleCss ]
, onClick (TogglePanel OptimisePanel)
]
[ text "Optimise" ]
-- Model Info
modelInfoGroup : Model -> Html Msg
modelInfoGroup model =
div
[ class [ FlexContainerCss ]
, styles <| modelInfoGroupPanelStyling ++ panelStyling
]
([ modelInfoPanel model
]
++ (if List.member MIBudeEnergy model.activeInfoBoxes then
[ budeEnergyInfo ]
else if List.member MIRPT model.activeInfoBoxes then
[ rptInfo ]
else if List.member MIHLKnobs model.activeInfoBoxes then
[ highlightKIHInfo ]
else
[]
)
)
modelInfoPanel : Model -> Html Msg
modelInfoPanel model =
div
[ class [ OverlayPanelCss, FlexItemCss ]
, styles [ Css.bottom (Css.px 0) ]
]
[ h3 [] [ text "Model Information" ]
, hr [] []
, infoText MIBudeEnergy "BUDE Energy �"
, Maybe.map (roundToXDecPlaces 1) model.score
|> Maybe.map toString
|> Maybe.withDefault ""
|> \val -> input [ value val, readonly True ] []
, hr [] []
, infoText MIRPT "Residues per Turn �"
, Maybe.map (roundToXDecPlaces 2) model.residuesPerTurn
|> Maybe.map toString
|> Maybe.withDefault ""
|> \val -> input [ value val, readonly True ] []
, hr [] []
, button
[ class [ CCBButtonCss ]
, styles [ Css.float Css.left ]
, onClick HighlightKnobs
]
[ text "Highlight Knobs" ]
, infoText MIHLKnobs "�"
, hr [] []
, downloadStructureButton model.pdbFile
]
budeEnergyInfo : Html msg
budeEnergyInfo =
div
[ class [ OverlayPanelCss, FlexItemCss ]
, styles infoBoxStyling
]
[ h3 [] [ text "BUDE Energy" ]
, text mIBudeEnergyText
]
mIBudeEnergyText : String
mIBudeEnergyText =
"""The interaction energy between helices as calculated by the BUDE force field implemented in the BUFF module of ISAMBARD."""
rptInfo : Html msg
rptInfo =
div
[ class [ OverlayPanelCss, FlexItemCss ]
, styles infoBoxStyling
]
[ h3 [] [ text "Residues Per Turn" ]
, text mIRPTText
]
mIRPTText : String
mIRPTText =
"""Residues per turn of the alpha helix, can be used as a proxy for backbone strain."""
highlightKIHInfo : Html msg
highlightKIHInfo =
div
[ class [ OverlayPanelCss, FlexItemCss ]
, styles infoBoxStyling
]
[ h3 [] [ text "Highlight Knobs" ]
, text highlightKIHText
]
highlightKIHText : String
highlightKIHText =
"""Highlights knob residues red, all other residues are coloured blue."""
modelInfoGroupPanelStyling : List Css.Mixin
modelInfoGroupPanelStyling =
[ Css.bottom (Css.px 0)
, Css.left (Css.px 0)
]
infoBoxStyling : List Css.Mixin
infoBoxStyling =
[ Css.maxWidth (Css.pct 40)
, Css.maxHeight (Css.em 8)
, Css.lineHeight (Css.em 1)
]
roundToXDecPlaces : Int -> Float -> Float
roundToXDecPlaces precision num =
let
scaling =
10 ^ precision |> toFloat
in
round (num * scaling)
|> toFloat
|> flip (/) scaling
downloadStructureButton : Maybe String -> Html Msg
downloadStructureButton pdbFile =
let
deactivated =
if pdbFile == Nothing then
True
else
False
in
button
[ class [ CCBButtonCss ]
, onClick DownloadPdb
, disabled deactivated
]
[ text "Download PDB" ]
-- Build History
buildHistoryPanel : Dict.Dict Int HistoryEntry -> Bool -> Bool -> Html Msg
buildHistoryPanel modelHistory building visible =
div
[ class [ OverlayPanelCss ]
, id [ BuildHistoryPanel ]
, styles <| panelStyling ++ buildHistoryPanelStyling
, hidden <| not visible
]
[ h2 [] [ text "Build History" ]
, hr [] []
, table []
[ modelDetailTableHeader
, List.map2 modelParametersAsRow
(Dict.toList modelHistory |> List.reverse)
(List.repeat (List.length <| Dict.toList modelHistory) building)
|> List.concat
|> tbody []
]
]
modelDetailTableHeader : Html msg
modelDetailTableHeader =
thead []
[ tr []
[ th [] []
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Radius" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Pitch" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Interface Angle" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Super-Helical Rotation" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Z-Shift" ]
, th [] [ text "Sequence" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Register" ]
, th [] [ text "BUDE Score" ]
, th [] []
]
]
modelParametersAsRow : ( HistoryID, HistoryEntry ) -> Bool -> List (Html Msg)
modelParametersAsRow ( hID, ( parameters, visible, score, helixType, buildMode, _ ) ) building =
let
foldedRows =
Dict.values parameters
|> List.tail
|> Maybe.withDefault []
|> List.map (modelFoldedRow score)
in
if not visible then
[ modelHistoryTopRow hID parameters building visible score helixType buildMode ]
else
(modelHistoryTopRow hID parameters building visible score helixType buildMode)
:: foldedRows
modelHistoryTopRow :
HistoryID
-> ParametersDict
-> Bool
-> Bool
-> Float
-> HelixType
-> BuildMode
-> Html Msg
modelHistoryTopRow hID parameters building visible score helixType buildMode =
let
topRowParameters =
Dict.values parameters
|> List.head
|> Maybe.withDefault emptyParameterRecord
in
tr
[]
([ div
[ onClick (ExpandHistory hID) ]
[ if (not visible) then
text "▶"
else
text "▼"
]
]
++ List.map makeParameterTh
(parametersToRow topRowParameters score)
++ [ button
[ class [ CCBButtonCss ]
, onClick (SetParametersAndBuild parameters helixType buildMode)
, disabled building
]
[ text "Rebuild" ]
]
)
modelFoldedRow : Float -> ParameterRecord -> Html Msg
modelFoldedRow score parameters =
tr
[]
([ text " ┋"
]
++ List.map makeParameterTh
(parametersToRow parameters score)
)
parametersToRow : ParameterRecord -> Float -> List String
parametersToRow parameters score =
[ parameters.radius
|> Maybe.withDefault 0
|> roundToXDecPlaces 1
|> toString
, parameters.pitch
|> Maybe.withDefault 0
|> round
|> toString
, parameters.phiCA
|> Maybe.withDefault 0
|> roundToXDecPlaces 1
|> toString
, parameters.superHelRot
|> Maybe.withDefault 0
|> roundToXDecPlaces 1
|> toString
, parameters.zShift
|> Maybe.withDefault 0
|> roundToXDecPlaces 1
|> toString
, parameters.sequence |> Maybe.withDefault ""
, parameters.register
, toString <| roundToXDecPlaces 2 score
]
makeParameterTh : String -> Html Msg
makeParameterTh pString =
text pString
|> List.singleton
|> th []
buildHistoryPanelStyling : List Css.Mixin
buildHistoryPanelStyling =
[ Css.top (Css.px 60)
, Css.right (Css.px 35)
]
toggleBuildHistoryPanel : Html Msg
toggleBuildHistoryPanel =
div
[ class [ OverlayPanelCss, RightPanelToggleCss ]
, onClick (TogglePanel BuildHistoryPanel)
]
[ text "Build History" ]
-- Viewer Panel
viewerPanel : Bool -> Html Msg
viewerPanel visible =
div
[ class [ OverlayPanelCss ]
, id [ ViewerPanel ]
, styles <| panelStyling ++ viewerPanelStyling
, hidden <| not visible
]
[ h2 [] [ text "Viewer Options" ]
, hr [] []
, h3 [] [ text "Representation" ]
, hr [] []
, text "Backbone"
, br [] []
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation Cartoon)
]
[ text "Cartoon" ]
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation Trace)
]
[ text "Trace" ]
, br [] []
, text "All Atoms"
, br [] []
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation BallsAndSticks)
]
[ text "Balls and Sticks" ]
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation Spheres)
]
[ text "Spheres" ]
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation Points)
]
[ text "Dots" ]
, hr [] []
, h3 [] [ text "Other Options" ]
, hr [] []
, button
[ class [ CCBButtonCss ]
, onClick ShowAxes
]
[ text "Axes" ]
, text " (xyz = rgb)"
]
viewerPanelStyling : List Css.Mixin
viewerPanelStyling =
[ Css.top (Css.px 60)
, Css.right (Css.px 35)
]
toggleViewerPanel : Html Msg
toggleViewerPanel =
div
[ class [ OverlayPanelCss, RightPanelToggleCss ]
, onClick (TogglePanel ViewerPanel)
]
[ text "Viewer" ]
-- Info Box
infoText : InfoBoxID -> String -> Html Msg
infoText infoBoxID contentText =
div
[ onMouseEnter (ShowInfo infoBoxID)
, onMouseLeave (CloseInfo infoBoxID)
]
[ text contentText ]
-- Building Status
buildingStatusPanel : Bool -> Html msg
buildingStatusPanel building =
div
[ class [ OverlayPanelCss ]
, id [ BuildingStatusPanel ]
, styles <| buildingStatusStyling ++ panelStyling
, hidden (not building)
]
[ text "Building"
, img [ src "static/css/infinity.gif", width 80, height 80 ] []
]
buildingStatusStyling : List Css.Mixin
buildingStatusStyling =
[ Css.top (Css.pct 50)
, Css.left (Css.pct 50)
, Css.width (Css.px 80)
, Css.height (Css.px 80)
]
-- Optimisation Job
optJobStatus : ( String, OptStatus ) -> Int -> Html Msg
optJobStatus ( optID, status ) position =
div
[ class [ OverlayPanelCss ]
, styles <| optJobStatusStyling position ++ panelStyling
]
([ text "Optimising"
, br [] []
, text ("(" ++ (toString status) ++ ")")
]
++ (case status of
Complete ->
[ button
[ onClick (RetrieveOptimisation optID) ]
[ text "Retrieve" ]
]
Failed ->
[ button
[ onClick (ClearOptimisation optID) ]
[ text "Clear" ]
]
_ ->
[ img
[ src "static/css/infinity.gif", width 80, height 80 ]
[]
]
)
)
optJobStatusStyling : Int -> List Css.Mixin
optJobStatusStyling position =
[ Css.textAlign Css.center
, Css.bottom (Css.px 20)
, Css.right (Css.px 35)
, Css.width (Css.px 90)
]
-- About Panel
aboutPanel : Bool -> Html Msg
aboutPanel visible =
div
[ class [ OverlayPanelCss ]
, styles <| panelStyling ++ aboutPanelStyling
, hidden <| not visible
]
[ h2 [] [ text "About (Ver 2.0.4)" ]
, hr [] []
, Markdown.toHtml [] aboutText
]
aboutText : String
aboutText =
"""CCBuilder is developed and maintained by the [Woolfson Group, University
of Bristol](http://www.chm.bris.ac.uk/org/woolfson/). The project is open
source with code available on
[GitHub](https://github.com/woolfson-group/ccbuilder2). If you
encounter any bugs or have ideas for enhancements to CCBuilder 2.0, please
either create an issue on GitHub or contact chris.wood@bris.ac.uk.
### Citation
[Wood CW and Woolfson DN (2017) CCBuilder 2.0: Powerful and accessible
coiled-coil modelling,
_Protein Science_. doi: 10.1002/pro.3279](http://dx.doi.org/10.1002/pro.3279)
### Useful References
[Wood CW _et al_ (2017) ISAMBARD: an open-source computational environment
for biomolecular analysis, modelling and design, Bioinformatics.
doi: 10.1093/bioinformatics/btx352](
https://doi.org/10.1093/bioinformatics/btx352)
"""
aboutPanelStyling : List Css.Mixin
aboutPanelStyling =
[ Css.bottom (Css.px 20)
, Css.right (Css.px 35)
, Css.maxWidth (Css.pct 40)
]
toggleAboutPanel : Html Msg
toggleAboutPanel =
div
[ class [ OverlayPanelCss, RightPanelToggleCss ]
, onClick (TogglePanel AboutPanel)
]
[ text "About" ]
| 4638 | module Views exposing (..)
import BuilderCss exposing (CssClasses(..), cssNamespace, panelStyling)
import BuildPanel
import Css
import Css.Colors
import Dict
import ExamplesPanel
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Html.CssHelpers
import Model exposing (..)
import Markdown
import Types
exposing
( Msg(..)
, ParameterRecord
, HistoryID
, HistoryEntry
, ParametersDict
, Parameter(..)
, HelixType(..)
, BuildMode(..)
, OptStatus(..)
, Panel(..)
, Representation
, RepOption(..)
, InfoBoxID(..)
, optStatusToString
, emptyParameterRecord
)
{ class, classList, id } =
Html.CssHelpers.withNamespace cssNamespace
styles : List Css.Mixin -> Attribute msg
styles =
Css.asPairs >> Html.Attributes.style
view : Model -> Html Msg
view model =
div [ id "viewer", styles viewerStyling ] [ overlayPanels model ]
viewerStyling : List Css.Mixin
viewerStyling =
[ Css.position Css.fixed
, Css.bottom (Css.px 0)
, Css.top (Css.px 0)
, Css.left (Css.px 0)
, Css.right (Css.px 0)
]
overlayPanels : Model -> Html Msg
overlayPanels model =
let
panelDivs =
[ siteHeader
, topLeftToggles
, topRightToggles
, bottomRightToggles
, BuildPanel.buildPanel
model.helixType
model.buildMode
model.parameters
model.currentInput
model.building
model.panelVisibility.buildPanel
, optimisePanel model
, ExamplesPanel.examplesPanel
model.building
model.panelVisibility.examplesPanel
, buildingStatusPanel model.building
, buildHistoryPanel
model.modelHistory
model.building
model.panelVisibility.buildHistoryPanel
, viewerPanel model.panelVisibility.viewerPanel
, modelInfoGroup model
, aboutPanel model.panelVisibility.aboutPanel
]
++ (List.length model.optJobs
|> List.range 1
|> List.map2 optJobStatus model.optJobs
)
in
div [] panelDivs
siteHeader : Html msg
siteHeader =
div
[ class [ FlexContainerCss ]
, id [ AppHeaderPanel ]
, styles <| headerStyling ++ panelStyling
]
[ header [ styles [ Css.width (Css.pct 50) ] ] [ h1 [] [ text "CCBuilder 2.0" ] ]
, div
[ styles
[ Css.width (Css.pct 50)
, Css.textAlign Css.right
, Css.paddingRight (Css.px 10)
]
]
[ h3
[ styles
[ Css.position Css.absolute
, Css.right (Css.px 50)
]
]
[ text "Powered by" ]
, a
[ href "https://github.com/woolfson-group/isambard" ]
[ img
[ styles
[ Css.height (Css.pct 80)
, Css.position Css.absolute
, Css.top (Css.pct 10)
, Css.right (Css.px 3)
, Css.borderRadius (Css.px 3)
]
, src "static/images/logo_small.png"
]
[]
]
]
]
headerStyling : List Css.Mixin
headerStyling =
[ Css.position Css.absolute
, Css.lineHeight (Css.px 50)
, Css.top (Css.px 0)
, Css.left (Css.px 0)
, Css.width (Css.pct 100)
]
topLeftToggles : Html Msg
topLeftToggles =
div [ styles topLeftTogglesStyling ]
[ BuildPanel.toggleBuildPanel
, ExamplesPanel.toggleExamplesPanel
, toggleOptimisePanel
]
topLeftTogglesStyling : List Css.Mixin
topLeftTogglesStyling =
[ Css.top (Css.px 60)
, Css.left (Css.px 0)
, Css.zIndex (Css.int 2)
, Css.position Css.absolute
]
topRightToggles : Html Msg
topRightToggles =
div [ styles topRightTogglesStyling ]
[ toggleBuildHistoryPanel
, toggleViewerPanel
]
topRightTogglesStyling : List Css.Mixin
topRightTogglesStyling =
[ Css.top (Css.px 60)
, Css.right (Css.px 0)
, Css.zIndex (Css.int 2)
, Css.position Css.absolute
, Css.width (Css.px 30)
]
bottomRightToggles : Html Msg
bottomRightToggles =
div [ styles bottomRightTogglesStyling ]
[ toggleAboutPanel
]
bottomRightTogglesStyling : List Css.Mixin
bottomRightTogglesStyling =
[ Css.bottom (Css.px 20)
, Css.right (Css.px 0)
, Css.zIndex (Css.int 2)
, Css.position Css.absolute
, Css.width (Css.px 30)
]
-- Optimise Panel
optimisePanel : Model -> Html Msg
optimisePanel model =
let
visible =
model.panelVisibility.optimisePanel
advancedBuild =
case model.buildMode of
Basic ->
False
Advanced ->
True
optimising =
if List.length model.optJobs > 0 then
True
else
False
totalResidueCount =
Dict.values model.parameters
|> List.map .sequence
|> List.map (Maybe.withDefault "")
|> List.map String.length
|> List.sum
aboveResLimit =
if totalResidueCount > 240 then
True
else
False
disabledOpt =
advancedBuild || optimising || aboveResLimit
in
div
[ class [ OverlayPanelCss ]
, styles <| panelStyling ++ optimisePanelStyling
, hidden <| not visible
]
([ h3 [] [ text "Optimise Parameters" ]
, hr [] []
{- Removing until fix
, text "Heat"
, br [] []
, input
[ type_ "range"
, Html.Attributes.min "0"
, Html.Attributes.max "2000"
, value (toString model.heat)
, onInput SetHeat
]
[]
, br [] []
-}
]
++ [ button
[ onClick Optimise, disabled disabledOpt ]
[ text "Optimise Model" ]
]
++ (if advancedBuild then
[ hr [] []
, h3 [] [ text "Warning" ]
, Markdown.toHtml
[ styles [ Css.color (Css.Colors.red) ]
]
("Optimisation cannot be performed in advanced mode"
++ ". If you'd like to run larger more complex"
++ " optimisations, please "
++ "consider using [ISAMBARD](https://github."
++ "com/woolfson-group/isambard)."
)
]
else if aboveResLimit then
[ hr [] []
, h3 [] [ text "Warning" ]
, Markdown.toHtml
[ styles [ Css.color (Css.Colors.red) ]
]
("Due to available compute, only models with 240 "
++ "or less residues can be optimised. If you'd"
++ " like to run larger optimisations, please "
++ "consider using [ISAMBARD](https://github."
++ "com/woolfson-group/isambard)."
)
]
else
[]
)
)
optimisePanelStyling : List Css.Mixin
optimisePanelStyling =
[ Css.top (Css.px 60)
, Css.left (Css.px 35)
, Css.maxWidth (Css.pct 30)
]
toggleOptimisePanel : Html Msg
toggleOptimisePanel =
div
[ class [ OverlayPanelCss, LeftPanelToggleCss ]
, onClick (TogglePanel OptimisePanel)
]
[ text "Optimise" ]
-- Model Info
modelInfoGroup : Model -> Html Msg
modelInfoGroup model =
div
[ class [ FlexContainerCss ]
, styles <| modelInfoGroupPanelStyling ++ panelStyling
]
([ modelInfoPanel model
]
++ (if List.member MIBudeEnergy model.activeInfoBoxes then
[ budeEnergyInfo ]
else if List.member MIRPT model.activeInfoBoxes then
[ rptInfo ]
else if List.member MIHLKnobs model.activeInfoBoxes then
[ highlightKIHInfo ]
else
[]
)
)
modelInfoPanel : Model -> Html Msg
modelInfoPanel model =
div
[ class [ OverlayPanelCss, FlexItemCss ]
, styles [ Css.bottom (Css.px 0) ]
]
[ h3 [] [ text "Model Information" ]
, hr [] []
, infoText MIBudeEnergy "BUDE Energy �"
, Maybe.map (roundToXDecPlaces 1) model.score
|> Maybe.map toString
|> Maybe.withDefault ""
|> \val -> input [ value val, readonly True ] []
, hr [] []
, infoText MIRPT "Residues per Turn �"
, Maybe.map (roundToXDecPlaces 2) model.residuesPerTurn
|> Maybe.map toString
|> Maybe.withDefault ""
|> \val -> input [ value val, readonly True ] []
, hr [] []
, button
[ class [ CCBButtonCss ]
, styles [ Css.float Css.left ]
, onClick HighlightKnobs
]
[ text "Highlight Knobs" ]
, infoText MIHLKnobs "�"
, hr [] []
, downloadStructureButton model.pdbFile
]
budeEnergyInfo : Html msg
budeEnergyInfo =
div
[ class [ OverlayPanelCss, FlexItemCss ]
, styles infoBoxStyling
]
[ h3 [] [ text "BUDE Energy" ]
, text mIBudeEnergyText
]
mIBudeEnergyText : String
mIBudeEnergyText =
"""The interaction energy between helices as calculated by the BUDE force field implemented in the BUFF module of ISAMBARD."""
rptInfo : Html msg
rptInfo =
div
[ class [ OverlayPanelCss, FlexItemCss ]
, styles infoBoxStyling
]
[ h3 [] [ text "Residues Per Turn" ]
, text mIRPTText
]
mIRPTText : String
mIRPTText =
"""Residues per turn of the alpha helix, can be used as a proxy for backbone strain."""
highlightKIHInfo : Html msg
highlightKIHInfo =
div
[ class [ OverlayPanelCss, FlexItemCss ]
, styles infoBoxStyling
]
[ h3 [] [ text "Highlight Knobs" ]
, text highlightKIHText
]
highlightKIHText : String
highlightKIHText =
"""Highlights knob residues red, all other residues are coloured blue."""
modelInfoGroupPanelStyling : List Css.Mixin
modelInfoGroupPanelStyling =
[ Css.bottom (Css.px 0)
, Css.left (Css.px 0)
]
infoBoxStyling : List Css.Mixin
infoBoxStyling =
[ Css.maxWidth (Css.pct 40)
, Css.maxHeight (Css.em 8)
, Css.lineHeight (Css.em 1)
]
roundToXDecPlaces : Int -> Float -> Float
roundToXDecPlaces precision num =
let
scaling =
10 ^ precision |> toFloat
in
round (num * scaling)
|> toFloat
|> flip (/) scaling
downloadStructureButton : Maybe String -> Html Msg
downloadStructureButton pdbFile =
let
deactivated =
if pdbFile == Nothing then
True
else
False
in
button
[ class [ CCBButtonCss ]
, onClick DownloadPdb
, disabled deactivated
]
[ text "Download PDB" ]
-- Build History
buildHistoryPanel : Dict.Dict Int HistoryEntry -> Bool -> Bool -> Html Msg
buildHistoryPanel modelHistory building visible =
div
[ class [ OverlayPanelCss ]
, id [ BuildHistoryPanel ]
, styles <| panelStyling ++ buildHistoryPanelStyling
, hidden <| not visible
]
[ h2 [] [ text "Build History" ]
, hr [] []
, table []
[ modelDetailTableHeader
, List.map2 modelParametersAsRow
(Dict.toList modelHistory |> List.reverse)
(List.repeat (List.length <| Dict.toList modelHistory) building)
|> List.concat
|> tbody []
]
]
modelDetailTableHeader : Html msg
modelDetailTableHeader =
thead []
[ tr []
[ th [] []
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Radius" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Pitch" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Interface Angle" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Super-Helical Rotation" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Z-Shift" ]
, th [] [ text "Sequence" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Register" ]
, th [] [ text "BUDE Score" ]
, th [] []
]
]
modelParametersAsRow : ( HistoryID, HistoryEntry ) -> Bool -> List (Html Msg)
modelParametersAsRow ( hID, ( parameters, visible, score, helixType, buildMode, _ ) ) building =
let
foldedRows =
Dict.values parameters
|> List.tail
|> Maybe.withDefault []
|> List.map (modelFoldedRow score)
in
if not visible then
[ modelHistoryTopRow hID parameters building visible score helixType buildMode ]
else
(modelHistoryTopRow hID parameters building visible score helixType buildMode)
:: foldedRows
modelHistoryTopRow :
HistoryID
-> ParametersDict
-> Bool
-> Bool
-> Float
-> HelixType
-> BuildMode
-> Html Msg
modelHistoryTopRow hID parameters building visible score helixType buildMode =
let
topRowParameters =
Dict.values parameters
|> List.head
|> Maybe.withDefault emptyParameterRecord
in
tr
[]
([ div
[ onClick (ExpandHistory hID) ]
[ if (not visible) then
text "▶"
else
text "▼"
]
]
++ List.map makeParameterTh
(parametersToRow topRowParameters score)
++ [ button
[ class [ CCBButtonCss ]
, onClick (SetParametersAndBuild parameters helixType buildMode)
, disabled building
]
[ text "Rebuild" ]
]
)
modelFoldedRow : Float -> ParameterRecord -> Html Msg
modelFoldedRow score parameters =
tr
[]
([ text " ┋"
]
++ List.map makeParameterTh
(parametersToRow parameters score)
)
parametersToRow : ParameterRecord -> Float -> List String
parametersToRow parameters score =
[ parameters.radius
|> Maybe.withDefault 0
|> roundToXDecPlaces 1
|> toString
, parameters.pitch
|> Maybe.withDefault 0
|> round
|> toString
, parameters.phiCA
|> Maybe.withDefault 0
|> roundToXDecPlaces 1
|> toString
, parameters.superHelRot
|> Maybe.withDefault 0
|> roundToXDecPlaces 1
|> toString
, parameters.zShift
|> Maybe.withDefault 0
|> roundToXDecPlaces 1
|> toString
, parameters.sequence |> Maybe.withDefault ""
, parameters.register
, toString <| roundToXDecPlaces 2 score
]
makeParameterTh : String -> Html Msg
makeParameterTh pString =
text pString
|> List.singleton
|> th []
buildHistoryPanelStyling : List Css.Mixin
buildHistoryPanelStyling =
[ Css.top (Css.px 60)
, Css.right (Css.px 35)
]
toggleBuildHistoryPanel : Html Msg
toggleBuildHistoryPanel =
div
[ class [ OverlayPanelCss, RightPanelToggleCss ]
, onClick (TogglePanel BuildHistoryPanel)
]
[ text "Build History" ]
-- Viewer Panel
viewerPanel : Bool -> Html Msg
viewerPanel visible =
div
[ class [ OverlayPanelCss ]
, id [ ViewerPanel ]
, styles <| panelStyling ++ viewerPanelStyling
, hidden <| not visible
]
[ h2 [] [ text "Viewer Options" ]
, hr [] []
, h3 [] [ text "Representation" ]
, hr [] []
, text "Backbone"
, br [] []
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation Cartoon)
]
[ text "Cartoon" ]
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation Trace)
]
[ text "Trace" ]
, br [] []
, text "All Atoms"
, br [] []
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation BallsAndSticks)
]
[ text "Balls and Sticks" ]
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation Spheres)
]
[ text "Spheres" ]
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation Points)
]
[ text "Dots" ]
, hr [] []
, h3 [] [ text "Other Options" ]
, hr [] []
, button
[ class [ CCBButtonCss ]
, onClick ShowAxes
]
[ text "Axes" ]
, text " (xyz = rgb)"
]
viewerPanelStyling : List Css.Mixin
viewerPanelStyling =
[ Css.top (Css.px 60)
, Css.right (Css.px 35)
]
toggleViewerPanel : Html Msg
toggleViewerPanel =
div
[ class [ OverlayPanelCss, RightPanelToggleCss ]
, onClick (TogglePanel ViewerPanel)
]
[ text "Viewer" ]
-- Info Box
infoText : InfoBoxID -> String -> Html Msg
infoText infoBoxID contentText =
div
[ onMouseEnter (ShowInfo infoBoxID)
, onMouseLeave (CloseInfo infoBoxID)
]
[ text contentText ]
-- Building Status
buildingStatusPanel : Bool -> Html msg
buildingStatusPanel building =
div
[ class [ OverlayPanelCss ]
, id [ BuildingStatusPanel ]
, styles <| buildingStatusStyling ++ panelStyling
, hidden (not building)
]
[ text "Building"
, img [ src "static/css/infinity.gif", width 80, height 80 ] []
]
buildingStatusStyling : List Css.Mixin
buildingStatusStyling =
[ Css.top (Css.pct 50)
, Css.left (Css.pct 50)
, Css.width (Css.px 80)
, Css.height (Css.px 80)
]
-- Optimisation Job
optJobStatus : ( String, OptStatus ) -> Int -> Html Msg
optJobStatus ( optID, status ) position =
div
[ class [ OverlayPanelCss ]
, styles <| optJobStatusStyling position ++ panelStyling
]
([ text "Optimising"
, br [] []
, text ("(" ++ (toString status) ++ ")")
]
++ (case status of
Complete ->
[ button
[ onClick (RetrieveOptimisation optID) ]
[ text "Retrieve" ]
]
Failed ->
[ button
[ onClick (ClearOptimisation optID) ]
[ text "Clear" ]
]
_ ->
[ img
[ src "static/css/infinity.gif", width 80, height 80 ]
[]
]
)
)
optJobStatusStyling : Int -> List Css.Mixin
optJobStatusStyling position =
[ Css.textAlign Css.center
, Css.bottom (Css.px 20)
, Css.right (Css.px 35)
, Css.width (Css.px 90)
]
-- About Panel
aboutPanel : Bool -> Html Msg
aboutPanel visible =
div
[ class [ OverlayPanelCss ]
, styles <| panelStyling ++ aboutPanelStyling
, hidden <| not visible
]
[ h2 [] [ text "About (Ver 2.0.4)" ]
, hr [] []
, Markdown.toHtml [] aboutText
]
aboutText : String
aboutText =
"""CCBuilder is developed and maintained by the [Woolfson Group, University
of Bristol](http://www.chm.bris.ac.uk/org/woolfson/). The project is open
source with code available on
[GitHub](https://github.com/woolfson-group/ccbuilder2). If you
encounter any bugs or have ideas for enhancements to CCBuilder 2.0, please
either create an issue on GitHub or contact <EMAIL>.
### Citation
[Wood CW and Woolfson DN (2017) CCBuilder 2.0: Powerful and accessible
coiled-coil modelling,
_Protein Science_. doi: 10.1002/pro.3279](http://dx.doi.org/10.1002/pro.3279)
### Useful References
[Wood CW _et al_ (2017) ISAMBARD: an open-source computational environment
for biomolecular analysis, modelling and design, Bioinformatics.
doi: 10.1093/bioinformatics/btx352](
https://doi.org/10.1093/bioinformatics/btx352)
"""
aboutPanelStyling : List Css.Mixin
aboutPanelStyling =
[ Css.bottom (Css.px 20)
, Css.right (Css.px 35)
, Css.maxWidth (Css.pct 40)
]
toggleAboutPanel : Html Msg
toggleAboutPanel =
div
[ class [ OverlayPanelCss, RightPanelToggleCss ]
, onClick (TogglePanel AboutPanel)
]
[ text "About" ]
| true | module Views exposing (..)
import BuilderCss exposing (CssClasses(..), cssNamespace, panelStyling)
import BuildPanel
import Css
import Css.Colors
import Dict
import ExamplesPanel
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Html.CssHelpers
import Model exposing (..)
import Markdown
import Types
exposing
( Msg(..)
, ParameterRecord
, HistoryID
, HistoryEntry
, ParametersDict
, Parameter(..)
, HelixType(..)
, BuildMode(..)
, OptStatus(..)
, Panel(..)
, Representation
, RepOption(..)
, InfoBoxID(..)
, optStatusToString
, emptyParameterRecord
)
{ class, classList, id } =
Html.CssHelpers.withNamespace cssNamespace
styles : List Css.Mixin -> Attribute msg
styles =
Css.asPairs >> Html.Attributes.style
view : Model -> Html Msg
view model =
div [ id "viewer", styles viewerStyling ] [ overlayPanels model ]
viewerStyling : List Css.Mixin
viewerStyling =
[ Css.position Css.fixed
, Css.bottom (Css.px 0)
, Css.top (Css.px 0)
, Css.left (Css.px 0)
, Css.right (Css.px 0)
]
overlayPanels : Model -> Html Msg
overlayPanels model =
let
panelDivs =
[ siteHeader
, topLeftToggles
, topRightToggles
, bottomRightToggles
, BuildPanel.buildPanel
model.helixType
model.buildMode
model.parameters
model.currentInput
model.building
model.panelVisibility.buildPanel
, optimisePanel model
, ExamplesPanel.examplesPanel
model.building
model.panelVisibility.examplesPanel
, buildingStatusPanel model.building
, buildHistoryPanel
model.modelHistory
model.building
model.panelVisibility.buildHistoryPanel
, viewerPanel model.panelVisibility.viewerPanel
, modelInfoGroup model
, aboutPanel model.panelVisibility.aboutPanel
]
++ (List.length model.optJobs
|> List.range 1
|> List.map2 optJobStatus model.optJobs
)
in
div [] panelDivs
siteHeader : Html msg
siteHeader =
div
[ class [ FlexContainerCss ]
, id [ AppHeaderPanel ]
, styles <| headerStyling ++ panelStyling
]
[ header [ styles [ Css.width (Css.pct 50) ] ] [ h1 [] [ text "CCBuilder 2.0" ] ]
, div
[ styles
[ Css.width (Css.pct 50)
, Css.textAlign Css.right
, Css.paddingRight (Css.px 10)
]
]
[ h3
[ styles
[ Css.position Css.absolute
, Css.right (Css.px 50)
]
]
[ text "Powered by" ]
, a
[ href "https://github.com/woolfson-group/isambard" ]
[ img
[ styles
[ Css.height (Css.pct 80)
, Css.position Css.absolute
, Css.top (Css.pct 10)
, Css.right (Css.px 3)
, Css.borderRadius (Css.px 3)
]
, src "static/images/logo_small.png"
]
[]
]
]
]
headerStyling : List Css.Mixin
headerStyling =
[ Css.position Css.absolute
, Css.lineHeight (Css.px 50)
, Css.top (Css.px 0)
, Css.left (Css.px 0)
, Css.width (Css.pct 100)
]
topLeftToggles : Html Msg
topLeftToggles =
div [ styles topLeftTogglesStyling ]
[ BuildPanel.toggleBuildPanel
, ExamplesPanel.toggleExamplesPanel
, toggleOptimisePanel
]
topLeftTogglesStyling : List Css.Mixin
topLeftTogglesStyling =
[ Css.top (Css.px 60)
, Css.left (Css.px 0)
, Css.zIndex (Css.int 2)
, Css.position Css.absolute
]
topRightToggles : Html Msg
topRightToggles =
div [ styles topRightTogglesStyling ]
[ toggleBuildHistoryPanel
, toggleViewerPanel
]
topRightTogglesStyling : List Css.Mixin
topRightTogglesStyling =
[ Css.top (Css.px 60)
, Css.right (Css.px 0)
, Css.zIndex (Css.int 2)
, Css.position Css.absolute
, Css.width (Css.px 30)
]
bottomRightToggles : Html Msg
bottomRightToggles =
div [ styles bottomRightTogglesStyling ]
[ toggleAboutPanel
]
bottomRightTogglesStyling : List Css.Mixin
bottomRightTogglesStyling =
[ Css.bottom (Css.px 20)
, Css.right (Css.px 0)
, Css.zIndex (Css.int 2)
, Css.position Css.absolute
, Css.width (Css.px 30)
]
-- Optimise Panel
optimisePanel : Model -> Html Msg
optimisePanel model =
let
visible =
model.panelVisibility.optimisePanel
advancedBuild =
case model.buildMode of
Basic ->
False
Advanced ->
True
optimising =
if List.length model.optJobs > 0 then
True
else
False
totalResidueCount =
Dict.values model.parameters
|> List.map .sequence
|> List.map (Maybe.withDefault "")
|> List.map String.length
|> List.sum
aboveResLimit =
if totalResidueCount > 240 then
True
else
False
disabledOpt =
advancedBuild || optimising || aboveResLimit
in
div
[ class [ OverlayPanelCss ]
, styles <| panelStyling ++ optimisePanelStyling
, hidden <| not visible
]
([ h3 [] [ text "Optimise Parameters" ]
, hr [] []
{- Removing until fix
, text "Heat"
, br [] []
, input
[ type_ "range"
, Html.Attributes.min "0"
, Html.Attributes.max "2000"
, value (toString model.heat)
, onInput SetHeat
]
[]
, br [] []
-}
]
++ [ button
[ onClick Optimise, disabled disabledOpt ]
[ text "Optimise Model" ]
]
++ (if advancedBuild then
[ hr [] []
, h3 [] [ text "Warning" ]
, Markdown.toHtml
[ styles [ Css.color (Css.Colors.red) ]
]
("Optimisation cannot be performed in advanced mode"
++ ". If you'd like to run larger more complex"
++ " optimisations, please "
++ "consider using [ISAMBARD](https://github."
++ "com/woolfson-group/isambard)."
)
]
else if aboveResLimit then
[ hr [] []
, h3 [] [ text "Warning" ]
, Markdown.toHtml
[ styles [ Css.color (Css.Colors.red) ]
]
("Due to available compute, only models with 240 "
++ "or less residues can be optimised. If you'd"
++ " like to run larger optimisations, please "
++ "consider using [ISAMBARD](https://github."
++ "com/woolfson-group/isambard)."
)
]
else
[]
)
)
optimisePanelStyling : List Css.Mixin
optimisePanelStyling =
[ Css.top (Css.px 60)
, Css.left (Css.px 35)
, Css.maxWidth (Css.pct 30)
]
toggleOptimisePanel : Html Msg
toggleOptimisePanel =
div
[ class [ OverlayPanelCss, LeftPanelToggleCss ]
, onClick (TogglePanel OptimisePanel)
]
[ text "Optimise" ]
-- Model Info
modelInfoGroup : Model -> Html Msg
modelInfoGroup model =
div
[ class [ FlexContainerCss ]
, styles <| modelInfoGroupPanelStyling ++ panelStyling
]
([ modelInfoPanel model
]
++ (if List.member MIBudeEnergy model.activeInfoBoxes then
[ budeEnergyInfo ]
else if List.member MIRPT model.activeInfoBoxes then
[ rptInfo ]
else if List.member MIHLKnobs model.activeInfoBoxes then
[ highlightKIHInfo ]
else
[]
)
)
modelInfoPanel : Model -> Html Msg
modelInfoPanel model =
div
[ class [ OverlayPanelCss, FlexItemCss ]
, styles [ Css.bottom (Css.px 0) ]
]
[ h3 [] [ text "Model Information" ]
, hr [] []
, infoText MIBudeEnergy "BUDE Energy �"
, Maybe.map (roundToXDecPlaces 1) model.score
|> Maybe.map toString
|> Maybe.withDefault ""
|> \val -> input [ value val, readonly True ] []
, hr [] []
, infoText MIRPT "Residues per Turn �"
, Maybe.map (roundToXDecPlaces 2) model.residuesPerTurn
|> Maybe.map toString
|> Maybe.withDefault ""
|> \val -> input [ value val, readonly True ] []
, hr [] []
, button
[ class [ CCBButtonCss ]
, styles [ Css.float Css.left ]
, onClick HighlightKnobs
]
[ text "Highlight Knobs" ]
, infoText MIHLKnobs "�"
, hr [] []
, downloadStructureButton model.pdbFile
]
budeEnergyInfo : Html msg
budeEnergyInfo =
div
[ class [ OverlayPanelCss, FlexItemCss ]
, styles infoBoxStyling
]
[ h3 [] [ text "BUDE Energy" ]
, text mIBudeEnergyText
]
mIBudeEnergyText : String
mIBudeEnergyText =
"""The interaction energy between helices as calculated by the BUDE force field implemented in the BUFF module of ISAMBARD."""
rptInfo : Html msg
rptInfo =
div
[ class [ OverlayPanelCss, FlexItemCss ]
, styles infoBoxStyling
]
[ h3 [] [ text "Residues Per Turn" ]
, text mIRPTText
]
mIRPTText : String
mIRPTText =
"""Residues per turn of the alpha helix, can be used as a proxy for backbone strain."""
highlightKIHInfo : Html msg
highlightKIHInfo =
div
[ class [ OverlayPanelCss, FlexItemCss ]
, styles infoBoxStyling
]
[ h3 [] [ text "Highlight Knobs" ]
, text highlightKIHText
]
highlightKIHText : String
highlightKIHText =
"""Highlights knob residues red, all other residues are coloured blue."""
modelInfoGroupPanelStyling : List Css.Mixin
modelInfoGroupPanelStyling =
[ Css.bottom (Css.px 0)
, Css.left (Css.px 0)
]
infoBoxStyling : List Css.Mixin
infoBoxStyling =
[ Css.maxWidth (Css.pct 40)
, Css.maxHeight (Css.em 8)
, Css.lineHeight (Css.em 1)
]
roundToXDecPlaces : Int -> Float -> Float
roundToXDecPlaces precision num =
let
scaling =
10 ^ precision |> toFloat
in
round (num * scaling)
|> toFloat
|> flip (/) scaling
downloadStructureButton : Maybe String -> Html Msg
downloadStructureButton pdbFile =
let
deactivated =
if pdbFile == Nothing then
True
else
False
in
button
[ class [ CCBButtonCss ]
, onClick DownloadPdb
, disabled deactivated
]
[ text "Download PDB" ]
-- Build History
buildHistoryPanel : Dict.Dict Int HistoryEntry -> Bool -> Bool -> Html Msg
buildHistoryPanel modelHistory building visible =
div
[ class [ OverlayPanelCss ]
, id [ BuildHistoryPanel ]
, styles <| panelStyling ++ buildHistoryPanelStyling
, hidden <| not visible
]
[ h2 [] [ text "Build History" ]
, hr [] []
, table []
[ modelDetailTableHeader
, List.map2 modelParametersAsRow
(Dict.toList modelHistory |> List.reverse)
(List.repeat (List.length <| Dict.toList modelHistory) building)
|> List.concat
|> tbody []
]
]
modelDetailTableHeader : Html msg
modelDetailTableHeader =
thead []
[ tr []
[ th [] []
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Radius" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Pitch" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Interface Angle" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Super-Helical Rotation" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Z-Shift" ]
, th [] [ text "Sequence" ]
, th [ styles [ Css.width (Css.em 6) ] ] [ text "Register" ]
, th [] [ text "BUDE Score" ]
, th [] []
]
]
modelParametersAsRow : ( HistoryID, HistoryEntry ) -> Bool -> List (Html Msg)
modelParametersAsRow ( hID, ( parameters, visible, score, helixType, buildMode, _ ) ) building =
let
foldedRows =
Dict.values parameters
|> List.tail
|> Maybe.withDefault []
|> List.map (modelFoldedRow score)
in
if not visible then
[ modelHistoryTopRow hID parameters building visible score helixType buildMode ]
else
(modelHistoryTopRow hID parameters building visible score helixType buildMode)
:: foldedRows
modelHistoryTopRow :
HistoryID
-> ParametersDict
-> Bool
-> Bool
-> Float
-> HelixType
-> BuildMode
-> Html Msg
modelHistoryTopRow hID parameters building visible score helixType buildMode =
let
topRowParameters =
Dict.values parameters
|> List.head
|> Maybe.withDefault emptyParameterRecord
in
tr
[]
([ div
[ onClick (ExpandHistory hID) ]
[ if (not visible) then
text "▶"
else
text "▼"
]
]
++ List.map makeParameterTh
(parametersToRow topRowParameters score)
++ [ button
[ class [ CCBButtonCss ]
, onClick (SetParametersAndBuild parameters helixType buildMode)
, disabled building
]
[ text "Rebuild" ]
]
)
modelFoldedRow : Float -> ParameterRecord -> Html Msg
modelFoldedRow score parameters =
tr
[]
([ text " ┋"
]
++ List.map makeParameterTh
(parametersToRow parameters score)
)
parametersToRow : ParameterRecord -> Float -> List String
parametersToRow parameters score =
[ parameters.radius
|> Maybe.withDefault 0
|> roundToXDecPlaces 1
|> toString
, parameters.pitch
|> Maybe.withDefault 0
|> round
|> toString
, parameters.phiCA
|> Maybe.withDefault 0
|> roundToXDecPlaces 1
|> toString
, parameters.superHelRot
|> Maybe.withDefault 0
|> roundToXDecPlaces 1
|> toString
, parameters.zShift
|> Maybe.withDefault 0
|> roundToXDecPlaces 1
|> toString
, parameters.sequence |> Maybe.withDefault ""
, parameters.register
, toString <| roundToXDecPlaces 2 score
]
makeParameterTh : String -> Html Msg
makeParameterTh pString =
text pString
|> List.singleton
|> th []
buildHistoryPanelStyling : List Css.Mixin
buildHistoryPanelStyling =
[ Css.top (Css.px 60)
, Css.right (Css.px 35)
]
toggleBuildHistoryPanel : Html Msg
toggleBuildHistoryPanel =
div
[ class [ OverlayPanelCss, RightPanelToggleCss ]
, onClick (TogglePanel BuildHistoryPanel)
]
[ text "Build History" ]
-- Viewer Panel
viewerPanel : Bool -> Html Msg
viewerPanel visible =
div
[ class [ OverlayPanelCss ]
, id [ ViewerPanel ]
, styles <| panelStyling ++ viewerPanelStyling
, hidden <| not visible
]
[ h2 [] [ text "Viewer Options" ]
, hr [] []
, h3 [] [ text "Representation" ]
, hr [] []
, text "Backbone"
, br [] []
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation Cartoon)
]
[ text "Cartoon" ]
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation Trace)
]
[ text "Trace" ]
, br [] []
, text "All Atoms"
, br [] []
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation BallsAndSticks)
]
[ text "Balls and Sticks" ]
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation Spheres)
]
[ text "Spheres" ]
, button
[ class [ CCBButtonCss ]
, onClick (EditRepresentation Points)
]
[ text "Dots" ]
, hr [] []
, h3 [] [ text "Other Options" ]
, hr [] []
, button
[ class [ CCBButtonCss ]
, onClick ShowAxes
]
[ text "Axes" ]
, text " (xyz = rgb)"
]
viewerPanelStyling : List Css.Mixin
viewerPanelStyling =
[ Css.top (Css.px 60)
, Css.right (Css.px 35)
]
toggleViewerPanel : Html Msg
toggleViewerPanel =
div
[ class [ OverlayPanelCss, RightPanelToggleCss ]
, onClick (TogglePanel ViewerPanel)
]
[ text "Viewer" ]
-- Info Box
infoText : InfoBoxID -> String -> Html Msg
infoText infoBoxID contentText =
div
[ onMouseEnter (ShowInfo infoBoxID)
, onMouseLeave (CloseInfo infoBoxID)
]
[ text contentText ]
-- Building Status
buildingStatusPanel : Bool -> Html msg
buildingStatusPanel building =
div
[ class [ OverlayPanelCss ]
, id [ BuildingStatusPanel ]
, styles <| buildingStatusStyling ++ panelStyling
, hidden (not building)
]
[ text "Building"
, img [ src "static/css/infinity.gif", width 80, height 80 ] []
]
buildingStatusStyling : List Css.Mixin
buildingStatusStyling =
[ Css.top (Css.pct 50)
, Css.left (Css.pct 50)
, Css.width (Css.px 80)
, Css.height (Css.px 80)
]
-- Optimisation Job
optJobStatus : ( String, OptStatus ) -> Int -> Html Msg
optJobStatus ( optID, status ) position =
div
[ class [ OverlayPanelCss ]
, styles <| optJobStatusStyling position ++ panelStyling
]
([ text "Optimising"
, br [] []
, text ("(" ++ (toString status) ++ ")")
]
++ (case status of
Complete ->
[ button
[ onClick (RetrieveOptimisation optID) ]
[ text "Retrieve" ]
]
Failed ->
[ button
[ onClick (ClearOptimisation optID) ]
[ text "Clear" ]
]
_ ->
[ img
[ src "static/css/infinity.gif", width 80, height 80 ]
[]
]
)
)
optJobStatusStyling : Int -> List Css.Mixin
optJobStatusStyling position =
[ Css.textAlign Css.center
, Css.bottom (Css.px 20)
, Css.right (Css.px 35)
, Css.width (Css.px 90)
]
-- About Panel
aboutPanel : Bool -> Html Msg
aboutPanel visible =
div
[ class [ OverlayPanelCss ]
, styles <| panelStyling ++ aboutPanelStyling
, hidden <| not visible
]
[ h2 [] [ text "About (Ver 2.0.4)" ]
, hr [] []
, Markdown.toHtml [] aboutText
]
aboutText : String
aboutText =
"""CCBuilder is developed and maintained by the [Woolfson Group, University
of Bristol](http://www.chm.bris.ac.uk/org/woolfson/). The project is open
source with code available on
[GitHub](https://github.com/woolfson-group/ccbuilder2). If you
encounter any bugs or have ideas for enhancements to CCBuilder 2.0, please
either create an issue on GitHub or contact PI:EMAIL:<EMAIL>END_PI.
### Citation
[Wood CW and Woolfson DN (2017) CCBuilder 2.0: Powerful and accessible
coiled-coil modelling,
_Protein Science_. doi: 10.1002/pro.3279](http://dx.doi.org/10.1002/pro.3279)
### Useful References
[Wood CW _et al_ (2017) ISAMBARD: an open-source computational environment
for biomolecular analysis, modelling and design, Bioinformatics.
doi: 10.1093/bioinformatics/btx352](
https://doi.org/10.1093/bioinformatics/btx352)
"""
aboutPanelStyling : List Css.Mixin
aboutPanelStyling =
[ Css.bottom (Css.px 20)
, Css.right (Css.px 35)
, Css.maxWidth (Css.pct 40)
]
toggleAboutPanel : Html Msg
toggleAboutPanel =
div
[ class [ OverlayPanelCss, RightPanelToggleCss ]
, onClick (TogglePanel AboutPanel)
]
[ text "About" ]
| elm |
[
{
"context": "\n\n-- PROPERTIES\n-- 📟\n\n\ndefaults =\n { appKey = \"kwsydtrzban41zr\"\n , name = \"Music from Dropbox\"\n }\n\n\n{-| Th",
"end": 706,
"score": 0.9996817112,
"start": 691,
"tag": "KEY",
"value": "kwsydtrzban41zr"
},
{
"context": "nal)\"\n , placeholder = \"/\"\n , password = False\n }\n , { key = \"appKey\"\n , label = \"A",
"end": 1042,
"score": 0.9977588058,
"start": 1037,
"tag": "PASSWORD",
"value": "False"
},
{
"context": ", placeholder = defaults.appKey\n , password = False\n }\n ]\n\n\n{-| Initial data set.\n-}\ninitialD",
"end": 1162,
"score": 0.9975713491,
"start": 1157,
"tag": "PASSWORD",
"value": "False"
}
] | src/Library/Sources/Services/Dropbox.elm | Borewit/diffuse | 1 | module Sources.Services.Dropbox exposing (authorizationSourceData, authorizationUrl, defaults, getProperDirectoryPath, initialData, makeTrackUrl, makeTree, parseErrorResponse, parsePreparationResponse, parseTreeResponse, postProcessTree, prepare, properties)
{-| Dropbox Service.
-}
import Base64
import Common
import Dict
import Dict.Ext as Dict
import Http
import Json.Decode
import Json.Encode
import Regex
import Sources exposing (Property, SourceData)
import Sources.Pick
import Sources.Processing exposing (..)
import Sources.Services.Common exposing (cleanPath, noPrep)
import Sources.Services.Dropbox.Parser as Parser
import Time
-- PROPERTIES
-- 📟
defaults =
{ appKey = "kwsydtrzban41zr"
, name = "Music from Dropbox"
}
{-| The list of properties we need from the user.
Tuple: (property, label, placeholder, isPassword)
Will be used for the forms.
-}
properties : List Property
properties =
[ { key = "directoryPath"
, label = "Directory (Optional)"
, placeholder = "/"
, password = False
}
, { key = "appKey"
, label = "App key"
, placeholder = defaults.appKey
, password = False
}
]
{-| Initial data set.
-}
initialData : SourceData
initialData =
Dict.fromList
[ ( "appKey", defaults.appKey )
, ( "directoryPath", "" )
, ( "name", defaults.name )
]
-- AUTHORIZATION
{-| Authorization url.
-}
authorizationUrl : SourceData -> String -> String
authorizationUrl sourceData origin =
let
encodeData data =
data
|> Dict.toList
|> List.map (Tuple.mapSecond Json.Encode.string)
|> Json.Encode.object
state =
sourceData
|> encodeData
|> Json.Encode.encode 0
|> Base64.encode
in
[ ( "response_type", "token" )
, ( "client_id", Dict.fetch "appKey" "unknown" sourceData )
, ( "redirect_uri", origin ++ "?path=sources/new/dropbox" )
, ( "state", state )
]
|> Common.queryString
|> String.append "https://www.dropbox.com/oauth2/authorize"
{-| Authorization source data.
-}
authorizationSourceData : { codeOrToken : Maybe String, state : Maybe String } -> SourceData
authorizationSourceData args =
args.state
|> Maybe.andThen (Base64.decode >> Result.toMaybe)
|> Maybe.withDefault "{}"
|> Json.Decode.decodeString (Json.Decode.dict Json.Decode.string)
|> Result.withDefault Dict.empty
|> Dict.unionFlipped initialData
|> Dict.update "accessToken" (\_ -> args.codeOrToken)
-- PREPARATION
prepare : String -> SourceData -> Marker -> (Result Http.Error String -> msg) -> Maybe (Cmd msg)
prepare _ _ _ _ =
Nothing
-- TREE
{-| Create a directory tree.
List all the tracks in the bucket.
Or a specific directory in the bucket.
-}
makeTree : SourceData -> Marker -> Time.Posix -> (Result Http.Error String -> msg) -> Cmd msg
makeTree srcData marker currentTime resultMsg =
let
accessToken =
Dict.fetch "accessToken" "" srcData
body =
(case marker of
TheBeginning ->
[ ( "limit", Json.Encode.int 2000 )
, ( "path", Json.Encode.string (getProperDirectoryPath srcData) )
, ( "recursive", Json.Encode.bool True )
]
InProgress cursor ->
[ ( "cursor", Json.Encode.string cursor )
]
TheEnd ->
[]
)
|> Json.Encode.object
|> Http.jsonBody
url =
case marker of
TheBeginning ->
"https://api.dropboxapi.com/2/files/list_folder"
InProgress _ ->
"https://api.dropboxapi.com/2/files/list_folder/continue"
TheEnd ->
""
in
Http.request
{ method = "POST"
, headers = [ Http.header "Authorization" ("Bearer " ++ accessToken) ]
, url = url
, body = body
, expect = Http.expectStringResponse resultMsg Common.translateHttpResponse
, timeout = Nothing
, tracker = Nothing
}
getProperDirectoryPath : SourceData -> String
getProperDirectoryPath srcData =
let
path =
srcData
|> Dict.get "directoryPath"
|> Maybe.withDefault ""
|> cleanPath
in
if path == "" then
""
else
"/" ++ path
{-| Re-export parser functions.
-}
parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker
parsePreparationResponse =
noPrep
parseTreeResponse : String -> Marker -> TreeAnswer Marker
parseTreeResponse =
Parser.parseTreeResponse
parseErrorResponse : String -> Maybe String
parseErrorResponse =
Parser.parseErrorResponse
-- POST
{-| Post process the tree results.
!!! Make sure we only use music files that we can use.
-}
postProcessTree : List String -> List String
postProcessTree =
Sources.Pick.selectMusicFiles
-- TRACK URL
{-| Create a public url for a file.
We need this to play the track.
-}
makeTrackUrl : Time.Posix -> SourceData -> HttpMethod -> String -> String
makeTrackUrl currentTime srcData method pathToFile =
"dropbox://" ++ Dict.fetch "accessToken" "" srcData ++ "@" ++ pathToFile
| 45013 | module Sources.Services.Dropbox exposing (authorizationSourceData, authorizationUrl, defaults, getProperDirectoryPath, initialData, makeTrackUrl, makeTree, parseErrorResponse, parsePreparationResponse, parseTreeResponse, postProcessTree, prepare, properties)
{-| Dropbox Service.
-}
import Base64
import Common
import Dict
import Dict.Ext as Dict
import Http
import Json.Decode
import Json.Encode
import Regex
import Sources exposing (Property, SourceData)
import Sources.Pick
import Sources.Processing exposing (..)
import Sources.Services.Common exposing (cleanPath, noPrep)
import Sources.Services.Dropbox.Parser as Parser
import Time
-- PROPERTIES
-- 📟
defaults =
{ appKey = "<KEY>"
, name = "Music from Dropbox"
}
{-| The list of properties we need from the user.
Tuple: (property, label, placeholder, isPassword)
Will be used for the forms.
-}
properties : List Property
properties =
[ { key = "directoryPath"
, label = "Directory (Optional)"
, placeholder = "/"
, password = <PASSWORD>
}
, { key = "appKey"
, label = "App key"
, placeholder = defaults.appKey
, password = <PASSWORD>
}
]
{-| Initial data set.
-}
initialData : SourceData
initialData =
Dict.fromList
[ ( "appKey", defaults.appKey )
, ( "directoryPath", "" )
, ( "name", defaults.name )
]
-- AUTHORIZATION
{-| Authorization url.
-}
authorizationUrl : SourceData -> String -> String
authorizationUrl sourceData origin =
let
encodeData data =
data
|> Dict.toList
|> List.map (Tuple.mapSecond Json.Encode.string)
|> Json.Encode.object
state =
sourceData
|> encodeData
|> Json.Encode.encode 0
|> Base64.encode
in
[ ( "response_type", "token" )
, ( "client_id", Dict.fetch "appKey" "unknown" sourceData )
, ( "redirect_uri", origin ++ "?path=sources/new/dropbox" )
, ( "state", state )
]
|> Common.queryString
|> String.append "https://www.dropbox.com/oauth2/authorize"
{-| Authorization source data.
-}
authorizationSourceData : { codeOrToken : Maybe String, state : Maybe String } -> SourceData
authorizationSourceData args =
args.state
|> Maybe.andThen (Base64.decode >> Result.toMaybe)
|> Maybe.withDefault "{}"
|> Json.Decode.decodeString (Json.Decode.dict Json.Decode.string)
|> Result.withDefault Dict.empty
|> Dict.unionFlipped initialData
|> Dict.update "accessToken" (\_ -> args.codeOrToken)
-- PREPARATION
prepare : String -> SourceData -> Marker -> (Result Http.Error String -> msg) -> Maybe (Cmd msg)
prepare _ _ _ _ =
Nothing
-- TREE
{-| Create a directory tree.
List all the tracks in the bucket.
Or a specific directory in the bucket.
-}
makeTree : SourceData -> Marker -> Time.Posix -> (Result Http.Error String -> msg) -> Cmd msg
makeTree srcData marker currentTime resultMsg =
let
accessToken =
Dict.fetch "accessToken" "" srcData
body =
(case marker of
TheBeginning ->
[ ( "limit", Json.Encode.int 2000 )
, ( "path", Json.Encode.string (getProperDirectoryPath srcData) )
, ( "recursive", Json.Encode.bool True )
]
InProgress cursor ->
[ ( "cursor", Json.Encode.string cursor )
]
TheEnd ->
[]
)
|> Json.Encode.object
|> Http.jsonBody
url =
case marker of
TheBeginning ->
"https://api.dropboxapi.com/2/files/list_folder"
InProgress _ ->
"https://api.dropboxapi.com/2/files/list_folder/continue"
TheEnd ->
""
in
Http.request
{ method = "POST"
, headers = [ Http.header "Authorization" ("Bearer " ++ accessToken) ]
, url = url
, body = body
, expect = Http.expectStringResponse resultMsg Common.translateHttpResponse
, timeout = Nothing
, tracker = Nothing
}
getProperDirectoryPath : SourceData -> String
getProperDirectoryPath srcData =
let
path =
srcData
|> Dict.get "directoryPath"
|> Maybe.withDefault ""
|> cleanPath
in
if path == "" then
""
else
"/" ++ path
{-| Re-export parser functions.
-}
parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker
parsePreparationResponse =
noPrep
parseTreeResponse : String -> Marker -> TreeAnswer Marker
parseTreeResponse =
Parser.parseTreeResponse
parseErrorResponse : String -> Maybe String
parseErrorResponse =
Parser.parseErrorResponse
-- POST
{-| Post process the tree results.
!!! Make sure we only use music files that we can use.
-}
postProcessTree : List String -> List String
postProcessTree =
Sources.Pick.selectMusicFiles
-- TRACK URL
{-| Create a public url for a file.
We need this to play the track.
-}
makeTrackUrl : Time.Posix -> SourceData -> HttpMethod -> String -> String
makeTrackUrl currentTime srcData method pathToFile =
"dropbox://" ++ Dict.fetch "accessToken" "" srcData ++ "@" ++ pathToFile
| true | module Sources.Services.Dropbox exposing (authorizationSourceData, authorizationUrl, defaults, getProperDirectoryPath, initialData, makeTrackUrl, makeTree, parseErrorResponse, parsePreparationResponse, parseTreeResponse, postProcessTree, prepare, properties)
{-| Dropbox Service.
-}
import Base64
import Common
import Dict
import Dict.Ext as Dict
import Http
import Json.Decode
import Json.Encode
import Regex
import Sources exposing (Property, SourceData)
import Sources.Pick
import Sources.Processing exposing (..)
import Sources.Services.Common exposing (cleanPath, noPrep)
import Sources.Services.Dropbox.Parser as Parser
import Time
-- PROPERTIES
-- 📟
defaults =
{ appKey = "PI:KEY:<KEY>END_PI"
, name = "Music from Dropbox"
}
{-| The list of properties we need from the user.
Tuple: (property, label, placeholder, isPassword)
Will be used for the forms.
-}
properties : List Property
properties =
[ { key = "directoryPath"
, label = "Directory (Optional)"
, placeholder = "/"
, password = PI:PASSWORD:<PASSWORD>END_PI
}
, { key = "appKey"
, label = "App key"
, placeholder = defaults.appKey
, password = PI:PASSWORD:<PASSWORD>END_PI
}
]
{-| Initial data set.
-}
initialData : SourceData
initialData =
Dict.fromList
[ ( "appKey", defaults.appKey )
, ( "directoryPath", "" )
, ( "name", defaults.name )
]
-- AUTHORIZATION
{-| Authorization url.
-}
authorizationUrl : SourceData -> String -> String
authorizationUrl sourceData origin =
let
encodeData data =
data
|> Dict.toList
|> List.map (Tuple.mapSecond Json.Encode.string)
|> Json.Encode.object
state =
sourceData
|> encodeData
|> Json.Encode.encode 0
|> Base64.encode
in
[ ( "response_type", "token" )
, ( "client_id", Dict.fetch "appKey" "unknown" sourceData )
, ( "redirect_uri", origin ++ "?path=sources/new/dropbox" )
, ( "state", state )
]
|> Common.queryString
|> String.append "https://www.dropbox.com/oauth2/authorize"
{-| Authorization source data.
-}
authorizationSourceData : { codeOrToken : Maybe String, state : Maybe String } -> SourceData
authorizationSourceData args =
args.state
|> Maybe.andThen (Base64.decode >> Result.toMaybe)
|> Maybe.withDefault "{}"
|> Json.Decode.decodeString (Json.Decode.dict Json.Decode.string)
|> Result.withDefault Dict.empty
|> Dict.unionFlipped initialData
|> Dict.update "accessToken" (\_ -> args.codeOrToken)
-- PREPARATION
prepare : String -> SourceData -> Marker -> (Result Http.Error String -> msg) -> Maybe (Cmd msg)
prepare _ _ _ _ =
Nothing
-- TREE
{-| Create a directory tree.
List all the tracks in the bucket.
Or a specific directory in the bucket.
-}
makeTree : SourceData -> Marker -> Time.Posix -> (Result Http.Error String -> msg) -> Cmd msg
makeTree srcData marker currentTime resultMsg =
let
accessToken =
Dict.fetch "accessToken" "" srcData
body =
(case marker of
TheBeginning ->
[ ( "limit", Json.Encode.int 2000 )
, ( "path", Json.Encode.string (getProperDirectoryPath srcData) )
, ( "recursive", Json.Encode.bool True )
]
InProgress cursor ->
[ ( "cursor", Json.Encode.string cursor )
]
TheEnd ->
[]
)
|> Json.Encode.object
|> Http.jsonBody
url =
case marker of
TheBeginning ->
"https://api.dropboxapi.com/2/files/list_folder"
InProgress _ ->
"https://api.dropboxapi.com/2/files/list_folder/continue"
TheEnd ->
""
in
Http.request
{ method = "POST"
, headers = [ Http.header "Authorization" ("Bearer " ++ accessToken) ]
, url = url
, body = body
, expect = Http.expectStringResponse resultMsg Common.translateHttpResponse
, timeout = Nothing
, tracker = Nothing
}
getProperDirectoryPath : SourceData -> String
getProperDirectoryPath srcData =
let
path =
srcData
|> Dict.get "directoryPath"
|> Maybe.withDefault ""
|> cleanPath
in
if path == "" then
""
else
"/" ++ path
{-| Re-export parser functions.
-}
parsePreparationResponse : String -> SourceData -> Marker -> PrepationAnswer Marker
parsePreparationResponse =
noPrep
parseTreeResponse : String -> Marker -> TreeAnswer Marker
parseTreeResponse =
Parser.parseTreeResponse
parseErrorResponse : String -> Maybe String
parseErrorResponse =
Parser.parseErrorResponse
-- POST
{-| Post process the tree results.
!!! Make sure we only use music files that we can use.
-}
postProcessTree : List String -> List String
postProcessTree =
Sources.Pick.selectMusicFiles
-- TRACK URL
{-| Create a public url for a file.
We need this to play the track.
-}
makeTrackUrl : Time.Posix -> SourceData -> HttpMethod -> String -> String
makeTrackUrl currentTime srcData method pathToFile =
"dropbox://" ++ Dict.fetch "accessToken" "" srcData ++ "@" ++ pathToFile
| elm |
[
{
"context": "div [ class \"container\" ] [ text \"© 2017 Copyright simplegtd.com\" ] ]\n ]\n\n\nlearnMoreLinks =\n let\n ",
"end": 3597,
"score": 0.8523012996,
"start": 3584,
"tag": "EMAIL",
"value": "simplegtd.com"
}
] | src/elm/Views/Landing.elm | jigargosar/elm-simple-gtd | 24 | module Views.Landing exposing (..)
import AppUrl
import Html exposing (..)
import Html.Attributes exposing (..)
import Mat
import Toolkit.Operators exposing (..)
view =
div [ id "landing" ]
[ navHeader
, banner
, overview
, footerView
]
navHeader =
div [ class "navbar-fixed" ]
[ nav []
[ div [ class "nav-wrapper container" ]
[ a [ class "brand-logo", href AppUrl.landing ]
[ div [ class "logo-font-icon" ] [ div [ class "logo-content" ] [ text "SG" ] ]
, div [ class "app-name" ]
[ span [ class "brand-name-font" ] [ text "S" ]
, text "imple"
, span [ class "brand-name-font" ] [ text "GTD" ]
]
]
, div [ class "right hide-on-med-and-down" ]
[ a [ class "btn primary-action", href AppUrl.getStarted ]
[ text "Get Started" ]
]
]
]
]
banner =
div [ class "banner" ]
[ div [ class "container" ]
[ div [ class "row" ]
[ div [ class "col s12 m6" ]
[ h3 [] [ text "Simply Get To Done" ]
, h5 [] [ text "Achieve more, with mind like water" ]
, a [ class "btn primary-action", href AppUrl.getStarted ] [ text "Get Started - It's Free" ]
, p [ class "" ] [ text "No sign up required!" ]
]
]
]
]
bannerMock =
img [ src "https://d3ptyyxy2at9ui.cloudfront.net/bc51cd8ccfb3787ee54ad263924a1a0a.jpg", class "responsive-img" ] []
overview =
div [ class "container overview center" ]
[ primaryFeatures
]
primaryFeatures =
let
descriptionLine desc =
p [] [ text desc ]
feature ( iconName, heading, desc ) =
div [ class "feature col s12 m4 center-align" ]
[ div [ class "section" ]
[ Mat.icon iconName
, h5 [] [ text heading ]
, div [] (desc .|> descriptionLine)
]
]
seamlessly =
""
list =
[ ( "palette"
, "Minimalistic Design"
, [ "Focus on doing with our simple & beautiful interface"
, "Less is more, that's our philosophy"
]
)
, ( "sync"
, "Work seamlessly"
, [ "We will sync automatically when you get online"
, "Additionally you never have to worry about upgrading, it just happens automatically"
]
)
, ( "nature_people"
, "Free and Open Source"
, [ "And we are proud of it"
, "You can contribute, tinker, learn, host yourself, sky is the limit"
, "No more worries about propriety software"
]
)
]
in
div [ class "row features primary" ]
(list .|> feature)
footerView =
footer [ class "page-footer" ]
[ div [ class "container footer" ]
[ div [ class "row" ]
[ div [ class "col s12" ]
[ learnMoreLinks
]
]
]
, div
[ class "footer-copyright" ]
[ div [ class "container" ] [ text "© 2017 Copyright simplegtd.com" ] ]
]
learnMoreLinks =
let
linkV ( hrefV, textV ) =
li [] [ a [ class "white-text", href hrefV, target "_blank" ] [ text textV ] ]
in
ul [ class "layout horizontal center-center wrap" ]
[ linkV ( AppUrl.github, "Github" )
, linkV ( AppUrl.forumsURL, "Forums" )
, linkV ( AppUrl.newIssueURL, "Report Issue" )
, linkV ( AppUrl.changeLogURL, "Change Log" )
, linkV ( AppUrl.contact, "Contact us" )
]
| 18027 | module Views.Landing exposing (..)
import AppUrl
import Html exposing (..)
import Html.Attributes exposing (..)
import Mat
import Toolkit.Operators exposing (..)
view =
div [ id "landing" ]
[ navHeader
, banner
, overview
, footerView
]
navHeader =
div [ class "navbar-fixed" ]
[ nav []
[ div [ class "nav-wrapper container" ]
[ a [ class "brand-logo", href AppUrl.landing ]
[ div [ class "logo-font-icon" ] [ div [ class "logo-content" ] [ text "SG" ] ]
, div [ class "app-name" ]
[ span [ class "brand-name-font" ] [ text "S" ]
, text "imple"
, span [ class "brand-name-font" ] [ text "GTD" ]
]
]
, div [ class "right hide-on-med-and-down" ]
[ a [ class "btn primary-action", href AppUrl.getStarted ]
[ text "Get Started" ]
]
]
]
]
banner =
div [ class "banner" ]
[ div [ class "container" ]
[ div [ class "row" ]
[ div [ class "col s12 m6" ]
[ h3 [] [ text "Simply Get To Done" ]
, h5 [] [ text "Achieve more, with mind like water" ]
, a [ class "btn primary-action", href AppUrl.getStarted ] [ text "Get Started - It's Free" ]
, p [ class "" ] [ text "No sign up required!" ]
]
]
]
]
bannerMock =
img [ src "https://d3ptyyxy2at9ui.cloudfront.net/bc51cd8ccfb3787ee54ad263924a1a0a.jpg", class "responsive-img" ] []
overview =
div [ class "container overview center" ]
[ primaryFeatures
]
primaryFeatures =
let
descriptionLine desc =
p [] [ text desc ]
feature ( iconName, heading, desc ) =
div [ class "feature col s12 m4 center-align" ]
[ div [ class "section" ]
[ Mat.icon iconName
, h5 [] [ text heading ]
, div [] (desc .|> descriptionLine)
]
]
seamlessly =
""
list =
[ ( "palette"
, "Minimalistic Design"
, [ "Focus on doing with our simple & beautiful interface"
, "Less is more, that's our philosophy"
]
)
, ( "sync"
, "Work seamlessly"
, [ "We will sync automatically when you get online"
, "Additionally you never have to worry about upgrading, it just happens automatically"
]
)
, ( "nature_people"
, "Free and Open Source"
, [ "And we are proud of it"
, "You can contribute, tinker, learn, host yourself, sky is the limit"
, "No more worries about propriety software"
]
)
]
in
div [ class "row features primary" ]
(list .|> feature)
footerView =
footer [ class "page-footer" ]
[ div [ class "container footer" ]
[ div [ class "row" ]
[ div [ class "col s12" ]
[ learnMoreLinks
]
]
]
, div
[ class "footer-copyright" ]
[ div [ class "container" ] [ text "© 2017 Copyright <EMAIL>" ] ]
]
learnMoreLinks =
let
linkV ( hrefV, textV ) =
li [] [ a [ class "white-text", href hrefV, target "_blank" ] [ text textV ] ]
in
ul [ class "layout horizontal center-center wrap" ]
[ linkV ( AppUrl.github, "Github" )
, linkV ( AppUrl.forumsURL, "Forums" )
, linkV ( AppUrl.newIssueURL, "Report Issue" )
, linkV ( AppUrl.changeLogURL, "Change Log" )
, linkV ( AppUrl.contact, "Contact us" )
]
| true | module Views.Landing exposing (..)
import AppUrl
import Html exposing (..)
import Html.Attributes exposing (..)
import Mat
import Toolkit.Operators exposing (..)
view =
div [ id "landing" ]
[ navHeader
, banner
, overview
, footerView
]
navHeader =
div [ class "navbar-fixed" ]
[ nav []
[ div [ class "nav-wrapper container" ]
[ a [ class "brand-logo", href AppUrl.landing ]
[ div [ class "logo-font-icon" ] [ div [ class "logo-content" ] [ text "SG" ] ]
, div [ class "app-name" ]
[ span [ class "brand-name-font" ] [ text "S" ]
, text "imple"
, span [ class "brand-name-font" ] [ text "GTD" ]
]
]
, div [ class "right hide-on-med-and-down" ]
[ a [ class "btn primary-action", href AppUrl.getStarted ]
[ text "Get Started" ]
]
]
]
]
banner =
div [ class "banner" ]
[ div [ class "container" ]
[ div [ class "row" ]
[ div [ class "col s12 m6" ]
[ h3 [] [ text "Simply Get To Done" ]
, h5 [] [ text "Achieve more, with mind like water" ]
, a [ class "btn primary-action", href AppUrl.getStarted ] [ text "Get Started - It's Free" ]
, p [ class "" ] [ text "No sign up required!" ]
]
]
]
]
bannerMock =
img [ src "https://d3ptyyxy2at9ui.cloudfront.net/bc51cd8ccfb3787ee54ad263924a1a0a.jpg", class "responsive-img" ] []
overview =
div [ class "container overview center" ]
[ primaryFeatures
]
primaryFeatures =
let
descriptionLine desc =
p [] [ text desc ]
feature ( iconName, heading, desc ) =
div [ class "feature col s12 m4 center-align" ]
[ div [ class "section" ]
[ Mat.icon iconName
, h5 [] [ text heading ]
, div [] (desc .|> descriptionLine)
]
]
seamlessly =
""
list =
[ ( "palette"
, "Minimalistic Design"
, [ "Focus on doing with our simple & beautiful interface"
, "Less is more, that's our philosophy"
]
)
, ( "sync"
, "Work seamlessly"
, [ "We will sync automatically when you get online"
, "Additionally you never have to worry about upgrading, it just happens automatically"
]
)
, ( "nature_people"
, "Free and Open Source"
, [ "And we are proud of it"
, "You can contribute, tinker, learn, host yourself, sky is the limit"
, "No more worries about propriety software"
]
)
]
in
div [ class "row features primary" ]
(list .|> feature)
footerView =
footer [ class "page-footer" ]
[ div [ class "container footer" ]
[ div [ class "row" ]
[ div [ class "col s12" ]
[ learnMoreLinks
]
]
]
, div
[ class "footer-copyright" ]
[ div [ class "container" ] [ text "© 2017 Copyright PI:EMAIL:<EMAIL>END_PI" ] ]
]
learnMoreLinks =
let
linkV ( hrefV, textV ) =
li [] [ a [ class "white-text", href hrefV, target "_blank" ] [ text textV ] ]
in
ul [ class "layout horizontal center-center wrap" ]
[ linkV ( AppUrl.github, "Github" )
, linkV ( AppUrl.forumsURL, "Forums" )
, linkV ( AppUrl.newIssueURL, "Report Issue" )
, linkV ( AppUrl.changeLogURL, "Change Log" )
, linkV ( AppUrl.contact, "Contact us" )
]
| elm |
[
{
"context": "string encryption functions.\n-- Copyright (c) 2017 Bill St. Clair <billstclair@gmail.com>\n-- Some rights reserved.\n",
"end": 171,
"score": 0.9998723865,
"start": 157,
"tag": "NAME",
"value": "Bill St. Clair"
},
{
"context": " functions.\n-- Copyright (c) 2017 Bill St. Clair <billstclair@gmail.com>\n-- Some rights reserved.\n-- Distributed under th",
"end": 194,
"score": 0.9999339581,
"start": 173,
"tag": "EMAIL",
"value": "billstclair@gmail.com"
}
] | src/Crypto/Strings/Crypt.elm | billstclair/elm-crypto-strings | 10 | ----------------------------------------------------------------------
--
-- Crypt.elm
-- General purpose string encryption functions.
-- Copyright (c) 2017 Bill St. Clair <billstclair@gmail.com>
-- Some rights reserved.
-- Distributed under the MIT License
-- See LICENSE.txt
--
----------------------------------------------------------------------
module Crypto.Strings.Crypt exposing
( DefaultKey
, expandKeyString, defaultConfig, encrypt, decrypt, seedGenerator
, listToBlocks, blocksToList
, padLastBlock, unpadLastBlock, stripTrailingZeroes
)
{-| Block chaining and string encryption for use with any block cipher.
# Types
@docs DefaultKey
# Functions
@docs expandKeyString, defaultConfig, encrypt, decrypt, seedGenerator
# Low-level functions
@docs listToBlocks, blocksToList
@docs padLastBlock, unpadLastBlock, stripTrailingZeroes
-}
import Array exposing (Array)
import Crypto.Strings.BlockAes as Aes
import Crypto.Strings.Chaining as Chaining
import Crypto.Strings.Encoding as Encoding
import Crypto.Strings.Types
exposing
( Block
, BlockSize
, Ciphertext
, Config
, Decryptor
, Encoding
, Encryptor
, Key(..)
, KeyEncoding
, KeyExpander
, Passphrase
, Plaintext
, RandomGenerator
)
import List.Extra as LE
import Random
processKey : Config key state randomState -> String -> Result String key
processKey config string =
let
expander =
config.encryption.keyExpander
keyEncoder =
config.keyEncoding.encoder
in
keyEncoder expander.keySize string
|> expander.expander
defaultEncoding =
Encoding.base64Encoding 60
{-| Default key type.
-}
type alias DefaultKey =
Key Aes.Key
{-| Default configuration.
-}
defaultConfig : Config Aes.Key Chaining.CtrState randomState
defaultConfig =
{ keyEncoding = Encoding.foldedSha256KeyEncoding
, encryption = Aes.encryption
, chaining = Chaining.ctrChaining
, encoding = defaultEncoding
}
{-| Expand a key preparing it for use with `encrypt` or `decrypt`.
-}
expandKeyString : Config key state randomState -> Passphrase -> Result String (Key key)
expandKeyString config passphrase =
case processKey config passphrase of
Err msg ->
Err msg
Ok key ->
Ok <| Key key
{-| A random generator that takes and returns a standard Elm Seed.
-}
seedGenerator : Random.Seed -> RandomGenerator Random.Seed
seedGenerator seed blockSize =
let
gen =
Random.list blockSize <| Random.int 0 255
( list, sd ) =
Random.step gen seed
in
( Array.fromList list, sd )
{-| Encrypt a list of blocks.
-}
encryptList : Config key state randomState -> RandomGenerator randomState -> Key key -> List Int -> ( List Int, randomState )
encryptList config generator (Key key) list =
let
chaining =
config.chaining
encryption =
config.encryption
chainer =
chaining.encryptor
pair =
( encryption.encryptor, encryption.decryptor )
( state, randomState ) =
chaining.initializer generator encryption.blockSize
step : Block -> ( List Block, state ) -> ( List Block, state )
step =
\block ( blocks, state_ ) ->
let
( outBlock, outState ) =
chainer state_ pair key block
in
( outBlock :: blocks, outState )
( cipherBlocks, finalState ) =
listToBlocks encryption.blockSize list
|> List.foldl step ( [], state )
in
( List.reverse cipherBlocks
|> blocksToList
|> chaining.adjoiner finalState
, randomState
)
{-| Encrypt a string.
-}
encrypt : Config key state randomState -> RandomGenerator randomState -> Key key -> Plaintext -> ( Ciphertext, randomState )
encrypt config generator key plaintext =
Encoding.plainTextEncoder plaintext
|> encryptList config generator key
|> (\( cipherList, randomState ) ->
( config.encoding.encoder cipherList
, randomState
)
)
extendArray : Int -> a -> Array a -> Array a
extendArray size fill array =
let
count =
size - Array.length array
in
if count <= 0 then
array
else
Array.append array <| Array.repeat count fill
marker : Int
marker =
0x80
padLastBlockLoop : Int -> List Block -> List Block -> List Block
padLastBlockLoop blockSize =
\blocks res ->
case blocks of
[] ->
[]
[ blk ] ->
let
block =
stripTrailingZeroes blk
len =
Array.length block
last =
Maybe.withDefault 0 <|
Array.get (len - 1) block
( b, bs, ln ) =
if len == blockSize && (last == 0 || last == marker) then
( Array.fromList [ marker ]
, [ block ]
, 1
)
else if len < blockSize then
( Array.push marker block
, []
, len + 1
)
else
( block
, []
, len
)
b2 =
if ln < blockSize then
Array.append b <|
Array.repeat (blockSize - ln) 0
else
b
in
(b2 :: List.append bs res)
|> List.reverse
head :: tail ->
padLastBlockLoop blockSize tail <| head :: res
{-| Put a 0x80 at the end of the last block, and pad with zeroes.
No padding is done if the last block is of the blockSize, and does NOT already end with 0 or 0x80.
-}
padLastBlock : Int -> List Block -> List Block
padLastBlock blockSize blocks =
padLastBlockLoop blockSize blocks []
unpadLastBlockLoop : List Block -> List Block -> List Block
unpadLastBlockLoop =
\blocks res ->
case blocks of
[] ->
[]
[ blk ] ->
let
block =
stripTrailingZeroes blk
len =
Array.length block
last =
Maybe.withDefault 1 <| Array.get (len - 1) block
b =
if last == marker then
Array.slice 0 -1 block
else
block
in
(b :: res)
|> List.reverse
head :: tail ->
unpadLastBlockLoop tail (head :: res)
{-| Remove the padding added by `padLastBlock` from the last block in a list.
-}
unpadLastBlock : List Block -> List Block
unpadLastBlock blocks =
unpadLastBlockLoop blocks []
stripTrailingZeroesLoop : Block -> Int -> Block
stripTrailingZeroesLoop block =
\idx ->
if idx < 0 then
block
else
case Array.get idx block of
Nothing ->
--can't happen
block
Just x ->
if x /= 0 then
Array.slice 0 (1 + idx) block
else
stripTrailingZeroesLoop block (idx - 1)
{-| Strip the trailing zeroes from a block.
-}
stripTrailingZeroes : Block -> Block
stripTrailingZeroes block =
let
len =
Array.length block
in
stripTrailingZeroesLoop block (len - 1)
{-| Convert a list of integers into a list of blocks.
The end of the last block will always be #x80 plus zeroes. If all the
blocks are full, and the last byte is NOT zero or #x80, then no
padding is added.
-}
listToBlocks : Int -> List Int -> List Block
listToBlocks blockSize list =
LE.greedyGroupsOf blockSize list
|> List.map (extendArray blockSize 0 << Array.fromList)
|> padLastBlock blockSize
{-| Convert a list of blocks into a list of integers.
-}
blocksToList : List Block -> List Int
blocksToList blocks =
unpadLastBlock blocks
|> List.map Array.toList
|> List.concat
{-| Decrypt a list of integers.
-}
decryptList : Config key state randomState -> Key key -> List Int -> List Int
decryptList config (Key key) list =
let
chaining =
config.chaining
encryption =
config.encryption
chainer =
chaining.decryptor
pair =
( encryption.encryptor, encryption.decryptor )
( cipherList, state ) =
chaining.separator encryption.blockSize list
cipherBlocks =
listToBlocks encryption.blockSize cipherList
step : Block -> ( List Block, state ) -> ( List Block, state )
step =
\block ( blocks, state_ ) ->
let
( outBlock, state2 ) =
chainer state_ pair key block
in
( outBlock :: blocks, state2 )
( plainBlocks, _ ) =
List.foldl step ( [], state ) cipherBlocks
in
List.reverse plainBlocks
|> blocksToList
{-| Decrypt a string created with `encrypt`.
-}
decrypt : Config key state randomState -> Key key -> Ciphertext -> Result Plaintext String
decrypt config key string =
--This will use the blockchain algorithm and block encoder
case config.encoding.decoder string of
Err msg ->
Err msg
Ok list ->
decryptList config key list
|> Encoding.plainTextDecoder
|> Ok
| 11867 | ----------------------------------------------------------------------
--
-- Crypt.elm
-- General purpose string encryption functions.
-- Copyright (c) 2017 <NAME> <<EMAIL>>
-- Some rights reserved.
-- Distributed under the MIT License
-- See LICENSE.txt
--
----------------------------------------------------------------------
module Crypto.Strings.Crypt exposing
( DefaultKey
, expandKeyString, defaultConfig, encrypt, decrypt, seedGenerator
, listToBlocks, blocksToList
, padLastBlock, unpadLastBlock, stripTrailingZeroes
)
{-| Block chaining and string encryption for use with any block cipher.
# Types
@docs DefaultKey
# Functions
@docs expandKeyString, defaultConfig, encrypt, decrypt, seedGenerator
# Low-level functions
@docs listToBlocks, blocksToList
@docs padLastBlock, unpadLastBlock, stripTrailingZeroes
-}
import Array exposing (Array)
import Crypto.Strings.BlockAes as Aes
import Crypto.Strings.Chaining as Chaining
import Crypto.Strings.Encoding as Encoding
import Crypto.Strings.Types
exposing
( Block
, BlockSize
, Ciphertext
, Config
, Decryptor
, Encoding
, Encryptor
, Key(..)
, KeyEncoding
, KeyExpander
, Passphrase
, Plaintext
, RandomGenerator
)
import List.Extra as LE
import Random
processKey : Config key state randomState -> String -> Result String key
processKey config string =
let
expander =
config.encryption.keyExpander
keyEncoder =
config.keyEncoding.encoder
in
keyEncoder expander.keySize string
|> expander.expander
defaultEncoding =
Encoding.base64Encoding 60
{-| Default key type.
-}
type alias DefaultKey =
Key Aes.Key
{-| Default configuration.
-}
defaultConfig : Config Aes.Key Chaining.CtrState randomState
defaultConfig =
{ keyEncoding = Encoding.foldedSha256KeyEncoding
, encryption = Aes.encryption
, chaining = Chaining.ctrChaining
, encoding = defaultEncoding
}
{-| Expand a key preparing it for use with `encrypt` or `decrypt`.
-}
expandKeyString : Config key state randomState -> Passphrase -> Result String (Key key)
expandKeyString config passphrase =
case processKey config passphrase of
Err msg ->
Err msg
Ok key ->
Ok <| Key key
{-| A random generator that takes and returns a standard Elm Seed.
-}
seedGenerator : Random.Seed -> RandomGenerator Random.Seed
seedGenerator seed blockSize =
let
gen =
Random.list blockSize <| Random.int 0 255
( list, sd ) =
Random.step gen seed
in
( Array.fromList list, sd )
{-| Encrypt a list of blocks.
-}
encryptList : Config key state randomState -> RandomGenerator randomState -> Key key -> List Int -> ( List Int, randomState )
encryptList config generator (Key key) list =
let
chaining =
config.chaining
encryption =
config.encryption
chainer =
chaining.encryptor
pair =
( encryption.encryptor, encryption.decryptor )
( state, randomState ) =
chaining.initializer generator encryption.blockSize
step : Block -> ( List Block, state ) -> ( List Block, state )
step =
\block ( blocks, state_ ) ->
let
( outBlock, outState ) =
chainer state_ pair key block
in
( outBlock :: blocks, outState )
( cipherBlocks, finalState ) =
listToBlocks encryption.blockSize list
|> List.foldl step ( [], state )
in
( List.reverse cipherBlocks
|> blocksToList
|> chaining.adjoiner finalState
, randomState
)
{-| Encrypt a string.
-}
encrypt : Config key state randomState -> RandomGenerator randomState -> Key key -> Plaintext -> ( Ciphertext, randomState )
encrypt config generator key plaintext =
Encoding.plainTextEncoder plaintext
|> encryptList config generator key
|> (\( cipherList, randomState ) ->
( config.encoding.encoder cipherList
, randomState
)
)
extendArray : Int -> a -> Array a -> Array a
extendArray size fill array =
let
count =
size - Array.length array
in
if count <= 0 then
array
else
Array.append array <| Array.repeat count fill
marker : Int
marker =
0x80
padLastBlockLoop : Int -> List Block -> List Block -> List Block
padLastBlockLoop blockSize =
\blocks res ->
case blocks of
[] ->
[]
[ blk ] ->
let
block =
stripTrailingZeroes blk
len =
Array.length block
last =
Maybe.withDefault 0 <|
Array.get (len - 1) block
( b, bs, ln ) =
if len == blockSize && (last == 0 || last == marker) then
( Array.fromList [ marker ]
, [ block ]
, 1
)
else if len < blockSize then
( Array.push marker block
, []
, len + 1
)
else
( block
, []
, len
)
b2 =
if ln < blockSize then
Array.append b <|
Array.repeat (blockSize - ln) 0
else
b
in
(b2 :: List.append bs res)
|> List.reverse
head :: tail ->
padLastBlockLoop blockSize tail <| head :: res
{-| Put a 0x80 at the end of the last block, and pad with zeroes.
No padding is done if the last block is of the blockSize, and does NOT already end with 0 or 0x80.
-}
padLastBlock : Int -> List Block -> List Block
padLastBlock blockSize blocks =
padLastBlockLoop blockSize blocks []
unpadLastBlockLoop : List Block -> List Block -> List Block
unpadLastBlockLoop =
\blocks res ->
case blocks of
[] ->
[]
[ blk ] ->
let
block =
stripTrailingZeroes blk
len =
Array.length block
last =
Maybe.withDefault 1 <| Array.get (len - 1) block
b =
if last == marker then
Array.slice 0 -1 block
else
block
in
(b :: res)
|> List.reverse
head :: tail ->
unpadLastBlockLoop tail (head :: res)
{-| Remove the padding added by `padLastBlock` from the last block in a list.
-}
unpadLastBlock : List Block -> List Block
unpadLastBlock blocks =
unpadLastBlockLoop blocks []
stripTrailingZeroesLoop : Block -> Int -> Block
stripTrailingZeroesLoop block =
\idx ->
if idx < 0 then
block
else
case Array.get idx block of
Nothing ->
--can't happen
block
Just x ->
if x /= 0 then
Array.slice 0 (1 + idx) block
else
stripTrailingZeroesLoop block (idx - 1)
{-| Strip the trailing zeroes from a block.
-}
stripTrailingZeroes : Block -> Block
stripTrailingZeroes block =
let
len =
Array.length block
in
stripTrailingZeroesLoop block (len - 1)
{-| Convert a list of integers into a list of blocks.
The end of the last block will always be #x80 plus zeroes. If all the
blocks are full, and the last byte is NOT zero or #x80, then no
padding is added.
-}
listToBlocks : Int -> List Int -> List Block
listToBlocks blockSize list =
LE.greedyGroupsOf blockSize list
|> List.map (extendArray blockSize 0 << Array.fromList)
|> padLastBlock blockSize
{-| Convert a list of blocks into a list of integers.
-}
blocksToList : List Block -> List Int
blocksToList blocks =
unpadLastBlock blocks
|> List.map Array.toList
|> List.concat
{-| Decrypt a list of integers.
-}
decryptList : Config key state randomState -> Key key -> List Int -> List Int
decryptList config (Key key) list =
let
chaining =
config.chaining
encryption =
config.encryption
chainer =
chaining.decryptor
pair =
( encryption.encryptor, encryption.decryptor )
( cipherList, state ) =
chaining.separator encryption.blockSize list
cipherBlocks =
listToBlocks encryption.blockSize cipherList
step : Block -> ( List Block, state ) -> ( List Block, state )
step =
\block ( blocks, state_ ) ->
let
( outBlock, state2 ) =
chainer state_ pair key block
in
( outBlock :: blocks, state2 )
( plainBlocks, _ ) =
List.foldl step ( [], state ) cipherBlocks
in
List.reverse plainBlocks
|> blocksToList
{-| Decrypt a string created with `encrypt`.
-}
decrypt : Config key state randomState -> Key key -> Ciphertext -> Result Plaintext String
decrypt config key string =
--This will use the blockchain algorithm and block encoder
case config.encoding.decoder string of
Err msg ->
Err msg
Ok list ->
decryptList config key list
|> Encoding.plainTextDecoder
|> Ok
| true | ----------------------------------------------------------------------
--
-- Crypt.elm
-- General purpose string encryption functions.
-- Copyright (c) 2017 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
-- Some rights reserved.
-- Distributed under the MIT License
-- See LICENSE.txt
--
----------------------------------------------------------------------
module Crypto.Strings.Crypt exposing
( DefaultKey
, expandKeyString, defaultConfig, encrypt, decrypt, seedGenerator
, listToBlocks, blocksToList
, padLastBlock, unpadLastBlock, stripTrailingZeroes
)
{-| Block chaining and string encryption for use with any block cipher.
# Types
@docs DefaultKey
# Functions
@docs expandKeyString, defaultConfig, encrypt, decrypt, seedGenerator
# Low-level functions
@docs listToBlocks, blocksToList
@docs padLastBlock, unpadLastBlock, stripTrailingZeroes
-}
import Array exposing (Array)
import Crypto.Strings.BlockAes as Aes
import Crypto.Strings.Chaining as Chaining
import Crypto.Strings.Encoding as Encoding
import Crypto.Strings.Types
exposing
( Block
, BlockSize
, Ciphertext
, Config
, Decryptor
, Encoding
, Encryptor
, Key(..)
, KeyEncoding
, KeyExpander
, Passphrase
, Plaintext
, RandomGenerator
)
import List.Extra as LE
import Random
processKey : Config key state randomState -> String -> Result String key
processKey config string =
let
expander =
config.encryption.keyExpander
keyEncoder =
config.keyEncoding.encoder
in
keyEncoder expander.keySize string
|> expander.expander
defaultEncoding =
Encoding.base64Encoding 60
{-| Default key type.
-}
type alias DefaultKey =
Key Aes.Key
{-| Default configuration.
-}
defaultConfig : Config Aes.Key Chaining.CtrState randomState
defaultConfig =
{ keyEncoding = Encoding.foldedSha256KeyEncoding
, encryption = Aes.encryption
, chaining = Chaining.ctrChaining
, encoding = defaultEncoding
}
{-| Expand a key preparing it for use with `encrypt` or `decrypt`.
-}
expandKeyString : Config key state randomState -> Passphrase -> Result String (Key key)
expandKeyString config passphrase =
case processKey config passphrase of
Err msg ->
Err msg
Ok key ->
Ok <| Key key
{-| A random generator that takes and returns a standard Elm Seed.
-}
seedGenerator : Random.Seed -> RandomGenerator Random.Seed
seedGenerator seed blockSize =
let
gen =
Random.list blockSize <| Random.int 0 255
( list, sd ) =
Random.step gen seed
in
( Array.fromList list, sd )
{-| Encrypt a list of blocks.
-}
encryptList : Config key state randomState -> RandomGenerator randomState -> Key key -> List Int -> ( List Int, randomState )
encryptList config generator (Key key) list =
let
chaining =
config.chaining
encryption =
config.encryption
chainer =
chaining.encryptor
pair =
( encryption.encryptor, encryption.decryptor )
( state, randomState ) =
chaining.initializer generator encryption.blockSize
step : Block -> ( List Block, state ) -> ( List Block, state )
step =
\block ( blocks, state_ ) ->
let
( outBlock, outState ) =
chainer state_ pair key block
in
( outBlock :: blocks, outState )
( cipherBlocks, finalState ) =
listToBlocks encryption.blockSize list
|> List.foldl step ( [], state )
in
( List.reverse cipherBlocks
|> blocksToList
|> chaining.adjoiner finalState
, randomState
)
{-| Encrypt a string.
-}
encrypt : Config key state randomState -> RandomGenerator randomState -> Key key -> Plaintext -> ( Ciphertext, randomState )
encrypt config generator key plaintext =
Encoding.plainTextEncoder plaintext
|> encryptList config generator key
|> (\( cipherList, randomState ) ->
( config.encoding.encoder cipherList
, randomState
)
)
extendArray : Int -> a -> Array a -> Array a
extendArray size fill array =
let
count =
size - Array.length array
in
if count <= 0 then
array
else
Array.append array <| Array.repeat count fill
marker : Int
marker =
0x80
padLastBlockLoop : Int -> List Block -> List Block -> List Block
padLastBlockLoop blockSize =
\blocks res ->
case blocks of
[] ->
[]
[ blk ] ->
let
block =
stripTrailingZeroes blk
len =
Array.length block
last =
Maybe.withDefault 0 <|
Array.get (len - 1) block
( b, bs, ln ) =
if len == blockSize && (last == 0 || last == marker) then
( Array.fromList [ marker ]
, [ block ]
, 1
)
else if len < blockSize then
( Array.push marker block
, []
, len + 1
)
else
( block
, []
, len
)
b2 =
if ln < blockSize then
Array.append b <|
Array.repeat (blockSize - ln) 0
else
b
in
(b2 :: List.append bs res)
|> List.reverse
head :: tail ->
padLastBlockLoop blockSize tail <| head :: res
{-| Put a 0x80 at the end of the last block, and pad with zeroes.
No padding is done if the last block is of the blockSize, and does NOT already end with 0 or 0x80.
-}
padLastBlock : Int -> List Block -> List Block
padLastBlock blockSize blocks =
padLastBlockLoop blockSize blocks []
unpadLastBlockLoop : List Block -> List Block -> List Block
unpadLastBlockLoop =
\blocks res ->
case blocks of
[] ->
[]
[ blk ] ->
let
block =
stripTrailingZeroes blk
len =
Array.length block
last =
Maybe.withDefault 1 <| Array.get (len - 1) block
b =
if last == marker then
Array.slice 0 -1 block
else
block
in
(b :: res)
|> List.reverse
head :: tail ->
unpadLastBlockLoop tail (head :: res)
{-| Remove the padding added by `padLastBlock` from the last block in a list.
-}
unpadLastBlock : List Block -> List Block
unpadLastBlock blocks =
unpadLastBlockLoop blocks []
stripTrailingZeroesLoop : Block -> Int -> Block
stripTrailingZeroesLoop block =
\idx ->
if idx < 0 then
block
else
case Array.get idx block of
Nothing ->
--can't happen
block
Just x ->
if x /= 0 then
Array.slice 0 (1 + idx) block
else
stripTrailingZeroesLoop block (idx - 1)
{-| Strip the trailing zeroes from a block.
-}
stripTrailingZeroes : Block -> Block
stripTrailingZeroes block =
let
len =
Array.length block
in
stripTrailingZeroesLoop block (len - 1)
{-| Convert a list of integers into a list of blocks.
The end of the last block will always be #x80 plus zeroes. If all the
blocks are full, and the last byte is NOT zero or #x80, then no
padding is added.
-}
listToBlocks : Int -> List Int -> List Block
listToBlocks blockSize list =
LE.greedyGroupsOf blockSize list
|> List.map (extendArray blockSize 0 << Array.fromList)
|> padLastBlock blockSize
{-| Convert a list of blocks into a list of integers.
-}
blocksToList : List Block -> List Int
blocksToList blocks =
unpadLastBlock blocks
|> List.map Array.toList
|> List.concat
{-| Decrypt a list of integers.
-}
decryptList : Config key state randomState -> Key key -> List Int -> List Int
decryptList config (Key key) list =
let
chaining =
config.chaining
encryption =
config.encryption
chainer =
chaining.decryptor
pair =
( encryption.encryptor, encryption.decryptor )
( cipherList, state ) =
chaining.separator encryption.blockSize list
cipherBlocks =
listToBlocks encryption.blockSize cipherList
step : Block -> ( List Block, state ) -> ( List Block, state )
step =
\block ( blocks, state_ ) ->
let
( outBlock, state2 ) =
chainer state_ pair key block
in
( outBlock :: blocks, state2 )
( plainBlocks, _ ) =
List.foldl step ( [], state ) cipherBlocks
in
List.reverse plainBlocks
|> blocksToList
{-| Decrypt a string created with `encrypt`.
-}
decrypt : Config key state randomState -> Key key -> Ciphertext -> Result Plaintext String
decrypt config key string =
--This will use the blockchain algorithm and block encoder
case config.encoding.decoder string of
Err msg ->
Err msg
Ok list ->
decryptList config key list
|> Encoding.plainTextDecoder
|> Ok
| elm |
[
{
"context": "!\n\n@docs Msg, createSVG\n\n-}\n\n{- Library created by Chris Schankula and Dr. Christopher Anand\n for the McMaster Uni",
"end": 4362,
"score": 0.9998512864,
"start": 4347,
"tag": "NAME",
"value": "Chris Schankula"
},
{
"context": "\n-}\n\n{- Library created by Chris Schankula and Dr. Christopher Anand\n for the McMaster University Computing and Soft",
"end": 4388,
"score": 0.9998820424,
"start": 4371,
"tag": "NAME",
"value": "Christopher Anand"
},
{
"context": "\n AlphaMask shape shape\n\n\n\n{-\n Contributed by Jack You.\n-}\n\n\nconvert : Float -> Float -> Float -> ( Floa",
"end": 99723,
"score": 0.9994658232,
"start": 99715,
"tag": "NAME",
"value": "Jack You"
}
] | src/GraphicSVG.elm | MacCASOutreach/graphicsvg | 46 | module GraphicSVG exposing
( Stencil, Shape, Collage(..), GraphicSVG
, collage, mapCollage
, App, app
, EllieApp, ellieApp
, line, polygon, openPolygon, ngon, triangle, rightTriangle, isosceles, sideAngleSide, square, rect, rectangle, roundedRect, circle, oval, wedge
, filled, outlined, repaint, addOutline, rgb, rgba, hsl, hsla
, group
, html
, curve, Pull(..), curveHelper
, LineType, noline, solid, dotted, dashed, longdash, dotdash, custom
, text, size, bold, italic, underline, strikethrough, centered, alignLeft, alignRight, selectable, sansserif, serif, fixedwidth, customFont
, move, rotate, scale, scaleX, scaleY, mirrorX, mirrorY, skewX, skewY
, clip, union, subtract, outside, ghost
, notifyTap, notifyTapAt, notifyEnter, notifyEnterAt, notifyLeave, notifyLeaveAt, notifyMouseMoveAt, notifyMouseDown, notifyMouseDownAt, notifyMouseUp, notifyMouseUpAt, notifyTouchStart, notifyTouchStartAt, notifyTouchEnd, notifyTouchEndAt, notifyTouchMoveAt
, makeTransparent, addHyperlink, puppetShow
, graphPaper, graphPaperCustom, map
, gradient, radialGradient, stop, transparentStop, rotateGradient
, Color, black, blank, blue, brown, charcoal, darkBlue, darkBrown, darkCharcoal, darkGray, darkGreen, darkGrey, darkOrange, darkPurple, darkRed, darkYellow, gray, green, grey, hotPink, lightBlue, lightBrown, lightCharcoal, lightGray, lightGreen, lightGrey, lightOrange, lightPurple, lightRed, lightYellow, orange, pink, purple, red, white, yellow
, Transform, ident, moveT, rotateT, scaleT, skewT, rotateAboutT, transform
, Msg(..), createSVG
)
{-| A library for creating SVG graphics in a way that is compatible with Elm's
old Graphics library. Also includes built-in functions for creating games and
other applications including keyboard presses and mouse movements.
# Basic Types
@docs Stencil, Shape, Collage, GraphicSVG
# Rendering To Screen
@docs collage, mapCollage
# App
@docs App, app
# EllieApp
@docs EllieApp, ellieApp
# Stencils
@docs line, polygon, openPolygon, ngon, triangle, rightTriangle, isosceles, sideAngleSide, square, rect, rectangle, roundedRect, circle, oval, wedge
# Creating Shapes from Stencils
@docs filled, outlined, repaint, addOutline, rgb, rgba, hsl, hsla
# Grouping Shapes
@docs group
# Rendering HTML
This feature is still very much experimental. Cross-platform support is
not guaranteed and weird things can happen.
@docs html
# Curves
@docs curve, Pull, curveHelper
# Line Styles
@docs LineType, noline, solid, dotted, dashed, longdash, dotdash, custom
# Text
@docs text, size, bold, italic, underline, strikethrough, centered, alignLeft, alignRight, selectable, sansserif, serif, fixedwidth, customFont
# Transformations
@docs move, rotate, scale, scaleX, scaleY, mirrorX, mirrorY, skewX, skewY
# Group Operations
@docs clip, union, subtract, outside, ghost
# Notifications
@docs notifyTap, notifyTapAt, notifyEnter, notifyEnterAt, notifyLeave, notifyLeaveAt, notifyMouseMoveAt, notifyMouseDown, notifyMouseDownAt, notifyMouseUp, notifyMouseUpAt, notifyTouchStart, notifyTouchStartAt, notifyTouchEnd, notifyTouchEndAt, notifyTouchMoveAt
# Miscellaneous
@docs makeTransparent, addHyperlink, puppetShow
# Helpers
@docs graphPaper, graphPaperCustom, map
# Let there be colours!
@docs Color, black, blank, blue, brown, charcoal, darkBlue, darkBrown, darkCharcoal, darkGray, darkGreen, darkGrey, darkOrange, darkPurple, darkRed, darkYellow, gray, green, grey, hotPink, lightBlue, lightBrown, lightCharcoal, lightGray, lightGreen, lightGrey, lightOrange, lightPurple, lightRed, lightYellow, orange, pink, purple, red, white, yellow
# Let there be gradients!
@docs stop, transparentStop, gradient, radialGradient, rotateGradient
# Advanced Transformations
_Advanced section warning!_ These functions provide a way to interface on a lower
level to the transformations normally handled in the background by GraphicSVG.
Most users should be happy to use the regular functions applied directly to shapes,
which are provided in the section above this one.
@docs Transform, ident, moveT, rotateT, scaleT, skewT, rotateAboutT, transform
# More Advanced Things
Don't worry about these unless you *_really_* know what you're doing!
@docs Msg, createSVG
-}
{- Library created by Chris Schankula and Dr. Christopher Anand
for the McMaster University Computing and Software Outreach Program
and CompSci 1JC3, with input and testing from the rest of the Outreach
team.
Last updated: January 25th, 2019
-}
import Array
import Browser exposing (UrlRequest)
import Browser.Dom exposing (Viewport, getViewportOf)
import Browser.Events exposing (onKeyDown, onKeyPress, onKeyUp, onResize)
import Browser.Navigation exposing (Key)
import Char
import Dict
import Html
import Html.Attributes
import Html.Events
import Json.Decode as D exposing (..)
import String exposing (..)
import Svg exposing (Attribute)
import Svg.Attributes exposing (..)
import Task
import Time exposing (..)
import Tuple
import Url exposing (Url)
import Color
{-| A primitive template representing the shape you wish to draw. This must be turned into
a `Shape` before being drawn to the screen with `collage` (see below).
-}
type Stencil
= Circle Float
| Rect Float Float
| RoundRect Float Float Float
| Oval Float Float
| BezierPath ( Float, Float ) (List ( ( Float, Float ), ( Float, Float ) ))
| Polygon (List ( Float, Float ))
| Path (List ( Float, Float ))
| Text Face String
{-| A filled, outlined, or filled and outlined object that can be drawn to the screen using `collage`.
-}
type Shape userMsg
= Inked (Maybe Color) (Maybe ( LineType, Color )) Stencil
| ForeignObject Float Float (Html.Html userMsg)
| Move ( Float, Float ) (Shape userMsg)
| Rotate Float (Shape userMsg)
| Scale Float Float (Shape userMsg)
| Skew Float Float (Shape userMsg)
| Transformed Transform (Shape userMsg)
| Group (List (Shape userMsg))
| GroupOutline (Shape userMsg)
| AlphaMask (Shape userMsg) (Shape userMsg)
| Clip (Shape userMsg) (Shape userMsg)
| Everything
| Notathing
| Link String (Shape userMsg)
| Tap userMsg (Shape userMsg)
| TapAt (( Float, Float ) -> userMsg) (Shape userMsg)
| EnterShape userMsg (Shape userMsg)
| EnterAt (( Float, Float ) -> userMsg) (Shape userMsg)
| Exit userMsg (Shape userMsg)
| ExitAt (( Float, Float ) -> userMsg) (Shape userMsg)
| MouseDown userMsg (Shape userMsg)
| MouseDownAt (( Float, Float ) -> userMsg) (Shape userMsg)
| MouseUp userMsg (Shape userMsg)
| MouseUpAt (( Float, Float ) -> userMsg) (Shape userMsg)
| MoveOverAt (( Float, Float ) -> userMsg) (Shape userMsg)
| TouchStart userMsg (Shape userMsg)
| TouchEnd userMsg (Shape userMsg)
| TouchStartAt (( Float, Float ) -> userMsg) (Shape userMsg)
| TouchEndAt (( Float, Float ) -> userMsg) (Shape userMsg)
| TouchMoveAt (( Float, Float ) -> userMsg) (Shape userMsg)
| GraphPaper Float Float Color
type FontAlign
= AlignLeft
| AlignCentred
| AlignRight
{-| To compose multiple pages or components which each have a Msg/view/update, we need to map messages.
(Ask if you don't know what this means.)
-}
map : (a -> b) -> Shape a -> Shape b
map f sh =
case sh of
Inked fillClr lt stencil ->
Inked fillClr lt stencil
ForeignObject w h htm ->
ForeignObject w h (Html.map f htm)
Move v shape ->
Move v (map f shape)
Rotate deg shape ->
Rotate deg (map f shape)
Scale sx sy shape ->
Scale sx sy (map f shape)
Skew skx sky shape ->
Skew skx sky (map f shape)
Transformed tm shape ->
Transformed tm (map f shape)
Link href shape ->
Link href (map f shape)
AlphaMask sh1 sh2 ->
AlphaMask (map f sh1) (map f sh2)
Clip sh1 sh2 ->
Clip (map f sh1) (map f sh2)
Everything ->
Everything
Notathing ->
Notathing
Tap msg shape ->
Tap (f msg) (map f shape)
TapAt msg shape ->
TapAt (f << msg) (map f shape)
EnterShape msg shape ->
EnterShape (f msg) (map f shape)
EnterAt msg shape ->
EnterAt (f << msg) (map f shape)
Exit msg shape ->
Exit (f msg) (map f shape)
ExitAt msg shape ->
ExitAt (f << msg) (map f shape)
MouseDown msg shape ->
MouseDown (f msg) (map f shape)
MouseDownAt msg shape ->
MouseDownAt (f << msg) (map f shape)
MouseUp msg shape ->
MouseUp (f msg) (map f shape)
MouseUpAt msg shape ->
MouseUpAt (f << msg) (map f shape)
MoveOverAt msg shape ->
MoveOverAt (f << msg) (map f shape)
TouchStart msg shape ->
TouchStart (f msg) (map f shape)
TouchEnd msg shape ->
TouchEnd (f msg) (map f shape)
TouchStartAt msg shape ->
TouchStartAt (f << msg) (map f shape)
TouchEndAt msg shape ->
TouchEndAt (f << msg) (map f shape)
TouchMoveAt msg shape ->
TouchMoveAt (f << msg) (map f shape)
Group shapes ->
Group (List.map (map f) shapes)
GroupOutline cmbndshp ->
GroupOutline (map f cmbndshp)
GraphPaper s th c ->
GraphPaper s th c
{-| To apply the function over all the shapes in the given `Collage` using the `map` function.
(Ask if you don't know what this means.)
-}
mapCollage : (a -> b) -> Collage a -> Collage b
mapCollage f (Collage w h shapes) =
Collage w h (List.map (map f) shapes)
{-| The `GraphicSVG` type alias represents the drawable surface of the window.
This type is only used to define a type signature for a user defined `view` as follows:
view : GraphicSVG.GraphicSVG userMsg
for use with `graphicsApp` and as follows:
view : Model -> GraphicSVG.GraphicSVG MyMsg
for use with `notificationsApp`, `gameApp` and `App`.
These assume that `Model` is the name of the user model type alias and
`MyMsg` is the name of the user message type. Simply substitute the names
actually used for these labels.
THIS IS DEPRECIATED AND ONLY KEPT FOR COMPATIBILITY WITH THE PREVIOUS VERSION;
Use "Collage userMsg" instead of "GraphicSVG userMsg", as they are identical except in name.
-}
type alias GraphicSVG userMsg =
Collage userMsg
{-| The `Color` type is used for filling or outlining a `Stencil`.
-}
type Color
= Solid Color.Color
| Gradient Gradient
type Gradient =
RadialGradient (List Stop)
| LinearGradient Float {- rotation -} (List Stop)
{-| Create a radial gradient from a list of colour stops.
-}
radialGradient : List Stop -> Color
radialGradient stops =
Gradient <| RadialGradient stops
{-| Create a linear gradient from a list of colour stops.
-}
gradient : List Stop -> Color
gradient stops =
Gradient <| LinearGradient 0 stops
{-| Rotate a linear gradient by a certain angle in radians.
-}
rotateGradient : Float -> Color -> Color
rotateGradient r grad =
case grad of
Gradient (LinearGradient rot stops) -> Gradient (LinearGradient (rot + r) stops)
radialGrad -> radialGrad
type Stop =
Stop Float {- stop position -} Float {- transparency -} Color.Color {- colour -}
{-| A colour stop in a gradient. This takes a colour and a position.
-}
stop : Color -> Float -> Stop
stop col pos =
case col of
Solid colour -> Stop pos 1 colour
_ -> Stop pos 1 (Color.rgba 0 0 0 0)
{-| A colour stop with transparency.
-}
transparentStop : Color -> Float -> Float -> Stop
transparentStop col pos alpha =
case col of
Solid colour -> Stop pos alpha colour
_ -> Stop pos 1 (Color.rgba 0 0 0 alpha)
createGradientSVG : String -> (Float, Float) -> Gradient -> Svg.Svg userMsg
createGradientSVG id (wid, hei) grad =
let
isRadial = case grad of
RadialGradient _ -> True
_ -> False
squareSize = if wid > hei then 2*wid else 2*hei
w = case grad of
RadialGradient stops ->
case List.head <| List.reverse stops of
Just (Stop pos _ _) -> pos
Nothing -> 0
LinearGradient _ stops ->
case List.head <| List.reverse stops of
Just (Stop pos _ _) -> pos
Nothing -> 0
createStop : Stop -> Svg.Svg userMsg
createStop (Stop pos trans colour) =
let
start = if isRadial then 0 else (1 - w/squareSize)/2 * 100
percent = if isRadial then pos / w * 100 else start + pos/squareSize * 100
percentTxt = String.fromFloat percent ++ "%"
colourTxt = "stop-color:" ++ mkRGB colour ++ ";"
opacityTxt = "stop-opacity:" ++ String.fromFloat trans ++ ";"
in
Svg.stop [Svg.Attributes.offset percentTxt, Svg.Attributes.style (colourTxt ++ opacityTxt)] []
defs = Svg.defs []
[
case grad of
LinearGradient _ stops ->
Svg.linearGradient
[ Svg.Attributes.id (id ++ "gradient")
, Svg.Attributes.gradientTransform <| "rotate(" ++ String.fromFloat rotation ++ "rad)"
--, Svg.Attributes.x1 "0%"
--, Svg.Attributes.y1 "0%"
--, Svg.Attributes.x2 "100%"
--, Svg.Attributes.y2 "0%"
, Svg.Attributes.gradientTransform ("rotate("++ String.fromFloat rotation ++ "rad)")
]
(List.map createStop stops)
RadialGradient stops ->
Svg.radialGradient
[ Svg.Attributes.id (id ++ "gradient")
, Svg.Attributes.cx "0"--(String.fromFloat (squareSize/2))
, Svg.Attributes.cy "0"--(String.fromFloat (squareSize/2))
, Svg.Attributes.r (String.fromFloat w)
, Svg.Attributes.gradientUnits "userSpaceOnUse"
]
(List.map createStop stops)
]
rotation =
case grad of
LinearGradient rot stops ->
rot * 180 / pi
_ -> 0
in
Svg.g [mask ("url(#" ++ id ++ "mask)")]
[ defs
, Svg.rect
([ x <| String.fromFloat <| -squareSize / 2
, y <| String.fromFloat <| -squareSize / 2
, width <| String.fromFloat squareSize
, height <| String.fromFloat squareSize
, fill ("url(#" ++ id ++ "gradient)")
, Svg.Attributes.id (id ++ "grad")
, Svg.Attributes.transform <| "rotate(" ++ String.fromFloat rotation ++")"
]
)
[]
]
{-| The `LineType` type is used to define the appearance of an outline for a `Stencil`.
`LineType` also defines the appearence of `line` and `curve`.
-}
type LineType
= NoLine
| Unbroken Float
| Broken (List ( Float, Float )) Float
{-| The `Face` type describes the appearance of a text `Stencil`.
THIS IS NOT EXPOSED BY ANY TYPE AND IS NOW NOT EXPOSED BY THE LIBARY.
-}
type Face
= Face
Float
-- size
Bool
-- bold
Bool
-- italic
Bool
-- underline
Bool
-- strikethrough
Bool
-- selectable
Font
-- font alignment
FontAlign
{-| The `Font` type describes the font of a text `Stencil`.
THIS IS NOT EXPOSED BY ANY TYPE AND IS NOW NOT EXPOSED BY THE LIBARY.
-}
type Font
= Serif
| Sansserif
| FixedWidth
| Custom String
{-| To make it easier to read the code defining a `curve`,
and to make sure we always use the right number of curve points
and pull points (which is one more curve point than pull points),
we define a special `Pull` type, whose first point is the point
we pull towards, and second point is the end point for this
curve segments.
-}
type Pull
= Pull ( Float, Float ) ( Float, Float )
{-| _Advanced Function Warning!_ `app` takes one parameter of its own type of the form:
{
init = \flags url key -> (model, cmd)
, view = \model -> { title = "Your Title goes here",
, body = view model
}
, update = \userMsg userModel -> ( userModel, Cmd userMsg )
, subscriptions = \userModel -> Sub userMsg
, onUrlRequest = \urlRequest -> userMsg
, onUrlChange = \url -> userMsg
}
This matches the Elm architecture and is analogous to `Browser.application`.
-}
app :
{ init : flags -> Url -> Key -> ( userModel, Cmd userMsg )
, update : userMsg -> userModel -> ( userModel, Cmd userMsg )
, view : userModel -> { title : String, body : Collage userMsg }
, subscriptions : userModel -> Sub userMsg
, onUrlRequest : UrlRequest -> userMsg
, onUrlChange : Url -> userMsg
}
-> App flags userModel userMsg
app input =
Browser.application
{ init =
\flags url key ->
let
userInit =
Tuple.first <| input.init flags url key
userView =
(input.view userInit).body
(Collage initW initH _) =
userView
userInitCmd =
Tuple.second <| input.init flags url key
in
( ( userInit, { initHiddenModel | cw = initW, ch = initH } ), initialCmd <| Cmd.map Graphics userInitCmd )
, update = hiddenAppUpdate input.view input.update
, view = hiddenAppView input.view
, subscriptions = subs <| input.subscriptions
, onUrlRequest = Graphics << input.onUrlRequest
, onUrlChange = Graphics << input.onUrlChange
}
{-| This type alias is only used as a target for a user `main` type signature to make
the type signature more clear and concise when `main` calls `app`:
main : App Flags Model Msg
main =
app Tick
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
, onUrlRequest = onUrlRequest
, onUrlChange = onUrlChange
}
where `Tick` is a message handler called once per browser window update,
`Flags` is the type alias (or type) of the flags input from JavaScript
`Model` is the type alias of the user persistent model, and
`Msg` is the name of the user message type; if other names are used,
they can just be substituted for these names.
Note that "type alias" could also be an ordinary "type" in all case,
just that the syntax for producing a new type is not as clean as using a
type alias for a record.
-}
type alias App flags userModel userMsg =
Program flags ( userModel, HiddenModel ) (Msg userMsg)
subs : (userModel -> Sub userMsg) -> ( userModel, gModel ) -> Sub (Msg userMsg)
subs userSubs ( userModel, _ ) =
Sub.batch
([ onResize (\_ _ -> WindowResize Nothing)
]
++ [ Sub.map Graphics (userSubs userModel) ]
)
hiddenAppUpdate :
(userModel -> { title : String, body : Collage userMsg })
-> (userMsg -> userModel -> ( userModel, Cmd userMsg ))
-> Msg userMsg
-> ( userModel, HiddenModel )
-> ( ( userModel, HiddenModel ), Cmd (Msg userMsg) )
hiddenAppUpdate userView userUpdate msg ( userModel, gModel ) =
let
mapUserCmd cmd =
Cmd.map Graphics cmd
(Collage cw ch _) =
(userView userModel).body
in
case msg of
Graphics message ->
let
( newModel, userCmds ) =
userUpdate message userModel
in
( ( newModel, { gModel | cw = cw, ch = ch } )
, mapUserCmd userCmds
)
WindowResize mWH ->
case mWH of
Just ( w, h ) ->
( ( userModel
, { gModel
| sw = Basics.toFloat w
, sh = Basics.toFloat h
}
)
, Cmd.none
)
Nothing ->
( (userModel, gModel)
, getViewportSize
)
ReturnPosition message ( x, y ) ->
let
( newModel, userCmds ) =
userUpdate
(message (convertCoords ( x, y ) gModel))
userModel
in
( ( newModel, gModel ), mapUserCmd userCmds )
NoOp -> (( userModel, gModel ), Cmd.none)
hiddenAppView :
(userModel -> { title : String, body : Collage userMsg })
-> ( userModel, HiddenModel )
-> { title : String, body : List (Html.Html (Msg userMsg)) }
hiddenAppView userView ( userModel, _ ) =
let
userViewEval =
userView userModel
title =
userViewEval.title
(Collage w h shapes) =
userViewEval.body
in
{ title = title, body = [ createCollage w h shapes ] }
{-| This type alias is only used as a target for a user `main` type signature to make
the type signature more clear and concise when `main` calls `ellieApp`:
main : EllieApp Flags Model Msg
main =
ellieApp Tick
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
}
where `Tick` is a message handler called once per browser window update,
`Flags` is the type alias (or type) of the flags input from JavaScript
`Model` is the type alias of the user persistent model, and
`Msg` is the name of the user message type; if other names are used,
they can just be substituted for these names.
Note that "type alias" could also be an ordinary "type" in all case,
just that the syntax for producing a new type is not as clean as using a
type alias for a record.
-}
type alias EllieApp flags userModel userMsg =
Program flags ( userModel, HiddenModel ) (Msg userMsg)
{-| _Advanced Function Warning!_ `ellieApp` takes one parameter of its own type of the form:
{
init = \flags url key -> (model, cmd)
, view = \model -> { title = "Your Title goes here",
, body = view model
}
, update = \userMsg userModel -> ( userModel, Cmd userMsg )
, subscriptions = \userModel -> Sub userMsg
}
This matches the Elm architecture and is analogous to `Browser.document`.
It is called ellieApp because this version is compatible with the online
Elm IDE Ellie.
-}
ellieApp :
{ init : flags -> ( userModel, Cmd userMsg )
, update : userMsg -> userModel -> ( userModel, Cmd userMsg )
, view : userModel -> { title : String, body : Collage userMsg }
, subscriptions : userModel -> Sub userMsg
}
-> EllieApp flags userModel userMsg
ellieApp input =
Browser.document
{ init =
\flags ->
let
userInit =
Tuple.first <| input.init flags
userView =
(input.view userInit).body
(Collage initW initH _) =
userView
userInitCmd =
Tuple.second <| input.init flags
in
( ( userInit, { initHiddenModel | cw = initW, ch = initH } ), initialCmd <| Cmd.map Graphics userInitCmd )
, update = hiddenAppUpdate input.view input.update
, view = hiddenAppView input.view
, subscriptions = subs <| input.subscriptions
}
convertCoords : ( Float, Float ) -> HiddenModel -> ( Float, Float )
convertCoords ( x, y ) gModel =
let
sw =
gModel.sw
sh =
gModel.sh
cw =
gModel.cw
ch =
gModel.ch
aspectout =
if not (sh == 0) then
sw / sh
else
4 / 3
aspectin =
if not (ch == 0) then
cw / ch
else
4 / 3
scaledInX =
aspectout < aspectin
scaledInY =
aspectout > aspectin
cscale =
if scaledInX then
sw / cw
else if scaledInY then
sh / ch
else
1
in
( (x - sw / 2) / cscale
, (y + sh / 2) / cscale
)
initialCmd :
Cmd (Msg userMsg)
-> Cmd (Msg userMsg)
initialCmd userCmd =
Cmd.batch
[ getViewportSize
, userCmd
]
getViewportSize : Cmd (Msg userMsg)
getViewportSize = Task.attempt
(\rvp -> case rvp of
Ok vp ->
WindowResize
<| Just ( round vp.viewport.width, round vp.viewport.height )
Err _ -> NoOp
)
(getViewportOf "render")
{-| The `Msg` type encapsulates all GraphicSVG internal messages.
This type is only used to define type signature fors user defined
`view` and `main` as follows:
view : GraphicSVG.Collage (GraphicSVG.Msg Msg)
for use with `graphicsApp` and `notificationsApp`, and as follows:
view : Model -> GraphicSVG.Collage (GraphicSVG.Msg Msg)
for use with `gameApp`.
It is also used to define the type signature for
a user supplied `main` as follows:
main : Program Never (GraphicsModel Model Msg) (GraphicSVG.Msg Msg)
for use with `graphicsApp` and `notificationsApp`, and as follows:
main : Program Never (GamesModel Model Msg) (GraphicSVG.Msg Msg)
for use when `main` calls `gameApp`
These assume that `Model` is the type alias of the user persistent model, and
`Msg` is the name of the user message type.
-}
type Msg userMsg
= Graphics userMsg
| WindowResize (Maybe ( Int, Int ))
| ReturnPosition (( Float, Float ) -> userMsg) ( Float, Float )
| NoOp
{-| The `HiddenModel` type alias encapsulates the GraphicSVG internal model
which is not exposed to user code.
-}
type alias HiddenModel =
{ cw : Float
, ch : Float
, sw : Float
, sh : Float
}
initHiddenModel : HiddenModel
initHiddenModel =
{ cw = 0
, ch = 0
, sw = 0
, sh = 0
}
{-| Create a line from a point to a point. Use `outlined` to convert to a viewable
`Shape`.
-}
line : ( Float, Float ) -> ( Float, Float ) -> Stencil
line p1 p2 =
Path [ p1, p2 ]
{-| Create a closed shape given a list of points. Can use `outlined` or `filled` to
convert to a `Shape`.
-}
polygon : List ( Float, Float ) -> Stencil
polygon ptList =
Polygon ptList
{-| Create an open shape given a list of points. Unlike with polygon, the first and
last points will not join up automatically. Can use `outlined` or `filled` to
convert to a `Shape`.
-}
openPolygon : List ( Float, Float ) -> Stencil
openPolygon ptList =
Path ptList
{-| Create a regular polygon with a given number of sides and radius. Examples:
ngon 3 50 -- triangle
ngon 5 50 -- pentagon
ngon 8 50 -- octogon
-}
ngon : Int -> Float -> Stencil
ngon n r =
Polygon <|
List.map
(ptOnCircle r (Basics.toFloat n) << Basics.toFloat)
(List.range 0 n)
{-| Synonym for `ngon 3`. Creates a triangle with a given size.
-}
triangle : Float -> Stencil
triangle r =
ngon 3 r
{-| Creates a right-angled triangle with a given base and height.
-}
rightTriangle : Float -> Float -> Stencil
rightTriangle base height =
polygon [ ( 0, 0 ), ( base, 0 ), ( 0, height ) ]
{-| Creates an isosceles triangle with a given base and height.
-}
isosceles : Float -> Float -> Stencil
isosceles base height =
polygon [ ( -base / 2, 0 ), ( base / 2, 0 ), ( 0, height ) ]
{-| Creates a triangle given two side lengths and the angle between them.
For example, `sideAngleSide 30 (degrees 45) 50` creates a triangle with side lengths
30 and 50 with an angle of 45 degrees between them.
-}
sideAngleSide : Float -> Float -> Float -> Stencil
sideAngleSide sideOne angle sideTwo =
polygon [ sideTwoPoint angle sideOne, ( 0, 0 ), ( sideTwo, 0 ) ]
sideTwoPoint : Float -> Float -> ( Float, Float )
sideTwoPoint angle sideOne =
( cos angle * sideOne, sin angle * sideOne )
{-| Creates a square with a given side length. (Synonym for `rect s s`)
-}
square : Float -> Stencil
square r =
Rect r r
{-| Creates a rectangle with a given width and height.
-}
rect : Float -> Float -> Stencil
rect w h =
Rect w h
{-| Synonym for `rect`.
-}
rectangle : Float -> Float -> Stencil
rectangle w h =
Rect w h
{-| Creates a rectangle with a given width, height, and circular rounded
corners with the given radius.
-}
roundedRect : Float -> Float -> Float -> Stencil
roundedRect w h r =
RoundRect w h r
{-| Creates a circle with a given radius.
-}
circle : Float -> Stencil
circle r =
Circle r
{-| Creates an oval with a given width and height.
-}
oval : Float -> Float -> Stencil
oval w h =
Oval w h
{-| Creates a graph paper with squares of a given size.
-}
graphPaper : Float -> Shape userMsg
graphPaper s =
GraphPaper s 1 (Solid <| Color.fromRgba { red = 135, green = 206, blue = 250, alpha = 1})
{-| Creates graph paper with squares of a given size, with a user-defined thickness and colour.
-}
graphPaperCustom : Float -> Float -> Color -> Shape userMsg
graphPaperCustom s th c =
GraphPaper s th c
createGraph : ( Float, Float ) -> Float -> Float -> Color -> Shape userMsg
createGraph ( w, h ) s th c =
let
sxi =
ceiling (w / (s * 2))
syi =
ceiling (h / (s * 2))
xlisti =
List.range -sxi sxi
ylisti =
List.range -syi syi
in
group
(List.map (createGraphX h s th c << Basics.toFloat) xlisti
++ List.map (createGraphY w s th c << Basics.toFloat) ylisti
)
createGraphX : Float -> Float -> Float -> Color -> Float -> Shape userMsg
createGraphX h s th c x =
filled c (rect th h) |> move ( x * s, 0 )
createGraphY : Float -> Float -> Float -> Color -> Float -> Shape userMsg
createGraphY w s th c y =
filled c (rect w th) |> move ( 0, y * s )
{-| Creates a wedge with a given radius, and a given fraction of a circle.
wedge 50 0.5 -- semi-circle
wedge 50 0.25 -- quarter-circle
wedge 50 0.75 -- three-quarter circle
-}
wedge : Float -> Float -> Stencil
wedge r frac =
let
n =
frac * 360 / 10 + 5
ni =
round n
dlta =
frac / Basics.toFloat ni
in
Polygon <|
if frac > 0 then
[ ( 0, 0 ), wedgeHelper r -frac ]
++ List.map
(wedgeHelper r
<< (*) dlta
<< Basics.toFloat
)
(List.range -ni ni)
++ [ wedgeHelper r frac, ( 0, 0 ) ]
else
[]
wedgeHelper : Float -> Float -> ( Float, Float )
wedgeHelper r cn =
let
angle =
turns (0.5 * cn)
in
( r * cos angle, r * sin angle )
ptOnCircle : Float -> Float -> Float -> ( Float, Float )
ptOnCircle r n cn =
let
angle =
turns (cn / n)
in
( r * cos angle, r * sin angle )
{-| Creates a curve starting at a point, pulled towards a point, ending at a third point. For example,
curve (0,0) [Pull (0,10) (0,20)]
gives a curve starting at (0,0), pulled towards (0,10) and ending at (0,20).
Think about curves as what you get when you take a bunch of
bendy sticks with their ends glued down to a board, and then pulling each stick
towards another point.
You always need an initial point and at least one `Pull`, but you can add as many `Pull`s as you want to
add additional curve segments, but each curve segment can only bend one way, since it is pulled in one direction.
-}
curve : ( Float, Float ) -> List Pull -> Stencil
curve ( a, b ) list =
BezierPath ( a, b ) (List.map curveListHelper list)
curveListHelper : Pull -> ( ( Float, Float ), ( Float, Float ) )
curveListHelper (Pull ( a, b ) ( c, d )) =
( ( a, b ), ( c, d ) )
{-| Add a hyperlink to any `Shape`:
circle 10
|> filled red
|> addHyperlink "http://outreach.mcmaster.ca"
-}
addHyperlink : String -> Shape userMsg -> Shape userMsg
addHyperlink link shape =
Link link shape
{-| Creates a text `Stencil`. You can change this `Stencil` using the text helper
functions. Note that `|> filled ...` or `|> outlined ...` must go at the _end_ of the text helper functions
(ie note that all these functions have type `Stencil -> Stencil`). For example,
text "Hello World"
|> fixedwidth
|> bold
|> size 14
|> filled black
-}
text : String -> Stencil
text str =
Text (Face 12 False False False False False Serif AlignLeft) str
{-| Apply to a curve or group of curves in order to view their start points,
end points and `Pull` points. Helpful while perfecting curves.
curve (0,0) [Pull (0,10) (0,20)]
|> curveHelper
-}
curveHelper : Shape userMsg -> Shape userMsg
curveHelper shape =
case shape of
Inked _ _ (BezierPath ( a, b ) list) ->
group [ shape, generateCurveHelper ( a, b ) list ]
Move s sh ->
Move s (curveHelper sh)
Rotate r sh ->
Rotate r (curveHelper sh)
Scale sx sy sh ->
Scale sx sy (curveHelper sh)
Skew skx sky sh ->
Skew skx sky (curveHelper sh)
Transformed tm sh ->
Transformed tm (curveHelper sh)
Group list ->
Group (List.map curveHelper list)
GroupOutline cmbndshp ->
GroupOutline (curveHelper cmbndshp)
Link s sh ->
Link s (curveHelper sh)
AlphaMask reg sh ->
AlphaMask reg (curveHelper sh)
Clip reg sh ->
Clip reg (curveHelper sh)
Tap userMsg sh ->
Tap userMsg (curveHelper sh)
TapAt userMsg sh ->
TapAt userMsg (curveHelper sh)
EnterShape userMsg sh ->
EnterShape userMsg (curveHelper sh)
EnterAt userMsg sh ->
EnterAt userMsg (curveHelper sh)
Exit userMsg sh ->
Exit userMsg (curveHelper sh)
ExitAt userMsg sh ->
ExitAt userMsg (curveHelper sh)
MouseDown userMsg sh ->
MouseDown userMsg (curveHelper sh)
MouseDownAt userMsg sh ->
MouseDownAt userMsg (curveHelper sh)
MouseUp userMsg sh ->
MouseUp userMsg (curveHelper sh)
MouseUpAt userMsg sh ->
MouseUpAt userMsg (curveHelper sh)
MoveOverAt userMsg sh ->
MoveOverAt userMsg (curveHelper sh)
TouchStart userMsg sh ->
TouchStart userMsg (curveHelper sh)
TouchEnd userMsg sh ->
TouchEnd userMsg (curveHelper sh)
TouchStartAt userMsg sh ->
TouchStartAt userMsg (curveHelper sh)
TouchEndAt userMsg sh ->
TouchEndAt userMsg (curveHelper sh)
TouchMoveAt userMsg sh ->
TouchMoveAt userMsg (curveHelper sh)
-- no changes for the rest...
Inked clr ln sh ->
Inked clr ln sh
ForeignObject w h htm ->
ForeignObject w h htm
Everything ->
Everything
Notathing ->
Notathing
GraphPaper s th clr ->
GraphPaper s th clr
generateCurveHelper :
( Float, Float )
-> List ( ( Float, Float ), ( Float, Float ) )
-> Shape userMsg
generateCurveHelper ( a, b ) list =
let
l1Array =
Array.fromList
([ ( a, b ) ]
++ List.concat (List.map createTopLevelList list)
)
in
group [ generateCHLines l1Array, generateCHCircles l1Array ]
generateCHLines : Array.Array ( Float, Float ) -> Shape userMsg
generateCHLines ar =
let
len =
Array.length ar
in
group (List.map (generateCHLine ar) (List.range 0 (len - 2)))
generateCHLine : Array.Array ( Float, Float ) -> Int -> Shape userMsg
generateCHLine ar int =
let
p1 =
case Array.get int ar of
Just p ->
p
Nothing ->
( 0, 0 )
p2 =
case Array.get (int + 1) ar of
Just p ->
p
Nothing ->
( 0, 0 )
in
outlined (dashed 0.5) black (line p1 p2)
generateCHCircles : Array.Array ( Float, Float ) -> Shape userMsg
generateCHCircles ar =
let
len =
Array.length ar
in
group (List.map (generateCHCircle ar) (List.range 0 (len - 1)))
generateCHCircle : Array.Array ( Float, Float ) -> Int -> Shape userMsg
generateCHCircle ar int =
let
p1 =
case Array.get int ar of
Just p ->
p
Nothing ->
( 0, 0 )
ptStr =
pairToString p1
in
group
[ filled red (circle 2)
, text ("(" ++ ptStr ++ ")")
|> filled black
|> move ( 5, 5 )
]
|> move p1
createTopLevelList : ( ( a, b ), ( a, b ) ) -> List ( a, b )
createTopLevelList ( ( a, b ), ( c, d ) ) =
[ ( a, b ), ( c, d ) ]
matrixMult : Transform -> Transform -> Transform
matrixMult ( ( a, c, e ), ( b, d, f ) ) ( ( a1, c1, e1 ), ( b1, d1, f1 ) ) =
( ( a * a1 + c * b1, a * c1 + c * d1, e + a * e1 + c * f1 )
, ( b * a1 + d * b1, b * c1 + d * d1, f + b * e1 + d * f1 )
)
{-| The identity or "starting" matrix. Applying this matrix to a shape is the equivalent
of doing no transformations at all. The matrix itself looks like
```
ident = ( ( 1 , 0 , 0 ) , ( 0 , 1 , 0 ) )
```
or,
```
1 0 0
0 1 0
```
-}
ident : Transform
ident =
( ( 1, 0, 0 )
, ( 0, 1, 0 )
)
{-| A matrix representing an SVG transformation matrix of the form:
```
( ( a , c , e ) , ( b , d , f ) )
```
or
```
a c e
b d f
```
The a, c, b and d control transformations such as skew, rotate and scale;
e and f control translation.
These matrices are best built up by starting with the identity matrix and
applying any number of `*T` functions (see below); for example,
```
myTransform =
ident
|> scaleT 2 2
|> rotateT (degrees 30)
|> moveT (0, 50)
```
-}
type alias Transform =
( ( Float, Float, Float ), ( Float, Float, Float ) )
{-| Apply a move (translation) transformation to a transformation matrix.
This is designed to be used as part of a pipe:
```
ident
|> moveT (15,-30.5)
```
-}
moveT : ( Float, Float ) -> Transform -> Transform
moveT ( u, v ) ( ( a, c, tx ), ( b, d, ty ) ) =
( ( a, c, tx + a * u + c * v )
, ( b, d, ty + b * u + d * v )
)
{-| Apply a rotation transformation to a transformation matrix.
This is designed to be used as part of a pipe:
```
ident
|> moveT (15,-30.5)
|> rotateT (degrees -30)
```
-}
rotateT : Float -> Transform -> Transform
rotateT rad ( ( a, c, tx ), ( b, d, ty ) ) =
let
sinX =
sin rad
cosX =
cos rad
in
( ( a * cosX + c * sinX, c * cosX - a * sinX, tx )
, ( b * cosX + d * sinX, d * cosX - b * sinX, ty )
)
{-| Apply a scale transformation to a transformation matrix. The first argument
scales in x and the second argument scales in y. This is designed
to be used as part of a pipe:
```
ident
|> moveT (15,-30.5)
|> rotateT (degrees -30)
|> scaleT 4 0.4
```
-}
scaleT : Float -> Float -> Transform -> Transform
scaleT sx sy ( ( a, c, tx ), ( b, d, ty ) ) =
( ( a * sx, c * sy, tx )
, ( b * sx, d * sy, ty )
)
{-| Apply a skew transformation to a matrix. The first argument
skews in x and the second argument skews in y. This is designed
to be used as part of a pipe:
```
ident
|> moveT (15,-30.5)
|> rotateT (degrees -30)
|> scaleT 4 0.4
|> skewT 0.5 1.3
```
-}
skewT : Float -> Float -> Transform -> Transform
skewT skx sky ( ( a, c, tx ), ( b, d, ty ) ) =
let
tanX =
tan -skx
tanY =
tan -sky
in
( ( a + c * tanY, c + a * tanX, tx )
, ( b + d * tanY, d + b * tanX, ty )
)
{-| Apply a rotation about a given point to a `Transform` matrix. For example,
the following transform will rotate a `Shape` 30 degrees about the point (0,50):
```
rotateAbout050 =
ident
|> rotateAboutT (0, 50) (degrees 30)
```
-}
rotateAboutT : ( Float, Float ) -> Float -> Transform -> Transform
rotateAboutT ( u, v ) rad ( ( a, c, tx ), ( b, d, ty ) ) =
let
sinX =
sin rad
cosX =
cos rad
in
( ( a * cosX + c * sinX, c * cosX - a * sinX, tx + a * u + c * v - v * (c * cosX - a * sinX) - u * (a * cosX + c * sinX) )
, ( b * cosX + d * sinX, d * cosX - b * sinX, ty + b * u + d * v - v * (d * cosX - b * sinX) - u * (b * cosX + d * sinX) )
)
{-| Manually transform a shape using a `Transform` matrix. Matrix multiplication will
be used to apply the given matrix to any transformations of the current
shape. This is designed to be used in the usual way in a pipe:
```
circle 10
|> filled red
|> transform moveLeft50
moveLeft50 =
ident
|> moveT (50,0)
```
NOTE: Transformations generated using pipes this way are applied backwards compared
to the "regular" `Shape userMsg` transformation functions. For example, `rect0` and
`rect1` below are equivalent:
```
myTransform =
ident
|> scaleT 2 2
|> rotateT (degrees 30)
|> moveT (0, 50)
rect0 =
rect 20 10
|> filled red
|> transform myTransform
rect1 =
rect 20 10
|> filled red
|> move (0, 50)
|> rotate (degrees 30)
|> scale 2
```
On the other hand, single transformations produce a result consistent with the
`Shape userMsg` transformations. `rect2` is also equivalent to the two above:
```
moveRight50 =
ident
|> moveT (50,0)
scale2 =
ident
|> scaleT 2 2
rotate30 =
ident
|> rotateT (degrees 30)
rect2 =
rect 20 10
|> filled red
|> transform moveRight50
|> transform scale2
|> transform rotate30
```
However, chaining together transformations in this way is discouraged because
it is less efficient than the regular `Shape userMsg` transformations in
the "Transformations" section.
-}
transform : Transform -> Shape userMsg -> Shape userMsg
transform tm sh =
Transformed tm sh
{-| The Collage type represents the drawable surface of the window which contains
a (x, y) pair of horizontal and vertical dimensions (arbitrary units,
not necessarily in pixels) to which the drawing surface will be scaled,
and the \`List' of Shapes to be drawn on the drawing surface.
-}
type Collage userMsg
= Collage Float Float (List (Shape userMsg))
{-| Creates a blank canvas on which you can draw. Takes a width, height and a
list of `Shape`s. Use this in your `view` functions in the three types of Apps above:
collage 500 500
[
circle 10 |> filled red
]
-}
collage : Float -> Float -> List (Shape userMsg) -> Collage userMsg
collage w h shapes =
Collage w h shapes
createCollage : Float -> Float -> List (Shape userMsg) -> Html.Html (Msg userMsg)
createCollage w h shapes =
Svg.svg
[ width "100%"
, height "100%"
, style "position:absolute;top:0px;left:0px;"
, viewBox
(String.fromFloat (-w / 2)
++ " "
++ String.fromFloat (-h / 2)
++ " "
++ String.fromFloat w
++ " "
++ String.fromFloat h
)
, id "render"
]
(cPath w h
:: [ Svg.g
[ clipPath "url(#cPath)" ]
(List.indexedMap
(\n -> createSVG (String.fromInt n) w h ident Graphics ReturnPosition)
shapes
)
]
)
cPath : Float -> Float -> Svg.Svg (Msg userMsg)
cPath w h =
Svg.defs []
[ Svg.clipPath
[ Svg.Attributes.id "cPath" ]
[ Svg.rect
[ width (String.fromFloat w)
, height (String.fromFloat h)
, x (String.fromFloat (-w / 2))
, y (String.fromFloat (-h / 2))
]
[]
]
]
{-| Take a `Collage` width and height as well as a list of tuples of depth and `Shape`.
to produce a list of `Shape`'s suitable for display as a group in a `Collage` with
`Shape`'s with lesser depth larger and in front of `Shape`'s with greater depth.
-}
puppetShow :
Float
-> Float
-> List ( Float, Shape userMsg )
-> List (Shape userMsg)
puppetShow w h listShapes =
List.map
(extractShape (Basics.max w h))
(List.sortWith flippedComparison listShapes)
extractShape : Float -> ( Float, Shape userMsg ) -> Shape userMsg
extractShape fl ( z, shape ) =
let
s =
fl / (fl + z)
in
shape |> scale s
flippedComparison : ( comparable, a ) -> ( comparable, b ) -> Order
flippedComparison ( f, _ ) ( s, _ ) =
compare s f
--Notification functions
{-| Receive a message (`userMsg`) when a `Shape` is clicked or tapped.
-}
notifyTap : userMsg -> Shape userMsg -> Shape userMsg
notifyTap msg shape =
Tap msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse or finger when the `Shape` is clicked or tapped.
-}
notifyTapAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyTapAt msg shape =
TapAt msg shape
{-| Receive a message (`userMsg`) when the mouse enters a `Shape`.
-}
notifyEnter : userMsg -> Shape userMsg -> Shape userMsg
notifyEnter msg shape =
EnterShape msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse enters a `Shape`.
-}
notifyEnterAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyEnterAt msg shape =
EnterAt msg shape
{-| Receive a message (`userMsg`) when the mouse leaves a `Shape`.
-}
notifyLeave : userMsg -> Shape userMsg -> Shape userMsg
notifyLeave msg shape =
Exit msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse leaves a `Shape`.
-}
notifyLeaveAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyLeaveAt msg shape =
ExitAt msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse is moved across a `Shape`.
-}
notifyMouseMoveAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyMouseMoveAt msg shape =
MoveOverAt msg shape
{-| Receive a message (`userMsg`) when the mouse button is pressed while the cursor is over a `Shape`.
-}
notifyMouseDown : userMsg -> Shape userMsg -> Shape userMsg
notifyMouseDown msg shape =
MouseDown msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse button is pressed while the cursor is over a `Shape`.
-}
notifyMouseDownAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyMouseDownAt msg shape =
MouseDownAt msg shape
{-| Receive a message (`userMsg`) when the mouse button is released while the cursor is over a `Shape`.
-}
notifyMouseUp : userMsg -> Shape userMsg -> Shape userMsg
notifyMouseUp msg shape =
MouseUp msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse button is released while the cursor is over a `Shape`.
-}
notifyMouseUpAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyMouseUpAt msg shape =
MouseUpAt msg shape
{-| Receive a message (`userMsg`) when the user begins touching a `Shape`.
-}
notifyTouchStart : userMsg -> Shape userMsg -> Shape userMsg
notifyTouchStart msg shape =
TouchStart msg shape
{-| Receive a message (`userMsg`) with the x and y position of the user's finger when the user begins touching a `Shape`.
-}
notifyTouchStartAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyTouchStartAt msg shape =
TouchStartAt msg shape
{-| Receive a message (`userMsg`) when the user lifts their finger off a `Shape`.
-}
notifyTouchEnd : userMsg -> Shape userMsg -> Shape userMsg
notifyTouchEnd msg shape =
TouchEnd msg shape
{-| Receive a message (`userMsg`) with the x and y position of the user's finger when the user lifts their finger off a `Shape`.
-}
notifyTouchEndAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyTouchEndAt msg shape =
TouchEndAt msg shape
{-| Receive a message (`userMsg`) with the x and y position of the user's finger when the user moves their finger over a `Shape`.
-}
notifyTouchMoveAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyTouchMoveAt msg shape =
TouchMoveAt msg shape
touchToPair : TouchPos -> ( Float, Float )
touchToPair tp =
case tp of
TouchPos x y ->
( x, -y )
mousePosDecoder =
D.map2 (\x y -> ( x, -y )) (D.field "offsetX" D.float) (D.field "offsetY" D.float)
onTapAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onTapAt msg =
Html.Events.on "click"
(D.map msg mousePosDecoder)
onEnterAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onEnterAt msg =
Html.Events.on "mouseover"
(D.map msg mousePosDecoder)
onLeaveAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onLeaveAt msg =
Html.Events.on "mouseleave"
(D.map msg mousePosDecoder)
onMoveAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onMoveAt msg =
Html.Events.on "mousemove"
(D.map msg mousePosDecoder)
onMouseDownAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onMouseDownAt msg =
Html.Events.on "mousedown"
(D.map msg mousePosDecoder)
onMouseUpAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onMouseUpAt msg =
Html.Events.on "mouseup"
(D.map msg mousePosDecoder)
onTouchStart : userMsg -> Html.Attribute userMsg
onTouchStart msg =
Html.Events.on "touchstart" (D.succeed msg)
onTouchStartAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onTouchStartAt msg =
Html.Events.on "touchstart"
(D.map (msg << touchToPair) touchDecoder)
onTouchEndAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onTouchEndAt msg =
Html.Events.on "touchend"
(D.map (msg << touchToPair) touchDecoder)
onTouchEnd : userMsg -> Html.Attribute userMsg
onTouchEnd msg =
Html.Events.on "touchend" (D.succeed msg)
onTouchMove : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onTouchMove msg =
Html.Events.preventDefaultOn "touchmove"
(D.map (\a -> ( (msg << touchToPair) a, True )) touchDecoder)
type TouchPos
= TouchPos Float Float
touchDecoder : Decoder TouchPos
touchDecoder =
D.oneOf
[ D.at
[ "touches", "0" ]
(D.map2
TouchPos
(D.field "pageX" D.float)
(D.field "pageY" D.float)
)
, D.map2
TouchPos
(D.field "pageX" D.float)
(D.field "pageY" D.float)
]
{-| Create Svg from a Shape. This is considered an advanced function and
is usually not used. Instead, use collage as part of a regular GraphicSVG
app or create a widget with GraphicSVG.Widget.
-}
createSVG : String -> Float -> Float -> Transform -> (a -> b) -> (((Float,Float) -> a) -> (Float,Float) -> b) -> Shape a -> Svg.Svg b
createSVG id w h trans msgWrapper positionWrapper shape =
case shape of
Inked fillClr lt stencil ->
let
( ( a, c, tx ), ( b, d, ty ) ) =
trans
attrs =
case fillClr of
Just (Gradient _) ->
clrAttrs ++ strokeAttrs
_ -> transAttrs ++ clrAttrs ++ strokeAttrs
transAttrs =
[ Svg.Attributes.transform <|
"matrix("
++ (String.concat <|
List.intersperse "," <|
List.map
String.fromFloat
[ a, -b, c, -d, tx, -ty ]
)
++ ")"
]
nonexistBody =
case fillClr of
Nothing -> True
_ -> False
clrAttrs =
case fillClr of
Nothing -> [ fill "none"]
Just (Solid bodyClr) ->
[ fill (mkRGB bodyClr)
, fillOpacity (mkAlpha bodyClr)
]
Just (Gradient _) ->
[
Svg.Attributes.id id
, fill (mkRGB <| Color.rgb 255 255 255)
]
strokeAttrs =
case lt of
Nothing ->
[]
Just ( Unbroken th, Solid strokeClr ) ->
let nonStroke =
let opcty = getAlpha strokeClr
in th <= 0 || opcty <= 0
in
if nonStroke then [] else
[ strokeWidth (String.fromFloat th)
, stroke (mkRGB strokeClr)
, strokeOpacity (mkAlpha strokeClr)
]
Just ( Broken dashes th, Solid strokeClr ) ->
let nonStroke =
let opcty = getAlpha strokeClr
in th <= 0 || opcty <= 0 ||
List.all (\( on, _ ) -> on == 0) dashes
in
if nonStroke then [] else
[ strokeWidth (String.fromFloat th)
, stroke (mkRGB strokeClr)
, strokeOpacity (mkAlpha strokeClr)
]
++ [ strokeDasharray <|
String.concat
(List.intersperse "," <|
List.map pairToString dashes
)
]
Just ( _, _ ) ->
[]
basicShape = case stencil of
Circle r ->
Svg.circle
([ cx "0"
, cy "0"
, Svg.Attributes.r (String.fromFloat r)
]
++ attrs
)
[]
Rect rw rh ->
Svg.rect
([ x <| String.fromFloat <| -rw / 2
, y <| String.fromFloat <| -rh / 2
, width <| String.fromFloat rw
, height <| String.fromFloat rh
]
++ attrs
)
[]
RoundRect rw rh r ->
Svg.rect
([ x <| String.fromFloat <| -rw / 2
, y <| String.fromFloat <| -rh / 2
, rx <| String.fromFloat r
, ry <| String.fromFloat r
, width <| String.fromFloat rw
, height <| String.fromFloat rh
]
++ attrs
)
[]
Oval ow oh ->
Svg.ellipse
([ cx "0"
, cy "0"
, rx <| String.fromFloat <| 0.5 * ow
, ry <| String.fromFloat <| 0.5 * oh
]
++ attrs
)
[]
Polygon vertices ->
Svg.polygon
([ points <|
String.concat <|
List.intersperse " " <|
List.map pairToString vertices
]
++ attrs
)
[]
Path vertices ->
Svg.polyline
([ points <|
String.concat <|
List.intersperse " " <|
List.map pairToString vertices
]
++ attrs
)
[]
BezierPath start pts ->
Svg.path
([ Svg.Attributes.d <| createBezierString start pts ]
++ attrs
)
[]
Text (Face si bo i u s sel f align) str ->
let
bol =
if bo then
"font-weight: bold;"
else
""
it =
if i then
"font-style: italic;"
else
""
txtDec =
if u && s then
"text-decoration: underline line-through;"
else if u then
"text-decoration: underline;"
else if s then
"text-decoration: line-through;"
else
""
select =
if not sel then
"-webkit-touch-callout: none;\n-webkit-user-select: none;\n-khtml-user-select: none;\n-moz-user-select: none;\n-ms-user-select: none;\nuser-select: none;cursor: default;"
else
""
anchor =
case align of
AlignCentred ->
"middle"
AlignLeft ->
"start"
AlignRight ->
"end"
font =
case f of
Sansserif ->
"sans-serif;"
Serif ->
"serif;"
FixedWidth ->
"monospace;"
Custom fStr ->
fStr ++ ";"
sty =
bol
++ it
++ txtDec
++ "font-family: "
++ font
++ select
in
Svg.text_
([ x "0"
, y "0"
, Svg.Attributes.style sty
, Svg.Attributes.fontSize (String.fromFloat si)
, Svg.Attributes.textAnchor anchor
, Html.Attributes.contenteditable True
]
++ [ Svg.Attributes.transform <|
"matrix("
++ (String.concat <|
List.intersperse "," <|
List.map
String.fromFloat
[ a, -b, -c, d, tx, -ty ]
)
++ ")"
]
++ [ Svg.Attributes.xmlSpace "preserve" ]
++ clrAttrs ++ strokeAttrs
)
[ Svg.text str ]
gradientDefs =
case fillClr of
Just (Gradient gr) ->
Just (createGradientSVG id (w, h) gr)
_ -> Nothing
in
if nonexistBody && List.isEmpty strokeAttrs then Svg.g [] []
else case gradientDefs of
Just gDefs ->
Svg.g transAttrs
[
Svg.mask [Svg.Attributes.id (id ++ "mask")]
[
basicShape
]
, gDefs
]
Nothing ->
basicShape
ForeignObject fw fh htm ->
let
( ( a, c, tx ), ( b, d, ty ) ) =
trans
in
Svg.foreignObject
[ width <| String.fromFloat fw
, height <| String.fromFloat fh
, Svg.Attributes.transform
<| "matrix(" ++ (String.concat <| List.intersperse ","
<| List.map
String.fromFloat
[ a, -b, -c, d, tx, -ty ]) ++ ")"
] [ Html.map msgWrapper htm ]
Move v sh ->
createSVG id w h (moveT v trans) msgWrapper positionWrapper sh
Everything ->
createSVG id w h ident msgWrapper positionWrapper (rect w h |> filled white)
Notathing ->
createSVG id w h ident msgWrapper positionWrapper (rect w h |> filled black)
Rotate deg sh ->
createSVG id w h (rotateT deg trans) msgWrapper positionWrapper sh
Scale sx sy sh ->
createSVG id w h (scaleT sx sy trans) msgWrapper positionWrapper sh
Skew sx sy sh ->
createSVG id w h (skewT sx sy trans) msgWrapper positionWrapper sh
Transformed tm sh ->
createSVG id w h (matrixMult trans tm) msgWrapper positionWrapper sh
Link href sh ->
Svg.a
[ xlinkHref href, target "_blank" ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
AlphaMask region sh ->
Svg.g []
[ Svg.defs []
[ Svg.mask
[ Svg.Attributes.id ("m" ++ id) ]
[ createSVG
(id ++ "m")
w
h
trans
msgWrapper
positionWrapper
(Group [ Everything, region |> repaint black ])
]
]
, Svg.g
[ Svg.Attributes.mask ("url(#m" ++ id ++ ")") ]
[ createSVG (id ++ "mm") w h trans msgWrapper positionWrapper sh ]
]
Clip region sh ->
Svg.g []
[ Svg.defs []
[ Svg.mask
[ Svg.Attributes.id ("c" ++ id) ]
[ createSVG
(id ++ "c")
w
h
trans
msgWrapper
positionWrapper
(Group [ Notathing, region |> repaint white ])
]
]
, Svg.g
[ Svg.Attributes.mask ("url(#c" ++ id ++ ")") ]
[ createSVG (id ++ "cc") w h trans msgWrapper positionWrapper sh ]
]
Tap msg sh ->
Svg.g
[ Html.Events.onClick (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TapAt msg sh ->
Svg.g
[ onTapAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
EnterShape msg sh ->
Svg.g
[ Html.Events.onMouseEnter (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
EnterAt msg sh ->
Svg.g
[ onEnterAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
Exit msg sh ->
Svg.g
[ Html.Events.onMouseLeave (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
ExitAt msg sh ->
Svg.g
[ onLeaveAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MouseDown msg sh ->
Svg.g
[ Html.Events.onMouseDown (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MouseDownAt msg sh ->
Svg.g
[ onMouseDownAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MouseUp msg sh ->
Svg.g
[ Html.Events.onMouseUp (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MouseUpAt msg sh ->
Svg.g
[ onMouseUpAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MoveOverAt msg sh ->
Svg.g
[ onMoveAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchStart msg sh ->
Svg.g
[ onTouchStart (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchEnd msg sh ->
Svg.g
[ onTouchEnd (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchStartAt msg sh ->
Svg.g
[ onTouchStartAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchEndAt msg sh ->
Svg.g
[ onTouchStartAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchMoveAt msg sh ->
Svg.g
[ onTouchMove (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
Group shapes ->
Svg.g [] <|
List.indexedMap
(\n ->
createSVG
(id ++ "g" ++ String.fromInt n)
w
h
trans
msgWrapper
positionWrapper
)
shapes
GroupOutline cmbndshp ->
createSVG id w h trans msgWrapper positionWrapper cmbndshp
GraphPaper s th c ->
if th <= 0 || s < 2 * th then
Svg.g [] []
else
createSVG id w h trans msgWrapper positionWrapper <|
createGraph ( w, h ) s th c
{-| Display HTML inside an SVG foreignObject.
-}
html : Float -> Float -> Html.Html userMsg -> Shape userMsg
html w h htm =
ForeignObject w h htm
--Filling / outlining functions
{-| Fill a `Stencil` with a `Color`, creating a `Shape`;
Note that any `Stencil` converted to a `Shape` this way can be made
transparent (for instance by using the `blank` `Color`) but will not be
"click-through", meaning that the body will catch any attached notifications
and not let them through to any visible `Shape`(s) revealed beneath them.
circle 10
|> filled red
-}
filled : Color -> Stencil -> Shape userMsg
filled color stencil =
Inked (Just color) Nothing stencil
{-| Make a `Shape` into a ghost. Mostly to be used inside of the clip operations.
Note that although the `blank` `Color` is transparent, it will still catch
notifications enabled on the `Shape` or block them if not enabled on the `Shape`.
-}
ghost : Stencil -> Shape userMsg
ghost stencil =
Inked (Just blank) Nothing stencil
{-| Repaint an already-`filled` `Shape`. This is helpful for repainting every `Shape` inside a `group` as well.
Repaints the outline the same color as the body of the shape including the outline, if used;
Note that this can repaint with a transparent `Color` (for instance, the `blank` `Color`) but
will never have the ability to be "click-through" so that it will always block (or catch)
notifications to covered `Shape`(s) revealed beneath.
group
[ circle 10
|> filled orange
, rect 10 40
|> filled blue
]
|> repaint green
-}
repaint : Color -> Shape userMsg -> Shape userMsg
repaint color shape =
case shape of
Inked _ Nothing st ->
Inked (Just color) Nothing st
Inked _ (Just ( lt, _ )) st ->
Inked (Just color) (Just ( lt, color )) st
Move s sh ->
Move s (repaint color sh)
Rotate r sh ->
Rotate r (repaint color sh)
Scale sx sy sh ->
Scale sx sy (repaint color sh)
Skew skx sky sh ->
Skew skx sky (repaint color sh)
Transformed tm sh ->
Transformed tm (repaint color sh)
Group shapes ->
Group (List.map (repaint color) shapes)
GroupOutline cmbndshp ->
GroupOutline (repaint color cmbndshp)
Link s sh ->
Link s (repaint color sh)
AlphaMask reg sh ->
AlphaMask reg (repaint color sh)
Clip reg sh ->
Clip reg (repaint color sh)
Tap userMsg sh ->
Tap userMsg (repaint color sh)
TapAt userMsg sh ->
TapAt userMsg (repaint color sh)
EnterShape userMsg sh ->
EnterShape userMsg (repaint color sh)
EnterAt userMsg sh ->
EnterAt userMsg (repaint color sh)
Exit userMsg sh ->
Exit userMsg (repaint color sh)
ExitAt userMsg sh ->
ExitAt userMsg (repaint color sh)
MouseDown userMsg sh ->
MouseDown userMsg (repaint color sh)
MouseDownAt userMsg sh ->
MouseDownAt userMsg (repaint color sh)
MouseUp userMsg sh ->
MouseUp userMsg (repaint color sh)
MouseUpAt userMsg sh ->
MouseUpAt userMsg (repaint color sh)
MoveOverAt userMsg sh ->
MoveOverAt userMsg (repaint color sh)
TouchStart userMsg sh ->
TouchStart userMsg (repaint color sh)
TouchEnd userMsg sh ->
TouchEnd userMsg (repaint color sh)
TouchStartAt userMsg sh ->
TouchStartAt userMsg (repaint color sh)
TouchEndAt userMsg sh ->
TouchEndAt userMsg (repaint color sh)
TouchMoveAt userMsg sh ->
TouchMoveAt userMsg (repaint color sh)
-- no changes for the rest...
ForeignObject w h htm ->
ForeignObject w h htm
Everything ->
Everything
Notathing ->
Notathing
GraphPaper s th _ ->
GraphPaper s th color
{-| Outline a Stencil with a `LineType` and `Color`, creating a `Shape`;
Note that this is the only way to convert a `Stencil` into a `Shape` that is
"click-through" as if the body is not just transparent but doesn't exist at all.
It works for all `Stencil`'s except for `Text` which can never be made "click-through"
due to a permanent transparent background area that cannot be disabled.
circle 10
|> outlined (solid 5) red
-}
outlined : LineType -> Color -> Stencil -> Shape userMsg
outlined style outlineClr stencil =
let
lineStyle =
case style of
NoLine ->
Nothing
_ ->
Just ( style, outlineClr )
in
Inked Nothing lineStyle stencil
{-| Add an outline to an already-filled `Shape`.
When applied to `Group`'s including `Shape`'s that have had `union` applied to them,
the outline will have half the expected stroke width only outside the `Shape`'s and
for `Shape`'s with `clip` or `subtract` applied to them, the half width stroke will be
interior to the composite shapes displayed.
The limitation is that when displaying "clip's" or "subtract's" containing "Group's",
the outline for the "Group's" won't be visibile at all (less common), nor will the
outline's for "clip's" or "subtract's" inside "Group's" be visible (more common);
also, the outline for the clipping or subtraction pattern may not be as expected when
the pattern is a "Group" as it won't appear at all in a "clip".
In these cases the workaround is just as before this was made available, to build up
the outlines desired using combinations of other shapes such as curves, clipped or
subtracted shapes, convential pre-applied outlines, etc.
Note that when applied to `Group`(s), `Clip`(s), and `AlphaMask`(s) (from subtracts),
the body colour may still be transparent so that `Shape`(s) can be revealed beneath,
but the bodies are not "click-through" so that notifications can be passed through to them,
and the transparent bodies can still capture notifications enabled on the resulting `Shape`(s).
circle 10
|> filled red
|> addOutline (solid 5) white
-}
addOutline : LineType -> Color -> Shape userMsg -> Shape userMsg
addOutline style outlineClr shape =
let
lineStyle =
case style of
NoLine ->
Nothing
_ ->
Just ( style, outlineClr )
in
case shape of
Inked clr _ st ->
Inked clr lineStyle st
Move s sh ->
Move s (addOutline style outlineClr sh)
Rotate r sh ->
Rotate r (addOutline style outlineClr sh)
Scale sx sy sh ->
Scale sx sy (addOutline style outlineClr sh)
Skew skx sky sh ->
Skew skx sky (addOutline style outlineClr sh)
Transformed tm sh ->
Transformed tm (addOutline style outlineClr sh)
Group list ->
let
innerlist =
List.filterMap
(\shp ->
case shp of
-- remove old outline shape
GroupOutline _ ->
Nothing
_ ->
Just <| addOutline NoLine black shp
)
list
in
case innerlist of
[] ->
{- should never happen -}
Group []
hd :: [] ->
addOutline style outlineClr hd
_ ->
if lineStyle == Nothing then
Group innerlist
else
let
outlnshp =
GroupOutline <|
subtract
(Group innerlist)
(Group
(List.map
(addOutline style outlineClr)
innerlist
)
)
in
Group <| innerlist ++ [ outlnshp ]
-- don't add an outline to one that's already been added but it should
-- never get here as GroupOutline should always be inside a Group which
-- will already have processed it, whether to change or remove it...
GroupOutline cmbndshp ->
GroupOutline cmbndshp
AlphaMask reg sh ->
let
ptrn =
addOutline NoLine black reg
inside =
addOutline NoLine black sh
in
if lineStyle == Nothing then
AlphaMask ptrn inside
else
let
ptrnlnd =
addOutline style outlineClr reg
newshp =
addOutline style outlineClr sh
ptrnoutln =
Clip inside ptrnlnd
shpoutln =
Clip inside newshp
in
AlphaMask ptrn <|
Group
[ inside
, GroupOutline <| Group [ shpoutln, ptrnoutln ]
]
Clip reg sh ->
let
ptrn =
addOutline NoLine black reg
inside =
addOutline NoLine black sh
in
if lineStyle == Nothing then
Clip ptrn inside
else
let
ptrnlnd =
addOutline style outlineClr (reg |> repaint blank)
newshp =
addOutline style outlineClr sh
ptrnoutln =
Clip inside ptrnlnd
shpoutln =
Clip inside newshp
in
Clip ptrn <|
Group
[ inside
, GroupOutline <| Group [ shpoutln, ptrnoutln ]
]
Link s sh ->
Link s (addOutline style outlineClr sh)
Tap userMsg sh ->
Tap userMsg (addOutline style outlineClr sh)
TapAt userMsg sh ->
TapAt userMsg (addOutline style outlineClr sh)
EnterShape userMsg sh ->
EnterShape userMsg (addOutline style outlineClr sh)
EnterAt userMsg sh ->
EnterAt userMsg (addOutline style outlineClr sh)
Exit userMsg sh ->
Exit userMsg (addOutline style outlineClr sh)
ExitAt userMsg sh ->
ExitAt userMsg (addOutline style outlineClr sh)
MouseDown userMsg sh ->
MouseDown userMsg (addOutline style outlineClr sh)
MouseDownAt userMsg sh ->
MouseDownAt userMsg (addOutline style outlineClr sh)
MouseUp userMsg sh ->
MouseUp userMsg (addOutline style outlineClr sh)
MouseUpAt userMsg sh ->
MouseUpAt userMsg (addOutline style outlineClr sh)
MoveOverAt userMsg sh ->
MoveOverAt userMsg (addOutline style outlineClr sh)
TouchStart userMsg sh ->
TouchStart userMsg (addOutline style outlineClr sh)
TouchEnd userMsg sh ->
TouchEnd userMsg (addOutline style outlineClr sh)
TouchStartAt userMsg sh ->
TouchStartAt userMsg (addOutline style outlineClr sh)
TouchEndAt userMsg sh ->
TouchEndAt userMsg (addOutline style outlineClr sh)
TouchMoveAt userMsg sh ->
TouchMoveAt userMsg (addOutline style outlineClr sh)
-- no changes for the rest...
ForeignObject w h htm ->
ForeignObject w h htm
Everything ->
Everything
Notathing ->
Notathing
GraphPaper s th clr ->
GraphPaper s th clr
multAlpha : Color.Color -> Float -> Color.Color
multAlpha color n =
let
colRec = Color.toRgba color
in
Color.fromRgba { colRec | alpha = colRec.alpha * n }
{-| Make a `Shape` transparent by the fraction given. Multiplies on top of other transparencies:
circle 10
|> filled red
|> makeTransparent 0.5
--results in a transparency of 0.5 (half vislible)
circle 10
|> filled red
|> makeTransparent 0.5
|> makeTransparent 0.5
--results in a transparency of 0.25 (a quarter visible)
-}
makeTransparent : Float -> Shape userMsg -> Shape userMsg
makeTransparent alpha shape =
case shape of
Inked Nothing (Just ( lineType, Solid colour )) st ->
Inked Nothing (Just ( lineType, Solid (multAlpha colour alpha))) st
Inked (Just (Solid colour)) (Just ( lineType, Solid sColour )) st ->
Inked (Just <| Solid (multAlpha colour alpha))
(Just ( lineType, Solid <| multAlpha sColour alpha)) st
Inked (Just (Solid colour)) Nothing st ->
Inked (Just <| Solid (multAlpha colour alpha)) Nothing st
Inked a b c ->
Inked a b c
ForeignObject w h htm ->
ForeignObject w h htm
Move s sh ->
Move s (makeTransparent alpha sh)
Rotate r sh ->
Rotate r (makeTransparent alpha sh)
Scale sx sy sh ->
Scale sx sy (makeTransparent alpha sh)
Skew skx sky sh ->
Skew skx sky (makeTransparent alpha sh)
Transformed tm sh ->
Transformed tm (makeTransparent alpha sh)
Group list ->
Group (List.map (makeTransparent alpha) list)
GroupOutline cmbndshp ->
GroupOutline (makeTransparent alpha cmbndshp)
Link s sh ->
Link s (makeTransparent alpha sh)
AlphaMask reg sh ->
AlphaMask reg (makeTransparent alpha sh)
Clip reg sh ->
Clip reg (makeTransparent alpha sh)
Everything ->
Everything
Notathing ->
Notathing
Tap userMsg sh ->
Tap userMsg (makeTransparent alpha sh)
TapAt userMsg sh ->
TapAt userMsg (makeTransparent alpha sh)
EnterShape userMsg sh ->
EnterShape userMsg (makeTransparent alpha sh)
EnterAt userMsg sh ->
EnterAt userMsg (makeTransparent alpha sh)
Exit userMsg sh ->
Exit userMsg (makeTransparent alpha sh)
ExitAt userMsg sh ->
ExitAt userMsg (makeTransparent alpha sh)
MouseDown userMsg sh ->
MouseDown userMsg (makeTransparent alpha sh)
MouseDownAt userMsg sh ->
MouseDownAt userMsg (makeTransparent alpha sh)
MouseUp userMsg sh ->
MouseUp userMsg (makeTransparent alpha sh)
MouseUpAt userMsg sh ->
MouseUpAt userMsg (makeTransparent alpha sh)
MoveOverAt userMsg sh ->
MoveOverAt userMsg (makeTransparent alpha sh)
TouchStart userMsg sh ->
TouchStart userMsg (makeTransparent alpha sh)
TouchEnd userMsg sh ->
TouchEnd userMsg (makeTransparent alpha sh)
TouchStartAt userMsg sh ->
TouchStartAt userMsg (makeTransparent alpha sh)
TouchEndAt userMsg sh ->
TouchEndAt userMsg (makeTransparent alpha sh)
TouchMoveAt userMsg sh ->
TouchMoveAt userMsg (makeTransparent alpha sh)
GraphPaper s th (Solid colour) ->
GraphPaper s th (Solid <| multAlpha colour alpha)
GraphPaper s th (Gradient gr) ->
GraphPaper s th (Gradient gr)
--Line styles
{-| Define a`LineType` that doesn't exist, doesn't appear.
-}
noline : () -> LineType
noline () =
NoLine
{-| Define a solid `LineType` with the given width.
-}
solid : Float -> LineType
solid th =
Unbroken th
{-| Define a dotted `LineType` with the given width.
-}
dotted : Float -> LineType
dotted th =
Broken [ ( th, th ) ] th
{-| Define a dashed `LineType` with the given width. Dashes are short line segments, versus dots which are theoretically points, but may be drawn with very short line segments.
-}
dashed : Float -> LineType
dashed th =
Broken [ ( th * 5, th * 2.5 ) ] th
{-| Define a dashed `LineType` with the given width, where the dashes are longer than normal.
-}
longdash : Float -> LineType
longdash th =
Broken [ ( th * 12, th * 6 ) ] th
{-| Define a `LineType` with the given width, including alternating dots and dashes.
-}
dotdash : Float -> LineType
dotdash th =
Broken [ ( th, th ), ( th * 5, th ) ] th
{-| A custom line defined by a list of (on,off):
custom [ ( 10, 5 ) ] 5 -- a line with dashes 10 long and spaces 5 long
custom [ ( 10, 5 ), ( 20, 5 ) ] -- on for 10, off 5, on 20, off 5
-}
custom : List ( Float, Float ) -> Float -> LineType
custom list th =
Broken list th
makePair : a -> ( a, a )
makePair n =
( n, n )
--Text functions
{-| Apply to a `text` `Stencil` to change the font size of the text.
The size has a unit called "points", which depends on the size and type of screen used, but try 12 to start.
-}
size : Float -> Stencil -> Stencil
size sze stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face sze bo i u s sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to make the text bold.
-}
bold : Stencil -> Stencil
bold stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si True i u s sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to make the text italicized (slanted).
-}
italic : Stencil -> Stencil
italic stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo True u s sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to underline the text.
-}
underline : Stencil -> Stencil
underline stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i True s sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to put a line through the centre of the text.
-}
strikethrough : Stencil -> Stencil
strikethrough stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u True sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to make the text selectable (so users can copy your text and paste it elsewhere).
-}
selectable : Stencil -> Stencil
selectable stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s True f c) str
a ->
a
{-| Apply to a `text` `Stencil` to right-align the text.
-}
alignRight : Stencil -> Stencil
alignRight stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel f AlignRight) str
a ->
a
{-| Apply to a `text` `Stencil` to centre the text.
-}
centered : Stencil -> Stencil
centered stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel f AlignCentred) str
a ->
a
{-| Apply to a `text` `Stencil` to left-align the text.
-}
alignLeft : Stencil -> Stencil
alignLeft stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel f AlignLeft) str
a ->
a
{-| Apply to a `text` `Stencil` to render the text with a Sans Serif font (ie one without thinner and thicker bits).
-}
sansserif : Stencil -> Stencil
sansserif stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel Sansserif c) str
a ->
a
{-| Apply to a `text` `Stencil` to render the text with a Serif font (ie one with thinner and thicker bits).
-}
serif : Stencil -> Stencil
serif stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel Serif c) str
a ->
a
{-| Apply to a text `Stencil` to render the text `Stencil` with a font in which every character has the same width.
This will mean that the letters line up from line to line which is important in programming languages like Elm.
-}
fixedwidth : Stencil -> Stencil
fixedwidth stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel FixedWidth c) str
a ->
a
{-| Apply to a `text` `Stencil` to render the text with a font of your choosing by specifying its name in a `String`.
_Use this sparingly as support for each font will vary across browsers and devices._
-}
customFont : String -> Stencil -> Stencil
customFont fStr stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel (Custom fStr) c) str
a ->
a
--Transformation functions
{-| Rotate a `Shape` by the specified amount (in radians). Use the `degrees` function to convert
from degrees into radians:
[
rect 30 60
|> filled blue
|> rotate(degrees 30)
]
-}
rotate : Float -> Shape userMsg -> Shape userMsg
rotate theta shape =
Rotate theta shape
{-| Move a `Shape` by a number of units along the x-axis and y-axis.
-}
move : ( Float, Float ) -> Shape userMsg -> Shape userMsg
move disp shape =
Move disp shape
{-| Scale a `Shape` by a given factor.
-}
scale : Float -> Shape userMsg -> Shape userMsg
scale s shape =
Scale s s shape
{-| Scale a `Shape` in the x-axis by a given factor.
-}
scaleX : Float -> Shape userMsg -> Shape userMsg
scaleX s shape =
Scale s 1 shape
{-| Scale a `Shape` in the y-axis by a given factor.
-}
scaleY : Float -> Shape userMsg -> Shape userMsg
scaleY s shape =
Scale 1 s shape
{-| Flip a `Shape` along the x-axis.
-}
mirrorX : Shape userMsg -> Shape userMsg
mirrorX shape =
Scale -1 1 shape
{-| Flip a `Shape` along the y-axis.
-}
mirrorY : Shape userMsg -> Shape userMsg
mirrorY shape =
Scale 1 -1 shape
{-| Skew a `Shape` along the x-axis.
-}
skewX : Float -> Shape userMsg -> Shape userMsg
skewX skx shape =
Skew skx 0 shape
{-| Skew a `Shape` along the y-axis.
-}
skewY : Float -> Shape userMsg -> Shape userMsg
skewY sky shape =
Skew 0 sky shape
{-| Combine any number of `Shape` types into one `Shape` that can be
transformed (moved, rotated, scaled, etc) as one `Shape`.
-}
group : List (Shape userMsg) -> Shape userMsg
group shapes =
Group shapes
{-| Define a colour given its red, green and blue components.
-}
rgb : Float -> Float -> Float -> Color
rgb r g b =
rgba r g b 1
{-| Define a colour given its red, green, blue and alpha components.
Alpha is a decimal number (`Float`) from 0 to 1 representing the level of transparency.
-}
rgba : Float -> Float -> Float -> Float -> Color
rgba r g b a =
Solid <| Color.fromRgba { red = ssc r, green = ssc g, blue = ssc b, alpha = ssa a }
ssc : number -> number
ssc n =
clamp 0 255 n
ssa : Float -> Float
ssa n =
clamp 0 1 n
pairToString : ( Float, Float ) -> String
pairToString ( x, y ) =
String.fromFloat x ++ "," ++ String.fromFloat y
createBezierString : ( Float, Float ) -> List ( ( Float, Float ), ( Float, Float ) ) -> String
createBezierString first list =
"M " ++ pairToString first ++ String.concat (List.map bezierStringHelper list)
bezierStringHelper : ( ( Float, Float ), ( Float, Float ) ) -> String
bezierStringHelper ( ( a, b ), ( c, d ) ) =
" Q " ++ pairToString ( a, b ) ++ " " ++ pairToString ( c, d )
getAlpha : Color.Color -> Float
getAlpha colour =
(Color.toRgba colour).alpha
mkAlpha : Color.Color -> String
mkAlpha =
String.fromFloat << getAlpha
mkRGB : Color.Color -> String
mkRGB colour =
let
col = Color.toRgba colour
in
"rgba(" ++ (String.fromFloat col.red) ++ "," ++ (String.fromFloat col.green) ++ "," ++ (String.fromFloat col.blue) ++ "," ++ (String.fromFloat col.alpha) ++ ")"
{-| Define a colour given its hue, saturation and light components.
-}
hsl : Float -> Float -> Float -> Color
hsl h s l =
case convert h s l of
( r, g, b ) ->
rgba r g b 1
{-| Define a colour given its hue, saturation, light and alpha components.
Alpha is a decimal number (`Float`) from 0 to 1 representing the level of transparency.
-}
hsla : Float -> Float -> Float -> Float -> Color
hsla h s l a =
case convert h s l of
( r, g, b ) ->
rgba r g b a
-- Clip path functionality
{-| Clipping to a shape
Cut out the `Shape` on the right using the `Shape` on the left.
-}
clip : Shape userMsg -> Shape userMsg -> Shape userMsg
clip shape1 shape2 =
Clip shape1 shape2
{-| Shape union
Combine two `Shape`s together into one to use with clip.
-}
union : Shape userMsg -> Shape userMsg -> Shape userMsg
union shape1 shape2 =
Group [ shape1, shape2 ]
{-| Shape subtraction
Subtract the `Shape` on the left from the `Shape` on the right.
-}
subtract : Shape userMsg -> Shape userMsg -> Shape userMsg
subtract shape1 shape2 =
AlphaMask shape1 shape2
{-| The whole region outside the given `Shape`.
-}
outside : Shape userMsg -> Shape userMsg
outside shape =
AlphaMask shape shape
{-
Contributed by Jack You.
-}
convert : Float -> Float -> Float -> ( Float, Float, Float )
convert hue sat lit =
let
hue_ =
modFloat hue (2 * pi)
rgb_ =
toRGB_ hue_ sat lit
chroma =
findChroma lit sat
m =
findM lit chroma
in
mapTriple (\x -> x * 255) (mapTriple (\x -> x + m) rgb_)
findChroma : Float -> Float -> Float
findChroma lit sat =
(1 - abs (2 * lit - 1)) * sat
findHue_ : Float -> Float
findHue_ hue =
hue / degrees 60
findX : Float -> Float -> Float
findX chroma hue =
chroma * (1 - abs (modFloat (findHue_ hue) 2 - 1))
findM : Float -> Float -> Float
findM lit chroma =
lit - 0.5 * chroma
toRGB_ : Float -> Float -> Float -> ( Float, Float, Float )
toRGB_ hue sat lit =
let
chroma =
findChroma lit sat
hue_ =
findHue_ hue
x =
findX chroma hue
in
if hue_ >= 0 && hue_ < 1 then
( chroma, x, 0 )
else if hue_ >= 1 && hue_ < 2 then
( x, chroma, 0 )
else if hue_ >= 2 && hue_ < 3 then
( 0, chroma, x )
else if hue_ >= 3 && hue_ < 4 then
( 0, x, chroma )
else if hue_ >= 4 && hue_ < 5 then
( x, 0, chroma )
else if hue_ >= 5 && hue_ < 6 then
( chroma, 0, x )
else
( 0, 0, 0 )
{- Helper Functions -}
modFloat : Float -> Float -> Float
modFloat x m =
x - m * Basics.toFloat (floor (x / m))
mapTriple : (a -> b) -> ( a, a, a ) -> ( b, b, b )
mapTriple f ( a1, a2, a3 ) =
( f a1, f a2, f a3 )
-- Colours
{-| -}
pink : Color
pink =
rgba 255 105 180 1
{-| -}
hotPink : Color
hotPink =
rgba 255 0 66 1
{-| -}
lightRed : Color
lightRed =
rgba 239 41 41 1
{-| -}
red : Color
red =
rgba 204 0 0 1
{-| -}
darkRed : Color
darkRed =
rgba 164 0 0 1
{-| -}
lightOrange : Color
lightOrange =
rgba 252 175 62 1
{-| -}
orange : Color
orange =
rgba 245 121 0 1
{-| -}
darkOrange : Color
darkOrange =
rgba 206 92 0 1
{-| -}
lightYellow : Color
lightYellow =
rgba 255 233 79 1
{-| -}
yellow : Color
yellow =
rgba 237 212 0 1
{-| -}
darkYellow : Color
darkYellow =
rgba 196 160 0 1
{-| -}
lightGreen : Color
lightGreen =
rgba 138 226 52 1
{-| -}
green : Color
green =
rgba 115 210 22 1
{-| -}
darkGreen : Color
darkGreen =
rgba 78 154 6 1
{-| -}
lightBlue : Color
lightBlue =
rgba 114 159 207 1
{-| -}
blue : Color
blue =
rgba 52 101 164 1
{-| -}
darkBlue : Color
darkBlue =
rgba 32 74 135 1
{-| -}
lightPurple : Color
lightPurple =
rgba 173 127 168 1
{-| -}
purple : Color
purple =
rgba 117 80 123 1
{-| -}
darkPurple : Color
darkPurple =
rgba 92 53 102 1
{-| -}
lightBrown : Color
lightBrown =
rgba 233 185 110 1
{-| -}
brown : Color
brown =
rgba 193 125 17 1
{-| -}
darkBrown : Color
darkBrown =
rgba 143 89 2 1
{-| -}
black : Color
black =
rgba 0 0 0 1
{-| -}
white : Color
white =
rgba 255 255 255 1
{-| -}
lightGrey : Color
lightGrey =
rgba 238 238 236 1
{-| -}
grey : Color
grey =
rgba 211 215 207 1
{-| -}
darkGrey : Color
darkGrey =
rgba 186 189 182 1
{-| -}
lightGray : Color
lightGray =
rgba 238 238 236 1
{-| -}
gray : Color
gray =
rgba 211 215 207 1
{-| -}
darkGray : Color
darkGray =
rgba 186 189 182 1
{-| -}
lightCharcoal : Color
lightCharcoal =
rgba 136 138 133 1
{-| -}
charcoal : Color
charcoal =
rgba 85 87 83 1
{-| -}
darkCharcoal : Color
darkCharcoal =
rgba 46 52 54 1
{-| -}
blank : Color
blank =
rgba 0 0 0 0
| 12471 | module GraphicSVG exposing
( Stencil, Shape, Collage(..), GraphicSVG
, collage, mapCollage
, App, app
, EllieApp, ellieApp
, line, polygon, openPolygon, ngon, triangle, rightTriangle, isosceles, sideAngleSide, square, rect, rectangle, roundedRect, circle, oval, wedge
, filled, outlined, repaint, addOutline, rgb, rgba, hsl, hsla
, group
, html
, curve, Pull(..), curveHelper
, LineType, noline, solid, dotted, dashed, longdash, dotdash, custom
, text, size, bold, italic, underline, strikethrough, centered, alignLeft, alignRight, selectable, sansserif, serif, fixedwidth, customFont
, move, rotate, scale, scaleX, scaleY, mirrorX, mirrorY, skewX, skewY
, clip, union, subtract, outside, ghost
, notifyTap, notifyTapAt, notifyEnter, notifyEnterAt, notifyLeave, notifyLeaveAt, notifyMouseMoveAt, notifyMouseDown, notifyMouseDownAt, notifyMouseUp, notifyMouseUpAt, notifyTouchStart, notifyTouchStartAt, notifyTouchEnd, notifyTouchEndAt, notifyTouchMoveAt
, makeTransparent, addHyperlink, puppetShow
, graphPaper, graphPaperCustom, map
, gradient, radialGradient, stop, transparentStop, rotateGradient
, Color, black, blank, blue, brown, charcoal, darkBlue, darkBrown, darkCharcoal, darkGray, darkGreen, darkGrey, darkOrange, darkPurple, darkRed, darkYellow, gray, green, grey, hotPink, lightBlue, lightBrown, lightCharcoal, lightGray, lightGreen, lightGrey, lightOrange, lightPurple, lightRed, lightYellow, orange, pink, purple, red, white, yellow
, Transform, ident, moveT, rotateT, scaleT, skewT, rotateAboutT, transform
, Msg(..), createSVG
)
{-| A library for creating SVG graphics in a way that is compatible with Elm's
old Graphics library. Also includes built-in functions for creating games and
other applications including keyboard presses and mouse movements.
# Basic Types
@docs Stencil, Shape, Collage, GraphicSVG
# Rendering To Screen
@docs collage, mapCollage
# App
@docs App, app
# EllieApp
@docs EllieApp, ellieApp
# Stencils
@docs line, polygon, openPolygon, ngon, triangle, rightTriangle, isosceles, sideAngleSide, square, rect, rectangle, roundedRect, circle, oval, wedge
# Creating Shapes from Stencils
@docs filled, outlined, repaint, addOutline, rgb, rgba, hsl, hsla
# Grouping Shapes
@docs group
# Rendering HTML
This feature is still very much experimental. Cross-platform support is
not guaranteed and weird things can happen.
@docs html
# Curves
@docs curve, Pull, curveHelper
# Line Styles
@docs LineType, noline, solid, dotted, dashed, longdash, dotdash, custom
# Text
@docs text, size, bold, italic, underline, strikethrough, centered, alignLeft, alignRight, selectable, sansserif, serif, fixedwidth, customFont
# Transformations
@docs move, rotate, scale, scaleX, scaleY, mirrorX, mirrorY, skewX, skewY
# Group Operations
@docs clip, union, subtract, outside, ghost
# Notifications
@docs notifyTap, notifyTapAt, notifyEnter, notifyEnterAt, notifyLeave, notifyLeaveAt, notifyMouseMoveAt, notifyMouseDown, notifyMouseDownAt, notifyMouseUp, notifyMouseUpAt, notifyTouchStart, notifyTouchStartAt, notifyTouchEnd, notifyTouchEndAt, notifyTouchMoveAt
# Miscellaneous
@docs makeTransparent, addHyperlink, puppetShow
# Helpers
@docs graphPaper, graphPaperCustom, map
# Let there be colours!
@docs Color, black, blank, blue, brown, charcoal, darkBlue, darkBrown, darkCharcoal, darkGray, darkGreen, darkGrey, darkOrange, darkPurple, darkRed, darkYellow, gray, green, grey, hotPink, lightBlue, lightBrown, lightCharcoal, lightGray, lightGreen, lightGrey, lightOrange, lightPurple, lightRed, lightYellow, orange, pink, purple, red, white, yellow
# Let there be gradients!
@docs stop, transparentStop, gradient, radialGradient, rotateGradient
# Advanced Transformations
_Advanced section warning!_ These functions provide a way to interface on a lower
level to the transformations normally handled in the background by GraphicSVG.
Most users should be happy to use the regular functions applied directly to shapes,
which are provided in the section above this one.
@docs Transform, ident, moveT, rotateT, scaleT, skewT, rotateAboutT, transform
# More Advanced Things
Don't worry about these unless you *_really_* know what you're doing!
@docs Msg, createSVG
-}
{- Library created by <NAME> and Dr. <NAME>
for the McMaster University Computing and Software Outreach Program
and CompSci 1JC3, with input and testing from the rest of the Outreach
team.
Last updated: January 25th, 2019
-}
import Array
import Browser exposing (UrlRequest)
import Browser.Dom exposing (Viewport, getViewportOf)
import Browser.Events exposing (onKeyDown, onKeyPress, onKeyUp, onResize)
import Browser.Navigation exposing (Key)
import Char
import Dict
import Html
import Html.Attributes
import Html.Events
import Json.Decode as D exposing (..)
import String exposing (..)
import Svg exposing (Attribute)
import Svg.Attributes exposing (..)
import Task
import Time exposing (..)
import Tuple
import Url exposing (Url)
import Color
{-| A primitive template representing the shape you wish to draw. This must be turned into
a `Shape` before being drawn to the screen with `collage` (see below).
-}
type Stencil
= Circle Float
| Rect Float Float
| RoundRect Float Float Float
| Oval Float Float
| BezierPath ( Float, Float ) (List ( ( Float, Float ), ( Float, Float ) ))
| Polygon (List ( Float, Float ))
| Path (List ( Float, Float ))
| Text Face String
{-| A filled, outlined, or filled and outlined object that can be drawn to the screen using `collage`.
-}
type Shape userMsg
= Inked (Maybe Color) (Maybe ( LineType, Color )) Stencil
| ForeignObject Float Float (Html.Html userMsg)
| Move ( Float, Float ) (Shape userMsg)
| Rotate Float (Shape userMsg)
| Scale Float Float (Shape userMsg)
| Skew Float Float (Shape userMsg)
| Transformed Transform (Shape userMsg)
| Group (List (Shape userMsg))
| GroupOutline (Shape userMsg)
| AlphaMask (Shape userMsg) (Shape userMsg)
| Clip (Shape userMsg) (Shape userMsg)
| Everything
| Notathing
| Link String (Shape userMsg)
| Tap userMsg (Shape userMsg)
| TapAt (( Float, Float ) -> userMsg) (Shape userMsg)
| EnterShape userMsg (Shape userMsg)
| EnterAt (( Float, Float ) -> userMsg) (Shape userMsg)
| Exit userMsg (Shape userMsg)
| ExitAt (( Float, Float ) -> userMsg) (Shape userMsg)
| MouseDown userMsg (Shape userMsg)
| MouseDownAt (( Float, Float ) -> userMsg) (Shape userMsg)
| MouseUp userMsg (Shape userMsg)
| MouseUpAt (( Float, Float ) -> userMsg) (Shape userMsg)
| MoveOverAt (( Float, Float ) -> userMsg) (Shape userMsg)
| TouchStart userMsg (Shape userMsg)
| TouchEnd userMsg (Shape userMsg)
| TouchStartAt (( Float, Float ) -> userMsg) (Shape userMsg)
| TouchEndAt (( Float, Float ) -> userMsg) (Shape userMsg)
| TouchMoveAt (( Float, Float ) -> userMsg) (Shape userMsg)
| GraphPaper Float Float Color
type FontAlign
= AlignLeft
| AlignCentred
| AlignRight
{-| To compose multiple pages or components which each have a Msg/view/update, we need to map messages.
(Ask if you don't know what this means.)
-}
map : (a -> b) -> Shape a -> Shape b
map f sh =
case sh of
Inked fillClr lt stencil ->
Inked fillClr lt stencil
ForeignObject w h htm ->
ForeignObject w h (Html.map f htm)
Move v shape ->
Move v (map f shape)
Rotate deg shape ->
Rotate deg (map f shape)
Scale sx sy shape ->
Scale sx sy (map f shape)
Skew skx sky shape ->
Skew skx sky (map f shape)
Transformed tm shape ->
Transformed tm (map f shape)
Link href shape ->
Link href (map f shape)
AlphaMask sh1 sh2 ->
AlphaMask (map f sh1) (map f sh2)
Clip sh1 sh2 ->
Clip (map f sh1) (map f sh2)
Everything ->
Everything
Notathing ->
Notathing
Tap msg shape ->
Tap (f msg) (map f shape)
TapAt msg shape ->
TapAt (f << msg) (map f shape)
EnterShape msg shape ->
EnterShape (f msg) (map f shape)
EnterAt msg shape ->
EnterAt (f << msg) (map f shape)
Exit msg shape ->
Exit (f msg) (map f shape)
ExitAt msg shape ->
ExitAt (f << msg) (map f shape)
MouseDown msg shape ->
MouseDown (f msg) (map f shape)
MouseDownAt msg shape ->
MouseDownAt (f << msg) (map f shape)
MouseUp msg shape ->
MouseUp (f msg) (map f shape)
MouseUpAt msg shape ->
MouseUpAt (f << msg) (map f shape)
MoveOverAt msg shape ->
MoveOverAt (f << msg) (map f shape)
TouchStart msg shape ->
TouchStart (f msg) (map f shape)
TouchEnd msg shape ->
TouchEnd (f msg) (map f shape)
TouchStartAt msg shape ->
TouchStartAt (f << msg) (map f shape)
TouchEndAt msg shape ->
TouchEndAt (f << msg) (map f shape)
TouchMoveAt msg shape ->
TouchMoveAt (f << msg) (map f shape)
Group shapes ->
Group (List.map (map f) shapes)
GroupOutline cmbndshp ->
GroupOutline (map f cmbndshp)
GraphPaper s th c ->
GraphPaper s th c
{-| To apply the function over all the shapes in the given `Collage` using the `map` function.
(Ask if you don't know what this means.)
-}
mapCollage : (a -> b) -> Collage a -> Collage b
mapCollage f (Collage w h shapes) =
Collage w h (List.map (map f) shapes)
{-| The `GraphicSVG` type alias represents the drawable surface of the window.
This type is only used to define a type signature for a user defined `view` as follows:
view : GraphicSVG.GraphicSVG userMsg
for use with `graphicsApp` and as follows:
view : Model -> GraphicSVG.GraphicSVG MyMsg
for use with `notificationsApp`, `gameApp` and `App`.
These assume that `Model` is the name of the user model type alias and
`MyMsg` is the name of the user message type. Simply substitute the names
actually used for these labels.
THIS IS DEPRECIATED AND ONLY KEPT FOR COMPATIBILITY WITH THE PREVIOUS VERSION;
Use "Collage userMsg" instead of "GraphicSVG userMsg", as they are identical except in name.
-}
type alias GraphicSVG userMsg =
Collage userMsg
{-| The `Color` type is used for filling or outlining a `Stencil`.
-}
type Color
= Solid Color.Color
| Gradient Gradient
type Gradient =
RadialGradient (List Stop)
| LinearGradient Float {- rotation -} (List Stop)
{-| Create a radial gradient from a list of colour stops.
-}
radialGradient : List Stop -> Color
radialGradient stops =
Gradient <| RadialGradient stops
{-| Create a linear gradient from a list of colour stops.
-}
gradient : List Stop -> Color
gradient stops =
Gradient <| LinearGradient 0 stops
{-| Rotate a linear gradient by a certain angle in radians.
-}
rotateGradient : Float -> Color -> Color
rotateGradient r grad =
case grad of
Gradient (LinearGradient rot stops) -> Gradient (LinearGradient (rot + r) stops)
radialGrad -> radialGrad
type Stop =
Stop Float {- stop position -} Float {- transparency -} Color.Color {- colour -}
{-| A colour stop in a gradient. This takes a colour and a position.
-}
stop : Color -> Float -> Stop
stop col pos =
case col of
Solid colour -> Stop pos 1 colour
_ -> Stop pos 1 (Color.rgba 0 0 0 0)
{-| A colour stop with transparency.
-}
transparentStop : Color -> Float -> Float -> Stop
transparentStop col pos alpha =
case col of
Solid colour -> Stop pos alpha colour
_ -> Stop pos 1 (Color.rgba 0 0 0 alpha)
createGradientSVG : String -> (Float, Float) -> Gradient -> Svg.Svg userMsg
createGradientSVG id (wid, hei) grad =
let
isRadial = case grad of
RadialGradient _ -> True
_ -> False
squareSize = if wid > hei then 2*wid else 2*hei
w = case grad of
RadialGradient stops ->
case List.head <| List.reverse stops of
Just (Stop pos _ _) -> pos
Nothing -> 0
LinearGradient _ stops ->
case List.head <| List.reverse stops of
Just (Stop pos _ _) -> pos
Nothing -> 0
createStop : Stop -> Svg.Svg userMsg
createStop (Stop pos trans colour) =
let
start = if isRadial then 0 else (1 - w/squareSize)/2 * 100
percent = if isRadial then pos / w * 100 else start + pos/squareSize * 100
percentTxt = String.fromFloat percent ++ "%"
colourTxt = "stop-color:" ++ mkRGB colour ++ ";"
opacityTxt = "stop-opacity:" ++ String.fromFloat trans ++ ";"
in
Svg.stop [Svg.Attributes.offset percentTxt, Svg.Attributes.style (colourTxt ++ opacityTxt)] []
defs = Svg.defs []
[
case grad of
LinearGradient _ stops ->
Svg.linearGradient
[ Svg.Attributes.id (id ++ "gradient")
, Svg.Attributes.gradientTransform <| "rotate(" ++ String.fromFloat rotation ++ "rad)"
--, Svg.Attributes.x1 "0%"
--, Svg.Attributes.y1 "0%"
--, Svg.Attributes.x2 "100%"
--, Svg.Attributes.y2 "0%"
, Svg.Attributes.gradientTransform ("rotate("++ String.fromFloat rotation ++ "rad)")
]
(List.map createStop stops)
RadialGradient stops ->
Svg.radialGradient
[ Svg.Attributes.id (id ++ "gradient")
, Svg.Attributes.cx "0"--(String.fromFloat (squareSize/2))
, Svg.Attributes.cy "0"--(String.fromFloat (squareSize/2))
, Svg.Attributes.r (String.fromFloat w)
, Svg.Attributes.gradientUnits "userSpaceOnUse"
]
(List.map createStop stops)
]
rotation =
case grad of
LinearGradient rot stops ->
rot * 180 / pi
_ -> 0
in
Svg.g [mask ("url(#" ++ id ++ "mask)")]
[ defs
, Svg.rect
([ x <| String.fromFloat <| -squareSize / 2
, y <| String.fromFloat <| -squareSize / 2
, width <| String.fromFloat squareSize
, height <| String.fromFloat squareSize
, fill ("url(#" ++ id ++ "gradient)")
, Svg.Attributes.id (id ++ "grad")
, Svg.Attributes.transform <| "rotate(" ++ String.fromFloat rotation ++")"
]
)
[]
]
{-| The `LineType` type is used to define the appearance of an outline for a `Stencil`.
`LineType` also defines the appearence of `line` and `curve`.
-}
type LineType
= NoLine
| Unbroken Float
| Broken (List ( Float, Float )) Float
{-| The `Face` type describes the appearance of a text `Stencil`.
THIS IS NOT EXPOSED BY ANY TYPE AND IS NOW NOT EXPOSED BY THE LIBARY.
-}
type Face
= Face
Float
-- size
Bool
-- bold
Bool
-- italic
Bool
-- underline
Bool
-- strikethrough
Bool
-- selectable
Font
-- font alignment
FontAlign
{-| The `Font` type describes the font of a text `Stencil`.
THIS IS NOT EXPOSED BY ANY TYPE AND IS NOW NOT EXPOSED BY THE LIBARY.
-}
type Font
= Serif
| Sansserif
| FixedWidth
| Custom String
{-| To make it easier to read the code defining a `curve`,
and to make sure we always use the right number of curve points
and pull points (which is one more curve point than pull points),
we define a special `Pull` type, whose first point is the point
we pull towards, and second point is the end point for this
curve segments.
-}
type Pull
= Pull ( Float, Float ) ( Float, Float )
{-| _Advanced Function Warning!_ `app` takes one parameter of its own type of the form:
{
init = \flags url key -> (model, cmd)
, view = \model -> { title = "Your Title goes here",
, body = view model
}
, update = \userMsg userModel -> ( userModel, Cmd userMsg )
, subscriptions = \userModel -> Sub userMsg
, onUrlRequest = \urlRequest -> userMsg
, onUrlChange = \url -> userMsg
}
This matches the Elm architecture and is analogous to `Browser.application`.
-}
app :
{ init : flags -> Url -> Key -> ( userModel, Cmd userMsg )
, update : userMsg -> userModel -> ( userModel, Cmd userMsg )
, view : userModel -> { title : String, body : Collage userMsg }
, subscriptions : userModel -> Sub userMsg
, onUrlRequest : UrlRequest -> userMsg
, onUrlChange : Url -> userMsg
}
-> App flags userModel userMsg
app input =
Browser.application
{ init =
\flags url key ->
let
userInit =
Tuple.first <| input.init flags url key
userView =
(input.view userInit).body
(Collage initW initH _) =
userView
userInitCmd =
Tuple.second <| input.init flags url key
in
( ( userInit, { initHiddenModel | cw = initW, ch = initH } ), initialCmd <| Cmd.map Graphics userInitCmd )
, update = hiddenAppUpdate input.view input.update
, view = hiddenAppView input.view
, subscriptions = subs <| input.subscriptions
, onUrlRequest = Graphics << input.onUrlRequest
, onUrlChange = Graphics << input.onUrlChange
}
{-| This type alias is only used as a target for a user `main` type signature to make
the type signature more clear and concise when `main` calls `app`:
main : App Flags Model Msg
main =
app Tick
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
, onUrlRequest = onUrlRequest
, onUrlChange = onUrlChange
}
where `Tick` is a message handler called once per browser window update,
`Flags` is the type alias (or type) of the flags input from JavaScript
`Model` is the type alias of the user persistent model, and
`Msg` is the name of the user message type; if other names are used,
they can just be substituted for these names.
Note that "type alias" could also be an ordinary "type" in all case,
just that the syntax for producing a new type is not as clean as using a
type alias for a record.
-}
type alias App flags userModel userMsg =
Program flags ( userModel, HiddenModel ) (Msg userMsg)
subs : (userModel -> Sub userMsg) -> ( userModel, gModel ) -> Sub (Msg userMsg)
subs userSubs ( userModel, _ ) =
Sub.batch
([ onResize (\_ _ -> WindowResize Nothing)
]
++ [ Sub.map Graphics (userSubs userModel) ]
)
hiddenAppUpdate :
(userModel -> { title : String, body : Collage userMsg })
-> (userMsg -> userModel -> ( userModel, Cmd userMsg ))
-> Msg userMsg
-> ( userModel, HiddenModel )
-> ( ( userModel, HiddenModel ), Cmd (Msg userMsg) )
hiddenAppUpdate userView userUpdate msg ( userModel, gModel ) =
let
mapUserCmd cmd =
Cmd.map Graphics cmd
(Collage cw ch _) =
(userView userModel).body
in
case msg of
Graphics message ->
let
( newModel, userCmds ) =
userUpdate message userModel
in
( ( newModel, { gModel | cw = cw, ch = ch } )
, mapUserCmd userCmds
)
WindowResize mWH ->
case mWH of
Just ( w, h ) ->
( ( userModel
, { gModel
| sw = Basics.toFloat w
, sh = Basics.toFloat h
}
)
, Cmd.none
)
Nothing ->
( (userModel, gModel)
, getViewportSize
)
ReturnPosition message ( x, y ) ->
let
( newModel, userCmds ) =
userUpdate
(message (convertCoords ( x, y ) gModel))
userModel
in
( ( newModel, gModel ), mapUserCmd userCmds )
NoOp -> (( userModel, gModel ), Cmd.none)
hiddenAppView :
(userModel -> { title : String, body : Collage userMsg })
-> ( userModel, HiddenModel )
-> { title : String, body : List (Html.Html (Msg userMsg)) }
hiddenAppView userView ( userModel, _ ) =
let
userViewEval =
userView userModel
title =
userViewEval.title
(Collage w h shapes) =
userViewEval.body
in
{ title = title, body = [ createCollage w h shapes ] }
{-| This type alias is only used as a target for a user `main` type signature to make
the type signature more clear and concise when `main` calls `ellieApp`:
main : EllieApp Flags Model Msg
main =
ellieApp Tick
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
}
where `Tick` is a message handler called once per browser window update,
`Flags` is the type alias (or type) of the flags input from JavaScript
`Model` is the type alias of the user persistent model, and
`Msg` is the name of the user message type; if other names are used,
they can just be substituted for these names.
Note that "type alias" could also be an ordinary "type" in all case,
just that the syntax for producing a new type is not as clean as using a
type alias for a record.
-}
type alias EllieApp flags userModel userMsg =
Program flags ( userModel, HiddenModel ) (Msg userMsg)
{-| _Advanced Function Warning!_ `ellieApp` takes one parameter of its own type of the form:
{
init = \flags url key -> (model, cmd)
, view = \model -> { title = "Your Title goes here",
, body = view model
}
, update = \userMsg userModel -> ( userModel, Cmd userMsg )
, subscriptions = \userModel -> Sub userMsg
}
This matches the Elm architecture and is analogous to `Browser.document`.
It is called ellieApp because this version is compatible with the online
Elm IDE Ellie.
-}
ellieApp :
{ init : flags -> ( userModel, Cmd userMsg )
, update : userMsg -> userModel -> ( userModel, Cmd userMsg )
, view : userModel -> { title : String, body : Collage userMsg }
, subscriptions : userModel -> Sub userMsg
}
-> EllieApp flags userModel userMsg
ellieApp input =
Browser.document
{ init =
\flags ->
let
userInit =
Tuple.first <| input.init flags
userView =
(input.view userInit).body
(Collage initW initH _) =
userView
userInitCmd =
Tuple.second <| input.init flags
in
( ( userInit, { initHiddenModel | cw = initW, ch = initH } ), initialCmd <| Cmd.map Graphics userInitCmd )
, update = hiddenAppUpdate input.view input.update
, view = hiddenAppView input.view
, subscriptions = subs <| input.subscriptions
}
convertCoords : ( Float, Float ) -> HiddenModel -> ( Float, Float )
convertCoords ( x, y ) gModel =
let
sw =
gModel.sw
sh =
gModel.sh
cw =
gModel.cw
ch =
gModel.ch
aspectout =
if not (sh == 0) then
sw / sh
else
4 / 3
aspectin =
if not (ch == 0) then
cw / ch
else
4 / 3
scaledInX =
aspectout < aspectin
scaledInY =
aspectout > aspectin
cscale =
if scaledInX then
sw / cw
else if scaledInY then
sh / ch
else
1
in
( (x - sw / 2) / cscale
, (y + sh / 2) / cscale
)
initialCmd :
Cmd (Msg userMsg)
-> Cmd (Msg userMsg)
initialCmd userCmd =
Cmd.batch
[ getViewportSize
, userCmd
]
getViewportSize : Cmd (Msg userMsg)
getViewportSize = Task.attempt
(\rvp -> case rvp of
Ok vp ->
WindowResize
<| Just ( round vp.viewport.width, round vp.viewport.height )
Err _ -> NoOp
)
(getViewportOf "render")
{-| The `Msg` type encapsulates all GraphicSVG internal messages.
This type is only used to define type signature fors user defined
`view` and `main` as follows:
view : GraphicSVG.Collage (GraphicSVG.Msg Msg)
for use with `graphicsApp` and `notificationsApp`, and as follows:
view : Model -> GraphicSVG.Collage (GraphicSVG.Msg Msg)
for use with `gameApp`.
It is also used to define the type signature for
a user supplied `main` as follows:
main : Program Never (GraphicsModel Model Msg) (GraphicSVG.Msg Msg)
for use with `graphicsApp` and `notificationsApp`, and as follows:
main : Program Never (GamesModel Model Msg) (GraphicSVG.Msg Msg)
for use when `main` calls `gameApp`
These assume that `Model` is the type alias of the user persistent model, and
`Msg` is the name of the user message type.
-}
type Msg userMsg
= Graphics userMsg
| WindowResize (Maybe ( Int, Int ))
| ReturnPosition (( Float, Float ) -> userMsg) ( Float, Float )
| NoOp
{-| The `HiddenModel` type alias encapsulates the GraphicSVG internal model
which is not exposed to user code.
-}
type alias HiddenModel =
{ cw : Float
, ch : Float
, sw : Float
, sh : Float
}
initHiddenModel : HiddenModel
initHiddenModel =
{ cw = 0
, ch = 0
, sw = 0
, sh = 0
}
{-| Create a line from a point to a point. Use `outlined` to convert to a viewable
`Shape`.
-}
line : ( Float, Float ) -> ( Float, Float ) -> Stencil
line p1 p2 =
Path [ p1, p2 ]
{-| Create a closed shape given a list of points. Can use `outlined` or `filled` to
convert to a `Shape`.
-}
polygon : List ( Float, Float ) -> Stencil
polygon ptList =
Polygon ptList
{-| Create an open shape given a list of points. Unlike with polygon, the first and
last points will not join up automatically. Can use `outlined` or `filled` to
convert to a `Shape`.
-}
openPolygon : List ( Float, Float ) -> Stencil
openPolygon ptList =
Path ptList
{-| Create a regular polygon with a given number of sides and radius. Examples:
ngon 3 50 -- triangle
ngon 5 50 -- pentagon
ngon 8 50 -- octogon
-}
ngon : Int -> Float -> Stencil
ngon n r =
Polygon <|
List.map
(ptOnCircle r (Basics.toFloat n) << Basics.toFloat)
(List.range 0 n)
{-| Synonym for `ngon 3`. Creates a triangle with a given size.
-}
triangle : Float -> Stencil
triangle r =
ngon 3 r
{-| Creates a right-angled triangle with a given base and height.
-}
rightTriangle : Float -> Float -> Stencil
rightTriangle base height =
polygon [ ( 0, 0 ), ( base, 0 ), ( 0, height ) ]
{-| Creates an isosceles triangle with a given base and height.
-}
isosceles : Float -> Float -> Stencil
isosceles base height =
polygon [ ( -base / 2, 0 ), ( base / 2, 0 ), ( 0, height ) ]
{-| Creates a triangle given two side lengths and the angle between them.
For example, `sideAngleSide 30 (degrees 45) 50` creates a triangle with side lengths
30 and 50 with an angle of 45 degrees between them.
-}
sideAngleSide : Float -> Float -> Float -> Stencil
sideAngleSide sideOne angle sideTwo =
polygon [ sideTwoPoint angle sideOne, ( 0, 0 ), ( sideTwo, 0 ) ]
sideTwoPoint : Float -> Float -> ( Float, Float )
sideTwoPoint angle sideOne =
( cos angle * sideOne, sin angle * sideOne )
{-| Creates a square with a given side length. (Synonym for `rect s s`)
-}
square : Float -> Stencil
square r =
Rect r r
{-| Creates a rectangle with a given width and height.
-}
rect : Float -> Float -> Stencil
rect w h =
Rect w h
{-| Synonym for `rect`.
-}
rectangle : Float -> Float -> Stencil
rectangle w h =
Rect w h
{-| Creates a rectangle with a given width, height, and circular rounded
corners with the given radius.
-}
roundedRect : Float -> Float -> Float -> Stencil
roundedRect w h r =
RoundRect w h r
{-| Creates a circle with a given radius.
-}
circle : Float -> Stencil
circle r =
Circle r
{-| Creates an oval with a given width and height.
-}
oval : Float -> Float -> Stencil
oval w h =
Oval w h
{-| Creates a graph paper with squares of a given size.
-}
graphPaper : Float -> Shape userMsg
graphPaper s =
GraphPaper s 1 (Solid <| Color.fromRgba { red = 135, green = 206, blue = 250, alpha = 1})
{-| Creates graph paper with squares of a given size, with a user-defined thickness and colour.
-}
graphPaperCustom : Float -> Float -> Color -> Shape userMsg
graphPaperCustom s th c =
GraphPaper s th c
createGraph : ( Float, Float ) -> Float -> Float -> Color -> Shape userMsg
createGraph ( w, h ) s th c =
let
sxi =
ceiling (w / (s * 2))
syi =
ceiling (h / (s * 2))
xlisti =
List.range -sxi sxi
ylisti =
List.range -syi syi
in
group
(List.map (createGraphX h s th c << Basics.toFloat) xlisti
++ List.map (createGraphY w s th c << Basics.toFloat) ylisti
)
createGraphX : Float -> Float -> Float -> Color -> Float -> Shape userMsg
createGraphX h s th c x =
filled c (rect th h) |> move ( x * s, 0 )
createGraphY : Float -> Float -> Float -> Color -> Float -> Shape userMsg
createGraphY w s th c y =
filled c (rect w th) |> move ( 0, y * s )
{-| Creates a wedge with a given radius, and a given fraction of a circle.
wedge 50 0.5 -- semi-circle
wedge 50 0.25 -- quarter-circle
wedge 50 0.75 -- three-quarter circle
-}
wedge : Float -> Float -> Stencil
wedge r frac =
let
n =
frac * 360 / 10 + 5
ni =
round n
dlta =
frac / Basics.toFloat ni
in
Polygon <|
if frac > 0 then
[ ( 0, 0 ), wedgeHelper r -frac ]
++ List.map
(wedgeHelper r
<< (*) dlta
<< Basics.toFloat
)
(List.range -ni ni)
++ [ wedgeHelper r frac, ( 0, 0 ) ]
else
[]
wedgeHelper : Float -> Float -> ( Float, Float )
wedgeHelper r cn =
let
angle =
turns (0.5 * cn)
in
( r * cos angle, r * sin angle )
ptOnCircle : Float -> Float -> Float -> ( Float, Float )
ptOnCircle r n cn =
let
angle =
turns (cn / n)
in
( r * cos angle, r * sin angle )
{-| Creates a curve starting at a point, pulled towards a point, ending at a third point. For example,
curve (0,0) [Pull (0,10) (0,20)]
gives a curve starting at (0,0), pulled towards (0,10) and ending at (0,20).
Think about curves as what you get when you take a bunch of
bendy sticks with their ends glued down to a board, and then pulling each stick
towards another point.
You always need an initial point and at least one `Pull`, but you can add as many `Pull`s as you want to
add additional curve segments, but each curve segment can only bend one way, since it is pulled in one direction.
-}
curve : ( Float, Float ) -> List Pull -> Stencil
curve ( a, b ) list =
BezierPath ( a, b ) (List.map curveListHelper list)
curveListHelper : Pull -> ( ( Float, Float ), ( Float, Float ) )
curveListHelper (Pull ( a, b ) ( c, d )) =
( ( a, b ), ( c, d ) )
{-| Add a hyperlink to any `Shape`:
circle 10
|> filled red
|> addHyperlink "http://outreach.mcmaster.ca"
-}
addHyperlink : String -> Shape userMsg -> Shape userMsg
addHyperlink link shape =
Link link shape
{-| Creates a text `Stencil`. You can change this `Stencil` using the text helper
functions. Note that `|> filled ...` or `|> outlined ...` must go at the _end_ of the text helper functions
(ie note that all these functions have type `Stencil -> Stencil`). For example,
text "Hello World"
|> fixedwidth
|> bold
|> size 14
|> filled black
-}
text : String -> Stencil
text str =
Text (Face 12 False False False False False Serif AlignLeft) str
{-| Apply to a curve or group of curves in order to view their start points,
end points and `Pull` points. Helpful while perfecting curves.
curve (0,0) [Pull (0,10) (0,20)]
|> curveHelper
-}
curveHelper : Shape userMsg -> Shape userMsg
curveHelper shape =
case shape of
Inked _ _ (BezierPath ( a, b ) list) ->
group [ shape, generateCurveHelper ( a, b ) list ]
Move s sh ->
Move s (curveHelper sh)
Rotate r sh ->
Rotate r (curveHelper sh)
Scale sx sy sh ->
Scale sx sy (curveHelper sh)
Skew skx sky sh ->
Skew skx sky (curveHelper sh)
Transformed tm sh ->
Transformed tm (curveHelper sh)
Group list ->
Group (List.map curveHelper list)
GroupOutline cmbndshp ->
GroupOutline (curveHelper cmbndshp)
Link s sh ->
Link s (curveHelper sh)
AlphaMask reg sh ->
AlphaMask reg (curveHelper sh)
Clip reg sh ->
Clip reg (curveHelper sh)
Tap userMsg sh ->
Tap userMsg (curveHelper sh)
TapAt userMsg sh ->
TapAt userMsg (curveHelper sh)
EnterShape userMsg sh ->
EnterShape userMsg (curveHelper sh)
EnterAt userMsg sh ->
EnterAt userMsg (curveHelper sh)
Exit userMsg sh ->
Exit userMsg (curveHelper sh)
ExitAt userMsg sh ->
ExitAt userMsg (curveHelper sh)
MouseDown userMsg sh ->
MouseDown userMsg (curveHelper sh)
MouseDownAt userMsg sh ->
MouseDownAt userMsg (curveHelper sh)
MouseUp userMsg sh ->
MouseUp userMsg (curveHelper sh)
MouseUpAt userMsg sh ->
MouseUpAt userMsg (curveHelper sh)
MoveOverAt userMsg sh ->
MoveOverAt userMsg (curveHelper sh)
TouchStart userMsg sh ->
TouchStart userMsg (curveHelper sh)
TouchEnd userMsg sh ->
TouchEnd userMsg (curveHelper sh)
TouchStartAt userMsg sh ->
TouchStartAt userMsg (curveHelper sh)
TouchEndAt userMsg sh ->
TouchEndAt userMsg (curveHelper sh)
TouchMoveAt userMsg sh ->
TouchMoveAt userMsg (curveHelper sh)
-- no changes for the rest...
Inked clr ln sh ->
Inked clr ln sh
ForeignObject w h htm ->
ForeignObject w h htm
Everything ->
Everything
Notathing ->
Notathing
GraphPaper s th clr ->
GraphPaper s th clr
generateCurveHelper :
( Float, Float )
-> List ( ( Float, Float ), ( Float, Float ) )
-> Shape userMsg
generateCurveHelper ( a, b ) list =
let
l1Array =
Array.fromList
([ ( a, b ) ]
++ List.concat (List.map createTopLevelList list)
)
in
group [ generateCHLines l1Array, generateCHCircles l1Array ]
generateCHLines : Array.Array ( Float, Float ) -> Shape userMsg
generateCHLines ar =
let
len =
Array.length ar
in
group (List.map (generateCHLine ar) (List.range 0 (len - 2)))
generateCHLine : Array.Array ( Float, Float ) -> Int -> Shape userMsg
generateCHLine ar int =
let
p1 =
case Array.get int ar of
Just p ->
p
Nothing ->
( 0, 0 )
p2 =
case Array.get (int + 1) ar of
Just p ->
p
Nothing ->
( 0, 0 )
in
outlined (dashed 0.5) black (line p1 p2)
generateCHCircles : Array.Array ( Float, Float ) -> Shape userMsg
generateCHCircles ar =
let
len =
Array.length ar
in
group (List.map (generateCHCircle ar) (List.range 0 (len - 1)))
generateCHCircle : Array.Array ( Float, Float ) -> Int -> Shape userMsg
generateCHCircle ar int =
let
p1 =
case Array.get int ar of
Just p ->
p
Nothing ->
( 0, 0 )
ptStr =
pairToString p1
in
group
[ filled red (circle 2)
, text ("(" ++ ptStr ++ ")")
|> filled black
|> move ( 5, 5 )
]
|> move p1
createTopLevelList : ( ( a, b ), ( a, b ) ) -> List ( a, b )
createTopLevelList ( ( a, b ), ( c, d ) ) =
[ ( a, b ), ( c, d ) ]
matrixMult : Transform -> Transform -> Transform
matrixMult ( ( a, c, e ), ( b, d, f ) ) ( ( a1, c1, e1 ), ( b1, d1, f1 ) ) =
( ( a * a1 + c * b1, a * c1 + c * d1, e + a * e1 + c * f1 )
, ( b * a1 + d * b1, b * c1 + d * d1, f + b * e1 + d * f1 )
)
{-| The identity or "starting" matrix. Applying this matrix to a shape is the equivalent
of doing no transformations at all. The matrix itself looks like
```
ident = ( ( 1 , 0 , 0 ) , ( 0 , 1 , 0 ) )
```
or,
```
1 0 0
0 1 0
```
-}
ident : Transform
ident =
( ( 1, 0, 0 )
, ( 0, 1, 0 )
)
{-| A matrix representing an SVG transformation matrix of the form:
```
( ( a , c , e ) , ( b , d , f ) )
```
or
```
a c e
b d f
```
The a, c, b and d control transformations such as skew, rotate and scale;
e and f control translation.
These matrices are best built up by starting with the identity matrix and
applying any number of `*T` functions (see below); for example,
```
myTransform =
ident
|> scaleT 2 2
|> rotateT (degrees 30)
|> moveT (0, 50)
```
-}
type alias Transform =
( ( Float, Float, Float ), ( Float, Float, Float ) )
{-| Apply a move (translation) transformation to a transformation matrix.
This is designed to be used as part of a pipe:
```
ident
|> moveT (15,-30.5)
```
-}
moveT : ( Float, Float ) -> Transform -> Transform
moveT ( u, v ) ( ( a, c, tx ), ( b, d, ty ) ) =
( ( a, c, tx + a * u + c * v )
, ( b, d, ty + b * u + d * v )
)
{-| Apply a rotation transformation to a transformation matrix.
This is designed to be used as part of a pipe:
```
ident
|> moveT (15,-30.5)
|> rotateT (degrees -30)
```
-}
rotateT : Float -> Transform -> Transform
rotateT rad ( ( a, c, tx ), ( b, d, ty ) ) =
let
sinX =
sin rad
cosX =
cos rad
in
( ( a * cosX + c * sinX, c * cosX - a * sinX, tx )
, ( b * cosX + d * sinX, d * cosX - b * sinX, ty )
)
{-| Apply a scale transformation to a transformation matrix. The first argument
scales in x and the second argument scales in y. This is designed
to be used as part of a pipe:
```
ident
|> moveT (15,-30.5)
|> rotateT (degrees -30)
|> scaleT 4 0.4
```
-}
scaleT : Float -> Float -> Transform -> Transform
scaleT sx sy ( ( a, c, tx ), ( b, d, ty ) ) =
( ( a * sx, c * sy, tx )
, ( b * sx, d * sy, ty )
)
{-| Apply a skew transformation to a matrix. The first argument
skews in x and the second argument skews in y. This is designed
to be used as part of a pipe:
```
ident
|> moveT (15,-30.5)
|> rotateT (degrees -30)
|> scaleT 4 0.4
|> skewT 0.5 1.3
```
-}
skewT : Float -> Float -> Transform -> Transform
skewT skx sky ( ( a, c, tx ), ( b, d, ty ) ) =
let
tanX =
tan -skx
tanY =
tan -sky
in
( ( a + c * tanY, c + a * tanX, tx )
, ( b + d * tanY, d + b * tanX, ty )
)
{-| Apply a rotation about a given point to a `Transform` matrix. For example,
the following transform will rotate a `Shape` 30 degrees about the point (0,50):
```
rotateAbout050 =
ident
|> rotateAboutT (0, 50) (degrees 30)
```
-}
rotateAboutT : ( Float, Float ) -> Float -> Transform -> Transform
rotateAboutT ( u, v ) rad ( ( a, c, tx ), ( b, d, ty ) ) =
let
sinX =
sin rad
cosX =
cos rad
in
( ( a * cosX + c * sinX, c * cosX - a * sinX, tx + a * u + c * v - v * (c * cosX - a * sinX) - u * (a * cosX + c * sinX) )
, ( b * cosX + d * sinX, d * cosX - b * sinX, ty + b * u + d * v - v * (d * cosX - b * sinX) - u * (b * cosX + d * sinX) )
)
{-| Manually transform a shape using a `Transform` matrix. Matrix multiplication will
be used to apply the given matrix to any transformations of the current
shape. This is designed to be used in the usual way in a pipe:
```
circle 10
|> filled red
|> transform moveLeft50
moveLeft50 =
ident
|> moveT (50,0)
```
NOTE: Transformations generated using pipes this way are applied backwards compared
to the "regular" `Shape userMsg` transformation functions. For example, `rect0` and
`rect1` below are equivalent:
```
myTransform =
ident
|> scaleT 2 2
|> rotateT (degrees 30)
|> moveT (0, 50)
rect0 =
rect 20 10
|> filled red
|> transform myTransform
rect1 =
rect 20 10
|> filled red
|> move (0, 50)
|> rotate (degrees 30)
|> scale 2
```
On the other hand, single transformations produce a result consistent with the
`Shape userMsg` transformations. `rect2` is also equivalent to the two above:
```
moveRight50 =
ident
|> moveT (50,0)
scale2 =
ident
|> scaleT 2 2
rotate30 =
ident
|> rotateT (degrees 30)
rect2 =
rect 20 10
|> filled red
|> transform moveRight50
|> transform scale2
|> transform rotate30
```
However, chaining together transformations in this way is discouraged because
it is less efficient than the regular `Shape userMsg` transformations in
the "Transformations" section.
-}
transform : Transform -> Shape userMsg -> Shape userMsg
transform tm sh =
Transformed tm sh
{-| The Collage type represents the drawable surface of the window which contains
a (x, y) pair of horizontal and vertical dimensions (arbitrary units,
not necessarily in pixels) to which the drawing surface will be scaled,
and the \`List' of Shapes to be drawn on the drawing surface.
-}
type Collage userMsg
= Collage Float Float (List (Shape userMsg))
{-| Creates a blank canvas on which you can draw. Takes a width, height and a
list of `Shape`s. Use this in your `view` functions in the three types of Apps above:
collage 500 500
[
circle 10 |> filled red
]
-}
collage : Float -> Float -> List (Shape userMsg) -> Collage userMsg
collage w h shapes =
Collage w h shapes
createCollage : Float -> Float -> List (Shape userMsg) -> Html.Html (Msg userMsg)
createCollage w h shapes =
Svg.svg
[ width "100%"
, height "100%"
, style "position:absolute;top:0px;left:0px;"
, viewBox
(String.fromFloat (-w / 2)
++ " "
++ String.fromFloat (-h / 2)
++ " "
++ String.fromFloat w
++ " "
++ String.fromFloat h
)
, id "render"
]
(cPath w h
:: [ Svg.g
[ clipPath "url(#cPath)" ]
(List.indexedMap
(\n -> createSVG (String.fromInt n) w h ident Graphics ReturnPosition)
shapes
)
]
)
cPath : Float -> Float -> Svg.Svg (Msg userMsg)
cPath w h =
Svg.defs []
[ Svg.clipPath
[ Svg.Attributes.id "cPath" ]
[ Svg.rect
[ width (String.fromFloat w)
, height (String.fromFloat h)
, x (String.fromFloat (-w / 2))
, y (String.fromFloat (-h / 2))
]
[]
]
]
{-| Take a `Collage` width and height as well as a list of tuples of depth and `Shape`.
to produce a list of `Shape`'s suitable for display as a group in a `Collage` with
`Shape`'s with lesser depth larger and in front of `Shape`'s with greater depth.
-}
puppetShow :
Float
-> Float
-> List ( Float, Shape userMsg )
-> List (Shape userMsg)
puppetShow w h listShapes =
List.map
(extractShape (Basics.max w h))
(List.sortWith flippedComparison listShapes)
extractShape : Float -> ( Float, Shape userMsg ) -> Shape userMsg
extractShape fl ( z, shape ) =
let
s =
fl / (fl + z)
in
shape |> scale s
flippedComparison : ( comparable, a ) -> ( comparable, b ) -> Order
flippedComparison ( f, _ ) ( s, _ ) =
compare s f
--Notification functions
{-| Receive a message (`userMsg`) when a `Shape` is clicked or tapped.
-}
notifyTap : userMsg -> Shape userMsg -> Shape userMsg
notifyTap msg shape =
Tap msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse or finger when the `Shape` is clicked or tapped.
-}
notifyTapAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyTapAt msg shape =
TapAt msg shape
{-| Receive a message (`userMsg`) when the mouse enters a `Shape`.
-}
notifyEnter : userMsg -> Shape userMsg -> Shape userMsg
notifyEnter msg shape =
EnterShape msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse enters a `Shape`.
-}
notifyEnterAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyEnterAt msg shape =
EnterAt msg shape
{-| Receive a message (`userMsg`) when the mouse leaves a `Shape`.
-}
notifyLeave : userMsg -> Shape userMsg -> Shape userMsg
notifyLeave msg shape =
Exit msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse leaves a `Shape`.
-}
notifyLeaveAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyLeaveAt msg shape =
ExitAt msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse is moved across a `Shape`.
-}
notifyMouseMoveAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyMouseMoveAt msg shape =
MoveOverAt msg shape
{-| Receive a message (`userMsg`) when the mouse button is pressed while the cursor is over a `Shape`.
-}
notifyMouseDown : userMsg -> Shape userMsg -> Shape userMsg
notifyMouseDown msg shape =
MouseDown msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse button is pressed while the cursor is over a `Shape`.
-}
notifyMouseDownAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyMouseDownAt msg shape =
MouseDownAt msg shape
{-| Receive a message (`userMsg`) when the mouse button is released while the cursor is over a `Shape`.
-}
notifyMouseUp : userMsg -> Shape userMsg -> Shape userMsg
notifyMouseUp msg shape =
MouseUp msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse button is released while the cursor is over a `Shape`.
-}
notifyMouseUpAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyMouseUpAt msg shape =
MouseUpAt msg shape
{-| Receive a message (`userMsg`) when the user begins touching a `Shape`.
-}
notifyTouchStart : userMsg -> Shape userMsg -> Shape userMsg
notifyTouchStart msg shape =
TouchStart msg shape
{-| Receive a message (`userMsg`) with the x and y position of the user's finger when the user begins touching a `Shape`.
-}
notifyTouchStartAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyTouchStartAt msg shape =
TouchStartAt msg shape
{-| Receive a message (`userMsg`) when the user lifts their finger off a `Shape`.
-}
notifyTouchEnd : userMsg -> Shape userMsg -> Shape userMsg
notifyTouchEnd msg shape =
TouchEnd msg shape
{-| Receive a message (`userMsg`) with the x and y position of the user's finger when the user lifts their finger off a `Shape`.
-}
notifyTouchEndAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyTouchEndAt msg shape =
TouchEndAt msg shape
{-| Receive a message (`userMsg`) with the x and y position of the user's finger when the user moves their finger over a `Shape`.
-}
notifyTouchMoveAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyTouchMoveAt msg shape =
TouchMoveAt msg shape
touchToPair : TouchPos -> ( Float, Float )
touchToPair tp =
case tp of
TouchPos x y ->
( x, -y )
mousePosDecoder =
D.map2 (\x y -> ( x, -y )) (D.field "offsetX" D.float) (D.field "offsetY" D.float)
onTapAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onTapAt msg =
Html.Events.on "click"
(D.map msg mousePosDecoder)
onEnterAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onEnterAt msg =
Html.Events.on "mouseover"
(D.map msg mousePosDecoder)
onLeaveAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onLeaveAt msg =
Html.Events.on "mouseleave"
(D.map msg mousePosDecoder)
onMoveAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onMoveAt msg =
Html.Events.on "mousemove"
(D.map msg mousePosDecoder)
onMouseDownAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onMouseDownAt msg =
Html.Events.on "mousedown"
(D.map msg mousePosDecoder)
onMouseUpAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onMouseUpAt msg =
Html.Events.on "mouseup"
(D.map msg mousePosDecoder)
onTouchStart : userMsg -> Html.Attribute userMsg
onTouchStart msg =
Html.Events.on "touchstart" (D.succeed msg)
onTouchStartAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onTouchStartAt msg =
Html.Events.on "touchstart"
(D.map (msg << touchToPair) touchDecoder)
onTouchEndAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onTouchEndAt msg =
Html.Events.on "touchend"
(D.map (msg << touchToPair) touchDecoder)
onTouchEnd : userMsg -> Html.Attribute userMsg
onTouchEnd msg =
Html.Events.on "touchend" (D.succeed msg)
onTouchMove : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onTouchMove msg =
Html.Events.preventDefaultOn "touchmove"
(D.map (\a -> ( (msg << touchToPair) a, True )) touchDecoder)
type TouchPos
= TouchPos Float Float
touchDecoder : Decoder TouchPos
touchDecoder =
D.oneOf
[ D.at
[ "touches", "0" ]
(D.map2
TouchPos
(D.field "pageX" D.float)
(D.field "pageY" D.float)
)
, D.map2
TouchPos
(D.field "pageX" D.float)
(D.field "pageY" D.float)
]
{-| Create Svg from a Shape. This is considered an advanced function and
is usually not used. Instead, use collage as part of a regular GraphicSVG
app or create a widget with GraphicSVG.Widget.
-}
createSVG : String -> Float -> Float -> Transform -> (a -> b) -> (((Float,Float) -> a) -> (Float,Float) -> b) -> Shape a -> Svg.Svg b
createSVG id w h trans msgWrapper positionWrapper shape =
case shape of
Inked fillClr lt stencil ->
let
( ( a, c, tx ), ( b, d, ty ) ) =
trans
attrs =
case fillClr of
Just (Gradient _) ->
clrAttrs ++ strokeAttrs
_ -> transAttrs ++ clrAttrs ++ strokeAttrs
transAttrs =
[ Svg.Attributes.transform <|
"matrix("
++ (String.concat <|
List.intersperse "," <|
List.map
String.fromFloat
[ a, -b, c, -d, tx, -ty ]
)
++ ")"
]
nonexistBody =
case fillClr of
Nothing -> True
_ -> False
clrAttrs =
case fillClr of
Nothing -> [ fill "none"]
Just (Solid bodyClr) ->
[ fill (mkRGB bodyClr)
, fillOpacity (mkAlpha bodyClr)
]
Just (Gradient _) ->
[
Svg.Attributes.id id
, fill (mkRGB <| Color.rgb 255 255 255)
]
strokeAttrs =
case lt of
Nothing ->
[]
Just ( Unbroken th, Solid strokeClr ) ->
let nonStroke =
let opcty = getAlpha strokeClr
in th <= 0 || opcty <= 0
in
if nonStroke then [] else
[ strokeWidth (String.fromFloat th)
, stroke (mkRGB strokeClr)
, strokeOpacity (mkAlpha strokeClr)
]
Just ( Broken dashes th, Solid strokeClr ) ->
let nonStroke =
let opcty = getAlpha strokeClr
in th <= 0 || opcty <= 0 ||
List.all (\( on, _ ) -> on == 0) dashes
in
if nonStroke then [] else
[ strokeWidth (String.fromFloat th)
, stroke (mkRGB strokeClr)
, strokeOpacity (mkAlpha strokeClr)
]
++ [ strokeDasharray <|
String.concat
(List.intersperse "," <|
List.map pairToString dashes
)
]
Just ( _, _ ) ->
[]
basicShape = case stencil of
Circle r ->
Svg.circle
([ cx "0"
, cy "0"
, Svg.Attributes.r (String.fromFloat r)
]
++ attrs
)
[]
Rect rw rh ->
Svg.rect
([ x <| String.fromFloat <| -rw / 2
, y <| String.fromFloat <| -rh / 2
, width <| String.fromFloat rw
, height <| String.fromFloat rh
]
++ attrs
)
[]
RoundRect rw rh r ->
Svg.rect
([ x <| String.fromFloat <| -rw / 2
, y <| String.fromFloat <| -rh / 2
, rx <| String.fromFloat r
, ry <| String.fromFloat r
, width <| String.fromFloat rw
, height <| String.fromFloat rh
]
++ attrs
)
[]
Oval ow oh ->
Svg.ellipse
([ cx "0"
, cy "0"
, rx <| String.fromFloat <| 0.5 * ow
, ry <| String.fromFloat <| 0.5 * oh
]
++ attrs
)
[]
Polygon vertices ->
Svg.polygon
([ points <|
String.concat <|
List.intersperse " " <|
List.map pairToString vertices
]
++ attrs
)
[]
Path vertices ->
Svg.polyline
([ points <|
String.concat <|
List.intersperse " " <|
List.map pairToString vertices
]
++ attrs
)
[]
BezierPath start pts ->
Svg.path
([ Svg.Attributes.d <| createBezierString start pts ]
++ attrs
)
[]
Text (Face si bo i u s sel f align) str ->
let
bol =
if bo then
"font-weight: bold;"
else
""
it =
if i then
"font-style: italic;"
else
""
txtDec =
if u && s then
"text-decoration: underline line-through;"
else if u then
"text-decoration: underline;"
else if s then
"text-decoration: line-through;"
else
""
select =
if not sel then
"-webkit-touch-callout: none;\n-webkit-user-select: none;\n-khtml-user-select: none;\n-moz-user-select: none;\n-ms-user-select: none;\nuser-select: none;cursor: default;"
else
""
anchor =
case align of
AlignCentred ->
"middle"
AlignLeft ->
"start"
AlignRight ->
"end"
font =
case f of
Sansserif ->
"sans-serif;"
Serif ->
"serif;"
FixedWidth ->
"monospace;"
Custom fStr ->
fStr ++ ";"
sty =
bol
++ it
++ txtDec
++ "font-family: "
++ font
++ select
in
Svg.text_
([ x "0"
, y "0"
, Svg.Attributes.style sty
, Svg.Attributes.fontSize (String.fromFloat si)
, Svg.Attributes.textAnchor anchor
, Html.Attributes.contenteditable True
]
++ [ Svg.Attributes.transform <|
"matrix("
++ (String.concat <|
List.intersperse "," <|
List.map
String.fromFloat
[ a, -b, -c, d, tx, -ty ]
)
++ ")"
]
++ [ Svg.Attributes.xmlSpace "preserve" ]
++ clrAttrs ++ strokeAttrs
)
[ Svg.text str ]
gradientDefs =
case fillClr of
Just (Gradient gr) ->
Just (createGradientSVG id (w, h) gr)
_ -> Nothing
in
if nonexistBody && List.isEmpty strokeAttrs then Svg.g [] []
else case gradientDefs of
Just gDefs ->
Svg.g transAttrs
[
Svg.mask [Svg.Attributes.id (id ++ "mask")]
[
basicShape
]
, gDefs
]
Nothing ->
basicShape
ForeignObject fw fh htm ->
let
( ( a, c, tx ), ( b, d, ty ) ) =
trans
in
Svg.foreignObject
[ width <| String.fromFloat fw
, height <| String.fromFloat fh
, Svg.Attributes.transform
<| "matrix(" ++ (String.concat <| List.intersperse ","
<| List.map
String.fromFloat
[ a, -b, -c, d, tx, -ty ]) ++ ")"
] [ Html.map msgWrapper htm ]
Move v sh ->
createSVG id w h (moveT v trans) msgWrapper positionWrapper sh
Everything ->
createSVG id w h ident msgWrapper positionWrapper (rect w h |> filled white)
Notathing ->
createSVG id w h ident msgWrapper positionWrapper (rect w h |> filled black)
Rotate deg sh ->
createSVG id w h (rotateT deg trans) msgWrapper positionWrapper sh
Scale sx sy sh ->
createSVG id w h (scaleT sx sy trans) msgWrapper positionWrapper sh
Skew sx sy sh ->
createSVG id w h (skewT sx sy trans) msgWrapper positionWrapper sh
Transformed tm sh ->
createSVG id w h (matrixMult trans tm) msgWrapper positionWrapper sh
Link href sh ->
Svg.a
[ xlinkHref href, target "_blank" ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
AlphaMask region sh ->
Svg.g []
[ Svg.defs []
[ Svg.mask
[ Svg.Attributes.id ("m" ++ id) ]
[ createSVG
(id ++ "m")
w
h
trans
msgWrapper
positionWrapper
(Group [ Everything, region |> repaint black ])
]
]
, Svg.g
[ Svg.Attributes.mask ("url(#m" ++ id ++ ")") ]
[ createSVG (id ++ "mm") w h trans msgWrapper positionWrapper sh ]
]
Clip region sh ->
Svg.g []
[ Svg.defs []
[ Svg.mask
[ Svg.Attributes.id ("c" ++ id) ]
[ createSVG
(id ++ "c")
w
h
trans
msgWrapper
positionWrapper
(Group [ Notathing, region |> repaint white ])
]
]
, Svg.g
[ Svg.Attributes.mask ("url(#c" ++ id ++ ")") ]
[ createSVG (id ++ "cc") w h trans msgWrapper positionWrapper sh ]
]
Tap msg sh ->
Svg.g
[ Html.Events.onClick (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TapAt msg sh ->
Svg.g
[ onTapAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
EnterShape msg sh ->
Svg.g
[ Html.Events.onMouseEnter (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
EnterAt msg sh ->
Svg.g
[ onEnterAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
Exit msg sh ->
Svg.g
[ Html.Events.onMouseLeave (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
ExitAt msg sh ->
Svg.g
[ onLeaveAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MouseDown msg sh ->
Svg.g
[ Html.Events.onMouseDown (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MouseDownAt msg sh ->
Svg.g
[ onMouseDownAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MouseUp msg sh ->
Svg.g
[ Html.Events.onMouseUp (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MouseUpAt msg sh ->
Svg.g
[ onMouseUpAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MoveOverAt msg sh ->
Svg.g
[ onMoveAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchStart msg sh ->
Svg.g
[ onTouchStart (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchEnd msg sh ->
Svg.g
[ onTouchEnd (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchStartAt msg sh ->
Svg.g
[ onTouchStartAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchEndAt msg sh ->
Svg.g
[ onTouchStartAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchMoveAt msg sh ->
Svg.g
[ onTouchMove (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
Group shapes ->
Svg.g [] <|
List.indexedMap
(\n ->
createSVG
(id ++ "g" ++ String.fromInt n)
w
h
trans
msgWrapper
positionWrapper
)
shapes
GroupOutline cmbndshp ->
createSVG id w h trans msgWrapper positionWrapper cmbndshp
GraphPaper s th c ->
if th <= 0 || s < 2 * th then
Svg.g [] []
else
createSVG id w h trans msgWrapper positionWrapper <|
createGraph ( w, h ) s th c
{-| Display HTML inside an SVG foreignObject.
-}
html : Float -> Float -> Html.Html userMsg -> Shape userMsg
html w h htm =
ForeignObject w h htm
--Filling / outlining functions
{-| Fill a `Stencil` with a `Color`, creating a `Shape`;
Note that any `Stencil` converted to a `Shape` this way can be made
transparent (for instance by using the `blank` `Color`) but will not be
"click-through", meaning that the body will catch any attached notifications
and not let them through to any visible `Shape`(s) revealed beneath them.
circle 10
|> filled red
-}
filled : Color -> Stencil -> Shape userMsg
filled color stencil =
Inked (Just color) Nothing stencil
{-| Make a `Shape` into a ghost. Mostly to be used inside of the clip operations.
Note that although the `blank` `Color` is transparent, it will still catch
notifications enabled on the `Shape` or block them if not enabled on the `Shape`.
-}
ghost : Stencil -> Shape userMsg
ghost stencil =
Inked (Just blank) Nothing stencil
{-| Repaint an already-`filled` `Shape`. This is helpful for repainting every `Shape` inside a `group` as well.
Repaints the outline the same color as the body of the shape including the outline, if used;
Note that this can repaint with a transparent `Color` (for instance, the `blank` `Color`) but
will never have the ability to be "click-through" so that it will always block (or catch)
notifications to covered `Shape`(s) revealed beneath.
group
[ circle 10
|> filled orange
, rect 10 40
|> filled blue
]
|> repaint green
-}
repaint : Color -> Shape userMsg -> Shape userMsg
repaint color shape =
case shape of
Inked _ Nothing st ->
Inked (Just color) Nothing st
Inked _ (Just ( lt, _ )) st ->
Inked (Just color) (Just ( lt, color )) st
Move s sh ->
Move s (repaint color sh)
Rotate r sh ->
Rotate r (repaint color sh)
Scale sx sy sh ->
Scale sx sy (repaint color sh)
Skew skx sky sh ->
Skew skx sky (repaint color sh)
Transformed tm sh ->
Transformed tm (repaint color sh)
Group shapes ->
Group (List.map (repaint color) shapes)
GroupOutline cmbndshp ->
GroupOutline (repaint color cmbndshp)
Link s sh ->
Link s (repaint color sh)
AlphaMask reg sh ->
AlphaMask reg (repaint color sh)
Clip reg sh ->
Clip reg (repaint color sh)
Tap userMsg sh ->
Tap userMsg (repaint color sh)
TapAt userMsg sh ->
TapAt userMsg (repaint color sh)
EnterShape userMsg sh ->
EnterShape userMsg (repaint color sh)
EnterAt userMsg sh ->
EnterAt userMsg (repaint color sh)
Exit userMsg sh ->
Exit userMsg (repaint color sh)
ExitAt userMsg sh ->
ExitAt userMsg (repaint color sh)
MouseDown userMsg sh ->
MouseDown userMsg (repaint color sh)
MouseDownAt userMsg sh ->
MouseDownAt userMsg (repaint color sh)
MouseUp userMsg sh ->
MouseUp userMsg (repaint color sh)
MouseUpAt userMsg sh ->
MouseUpAt userMsg (repaint color sh)
MoveOverAt userMsg sh ->
MoveOverAt userMsg (repaint color sh)
TouchStart userMsg sh ->
TouchStart userMsg (repaint color sh)
TouchEnd userMsg sh ->
TouchEnd userMsg (repaint color sh)
TouchStartAt userMsg sh ->
TouchStartAt userMsg (repaint color sh)
TouchEndAt userMsg sh ->
TouchEndAt userMsg (repaint color sh)
TouchMoveAt userMsg sh ->
TouchMoveAt userMsg (repaint color sh)
-- no changes for the rest...
ForeignObject w h htm ->
ForeignObject w h htm
Everything ->
Everything
Notathing ->
Notathing
GraphPaper s th _ ->
GraphPaper s th color
{-| Outline a Stencil with a `LineType` and `Color`, creating a `Shape`;
Note that this is the only way to convert a `Stencil` into a `Shape` that is
"click-through" as if the body is not just transparent but doesn't exist at all.
It works for all `Stencil`'s except for `Text` which can never be made "click-through"
due to a permanent transparent background area that cannot be disabled.
circle 10
|> outlined (solid 5) red
-}
outlined : LineType -> Color -> Stencil -> Shape userMsg
outlined style outlineClr stencil =
let
lineStyle =
case style of
NoLine ->
Nothing
_ ->
Just ( style, outlineClr )
in
Inked Nothing lineStyle stencil
{-| Add an outline to an already-filled `Shape`.
When applied to `Group`'s including `Shape`'s that have had `union` applied to them,
the outline will have half the expected stroke width only outside the `Shape`'s and
for `Shape`'s with `clip` or `subtract` applied to them, the half width stroke will be
interior to the composite shapes displayed.
The limitation is that when displaying "clip's" or "subtract's" containing "Group's",
the outline for the "Group's" won't be visibile at all (less common), nor will the
outline's for "clip's" or "subtract's" inside "Group's" be visible (more common);
also, the outline for the clipping or subtraction pattern may not be as expected when
the pattern is a "Group" as it won't appear at all in a "clip".
In these cases the workaround is just as before this was made available, to build up
the outlines desired using combinations of other shapes such as curves, clipped or
subtracted shapes, convential pre-applied outlines, etc.
Note that when applied to `Group`(s), `Clip`(s), and `AlphaMask`(s) (from subtracts),
the body colour may still be transparent so that `Shape`(s) can be revealed beneath,
but the bodies are not "click-through" so that notifications can be passed through to them,
and the transparent bodies can still capture notifications enabled on the resulting `Shape`(s).
circle 10
|> filled red
|> addOutline (solid 5) white
-}
addOutline : LineType -> Color -> Shape userMsg -> Shape userMsg
addOutline style outlineClr shape =
let
lineStyle =
case style of
NoLine ->
Nothing
_ ->
Just ( style, outlineClr )
in
case shape of
Inked clr _ st ->
Inked clr lineStyle st
Move s sh ->
Move s (addOutline style outlineClr sh)
Rotate r sh ->
Rotate r (addOutline style outlineClr sh)
Scale sx sy sh ->
Scale sx sy (addOutline style outlineClr sh)
Skew skx sky sh ->
Skew skx sky (addOutline style outlineClr sh)
Transformed tm sh ->
Transformed tm (addOutline style outlineClr sh)
Group list ->
let
innerlist =
List.filterMap
(\shp ->
case shp of
-- remove old outline shape
GroupOutline _ ->
Nothing
_ ->
Just <| addOutline NoLine black shp
)
list
in
case innerlist of
[] ->
{- should never happen -}
Group []
hd :: [] ->
addOutline style outlineClr hd
_ ->
if lineStyle == Nothing then
Group innerlist
else
let
outlnshp =
GroupOutline <|
subtract
(Group innerlist)
(Group
(List.map
(addOutline style outlineClr)
innerlist
)
)
in
Group <| innerlist ++ [ outlnshp ]
-- don't add an outline to one that's already been added but it should
-- never get here as GroupOutline should always be inside a Group which
-- will already have processed it, whether to change or remove it...
GroupOutline cmbndshp ->
GroupOutline cmbndshp
AlphaMask reg sh ->
let
ptrn =
addOutline NoLine black reg
inside =
addOutline NoLine black sh
in
if lineStyle == Nothing then
AlphaMask ptrn inside
else
let
ptrnlnd =
addOutline style outlineClr reg
newshp =
addOutline style outlineClr sh
ptrnoutln =
Clip inside ptrnlnd
shpoutln =
Clip inside newshp
in
AlphaMask ptrn <|
Group
[ inside
, GroupOutline <| Group [ shpoutln, ptrnoutln ]
]
Clip reg sh ->
let
ptrn =
addOutline NoLine black reg
inside =
addOutline NoLine black sh
in
if lineStyle == Nothing then
Clip ptrn inside
else
let
ptrnlnd =
addOutline style outlineClr (reg |> repaint blank)
newshp =
addOutline style outlineClr sh
ptrnoutln =
Clip inside ptrnlnd
shpoutln =
Clip inside newshp
in
Clip ptrn <|
Group
[ inside
, GroupOutline <| Group [ shpoutln, ptrnoutln ]
]
Link s sh ->
Link s (addOutline style outlineClr sh)
Tap userMsg sh ->
Tap userMsg (addOutline style outlineClr sh)
TapAt userMsg sh ->
TapAt userMsg (addOutline style outlineClr sh)
EnterShape userMsg sh ->
EnterShape userMsg (addOutline style outlineClr sh)
EnterAt userMsg sh ->
EnterAt userMsg (addOutline style outlineClr sh)
Exit userMsg sh ->
Exit userMsg (addOutline style outlineClr sh)
ExitAt userMsg sh ->
ExitAt userMsg (addOutline style outlineClr sh)
MouseDown userMsg sh ->
MouseDown userMsg (addOutline style outlineClr sh)
MouseDownAt userMsg sh ->
MouseDownAt userMsg (addOutline style outlineClr sh)
MouseUp userMsg sh ->
MouseUp userMsg (addOutline style outlineClr sh)
MouseUpAt userMsg sh ->
MouseUpAt userMsg (addOutline style outlineClr sh)
MoveOverAt userMsg sh ->
MoveOverAt userMsg (addOutline style outlineClr sh)
TouchStart userMsg sh ->
TouchStart userMsg (addOutline style outlineClr sh)
TouchEnd userMsg sh ->
TouchEnd userMsg (addOutline style outlineClr sh)
TouchStartAt userMsg sh ->
TouchStartAt userMsg (addOutline style outlineClr sh)
TouchEndAt userMsg sh ->
TouchEndAt userMsg (addOutline style outlineClr sh)
TouchMoveAt userMsg sh ->
TouchMoveAt userMsg (addOutline style outlineClr sh)
-- no changes for the rest...
ForeignObject w h htm ->
ForeignObject w h htm
Everything ->
Everything
Notathing ->
Notathing
GraphPaper s th clr ->
GraphPaper s th clr
multAlpha : Color.Color -> Float -> Color.Color
multAlpha color n =
let
colRec = Color.toRgba color
in
Color.fromRgba { colRec | alpha = colRec.alpha * n }
{-| Make a `Shape` transparent by the fraction given. Multiplies on top of other transparencies:
circle 10
|> filled red
|> makeTransparent 0.5
--results in a transparency of 0.5 (half vislible)
circle 10
|> filled red
|> makeTransparent 0.5
|> makeTransparent 0.5
--results in a transparency of 0.25 (a quarter visible)
-}
makeTransparent : Float -> Shape userMsg -> Shape userMsg
makeTransparent alpha shape =
case shape of
Inked Nothing (Just ( lineType, Solid colour )) st ->
Inked Nothing (Just ( lineType, Solid (multAlpha colour alpha))) st
Inked (Just (Solid colour)) (Just ( lineType, Solid sColour )) st ->
Inked (Just <| Solid (multAlpha colour alpha))
(Just ( lineType, Solid <| multAlpha sColour alpha)) st
Inked (Just (Solid colour)) Nothing st ->
Inked (Just <| Solid (multAlpha colour alpha)) Nothing st
Inked a b c ->
Inked a b c
ForeignObject w h htm ->
ForeignObject w h htm
Move s sh ->
Move s (makeTransparent alpha sh)
Rotate r sh ->
Rotate r (makeTransparent alpha sh)
Scale sx sy sh ->
Scale sx sy (makeTransparent alpha sh)
Skew skx sky sh ->
Skew skx sky (makeTransparent alpha sh)
Transformed tm sh ->
Transformed tm (makeTransparent alpha sh)
Group list ->
Group (List.map (makeTransparent alpha) list)
GroupOutline cmbndshp ->
GroupOutline (makeTransparent alpha cmbndshp)
Link s sh ->
Link s (makeTransparent alpha sh)
AlphaMask reg sh ->
AlphaMask reg (makeTransparent alpha sh)
Clip reg sh ->
Clip reg (makeTransparent alpha sh)
Everything ->
Everything
Notathing ->
Notathing
Tap userMsg sh ->
Tap userMsg (makeTransparent alpha sh)
TapAt userMsg sh ->
TapAt userMsg (makeTransparent alpha sh)
EnterShape userMsg sh ->
EnterShape userMsg (makeTransparent alpha sh)
EnterAt userMsg sh ->
EnterAt userMsg (makeTransparent alpha sh)
Exit userMsg sh ->
Exit userMsg (makeTransparent alpha sh)
ExitAt userMsg sh ->
ExitAt userMsg (makeTransparent alpha sh)
MouseDown userMsg sh ->
MouseDown userMsg (makeTransparent alpha sh)
MouseDownAt userMsg sh ->
MouseDownAt userMsg (makeTransparent alpha sh)
MouseUp userMsg sh ->
MouseUp userMsg (makeTransparent alpha sh)
MouseUpAt userMsg sh ->
MouseUpAt userMsg (makeTransparent alpha sh)
MoveOverAt userMsg sh ->
MoveOverAt userMsg (makeTransparent alpha sh)
TouchStart userMsg sh ->
TouchStart userMsg (makeTransparent alpha sh)
TouchEnd userMsg sh ->
TouchEnd userMsg (makeTransparent alpha sh)
TouchStartAt userMsg sh ->
TouchStartAt userMsg (makeTransparent alpha sh)
TouchEndAt userMsg sh ->
TouchEndAt userMsg (makeTransparent alpha sh)
TouchMoveAt userMsg sh ->
TouchMoveAt userMsg (makeTransparent alpha sh)
GraphPaper s th (Solid colour) ->
GraphPaper s th (Solid <| multAlpha colour alpha)
GraphPaper s th (Gradient gr) ->
GraphPaper s th (Gradient gr)
--Line styles
{-| Define a`LineType` that doesn't exist, doesn't appear.
-}
noline : () -> LineType
noline () =
NoLine
{-| Define a solid `LineType` with the given width.
-}
solid : Float -> LineType
solid th =
Unbroken th
{-| Define a dotted `LineType` with the given width.
-}
dotted : Float -> LineType
dotted th =
Broken [ ( th, th ) ] th
{-| Define a dashed `LineType` with the given width. Dashes are short line segments, versus dots which are theoretically points, but may be drawn with very short line segments.
-}
dashed : Float -> LineType
dashed th =
Broken [ ( th * 5, th * 2.5 ) ] th
{-| Define a dashed `LineType` with the given width, where the dashes are longer than normal.
-}
longdash : Float -> LineType
longdash th =
Broken [ ( th * 12, th * 6 ) ] th
{-| Define a `LineType` with the given width, including alternating dots and dashes.
-}
dotdash : Float -> LineType
dotdash th =
Broken [ ( th, th ), ( th * 5, th ) ] th
{-| A custom line defined by a list of (on,off):
custom [ ( 10, 5 ) ] 5 -- a line with dashes 10 long and spaces 5 long
custom [ ( 10, 5 ), ( 20, 5 ) ] -- on for 10, off 5, on 20, off 5
-}
custom : List ( Float, Float ) -> Float -> LineType
custom list th =
Broken list th
makePair : a -> ( a, a )
makePair n =
( n, n )
--Text functions
{-| Apply to a `text` `Stencil` to change the font size of the text.
The size has a unit called "points", which depends on the size and type of screen used, but try 12 to start.
-}
size : Float -> Stencil -> Stencil
size sze stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face sze bo i u s sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to make the text bold.
-}
bold : Stencil -> Stencil
bold stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si True i u s sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to make the text italicized (slanted).
-}
italic : Stencil -> Stencil
italic stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo True u s sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to underline the text.
-}
underline : Stencil -> Stencil
underline stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i True s sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to put a line through the centre of the text.
-}
strikethrough : Stencil -> Stencil
strikethrough stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u True sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to make the text selectable (so users can copy your text and paste it elsewhere).
-}
selectable : Stencil -> Stencil
selectable stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s True f c) str
a ->
a
{-| Apply to a `text` `Stencil` to right-align the text.
-}
alignRight : Stencil -> Stencil
alignRight stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel f AlignRight) str
a ->
a
{-| Apply to a `text` `Stencil` to centre the text.
-}
centered : Stencil -> Stencil
centered stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel f AlignCentred) str
a ->
a
{-| Apply to a `text` `Stencil` to left-align the text.
-}
alignLeft : Stencil -> Stencil
alignLeft stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel f AlignLeft) str
a ->
a
{-| Apply to a `text` `Stencil` to render the text with a Sans Serif font (ie one without thinner and thicker bits).
-}
sansserif : Stencil -> Stencil
sansserif stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel Sansserif c) str
a ->
a
{-| Apply to a `text` `Stencil` to render the text with a Serif font (ie one with thinner and thicker bits).
-}
serif : Stencil -> Stencil
serif stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel Serif c) str
a ->
a
{-| Apply to a text `Stencil` to render the text `Stencil` with a font in which every character has the same width.
This will mean that the letters line up from line to line which is important in programming languages like Elm.
-}
fixedwidth : Stencil -> Stencil
fixedwidth stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel FixedWidth c) str
a ->
a
{-| Apply to a `text` `Stencil` to render the text with a font of your choosing by specifying its name in a `String`.
_Use this sparingly as support for each font will vary across browsers and devices._
-}
customFont : String -> Stencil -> Stencil
customFont fStr stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel (Custom fStr) c) str
a ->
a
--Transformation functions
{-| Rotate a `Shape` by the specified amount (in radians). Use the `degrees` function to convert
from degrees into radians:
[
rect 30 60
|> filled blue
|> rotate(degrees 30)
]
-}
rotate : Float -> Shape userMsg -> Shape userMsg
rotate theta shape =
Rotate theta shape
{-| Move a `Shape` by a number of units along the x-axis and y-axis.
-}
move : ( Float, Float ) -> Shape userMsg -> Shape userMsg
move disp shape =
Move disp shape
{-| Scale a `Shape` by a given factor.
-}
scale : Float -> Shape userMsg -> Shape userMsg
scale s shape =
Scale s s shape
{-| Scale a `Shape` in the x-axis by a given factor.
-}
scaleX : Float -> Shape userMsg -> Shape userMsg
scaleX s shape =
Scale s 1 shape
{-| Scale a `Shape` in the y-axis by a given factor.
-}
scaleY : Float -> Shape userMsg -> Shape userMsg
scaleY s shape =
Scale 1 s shape
{-| Flip a `Shape` along the x-axis.
-}
mirrorX : Shape userMsg -> Shape userMsg
mirrorX shape =
Scale -1 1 shape
{-| Flip a `Shape` along the y-axis.
-}
mirrorY : Shape userMsg -> Shape userMsg
mirrorY shape =
Scale 1 -1 shape
{-| Skew a `Shape` along the x-axis.
-}
skewX : Float -> Shape userMsg -> Shape userMsg
skewX skx shape =
Skew skx 0 shape
{-| Skew a `Shape` along the y-axis.
-}
skewY : Float -> Shape userMsg -> Shape userMsg
skewY sky shape =
Skew 0 sky shape
{-| Combine any number of `Shape` types into one `Shape` that can be
transformed (moved, rotated, scaled, etc) as one `Shape`.
-}
group : List (Shape userMsg) -> Shape userMsg
group shapes =
Group shapes
{-| Define a colour given its red, green and blue components.
-}
rgb : Float -> Float -> Float -> Color
rgb r g b =
rgba r g b 1
{-| Define a colour given its red, green, blue and alpha components.
Alpha is a decimal number (`Float`) from 0 to 1 representing the level of transparency.
-}
rgba : Float -> Float -> Float -> Float -> Color
rgba r g b a =
Solid <| Color.fromRgba { red = ssc r, green = ssc g, blue = ssc b, alpha = ssa a }
ssc : number -> number
ssc n =
clamp 0 255 n
ssa : Float -> Float
ssa n =
clamp 0 1 n
pairToString : ( Float, Float ) -> String
pairToString ( x, y ) =
String.fromFloat x ++ "," ++ String.fromFloat y
createBezierString : ( Float, Float ) -> List ( ( Float, Float ), ( Float, Float ) ) -> String
createBezierString first list =
"M " ++ pairToString first ++ String.concat (List.map bezierStringHelper list)
bezierStringHelper : ( ( Float, Float ), ( Float, Float ) ) -> String
bezierStringHelper ( ( a, b ), ( c, d ) ) =
" Q " ++ pairToString ( a, b ) ++ " " ++ pairToString ( c, d )
getAlpha : Color.Color -> Float
getAlpha colour =
(Color.toRgba colour).alpha
mkAlpha : Color.Color -> String
mkAlpha =
String.fromFloat << getAlpha
mkRGB : Color.Color -> String
mkRGB colour =
let
col = Color.toRgba colour
in
"rgba(" ++ (String.fromFloat col.red) ++ "," ++ (String.fromFloat col.green) ++ "," ++ (String.fromFloat col.blue) ++ "," ++ (String.fromFloat col.alpha) ++ ")"
{-| Define a colour given its hue, saturation and light components.
-}
hsl : Float -> Float -> Float -> Color
hsl h s l =
case convert h s l of
( r, g, b ) ->
rgba r g b 1
{-| Define a colour given its hue, saturation, light and alpha components.
Alpha is a decimal number (`Float`) from 0 to 1 representing the level of transparency.
-}
hsla : Float -> Float -> Float -> Float -> Color
hsla h s l a =
case convert h s l of
( r, g, b ) ->
rgba r g b a
-- Clip path functionality
{-| Clipping to a shape
Cut out the `Shape` on the right using the `Shape` on the left.
-}
clip : Shape userMsg -> Shape userMsg -> Shape userMsg
clip shape1 shape2 =
Clip shape1 shape2
{-| Shape union
Combine two `Shape`s together into one to use with clip.
-}
union : Shape userMsg -> Shape userMsg -> Shape userMsg
union shape1 shape2 =
Group [ shape1, shape2 ]
{-| Shape subtraction
Subtract the `Shape` on the left from the `Shape` on the right.
-}
subtract : Shape userMsg -> Shape userMsg -> Shape userMsg
subtract shape1 shape2 =
AlphaMask shape1 shape2
{-| The whole region outside the given `Shape`.
-}
outside : Shape userMsg -> Shape userMsg
outside shape =
AlphaMask shape shape
{-
Contributed by <NAME>.
-}
convert : Float -> Float -> Float -> ( Float, Float, Float )
convert hue sat lit =
let
hue_ =
modFloat hue (2 * pi)
rgb_ =
toRGB_ hue_ sat lit
chroma =
findChroma lit sat
m =
findM lit chroma
in
mapTriple (\x -> x * 255) (mapTriple (\x -> x + m) rgb_)
findChroma : Float -> Float -> Float
findChroma lit sat =
(1 - abs (2 * lit - 1)) * sat
findHue_ : Float -> Float
findHue_ hue =
hue / degrees 60
findX : Float -> Float -> Float
findX chroma hue =
chroma * (1 - abs (modFloat (findHue_ hue) 2 - 1))
findM : Float -> Float -> Float
findM lit chroma =
lit - 0.5 * chroma
toRGB_ : Float -> Float -> Float -> ( Float, Float, Float )
toRGB_ hue sat lit =
let
chroma =
findChroma lit sat
hue_ =
findHue_ hue
x =
findX chroma hue
in
if hue_ >= 0 && hue_ < 1 then
( chroma, x, 0 )
else if hue_ >= 1 && hue_ < 2 then
( x, chroma, 0 )
else if hue_ >= 2 && hue_ < 3 then
( 0, chroma, x )
else if hue_ >= 3 && hue_ < 4 then
( 0, x, chroma )
else if hue_ >= 4 && hue_ < 5 then
( x, 0, chroma )
else if hue_ >= 5 && hue_ < 6 then
( chroma, 0, x )
else
( 0, 0, 0 )
{- Helper Functions -}
modFloat : Float -> Float -> Float
modFloat x m =
x - m * Basics.toFloat (floor (x / m))
mapTriple : (a -> b) -> ( a, a, a ) -> ( b, b, b )
mapTriple f ( a1, a2, a3 ) =
( f a1, f a2, f a3 )
-- Colours
{-| -}
pink : Color
pink =
rgba 255 105 180 1
{-| -}
hotPink : Color
hotPink =
rgba 255 0 66 1
{-| -}
lightRed : Color
lightRed =
rgba 239 41 41 1
{-| -}
red : Color
red =
rgba 204 0 0 1
{-| -}
darkRed : Color
darkRed =
rgba 164 0 0 1
{-| -}
lightOrange : Color
lightOrange =
rgba 252 175 62 1
{-| -}
orange : Color
orange =
rgba 245 121 0 1
{-| -}
darkOrange : Color
darkOrange =
rgba 206 92 0 1
{-| -}
lightYellow : Color
lightYellow =
rgba 255 233 79 1
{-| -}
yellow : Color
yellow =
rgba 237 212 0 1
{-| -}
darkYellow : Color
darkYellow =
rgba 196 160 0 1
{-| -}
lightGreen : Color
lightGreen =
rgba 138 226 52 1
{-| -}
green : Color
green =
rgba 115 210 22 1
{-| -}
darkGreen : Color
darkGreen =
rgba 78 154 6 1
{-| -}
lightBlue : Color
lightBlue =
rgba 114 159 207 1
{-| -}
blue : Color
blue =
rgba 52 101 164 1
{-| -}
darkBlue : Color
darkBlue =
rgba 32 74 135 1
{-| -}
lightPurple : Color
lightPurple =
rgba 173 127 168 1
{-| -}
purple : Color
purple =
rgba 117 80 123 1
{-| -}
darkPurple : Color
darkPurple =
rgba 92 53 102 1
{-| -}
lightBrown : Color
lightBrown =
rgba 233 185 110 1
{-| -}
brown : Color
brown =
rgba 193 125 17 1
{-| -}
darkBrown : Color
darkBrown =
rgba 143 89 2 1
{-| -}
black : Color
black =
rgba 0 0 0 1
{-| -}
white : Color
white =
rgba 255 255 255 1
{-| -}
lightGrey : Color
lightGrey =
rgba 238 238 236 1
{-| -}
grey : Color
grey =
rgba 211 215 207 1
{-| -}
darkGrey : Color
darkGrey =
rgba 186 189 182 1
{-| -}
lightGray : Color
lightGray =
rgba 238 238 236 1
{-| -}
gray : Color
gray =
rgba 211 215 207 1
{-| -}
darkGray : Color
darkGray =
rgba 186 189 182 1
{-| -}
lightCharcoal : Color
lightCharcoal =
rgba 136 138 133 1
{-| -}
charcoal : Color
charcoal =
rgba 85 87 83 1
{-| -}
darkCharcoal : Color
darkCharcoal =
rgba 46 52 54 1
{-| -}
blank : Color
blank =
rgba 0 0 0 0
| true | module GraphicSVG exposing
( Stencil, Shape, Collage(..), GraphicSVG
, collage, mapCollage
, App, app
, EllieApp, ellieApp
, line, polygon, openPolygon, ngon, triangle, rightTriangle, isosceles, sideAngleSide, square, rect, rectangle, roundedRect, circle, oval, wedge
, filled, outlined, repaint, addOutline, rgb, rgba, hsl, hsla
, group
, html
, curve, Pull(..), curveHelper
, LineType, noline, solid, dotted, dashed, longdash, dotdash, custom
, text, size, bold, italic, underline, strikethrough, centered, alignLeft, alignRight, selectable, sansserif, serif, fixedwidth, customFont
, move, rotate, scale, scaleX, scaleY, mirrorX, mirrorY, skewX, skewY
, clip, union, subtract, outside, ghost
, notifyTap, notifyTapAt, notifyEnter, notifyEnterAt, notifyLeave, notifyLeaveAt, notifyMouseMoveAt, notifyMouseDown, notifyMouseDownAt, notifyMouseUp, notifyMouseUpAt, notifyTouchStart, notifyTouchStartAt, notifyTouchEnd, notifyTouchEndAt, notifyTouchMoveAt
, makeTransparent, addHyperlink, puppetShow
, graphPaper, graphPaperCustom, map
, gradient, radialGradient, stop, transparentStop, rotateGradient
, Color, black, blank, blue, brown, charcoal, darkBlue, darkBrown, darkCharcoal, darkGray, darkGreen, darkGrey, darkOrange, darkPurple, darkRed, darkYellow, gray, green, grey, hotPink, lightBlue, lightBrown, lightCharcoal, lightGray, lightGreen, lightGrey, lightOrange, lightPurple, lightRed, lightYellow, orange, pink, purple, red, white, yellow
, Transform, ident, moveT, rotateT, scaleT, skewT, rotateAboutT, transform
, Msg(..), createSVG
)
{-| A library for creating SVG graphics in a way that is compatible with Elm's
old Graphics library. Also includes built-in functions for creating games and
other applications including keyboard presses and mouse movements.
# Basic Types
@docs Stencil, Shape, Collage, GraphicSVG
# Rendering To Screen
@docs collage, mapCollage
# App
@docs App, app
# EllieApp
@docs EllieApp, ellieApp
# Stencils
@docs line, polygon, openPolygon, ngon, triangle, rightTriangle, isosceles, sideAngleSide, square, rect, rectangle, roundedRect, circle, oval, wedge
# Creating Shapes from Stencils
@docs filled, outlined, repaint, addOutline, rgb, rgba, hsl, hsla
# Grouping Shapes
@docs group
# Rendering HTML
This feature is still very much experimental. Cross-platform support is
not guaranteed and weird things can happen.
@docs html
# Curves
@docs curve, Pull, curveHelper
# Line Styles
@docs LineType, noline, solid, dotted, dashed, longdash, dotdash, custom
# Text
@docs text, size, bold, italic, underline, strikethrough, centered, alignLeft, alignRight, selectable, sansserif, serif, fixedwidth, customFont
# Transformations
@docs move, rotate, scale, scaleX, scaleY, mirrorX, mirrorY, skewX, skewY
# Group Operations
@docs clip, union, subtract, outside, ghost
# Notifications
@docs notifyTap, notifyTapAt, notifyEnter, notifyEnterAt, notifyLeave, notifyLeaveAt, notifyMouseMoveAt, notifyMouseDown, notifyMouseDownAt, notifyMouseUp, notifyMouseUpAt, notifyTouchStart, notifyTouchStartAt, notifyTouchEnd, notifyTouchEndAt, notifyTouchMoveAt
# Miscellaneous
@docs makeTransparent, addHyperlink, puppetShow
# Helpers
@docs graphPaper, graphPaperCustom, map
# Let there be colours!
@docs Color, black, blank, blue, brown, charcoal, darkBlue, darkBrown, darkCharcoal, darkGray, darkGreen, darkGrey, darkOrange, darkPurple, darkRed, darkYellow, gray, green, grey, hotPink, lightBlue, lightBrown, lightCharcoal, lightGray, lightGreen, lightGrey, lightOrange, lightPurple, lightRed, lightYellow, orange, pink, purple, red, white, yellow
# Let there be gradients!
@docs stop, transparentStop, gradient, radialGradient, rotateGradient
# Advanced Transformations
_Advanced section warning!_ These functions provide a way to interface on a lower
level to the transformations normally handled in the background by GraphicSVG.
Most users should be happy to use the regular functions applied directly to shapes,
which are provided in the section above this one.
@docs Transform, ident, moveT, rotateT, scaleT, skewT, rotateAboutT, transform
# More Advanced Things
Don't worry about these unless you *_really_* know what you're doing!
@docs Msg, createSVG
-}
{- Library created by PI:NAME:<NAME>END_PI and Dr. PI:NAME:<NAME>END_PI
for the McMaster University Computing and Software Outreach Program
and CompSci 1JC3, with input and testing from the rest of the Outreach
team.
Last updated: January 25th, 2019
-}
import Array
import Browser exposing (UrlRequest)
import Browser.Dom exposing (Viewport, getViewportOf)
import Browser.Events exposing (onKeyDown, onKeyPress, onKeyUp, onResize)
import Browser.Navigation exposing (Key)
import Char
import Dict
import Html
import Html.Attributes
import Html.Events
import Json.Decode as D exposing (..)
import String exposing (..)
import Svg exposing (Attribute)
import Svg.Attributes exposing (..)
import Task
import Time exposing (..)
import Tuple
import Url exposing (Url)
import Color
{-| A primitive template representing the shape you wish to draw. This must be turned into
a `Shape` before being drawn to the screen with `collage` (see below).
-}
type Stencil
= Circle Float
| Rect Float Float
| RoundRect Float Float Float
| Oval Float Float
| BezierPath ( Float, Float ) (List ( ( Float, Float ), ( Float, Float ) ))
| Polygon (List ( Float, Float ))
| Path (List ( Float, Float ))
| Text Face String
{-| A filled, outlined, or filled and outlined object that can be drawn to the screen using `collage`.
-}
type Shape userMsg
= Inked (Maybe Color) (Maybe ( LineType, Color )) Stencil
| ForeignObject Float Float (Html.Html userMsg)
| Move ( Float, Float ) (Shape userMsg)
| Rotate Float (Shape userMsg)
| Scale Float Float (Shape userMsg)
| Skew Float Float (Shape userMsg)
| Transformed Transform (Shape userMsg)
| Group (List (Shape userMsg))
| GroupOutline (Shape userMsg)
| AlphaMask (Shape userMsg) (Shape userMsg)
| Clip (Shape userMsg) (Shape userMsg)
| Everything
| Notathing
| Link String (Shape userMsg)
| Tap userMsg (Shape userMsg)
| TapAt (( Float, Float ) -> userMsg) (Shape userMsg)
| EnterShape userMsg (Shape userMsg)
| EnterAt (( Float, Float ) -> userMsg) (Shape userMsg)
| Exit userMsg (Shape userMsg)
| ExitAt (( Float, Float ) -> userMsg) (Shape userMsg)
| MouseDown userMsg (Shape userMsg)
| MouseDownAt (( Float, Float ) -> userMsg) (Shape userMsg)
| MouseUp userMsg (Shape userMsg)
| MouseUpAt (( Float, Float ) -> userMsg) (Shape userMsg)
| MoveOverAt (( Float, Float ) -> userMsg) (Shape userMsg)
| TouchStart userMsg (Shape userMsg)
| TouchEnd userMsg (Shape userMsg)
| TouchStartAt (( Float, Float ) -> userMsg) (Shape userMsg)
| TouchEndAt (( Float, Float ) -> userMsg) (Shape userMsg)
| TouchMoveAt (( Float, Float ) -> userMsg) (Shape userMsg)
| GraphPaper Float Float Color
type FontAlign
= AlignLeft
| AlignCentred
| AlignRight
{-| To compose multiple pages or components which each have a Msg/view/update, we need to map messages.
(Ask if you don't know what this means.)
-}
map : (a -> b) -> Shape a -> Shape b
map f sh =
case sh of
Inked fillClr lt stencil ->
Inked fillClr lt stencil
ForeignObject w h htm ->
ForeignObject w h (Html.map f htm)
Move v shape ->
Move v (map f shape)
Rotate deg shape ->
Rotate deg (map f shape)
Scale sx sy shape ->
Scale sx sy (map f shape)
Skew skx sky shape ->
Skew skx sky (map f shape)
Transformed tm shape ->
Transformed tm (map f shape)
Link href shape ->
Link href (map f shape)
AlphaMask sh1 sh2 ->
AlphaMask (map f sh1) (map f sh2)
Clip sh1 sh2 ->
Clip (map f sh1) (map f sh2)
Everything ->
Everything
Notathing ->
Notathing
Tap msg shape ->
Tap (f msg) (map f shape)
TapAt msg shape ->
TapAt (f << msg) (map f shape)
EnterShape msg shape ->
EnterShape (f msg) (map f shape)
EnterAt msg shape ->
EnterAt (f << msg) (map f shape)
Exit msg shape ->
Exit (f msg) (map f shape)
ExitAt msg shape ->
ExitAt (f << msg) (map f shape)
MouseDown msg shape ->
MouseDown (f msg) (map f shape)
MouseDownAt msg shape ->
MouseDownAt (f << msg) (map f shape)
MouseUp msg shape ->
MouseUp (f msg) (map f shape)
MouseUpAt msg shape ->
MouseUpAt (f << msg) (map f shape)
MoveOverAt msg shape ->
MoveOverAt (f << msg) (map f shape)
TouchStart msg shape ->
TouchStart (f msg) (map f shape)
TouchEnd msg shape ->
TouchEnd (f msg) (map f shape)
TouchStartAt msg shape ->
TouchStartAt (f << msg) (map f shape)
TouchEndAt msg shape ->
TouchEndAt (f << msg) (map f shape)
TouchMoveAt msg shape ->
TouchMoveAt (f << msg) (map f shape)
Group shapes ->
Group (List.map (map f) shapes)
GroupOutline cmbndshp ->
GroupOutline (map f cmbndshp)
GraphPaper s th c ->
GraphPaper s th c
{-| To apply the function over all the shapes in the given `Collage` using the `map` function.
(Ask if you don't know what this means.)
-}
mapCollage : (a -> b) -> Collage a -> Collage b
mapCollage f (Collage w h shapes) =
Collage w h (List.map (map f) shapes)
{-| The `GraphicSVG` type alias represents the drawable surface of the window.
This type is only used to define a type signature for a user defined `view` as follows:
view : GraphicSVG.GraphicSVG userMsg
for use with `graphicsApp` and as follows:
view : Model -> GraphicSVG.GraphicSVG MyMsg
for use with `notificationsApp`, `gameApp` and `App`.
These assume that `Model` is the name of the user model type alias and
`MyMsg` is the name of the user message type. Simply substitute the names
actually used for these labels.
THIS IS DEPRECIATED AND ONLY KEPT FOR COMPATIBILITY WITH THE PREVIOUS VERSION;
Use "Collage userMsg" instead of "GraphicSVG userMsg", as they are identical except in name.
-}
type alias GraphicSVG userMsg =
Collage userMsg
{-| The `Color` type is used for filling or outlining a `Stencil`.
-}
type Color
= Solid Color.Color
| Gradient Gradient
type Gradient =
RadialGradient (List Stop)
| LinearGradient Float {- rotation -} (List Stop)
{-| Create a radial gradient from a list of colour stops.
-}
radialGradient : List Stop -> Color
radialGradient stops =
Gradient <| RadialGradient stops
{-| Create a linear gradient from a list of colour stops.
-}
gradient : List Stop -> Color
gradient stops =
Gradient <| LinearGradient 0 stops
{-| Rotate a linear gradient by a certain angle in radians.
-}
rotateGradient : Float -> Color -> Color
rotateGradient r grad =
case grad of
Gradient (LinearGradient rot stops) -> Gradient (LinearGradient (rot + r) stops)
radialGrad -> radialGrad
type Stop =
Stop Float {- stop position -} Float {- transparency -} Color.Color {- colour -}
{-| A colour stop in a gradient. This takes a colour and a position.
-}
stop : Color -> Float -> Stop
stop col pos =
case col of
Solid colour -> Stop pos 1 colour
_ -> Stop pos 1 (Color.rgba 0 0 0 0)
{-| A colour stop with transparency.
-}
transparentStop : Color -> Float -> Float -> Stop
transparentStop col pos alpha =
case col of
Solid colour -> Stop pos alpha colour
_ -> Stop pos 1 (Color.rgba 0 0 0 alpha)
createGradientSVG : String -> (Float, Float) -> Gradient -> Svg.Svg userMsg
createGradientSVG id (wid, hei) grad =
let
isRadial = case grad of
RadialGradient _ -> True
_ -> False
squareSize = if wid > hei then 2*wid else 2*hei
w = case grad of
RadialGradient stops ->
case List.head <| List.reverse stops of
Just (Stop pos _ _) -> pos
Nothing -> 0
LinearGradient _ stops ->
case List.head <| List.reverse stops of
Just (Stop pos _ _) -> pos
Nothing -> 0
createStop : Stop -> Svg.Svg userMsg
createStop (Stop pos trans colour) =
let
start = if isRadial then 0 else (1 - w/squareSize)/2 * 100
percent = if isRadial then pos / w * 100 else start + pos/squareSize * 100
percentTxt = String.fromFloat percent ++ "%"
colourTxt = "stop-color:" ++ mkRGB colour ++ ";"
opacityTxt = "stop-opacity:" ++ String.fromFloat trans ++ ";"
in
Svg.stop [Svg.Attributes.offset percentTxt, Svg.Attributes.style (colourTxt ++ opacityTxt)] []
defs = Svg.defs []
[
case grad of
LinearGradient _ stops ->
Svg.linearGradient
[ Svg.Attributes.id (id ++ "gradient")
, Svg.Attributes.gradientTransform <| "rotate(" ++ String.fromFloat rotation ++ "rad)"
--, Svg.Attributes.x1 "0%"
--, Svg.Attributes.y1 "0%"
--, Svg.Attributes.x2 "100%"
--, Svg.Attributes.y2 "0%"
, Svg.Attributes.gradientTransform ("rotate("++ String.fromFloat rotation ++ "rad)")
]
(List.map createStop stops)
RadialGradient stops ->
Svg.radialGradient
[ Svg.Attributes.id (id ++ "gradient")
, Svg.Attributes.cx "0"--(String.fromFloat (squareSize/2))
, Svg.Attributes.cy "0"--(String.fromFloat (squareSize/2))
, Svg.Attributes.r (String.fromFloat w)
, Svg.Attributes.gradientUnits "userSpaceOnUse"
]
(List.map createStop stops)
]
rotation =
case grad of
LinearGradient rot stops ->
rot * 180 / pi
_ -> 0
in
Svg.g [mask ("url(#" ++ id ++ "mask)")]
[ defs
, Svg.rect
([ x <| String.fromFloat <| -squareSize / 2
, y <| String.fromFloat <| -squareSize / 2
, width <| String.fromFloat squareSize
, height <| String.fromFloat squareSize
, fill ("url(#" ++ id ++ "gradient)")
, Svg.Attributes.id (id ++ "grad")
, Svg.Attributes.transform <| "rotate(" ++ String.fromFloat rotation ++")"
]
)
[]
]
{-| The `LineType` type is used to define the appearance of an outline for a `Stencil`.
`LineType` also defines the appearence of `line` and `curve`.
-}
type LineType
= NoLine
| Unbroken Float
| Broken (List ( Float, Float )) Float
{-| The `Face` type describes the appearance of a text `Stencil`.
THIS IS NOT EXPOSED BY ANY TYPE AND IS NOW NOT EXPOSED BY THE LIBARY.
-}
type Face
= Face
Float
-- size
Bool
-- bold
Bool
-- italic
Bool
-- underline
Bool
-- strikethrough
Bool
-- selectable
Font
-- font alignment
FontAlign
{-| The `Font` type describes the font of a text `Stencil`.
THIS IS NOT EXPOSED BY ANY TYPE AND IS NOW NOT EXPOSED BY THE LIBARY.
-}
type Font
= Serif
| Sansserif
| FixedWidth
| Custom String
{-| To make it easier to read the code defining a `curve`,
and to make sure we always use the right number of curve points
and pull points (which is one more curve point than pull points),
we define a special `Pull` type, whose first point is the point
we pull towards, and second point is the end point for this
curve segments.
-}
type Pull
= Pull ( Float, Float ) ( Float, Float )
{-| _Advanced Function Warning!_ `app` takes one parameter of its own type of the form:
{
init = \flags url key -> (model, cmd)
, view = \model -> { title = "Your Title goes here",
, body = view model
}
, update = \userMsg userModel -> ( userModel, Cmd userMsg )
, subscriptions = \userModel -> Sub userMsg
, onUrlRequest = \urlRequest -> userMsg
, onUrlChange = \url -> userMsg
}
This matches the Elm architecture and is analogous to `Browser.application`.
-}
app :
{ init : flags -> Url -> Key -> ( userModel, Cmd userMsg )
, update : userMsg -> userModel -> ( userModel, Cmd userMsg )
, view : userModel -> { title : String, body : Collage userMsg }
, subscriptions : userModel -> Sub userMsg
, onUrlRequest : UrlRequest -> userMsg
, onUrlChange : Url -> userMsg
}
-> App flags userModel userMsg
app input =
Browser.application
{ init =
\flags url key ->
let
userInit =
Tuple.first <| input.init flags url key
userView =
(input.view userInit).body
(Collage initW initH _) =
userView
userInitCmd =
Tuple.second <| input.init flags url key
in
( ( userInit, { initHiddenModel | cw = initW, ch = initH } ), initialCmd <| Cmd.map Graphics userInitCmd )
, update = hiddenAppUpdate input.view input.update
, view = hiddenAppView input.view
, subscriptions = subs <| input.subscriptions
, onUrlRequest = Graphics << input.onUrlRequest
, onUrlChange = Graphics << input.onUrlChange
}
{-| This type alias is only used as a target for a user `main` type signature to make
the type signature more clear and concise when `main` calls `app`:
main : App Flags Model Msg
main =
app Tick
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
, onUrlRequest = onUrlRequest
, onUrlChange = onUrlChange
}
where `Tick` is a message handler called once per browser window update,
`Flags` is the type alias (or type) of the flags input from JavaScript
`Model` is the type alias of the user persistent model, and
`Msg` is the name of the user message type; if other names are used,
they can just be substituted for these names.
Note that "type alias" could also be an ordinary "type" in all case,
just that the syntax for producing a new type is not as clean as using a
type alias for a record.
-}
type alias App flags userModel userMsg =
Program flags ( userModel, HiddenModel ) (Msg userMsg)
subs : (userModel -> Sub userMsg) -> ( userModel, gModel ) -> Sub (Msg userMsg)
subs userSubs ( userModel, _ ) =
Sub.batch
([ onResize (\_ _ -> WindowResize Nothing)
]
++ [ Sub.map Graphics (userSubs userModel) ]
)
hiddenAppUpdate :
(userModel -> { title : String, body : Collage userMsg })
-> (userMsg -> userModel -> ( userModel, Cmd userMsg ))
-> Msg userMsg
-> ( userModel, HiddenModel )
-> ( ( userModel, HiddenModel ), Cmd (Msg userMsg) )
hiddenAppUpdate userView userUpdate msg ( userModel, gModel ) =
let
mapUserCmd cmd =
Cmd.map Graphics cmd
(Collage cw ch _) =
(userView userModel).body
in
case msg of
Graphics message ->
let
( newModel, userCmds ) =
userUpdate message userModel
in
( ( newModel, { gModel | cw = cw, ch = ch } )
, mapUserCmd userCmds
)
WindowResize mWH ->
case mWH of
Just ( w, h ) ->
( ( userModel
, { gModel
| sw = Basics.toFloat w
, sh = Basics.toFloat h
}
)
, Cmd.none
)
Nothing ->
( (userModel, gModel)
, getViewportSize
)
ReturnPosition message ( x, y ) ->
let
( newModel, userCmds ) =
userUpdate
(message (convertCoords ( x, y ) gModel))
userModel
in
( ( newModel, gModel ), mapUserCmd userCmds )
NoOp -> (( userModel, gModel ), Cmd.none)
hiddenAppView :
(userModel -> { title : String, body : Collage userMsg })
-> ( userModel, HiddenModel )
-> { title : String, body : List (Html.Html (Msg userMsg)) }
hiddenAppView userView ( userModel, _ ) =
let
userViewEval =
userView userModel
title =
userViewEval.title
(Collage w h shapes) =
userViewEval.body
in
{ title = title, body = [ createCollage w h shapes ] }
{-| This type alias is only used as a target for a user `main` type signature to make
the type signature more clear and concise when `main` calls `ellieApp`:
main : EllieApp Flags Model Msg
main =
ellieApp Tick
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
}
where `Tick` is a message handler called once per browser window update,
`Flags` is the type alias (or type) of the flags input from JavaScript
`Model` is the type alias of the user persistent model, and
`Msg` is the name of the user message type; if other names are used,
they can just be substituted for these names.
Note that "type alias" could also be an ordinary "type" in all case,
just that the syntax for producing a new type is not as clean as using a
type alias for a record.
-}
type alias EllieApp flags userModel userMsg =
Program flags ( userModel, HiddenModel ) (Msg userMsg)
{-| _Advanced Function Warning!_ `ellieApp` takes one parameter of its own type of the form:
{
init = \flags url key -> (model, cmd)
, view = \model -> { title = "Your Title goes here",
, body = view model
}
, update = \userMsg userModel -> ( userModel, Cmd userMsg )
, subscriptions = \userModel -> Sub userMsg
}
This matches the Elm architecture and is analogous to `Browser.document`.
It is called ellieApp because this version is compatible with the online
Elm IDE Ellie.
-}
ellieApp :
{ init : flags -> ( userModel, Cmd userMsg )
, update : userMsg -> userModel -> ( userModel, Cmd userMsg )
, view : userModel -> { title : String, body : Collage userMsg }
, subscriptions : userModel -> Sub userMsg
}
-> EllieApp flags userModel userMsg
ellieApp input =
Browser.document
{ init =
\flags ->
let
userInit =
Tuple.first <| input.init flags
userView =
(input.view userInit).body
(Collage initW initH _) =
userView
userInitCmd =
Tuple.second <| input.init flags
in
( ( userInit, { initHiddenModel | cw = initW, ch = initH } ), initialCmd <| Cmd.map Graphics userInitCmd )
, update = hiddenAppUpdate input.view input.update
, view = hiddenAppView input.view
, subscriptions = subs <| input.subscriptions
}
convertCoords : ( Float, Float ) -> HiddenModel -> ( Float, Float )
convertCoords ( x, y ) gModel =
let
sw =
gModel.sw
sh =
gModel.sh
cw =
gModel.cw
ch =
gModel.ch
aspectout =
if not (sh == 0) then
sw / sh
else
4 / 3
aspectin =
if not (ch == 0) then
cw / ch
else
4 / 3
scaledInX =
aspectout < aspectin
scaledInY =
aspectout > aspectin
cscale =
if scaledInX then
sw / cw
else if scaledInY then
sh / ch
else
1
in
( (x - sw / 2) / cscale
, (y + sh / 2) / cscale
)
initialCmd :
Cmd (Msg userMsg)
-> Cmd (Msg userMsg)
initialCmd userCmd =
Cmd.batch
[ getViewportSize
, userCmd
]
getViewportSize : Cmd (Msg userMsg)
getViewportSize = Task.attempt
(\rvp -> case rvp of
Ok vp ->
WindowResize
<| Just ( round vp.viewport.width, round vp.viewport.height )
Err _ -> NoOp
)
(getViewportOf "render")
{-| The `Msg` type encapsulates all GraphicSVG internal messages.
This type is only used to define type signature fors user defined
`view` and `main` as follows:
view : GraphicSVG.Collage (GraphicSVG.Msg Msg)
for use with `graphicsApp` and `notificationsApp`, and as follows:
view : Model -> GraphicSVG.Collage (GraphicSVG.Msg Msg)
for use with `gameApp`.
It is also used to define the type signature for
a user supplied `main` as follows:
main : Program Never (GraphicsModel Model Msg) (GraphicSVG.Msg Msg)
for use with `graphicsApp` and `notificationsApp`, and as follows:
main : Program Never (GamesModel Model Msg) (GraphicSVG.Msg Msg)
for use when `main` calls `gameApp`
These assume that `Model` is the type alias of the user persistent model, and
`Msg` is the name of the user message type.
-}
type Msg userMsg
= Graphics userMsg
| WindowResize (Maybe ( Int, Int ))
| ReturnPosition (( Float, Float ) -> userMsg) ( Float, Float )
| NoOp
{-| The `HiddenModel` type alias encapsulates the GraphicSVG internal model
which is not exposed to user code.
-}
type alias HiddenModel =
{ cw : Float
, ch : Float
, sw : Float
, sh : Float
}
initHiddenModel : HiddenModel
initHiddenModel =
{ cw = 0
, ch = 0
, sw = 0
, sh = 0
}
{-| Create a line from a point to a point. Use `outlined` to convert to a viewable
`Shape`.
-}
line : ( Float, Float ) -> ( Float, Float ) -> Stencil
line p1 p2 =
Path [ p1, p2 ]
{-| Create a closed shape given a list of points. Can use `outlined` or `filled` to
convert to a `Shape`.
-}
polygon : List ( Float, Float ) -> Stencil
polygon ptList =
Polygon ptList
{-| Create an open shape given a list of points. Unlike with polygon, the first and
last points will not join up automatically. Can use `outlined` or `filled` to
convert to a `Shape`.
-}
openPolygon : List ( Float, Float ) -> Stencil
openPolygon ptList =
Path ptList
{-| Create a regular polygon with a given number of sides and radius. Examples:
ngon 3 50 -- triangle
ngon 5 50 -- pentagon
ngon 8 50 -- octogon
-}
ngon : Int -> Float -> Stencil
ngon n r =
Polygon <|
List.map
(ptOnCircle r (Basics.toFloat n) << Basics.toFloat)
(List.range 0 n)
{-| Synonym for `ngon 3`. Creates a triangle with a given size.
-}
triangle : Float -> Stencil
triangle r =
ngon 3 r
{-| Creates a right-angled triangle with a given base and height.
-}
rightTriangle : Float -> Float -> Stencil
rightTriangle base height =
polygon [ ( 0, 0 ), ( base, 0 ), ( 0, height ) ]
{-| Creates an isosceles triangle with a given base and height.
-}
isosceles : Float -> Float -> Stencil
isosceles base height =
polygon [ ( -base / 2, 0 ), ( base / 2, 0 ), ( 0, height ) ]
{-| Creates a triangle given two side lengths and the angle between them.
For example, `sideAngleSide 30 (degrees 45) 50` creates a triangle with side lengths
30 and 50 with an angle of 45 degrees between them.
-}
sideAngleSide : Float -> Float -> Float -> Stencil
sideAngleSide sideOne angle sideTwo =
polygon [ sideTwoPoint angle sideOne, ( 0, 0 ), ( sideTwo, 0 ) ]
sideTwoPoint : Float -> Float -> ( Float, Float )
sideTwoPoint angle sideOne =
( cos angle * sideOne, sin angle * sideOne )
{-| Creates a square with a given side length. (Synonym for `rect s s`)
-}
square : Float -> Stencil
square r =
Rect r r
{-| Creates a rectangle with a given width and height.
-}
rect : Float -> Float -> Stencil
rect w h =
Rect w h
{-| Synonym for `rect`.
-}
rectangle : Float -> Float -> Stencil
rectangle w h =
Rect w h
{-| Creates a rectangle with a given width, height, and circular rounded
corners with the given radius.
-}
roundedRect : Float -> Float -> Float -> Stencil
roundedRect w h r =
RoundRect w h r
{-| Creates a circle with a given radius.
-}
circle : Float -> Stencil
circle r =
Circle r
{-| Creates an oval with a given width and height.
-}
oval : Float -> Float -> Stencil
oval w h =
Oval w h
{-| Creates a graph paper with squares of a given size.
-}
graphPaper : Float -> Shape userMsg
graphPaper s =
GraphPaper s 1 (Solid <| Color.fromRgba { red = 135, green = 206, blue = 250, alpha = 1})
{-| Creates graph paper with squares of a given size, with a user-defined thickness and colour.
-}
graphPaperCustom : Float -> Float -> Color -> Shape userMsg
graphPaperCustom s th c =
GraphPaper s th c
createGraph : ( Float, Float ) -> Float -> Float -> Color -> Shape userMsg
createGraph ( w, h ) s th c =
let
sxi =
ceiling (w / (s * 2))
syi =
ceiling (h / (s * 2))
xlisti =
List.range -sxi sxi
ylisti =
List.range -syi syi
in
group
(List.map (createGraphX h s th c << Basics.toFloat) xlisti
++ List.map (createGraphY w s th c << Basics.toFloat) ylisti
)
createGraphX : Float -> Float -> Float -> Color -> Float -> Shape userMsg
createGraphX h s th c x =
filled c (rect th h) |> move ( x * s, 0 )
createGraphY : Float -> Float -> Float -> Color -> Float -> Shape userMsg
createGraphY w s th c y =
filled c (rect w th) |> move ( 0, y * s )
{-| Creates a wedge with a given radius, and a given fraction of a circle.
wedge 50 0.5 -- semi-circle
wedge 50 0.25 -- quarter-circle
wedge 50 0.75 -- three-quarter circle
-}
wedge : Float -> Float -> Stencil
wedge r frac =
let
n =
frac * 360 / 10 + 5
ni =
round n
dlta =
frac / Basics.toFloat ni
in
Polygon <|
if frac > 0 then
[ ( 0, 0 ), wedgeHelper r -frac ]
++ List.map
(wedgeHelper r
<< (*) dlta
<< Basics.toFloat
)
(List.range -ni ni)
++ [ wedgeHelper r frac, ( 0, 0 ) ]
else
[]
wedgeHelper : Float -> Float -> ( Float, Float )
wedgeHelper r cn =
let
angle =
turns (0.5 * cn)
in
( r * cos angle, r * sin angle )
ptOnCircle : Float -> Float -> Float -> ( Float, Float )
ptOnCircle r n cn =
let
angle =
turns (cn / n)
in
( r * cos angle, r * sin angle )
{-| Creates a curve starting at a point, pulled towards a point, ending at a third point. For example,
curve (0,0) [Pull (0,10) (0,20)]
gives a curve starting at (0,0), pulled towards (0,10) and ending at (0,20).
Think about curves as what you get when you take a bunch of
bendy sticks with their ends glued down to a board, and then pulling each stick
towards another point.
You always need an initial point and at least one `Pull`, but you can add as many `Pull`s as you want to
add additional curve segments, but each curve segment can only bend one way, since it is pulled in one direction.
-}
curve : ( Float, Float ) -> List Pull -> Stencil
curve ( a, b ) list =
BezierPath ( a, b ) (List.map curveListHelper list)
curveListHelper : Pull -> ( ( Float, Float ), ( Float, Float ) )
curveListHelper (Pull ( a, b ) ( c, d )) =
( ( a, b ), ( c, d ) )
{-| Add a hyperlink to any `Shape`:
circle 10
|> filled red
|> addHyperlink "http://outreach.mcmaster.ca"
-}
addHyperlink : String -> Shape userMsg -> Shape userMsg
addHyperlink link shape =
Link link shape
{-| Creates a text `Stencil`. You can change this `Stencil` using the text helper
functions. Note that `|> filled ...` or `|> outlined ...` must go at the _end_ of the text helper functions
(ie note that all these functions have type `Stencil -> Stencil`). For example,
text "Hello World"
|> fixedwidth
|> bold
|> size 14
|> filled black
-}
text : String -> Stencil
text str =
Text (Face 12 False False False False False Serif AlignLeft) str
{-| Apply to a curve or group of curves in order to view their start points,
end points and `Pull` points. Helpful while perfecting curves.
curve (0,0) [Pull (0,10) (0,20)]
|> curveHelper
-}
curveHelper : Shape userMsg -> Shape userMsg
curveHelper shape =
case shape of
Inked _ _ (BezierPath ( a, b ) list) ->
group [ shape, generateCurveHelper ( a, b ) list ]
Move s sh ->
Move s (curveHelper sh)
Rotate r sh ->
Rotate r (curveHelper sh)
Scale sx sy sh ->
Scale sx sy (curveHelper sh)
Skew skx sky sh ->
Skew skx sky (curveHelper sh)
Transformed tm sh ->
Transformed tm (curveHelper sh)
Group list ->
Group (List.map curveHelper list)
GroupOutline cmbndshp ->
GroupOutline (curveHelper cmbndshp)
Link s sh ->
Link s (curveHelper sh)
AlphaMask reg sh ->
AlphaMask reg (curveHelper sh)
Clip reg sh ->
Clip reg (curveHelper sh)
Tap userMsg sh ->
Tap userMsg (curveHelper sh)
TapAt userMsg sh ->
TapAt userMsg (curveHelper sh)
EnterShape userMsg sh ->
EnterShape userMsg (curveHelper sh)
EnterAt userMsg sh ->
EnterAt userMsg (curveHelper sh)
Exit userMsg sh ->
Exit userMsg (curveHelper sh)
ExitAt userMsg sh ->
ExitAt userMsg (curveHelper sh)
MouseDown userMsg sh ->
MouseDown userMsg (curveHelper sh)
MouseDownAt userMsg sh ->
MouseDownAt userMsg (curveHelper sh)
MouseUp userMsg sh ->
MouseUp userMsg (curveHelper sh)
MouseUpAt userMsg sh ->
MouseUpAt userMsg (curveHelper sh)
MoveOverAt userMsg sh ->
MoveOverAt userMsg (curveHelper sh)
TouchStart userMsg sh ->
TouchStart userMsg (curveHelper sh)
TouchEnd userMsg sh ->
TouchEnd userMsg (curveHelper sh)
TouchStartAt userMsg sh ->
TouchStartAt userMsg (curveHelper sh)
TouchEndAt userMsg sh ->
TouchEndAt userMsg (curveHelper sh)
TouchMoveAt userMsg sh ->
TouchMoveAt userMsg (curveHelper sh)
-- no changes for the rest...
Inked clr ln sh ->
Inked clr ln sh
ForeignObject w h htm ->
ForeignObject w h htm
Everything ->
Everything
Notathing ->
Notathing
GraphPaper s th clr ->
GraphPaper s th clr
generateCurveHelper :
( Float, Float )
-> List ( ( Float, Float ), ( Float, Float ) )
-> Shape userMsg
generateCurveHelper ( a, b ) list =
let
l1Array =
Array.fromList
([ ( a, b ) ]
++ List.concat (List.map createTopLevelList list)
)
in
group [ generateCHLines l1Array, generateCHCircles l1Array ]
generateCHLines : Array.Array ( Float, Float ) -> Shape userMsg
generateCHLines ar =
let
len =
Array.length ar
in
group (List.map (generateCHLine ar) (List.range 0 (len - 2)))
generateCHLine : Array.Array ( Float, Float ) -> Int -> Shape userMsg
generateCHLine ar int =
let
p1 =
case Array.get int ar of
Just p ->
p
Nothing ->
( 0, 0 )
p2 =
case Array.get (int + 1) ar of
Just p ->
p
Nothing ->
( 0, 0 )
in
outlined (dashed 0.5) black (line p1 p2)
generateCHCircles : Array.Array ( Float, Float ) -> Shape userMsg
generateCHCircles ar =
let
len =
Array.length ar
in
group (List.map (generateCHCircle ar) (List.range 0 (len - 1)))
generateCHCircle : Array.Array ( Float, Float ) -> Int -> Shape userMsg
generateCHCircle ar int =
let
p1 =
case Array.get int ar of
Just p ->
p
Nothing ->
( 0, 0 )
ptStr =
pairToString p1
in
group
[ filled red (circle 2)
, text ("(" ++ ptStr ++ ")")
|> filled black
|> move ( 5, 5 )
]
|> move p1
createTopLevelList : ( ( a, b ), ( a, b ) ) -> List ( a, b )
createTopLevelList ( ( a, b ), ( c, d ) ) =
[ ( a, b ), ( c, d ) ]
matrixMult : Transform -> Transform -> Transform
matrixMult ( ( a, c, e ), ( b, d, f ) ) ( ( a1, c1, e1 ), ( b1, d1, f1 ) ) =
( ( a * a1 + c * b1, a * c1 + c * d1, e + a * e1 + c * f1 )
, ( b * a1 + d * b1, b * c1 + d * d1, f + b * e1 + d * f1 )
)
{-| The identity or "starting" matrix. Applying this matrix to a shape is the equivalent
of doing no transformations at all. The matrix itself looks like
```
ident = ( ( 1 , 0 , 0 ) , ( 0 , 1 , 0 ) )
```
or,
```
1 0 0
0 1 0
```
-}
ident : Transform
ident =
( ( 1, 0, 0 )
, ( 0, 1, 0 )
)
{-| A matrix representing an SVG transformation matrix of the form:
```
( ( a , c , e ) , ( b , d , f ) )
```
or
```
a c e
b d f
```
The a, c, b and d control transformations such as skew, rotate and scale;
e and f control translation.
These matrices are best built up by starting with the identity matrix and
applying any number of `*T` functions (see below); for example,
```
myTransform =
ident
|> scaleT 2 2
|> rotateT (degrees 30)
|> moveT (0, 50)
```
-}
type alias Transform =
( ( Float, Float, Float ), ( Float, Float, Float ) )
{-| Apply a move (translation) transformation to a transformation matrix.
This is designed to be used as part of a pipe:
```
ident
|> moveT (15,-30.5)
```
-}
moveT : ( Float, Float ) -> Transform -> Transform
moveT ( u, v ) ( ( a, c, tx ), ( b, d, ty ) ) =
( ( a, c, tx + a * u + c * v )
, ( b, d, ty + b * u + d * v )
)
{-| Apply a rotation transformation to a transformation matrix.
This is designed to be used as part of a pipe:
```
ident
|> moveT (15,-30.5)
|> rotateT (degrees -30)
```
-}
rotateT : Float -> Transform -> Transform
rotateT rad ( ( a, c, tx ), ( b, d, ty ) ) =
let
sinX =
sin rad
cosX =
cos rad
in
( ( a * cosX + c * sinX, c * cosX - a * sinX, tx )
, ( b * cosX + d * sinX, d * cosX - b * sinX, ty )
)
{-| Apply a scale transformation to a transformation matrix. The first argument
scales in x and the second argument scales in y. This is designed
to be used as part of a pipe:
```
ident
|> moveT (15,-30.5)
|> rotateT (degrees -30)
|> scaleT 4 0.4
```
-}
scaleT : Float -> Float -> Transform -> Transform
scaleT sx sy ( ( a, c, tx ), ( b, d, ty ) ) =
( ( a * sx, c * sy, tx )
, ( b * sx, d * sy, ty )
)
{-| Apply a skew transformation to a matrix. The first argument
skews in x and the second argument skews in y. This is designed
to be used as part of a pipe:
```
ident
|> moveT (15,-30.5)
|> rotateT (degrees -30)
|> scaleT 4 0.4
|> skewT 0.5 1.3
```
-}
skewT : Float -> Float -> Transform -> Transform
skewT skx sky ( ( a, c, tx ), ( b, d, ty ) ) =
let
tanX =
tan -skx
tanY =
tan -sky
in
( ( a + c * tanY, c + a * tanX, tx )
, ( b + d * tanY, d + b * tanX, ty )
)
{-| Apply a rotation about a given point to a `Transform` matrix. For example,
the following transform will rotate a `Shape` 30 degrees about the point (0,50):
```
rotateAbout050 =
ident
|> rotateAboutT (0, 50) (degrees 30)
```
-}
rotateAboutT : ( Float, Float ) -> Float -> Transform -> Transform
rotateAboutT ( u, v ) rad ( ( a, c, tx ), ( b, d, ty ) ) =
let
sinX =
sin rad
cosX =
cos rad
in
( ( a * cosX + c * sinX, c * cosX - a * sinX, tx + a * u + c * v - v * (c * cosX - a * sinX) - u * (a * cosX + c * sinX) )
, ( b * cosX + d * sinX, d * cosX - b * sinX, ty + b * u + d * v - v * (d * cosX - b * sinX) - u * (b * cosX + d * sinX) )
)
{-| Manually transform a shape using a `Transform` matrix. Matrix multiplication will
be used to apply the given matrix to any transformations of the current
shape. This is designed to be used in the usual way in a pipe:
```
circle 10
|> filled red
|> transform moveLeft50
moveLeft50 =
ident
|> moveT (50,0)
```
NOTE: Transformations generated using pipes this way are applied backwards compared
to the "regular" `Shape userMsg` transformation functions. For example, `rect0` and
`rect1` below are equivalent:
```
myTransform =
ident
|> scaleT 2 2
|> rotateT (degrees 30)
|> moveT (0, 50)
rect0 =
rect 20 10
|> filled red
|> transform myTransform
rect1 =
rect 20 10
|> filled red
|> move (0, 50)
|> rotate (degrees 30)
|> scale 2
```
On the other hand, single transformations produce a result consistent with the
`Shape userMsg` transformations. `rect2` is also equivalent to the two above:
```
moveRight50 =
ident
|> moveT (50,0)
scale2 =
ident
|> scaleT 2 2
rotate30 =
ident
|> rotateT (degrees 30)
rect2 =
rect 20 10
|> filled red
|> transform moveRight50
|> transform scale2
|> transform rotate30
```
However, chaining together transformations in this way is discouraged because
it is less efficient than the regular `Shape userMsg` transformations in
the "Transformations" section.
-}
transform : Transform -> Shape userMsg -> Shape userMsg
transform tm sh =
Transformed tm sh
{-| The Collage type represents the drawable surface of the window which contains
a (x, y) pair of horizontal and vertical dimensions (arbitrary units,
not necessarily in pixels) to which the drawing surface will be scaled,
and the \`List' of Shapes to be drawn on the drawing surface.
-}
type Collage userMsg
= Collage Float Float (List (Shape userMsg))
{-| Creates a blank canvas on which you can draw. Takes a width, height and a
list of `Shape`s. Use this in your `view` functions in the three types of Apps above:
collage 500 500
[
circle 10 |> filled red
]
-}
collage : Float -> Float -> List (Shape userMsg) -> Collage userMsg
collage w h shapes =
Collage w h shapes
createCollage : Float -> Float -> List (Shape userMsg) -> Html.Html (Msg userMsg)
createCollage w h shapes =
Svg.svg
[ width "100%"
, height "100%"
, style "position:absolute;top:0px;left:0px;"
, viewBox
(String.fromFloat (-w / 2)
++ " "
++ String.fromFloat (-h / 2)
++ " "
++ String.fromFloat w
++ " "
++ String.fromFloat h
)
, id "render"
]
(cPath w h
:: [ Svg.g
[ clipPath "url(#cPath)" ]
(List.indexedMap
(\n -> createSVG (String.fromInt n) w h ident Graphics ReturnPosition)
shapes
)
]
)
cPath : Float -> Float -> Svg.Svg (Msg userMsg)
cPath w h =
Svg.defs []
[ Svg.clipPath
[ Svg.Attributes.id "cPath" ]
[ Svg.rect
[ width (String.fromFloat w)
, height (String.fromFloat h)
, x (String.fromFloat (-w / 2))
, y (String.fromFloat (-h / 2))
]
[]
]
]
{-| Take a `Collage` width and height as well as a list of tuples of depth and `Shape`.
to produce a list of `Shape`'s suitable for display as a group in a `Collage` with
`Shape`'s with lesser depth larger and in front of `Shape`'s with greater depth.
-}
puppetShow :
Float
-> Float
-> List ( Float, Shape userMsg )
-> List (Shape userMsg)
puppetShow w h listShapes =
List.map
(extractShape (Basics.max w h))
(List.sortWith flippedComparison listShapes)
extractShape : Float -> ( Float, Shape userMsg ) -> Shape userMsg
extractShape fl ( z, shape ) =
let
s =
fl / (fl + z)
in
shape |> scale s
flippedComparison : ( comparable, a ) -> ( comparable, b ) -> Order
flippedComparison ( f, _ ) ( s, _ ) =
compare s f
--Notification functions
{-| Receive a message (`userMsg`) when a `Shape` is clicked or tapped.
-}
notifyTap : userMsg -> Shape userMsg -> Shape userMsg
notifyTap msg shape =
Tap msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse or finger when the `Shape` is clicked or tapped.
-}
notifyTapAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyTapAt msg shape =
TapAt msg shape
{-| Receive a message (`userMsg`) when the mouse enters a `Shape`.
-}
notifyEnter : userMsg -> Shape userMsg -> Shape userMsg
notifyEnter msg shape =
EnterShape msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse enters a `Shape`.
-}
notifyEnterAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyEnterAt msg shape =
EnterAt msg shape
{-| Receive a message (`userMsg`) when the mouse leaves a `Shape`.
-}
notifyLeave : userMsg -> Shape userMsg -> Shape userMsg
notifyLeave msg shape =
Exit msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse leaves a `Shape`.
-}
notifyLeaveAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyLeaveAt msg shape =
ExitAt msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse is moved across a `Shape`.
-}
notifyMouseMoveAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyMouseMoveAt msg shape =
MoveOverAt msg shape
{-| Receive a message (`userMsg`) when the mouse button is pressed while the cursor is over a `Shape`.
-}
notifyMouseDown : userMsg -> Shape userMsg -> Shape userMsg
notifyMouseDown msg shape =
MouseDown msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse button is pressed while the cursor is over a `Shape`.
-}
notifyMouseDownAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyMouseDownAt msg shape =
MouseDownAt msg shape
{-| Receive a message (`userMsg`) when the mouse button is released while the cursor is over a `Shape`.
-}
notifyMouseUp : userMsg -> Shape userMsg -> Shape userMsg
notifyMouseUp msg shape =
MouseUp msg shape
{-| Receive a message (`userMsg`) with the x and y position of the mouse when the mouse button is released while the cursor is over a `Shape`.
-}
notifyMouseUpAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyMouseUpAt msg shape =
MouseUpAt msg shape
{-| Receive a message (`userMsg`) when the user begins touching a `Shape`.
-}
notifyTouchStart : userMsg -> Shape userMsg -> Shape userMsg
notifyTouchStart msg shape =
TouchStart msg shape
{-| Receive a message (`userMsg`) with the x and y position of the user's finger when the user begins touching a `Shape`.
-}
notifyTouchStartAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyTouchStartAt msg shape =
TouchStartAt msg shape
{-| Receive a message (`userMsg`) when the user lifts their finger off a `Shape`.
-}
notifyTouchEnd : userMsg -> Shape userMsg -> Shape userMsg
notifyTouchEnd msg shape =
TouchEnd msg shape
{-| Receive a message (`userMsg`) with the x and y position of the user's finger when the user lifts their finger off a `Shape`.
-}
notifyTouchEndAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyTouchEndAt msg shape =
TouchEndAt msg shape
{-| Receive a message (`userMsg`) with the x and y position of the user's finger when the user moves their finger over a `Shape`.
-}
notifyTouchMoveAt : (( Float, Float ) -> userMsg) -> Shape userMsg -> Shape userMsg
notifyTouchMoveAt msg shape =
TouchMoveAt msg shape
touchToPair : TouchPos -> ( Float, Float )
touchToPair tp =
case tp of
TouchPos x y ->
( x, -y )
mousePosDecoder =
D.map2 (\x y -> ( x, -y )) (D.field "offsetX" D.float) (D.field "offsetY" D.float)
onTapAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onTapAt msg =
Html.Events.on "click"
(D.map msg mousePosDecoder)
onEnterAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onEnterAt msg =
Html.Events.on "mouseover"
(D.map msg mousePosDecoder)
onLeaveAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onLeaveAt msg =
Html.Events.on "mouseleave"
(D.map msg mousePosDecoder)
onMoveAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onMoveAt msg =
Html.Events.on "mousemove"
(D.map msg mousePosDecoder)
onMouseDownAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onMouseDownAt msg =
Html.Events.on "mousedown"
(D.map msg mousePosDecoder)
onMouseUpAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onMouseUpAt msg =
Html.Events.on "mouseup"
(D.map msg mousePosDecoder)
onTouchStart : userMsg -> Html.Attribute userMsg
onTouchStart msg =
Html.Events.on "touchstart" (D.succeed msg)
onTouchStartAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onTouchStartAt msg =
Html.Events.on "touchstart"
(D.map (msg << touchToPair) touchDecoder)
onTouchEndAt : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onTouchEndAt msg =
Html.Events.on "touchend"
(D.map (msg << touchToPair) touchDecoder)
onTouchEnd : userMsg -> Html.Attribute userMsg
onTouchEnd msg =
Html.Events.on "touchend" (D.succeed msg)
onTouchMove : (( Float, Float ) -> userMsg) -> Html.Attribute userMsg
onTouchMove msg =
Html.Events.preventDefaultOn "touchmove"
(D.map (\a -> ( (msg << touchToPair) a, True )) touchDecoder)
type TouchPos
= TouchPos Float Float
touchDecoder : Decoder TouchPos
touchDecoder =
D.oneOf
[ D.at
[ "touches", "0" ]
(D.map2
TouchPos
(D.field "pageX" D.float)
(D.field "pageY" D.float)
)
, D.map2
TouchPos
(D.field "pageX" D.float)
(D.field "pageY" D.float)
]
{-| Create Svg from a Shape. This is considered an advanced function and
is usually not used. Instead, use collage as part of a regular GraphicSVG
app or create a widget with GraphicSVG.Widget.
-}
createSVG : String -> Float -> Float -> Transform -> (a -> b) -> (((Float,Float) -> a) -> (Float,Float) -> b) -> Shape a -> Svg.Svg b
createSVG id w h trans msgWrapper positionWrapper shape =
case shape of
Inked fillClr lt stencil ->
let
( ( a, c, tx ), ( b, d, ty ) ) =
trans
attrs =
case fillClr of
Just (Gradient _) ->
clrAttrs ++ strokeAttrs
_ -> transAttrs ++ clrAttrs ++ strokeAttrs
transAttrs =
[ Svg.Attributes.transform <|
"matrix("
++ (String.concat <|
List.intersperse "," <|
List.map
String.fromFloat
[ a, -b, c, -d, tx, -ty ]
)
++ ")"
]
nonexistBody =
case fillClr of
Nothing -> True
_ -> False
clrAttrs =
case fillClr of
Nothing -> [ fill "none"]
Just (Solid bodyClr) ->
[ fill (mkRGB bodyClr)
, fillOpacity (mkAlpha bodyClr)
]
Just (Gradient _) ->
[
Svg.Attributes.id id
, fill (mkRGB <| Color.rgb 255 255 255)
]
strokeAttrs =
case lt of
Nothing ->
[]
Just ( Unbroken th, Solid strokeClr ) ->
let nonStroke =
let opcty = getAlpha strokeClr
in th <= 0 || opcty <= 0
in
if nonStroke then [] else
[ strokeWidth (String.fromFloat th)
, stroke (mkRGB strokeClr)
, strokeOpacity (mkAlpha strokeClr)
]
Just ( Broken dashes th, Solid strokeClr ) ->
let nonStroke =
let opcty = getAlpha strokeClr
in th <= 0 || opcty <= 0 ||
List.all (\( on, _ ) -> on == 0) dashes
in
if nonStroke then [] else
[ strokeWidth (String.fromFloat th)
, stroke (mkRGB strokeClr)
, strokeOpacity (mkAlpha strokeClr)
]
++ [ strokeDasharray <|
String.concat
(List.intersperse "," <|
List.map pairToString dashes
)
]
Just ( _, _ ) ->
[]
basicShape = case stencil of
Circle r ->
Svg.circle
([ cx "0"
, cy "0"
, Svg.Attributes.r (String.fromFloat r)
]
++ attrs
)
[]
Rect rw rh ->
Svg.rect
([ x <| String.fromFloat <| -rw / 2
, y <| String.fromFloat <| -rh / 2
, width <| String.fromFloat rw
, height <| String.fromFloat rh
]
++ attrs
)
[]
RoundRect rw rh r ->
Svg.rect
([ x <| String.fromFloat <| -rw / 2
, y <| String.fromFloat <| -rh / 2
, rx <| String.fromFloat r
, ry <| String.fromFloat r
, width <| String.fromFloat rw
, height <| String.fromFloat rh
]
++ attrs
)
[]
Oval ow oh ->
Svg.ellipse
([ cx "0"
, cy "0"
, rx <| String.fromFloat <| 0.5 * ow
, ry <| String.fromFloat <| 0.5 * oh
]
++ attrs
)
[]
Polygon vertices ->
Svg.polygon
([ points <|
String.concat <|
List.intersperse " " <|
List.map pairToString vertices
]
++ attrs
)
[]
Path vertices ->
Svg.polyline
([ points <|
String.concat <|
List.intersperse " " <|
List.map pairToString vertices
]
++ attrs
)
[]
BezierPath start pts ->
Svg.path
([ Svg.Attributes.d <| createBezierString start pts ]
++ attrs
)
[]
Text (Face si bo i u s sel f align) str ->
let
bol =
if bo then
"font-weight: bold;"
else
""
it =
if i then
"font-style: italic;"
else
""
txtDec =
if u && s then
"text-decoration: underline line-through;"
else if u then
"text-decoration: underline;"
else if s then
"text-decoration: line-through;"
else
""
select =
if not sel then
"-webkit-touch-callout: none;\n-webkit-user-select: none;\n-khtml-user-select: none;\n-moz-user-select: none;\n-ms-user-select: none;\nuser-select: none;cursor: default;"
else
""
anchor =
case align of
AlignCentred ->
"middle"
AlignLeft ->
"start"
AlignRight ->
"end"
font =
case f of
Sansserif ->
"sans-serif;"
Serif ->
"serif;"
FixedWidth ->
"monospace;"
Custom fStr ->
fStr ++ ";"
sty =
bol
++ it
++ txtDec
++ "font-family: "
++ font
++ select
in
Svg.text_
([ x "0"
, y "0"
, Svg.Attributes.style sty
, Svg.Attributes.fontSize (String.fromFloat si)
, Svg.Attributes.textAnchor anchor
, Html.Attributes.contenteditable True
]
++ [ Svg.Attributes.transform <|
"matrix("
++ (String.concat <|
List.intersperse "," <|
List.map
String.fromFloat
[ a, -b, -c, d, tx, -ty ]
)
++ ")"
]
++ [ Svg.Attributes.xmlSpace "preserve" ]
++ clrAttrs ++ strokeAttrs
)
[ Svg.text str ]
gradientDefs =
case fillClr of
Just (Gradient gr) ->
Just (createGradientSVG id (w, h) gr)
_ -> Nothing
in
if nonexistBody && List.isEmpty strokeAttrs then Svg.g [] []
else case gradientDefs of
Just gDefs ->
Svg.g transAttrs
[
Svg.mask [Svg.Attributes.id (id ++ "mask")]
[
basicShape
]
, gDefs
]
Nothing ->
basicShape
ForeignObject fw fh htm ->
let
( ( a, c, tx ), ( b, d, ty ) ) =
trans
in
Svg.foreignObject
[ width <| String.fromFloat fw
, height <| String.fromFloat fh
, Svg.Attributes.transform
<| "matrix(" ++ (String.concat <| List.intersperse ","
<| List.map
String.fromFloat
[ a, -b, -c, d, tx, -ty ]) ++ ")"
] [ Html.map msgWrapper htm ]
Move v sh ->
createSVG id w h (moveT v trans) msgWrapper positionWrapper sh
Everything ->
createSVG id w h ident msgWrapper positionWrapper (rect w h |> filled white)
Notathing ->
createSVG id w h ident msgWrapper positionWrapper (rect w h |> filled black)
Rotate deg sh ->
createSVG id w h (rotateT deg trans) msgWrapper positionWrapper sh
Scale sx sy sh ->
createSVG id w h (scaleT sx sy trans) msgWrapper positionWrapper sh
Skew sx sy sh ->
createSVG id w h (skewT sx sy trans) msgWrapper positionWrapper sh
Transformed tm sh ->
createSVG id w h (matrixMult trans tm) msgWrapper positionWrapper sh
Link href sh ->
Svg.a
[ xlinkHref href, target "_blank" ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
AlphaMask region sh ->
Svg.g []
[ Svg.defs []
[ Svg.mask
[ Svg.Attributes.id ("m" ++ id) ]
[ createSVG
(id ++ "m")
w
h
trans
msgWrapper
positionWrapper
(Group [ Everything, region |> repaint black ])
]
]
, Svg.g
[ Svg.Attributes.mask ("url(#m" ++ id ++ ")") ]
[ createSVG (id ++ "mm") w h trans msgWrapper positionWrapper sh ]
]
Clip region sh ->
Svg.g []
[ Svg.defs []
[ Svg.mask
[ Svg.Attributes.id ("c" ++ id) ]
[ createSVG
(id ++ "c")
w
h
trans
msgWrapper
positionWrapper
(Group [ Notathing, region |> repaint white ])
]
]
, Svg.g
[ Svg.Attributes.mask ("url(#c" ++ id ++ ")") ]
[ createSVG (id ++ "cc") w h trans msgWrapper positionWrapper sh ]
]
Tap msg sh ->
Svg.g
[ Html.Events.onClick (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TapAt msg sh ->
Svg.g
[ onTapAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
EnterShape msg sh ->
Svg.g
[ Html.Events.onMouseEnter (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
EnterAt msg sh ->
Svg.g
[ onEnterAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
Exit msg sh ->
Svg.g
[ Html.Events.onMouseLeave (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
ExitAt msg sh ->
Svg.g
[ onLeaveAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MouseDown msg sh ->
Svg.g
[ Html.Events.onMouseDown (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MouseDownAt msg sh ->
Svg.g
[ onMouseDownAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MouseUp msg sh ->
Svg.g
[ Html.Events.onMouseUp (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MouseUpAt msg sh ->
Svg.g
[ onMouseUpAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
MoveOverAt msg sh ->
Svg.g
[ onMoveAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchStart msg sh ->
Svg.g
[ onTouchStart (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchEnd msg sh ->
Svg.g
[ onTouchEnd (msgWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchStartAt msg sh ->
Svg.g
[ onTouchStartAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchEndAt msg sh ->
Svg.g
[ onTouchStartAt (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
TouchMoveAt msg sh ->
Svg.g
[ onTouchMove (positionWrapper msg) ]
[ createSVG id w h trans msgWrapper positionWrapper sh ]
Group shapes ->
Svg.g [] <|
List.indexedMap
(\n ->
createSVG
(id ++ "g" ++ String.fromInt n)
w
h
trans
msgWrapper
positionWrapper
)
shapes
GroupOutline cmbndshp ->
createSVG id w h trans msgWrapper positionWrapper cmbndshp
GraphPaper s th c ->
if th <= 0 || s < 2 * th then
Svg.g [] []
else
createSVG id w h trans msgWrapper positionWrapper <|
createGraph ( w, h ) s th c
{-| Display HTML inside an SVG foreignObject.
-}
html : Float -> Float -> Html.Html userMsg -> Shape userMsg
html w h htm =
ForeignObject w h htm
--Filling / outlining functions
{-| Fill a `Stencil` with a `Color`, creating a `Shape`;
Note that any `Stencil` converted to a `Shape` this way can be made
transparent (for instance by using the `blank` `Color`) but will not be
"click-through", meaning that the body will catch any attached notifications
and not let them through to any visible `Shape`(s) revealed beneath them.
circle 10
|> filled red
-}
filled : Color -> Stencil -> Shape userMsg
filled color stencil =
Inked (Just color) Nothing stencil
{-| Make a `Shape` into a ghost. Mostly to be used inside of the clip operations.
Note that although the `blank` `Color` is transparent, it will still catch
notifications enabled on the `Shape` or block them if not enabled on the `Shape`.
-}
ghost : Stencil -> Shape userMsg
ghost stencil =
Inked (Just blank) Nothing stencil
{-| Repaint an already-`filled` `Shape`. This is helpful for repainting every `Shape` inside a `group` as well.
Repaints the outline the same color as the body of the shape including the outline, if used;
Note that this can repaint with a transparent `Color` (for instance, the `blank` `Color`) but
will never have the ability to be "click-through" so that it will always block (or catch)
notifications to covered `Shape`(s) revealed beneath.
group
[ circle 10
|> filled orange
, rect 10 40
|> filled blue
]
|> repaint green
-}
repaint : Color -> Shape userMsg -> Shape userMsg
repaint color shape =
case shape of
Inked _ Nothing st ->
Inked (Just color) Nothing st
Inked _ (Just ( lt, _ )) st ->
Inked (Just color) (Just ( lt, color )) st
Move s sh ->
Move s (repaint color sh)
Rotate r sh ->
Rotate r (repaint color sh)
Scale sx sy sh ->
Scale sx sy (repaint color sh)
Skew skx sky sh ->
Skew skx sky (repaint color sh)
Transformed tm sh ->
Transformed tm (repaint color sh)
Group shapes ->
Group (List.map (repaint color) shapes)
GroupOutline cmbndshp ->
GroupOutline (repaint color cmbndshp)
Link s sh ->
Link s (repaint color sh)
AlphaMask reg sh ->
AlphaMask reg (repaint color sh)
Clip reg sh ->
Clip reg (repaint color sh)
Tap userMsg sh ->
Tap userMsg (repaint color sh)
TapAt userMsg sh ->
TapAt userMsg (repaint color sh)
EnterShape userMsg sh ->
EnterShape userMsg (repaint color sh)
EnterAt userMsg sh ->
EnterAt userMsg (repaint color sh)
Exit userMsg sh ->
Exit userMsg (repaint color sh)
ExitAt userMsg sh ->
ExitAt userMsg (repaint color sh)
MouseDown userMsg sh ->
MouseDown userMsg (repaint color sh)
MouseDownAt userMsg sh ->
MouseDownAt userMsg (repaint color sh)
MouseUp userMsg sh ->
MouseUp userMsg (repaint color sh)
MouseUpAt userMsg sh ->
MouseUpAt userMsg (repaint color sh)
MoveOverAt userMsg sh ->
MoveOverAt userMsg (repaint color sh)
TouchStart userMsg sh ->
TouchStart userMsg (repaint color sh)
TouchEnd userMsg sh ->
TouchEnd userMsg (repaint color sh)
TouchStartAt userMsg sh ->
TouchStartAt userMsg (repaint color sh)
TouchEndAt userMsg sh ->
TouchEndAt userMsg (repaint color sh)
TouchMoveAt userMsg sh ->
TouchMoveAt userMsg (repaint color sh)
-- no changes for the rest...
ForeignObject w h htm ->
ForeignObject w h htm
Everything ->
Everything
Notathing ->
Notathing
GraphPaper s th _ ->
GraphPaper s th color
{-| Outline a Stencil with a `LineType` and `Color`, creating a `Shape`;
Note that this is the only way to convert a `Stencil` into a `Shape` that is
"click-through" as if the body is not just transparent but doesn't exist at all.
It works for all `Stencil`'s except for `Text` which can never be made "click-through"
due to a permanent transparent background area that cannot be disabled.
circle 10
|> outlined (solid 5) red
-}
outlined : LineType -> Color -> Stencil -> Shape userMsg
outlined style outlineClr stencil =
let
lineStyle =
case style of
NoLine ->
Nothing
_ ->
Just ( style, outlineClr )
in
Inked Nothing lineStyle stencil
{-| Add an outline to an already-filled `Shape`.
When applied to `Group`'s including `Shape`'s that have had `union` applied to them,
the outline will have half the expected stroke width only outside the `Shape`'s and
for `Shape`'s with `clip` or `subtract` applied to them, the half width stroke will be
interior to the composite shapes displayed.
The limitation is that when displaying "clip's" or "subtract's" containing "Group's",
the outline for the "Group's" won't be visibile at all (less common), nor will the
outline's for "clip's" or "subtract's" inside "Group's" be visible (more common);
also, the outline for the clipping or subtraction pattern may not be as expected when
the pattern is a "Group" as it won't appear at all in a "clip".
In these cases the workaround is just as before this was made available, to build up
the outlines desired using combinations of other shapes such as curves, clipped or
subtracted shapes, convential pre-applied outlines, etc.
Note that when applied to `Group`(s), `Clip`(s), and `AlphaMask`(s) (from subtracts),
the body colour may still be transparent so that `Shape`(s) can be revealed beneath,
but the bodies are not "click-through" so that notifications can be passed through to them,
and the transparent bodies can still capture notifications enabled on the resulting `Shape`(s).
circle 10
|> filled red
|> addOutline (solid 5) white
-}
addOutline : LineType -> Color -> Shape userMsg -> Shape userMsg
addOutline style outlineClr shape =
let
lineStyle =
case style of
NoLine ->
Nothing
_ ->
Just ( style, outlineClr )
in
case shape of
Inked clr _ st ->
Inked clr lineStyle st
Move s sh ->
Move s (addOutline style outlineClr sh)
Rotate r sh ->
Rotate r (addOutline style outlineClr sh)
Scale sx sy sh ->
Scale sx sy (addOutline style outlineClr sh)
Skew skx sky sh ->
Skew skx sky (addOutline style outlineClr sh)
Transformed tm sh ->
Transformed tm (addOutline style outlineClr sh)
Group list ->
let
innerlist =
List.filterMap
(\shp ->
case shp of
-- remove old outline shape
GroupOutline _ ->
Nothing
_ ->
Just <| addOutline NoLine black shp
)
list
in
case innerlist of
[] ->
{- should never happen -}
Group []
hd :: [] ->
addOutline style outlineClr hd
_ ->
if lineStyle == Nothing then
Group innerlist
else
let
outlnshp =
GroupOutline <|
subtract
(Group innerlist)
(Group
(List.map
(addOutline style outlineClr)
innerlist
)
)
in
Group <| innerlist ++ [ outlnshp ]
-- don't add an outline to one that's already been added but it should
-- never get here as GroupOutline should always be inside a Group which
-- will already have processed it, whether to change or remove it...
GroupOutline cmbndshp ->
GroupOutline cmbndshp
AlphaMask reg sh ->
let
ptrn =
addOutline NoLine black reg
inside =
addOutline NoLine black sh
in
if lineStyle == Nothing then
AlphaMask ptrn inside
else
let
ptrnlnd =
addOutline style outlineClr reg
newshp =
addOutline style outlineClr sh
ptrnoutln =
Clip inside ptrnlnd
shpoutln =
Clip inside newshp
in
AlphaMask ptrn <|
Group
[ inside
, GroupOutline <| Group [ shpoutln, ptrnoutln ]
]
Clip reg sh ->
let
ptrn =
addOutline NoLine black reg
inside =
addOutline NoLine black sh
in
if lineStyle == Nothing then
Clip ptrn inside
else
let
ptrnlnd =
addOutline style outlineClr (reg |> repaint blank)
newshp =
addOutline style outlineClr sh
ptrnoutln =
Clip inside ptrnlnd
shpoutln =
Clip inside newshp
in
Clip ptrn <|
Group
[ inside
, GroupOutline <| Group [ shpoutln, ptrnoutln ]
]
Link s sh ->
Link s (addOutline style outlineClr sh)
Tap userMsg sh ->
Tap userMsg (addOutline style outlineClr sh)
TapAt userMsg sh ->
TapAt userMsg (addOutline style outlineClr sh)
EnterShape userMsg sh ->
EnterShape userMsg (addOutline style outlineClr sh)
EnterAt userMsg sh ->
EnterAt userMsg (addOutline style outlineClr sh)
Exit userMsg sh ->
Exit userMsg (addOutline style outlineClr sh)
ExitAt userMsg sh ->
ExitAt userMsg (addOutline style outlineClr sh)
MouseDown userMsg sh ->
MouseDown userMsg (addOutline style outlineClr sh)
MouseDownAt userMsg sh ->
MouseDownAt userMsg (addOutline style outlineClr sh)
MouseUp userMsg sh ->
MouseUp userMsg (addOutline style outlineClr sh)
MouseUpAt userMsg sh ->
MouseUpAt userMsg (addOutline style outlineClr sh)
MoveOverAt userMsg sh ->
MoveOverAt userMsg (addOutline style outlineClr sh)
TouchStart userMsg sh ->
TouchStart userMsg (addOutline style outlineClr sh)
TouchEnd userMsg sh ->
TouchEnd userMsg (addOutline style outlineClr sh)
TouchStartAt userMsg sh ->
TouchStartAt userMsg (addOutline style outlineClr sh)
TouchEndAt userMsg sh ->
TouchEndAt userMsg (addOutline style outlineClr sh)
TouchMoveAt userMsg sh ->
TouchMoveAt userMsg (addOutline style outlineClr sh)
-- no changes for the rest...
ForeignObject w h htm ->
ForeignObject w h htm
Everything ->
Everything
Notathing ->
Notathing
GraphPaper s th clr ->
GraphPaper s th clr
multAlpha : Color.Color -> Float -> Color.Color
multAlpha color n =
let
colRec = Color.toRgba color
in
Color.fromRgba { colRec | alpha = colRec.alpha * n }
{-| Make a `Shape` transparent by the fraction given. Multiplies on top of other transparencies:
circle 10
|> filled red
|> makeTransparent 0.5
--results in a transparency of 0.5 (half vislible)
circle 10
|> filled red
|> makeTransparent 0.5
|> makeTransparent 0.5
--results in a transparency of 0.25 (a quarter visible)
-}
makeTransparent : Float -> Shape userMsg -> Shape userMsg
makeTransparent alpha shape =
case shape of
Inked Nothing (Just ( lineType, Solid colour )) st ->
Inked Nothing (Just ( lineType, Solid (multAlpha colour alpha))) st
Inked (Just (Solid colour)) (Just ( lineType, Solid sColour )) st ->
Inked (Just <| Solid (multAlpha colour alpha))
(Just ( lineType, Solid <| multAlpha sColour alpha)) st
Inked (Just (Solid colour)) Nothing st ->
Inked (Just <| Solid (multAlpha colour alpha)) Nothing st
Inked a b c ->
Inked a b c
ForeignObject w h htm ->
ForeignObject w h htm
Move s sh ->
Move s (makeTransparent alpha sh)
Rotate r sh ->
Rotate r (makeTransparent alpha sh)
Scale sx sy sh ->
Scale sx sy (makeTransparent alpha sh)
Skew skx sky sh ->
Skew skx sky (makeTransparent alpha sh)
Transformed tm sh ->
Transformed tm (makeTransparent alpha sh)
Group list ->
Group (List.map (makeTransparent alpha) list)
GroupOutline cmbndshp ->
GroupOutline (makeTransparent alpha cmbndshp)
Link s sh ->
Link s (makeTransparent alpha sh)
AlphaMask reg sh ->
AlphaMask reg (makeTransparent alpha sh)
Clip reg sh ->
Clip reg (makeTransparent alpha sh)
Everything ->
Everything
Notathing ->
Notathing
Tap userMsg sh ->
Tap userMsg (makeTransparent alpha sh)
TapAt userMsg sh ->
TapAt userMsg (makeTransparent alpha sh)
EnterShape userMsg sh ->
EnterShape userMsg (makeTransparent alpha sh)
EnterAt userMsg sh ->
EnterAt userMsg (makeTransparent alpha sh)
Exit userMsg sh ->
Exit userMsg (makeTransparent alpha sh)
ExitAt userMsg sh ->
ExitAt userMsg (makeTransparent alpha sh)
MouseDown userMsg sh ->
MouseDown userMsg (makeTransparent alpha sh)
MouseDownAt userMsg sh ->
MouseDownAt userMsg (makeTransparent alpha sh)
MouseUp userMsg sh ->
MouseUp userMsg (makeTransparent alpha sh)
MouseUpAt userMsg sh ->
MouseUpAt userMsg (makeTransparent alpha sh)
MoveOverAt userMsg sh ->
MoveOverAt userMsg (makeTransparent alpha sh)
TouchStart userMsg sh ->
TouchStart userMsg (makeTransparent alpha sh)
TouchEnd userMsg sh ->
TouchEnd userMsg (makeTransparent alpha sh)
TouchStartAt userMsg sh ->
TouchStartAt userMsg (makeTransparent alpha sh)
TouchEndAt userMsg sh ->
TouchEndAt userMsg (makeTransparent alpha sh)
TouchMoveAt userMsg sh ->
TouchMoveAt userMsg (makeTransparent alpha sh)
GraphPaper s th (Solid colour) ->
GraphPaper s th (Solid <| multAlpha colour alpha)
GraphPaper s th (Gradient gr) ->
GraphPaper s th (Gradient gr)
--Line styles
{-| Define a`LineType` that doesn't exist, doesn't appear.
-}
noline : () -> LineType
noline () =
NoLine
{-| Define a solid `LineType` with the given width.
-}
solid : Float -> LineType
solid th =
Unbroken th
{-| Define a dotted `LineType` with the given width.
-}
dotted : Float -> LineType
dotted th =
Broken [ ( th, th ) ] th
{-| Define a dashed `LineType` with the given width. Dashes are short line segments, versus dots which are theoretically points, but may be drawn with very short line segments.
-}
dashed : Float -> LineType
dashed th =
Broken [ ( th * 5, th * 2.5 ) ] th
{-| Define a dashed `LineType` with the given width, where the dashes are longer than normal.
-}
longdash : Float -> LineType
longdash th =
Broken [ ( th * 12, th * 6 ) ] th
{-| Define a `LineType` with the given width, including alternating dots and dashes.
-}
dotdash : Float -> LineType
dotdash th =
Broken [ ( th, th ), ( th * 5, th ) ] th
{-| A custom line defined by a list of (on,off):
custom [ ( 10, 5 ) ] 5 -- a line with dashes 10 long and spaces 5 long
custom [ ( 10, 5 ), ( 20, 5 ) ] -- on for 10, off 5, on 20, off 5
-}
custom : List ( Float, Float ) -> Float -> LineType
custom list th =
Broken list th
makePair : a -> ( a, a )
makePair n =
( n, n )
--Text functions
{-| Apply to a `text` `Stencil` to change the font size of the text.
The size has a unit called "points", which depends on the size and type of screen used, but try 12 to start.
-}
size : Float -> Stencil -> Stencil
size sze stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face sze bo i u s sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to make the text bold.
-}
bold : Stencil -> Stencil
bold stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si True i u s sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to make the text italicized (slanted).
-}
italic : Stencil -> Stencil
italic stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo True u s sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to underline the text.
-}
underline : Stencil -> Stencil
underline stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i True s sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to put a line through the centre of the text.
-}
strikethrough : Stencil -> Stencil
strikethrough stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u True sel f c) str
a ->
a
{-| Apply to a `text` `Stencil` to make the text selectable (so users can copy your text and paste it elsewhere).
-}
selectable : Stencil -> Stencil
selectable stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s True f c) str
a ->
a
{-| Apply to a `text` `Stencil` to right-align the text.
-}
alignRight : Stencil -> Stencil
alignRight stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel f AlignRight) str
a ->
a
{-| Apply to a `text` `Stencil` to centre the text.
-}
centered : Stencil -> Stencil
centered stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel f AlignCentred) str
a ->
a
{-| Apply to a `text` `Stencil` to left-align the text.
-}
alignLeft : Stencil -> Stencil
alignLeft stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel f AlignLeft) str
a ->
a
{-| Apply to a `text` `Stencil` to render the text with a Sans Serif font (ie one without thinner and thicker bits).
-}
sansserif : Stencil -> Stencil
sansserif stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel Sansserif c) str
a ->
a
{-| Apply to a `text` `Stencil` to render the text with a Serif font (ie one with thinner and thicker bits).
-}
serif : Stencil -> Stencil
serif stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel Serif c) str
a ->
a
{-| Apply to a text `Stencil` to render the text `Stencil` with a font in which every character has the same width.
This will mean that the letters line up from line to line which is important in programming languages like Elm.
-}
fixedwidth : Stencil -> Stencil
fixedwidth stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel FixedWidth c) str
a ->
a
{-| Apply to a `text` `Stencil` to render the text with a font of your choosing by specifying its name in a `String`.
_Use this sparingly as support for each font will vary across browsers and devices._
-}
customFont : String -> Stencil -> Stencil
customFont fStr stencil =
case stencil of
Text (Face si bo i u s sel f c) str ->
Text (Face si bo i u s sel (Custom fStr) c) str
a ->
a
--Transformation functions
{-| Rotate a `Shape` by the specified amount (in radians). Use the `degrees` function to convert
from degrees into radians:
[
rect 30 60
|> filled blue
|> rotate(degrees 30)
]
-}
rotate : Float -> Shape userMsg -> Shape userMsg
rotate theta shape =
Rotate theta shape
{-| Move a `Shape` by a number of units along the x-axis and y-axis.
-}
move : ( Float, Float ) -> Shape userMsg -> Shape userMsg
move disp shape =
Move disp shape
{-| Scale a `Shape` by a given factor.
-}
scale : Float -> Shape userMsg -> Shape userMsg
scale s shape =
Scale s s shape
{-| Scale a `Shape` in the x-axis by a given factor.
-}
scaleX : Float -> Shape userMsg -> Shape userMsg
scaleX s shape =
Scale s 1 shape
{-| Scale a `Shape` in the y-axis by a given factor.
-}
scaleY : Float -> Shape userMsg -> Shape userMsg
scaleY s shape =
Scale 1 s shape
{-| Flip a `Shape` along the x-axis.
-}
mirrorX : Shape userMsg -> Shape userMsg
mirrorX shape =
Scale -1 1 shape
{-| Flip a `Shape` along the y-axis.
-}
mirrorY : Shape userMsg -> Shape userMsg
mirrorY shape =
Scale 1 -1 shape
{-| Skew a `Shape` along the x-axis.
-}
skewX : Float -> Shape userMsg -> Shape userMsg
skewX skx shape =
Skew skx 0 shape
{-| Skew a `Shape` along the y-axis.
-}
skewY : Float -> Shape userMsg -> Shape userMsg
skewY sky shape =
Skew 0 sky shape
{-| Combine any number of `Shape` types into one `Shape` that can be
transformed (moved, rotated, scaled, etc) as one `Shape`.
-}
group : List (Shape userMsg) -> Shape userMsg
group shapes =
Group shapes
{-| Define a colour given its red, green and blue components.
-}
rgb : Float -> Float -> Float -> Color
rgb r g b =
rgba r g b 1
{-| Define a colour given its red, green, blue and alpha components.
Alpha is a decimal number (`Float`) from 0 to 1 representing the level of transparency.
-}
rgba : Float -> Float -> Float -> Float -> Color
rgba r g b a =
Solid <| Color.fromRgba { red = ssc r, green = ssc g, blue = ssc b, alpha = ssa a }
ssc : number -> number
ssc n =
clamp 0 255 n
ssa : Float -> Float
ssa n =
clamp 0 1 n
pairToString : ( Float, Float ) -> String
pairToString ( x, y ) =
String.fromFloat x ++ "," ++ String.fromFloat y
createBezierString : ( Float, Float ) -> List ( ( Float, Float ), ( Float, Float ) ) -> String
createBezierString first list =
"M " ++ pairToString first ++ String.concat (List.map bezierStringHelper list)
bezierStringHelper : ( ( Float, Float ), ( Float, Float ) ) -> String
bezierStringHelper ( ( a, b ), ( c, d ) ) =
" Q " ++ pairToString ( a, b ) ++ " " ++ pairToString ( c, d )
getAlpha : Color.Color -> Float
getAlpha colour =
(Color.toRgba colour).alpha
mkAlpha : Color.Color -> String
mkAlpha =
String.fromFloat << getAlpha
mkRGB : Color.Color -> String
mkRGB colour =
let
col = Color.toRgba colour
in
"rgba(" ++ (String.fromFloat col.red) ++ "," ++ (String.fromFloat col.green) ++ "," ++ (String.fromFloat col.blue) ++ "," ++ (String.fromFloat col.alpha) ++ ")"
{-| Define a colour given its hue, saturation and light components.
-}
hsl : Float -> Float -> Float -> Color
hsl h s l =
case convert h s l of
( r, g, b ) ->
rgba r g b 1
{-| Define a colour given its hue, saturation, light and alpha components.
Alpha is a decimal number (`Float`) from 0 to 1 representing the level of transparency.
-}
hsla : Float -> Float -> Float -> Float -> Color
hsla h s l a =
case convert h s l of
( r, g, b ) ->
rgba r g b a
-- Clip path functionality
{-| Clipping to a shape
Cut out the `Shape` on the right using the `Shape` on the left.
-}
clip : Shape userMsg -> Shape userMsg -> Shape userMsg
clip shape1 shape2 =
Clip shape1 shape2
{-| Shape union
Combine two `Shape`s together into one to use with clip.
-}
union : Shape userMsg -> Shape userMsg -> Shape userMsg
union shape1 shape2 =
Group [ shape1, shape2 ]
{-| Shape subtraction
Subtract the `Shape` on the left from the `Shape` on the right.
-}
subtract : Shape userMsg -> Shape userMsg -> Shape userMsg
subtract shape1 shape2 =
AlphaMask shape1 shape2
{-| The whole region outside the given `Shape`.
-}
outside : Shape userMsg -> Shape userMsg
outside shape =
AlphaMask shape shape
{-
Contributed by PI:NAME:<NAME>END_PI.
-}
convert : Float -> Float -> Float -> ( Float, Float, Float )
convert hue sat lit =
let
hue_ =
modFloat hue (2 * pi)
rgb_ =
toRGB_ hue_ sat lit
chroma =
findChroma lit sat
m =
findM lit chroma
in
mapTriple (\x -> x * 255) (mapTriple (\x -> x + m) rgb_)
findChroma : Float -> Float -> Float
findChroma lit sat =
(1 - abs (2 * lit - 1)) * sat
findHue_ : Float -> Float
findHue_ hue =
hue / degrees 60
findX : Float -> Float -> Float
findX chroma hue =
chroma * (1 - abs (modFloat (findHue_ hue) 2 - 1))
findM : Float -> Float -> Float
findM lit chroma =
lit - 0.5 * chroma
toRGB_ : Float -> Float -> Float -> ( Float, Float, Float )
toRGB_ hue sat lit =
let
chroma =
findChroma lit sat
hue_ =
findHue_ hue
x =
findX chroma hue
in
if hue_ >= 0 && hue_ < 1 then
( chroma, x, 0 )
else if hue_ >= 1 && hue_ < 2 then
( x, chroma, 0 )
else if hue_ >= 2 && hue_ < 3 then
( 0, chroma, x )
else if hue_ >= 3 && hue_ < 4 then
( 0, x, chroma )
else if hue_ >= 4 && hue_ < 5 then
( x, 0, chroma )
else if hue_ >= 5 && hue_ < 6 then
( chroma, 0, x )
else
( 0, 0, 0 )
{- Helper Functions -}
modFloat : Float -> Float -> Float
modFloat x m =
x - m * Basics.toFloat (floor (x / m))
mapTriple : (a -> b) -> ( a, a, a ) -> ( b, b, b )
mapTriple f ( a1, a2, a3 ) =
( f a1, f a2, f a3 )
-- Colours
{-| -}
pink : Color
pink =
rgba 255 105 180 1
{-| -}
hotPink : Color
hotPink =
rgba 255 0 66 1
{-| -}
lightRed : Color
lightRed =
rgba 239 41 41 1
{-| -}
red : Color
red =
rgba 204 0 0 1
{-| -}
darkRed : Color
darkRed =
rgba 164 0 0 1
{-| -}
lightOrange : Color
lightOrange =
rgba 252 175 62 1
{-| -}
orange : Color
orange =
rgba 245 121 0 1
{-| -}
darkOrange : Color
darkOrange =
rgba 206 92 0 1
{-| -}
lightYellow : Color
lightYellow =
rgba 255 233 79 1
{-| -}
yellow : Color
yellow =
rgba 237 212 0 1
{-| -}
darkYellow : Color
darkYellow =
rgba 196 160 0 1
{-| -}
lightGreen : Color
lightGreen =
rgba 138 226 52 1
{-| -}
green : Color
green =
rgba 115 210 22 1
{-| -}
darkGreen : Color
darkGreen =
rgba 78 154 6 1
{-| -}
lightBlue : Color
lightBlue =
rgba 114 159 207 1
{-| -}
blue : Color
blue =
rgba 52 101 164 1
{-| -}
darkBlue : Color
darkBlue =
rgba 32 74 135 1
{-| -}
lightPurple : Color
lightPurple =
rgba 173 127 168 1
{-| -}
purple : Color
purple =
rgba 117 80 123 1
{-| -}
darkPurple : Color
darkPurple =
rgba 92 53 102 1
{-| -}
lightBrown : Color
lightBrown =
rgba 233 185 110 1
{-| -}
brown : Color
brown =
rgba 193 125 17 1
{-| -}
darkBrown : Color
darkBrown =
rgba 143 89 2 1
{-| -}
black : Color
black =
rgba 0 0 0 1
{-| -}
white : Color
white =
rgba 255 255 255 1
{-| -}
lightGrey : Color
lightGrey =
rgba 238 238 236 1
{-| -}
grey : Color
grey =
rgba 211 215 207 1
{-| -}
darkGrey : Color
darkGrey =
rgba 186 189 182 1
{-| -}
lightGray : Color
lightGray =
rgba 238 238 236 1
{-| -}
gray : Color
gray =
rgba 211 215 207 1
{-| -}
darkGray : Color
darkGray =
rgba 186 189 182 1
{-| -}
lightCharcoal : Color
lightCharcoal =
rgba 136 138 133 1
{-| -}
charcoal : Color
charcoal =
rgba 85 87 83 1
{-| -}
darkCharcoal : Color
darkCharcoal =
rgba 46 52 54 1
{-| -}
blank : Color
blank =
rgba 0 0 0 0
| elm |
[
{
"context": " authorsColour =\n black\n\n -- Chris Schankula avatar\n char1 =\n group\n ",
"end": 13748,
"score": 0.9997289777,
"start": 13733,
"tag": "NAME",
"value": "Chris Schankula"
},
{
"context": "thors =\n group\n [ text \"Christopher W. Schankula\"\n |> size 4\n ",
"end": 16889,
"score": 0.9998865724,
"start": 16865,
"tag": "NAME",
"value": "Christopher W. Schankula"
},
{
"context": " |> move ( -35, -26 )\n , text \", Lucas Dutton,\"\n |> size 4\n ",
"end": 17150,
"score": 0.9998744726,
"start": 17138,
"tag": "NAME",
"value": "Lucas Dutton"
},
{
"context": " |> move ( 4.5, -26 )\n , text \" Nhan Q. D. Thai\"\n |> size 4\n ",
"end": 17414,
"score": 0.9998904467,
"start": 17399,
"tag": "NAME",
"value": "Nhan Q. D. Thai"
},
{
"context": " |> move ( 35, -26 )\n , text \"Yumna Irfan, Padma Pasupathi,\"\n |> size 4\n",
"end": 17671,
"score": 0.9998865128,
"start": 17660,
"tag": "NAME",
"value": "Yumna Irfan"
},
{
"context": "e ( 35, -26 )\n , text \"Yumna Irfan, Padma Pasupathi,\"\n |> size 4\n ",
"end": 17688,
"score": 0.9998798966,
"start": 17673,
"tag": "NAME",
"value": "Padma Pasupathi"
},
{
"context": " |> move ( 5, -32 )\n , text \"Chinmay Sheth, Christopher Kumar Anand\"\n |> ",
"end": 17947,
"score": 0.999876976,
"start": 17934,
"tag": "NAME",
"value": "Chinmay Sheth"
},
{
"context": " ( 5, -32 )\n , text \"Chinmay Sheth, Christopher Kumar Anand\"\n |> size 4\n ",
"end": 17972,
"score": 0.9998841286,
"start": 17949,
"tag": "NAME",
"value": "Christopher Kumar Anand"
},
{
"context": " outreachLogo ]\n , audio = Nothing \n }\n\n\n\n--Chris\n\n\nchar1R =\n { time = 0\n , eyeColour = RGB 2",
"end": 34429,
"score": 0.9606359005,
"start": 34424,
"tag": "NAME",
"value": "Chris"
},
{
"context": "selected = AvatarCreator.SelectNone\n }\n\n\n\n-- Dr Anand\n\n\nchar2R =\n { time = 0\n , eyeColour = RGB 1",
"end": 34754,
"score": 0.9955780506,
"start": 34749,
"tag": "NAME",
"value": "Anand"
},
{
"context": " , selected = AvatarCreator.SelectNone\n }\n\n\n\n-- Yumna\n\n\nchar3R =\n { time = 0\n , eyeColour = R",
"end": 35069,
"score": 0.6052894592,
"start": 35068,
"tag": "NAME",
"value": "Y"
},
{
"context": " , selected = AvatarCreator.SelectNone\n }\n\n\n\n--Ankit\n\n\nchar4R =\n { time = 0\n , eyeColour = RGB 3",
"end": 35393,
"score": 0.881706357,
"start": 35388,
"tag": "NAME",
"value": "Ankit"
},
{
"context": " , selected = AvatarCreator.SelectNone\n }\n\n\n\n-- Tanya\n\n\nchar5R =\n { time = 0\n , eyeColour = RGB 4",
"end": 35707,
"score": 0.8607802391,
"start": 35702,
"tag": "NAME",
"value": "Tanya"
},
{
"context": " , selected = AvatarCreator.SelectNone\n }\n\n\n\n-- Pedram\n\n\nchar6R =\n { time = 0\n , eyeColour = RGB 1",
"end": 36025,
"score": 0.9853034616,
"start": 36019,
"tag": "NAME",
"value": "Pedram"
},
{
"context": " , selected = AvatarCreator.SelectNone\n }\n\n\n\n-- Chitwan\n\n\nchar7R =\n { time = 0\n , eyeColour = RGB 1",
"end": 36343,
"score": 0.9151449203,
"start": 36336,
"tag": "NAME",
"value": "Chitwan"
}
] | ElmSlides/TEAStateDiagrams.elm | MacCASOutreach/NSIT2020 | 0 | port module TEAStateDiagrams exposing (main, slides)
import Array
import AvatarCreator
import Browser.Events as BEvents
import ColourPalette exposing (RGB(..), drawRGB)
import ElmArchitecture
import GraphicSVG exposing (..)
import GraphicSVG.App exposing (..)
import Html as H
import Html.Attributes as HA
import Json.Decode as Decode
import RedPurpleBlue
import WebFramework exposing (webFrameworkSlides)
import DoubleDiamond exposing (..)
import Url as Url
import Browser
import Browser.Navigation exposing (Key(..))
import Json.Encode as E
port play : E.Value -> Cmd msg
port getAudioDuration : (E.Value -> msg) -> Sub msg
people =
[]
type Message
= GameTick Float GetKeyState --The tick needs to have Float and GetKeyState which handles key presses.
| NextSlide
| LastSlide
| RPBMsg RedPurpleBlue.Msg -- (1) include message from included module
| AvatarMsg AvatarCreator.Msg
| NoOp
| MakeRequest Browser.UrlRequest
| UrlChange Url.Url
| GetNewAudioDuration (Maybe Float)
| DDiamondMsg DoubleDiamond.Msg
-- this is the main function, and for simple animations, you would only replace the view function, or edit it below
main : AppWithTick () Model Message
main =
appWithTick GameTick
{ init = \_ _ _ -> ( init, playSlideSound <| slide1 init)
, view = \model -> { title = "The Elm Architecture and State Diagrams", body = view model }
, update = update
, subscriptions = \_ -> Sub.batch [BEvents.onKeyUp controlSlide, subAudioDuration]
, onUrlChange = \_ -> NoOp
, onUrlRequest = \_ -> NoOp
}
subAudioDuration : Sub Message
subAudioDuration =
let
durationDecoder val =
case Decode.decodeValue Decode.float val of
Ok duration -> GetNewAudioDuration <| Just duration
Err _ -> GetNewAudioDuration Nothing
in
getAudioDuration durationDecoder
controlSlide : Decode.Decoder Message
controlSlide =
Decode.map
(\key ->
if key == "PageUp" then
LastSlide
else if key == "PageDown" then
NextSlide
else if key == "ArrowRight" then
NextSlide
else if key == "ArrowLeft" then
LastSlide
else
NoOp
)
keyDecoder
keyDecoder : Decode.Decoder String
keyDecoder =
Decode.field "key" Decode.string
-- MODEL
type alias Model =
{ t : Float
, idx : Int
, p : Bool
, -- Pause
r : Float
, -- Rewind
a : Float -- Acceleration
, rpb : RedPurpleBlue.Model
, audioDuration : Maybe Float
, time : Float
, slideStartTime : Float
, ddiamond : DoubleDiamond.Model
}
init : Model
init =
{ t = 0
, idx = 0
, p = False
, -- Pause
r = 1
, -- Rewind
a = 1 -- Acceleration
, rpb = RedPurpleBlue.init
, audioDuration = Nothing
, time = 0
, slideStartTime = 0
, ddiamond = DoubleDiamond.init
}
-- VIEW
view model =
let
t =
model.t
slide m =
((Maybe.withDefault default (Array.get model.idx slides)) m).shapes
in
collage 1000 500 (slide model ++ [audioBar model] ++ borders ++ navigators)
audioBar model =
case model.audioDuration of
Just dur ->
let
percentage = (model.time - model.slideStartTime)/dur
in
group
[
roundedRect 1000 10 5
|> filled gray
, roundedRect (1000 * percentage) 10 5
|> filled green
|> makeTransparent 0.3
]
|> move(0,-245)
Nothing -> group []
-- UPDATE
playSlideSound : Slide Message -> Cmd Message
playSlideSound slide =
case slide.audio of
Just s -> play (E.string s)
_ -> Cmd.none
update : Message -> Model -> ( Model, Cmd Message )
update message model =
let
_ =
case message of
GameTick _ _ ->
message
otherwise ->
Debug.log "message" message
in
case message of
NextSlide ->
let
newSlideId = min (model.idx + 1) (Array.length slides - 1)
newSlide =
case Array.get newSlideId slides of
Just slide -> slide model
_ -> default model
in
({ model
| t = 0
, idx = newSlideId
, slideStartTime = model.time
, audioDuration = Nothing
}, Debug.log "next slide cmd" playSlideSound newSlide )
LastSlide ->
let
newSlideId = max (model.idx - 1) 0
newSlide =
case Array.get newSlideId slides of
Just slide -> slide model
_ -> default model
in
({ model
| t = 0
, idx = newSlideId
, slideStartTime = model.time
, audioDuration = Nothing
} , Debug.log "last slide cmd" playSlideSound newSlide )
otherwise ->
(
case message of
GameTick tick ( getKeyState, changeP1, changeP2 ) ->
{ model
| t = max (model.t + 2.5 * model.a * model.r) 0
, time = tick
}
NextSlide ->
{ model
| t = 0
, idx = min (model.idx + 1) (Array.length slides - 1)
}
LastSlide ->
{ model
| t = 0
, idx = max (model.idx - 1) 0
}
RPBMsg msg ->
{ model | rpb = RedPurpleBlue.update msg model.rpb }
DDiamondMsg msg ->
{ model | ddiamond = DoubleDiamond.update msg model.ddiamond }
AvatarMsg msg ->
model
NoOp ->
model
MakeRequest _ -> model
UrlChange _ -> model
GetNewAudioDuration mDur ->
{ model | audioDuration = mDur }
, Cmd.none
)
--- MISCELLANEOUS
heritageMaroon =
rgb 122 0 60
heritageGold =
rgb 253 191 87
heritageGrey =
rgb 94 106 113
default _ =
{ shapes = [], audio = Nothing }
borders =
[ rect 5000 5000
|> filled white
|> move ( 3000, 0 )
, rect 5000 5000
|> filled white
|> move ( -3000, 0 )
, rect 5000 5000
|> filled white
|> move ( 0, 2750 )
, rect 5000 5000
|> filled white
|> move ( 0, -2750 )
]
navigators =
[ group
[ circle 40
|> filled gray
, triangle 30
|> filled white
]
|> move ( 450, -200 )
|> makeTransparent 0.5
|> notifyTap NextSlide
, group
[ circle 40
|> filled gray
, triangle 30
|> filled white
]
|> rotate (degrees 180)
|> move ( -450, -200 )
|> makeTransparent 0.5
|> notifyTap LastSlide
]
renderAvatar : AvatarCreator.Model -> Shape Message
renderAvatar avatarModel =
GraphicSVG.map AvatarMsg <| AvatarCreator.theFace avatarModel
makeBullets : Float -> List ( Int, String ) -> Float -> List (Shape msg)
makeBullets t l start =
case l of
( indt, x ) :: xs ->
(group
[ text x
|> size 20
|> customFont "Helvetica"
|> filled black
|> move ( -200, start )
|> fadeIn t 100
, circle 5
|> filled black
|> move ( -220, start + 5 )
|> fadeIn t 100
]
|> move ( 30 * toFloat indt, 0 )
)
:: makeBullets (t - 100) xs (start - 35)
_ ->
[]
-- FUNCTIONS
--<< So why do I see (t - 100) or whatever value so often? >>
-- Whenever I do that, I'm basically delaying what I want to happen
-- by that value. Is it measure in seconds, frames or what? What's the unit here?
-- To be honest, I don't know. It has a lot to do with the UPDATE function, and
-- what value for 'x' you are using for " t = model.t + x ".
disappear x n =
if x > n then
makeTransparent 0
else
makeTransparent 1
-- Makes things vanish off the screen!
loop t n =
let
y =
toFloat (floor (t / n))
-- This function is how I make things loop!
in
t - y * n
appear x n =
if x > n then
makeTransparent 1
else
makeTransparent 0
-- Makes things suddenly appear on the screen!
fadeIn t n =
makeTransparent (tranSin (t - n) 1)
fadeOut t n =
makeTransparent (1 - tranSin (t - n) 1)
trans t y =
if
t < 0
-- Used for all permanent transitions (fading out, color change, etc.) LINEAR.
then
0
else
Basics.min t y
tranSin t y =
if
t < 0
-- Used for all permanent transitions (fading out, color change, etc.) Uses sin.
then
0
else if t / 100 > pi / 2 then
y
else
sin (t / 100) * y
drawLine t ( x1, y1 ) ( x2, y2 ) =
line ( x1, y1 ) ( x1 + tranSin t (x2 - x1), y1 + tranSin t (y2 - y1) )
-- Down here is where you will find the slides!
-- To add more slides, simply add them to the list below.
fm : { a | t : Float } -> Float
fm m =
m.t
scaleTEA : Slide msg -> Slide msg
scaleTEA rec = {rec | shapes = [ move ( 0, -50 ) <| scale 3 <| group rec.shapes, outreachLogo, title "The Elm Architecture" ] }
type alias Slide msg =
{ shapes : List (Shape msg)
, audio : Maybe String
}
--slides : Array.Array ({ a | t : Float } -> Slide Message)
slides =
Array.fromList <|
[ slide1
, slide2 << fm
, scaleTEA << ElmArchitecture.slide1 << fm
, scaleTEA << ElmArchitecture.slide2 << fm
, scaleTEA << ElmArchitecture.slide3 << fm
, scaleTEA << ElmArchitecture.slide4 << fm
, scaleTEA << ElmArchitecture.slide5 << fm
, scaleTEA << ElmArchitecture.slide6 << fm
, scaleTEA << ElmArchitecture.slide7 << fm
, scaleTEA << ElmArchitecture.slide8 << fm
, scaleTEA << ElmArchitecture.slide9 << fm
, scaleTEA << ElmArchitecture.slide10 << fm
, scaleTEA << ElmArchitecture.slide11 << fm
, scaleTEA << ElmArchitecture.slide12 << fm
, slidePC0
, slidePC1
, slidePC2
, slidePC3
, slidePC4
, slidePC5
, slidePC0
, slidePC6
, slidePC6a
, slidePC6b
, slideSolid
, slideLiquid
, slideGas
]
title t =
text t
|> size 40
|> bold
|> customFont "Helvetica"
|> centered
|> filled heritageMaroon
|> move ( 0, 200 )
--<< EVERYTHING FOR FIRST PAGE >>-
outreachLogo =
group
[ GraphicSVG.html 100 100 (H.img [ HA.style "width" "100%", HA.src "images/Logo.png" ] [])
|> move ( -500, 250 )
|> addHyperlink "http://outreach.mcmaster.ca"
, text "I4CS 2020"
|> size 12
|> customFont "Arial"
|> filled black
|> move ( -485, 170 )
]
insertPicture url =
group
[ GraphicSVG.html 100 100 (H.img [ HA.style "width" "100%", HA.src url ] [])
|> addHyperlink "http://outreach.mcmaster.ca"
]
subtitle t =
text t
|> size 40
|> bold
|> customFont "Helvetica"
|> centered
|> filled green
slide0 model =
{ shapes = [], audio = Nothing }
arm shirtCol skinCol =
group
[ roundedRect 2 5 1
-- left arm
|> filled skinCol
|> rotate (degrees 120)
|> move ( -8, -4 )
, roundedRect 3 5 1
-- left sleeve
|> filled shirtCol
|> rotate (degrees 120)
|> move ( -5, -2 )
]
body shirtCol skinCol t =
group
[ roundedRect 3 8 1
-- left leg
|> filled blue
|> move ( -2, -11 )
, roundedRect 3 8 1
-- right leg
|> filled blue
|> move ( 2, -11 )
, roundedRect 2 5 1
-- neck
|> filled skinCol
, roundedRect 8 10 2
--body
|> filled shirtCol
|> move ( 0, -4 )
|> addHyperlink "http://outreach.mcmaster.ca"
, GraphicSVG.html 28 42 (H.img [ HA.style "width" "100%", HA.src "images/Shirt.png" ] [])
|> scale 0.2
|> move ( -3, 0 )
|> addHyperlink "http://outreach.mcmaster.ca"
, wedge 1.5 0.5
-- right shoe
|> filled lightBrown
|> rotate (degrees 90)
|> move ( 2, -15 )
, wedge 1.5 0.5
-- left shoe
|> filled lightBrown
|> rotate (degrees 90)
|> move ( -2, -15 )
]
slide1 model =
let
authorsColour =
black
-- Chris Schankula avatar
char1 =
group
[ arm (rgb 255 0 0) (drawRGB char1R.skinColour)
-- left arm
|> rotate
(if model.t < 320 then
degrees (20 * sin (model.t * 0.1) - 20)
else
degrees 20 - 0.5
)
|> move ( 0, -1 )
, arm (rgb 255 0 0) (drawRGB char1R.skinColour)
-- right arm
|> mirrorX
|> rotate (degrees -20)
|> move ( 0, 2 )
, body (rgb 255 0 0) (drawRGB char1R.skinColour) model.t
, renderAvatar char1R |> scale 0.2 |> move ( 0, 6 )
]
-- Nhan avatar
char2 =
group
[ arm yellow (drawRGB char2R.skinColour)
-- left arm
|> rotate
(if model.t < 320 then
degrees (20 * sin (model.t * 0.1) - 20)
else
degrees 20 - 0.5
)
|> move ( 0, -1 )
, arm yellow (drawRGB char2R.skinColour)
-- right arm
|> mirrorX
|> rotate (degrees -20)
|> move ( 0, 2 )
, body yellow (drawRGB char2R.skinColour) model.t
, renderAvatar char2R |> scale 0.2 |> move ( 0, 6 )
]
-- Yumna Irfan avatar
char3 =
group
[ arm green (drawRGB char3R.skinColour)
-- left arm
|> rotate (degrees -70)
, arm green (drawRGB char3R.skinColour)
-- right arm
|> mirrorX
|> rotate (degrees -20)
|> move ( 0, 2 )
, body green (drawRGB char3R.skinColour) model.t
|> mirrorX
, renderAvatar char3R |> scale 0.2 |> move ( 0, 6 )
]
-- Tanya avatar
char4 =
group
[ arm orange (drawRGB char5R.skinColour)
--left arm
|> rotate (degrees -68)
|> move ( 0, -2 )
, arm orange (drawRGB char5R.skinColour)
-- right arm
|> mirrorX
|> rotate (degrees -20)
|> move ( 0, 2 )
, body orange (drawRGB char5R.skinColour) model.t
, renderAvatar char5R |> scale 0.2 |> move ( 0, 6 )
] |> move(6,0)
heading =
group
[ text "The Elm Architecture and State Diagrams"
|> size 6.5
|> bold
|> customFont "Helvetica"
|> centered
|> filled heritageMaroon
]
authors =
group
[ text "Christopher W. Schankula"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( -35, -26 )
, text ", Lucas Dutton,"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( 4.5, -26 )
, text " Nhan Q. D. Thai"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( 35, -26 )
, text "Yumna Irfan, Padma Pasupathi,"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( 5, -32 )
, text "Chinmay Sheth, Christopher Kumar Anand"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( 5, -38 )
]
in
{ shapes =
[ group
[ group
[ GraphicSVG.html 40 40 (H.img [ HA.style "width" "100%", HA.src "images/Logo.png" ] [])
|> scale 0.6
|> move ( -12, 2 )
|> fadeIn model.t 150
|> addHyperlink "http://outreach.mcmaster.ca"
, group
[ text "Software:"
|> size 7
|> bold
|> customFont "Helvetica"
|> centered
|> filled heritageMaroon
|> addHyperlink "http://outreach.mcmaster.ca"
|> move ( 0, -25 )
, text "Tool For Change"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled heritageGold
|> addOutline (solid 0.125) heritageGrey
|> addHyperlink "http://outreach.mcmaster.ca"
|> move ( 0, -30 )
]
|> scale 0.85
]
|> move ( -31, -20 )
, GraphicSVG.html 40 40 (H.img [ HA.style "width" "100%", HA.src "images/MacEng.jpg" ] [])
|> move ( 20, -22 )
|> fadeIn model.t 150
|> addHyperlink "https://www.eng.mcmaster.ca/"
, group
[ group [ char1 |> move ( -10, 0 ), char2 |> move ( 10, 0 ) ]
|> move
( if model.t < 400 then
0
else
clamp 0 80 (model.t - 400)
, if model.t < 400 then
0
else
clamp -30 0 (-1 * model.t + 400)
)
, rect 100 40
|> filled white
|> fadeOut model.t 20
, heading
|> move
( if model.t < 200 then
-400
else
clamp -400 0 (-210 + (model.t - 200) * 0.3)
, 8
)
, authors
|> move
( if model.t < 200 then
400
else
clamp -6 400 (210 - (model.t - 200) * 0.3)
, 16
)
, char4
|> scale 0.7
|> move
( if model.t < 200 then
-400
else
clamp -400 90 (-128 + (model.t - 200) * 0.3)
, 4
)
, char3
|> mirrorX
|> scale 0.7
|> move
( if model.t < 200 then
400
else
clamp -90 120 (150 - (model.t - 200) * 0.3)
, -21
)
]
|> move ( 0, 25 )
]
|> scale 5
]
, audio = Nothing
}
decoratingPartPC6a =
let
customRed =
rgb 255 0 0
customBlue =
rgb 0 0 255
customPurple =
rgb 255 0 255
in
group [ circle 32 |> filled customRed |> move ( -240, 80 )
, rect 40 20 |> filled customRed |> move ( 150, 105 )
, circle 32 |> filled customPurple |> move ( -360, -80 )
, rect 64 20 |> filled customPurple |> move ( 221, 105 )
, circle 32 |> filled customBlue |> move ( -120, -80 )
, rect 42 20 |> filled customBlue |> move ( 298, 105 )
, rectangle 340 45 |> filled customPurple |> move ( 0, 157 )
]
slideDesignThinking: { a | ddiamond : DoubleDiamond.Model , t : Float } -> Slide Message
slideDesignThinking model = {shapes = List.map (GraphicSVG.map DDiamondMsg)
[ title "Design Thinking"
, group (DoubleDiamond.myShapes model.ddiamond) |> scale 3.7
]
, audio = Nothing}
slidePC0 model =
{shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model", group [ roundedRect 100 20 5 |> filled red, text "Click Me!" |> centered |> filled black |> move ( 0, -5 ) ] |> move ( 0, -220 ) ] ++ RedPurpleBlue.diagram "" (Just RedPurpleBlue.Red) Nothing ++ [ outreachLogo ]
, audio = Nothing
}
slidePC1 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model" ] ++ RedPurpleBlue.diagram "" Nothing (Just ( RedPurpleBlue.Red, "ChangeColour" )) ++ [ outreachLogo ]
, audio = Nothing
}
slidePC2 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model", group [ roundedRect 100 20 5 |> filled (rgb 200 0 200), text "Click Me!" |> centered |> filled black |> move ( 0, -5 ) ] |> move ( 0, -220 ) ] ++ RedPurpleBlue.diagram "" (Just RedPurpleBlue.Purple) Nothing ++ [ outreachLogo ]
, audio = Nothing
}
slidePC3 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model" ] ++ RedPurpleBlue.diagram "" Nothing (Just ( RedPurpleBlue.Purple, "ChangeColour" )) ++ [ outreachLogo ]
, audio = Nothing
}
slidePC4 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model", group [ roundedRect 100 20 5 |> filled (rgb 0 0 255), text "Click Me!" |> centered |> filled black |> move ( 0, -5 ) ] |> move ( 0, -220 ) ] ++ RedPurpleBlue.diagram "" (Just RedPurpleBlue.Blue) Nothing ++ [ outreachLogo ]
, audio = Nothing
}
slidePC5 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model" ] ++ RedPurpleBlue.diagram "" Nothing (Just ( RedPurpleBlue.Blue, "ChangeColour" )) ++ [ outreachLogo ]
, audio = Nothing
}
slidePC6 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "State Diagram → Elm" ] ++ [ scale 0.8 <| move ( -300, 0 ) <| group <| RedPurpleBlue.diagram "" Nothing Nothing, group (rpbTxt model) |> move ( 225, 50 ) ] ++ [ outreachLogo ]
, audio = Nothing
}
slidePC6a =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "State Diagram → Elm", decoratingPartPC6a, pcUnder "states → constructors" ] ++ [ scale 0.8 <| move ( -300, 0 ) <| group <| RedPurpleBlue.diagram "" Nothing Nothing, group (rpbTxt model) |> move ( 225, 50 ) ] ++ [ outreachLogo ]
, audio = Nothing
}
slidePC6b =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "State Diagram → Elm", rectangle 420 45 |> filled heritageGold |> move ( 0, 157 ), pcUnder "transitions → update functions", rectangle 340 45 |> filled heritageGold |> move ( 214, -72 ), rectangle 125 25 |> filled heritageGold |> move ( 174, 67 ), rectangle 100 25 |> filled heritageGold |> move ( -120, 43 ), rectangle 100 25 |> filled heritageGold |> move ( -360, 43 ), rectangle 100 25 |> filled heritageGold |> move ( -240, -117 ) ] ++ [ scale 0.8 <| move ( -300, 0 ) <| group <| RedPurpleBlue.diagram "" Nothing Nothing, group (rpbTxt model) |> move ( 225, 50 ) ] ++ [ outreachLogo ]
, audio = Nothing
}
pcUnder txt =
text txt
|> size 30
|> italic
|> customFont "Helvetica"
|> centered
|> filled black
|> move ( 0, 150 )
user1State t f =
let
frac =
0.002 * t - toFloat (floor (0.002 * t))
in
if 6 * frac < 1 then
f (Just RedPurpleBlue.Red) Nothing
else if 6 * frac < 2 then
f Nothing (Just ( RedPurpleBlue.Red, "ChangeColour" ))
else if 6 * frac < 3 then
f (Just RedPurpleBlue.Purple) Nothing
else if 6 * frac < 4 then
f Nothing (Just ( RedPurpleBlue.Purple, "ChangeColour" ))
else if 6 * frac < 5 then
f (Just RedPurpleBlue.Blue) Nothing
else
f Nothing (Just ( RedPurpleBlue.Blue, "ChangeColour" ))
user1State1 t f =
let
frac =
0.002 * t - toFloat (floor (0.002 * t))
in
if 6 * frac < 1 then
f (Just RedPurpleBlue.Blue) Nothing
else if 6 * frac < 2 then
f Nothing (Just ( RedPurpleBlue.Blue, "ChangeColour" ))
else if 6 * frac < 3 then
f (Just RedPurpleBlue.Red) Nothing
else if 6 * frac < 4 then
f Nothing (Just ( RedPurpleBlue.Red, "ChangeColour" ))
else if 6 * frac < 5 then
f (Just RedPurpleBlue.Purple) Nothing
else
f Nothing (Just ( RedPurpleBlue.Purple, "ChangeColour" ))
user1State2 t f =
let
frac =
0.002 * t - toFloat (floor (0.002 * t))
in
if 6 * frac < 1 then
f (Just RedPurpleBlue.Purple) Nothing
else if 6 * frac < 2 then
f Nothing (Just ( RedPurpleBlue.Purple, "ChangeColour" ))
else if 6 * frac < 3 then
f (Just RedPurpleBlue.Blue) Nothing
else if 6 * frac < 4 then
f Nothing (Just ( RedPurpleBlue.Blue, "ChangeColour" ))
else if 6 * frac < 5 then
f (Just RedPurpleBlue.Red) Nothing
else
f Nothing (Just ( RedPurpleBlue.Red, "ChangeColour" ))
codeMarkdown codeString co =
let
code c ( txt, ln ) =
text txt
|> size 8
|> bold
|> customFont "Helvetica"
|> fixedwidth
|> filled c
|> move ( 0, -9 * ln )
lns =
String.lines codeString
positions : List String -> Float -> List ( String, Float )
positions lines i =
case lines of
l :: ls ->
( l, i ) :: positions ls (i + 1)
[] ->
[]
in
group (List.map (code co) (positions lns 0))
rpbTxt model =
[ group
[ codeMarkdown """ Model = Red Purple Blue
Msg = ChangeColour
view Model Html Msg
update Msg Model Model Cmd Msg
update msg model
msg
ChangeColour
updateColour model Cmd.none
updateColour Model Model
updateColour model =
model
Red Purple
Purple Blue
Blue Red
""" black
|> scale 2
|> move ( -215, 50 )
, codeMarkdown """type | |
type
: ->
: -> -> ( , )
=
case of
->
( , )
: ->
case of
->
->
->
""" pink
|> scale 2
|> move ( -215, 50 )
]
]
slide2 model =
{shapes = [ title "The Elm Language"
|> move ( -5, -30 )
, group
(makeBullets model
[ ( 0, "Functional language" )
, ( 0, "Compact syntax" )
, ( 0, "Pure functions" )
, ( 0, "Composable functions" )
, ( 0, "Strongly typed" )
, ( 1, "Detailed compiler errors for refactoring" )
, ( 0, "Compiles into JavaScript" )
]
0
)
|> move ( -80, 115 )
, outreachLogo
, html 200 200 (H.img [ HA.src "images/Elm.png", HA.style "width" "100%" ] [])
|> move ( 170, 70 )
]
, audio = Nothing
}
slideModelDrivenDevelopment model =
{shapes = [ title "Model Driven Development"
|> move ( -5, -30 )
, group
(makeBullets model.t
[ ( 0, "Software development approach" )
, ( 0, "For large-scale software development projects" )
, ( 0, "Higher level of abstraction" )
, ( 1, "Accelerates development" )
, ( 1, "Increases software quality" )
, ( 0, "Low code" )
, ( 1, "because code is automatically (re)generated" )
]
0
)
|> move ( -140, 90 )
, insertPicture "images/FoodGameStateDiagram.png"
|> scale 4.2
|> move (60,120)
, outreachLogo
]
, audio = Nothing
}
slidePALDraw model =
{shapes = [ title "PALDraw"
|> scale 0.9
|> move ( -310, -175 )
, group
(makeBullets model.t
[ ( 0, "PALDraw is a visual specification tool" )
]
0
)
|> scale 0.75
|> move ( -280, -20 )
, insertPicture "images/Combined.png"
|> scale 6
|> move (-180,200)
, outreachLogo
]
, audio = Nothing
}
solidState model =
let
( vx, vy ) =
( 0.2, 0.7 )
headBack =
group
[ rect 80 15
|> filled lightBlue
|> makeTransparent 0.3
, rect 80 15
|> outlined (solid 1) black
]
molecule =
group
[ circle 2 |> filled (rgb 0 200 0) |> move ( 8, 0 )
, circle 7 |> filled (rgb 0 0 250)
, circle 2 |> filled (rgb 0 200 0) |> move ( 0, 8 )
]
in
[ molecule
|> rotate (vx * (0.1 * model.t))
|> move
( 60 * sin (vx * (0.01 * model.t))
, 40 * sin (vy * (0.01 * model.t))
)
, text "Solid State"
|> centered
|> filled black
|> move ( 0, 55 )
, headBack
|> move ( 0, 58 )
]
liquidState model =
let
( vx, vy ) =
( pi, 2 )
headBack =
group
[ rect 80 15
|> filled lightBlue
|> makeTransparent 0.3
, rect 80 15
|> outlined (solid 1) black
]
molecule =
group
[ circle 2 |> filled (rgb 0 200 0) |> move ( 8, 0 )
, circle 7 |> filled (rgb 0 0 250)
, circle 2 |> filled (rgb 0 200 0) |> move ( 0, 8 )
]
in
[ molecule
|> rotate (vx * (0.02 * model.t))
|> move
( 60 * sin (vx * (0.015 * model.t))
, 40 * sin (vy * (0.015 * model.t))
)
, text "Liquid State"
|> centered
|> filled black
|> move ( 0, 55 )
, headBack
|> move ( 0, 58 )
]
gasState model =
let
( vx, vy ) =
( 57, 64 )
headBack =
group
[ rect 80 15
|> filled lightBlue
|> makeTransparent 0.3
, rect 80 15
|> outlined (solid 1) black
]
molecule =
group
[ circle 2 |> filled (rgb 0 200 0) |> move ( 8, 0 )
, circle 7 |> filled (rgb 0 0 250)
, circle 2 |> filled (rgb 0 200 0) |> move ( 0, 8 )
]
in
[ molecule
|> rotate (vx * (0.02 * model.t))
|> move
( 60 * sin (vx * (0.019 * model.t))
, 40 * sin (vy * (0.019 * model.t))
)
, text "Gaseous State"
|> centered
|> filled black
|> move ( 0, 55 )
, headBack
|> move ( 0, 58 )
]
slideSolid model =
{shapes = [ group (solidState model) |> scale 4 |> move ( 0, -50 ), outreachLogo ]
, audio = Nothing
}
slideLiquid model =
{shapes = [ group (liquidState model) |> scale 4 |> move ( 0, -50 ), outreachLogo ]
, audio = Nothing
}
slideGas model =
{shapes = [ group (gasState model) |> scale 4 |> move ( 0, -50 ), outreachLogo ]
, audio = Nothing
}
--Chris
char1R =
{ time = 0
, eyeColour = RGB 211 255 255
, skinColour = RGB 255 223 196
, headcoverColour = RGB 204 255 204
, hairFront = 7
, hairColour = RGB 255 153 51
, highlightColour = RGB 204 102 0
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- Dr Anand
char2R =
{ time = 0
, eyeColour = RGB 129 73 31
, skinColour = RGB 217 144 105
, headcoverColour = RGB 204 255 204
, hairFront = 16
, hairColour = RGB 32 32 32
, highlightColour = RGB 102 0 204
, eyeShape = 3
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- Yumna
char3R =
{ time = 0
, eyeColour = RGB 32 32 32
, skinColour = RGB 219 144 101
, headcoverColour = RGB 204 255 204
, hairFront = 13
, hairColour = RGB 250 240 190
, highlightColour = RGB 102 0 204
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
--Ankit
char4R =
{ time = 0
, eyeColour = RGB 32 32 32
, skinColour = RGB 219 144 101
, headcoverColour = RGB 204 255 204
, hairFront = 5
, hairColour = RGB 0 0 0
, highlightColour = RGB 102 0 204
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- Tanya
char5R =
{ time = 0
, eyeColour = RGB 47 75 75
, skinColour = RGB 255 223 196
, headcoverColour = RGB 204 255 204
, hairFront = 9
, hairColour = RGB 130 72 24
, highlightColour = RGB 32 32 32
, eyeShape = 3
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- Pedram
char6R =
{ time = 0
, eyeColour = RGB 147 0 73
, skinColour = RGB 255 204 204
, headcoverColour = RGB 204 255 204
, hairFront = 0
, hairColour = RGB 32 32 32
, highlightColour = RGB 32 32 32
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- Chitwan
char7R =
{ time = 0
, eyeColour = RGB 198 120 86
, skinColour = RGB 229 184 143
, headcoverColour = RGB 204 255 204
, hairFront = 3
, hairColour = RGB 62 43 19
, highlightColour = RGB 32 32 32
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
{-
To use slides with sound: elm make <moduleName>.elm --output=soundslides.js
- use elm reactor and go to soundslides.html
-} | 36165 | port module TEAStateDiagrams exposing (main, slides)
import Array
import AvatarCreator
import Browser.Events as BEvents
import ColourPalette exposing (RGB(..), drawRGB)
import ElmArchitecture
import GraphicSVG exposing (..)
import GraphicSVG.App exposing (..)
import Html as H
import Html.Attributes as HA
import Json.Decode as Decode
import RedPurpleBlue
import WebFramework exposing (webFrameworkSlides)
import DoubleDiamond exposing (..)
import Url as Url
import Browser
import Browser.Navigation exposing (Key(..))
import Json.Encode as E
port play : E.Value -> Cmd msg
port getAudioDuration : (E.Value -> msg) -> Sub msg
people =
[]
type Message
= GameTick Float GetKeyState --The tick needs to have Float and GetKeyState which handles key presses.
| NextSlide
| LastSlide
| RPBMsg RedPurpleBlue.Msg -- (1) include message from included module
| AvatarMsg AvatarCreator.Msg
| NoOp
| MakeRequest Browser.UrlRequest
| UrlChange Url.Url
| GetNewAudioDuration (Maybe Float)
| DDiamondMsg DoubleDiamond.Msg
-- this is the main function, and for simple animations, you would only replace the view function, or edit it below
main : AppWithTick () Model Message
main =
appWithTick GameTick
{ init = \_ _ _ -> ( init, playSlideSound <| slide1 init)
, view = \model -> { title = "The Elm Architecture and State Diagrams", body = view model }
, update = update
, subscriptions = \_ -> Sub.batch [BEvents.onKeyUp controlSlide, subAudioDuration]
, onUrlChange = \_ -> NoOp
, onUrlRequest = \_ -> NoOp
}
subAudioDuration : Sub Message
subAudioDuration =
let
durationDecoder val =
case Decode.decodeValue Decode.float val of
Ok duration -> GetNewAudioDuration <| Just duration
Err _ -> GetNewAudioDuration Nothing
in
getAudioDuration durationDecoder
controlSlide : Decode.Decoder Message
controlSlide =
Decode.map
(\key ->
if key == "PageUp" then
LastSlide
else if key == "PageDown" then
NextSlide
else if key == "ArrowRight" then
NextSlide
else if key == "ArrowLeft" then
LastSlide
else
NoOp
)
keyDecoder
keyDecoder : Decode.Decoder String
keyDecoder =
Decode.field "key" Decode.string
-- MODEL
type alias Model =
{ t : Float
, idx : Int
, p : Bool
, -- Pause
r : Float
, -- Rewind
a : Float -- Acceleration
, rpb : RedPurpleBlue.Model
, audioDuration : Maybe Float
, time : Float
, slideStartTime : Float
, ddiamond : DoubleDiamond.Model
}
init : Model
init =
{ t = 0
, idx = 0
, p = False
, -- Pause
r = 1
, -- Rewind
a = 1 -- Acceleration
, rpb = RedPurpleBlue.init
, audioDuration = Nothing
, time = 0
, slideStartTime = 0
, ddiamond = DoubleDiamond.init
}
-- VIEW
view model =
let
t =
model.t
slide m =
((Maybe.withDefault default (Array.get model.idx slides)) m).shapes
in
collage 1000 500 (slide model ++ [audioBar model] ++ borders ++ navigators)
audioBar model =
case model.audioDuration of
Just dur ->
let
percentage = (model.time - model.slideStartTime)/dur
in
group
[
roundedRect 1000 10 5
|> filled gray
, roundedRect (1000 * percentage) 10 5
|> filled green
|> makeTransparent 0.3
]
|> move(0,-245)
Nothing -> group []
-- UPDATE
playSlideSound : Slide Message -> Cmd Message
playSlideSound slide =
case slide.audio of
Just s -> play (E.string s)
_ -> Cmd.none
update : Message -> Model -> ( Model, Cmd Message )
update message model =
let
_ =
case message of
GameTick _ _ ->
message
otherwise ->
Debug.log "message" message
in
case message of
NextSlide ->
let
newSlideId = min (model.idx + 1) (Array.length slides - 1)
newSlide =
case Array.get newSlideId slides of
Just slide -> slide model
_ -> default model
in
({ model
| t = 0
, idx = newSlideId
, slideStartTime = model.time
, audioDuration = Nothing
}, Debug.log "next slide cmd" playSlideSound newSlide )
LastSlide ->
let
newSlideId = max (model.idx - 1) 0
newSlide =
case Array.get newSlideId slides of
Just slide -> slide model
_ -> default model
in
({ model
| t = 0
, idx = newSlideId
, slideStartTime = model.time
, audioDuration = Nothing
} , Debug.log "last slide cmd" playSlideSound newSlide )
otherwise ->
(
case message of
GameTick tick ( getKeyState, changeP1, changeP2 ) ->
{ model
| t = max (model.t + 2.5 * model.a * model.r) 0
, time = tick
}
NextSlide ->
{ model
| t = 0
, idx = min (model.idx + 1) (Array.length slides - 1)
}
LastSlide ->
{ model
| t = 0
, idx = max (model.idx - 1) 0
}
RPBMsg msg ->
{ model | rpb = RedPurpleBlue.update msg model.rpb }
DDiamondMsg msg ->
{ model | ddiamond = DoubleDiamond.update msg model.ddiamond }
AvatarMsg msg ->
model
NoOp ->
model
MakeRequest _ -> model
UrlChange _ -> model
GetNewAudioDuration mDur ->
{ model | audioDuration = mDur }
, Cmd.none
)
--- MISCELLANEOUS
heritageMaroon =
rgb 122 0 60
heritageGold =
rgb 253 191 87
heritageGrey =
rgb 94 106 113
default _ =
{ shapes = [], audio = Nothing }
borders =
[ rect 5000 5000
|> filled white
|> move ( 3000, 0 )
, rect 5000 5000
|> filled white
|> move ( -3000, 0 )
, rect 5000 5000
|> filled white
|> move ( 0, 2750 )
, rect 5000 5000
|> filled white
|> move ( 0, -2750 )
]
navigators =
[ group
[ circle 40
|> filled gray
, triangle 30
|> filled white
]
|> move ( 450, -200 )
|> makeTransparent 0.5
|> notifyTap NextSlide
, group
[ circle 40
|> filled gray
, triangle 30
|> filled white
]
|> rotate (degrees 180)
|> move ( -450, -200 )
|> makeTransparent 0.5
|> notifyTap LastSlide
]
renderAvatar : AvatarCreator.Model -> Shape Message
renderAvatar avatarModel =
GraphicSVG.map AvatarMsg <| AvatarCreator.theFace avatarModel
makeBullets : Float -> List ( Int, String ) -> Float -> List (Shape msg)
makeBullets t l start =
case l of
( indt, x ) :: xs ->
(group
[ text x
|> size 20
|> customFont "Helvetica"
|> filled black
|> move ( -200, start )
|> fadeIn t 100
, circle 5
|> filled black
|> move ( -220, start + 5 )
|> fadeIn t 100
]
|> move ( 30 * toFloat indt, 0 )
)
:: makeBullets (t - 100) xs (start - 35)
_ ->
[]
-- FUNCTIONS
--<< So why do I see (t - 100) or whatever value so often? >>
-- Whenever I do that, I'm basically delaying what I want to happen
-- by that value. Is it measure in seconds, frames or what? What's the unit here?
-- To be honest, I don't know. It has a lot to do with the UPDATE function, and
-- what value for 'x' you are using for " t = model.t + x ".
disappear x n =
if x > n then
makeTransparent 0
else
makeTransparent 1
-- Makes things vanish off the screen!
loop t n =
let
y =
toFloat (floor (t / n))
-- This function is how I make things loop!
in
t - y * n
appear x n =
if x > n then
makeTransparent 1
else
makeTransparent 0
-- Makes things suddenly appear on the screen!
fadeIn t n =
makeTransparent (tranSin (t - n) 1)
fadeOut t n =
makeTransparent (1 - tranSin (t - n) 1)
trans t y =
if
t < 0
-- Used for all permanent transitions (fading out, color change, etc.) LINEAR.
then
0
else
Basics.min t y
tranSin t y =
if
t < 0
-- Used for all permanent transitions (fading out, color change, etc.) Uses sin.
then
0
else if t / 100 > pi / 2 then
y
else
sin (t / 100) * y
drawLine t ( x1, y1 ) ( x2, y2 ) =
line ( x1, y1 ) ( x1 + tranSin t (x2 - x1), y1 + tranSin t (y2 - y1) )
-- Down here is where you will find the slides!
-- To add more slides, simply add them to the list below.
fm : { a | t : Float } -> Float
fm m =
m.t
scaleTEA : Slide msg -> Slide msg
scaleTEA rec = {rec | shapes = [ move ( 0, -50 ) <| scale 3 <| group rec.shapes, outreachLogo, title "The Elm Architecture" ] }
type alias Slide msg =
{ shapes : List (Shape msg)
, audio : Maybe String
}
--slides : Array.Array ({ a | t : Float } -> Slide Message)
slides =
Array.fromList <|
[ slide1
, slide2 << fm
, scaleTEA << ElmArchitecture.slide1 << fm
, scaleTEA << ElmArchitecture.slide2 << fm
, scaleTEA << ElmArchitecture.slide3 << fm
, scaleTEA << ElmArchitecture.slide4 << fm
, scaleTEA << ElmArchitecture.slide5 << fm
, scaleTEA << ElmArchitecture.slide6 << fm
, scaleTEA << ElmArchitecture.slide7 << fm
, scaleTEA << ElmArchitecture.slide8 << fm
, scaleTEA << ElmArchitecture.slide9 << fm
, scaleTEA << ElmArchitecture.slide10 << fm
, scaleTEA << ElmArchitecture.slide11 << fm
, scaleTEA << ElmArchitecture.slide12 << fm
, slidePC0
, slidePC1
, slidePC2
, slidePC3
, slidePC4
, slidePC5
, slidePC0
, slidePC6
, slidePC6a
, slidePC6b
, slideSolid
, slideLiquid
, slideGas
]
title t =
text t
|> size 40
|> bold
|> customFont "Helvetica"
|> centered
|> filled heritageMaroon
|> move ( 0, 200 )
--<< EVERYTHING FOR FIRST PAGE >>-
outreachLogo =
group
[ GraphicSVG.html 100 100 (H.img [ HA.style "width" "100%", HA.src "images/Logo.png" ] [])
|> move ( -500, 250 )
|> addHyperlink "http://outreach.mcmaster.ca"
, text "I4CS 2020"
|> size 12
|> customFont "Arial"
|> filled black
|> move ( -485, 170 )
]
insertPicture url =
group
[ GraphicSVG.html 100 100 (H.img [ HA.style "width" "100%", HA.src url ] [])
|> addHyperlink "http://outreach.mcmaster.ca"
]
subtitle t =
text t
|> size 40
|> bold
|> customFont "Helvetica"
|> centered
|> filled green
slide0 model =
{ shapes = [], audio = Nothing }
arm shirtCol skinCol =
group
[ roundedRect 2 5 1
-- left arm
|> filled skinCol
|> rotate (degrees 120)
|> move ( -8, -4 )
, roundedRect 3 5 1
-- left sleeve
|> filled shirtCol
|> rotate (degrees 120)
|> move ( -5, -2 )
]
body shirtCol skinCol t =
group
[ roundedRect 3 8 1
-- left leg
|> filled blue
|> move ( -2, -11 )
, roundedRect 3 8 1
-- right leg
|> filled blue
|> move ( 2, -11 )
, roundedRect 2 5 1
-- neck
|> filled skinCol
, roundedRect 8 10 2
--body
|> filled shirtCol
|> move ( 0, -4 )
|> addHyperlink "http://outreach.mcmaster.ca"
, GraphicSVG.html 28 42 (H.img [ HA.style "width" "100%", HA.src "images/Shirt.png" ] [])
|> scale 0.2
|> move ( -3, 0 )
|> addHyperlink "http://outreach.mcmaster.ca"
, wedge 1.5 0.5
-- right shoe
|> filled lightBrown
|> rotate (degrees 90)
|> move ( 2, -15 )
, wedge 1.5 0.5
-- left shoe
|> filled lightBrown
|> rotate (degrees 90)
|> move ( -2, -15 )
]
slide1 model =
let
authorsColour =
black
-- <NAME> avatar
char1 =
group
[ arm (rgb 255 0 0) (drawRGB char1R.skinColour)
-- left arm
|> rotate
(if model.t < 320 then
degrees (20 * sin (model.t * 0.1) - 20)
else
degrees 20 - 0.5
)
|> move ( 0, -1 )
, arm (rgb 255 0 0) (drawRGB char1R.skinColour)
-- right arm
|> mirrorX
|> rotate (degrees -20)
|> move ( 0, 2 )
, body (rgb 255 0 0) (drawRGB char1R.skinColour) model.t
, renderAvatar char1R |> scale 0.2 |> move ( 0, 6 )
]
-- Nhan avatar
char2 =
group
[ arm yellow (drawRGB char2R.skinColour)
-- left arm
|> rotate
(if model.t < 320 then
degrees (20 * sin (model.t * 0.1) - 20)
else
degrees 20 - 0.5
)
|> move ( 0, -1 )
, arm yellow (drawRGB char2R.skinColour)
-- right arm
|> mirrorX
|> rotate (degrees -20)
|> move ( 0, 2 )
, body yellow (drawRGB char2R.skinColour) model.t
, renderAvatar char2R |> scale 0.2 |> move ( 0, 6 )
]
-- Yumna Irfan avatar
char3 =
group
[ arm green (drawRGB char3R.skinColour)
-- left arm
|> rotate (degrees -70)
, arm green (drawRGB char3R.skinColour)
-- right arm
|> mirrorX
|> rotate (degrees -20)
|> move ( 0, 2 )
, body green (drawRGB char3R.skinColour) model.t
|> mirrorX
, renderAvatar char3R |> scale 0.2 |> move ( 0, 6 )
]
-- Tanya avatar
char4 =
group
[ arm orange (drawRGB char5R.skinColour)
--left arm
|> rotate (degrees -68)
|> move ( 0, -2 )
, arm orange (drawRGB char5R.skinColour)
-- right arm
|> mirrorX
|> rotate (degrees -20)
|> move ( 0, 2 )
, body orange (drawRGB char5R.skinColour) model.t
, renderAvatar char5R |> scale 0.2 |> move ( 0, 6 )
] |> move(6,0)
heading =
group
[ text "The Elm Architecture and State Diagrams"
|> size 6.5
|> bold
|> customFont "Helvetica"
|> centered
|> filled heritageMaroon
]
authors =
group
[ text "<NAME>"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( -35, -26 )
, text ", <NAME>,"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( 4.5, -26 )
, text " <NAME>"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( 35, -26 )
, text "<NAME>, <NAME>,"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( 5, -32 )
, text "<NAME>, <NAME>"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( 5, -38 )
]
in
{ shapes =
[ group
[ group
[ GraphicSVG.html 40 40 (H.img [ HA.style "width" "100%", HA.src "images/Logo.png" ] [])
|> scale 0.6
|> move ( -12, 2 )
|> fadeIn model.t 150
|> addHyperlink "http://outreach.mcmaster.ca"
, group
[ text "Software:"
|> size 7
|> bold
|> customFont "Helvetica"
|> centered
|> filled heritageMaroon
|> addHyperlink "http://outreach.mcmaster.ca"
|> move ( 0, -25 )
, text "Tool For Change"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled heritageGold
|> addOutline (solid 0.125) heritageGrey
|> addHyperlink "http://outreach.mcmaster.ca"
|> move ( 0, -30 )
]
|> scale 0.85
]
|> move ( -31, -20 )
, GraphicSVG.html 40 40 (H.img [ HA.style "width" "100%", HA.src "images/MacEng.jpg" ] [])
|> move ( 20, -22 )
|> fadeIn model.t 150
|> addHyperlink "https://www.eng.mcmaster.ca/"
, group
[ group [ char1 |> move ( -10, 0 ), char2 |> move ( 10, 0 ) ]
|> move
( if model.t < 400 then
0
else
clamp 0 80 (model.t - 400)
, if model.t < 400 then
0
else
clamp -30 0 (-1 * model.t + 400)
)
, rect 100 40
|> filled white
|> fadeOut model.t 20
, heading
|> move
( if model.t < 200 then
-400
else
clamp -400 0 (-210 + (model.t - 200) * 0.3)
, 8
)
, authors
|> move
( if model.t < 200 then
400
else
clamp -6 400 (210 - (model.t - 200) * 0.3)
, 16
)
, char4
|> scale 0.7
|> move
( if model.t < 200 then
-400
else
clamp -400 90 (-128 + (model.t - 200) * 0.3)
, 4
)
, char3
|> mirrorX
|> scale 0.7
|> move
( if model.t < 200 then
400
else
clamp -90 120 (150 - (model.t - 200) * 0.3)
, -21
)
]
|> move ( 0, 25 )
]
|> scale 5
]
, audio = Nothing
}
decoratingPartPC6a =
let
customRed =
rgb 255 0 0
customBlue =
rgb 0 0 255
customPurple =
rgb 255 0 255
in
group [ circle 32 |> filled customRed |> move ( -240, 80 )
, rect 40 20 |> filled customRed |> move ( 150, 105 )
, circle 32 |> filled customPurple |> move ( -360, -80 )
, rect 64 20 |> filled customPurple |> move ( 221, 105 )
, circle 32 |> filled customBlue |> move ( -120, -80 )
, rect 42 20 |> filled customBlue |> move ( 298, 105 )
, rectangle 340 45 |> filled customPurple |> move ( 0, 157 )
]
slideDesignThinking: { a | ddiamond : DoubleDiamond.Model , t : Float } -> Slide Message
slideDesignThinking model = {shapes = List.map (GraphicSVG.map DDiamondMsg)
[ title "Design Thinking"
, group (DoubleDiamond.myShapes model.ddiamond) |> scale 3.7
]
, audio = Nothing}
slidePC0 model =
{shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model", group [ roundedRect 100 20 5 |> filled red, text "Click Me!" |> centered |> filled black |> move ( 0, -5 ) ] |> move ( 0, -220 ) ] ++ RedPurpleBlue.diagram "" (Just RedPurpleBlue.Red) Nothing ++ [ outreachLogo ]
, audio = Nothing
}
slidePC1 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model" ] ++ RedPurpleBlue.diagram "" Nothing (Just ( RedPurpleBlue.Red, "ChangeColour" )) ++ [ outreachLogo ]
, audio = Nothing
}
slidePC2 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model", group [ roundedRect 100 20 5 |> filled (rgb 200 0 200), text "Click Me!" |> centered |> filled black |> move ( 0, -5 ) ] |> move ( 0, -220 ) ] ++ RedPurpleBlue.diagram "" (Just RedPurpleBlue.Purple) Nothing ++ [ outreachLogo ]
, audio = Nothing
}
slidePC3 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model" ] ++ RedPurpleBlue.diagram "" Nothing (Just ( RedPurpleBlue.Purple, "ChangeColour" )) ++ [ outreachLogo ]
, audio = Nothing
}
slidePC4 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model", group [ roundedRect 100 20 5 |> filled (rgb 0 0 255), text "Click Me!" |> centered |> filled black |> move ( 0, -5 ) ] |> move ( 0, -220 ) ] ++ RedPurpleBlue.diagram "" (Just RedPurpleBlue.Blue) Nothing ++ [ outreachLogo ]
, audio = Nothing
}
slidePC5 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model" ] ++ RedPurpleBlue.diagram "" Nothing (Just ( RedPurpleBlue.Blue, "ChangeColour" )) ++ [ outreachLogo ]
, audio = Nothing
}
slidePC6 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "State Diagram → Elm" ] ++ [ scale 0.8 <| move ( -300, 0 ) <| group <| RedPurpleBlue.diagram "" Nothing Nothing, group (rpbTxt model) |> move ( 225, 50 ) ] ++ [ outreachLogo ]
, audio = Nothing
}
slidePC6a =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "State Diagram → Elm", decoratingPartPC6a, pcUnder "states → constructors" ] ++ [ scale 0.8 <| move ( -300, 0 ) <| group <| RedPurpleBlue.diagram "" Nothing Nothing, group (rpbTxt model) |> move ( 225, 50 ) ] ++ [ outreachLogo ]
, audio = Nothing
}
slidePC6b =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "State Diagram → Elm", rectangle 420 45 |> filled heritageGold |> move ( 0, 157 ), pcUnder "transitions → update functions", rectangle 340 45 |> filled heritageGold |> move ( 214, -72 ), rectangle 125 25 |> filled heritageGold |> move ( 174, 67 ), rectangle 100 25 |> filled heritageGold |> move ( -120, 43 ), rectangle 100 25 |> filled heritageGold |> move ( -360, 43 ), rectangle 100 25 |> filled heritageGold |> move ( -240, -117 ) ] ++ [ scale 0.8 <| move ( -300, 0 ) <| group <| RedPurpleBlue.diagram "" Nothing Nothing, group (rpbTxt model) |> move ( 225, 50 ) ] ++ [ outreachLogo ]
, audio = Nothing
}
pcUnder txt =
text txt
|> size 30
|> italic
|> customFont "Helvetica"
|> centered
|> filled black
|> move ( 0, 150 )
user1State t f =
let
frac =
0.002 * t - toFloat (floor (0.002 * t))
in
if 6 * frac < 1 then
f (Just RedPurpleBlue.Red) Nothing
else if 6 * frac < 2 then
f Nothing (Just ( RedPurpleBlue.Red, "ChangeColour" ))
else if 6 * frac < 3 then
f (Just RedPurpleBlue.Purple) Nothing
else if 6 * frac < 4 then
f Nothing (Just ( RedPurpleBlue.Purple, "ChangeColour" ))
else if 6 * frac < 5 then
f (Just RedPurpleBlue.Blue) Nothing
else
f Nothing (Just ( RedPurpleBlue.Blue, "ChangeColour" ))
user1State1 t f =
let
frac =
0.002 * t - toFloat (floor (0.002 * t))
in
if 6 * frac < 1 then
f (Just RedPurpleBlue.Blue) Nothing
else if 6 * frac < 2 then
f Nothing (Just ( RedPurpleBlue.Blue, "ChangeColour" ))
else if 6 * frac < 3 then
f (Just RedPurpleBlue.Red) Nothing
else if 6 * frac < 4 then
f Nothing (Just ( RedPurpleBlue.Red, "ChangeColour" ))
else if 6 * frac < 5 then
f (Just RedPurpleBlue.Purple) Nothing
else
f Nothing (Just ( RedPurpleBlue.Purple, "ChangeColour" ))
user1State2 t f =
let
frac =
0.002 * t - toFloat (floor (0.002 * t))
in
if 6 * frac < 1 then
f (Just RedPurpleBlue.Purple) Nothing
else if 6 * frac < 2 then
f Nothing (Just ( RedPurpleBlue.Purple, "ChangeColour" ))
else if 6 * frac < 3 then
f (Just RedPurpleBlue.Blue) Nothing
else if 6 * frac < 4 then
f Nothing (Just ( RedPurpleBlue.Blue, "ChangeColour" ))
else if 6 * frac < 5 then
f (Just RedPurpleBlue.Red) Nothing
else
f Nothing (Just ( RedPurpleBlue.Red, "ChangeColour" ))
codeMarkdown codeString co =
let
code c ( txt, ln ) =
text txt
|> size 8
|> bold
|> customFont "Helvetica"
|> fixedwidth
|> filled c
|> move ( 0, -9 * ln )
lns =
String.lines codeString
positions : List String -> Float -> List ( String, Float )
positions lines i =
case lines of
l :: ls ->
( l, i ) :: positions ls (i + 1)
[] ->
[]
in
group (List.map (code co) (positions lns 0))
rpbTxt model =
[ group
[ codeMarkdown """ Model = Red Purple Blue
Msg = ChangeColour
view Model Html Msg
update Msg Model Model Cmd Msg
update msg model
msg
ChangeColour
updateColour model Cmd.none
updateColour Model Model
updateColour model =
model
Red Purple
Purple Blue
Blue Red
""" black
|> scale 2
|> move ( -215, 50 )
, codeMarkdown """type | |
type
: ->
: -> -> ( , )
=
case of
->
( , )
: ->
case of
->
->
->
""" pink
|> scale 2
|> move ( -215, 50 )
]
]
slide2 model =
{shapes = [ title "The Elm Language"
|> move ( -5, -30 )
, group
(makeBullets model
[ ( 0, "Functional language" )
, ( 0, "Compact syntax" )
, ( 0, "Pure functions" )
, ( 0, "Composable functions" )
, ( 0, "Strongly typed" )
, ( 1, "Detailed compiler errors for refactoring" )
, ( 0, "Compiles into JavaScript" )
]
0
)
|> move ( -80, 115 )
, outreachLogo
, html 200 200 (H.img [ HA.src "images/Elm.png", HA.style "width" "100%" ] [])
|> move ( 170, 70 )
]
, audio = Nothing
}
slideModelDrivenDevelopment model =
{shapes = [ title "Model Driven Development"
|> move ( -5, -30 )
, group
(makeBullets model.t
[ ( 0, "Software development approach" )
, ( 0, "For large-scale software development projects" )
, ( 0, "Higher level of abstraction" )
, ( 1, "Accelerates development" )
, ( 1, "Increases software quality" )
, ( 0, "Low code" )
, ( 1, "because code is automatically (re)generated" )
]
0
)
|> move ( -140, 90 )
, insertPicture "images/FoodGameStateDiagram.png"
|> scale 4.2
|> move (60,120)
, outreachLogo
]
, audio = Nothing
}
slidePALDraw model =
{shapes = [ title "PALDraw"
|> scale 0.9
|> move ( -310, -175 )
, group
(makeBullets model.t
[ ( 0, "PALDraw is a visual specification tool" )
]
0
)
|> scale 0.75
|> move ( -280, -20 )
, insertPicture "images/Combined.png"
|> scale 6
|> move (-180,200)
, outreachLogo
]
, audio = Nothing
}
solidState model =
let
( vx, vy ) =
( 0.2, 0.7 )
headBack =
group
[ rect 80 15
|> filled lightBlue
|> makeTransparent 0.3
, rect 80 15
|> outlined (solid 1) black
]
molecule =
group
[ circle 2 |> filled (rgb 0 200 0) |> move ( 8, 0 )
, circle 7 |> filled (rgb 0 0 250)
, circle 2 |> filled (rgb 0 200 0) |> move ( 0, 8 )
]
in
[ molecule
|> rotate (vx * (0.1 * model.t))
|> move
( 60 * sin (vx * (0.01 * model.t))
, 40 * sin (vy * (0.01 * model.t))
)
, text "Solid State"
|> centered
|> filled black
|> move ( 0, 55 )
, headBack
|> move ( 0, 58 )
]
liquidState model =
let
( vx, vy ) =
( pi, 2 )
headBack =
group
[ rect 80 15
|> filled lightBlue
|> makeTransparent 0.3
, rect 80 15
|> outlined (solid 1) black
]
molecule =
group
[ circle 2 |> filled (rgb 0 200 0) |> move ( 8, 0 )
, circle 7 |> filled (rgb 0 0 250)
, circle 2 |> filled (rgb 0 200 0) |> move ( 0, 8 )
]
in
[ molecule
|> rotate (vx * (0.02 * model.t))
|> move
( 60 * sin (vx * (0.015 * model.t))
, 40 * sin (vy * (0.015 * model.t))
)
, text "Liquid State"
|> centered
|> filled black
|> move ( 0, 55 )
, headBack
|> move ( 0, 58 )
]
gasState model =
let
( vx, vy ) =
( 57, 64 )
headBack =
group
[ rect 80 15
|> filled lightBlue
|> makeTransparent 0.3
, rect 80 15
|> outlined (solid 1) black
]
molecule =
group
[ circle 2 |> filled (rgb 0 200 0) |> move ( 8, 0 )
, circle 7 |> filled (rgb 0 0 250)
, circle 2 |> filled (rgb 0 200 0) |> move ( 0, 8 )
]
in
[ molecule
|> rotate (vx * (0.02 * model.t))
|> move
( 60 * sin (vx * (0.019 * model.t))
, 40 * sin (vy * (0.019 * model.t))
)
, text "Gaseous State"
|> centered
|> filled black
|> move ( 0, 55 )
, headBack
|> move ( 0, 58 )
]
slideSolid model =
{shapes = [ group (solidState model) |> scale 4 |> move ( 0, -50 ), outreachLogo ]
, audio = Nothing
}
slideLiquid model =
{shapes = [ group (liquidState model) |> scale 4 |> move ( 0, -50 ), outreachLogo ]
, audio = Nothing
}
slideGas model =
{shapes = [ group (gasState model) |> scale 4 |> move ( 0, -50 ), outreachLogo ]
, audio = Nothing
}
--<NAME>
char1R =
{ time = 0
, eyeColour = RGB 211 255 255
, skinColour = RGB 255 223 196
, headcoverColour = RGB 204 255 204
, hairFront = 7
, hairColour = RGB 255 153 51
, highlightColour = RGB 204 102 0
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- Dr <NAME>
char2R =
{ time = 0
, eyeColour = RGB 129 73 31
, skinColour = RGB 217 144 105
, headcoverColour = RGB 204 255 204
, hairFront = 16
, hairColour = RGB 32 32 32
, highlightColour = RGB 102 0 204
, eyeShape = 3
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- <NAME>umna
char3R =
{ time = 0
, eyeColour = RGB 32 32 32
, skinColour = RGB 219 144 101
, headcoverColour = RGB 204 255 204
, hairFront = 13
, hairColour = RGB 250 240 190
, highlightColour = RGB 102 0 204
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
--<NAME>
char4R =
{ time = 0
, eyeColour = RGB 32 32 32
, skinColour = RGB 219 144 101
, headcoverColour = RGB 204 255 204
, hairFront = 5
, hairColour = RGB 0 0 0
, highlightColour = RGB 102 0 204
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- <NAME>
char5R =
{ time = 0
, eyeColour = RGB 47 75 75
, skinColour = RGB 255 223 196
, headcoverColour = RGB 204 255 204
, hairFront = 9
, hairColour = RGB 130 72 24
, highlightColour = RGB 32 32 32
, eyeShape = 3
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- <NAME>
char6R =
{ time = 0
, eyeColour = RGB 147 0 73
, skinColour = RGB 255 204 204
, headcoverColour = RGB 204 255 204
, hairFront = 0
, hairColour = RGB 32 32 32
, highlightColour = RGB 32 32 32
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- <NAME>
char7R =
{ time = 0
, eyeColour = RGB 198 120 86
, skinColour = RGB 229 184 143
, headcoverColour = RGB 204 255 204
, hairFront = 3
, hairColour = RGB 62 43 19
, highlightColour = RGB 32 32 32
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
{-
To use slides with sound: elm make <moduleName>.elm --output=soundslides.js
- use elm reactor and go to soundslides.html
-} | true | port module TEAStateDiagrams exposing (main, slides)
import Array
import AvatarCreator
import Browser.Events as BEvents
import ColourPalette exposing (RGB(..), drawRGB)
import ElmArchitecture
import GraphicSVG exposing (..)
import GraphicSVG.App exposing (..)
import Html as H
import Html.Attributes as HA
import Json.Decode as Decode
import RedPurpleBlue
import WebFramework exposing (webFrameworkSlides)
import DoubleDiamond exposing (..)
import Url as Url
import Browser
import Browser.Navigation exposing (Key(..))
import Json.Encode as E
port play : E.Value -> Cmd msg
port getAudioDuration : (E.Value -> msg) -> Sub msg
people =
[]
type Message
= GameTick Float GetKeyState --The tick needs to have Float and GetKeyState which handles key presses.
| NextSlide
| LastSlide
| RPBMsg RedPurpleBlue.Msg -- (1) include message from included module
| AvatarMsg AvatarCreator.Msg
| NoOp
| MakeRequest Browser.UrlRequest
| UrlChange Url.Url
| GetNewAudioDuration (Maybe Float)
| DDiamondMsg DoubleDiamond.Msg
-- this is the main function, and for simple animations, you would only replace the view function, or edit it below
main : AppWithTick () Model Message
main =
appWithTick GameTick
{ init = \_ _ _ -> ( init, playSlideSound <| slide1 init)
, view = \model -> { title = "The Elm Architecture and State Diagrams", body = view model }
, update = update
, subscriptions = \_ -> Sub.batch [BEvents.onKeyUp controlSlide, subAudioDuration]
, onUrlChange = \_ -> NoOp
, onUrlRequest = \_ -> NoOp
}
subAudioDuration : Sub Message
subAudioDuration =
let
durationDecoder val =
case Decode.decodeValue Decode.float val of
Ok duration -> GetNewAudioDuration <| Just duration
Err _ -> GetNewAudioDuration Nothing
in
getAudioDuration durationDecoder
controlSlide : Decode.Decoder Message
controlSlide =
Decode.map
(\key ->
if key == "PageUp" then
LastSlide
else if key == "PageDown" then
NextSlide
else if key == "ArrowRight" then
NextSlide
else if key == "ArrowLeft" then
LastSlide
else
NoOp
)
keyDecoder
keyDecoder : Decode.Decoder String
keyDecoder =
Decode.field "key" Decode.string
-- MODEL
type alias Model =
{ t : Float
, idx : Int
, p : Bool
, -- Pause
r : Float
, -- Rewind
a : Float -- Acceleration
, rpb : RedPurpleBlue.Model
, audioDuration : Maybe Float
, time : Float
, slideStartTime : Float
, ddiamond : DoubleDiamond.Model
}
init : Model
init =
{ t = 0
, idx = 0
, p = False
, -- Pause
r = 1
, -- Rewind
a = 1 -- Acceleration
, rpb = RedPurpleBlue.init
, audioDuration = Nothing
, time = 0
, slideStartTime = 0
, ddiamond = DoubleDiamond.init
}
-- VIEW
view model =
let
t =
model.t
slide m =
((Maybe.withDefault default (Array.get model.idx slides)) m).shapes
in
collage 1000 500 (slide model ++ [audioBar model] ++ borders ++ navigators)
audioBar model =
case model.audioDuration of
Just dur ->
let
percentage = (model.time - model.slideStartTime)/dur
in
group
[
roundedRect 1000 10 5
|> filled gray
, roundedRect (1000 * percentage) 10 5
|> filled green
|> makeTransparent 0.3
]
|> move(0,-245)
Nothing -> group []
-- UPDATE
playSlideSound : Slide Message -> Cmd Message
playSlideSound slide =
case slide.audio of
Just s -> play (E.string s)
_ -> Cmd.none
update : Message -> Model -> ( Model, Cmd Message )
update message model =
let
_ =
case message of
GameTick _ _ ->
message
otherwise ->
Debug.log "message" message
in
case message of
NextSlide ->
let
newSlideId = min (model.idx + 1) (Array.length slides - 1)
newSlide =
case Array.get newSlideId slides of
Just slide -> slide model
_ -> default model
in
({ model
| t = 0
, idx = newSlideId
, slideStartTime = model.time
, audioDuration = Nothing
}, Debug.log "next slide cmd" playSlideSound newSlide )
LastSlide ->
let
newSlideId = max (model.idx - 1) 0
newSlide =
case Array.get newSlideId slides of
Just slide -> slide model
_ -> default model
in
({ model
| t = 0
, idx = newSlideId
, slideStartTime = model.time
, audioDuration = Nothing
} , Debug.log "last slide cmd" playSlideSound newSlide )
otherwise ->
(
case message of
GameTick tick ( getKeyState, changeP1, changeP2 ) ->
{ model
| t = max (model.t + 2.5 * model.a * model.r) 0
, time = tick
}
NextSlide ->
{ model
| t = 0
, idx = min (model.idx + 1) (Array.length slides - 1)
}
LastSlide ->
{ model
| t = 0
, idx = max (model.idx - 1) 0
}
RPBMsg msg ->
{ model | rpb = RedPurpleBlue.update msg model.rpb }
DDiamondMsg msg ->
{ model | ddiamond = DoubleDiamond.update msg model.ddiamond }
AvatarMsg msg ->
model
NoOp ->
model
MakeRequest _ -> model
UrlChange _ -> model
GetNewAudioDuration mDur ->
{ model | audioDuration = mDur }
, Cmd.none
)
--- MISCELLANEOUS
heritageMaroon =
rgb 122 0 60
heritageGold =
rgb 253 191 87
heritageGrey =
rgb 94 106 113
default _ =
{ shapes = [], audio = Nothing }
borders =
[ rect 5000 5000
|> filled white
|> move ( 3000, 0 )
, rect 5000 5000
|> filled white
|> move ( -3000, 0 )
, rect 5000 5000
|> filled white
|> move ( 0, 2750 )
, rect 5000 5000
|> filled white
|> move ( 0, -2750 )
]
navigators =
[ group
[ circle 40
|> filled gray
, triangle 30
|> filled white
]
|> move ( 450, -200 )
|> makeTransparent 0.5
|> notifyTap NextSlide
, group
[ circle 40
|> filled gray
, triangle 30
|> filled white
]
|> rotate (degrees 180)
|> move ( -450, -200 )
|> makeTransparent 0.5
|> notifyTap LastSlide
]
renderAvatar : AvatarCreator.Model -> Shape Message
renderAvatar avatarModel =
GraphicSVG.map AvatarMsg <| AvatarCreator.theFace avatarModel
makeBullets : Float -> List ( Int, String ) -> Float -> List (Shape msg)
makeBullets t l start =
case l of
( indt, x ) :: xs ->
(group
[ text x
|> size 20
|> customFont "Helvetica"
|> filled black
|> move ( -200, start )
|> fadeIn t 100
, circle 5
|> filled black
|> move ( -220, start + 5 )
|> fadeIn t 100
]
|> move ( 30 * toFloat indt, 0 )
)
:: makeBullets (t - 100) xs (start - 35)
_ ->
[]
-- FUNCTIONS
--<< So why do I see (t - 100) or whatever value so often? >>
-- Whenever I do that, I'm basically delaying what I want to happen
-- by that value. Is it measure in seconds, frames or what? What's the unit here?
-- To be honest, I don't know. It has a lot to do with the UPDATE function, and
-- what value for 'x' you are using for " t = model.t + x ".
disappear x n =
if x > n then
makeTransparent 0
else
makeTransparent 1
-- Makes things vanish off the screen!
loop t n =
let
y =
toFloat (floor (t / n))
-- This function is how I make things loop!
in
t - y * n
appear x n =
if x > n then
makeTransparent 1
else
makeTransparent 0
-- Makes things suddenly appear on the screen!
fadeIn t n =
makeTransparent (tranSin (t - n) 1)
fadeOut t n =
makeTransparent (1 - tranSin (t - n) 1)
trans t y =
if
t < 0
-- Used for all permanent transitions (fading out, color change, etc.) LINEAR.
then
0
else
Basics.min t y
tranSin t y =
if
t < 0
-- Used for all permanent transitions (fading out, color change, etc.) Uses sin.
then
0
else if t / 100 > pi / 2 then
y
else
sin (t / 100) * y
drawLine t ( x1, y1 ) ( x2, y2 ) =
line ( x1, y1 ) ( x1 + tranSin t (x2 - x1), y1 + tranSin t (y2 - y1) )
-- Down here is where you will find the slides!
-- To add more slides, simply add them to the list below.
fm : { a | t : Float } -> Float
fm m =
m.t
scaleTEA : Slide msg -> Slide msg
scaleTEA rec = {rec | shapes = [ move ( 0, -50 ) <| scale 3 <| group rec.shapes, outreachLogo, title "The Elm Architecture" ] }
type alias Slide msg =
{ shapes : List (Shape msg)
, audio : Maybe String
}
--slides : Array.Array ({ a | t : Float } -> Slide Message)
slides =
Array.fromList <|
[ slide1
, slide2 << fm
, scaleTEA << ElmArchitecture.slide1 << fm
, scaleTEA << ElmArchitecture.slide2 << fm
, scaleTEA << ElmArchitecture.slide3 << fm
, scaleTEA << ElmArchitecture.slide4 << fm
, scaleTEA << ElmArchitecture.slide5 << fm
, scaleTEA << ElmArchitecture.slide6 << fm
, scaleTEA << ElmArchitecture.slide7 << fm
, scaleTEA << ElmArchitecture.slide8 << fm
, scaleTEA << ElmArchitecture.slide9 << fm
, scaleTEA << ElmArchitecture.slide10 << fm
, scaleTEA << ElmArchitecture.slide11 << fm
, scaleTEA << ElmArchitecture.slide12 << fm
, slidePC0
, slidePC1
, slidePC2
, slidePC3
, slidePC4
, slidePC5
, slidePC0
, slidePC6
, slidePC6a
, slidePC6b
, slideSolid
, slideLiquid
, slideGas
]
title t =
text t
|> size 40
|> bold
|> customFont "Helvetica"
|> centered
|> filled heritageMaroon
|> move ( 0, 200 )
--<< EVERYTHING FOR FIRST PAGE >>-
outreachLogo =
group
[ GraphicSVG.html 100 100 (H.img [ HA.style "width" "100%", HA.src "images/Logo.png" ] [])
|> move ( -500, 250 )
|> addHyperlink "http://outreach.mcmaster.ca"
, text "I4CS 2020"
|> size 12
|> customFont "Arial"
|> filled black
|> move ( -485, 170 )
]
insertPicture url =
group
[ GraphicSVG.html 100 100 (H.img [ HA.style "width" "100%", HA.src url ] [])
|> addHyperlink "http://outreach.mcmaster.ca"
]
subtitle t =
text t
|> size 40
|> bold
|> customFont "Helvetica"
|> centered
|> filled green
slide0 model =
{ shapes = [], audio = Nothing }
arm shirtCol skinCol =
group
[ roundedRect 2 5 1
-- left arm
|> filled skinCol
|> rotate (degrees 120)
|> move ( -8, -4 )
, roundedRect 3 5 1
-- left sleeve
|> filled shirtCol
|> rotate (degrees 120)
|> move ( -5, -2 )
]
body shirtCol skinCol t =
group
[ roundedRect 3 8 1
-- left leg
|> filled blue
|> move ( -2, -11 )
, roundedRect 3 8 1
-- right leg
|> filled blue
|> move ( 2, -11 )
, roundedRect 2 5 1
-- neck
|> filled skinCol
, roundedRect 8 10 2
--body
|> filled shirtCol
|> move ( 0, -4 )
|> addHyperlink "http://outreach.mcmaster.ca"
, GraphicSVG.html 28 42 (H.img [ HA.style "width" "100%", HA.src "images/Shirt.png" ] [])
|> scale 0.2
|> move ( -3, 0 )
|> addHyperlink "http://outreach.mcmaster.ca"
, wedge 1.5 0.5
-- right shoe
|> filled lightBrown
|> rotate (degrees 90)
|> move ( 2, -15 )
, wedge 1.5 0.5
-- left shoe
|> filled lightBrown
|> rotate (degrees 90)
|> move ( -2, -15 )
]
slide1 model =
let
authorsColour =
black
-- PI:NAME:<NAME>END_PI avatar
char1 =
group
[ arm (rgb 255 0 0) (drawRGB char1R.skinColour)
-- left arm
|> rotate
(if model.t < 320 then
degrees (20 * sin (model.t * 0.1) - 20)
else
degrees 20 - 0.5
)
|> move ( 0, -1 )
, arm (rgb 255 0 0) (drawRGB char1R.skinColour)
-- right arm
|> mirrorX
|> rotate (degrees -20)
|> move ( 0, 2 )
, body (rgb 255 0 0) (drawRGB char1R.skinColour) model.t
, renderAvatar char1R |> scale 0.2 |> move ( 0, 6 )
]
-- Nhan avatar
char2 =
group
[ arm yellow (drawRGB char2R.skinColour)
-- left arm
|> rotate
(if model.t < 320 then
degrees (20 * sin (model.t * 0.1) - 20)
else
degrees 20 - 0.5
)
|> move ( 0, -1 )
, arm yellow (drawRGB char2R.skinColour)
-- right arm
|> mirrorX
|> rotate (degrees -20)
|> move ( 0, 2 )
, body yellow (drawRGB char2R.skinColour) model.t
, renderAvatar char2R |> scale 0.2 |> move ( 0, 6 )
]
-- Yumna Irfan avatar
char3 =
group
[ arm green (drawRGB char3R.skinColour)
-- left arm
|> rotate (degrees -70)
, arm green (drawRGB char3R.skinColour)
-- right arm
|> mirrorX
|> rotate (degrees -20)
|> move ( 0, 2 )
, body green (drawRGB char3R.skinColour) model.t
|> mirrorX
, renderAvatar char3R |> scale 0.2 |> move ( 0, 6 )
]
-- Tanya avatar
char4 =
group
[ arm orange (drawRGB char5R.skinColour)
--left arm
|> rotate (degrees -68)
|> move ( 0, -2 )
, arm orange (drawRGB char5R.skinColour)
-- right arm
|> mirrorX
|> rotate (degrees -20)
|> move ( 0, 2 )
, body orange (drawRGB char5R.skinColour) model.t
, renderAvatar char5R |> scale 0.2 |> move ( 0, 6 )
] |> move(6,0)
heading =
group
[ text "The Elm Architecture and State Diagrams"
|> size 6.5
|> bold
|> customFont "Helvetica"
|> centered
|> filled heritageMaroon
]
authors =
group
[ text "PI:NAME:<NAME>END_PI"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( -35, -26 )
, text ", PI:NAME:<NAME>END_PI,"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( 4.5, -26 )
, text " PI:NAME:<NAME>END_PI"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( 35, -26 )
, text "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI,"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( 5, -32 )
, text "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled authorsColour
|> move ( 5, -38 )
]
in
{ shapes =
[ group
[ group
[ GraphicSVG.html 40 40 (H.img [ HA.style "width" "100%", HA.src "images/Logo.png" ] [])
|> scale 0.6
|> move ( -12, 2 )
|> fadeIn model.t 150
|> addHyperlink "http://outreach.mcmaster.ca"
, group
[ text "Software:"
|> size 7
|> bold
|> customFont "Helvetica"
|> centered
|> filled heritageMaroon
|> addHyperlink "http://outreach.mcmaster.ca"
|> move ( 0, -25 )
, text "Tool For Change"
|> size 4
|> bold
|> customFont "Helvetica"
|> centered
|> filled heritageGold
|> addOutline (solid 0.125) heritageGrey
|> addHyperlink "http://outreach.mcmaster.ca"
|> move ( 0, -30 )
]
|> scale 0.85
]
|> move ( -31, -20 )
, GraphicSVG.html 40 40 (H.img [ HA.style "width" "100%", HA.src "images/MacEng.jpg" ] [])
|> move ( 20, -22 )
|> fadeIn model.t 150
|> addHyperlink "https://www.eng.mcmaster.ca/"
, group
[ group [ char1 |> move ( -10, 0 ), char2 |> move ( 10, 0 ) ]
|> move
( if model.t < 400 then
0
else
clamp 0 80 (model.t - 400)
, if model.t < 400 then
0
else
clamp -30 0 (-1 * model.t + 400)
)
, rect 100 40
|> filled white
|> fadeOut model.t 20
, heading
|> move
( if model.t < 200 then
-400
else
clamp -400 0 (-210 + (model.t - 200) * 0.3)
, 8
)
, authors
|> move
( if model.t < 200 then
400
else
clamp -6 400 (210 - (model.t - 200) * 0.3)
, 16
)
, char4
|> scale 0.7
|> move
( if model.t < 200 then
-400
else
clamp -400 90 (-128 + (model.t - 200) * 0.3)
, 4
)
, char3
|> mirrorX
|> scale 0.7
|> move
( if model.t < 200 then
400
else
clamp -90 120 (150 - (model.t - 200) * 0.3)
, -21
)
]
|> move ( 0, 25 )
]
|> scale 5
]
, audio = Nothing
}
decoratingPartPC6a =
let
customRed =
rgb 255 0 0
customBlue =
rgb 0 0 255
customPurple =
rgb 255 0 255
in
group [ circle 32 |> filled customRed |> move ( -240, 80 )
, rect 40 20 |> filled customRed |> move ( 150, 105 )
, circle 32 |> filled customPurple |> move ( -360, -80 )
, rect 64 20 |> filled customPurple |> move ( 221, 105 )
, circle 32 |> filled customBlue |> move ( -120, -80 )
, rect 42 20 |> filled customBlue |> move ( 298, 105 )
, rectangle 340 45 |> filled customPurple |> move ( 0, 157 )
]
slideDesignThinking: { a | ddiamond : DoubleDiamond.Model , t : Float } -> Slide Message
slideDesignThinking model = {shapes = List.map (GraphicSVG.map DDiamondMsg)
[ title "Design Thinking"
, group (DoubleDiamond.myShapes model.ddiamond) |> scale 3.7
]
, audio = Nothing}
slidePC0 model =
{shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model", group [ roundedRect 100 20 5 |> filled red, text "Click Me!" |> centered |> filled black |> move ( 0, -5 ) ] |> move ( 0, -220 ) ] ++ RedPurpleBlue.diagram "" (Just RedPurpleBlue.Red) Nothing ++ [ outreachLogo ]
, audio = Nothing
}
slidePC1 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model" ] ++ RedPurpleBlue.diagram "" Nothing (Just ( RedPurpleBlue.Red, "ChangeColour" )) ++ [ outreachLogo ]
, audio = Nothing
}
slidePC2 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model", group [ roundedRect 100 20 5 |> filled (rgb 200 0 200), text "Click Me!" |> centered |> filled black |> move ( 0, -5 ) ] |> move ( 0, -220 ) ] ++ RedPurpleBlue.diagram "" (Just RedPurpleBlue.Purple) Nothing ++ [ outreachLogo ]
, audio = Nothing
}
slidePC3 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model" ] ++ RedPurpleBlue.diagram "" Nothing (Just ( RedPurpleBlue.Purple, "ChangeColour" )) ++ [ outreachLogo ]
, audio = Nothing
}
slidePC4 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model", group [ roundedRect 100 20 5 |> filled (rgb 0 0 255), text "Click Me!" |> centered |> filled black |> move ( 0, -5 ) ] |> move ( 0, -220 ) ] ++ RedPurpleBlue.diagram "" (Just RedPurpleBlue.Blue) Nothing ++ [ outreachLogo ]
, audio = Nothing
}
slidePC5 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "Reasoning About the Model" ] ++ RedPurpleBlue.diagram "" Nothing (Just ( RedPurpleBlue.Blue, "ChangeColour" )) ++ [ outreachLogo ]
, audio = Nothing
}
slidePC6 =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "State Diagram → Elm" ] ++ [ scale 0.8 <| move ( -300, 0 ) <| group <| RedPurpleBlue.diagram "" Nothing Nothing, group (rpbTxt model) |> move ( 225, 50 ) ] ++ [ outreachLogo ]
, audio = Nothing
}
slidePC6a =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "State Diagram → Elm", decoratingPartPC6a, pcUnder "states → constructors" ] ++ [ scale 0.8 <| move ( -300, 0 ) <| group <| RedPurpleBlue.diagram "" Nothing Nothing, group (rpbTxt model) |> move ( 225, 50 ) ] ++ [ outreachLogo ]
, audio = Nothing
}
slidePC6b =
\model -> {shapes = List.map (GraphicSVG.map RPBMsg) <| [ title "State Diagram → Elm", rectangle 420 45 |> filled heritageGold |> move ( 0, 157 ), pcUnder "transitions → update functions", rectangle 340 45 |> filled heritageGold |> move ( 214, -72 ), rectangle 125 25 |> filled heritageGold |> move ( 174, 67 ), rectangle 100 25 |> filled heritageGold |> move ( -120, 43 ), rectangle 100 25 |> filled heritageGold |> move ( -360, 43 ), rectangle 100 25 |> filled heritageGold |> move ( -240, -117 ) ] ++ [ scale 0.8 <| move ( -300, 0 ) <| group <| RedPurpleBlue.diagram "" Nothing Nothing, group (rpbTxt model) |> move ( 225, 50 ) ] ++ [ outreachLogo ]
, audio = Nothing
}
pcUnder txt =
text txt
|> size 30
|> italic
|> customFont "Helvetica"
|> centered
|> filled black
|> move ( 0, 150 )
user1State t f =
let
frac =
0.002 * t - toFloat (floor (0.002 * t))
in
if 6 * frac < 1 then
f (Just RedPurpleBlue.Red) Nothing
else if 6 * frac < 2 then
f Nothing (Just ( RedPurpleBlue.Red, "ChangeColour" ))
else if 6 * frac < 3 then
f (Just RedPurpleBlue.Purple) Nothing
else if 6 * frac < 4 then
f Nothing (Just ( RedPurpleBlue.Purple, "ChangeColour" ))
else if 6 * frac < 5 then
f (Just RedPurpleBlue.Blue) Nothing
else
f Nothing (Just ( RedPurpleBlue.Blue, "ChangeColour" ))
user1State1 t f =
let
frac =
0.002 * t - toFloat (floor (0.002 * t))
in
if 6 * frac < 1 then
f (Just RedPurpleBlue.Blue) Nothing
else if 6 * frac < 2 then
f Nothing (Just ( RedPurpleBlue.Blue, "ChangeColour" ))
else if 6 * frac < 3 then
f (Just RedPurpleBlue.Red) Nothing
else if 6 * frac < 4 then
f Nothing (Just ( RedPurpleBlue.Red, "ChangeColour" ))
else if 6 * frac < 5 then
f (Just RedPurpleBlue.Purple) Nothing
else
f Nothing (Just ( RedPurpleBlue.Purple, "ChangeColour" ))
user1State2 t f =
let
frac =
0.002 * t - toFloat (floor (0.002 * t))
in
if 6 * frac < 1 then
f (Just RedPurpleBlue.Purple) Nothing
else if 6 * frac < 2 then
f Nothing (Just ( RedPurpleBlue.Purple, "ChangeColour" ))
else if 6 * frac < 3 then
f (Just RedPurpleBlue.Blue) Nothing
else if 6 * frac < 4 then
f Nothing (Just ( RedPurpleBlue.Blue, "ChangeColour" ))
else if 6 * frac < 5 then
f (Just RedPurpleBlue.Red) Nothing
else
f Nothing (Just ( RedPurpleBlue.Red, "ChangeColour" ))
codeMarkdown codeString co =
let
code c ( txt, ln ) =
text txt
|> size 8
|> bold
|> customFont "Helvetica"
|> fixedwidth
|> filled c
|> move ( 0, -9 * ln )
lns =
String.lines codeString
positions : List String -> Float -> List ( String, Float )
positions lines i =
case lines of
l :: ls ->
( l, i ) :: positions ls (i + 1)
[] ->
[]
in
group (List.map (code co) (positions lns 0))
rpbTxt model =
[ group
[ codeMarkdown """ Model = Red Purple Blue
Msg = ChangeColour
view Model Html Msg
update Msg Model Model Cmd Msg
update msg model
msg
ChangeColour
updateColour model Cmd.none
updateColour Model Model
updateColour model =
model
Red Purple
Purple Blue
Blue Red
""" black
|> scale 2
|> move ( -215, 50 )
, codeMarkdown """type | |
type
: ->
: -> -> ( , )
=
case of
->
( , )
: ->
case of
->
->
->
""" pink
|> scale 2
|> move ( -215, 50 )
]
]
slide2 model =
{shapes = [ title "The Elm Language"
|> move ( -5, -30 )
, group
(makeBullets model
[ ( 0, "Functional language" )
, ( 0, "Compact syntax" )
, ( 0, "Pure functions" )
, ( 0, "Composable functions" )
, ( 0, "Strongly typed" )
, ( 1, "Detailed compiler errors for refactoring" )
, ( 0, "Compiles into JavaScript" )
]
0
)
|> move ( -80, 115 )
, outreachLogo
, html 200 200 (H.img [ HA.src "images/Elm.png", HA.style "width" "100%" ] [])
|> move ( 170, 70 )
]
, audio = Nothing
}
slideModelDrivenDevelopment model =
{shapes = [ title "Model Driven Development"
|> move ( -5, -30 )
, group
(makeBullets model.t
[ ( 0, "Software development approach" )
, ( 0, "For large-scale software development projects" )
, ( 0, "Higher level of abstraction" )
, ( 1, "Accelerates development" )
, ( 1, "Increases software quality" )
, ( 0, "Low code" )
, ( 1, "because code is automatically (re)generated" )
]
0
)
|> move ( -140, 90 )
, insertPicture "images/FoodGameStateDiagram.png"
|> scale 4.2
|> move (60,120)
, outreachLogo
]
, audio = Nothing
}
slidePALDraw model =
{shapes = [ title "PALDraw"
|> scale 0.9
|> move ( -310, -175 )
, group
(makeBullets model.t
[ ( 0, "PALDraw is a visual specification tool" )
]
0
)
|> scale 0.75
|> move ( -280, -20 )
, insertPicture "images/Combined.png"
|> scale 6
|> move (-180,200)
, outreachLogo
]
, audio = Nothing
}
solidState model =
let
( vx, vy ) =
( 0.2, 0.7 )
headBack =
group
[ rect 80 15
|> filled lightBlue
|> makeTransparent 0.3
, rect 80 15
|> outlined (solid 1) black
]
molecule =
group
[ circle 2 |> filled (rgb 0 200 0) |> move ( 8, 0 )
, circle 7 |> filled (rgb 0 0 250)
, circle 2 |> filled (rgb 0 200 0) |> move ( 0, 8 )
]
in
[ molecule
|> rotate (vx * (0.1 * model.t))
|> move
( 60 * sin (vx * (0.01 * model.t))
, 40 * sin (vy * (0.01 * model.t))
)
, text "Solid State"
|> centered
|> filled black
|> move ( 0, 55 )
, headBack
|> move ( 0, 58 )
]
liquidState model =
let
( vx, vy ) =
( pi, 2 )
headBack =
group
[ rect 80 15
|> filled lightBlue
|> makeTransparent 0.3
, rect 80 15
|> outlined (solid 1) black
]
molecule =
group
[ circle 2 |> filled (rgb 0 200 0) |> move ( 8, 0 )
, circle 7 |> filled (rgb 0 0 250)
, circle 2 |> filled (rgb 0 200 0) |> move ( 0, 8 )
]
in
[ molecule
|> rotate (vx * (0.02 * model.t))
|> move
( 60 * sin (vx * (0.015 * model.t))
, 40 * sin (vy * (0.015 * model.t))
)
, text "Liquid State"
|> centered
|> filled black
|> move ( 0, 55 )
, headBack
|> move ( 0, 58 )
]
gasState model =
let
( vx, vy ) =
( 57, 64 )
headBack =
group
[ rect 80 15
|> filled lightBlue
|> makeTransparent 0.3
, rect 80 15
|> outlined (solid 1) black
]
molecule =
group
[ circle 2 |> filled (rgb 0 200 0) |> move ( 8, 0 )
, circle 7 |> filled (rgb 0 0 250)
, circle 2 |> filled (rgb 0 200 0) |> move ( 0, 8 )
]
in
[ molecule
|> rotate (vx * (0.02 * model.t))
|> move
( 60 * sin (vx * (0.019 * model.t))
, 40 * sin (vy * (0.019 * model.t))
)
, text "Gaseous State"
|> centered
|> filled black
|> move ( 0, 55 )
, headBack
|> move ( 0, 58 )
]
slideSolid model =
{shapes = [ group (solidState model) |> scale 4 |> move ( 0, -50 ), outreachLogo ]
, audio = Nothing
}
slideLiquid model =
{shapes = [ group (liquidState model) |> scale 4 |> move ( 0, -50 ), outreachLogo ]
, audio = Nothing
}
slideGas model =
{shapes = [ group (gasState model) |> scale 4 |> move ( 0, -50 ), outreachLogo ]
, audio = Nothing
}
--PI:NAME:<NAME>END_PI
char1R =
{ time = 0
, eyeColour = RGB 211 255 255
, skinColour = RGB 255 223 196
, headcoverColour = RGB 204 255 204
, hairFront = 7
, hairColour = RGB 255 153 51
, highlightColour = RGB 204 102 0
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- Dr PI:NAME:<NAME>END_PI
char2R =
{ time = 0
, eyeColour = RGB 129 73 31
, skinColour = RGB 217 144 105
, headcoverColour = RGB 204 255 204
, hairFront = 16
, hairColour = RGB 32 32 32
, highlightColour = RGB 102 0 204
, eyeShape = 3
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- PI:NAME:<NAME>END_PIumna
char3R =
{ time = 0
, eyeColour = RGB 32 32 32
, skinColour = RGB 219 144 101
, headcoverColour = RGB 204 255 204
, hairFront = 13
, hairColour = RGB 250 240 190
, highlightColour = RGB 102 0 204
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
--PI:NAME:<NAME>END_PI
char4R =
{ time = 0
, eyeColour = RGB 32 32 32
, skinColour = RGB 219 144 101
, headcoverColour = RGB 204 255 204
, hairFront = 5
, hairColour = RGB 0 0 0
, highlightColour = RGB 102 0 204
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- PI:NAME:<NAME>END_PI
char5R =
{ time = 0
, eyeColour = RGB 47 75 75
, skinColour = RGB 255 223 196
, headcoverColour = RGB 204 255 204
, hairFront = 9
, hairColour = RGB 130 72 24
, highlightColour = RGB 32 32 32
, eyeShape = 3
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- PI:NAME:<NAME>END_PI
char6R =
{ time = 0
, eyeColour = RGB 147 0 73
, skinColour = RGB 255 204 204
, headcoverColour = RGB 204 255 204
, hairFront = 0
, hairColour = RGB 32 32 32
, highlightColour = RGB 32 32 32
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
-- PI:NAME:<NAME>END_PI
char7R =
{ time = 0
, eyeColour = RGB 198 120 86
, skinColour = RGB 229 184 143
, headcoverColour = RGB 204 255 204
, hairFront = 3
, hairColour = RGB 62 43 19
, highlightColour = RGB 32 32 32
, eyeShape = 0
, extra = 0
, selected = AvatarCreator.SelectNone
}
{-
To use slides with sound: elm make <moduleName>.elm --output=soundslides.js
- use elm reactor and go to soundslides.html
-} | elm |
[
{
"context": "ge/svg+xml\">\n -- <img src=\"logo.png\" alt=\"Company Name\">\n -- </object>\n -- </figure>\n\n+ _",
"end": 2251,
"score": 0.6190447211,
"start": 2244,
"tag": "NAME",
"value": "Company"
}
] | src/Ui/Media.elm | danielnarey/elm-modular-ui | 11 | module Ui.Media exposing
( image, svg, video, audio, withCaption )
{-|
# Content Element: Media
This module contains helpers to insert images and other media content into your
page layout, with built-in features for web accessibility. The image constructor
applies the *.image* Bulma element class, which is helpful for positioning
and images and provides a set of fixed and responsive size modifiers. Other
media content types that are not supported by Bulma are assigned class names
for custom styling.
## Media Elements
@docs image, svg, video, audio
## Adding a Caption
@docs withCaption
-}
-- Framework
import Ui
import Dom.Element
import Dom.Node
import Dom.Property
import Dom.Attribute
-- Core
import Char
{-| Construct image content (typically from a JPEG or PNG source), with alt
text for screen readers
{ path = "http://bulma.io/images/placeholders/128x128.png"
, altText = "This is a placeholder"
}
|> Ui.Media.image
|> Ui.Modifier.add "is-128x128"
|> Ui.render
--> <figure class="image is-128x128">
-- <img src="http://bulma.io/images/placeholders/128x128.png" alt="This is a placeholder">
-- </figure>
+ __HTML tags__: `<figure>` > `<img>`
+ __ARIA roles__: *figure* > *img* (defaults)
+ __Element class__: *.image*
+ __Available modifiers__: size ([fixed](https://bulma.io/documentation/elements/image/#fixed-square-images),
[responsive](https://bulma.io/documentation/elements/image/#responsive-images-with-ratios))
+ __Bulma CSS reference__: http://bulma.io/documentation/elements/image/
-}
image : { path : String, altText : String } -> Ui.Element msg
image args =
[ Dom.Node.leaf "img"
[ "src"
|> Dom.Property.string args.path
, "alt"
|> Dom.Property.string args.altText
]
]
|> Dom.Element.wrapNodes "figure"
|> Dom.Element.withClasses
[ "image" ]
{-| Construct SVG content, with a raster image fallback for older browsers and
alt text for screen readers
{ path = "logo.svg"
, fallback = "logo.png"
, altText = "Company Logo"
}
|> Ui.Media.svg
|> Ui.render
--> <figure class="svg-object">
-- <object data="logo.svg" type="image/svg+xml">
-- <img src="logo.png" alt="Company Name">
-- </object>
-- </figure>
+ __HTML tags__: `<figure>` > `<object>` > `<img>`
+ __ARIA roles__: *figure* > *img* (defaults)
+ __Element class__: *.svg-object*
+ __Available modifiers__: none
+ __Bulma CSS reference__: none (*.svg-object* is not a Bulma element class)
-}
svg : { path : String, fallback : String, altText : String } -> Ui.Element msg
svg args =
[ [ Dom.Node.leaf "img"
[ "src"
|> Dom.Property.string args.fallback
, "alt"
|> Dom.Property.string args.altText
]
]
|> Dom.Node.container "object"
[ "data"
|> Dom.Property.string args.path
, "type"
|> Dom.Property.string "image/svg+xml"
]
]
|> Dom.Element.wrapNodes "figure"
|> Dom.Element.withClasses
[ "svg-object" ]
{-| Construct video content, with an automatically generated error message as a
fallback. Several source files may be listed to ensure that the video is
playable in all modern browsers. The second string in each tuple gives the
[media type code](https://www.iana.org/assignments/media-types/media-types.xhtml)
of the file. The `hasControls` argument indicates whether controls should be
displayed in the video frame.
{ sourceList =
[ ("movie.mp4", "video/mp4")
, ("movie.ogg", "video/ogg")
]
, hasControls = True
}
|> Ui.Media.video
|> Ui.render
--> <figure class="video">
-- <video controls role="application">
-- <source src="movie.mp4" type="video/mp4">
-- <source src="movie.ogg" type="video/ogg">
-- <p>Video file 'movie.mp4' cannot be loaded. Verify that your browser
-- is up to date and can play 'video/mp4' files.</p>
-- <p>Video file 'movie.ogg' cannot be loaded. Verify that your browser
-- is up to date and can play 'video/ogg' files.</p>
-- </video>
-- </figure>
+ __HTML tags__: `<figure>` > `<video>` > `<source>`
+ __ARIA roles__: *figure* (default) > *application*
+ __Element class__: *.video*
+ __Available modifiers__: none
+ __Bulma CSS reference__: none (*.video* is not a Bulma element class)
-}
video : { sourceList : List (String, String), hasControls : Bool } -> Ui.Element msg
video args =
let
toSourceNode (path, filetype) =
[ "src"
|> Dom.Property.string path
, "type"
|> Dom.Property.string filetype
]
|> Dom.Node.leaf "source"
toErrorMessage (path, filetype) =
[ "Video file '"
, path
, "' cannot be loaded. "
, "Verify that your browser is up to date and can play '"
, filetype
, "' files."
]
|> String.concat
|> Dom.Node.textWrapper "p" []
in
[ [ args.sourceList
|> List.map toSourceNode
, args.sourceList
|> List.map toErrorMessage
]
|> List.concat
|> Dom.Node.container "video"
[ "controls"
|> Dom.Property.bool args.hasControls
, "role"
|> Dom.Attribute.string "application"
]
]
|> Dom.Element.wrapNodes "figure"
|> Dom.Element.withClasses
[ "video" ]
{-| Construct audio content, with an automatically generated error message as a
fallback. Several source files may be listed to ensure that the audio is
playable in all modern browsers. The second string in each tuple gives the
[media type code](https://www.iana.org/assignments/media-types/media-types.xhtml)
of the file. The boolean argument indicates whether controls should be
displayed.
{ sourceList =
[ ("horse.ogg", "audio/ogg")
, ("horse.mp3", "audio/mpeg")
]
, hasControls = True
}
|> Ui.Media.audio
|> Ui.render
--> <figure>
-- <audio controls role="application">
-- <source src="horse.ogg" type="audio/ogg">
-- <source src="horse.mp3" type="audio/mpeg">
-- <p>Audio file 'horse.ogg' cannot be loaded. Verify that your browser
-- is up to date and can play 'audio/ogg' files.</p>
-- <p>Audio file 'horse.mp3' cannot be loaded. Verify that your browser
-- is up to date and can play 'audio/mpeg' files.</p>
-- </audio>
-- </figure>
+ __HTML tags__: `<figure>` > `<audio>` > `<source>`
+ __ARIA roles__: *figure* (default) > *application*
+ __Element class__: *.audio*
+ __Available modifiers__: none
+ __Bulma CSS reference__: none (*.audio* is not a Bulma element class)
-}
audio : { sourceList : List (String, String), hasControls : Bool } -> Ui.Element msg
audio args =
let
toSourceNode (path, filetype) =
[ "src"
|> Dom.Property.string path
, "type"
|> Dom.Property.string filetype
]
|> Dom.Node.leaf "source"
toErrorMessage (path, filetype) =
[ "Audio file '"
, path
, "' cannot be loaded. "
, "Verify that your browser is up to date and can play '"
, filetype
, "' files."
]
|> String.concat
|> Dom.Node.textWrapper "p" []
in
[ [ args.sourceList
|> List.map toSourceNode
, args.sourceList
|> List.map toErrorMessage
]
|> List.concat
|> Dom.Node.container "audio"
[ "controls"
|> Dom.Property.bool args.hasControls
, "role"
|> Dom.Attribute.string "application"
]
]
|> Dom.Element.wrapNodes "figure"
|> Dom.Element.withClasses
[ "audio" ]
{-| Add a figure caption to a media element. The `id` argument is a unique
integer that is used to generate an *id* attribute for the caption so that
it can be identified for screen readers as labelling the media element.
{ path = "http://bulma.io/images/placeholders/128x128.png"
, altText = "This is a placeholder"
}
|> Ui.Media.image
|> Ui.Modifier.add "is-128x128"
|> Ui.Media.withCaption
{ id = 1
, text = "This image is 128 px by 128 px."
}
|> Ui.render
--> <figure class="image is-128x128" aria-labelledby="caption-1">
-- <img src="http://bulma.io/images/placeholders/128x128.png" alt="This is a placeholder">
-- <figcaption id="caption-1">This image is 128 px x 128 px.</figcaption>
-- </figure>
+ __HTML tags__: `<figure>` > `<figcaption>`
+ __ARIA attribute__: *aria-labelledby* (caption is identified as the visible label for the figure element)
-}
withCaption : { id : Int, text : String } -> Ui.Element msg -> Ui.Element msg
withCaption args figureElement =
figureElement
|> Dom.Element.appendChild
( args.text
|> Dom.Element.textWrapper "figcaption"
|> Dom.Element.withAttributes
[ "id"
|> Dom.Property.string
( args.id
|> Basics.toString
|> String.append "caption-"
)
]
)
|> Dom.Element.addAttribute
( "aria-labelledby"
|> Dom.Attribute.string
( args.id
|> Basics.toString
|> String.append "caption-"
)
)
| 27619 | module Ui.Media exposing
( image, svg, video, audio, withCaption )
{-|
# Content Element: Media
This module contains helpers to insert images and other media content into your
page layout, with built-in features for web accessibility. The image constructor
applies the *.image* Bulma element class, which is helpful for positioning
and images and provides a set of fixed and responsive size modifiers. Other
media content types that are not supported by Bulma are assigned class names
for custom styling.
## Media Elements
@docs image, svg, video, audio
## Adding a Caption
@docs withCaption
-}
-- Framework
import Ui
import Dom.Element
import Dom.Node
import Dom.Property
import Dom.Attribute
-- Core
import Char
{-| Construct image content (typically from a JPEG or PNG source), with alt
text for screen readers
{ path = "http://bulma.io/images/placeholders/128x128.png"
, altText = "This is a placeholder"
}
|> Ui.Media.image
|> Ui.Modifier.add "is-128x128"
|> Ui.render
--> <figure class="image is-128x128">
-- <img src="http://bulma.io/images/placeholders/128x128.png" alt="This is a placeholder">
-- </figure>
+ __HTML tags__: `<figure>` > `<img>`
+ __ARIA roles__: *figure* > *img* (defaults)
+ __Element class__: *.image*
+ __Available modifiers__: size ([fixed](https://bulma.io/documentation/elements/image/#fixed-square-images),
[responsive](https://bulma.io/documentation/elements/image/#responsive-images-with-ratios))
+ __Bulma CSS reference__: http://bulma.io/documentation/elements/image/
-}
image : { path : String, altText : String } -> Ui.Element msg
image args =
[ Dom.Node.leaf "img"
[ "src"
|> Dom.Property.string args.path
, "alt"
|> Dom.Property.string args.altText
]
]
|> Dom.Element.wrapNodes "figure"
|> Dom.Element.withClasses
[ "image" ]
{-| Construct SVG content, with a raster image fallback for older browsers and
alt text for screen readers
{ path = "logo.svg"
, fallback = "logo.png"
, altText = "Company Logo"
}
|> Ui.Media.svg
|> Ui.render
--> <figure class="svg-object">
-- <object data="logo.svg" type="image/svg+xml">
-- <img src="logo.png" alt="<NAME> Name">
-- </object>
-- </figure>
+ __HTML tags__: `<figure>` > `<object>` > `<img>`
+ __ARIA roles__: *figure* > *img* (defaults)
+ __Element class__: *.svg-object*
+ __Available modifiers__: none
+ __Bulma CSS reference__: none (*.svg-object* is not a Bulma element class)
-}
svg : { path : String, fallback : String, altText : String } -> Ui.Element msg
svg args =
[ [ Dom.Node.leaf "img"
[ "src"
|> Dom.Property.string args.fallback
, "alt"
|> Dom.Property.string args.altText
]
]
|> Dom.Node.container "object"
[ "data"
|> Dom.Property.string args.path
, "type"
|> Dom.Property.string "image/svg+xml"
]
]
|> Dom.Element.wrapNodes "figure"
|> Dom.Element.withClasses
[ "svg-object" ]
{-| Construct video content, with an automatically generated error message as a
fallback. Several source files may be listed to ensure that the video is
playable in all modern browsers. The second string in each tuple gives the
[media type code](https://www.iana.org/assignments/media-types/media-types.xhtml)
of the file. The `hasControls` argument indicates whether controls should be
displayed in the video frame.
{ sourceList =
[ ("movie.mp4", "video/mp4")
, ("movie.ogg", "video/ogg")
]
, hasControls = True
}
|> Ui.Media.video
|> Ui.render
--> <figure class="video">
-- <video controls role="application">
-- <source src="movie.mp4" type="video/mp4">
-- <source src="movie.ogg" type="video/ogg">
-- <p>Video file 'movie.mp4' cannot be loaded. Verify that your browser
-- is up to date and can play 'video/mp4' files.</p>
-- <p>Video file 'movie.ogg' cannot be loaded. Verify that your browser
-- is up to date and can play 'video/ogg' files.</p>
-- </video>
-- </figure>
+ __HTML tags__: `<figure>` > `<video>` > `<source>`
+ __ARIA roles__: *figure* (default) > *application*
+ __Element class__: *.video*
+ __Available modifiers__: none
+ __Bulma CSS reference__: none (*.video* is not a Bulma element class)
-}
video : { sourceList : List (String, String), hasControls : Bool } -> Ui.Element msg
video args =
let
toSourceNode (path, filetype) =
[ "src"
|> Dom.Property.string path
, "type"
|> Dom.Property.string filetype
]
|> Dom.Node.leaf "source"
toErrorMessage (path, filetype) =
[ "Video file '"
, path
, "' cannot be loaded. "
, "Verify that your browser is up to date and can play '"
, filetype
, "' files."
]
|> String.concat
|> Dom.Node.textWrapper "p" []
in
[ [ args.sourceList
|> List.map toSourceNode
, args.sourceList
|> List.map toErrorMessage
]
|> List.concat
|> Dom.Node.container "video"
[ "controls"
|> Dom.Property.bool args.hasControls
, "role"
|> Dom.Attribute.string "application"
]
]
|> Dom.Element.wrapNodes "figure"
|> Dom.Element.withClasses
[ "video" ]
{-| Construct audio content, with an automatically generated error message as a
fallback. Several source files may be listed to ensure that the audio is
playable in all modern browsers. The second string in each tuple gives the
[media type code](https://www.iana.org/assignments/media-types/media-types.xhtml)
of the file. The boolean argument indicates whether controls should be
displayed.
{ sourceList =
[ ("horse.ogg", "audio/ogg")
, ("horse.mp3", "audio/mpeg")
]
, hasControls = True
}
|> Ui.Media.audio
|> Ui.render
--> <figure>
-- <audio controls role="application">
-- <source src="horse.ogg" type="audio/ogg">
-- <source src="horse.mp3" type="audio/mpeg">
-- <p>Audio file 'horse.ogg' cannot be loaded. Verify that your browser
-- is up to date and can play 'audio/ogg' files.</p>
-- <p>Audio file 'horse.mp3' cannot be loaded. Verify that your browser
-- is up to date and can play 'audio/mpeg' files.</p>
-- </audio>
-- </figure>
+ __HTML tags__: `<figure>` > `<audio>` > `<source>`
+ __ARIA roles__: *figure* (default) > *application*
+ __Element class__: *.audio*
+ __Available modifiers__: none
+ __Bulma CSS reference__: none (*.audio* is not a Bulma element class)
-}
audio : { sourceList : List (String, String), hasControls : Bool } -> Ui.Element msg
audio args =
let
toSourceNode (path, filetype) =
[ "src"
|> Dom.Property.string path
, "type"
|> Dom.Property.string filetype
]
|> Dom.Node.leaf "source"
toErrorMessage (path, filetype) =
[ "Audio file '"
, path
, "' cannot be loaded. "
, "Verify that your browser is up to date and can play '"
, filetype
, "' files."
]
|> String.concat
|> Dom.Node.textWrapper "p" []
in
[ [ args.sourceList
|> List.map toSourceNode
, args.sourceList
|> List.map toErrorMessage
]
|> List.concat
|> Dom.Node.container "audio"
[ "controls"
|> Dom.Property.bool args.hasControls
, "role"
|> Dom.Attribute.string "application"
]
]
|> Dom.Element.wrapNodes "figure"
|> Dom.Element.withClasses
[ "audio" ]
{-| Add a figure caption to a media element. The `id` argument is a unique
integer that is used to generate an *id* attribute for the caption so that
it can be identified for screen readers as labelling the media element.
{ path = "http://bulma.io/images/placeholders/128x128.png"
, altText = "This is a placeholder"
}
|> Ui.Media.image
|> Ui.Modifier.add "is-128x128"
|> Ui.Media.withCaption
{ id = 1
, text = "This image is 128 px by 128 px."
}
|> Ui.render
--> <figure class="image is-128x128" aria-labelledby="caption-1">
-- <img src="http://bulma.io/images/placeholders/128x128.png" alt="This is a placeholder">
-- <figcaption id="caption-1">This image is 128 px x 128 px.</figcaption>
-- </figure>
+ __HTML tags__: `<figure>` > `<figcaption>`
+ __ARIA attribute__: *aria-labelledby* (caption is identified as the visible label for the figure element)
-}
withCaption : { id : Int, text : String } -> Ui.Element msg -> Ui.Element msg
withCaption args figureElement =
figureElement
|> Dom.Element.appendChild
( args.text
|> Dom.Element.textWrapper "figcaption"
|> Dom.Element.withAttributes
[ "id"
|> Dom.Property.string
( args.id
|> Basics.toString
|> String.append "caption-"
)
]
)
|> Dom.Element.addAttribute
( "aria-labelledby"
|> Dom.Attribute.string
( args.id
|> Basics.toString
|> String.append "caption-"
)
)
| true | module Ui.Media exposing
( image, svg, video, audio, withCaption )
{-|
# Content Element: Media
This module contains helpers to insert images and other media content into your
page layout, with built-in features for web accessibility. The image constructor
applies the *.image* Bulma element class, which is helpful for positioning
and images and provides a set of fixed and responsive size modifiers. Other
media content types that are not supported by Bulma are assigned class names
for custom styling.
## Media Elements
@docs image, svg, video, audio
## Adding a Caption
@docs withCaption
-}
-- Framework
import Ui
import Dom.Element
import Dom.Node
import Dom.Property
import Dom.Attribute
-- Core
import Char
{-| Construct image content (typically from a JPEG or PNG source), with alt
text for screen readers
{ path = "http://bulma.io/images/placeholders/128x128.png"
, altText = "This is a placeholder"
}
|> Ui.Media.image
|> Ui.Modifier.add "is-128x128"
|> Ui.render
--> <figure class="image is-128x128">
-- <img src="http://bulma.io/images/placeholders/128x128.png" alt="This is a placeholder">
-- </figure>
+ __HTML tags__: `<figure>` > `<img>`
+ __ARIA roles__: *figure* > *img* (defaults)
+ __Element class__: *.image*
+ __Available modifiers__: size ([fixed](https://bulma.io/documentation/elements/image/#fixed-square-images),
[responsive](https://bulma.io/documentation/elements/image/#responsive-images-with-ratios))
+ __Bulma CSS reference__: http://bulma.io/documentation/elements/image/
-}
image : { path : String, altText : String } -> Ui.Element msg
image args =
[ Dom.Node.leaf "img"
[ "src"
|> Dom.Property.string args.path
, "alt"
|> Dom.Property.string args.altText
]
]
|> Dom.Element.wrapNodes "figure"
|> Dom.Element.withClasses
[ "image" ]
{-| Construct SVG content, with a raster image fallback for older browsers and
alt text for screen readers
{ path = "logo.svg"
, fallback = "logo.png"
, altText = "Company Logo"
}
|> Ui.Media.svg
|> Ui.render
--> <figure class="svg-object">
-- <object data="logo.svg" type="image/svg+xml">
-- <img src="logo.png" alt="PI:NAME:<NAME>END_PI Name">
-- </object>
-- </figure>
+ __HTML tags__: `<figure>` > `<object>` > `<img>`
+ __ARIA roles__: *figure* > *img* (defaults)
+ __Element class__: *.svg-object*
+ __Available modifiers__: none
+ __Bulma CSS reference__: none (*.svg-object* is not a Bulma element class)
-}
svg : { path : String, fallback : String, altText : String } -> Ui.Element msg
svg args =
[ [ Dom.Node.leaf "img"
[ "src"
|> Dom.Property.string args.fallback
, "alt"
|> Dom.Property.string args.altText
]
]
|> Dom.Node.container "object"
[ "data"
|> Dom.Property.string args.path
, "type"
|> Dom.Property.string "image/svg+xml"
]
]
|> Dom.Element.wrapNodes "figure"
|> Dom.Element.withClasses
[ "svg-object" ]
{-| Construct video content, with an automatically generated error message as a
fallback. Several source files may be listed to ensure that the video is
playable in all modern browsers. The second string in each tuple gives the
[media type code](https://www.iana.org/assignments/media-types/media-types.xhtml)
of the file. The `hasControls` argument indicates whether controls should be
displayed in the video frame.
{ sourceList =
[ ("movie.mp4", "video/mp4")
, ("movie.ogg", "video/ogg")
]
, hasControls = True
}
|> Ui.Media.video
|> Ui.render
--> <figure class="video">
-- <video controls role="application">
-- <source src="movie.mp4" type="video/mp4">
-- <source src="movie.ogg" type="video/ogg">
-- <p>Video file 'movie.mp4' cannot be loaded. Verify that your browser
-- is up to date and can play 'video/mp4' files.</p>
-- <p>Video file 'movie.ogg' cannot be loaded. Verify that your browser
-- is up to date and can play 'video/ogg' files.</p>
-- </video>
-- </figure>
+ __HTML tags__: `<figure>` > `<video>` > `<source>`
+ __ARIA roles__: *figure* (default) > *application*
+ __Element class__: *.video*
+ __Available modifiers__: none
+ __Bulma CSS reference__: none (*.video* is not a Bulma element class)
-}
video : { sourceList : List (String, String), hasControls : Bool } -> Ui.Element msg
video args =
let
toSourceNode (path, filetype) =
[ "src"
|> Dom.Property.string path
, "type"
|> Dom.Property.string filetype
]
|> Dom.Node.leaf "source"
toErrorMessage (path, filetype) =
[ "Video file '"
, path
, "' cannot be loaded. "
, "Verify that your browser is up to date and can play '"
, filetype
, "' files."
]
|> String.concat
|> Dom.Node.textWrapper "p" []
in
[ [ args.sourceList
|> List.map toSourceNode
, args.sourceList
|> List.map toErrorMessage
]
|> List.concat
|> Dom.Node.container "video"
[ "controls"
|> Dom.Property.bool args.hasControls
, "role"
|> Dom.Attribute.string "application"
]
]
|> Dom.Element.wrapNodes "figure"
|> Dom.Element.withClasses
[ "video" ]
{-| Construct audio content, with an automatically generated error message as a
fallback. Several source files may be listed to ensure that the audio is
playable in all modern browsers. The second string in each tuple gives the
[media type code](https://www.iana.org/assignments/media-types/media-types.xhtml)
of the file. The boolean argument indicates whether controls should be
displayed.
{ sourceList =
[ ("horse.ogg", "audio/ogg")
, ("horse.mp3", "audio/mpeg")
]
, hasControls = True
}
|> Ui.Media.audio
|> Ui.render
--> <figure>
-- <audio controls role="application">
-- <source src="horse.ogg" type="audio/ogg">
-- <source src="horse.mp3" type="audio/mpeg">
-- <p>Audio file 'horse.ogg' cannot be loaded. Verify that your browser
-- is up to date and can play 'audio/ogg' files.</p>
-- <p>Audio file 'horse.mp3' cannot be loaded. Verify that your browser
-- is up to date and can play 'audio/mpeg' files.</p>
-- </audio>
-- </figure>
+ __HTML tags__: `<figure>` > `<audio>` > `<source>`
+ __ARIA roles__: *figure* (default) > *application*
+ __Element class__: *.audio*
+ __Available modifiers__: none
+ __Bulma CSS reference__: none (*.audio* is not a Bulma element class)
-}
audio : { sourceList : List (String, String), hasControls : Bool } -> Ui.Element msg
audio args =
let
toSourceNode (path, filetype) =
[ "src"
|> Dom.Property.string path
, "type"
|> Dom.Property.string filetype
]
|> Dom.Node.leaf "source"
toErrorMessage (path, filetype) =
[ "Audio file '"
, path
, "' cannot be loaded. "
, "Verify that your browser is up to date and can play '"
, filetype
, "' files."
]
|> String.concat
|> Dom.Node.textWrapper "p" []
in
[ [ args.sourceList
|> List.map toSourceNode
, args.sourceList
|> List.map toErrorMessage
]
|> List.concat
|> Dom.Node.container "audio"
[ "controls"
|> Dom.Property.bool args.hasControls
, "role"
|> Dom.Attribute.string "application"
]
]
|> Dom.Element.wrapNodes "figure"
|> Dom.Element.withClasses
[ "audio" ]
{-| Add a figure caption to a media element. The `id` argument is a unique
integer that is used to generate an *id* attribute for the caption so that
it can be identified for screen readers as labelling the media element.
{ path = "http://bulma.io/images/placeholders/128x128.png"
, altText = "This is a placeholder"
}
|> Ui.Media.image
|> Ui.Modifier.add "is-128x128"
|> Ui.Media.withCaption
{ id = 1
, text = "This image is 128 px by 128 px."
}
|> Ui.render
--> <figure class="image is-128x128" aria-labelledby="caption-1">
-- <img src="http://bulma.io/images/placeholders/128x128.png" alt="This is a placeholder">
-- <figcaption id="caption-1">This image is 128 px x 128 px.</figcaption>
-- </figure>
+ __HTML tags__: `<figure>` > `<figcaption>`
+ __ARIA attribute__: *aria-labelledby* (caption is identified as the visible label for the figure element)
-}
withCaption : { id : Int, text : String } -> Ui.Element msg -> Ui.Element msg
withCaption args figureElement =
figureElement
|> Dom.Element.appendChild
( args.text
|> Dom.Element.textWrapper "figcaption"
|> Dom.Element.withAttributes
[ "id"
|> Dom.Property.string
( args.id
|> Basics.toString
|> String.append "caption-"
)
]
)
|> Dom.Element.addAttribute
( "aria-labelledby"
|> Dom.Attribute.string
( args.id
|> Basics.toString
|> String.append "caption-"
)
)
| elm |
[
{
"context": "Info =\n E.object\n [ ( \"name\", E.string \"Tom\" )\n , ( \"age\", E.int 42 )\n ]\n\n\nupda",
"end": 1119,
"score": 0.9937701821,
"start": 1116,
"tag": "NAME",
"value": "Tom"
}
] | examples/dl_elm/src/atmpt1.elm | wilspi/realm | 8 | port module Main exposing (main)
import Browser
import Html exposing (Html, pre, text)
import Http
import Json.Decode as JD exposing (Decoder, field, int, map2, string)
import Json.Encode as E
-- MAIN
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
decoder : JD.Decoder Flag
decoder =
map2 Flag
(field "i" int)
(field "flag_s" string)
-- MODEL
type Mode
= Failure
| Loading
| Success String
type alias Model =
{ mode : Mode
, flag_i : Int
, flag_s : String
}
type alias Flag =
{ i : Int
, s : String
}
port hello : E.Value -> Cmd msg
init : Flag -> ( Model, Cmd Msg )
init flag =
( { mode = Loading
, flag_i = flag.i
, flag_s = flag.s
}
, Http.get
{ url = "https://elm-lang.org/assets/public-opinion.txt"
, expect = Http.expectString GotText
}
)
-- UPDATE
type Msg
= GotText (Result Http.Error String)
myInfo : E.Value
myInfo =
E.object
[ ( "name", E.string "Tom" )
, ( "age", E.int 42 )
]
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
GotText result ->
case result of
Ok fullText ->
( { model | mode = Success fullText }, hello myInfo )
Err _ ->
( { model | mode = Failure }, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
view : Model -> Html Msg
view model =
case model.mode of
Failure ->
text "I was unable to load your book."
Loading ->
text ("Loading..." ++ model.flag_s ++ String.fromInt model.flag_i)
Success fullText ->
pre [] [ text fullText ]
| 20881 | port module Main exposing (main)
import Browser
import Html exposing (Html, pre, text)
import Http
import Json.Decode as JD exposing (Decoder, field, int, map2, string)
import Json.Encode as E
-- MAIN
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
decoder : JD.Decoder Flag
decoder =
map2 Flag
(field "i" int)
(field "flag_s" string)
-- MODEL
type Mode
= Failure
| Loading
| Success String
type alias Model =
{ mode : Mode
, flag_i : Int
, flag_s : String
}
type alias Flag =
{ i : Int
, s : String
}
port hello : E.Value -> Cmd msg
init : Flag -> ( Model, Cmd Msg )
init flag =
( { mode = Loading
, flag_i = flag.i
, flag_s = flag.s
}
, Http.get
{ url = "https://elm-lang.org/assets/public-opinion.txt"
, expect = Http.expectString GotText
}
)
-- UPDATE
type Msg
= GotText (Result Http.Error String)
myInfo : E.Value
myInfo =
E.object
[ ( "name", E.string "<NAME>" )
, ( "age", E.int 42 )
]
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
GotText result ->
case result of
Ok fullText ->
( { model | mode = Success fullText }, hello myInfo )
Err _ ->
( { model | mode = Failure }, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
view : Model -> Html Msg
view model =
case model.mode of
Failure ->
text "I was unable to load your book."
Loading ->
text ("Loading..." ++ model.flag_s ++ String.fromInt model.flag_i)
Success fullText ->
pre [] [ text fullText ]
| true | port module Main exposing (main)
import Browser
import Html exposing (Html, pre, text)
import Http
import Json.Decode as JD exposing (Decoder, field, int, map2, string)
import Json.Encode as E
-- MAIN
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
decoder : JD.Decoder Flag
decoder =
map2 Flag
(field "i" int)
(field "flag_s" string)
-- MODEL
type Mode
= Failure
| Loading
| Success String
type alias Model =
{ mode : Mode
, flag_i : Int
, flag_s : String
}
type alias Flag =
{ i : Int
, s : String
}
port hello : E.Value -> Cmd msg
init : Flag -> ( Model, Cmd Msg )
init flag =
( { mode = Loading
, flag_i = flag.i
, flag_s = flag.s
}
, Http.get
{ url = "https://elm-lang.org/assets/public-opinion.txt"
, expect = Http.expectString GotText
}
)
-- UPDATE
type Msg
= GotText (Result Http.Error String)
myInfo : E.Value
myInfo =
E.object
[ ( "name", E.string "PI:NAME:<NAME>END_PI" )
, ( "age", E.int 42 )
]
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
GotText result ->
case result of
Ok fullText ->
( { model | mode = Success fullText }, hello myInfo )
Err _ ->
( { model | mode = Failure }, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
view : Model -> Html Msg
view model =
case model.mode of
Failure ->
text "I was unable to load your book."
Loading ->
text ("Loading..." ++ model.flag_s ++ String.fromInt model.flag_i)
Success fullText ->
pre [] [ text fullText ]
| elm |
[
{
"context": "elm\n-- A demonstration of the Graphing library\n\n-- C. Moresco (moresco.cm@gmail.com)\n\nmodule ImpulseDemo where\n",
"end": 76,
"score": 0.9998283386,
"start": 66,
"tag": "NAME",
"value": "C. Moresco"
},
{
"context": "nstration of the Graphing library\n\n-- C. Moresco (moresco.cm@gmail.com)\n\nmodule ImpulseDemo where\n\nimport Graphing expos",
"end": 98,
"score": 0.9999331236,
"start": 78,
"tag": "EMAIL",
"value": "moresco.cm@gmail.com"
}
] | ImpulseDemo.elm | catherinemoresco/elm-fourier-tutorial | 1 | -- ImpulseDemo.elm
-- A demonstration of the Graphing library
-- C. Moresco (moresco.cm@gmail.com)
module ImpulseDemo where
import Graphing exposing (graph, defaultGraph, defaultPlot, PlotAttributes)
import Svg
import Signal
import Time
import Mouse
import Json.Decode as Json
--import Svg.Attributes exposing (..)
import Html.Attributes exposing (..)
import Html exposing (Html)
import Html.Events as Events
data : Signal Graphing.ToPlot
data = Signal.map Graphing.wrapData mouseCoordData
function : Signal Graphing.ToPlot
function = Signal.map Graphing.wrapFunc <|
let sinFromFreqSpace (x, y) = (\z -> y * sin (x * pi * z)) in
Signal.map (List.foldr (addFunc) (\_ -> 0 ))
<| Signal.map (List.map sinFromFreqSpace) mouseCoordData
dataList : List (Float, Float)
dataList = List.concat <| List.map2 (\x y -> [x, y])
(List.map (\ x-> (x, abs <| (4/pi)/x)) <| List.map (\x -> 2*x - 1) [1..10])
(List.map (\x -> (x, 0)) <| List.map (\x -> 2*x) [1..10])
mouseCoordData : Signal (List (Float, Float))
mouseCoordData =
Signal.foldp (updateData graphStyle) dataList
<| Signal.filterMap filterNothing (-1, -1) maybeMouse
filterNothing : (Bool, (Float, Float)) -> Maybe (Float, Float)
filterNothing (a, coord) = case a of
True -> Just coord
False -> Nothing
maybeMouse : Signal (Bool, (Float, Float))
maybeMouse =
Signal.map2 (,) Mouse.isDown
<| Signal.map (\(x, y) -> (toFloat x, toFloat y)) Mouse.position
getSector : (Float, Float) -> Graphing.GraphAttributes -> Maybe Int
getSector (x, y) ga =
let margin = toFloat ga.margin
width = toFloat (ga.width - 2 * ga.margin)
height = toFloat ga.height
_ = Debug.log "" x
in
if x < margin then Nothing
else if x > width + margin + 15then Nothing
else if y < margin then Nothing
else if y > height + margin then Nothing
else let sectorSize = (width/(toFloat <| List.length dataList)) in
Just <| (floor <| (x - margin - 15)/sectorSize - 0.5)
getYValue : (Float, Float) -> Graphing.GraphAttributes -> Maybe Float
getYValue (x, y) ga =
let margin = toFloat ga.margin
width = toFloat ga.width
height = toFloat ga.height
(ymin, ymax) = ga.yInterval
in
if y < margin then Nothing
else if y > height + margin then Nothing
else Just (lerp (height + margin) y margin ymin ymax)
updateData : Graphing.GraphAttributes -> (Float, Float) -> List (Float, Float) -> List (Float, Float)
updateData ga mousePos data =
let foo (sector, yval) data =
case data of
[] -> []
x::xs -> if sector == 0 then (fst x, yval) :: xs
else x :: (foo (sector - 1, yval) xs)
in
case (getSector mousePos ga, getYValue mousePos ga) of
(Nothing, _) -> data
(_, Nothing ) -> data
(Just sector, Just yval) -> foo (sector, yval) data
graphStyle : Graphing.GraphAttributes
graphStyle = { defaultGraph | width=800,
height=200,
yInterval=(0, (4/pi)*1.5),
xInterval=(0, 20),
margin=25,
axisColor="#000",
xTicksEvery=1}
graphStyleSin : Graphing.GraphAttributes
graphStyleSin = { defaultGraph | width=800,
height=200,
yInterval=(-10, 10),
xInterval=(0, 4),
margin=25,
axisColor="#000",
yTicksEvery=10}
main : Signal Html
main = Signal.map (Html.div []) <| combine
[ freq
, Signal.constant <| Html.div [class "spacer"] []
, sinusoid
]
freq : Signal Html
freq = Signal.map (Html.div [class "white shadow"] ) <| combine
[Signal.constant <| Html.div [class "spacer"] []
, Signal.constant <| Html.div [class "centered header-font"] [Html.text "Frequency Domain Representation"]
, Signal.map (\x -> graph [(x, {defaultPlot | strokeColor="#999", dotColor="#ee2560"})] graphStyle) <| data]
sinusoid : Signal Html
sinusoid = Signal.map (Html.div [class "white shadow"] ) <| combine
[Signal.constant <| Html.div [class "spacer"] []
,Signal.constant <| Html.div [class "centered header-font"] [Html.text "Sinusoidal Signal"]
, Signal.map (\x -> graph [(x, {defaultPlot | strokeColor="#ee2560"})] graphStyleSin) <| function
]
lerp : Float -> Float -> Float -> Float -> Float -> Float
lerp x0 x x1 y0 y1 =
y0 + (y1 - y0)*((x - x0)/(x1 - x0))
addFunc : (Float->Float) -> (Float->Float) -> (Float->Float)
addFunc x y = (\z -> x z + y z)
{-| This was originally part of the signal library, then it wasn't...then it was added again? Not sure.
I got this from https://groups.google.com/forum/#!topic/elm-discuss/CVRhrF4Wn7k. -}
combine : List (Signal a) -> Signal (List a)
combine l = List.foldr (Signal.map2 (\x y -> [x] ++ y)) (Signal.constant []) l
| 47704 | -- ImpulseDemo.elm
-- A demonstration of the Graphing library
-- <NAME> (<EMAIL>)
module ImpulseDemo where
import Graphing exposing (graph, defaultGraph, defaultPlot, PlotAttributes)
import Svg
import Signal
import Time
import Mouse
import Json.Decode as Json
--import Svg.Attributes exposing (..)
import Html.Attributes exposing (..)
import Html exposing (Html)
import Html.Events as Events
data : Signal Graphing.ToPlot
data = Signal.map Graphing.wrapData mouseCoordData
function : Signal Graphing.ToPlot
function = Signal.map Graphing.wrapFunc <|
let sinFromFreqSpace (x, y) = (\z -> y * sin (x * pi * z)) in
Signal.map (List.foldr (addFunc) (\_ -> 0 ))
<| Signal.map (List.map sinFromFreqSpace) mouseCoordData
dataList : List (Float, Float)
dataList = List.concat <| List.map2 (\x y -> [x, y])
(List.map (\ x-> (x, abs <| (4/pi)/x)) <| List.map (\x -> 2*x - 1) [1..10])
(List.map (\x -> (x, 0)) <| List.map (\x -> 2*x) [1..10])
mouseCoordData : Signal (List (Float, Float))
mouseCoordData =
Signal.foldp (updateData graphStyle) dataList
<| Signal.filterMap filterNothing (-1, -1) maybeMouse
filterNothing : (Bool, (Float, Float)) -> Maybe (Float, Float)
filterNothing (a, coord) = case a of
True -> Just coord
False -> Nothing
maybeMouse : Signal (Bool, (Float, Float))
maybeMouse =
Signal.map2 (,) Mouse.isDown
<| Signal.map (\(x, y) -> (toFloat x, toFloat y)) Mouse.position
getSector : (Float, Float) -> Graphing.GraphAttributes -> Maybe Int
getSector (x, y) ga =
let margin = toFloat ga.margin
width = toFloat (ga.width - 2 * ga.margin)
height = toFloat ga.height
_ = Debug.log "" x
in
if x < margin then Nothing
else if x > width + margin + 15then Nothing
else if y < margin then Nothing
else if y > height + margin then Nothing
else let sectorSize = (width/(toFloat <| List.length dataList)) in
Just <| (floor <| (x - margin - 15)/sectorSize - 0.5)
getYValue : (Float, Float) -> Graphing.GraphAttributes -> Maybe Float
getYValue (x, y) ga =
let margin = toFloat ga.margin
width = toFloat ga.width
height = toFloat ga.height
(ymin, ymax) = ga.yInterval
in
if y < margin then Nothing
else if y > height + margin then Nothing
else Just (lerp (height + margin) y margin ymin ymax)
updateData : Graphing.GraphAttributes -> (Float, Float) -> List (Float, Float) -> List (Float, Float)
updateData ga mousePos data =
let foo (sector, yval) data =
case data of
[] -> []
x::xs -> if sector == 0 then (fst x, yval) :: xs
else x :: (foo (sector - 1, yval) xs)
in
case (getSector mousePos ga, getYValue mousePos ga) of
(Nothing, _) -> data
(_, Nothing ) -> data
(Just sector, Just yval) -> foo (sector, yval) data
graphStyle : Graphing.GraphAttributes
graphStyle = { defaultGraph | width=800,
height=200,
yInterval=(0, (4/pi)*1.5),
xInterval=(0, 20),
margin=25,
axisColor="#000",
xTicksEvery=1}
graphStyleSin : Graphing.GraphAttributes
graphStyleSin = { defaultGraph | width=800,
height=200,
yInterval=(-10, 10),
xInterval=(0, 4),
margin=25,
axisColor="#000",
yTicksEvery=10}
main : Signal Html
main = Signal.map (Html.div []) <| combine
[ freq
, Signal.constant <| Html.div [class "spacer"] []
, sinusoid
]
freq : Signal Html
freq = Signal.map (Html.div [class "white shadow"] ) <| combine
[Signal.constant <| Html.div [class "spacer"] []
, Signal.constant <| Html.div [class "centered header-font"] [Html.text "Frequency Domain Representation"]
, Signal.map (\x -> graph [(x, {defaultPlot | strokeColor="#999", dotColor="#ee2560"})] graphStyle) <| data]
sinusoid : Signal Html
sinusoid = Signal.map (Html.div [class "white shadow"] ) <| combine
[Signal.constant <| Html.div [class "spacer"] []
,Signal.constant <| Html.div [class "centered header-font"] [Html.text "Sinusoidal Signal"]
, Signal.map (\x -> graph [(x, {defaultPlot | strokeColor="#ee2560"})] graphStyleSin) <| function
]
lerp : Float -> Float -> Float -> Float -> Float -> Float
lerp x0 x x1 y0 y1 =
y0 + (y1 - y0)*((x - x0)/(x1 - x0))
addFunc : (Float->Float) -> (Float->Float) -> (Float->Float)
addFunc x y = (\z -> x z + y z)
{-| This was originally part of the signal library, then it wasn't...then it was added again? Not sure.
I got this from https://groups.google.com/forum/#!topic/elm-discuss/CVRhrF4Wn7k. -}
combine : List (Signal a) -> Signal (List a)
combine l = List.foldr (Signal.map2 (\x y -> [x] ++ y)) (Signal.constant []) l
| true | -- ImpulseDemo.elm
-- A demonstration of the Graphing library
-- PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
module ImpulseDemo where
import Graphing exposing (graph, defaultGraph, defaultPlot, PlotAttributes)
import Svg
import Signal
import Time
import Mouse
import Json.Decode as Json
--import Svg.Attributes exposing (..)
import Html.Attributes exposing (..)
import Html exposing (Html)
import Html.Events as Events
data : Signal Graphing.ToPlot
data = Signal.map Graphing.wrapData mouseCoordData
function : Signal Graphing.ToPlot
function = Signal.map Graphing.wrapFunc <|
let sinFromFreqSpace (x, y) = (\z -> y * sin (x * pi * z)) in
Signal.map (List.foldr (addFunc) (\_ -> 0 ))
<| Signal.map (List.map sinFromFreqSpace) mouseCoordData
dataList : List (Float, Float)
dataList = List.concat <| List.map2 (\x y -> [x, y])
(List.map (\ x-> (x, abs <| (4/pi)/x)) <| List.map (\x -> 2*x - 1) [1..10])
(List.map (\x -> (x, 0)) <| List.map (\x -> 2*x) [1..10])
mouseCoordData : Signal (List (Float, Float))
mouseCoordData =
Signal.foldp (updateData graphStyle) dataList
<| Signal.filterMap filterNothing (-1, -1) maybeMouse
filterNothing : (Bool, (Float, Float)) -> Maybe (Float, Float)
filterNothing (a, coord) = case a of
True -> Just coord
False -> Nothing
maybeMouse : Signal (Bool, (Float, Float))
maybeMouse =
Signal.map2 (,) Mouse.isDown
<| Signal.map (\(x, y) -> (toFloat x, toFloat y)) Mouse.position
getSector : (Float, Float) -> Graphing.GraphAttributes -> Maybe Int
getSector (x, y) ga =
let margin = toFloat ga.margin
width = toFloat (ga.width - 2 * ga.margin)
height = toFloat ga.height
_ = Debug.log "" x
in
if x < margin then Nothing
else if x > width + margin + 15then Nothing
else if y < margin then Nothing
else if y > height + margin then Nothing
else let sectorSize = (width/(toFloat <| List.length dataList)) in
Just <| (floor <| (x - margin - 15)/sectorSize - 0.5)
getYValue : (Float, Float) -> Graphing.GraphAttributes -> Maybe Float
getYValue (x, y) ga =
let margin = toFloat ga.margin
width = toFloat ga.width
height = toFloat ga.height
(ymin, ymax) = ga.yInterval
in
if y < margin then Nothing
else if y > height + margin then Nothing
else Just (lerp (height + margin) y margin ymin ymax)
updateData : Graphing.GraphAttributes -> (Float, Float) -> List (Float, Float) -> List (Float, Float)
updateData ga mousePos data =
let foo (sector, yval) data =
case data of
[] -> []
x::xs -> if sector == 0 then (fst x, yval) :: xs
else x :: (foo (sector - 1, yval) xs)
in
case (getSector mousePos ga, getYValue mousePos ga) of
(Nothing, _) -> data
(_, Nothing ) -> data
(Just sector, Just yval) -> foo (sector, yval) data
graphStyle : Graphing.GraphAttributes
graphStyle = { defaultGraph | width=800,
height=200,
yInterval=(0, (4/pi)*1.5),
xInterval=(0, 20),
margin=25,
axisColor="#000",
xTicksEvery=1}
graphStyleSin : Graphing.GraphAttributes
graphStyleSin = { defaultGraph | width=800,
height=200,
yInterval=(-10, 10),
xInterval=(0, 4),
margin=25,
axisColor="#000",
yTicksEvery=10}
main : Signal Html
main = Signal.map (Html.div []) <| combine
[ freq
, Signal.constant <| Html.div [class "spacer"] []
, sinusoid
]
freq : Signal Html
freq = Signal.map (Html.div [class "white shadow"] ) <| combine
[Signal.constant <| Html.div [class "spacer"] []
, Signal.constant <| Html.div [class "centered header-font"] [Html.text "Frequency Domain Representation"]
, Signal.map (\x -> graph [(x, {defaultPlot | strokeColor="#999", dotColor="#ee2560"})] graphStyle) <| data]
sinusoid : Signal Html
sinusoid = Signal.map (Html.div [class "white shadow"] ) <| combine
[Signal.constant <| Html.div [class "spacer"] []
,Signal.constant <| Html.div [class "centered header-font"] [Html.text "Sinusoidal Signal"]
, Signal.map (\x -> graph [(x, {defaultPlot | strokeColor="#ee2560"})] graphStyleSin) <| function
]
lerp : Float -> Float -> Float -> Float -> Float -> Float
lerp x0 x x1 y0 y1 =
y0 + (y1 - y0)*((x - x0)/(x1 - x0))
addFunc : (Float->Float) -> (Float->Float) -> (Float->Float)
addFunc x y = (\z -> x z + y z)
{-| This was originally part of the signal library, then it wasn't...then it was added again? Not sure.
I got this from https://groups.google.com/forum/#!topic/elm-discuss/CVRhrF4Wn7k. -}
combine : List (Signal a) -> Signal (List a)
combine l = List.foldr (Signal.map2 (\x y -> [x] ++ y)) (Signal.constant []) l
| elm |
[
{
"context": " monthShort\r\n@docs monthName\r\n\r\nCopyright (c) 2016 Robin Luiten\r\n-}\r\n\r\n\r\nimport Date exposing (Day (..), Month (.",
"end": 180,
"score": 0.9998556376,
"start": 168,
"tag": "NAME",
"value": "Robin Luiten"
}
] | src/Date/I18n/I_en_us.elm | altworx/elm-date-extra | 0 | module Date.I18n.I_en_us where
{-| English values for day and month names.
@docs dayShort
@docs dayName
@docs monthShort
@docs monthName
Copyright (c) 2016 Robin Luiten
-}
import Date exposing (Day (..), Month (..))
{-| Day short name. -}
dayShort : Day -> String
dayShort day =
case day of
Mon -> "Mon"
Tue -> "Tue"
Wed -> "Wed"
Thu -> "Thu"
Fri -> "Fri"
Sat -> "Sat"
Sun -> "Sun"
{-| Day full name. -}
dayName : Day -> String
dayName day =
case day of
Mon -> "Monday"
Tue -> "Tuesday"
Wed -> "Wednesday"
Thu -> "Thursday"
Fri -> "Friday"
Sat -> "Saturday"
Sun -> "Sunday"
{-| Month short name. -}
monthShort : Month -> String
monthShort month =
case month of
Jan -> "Jan"
Feb -> "Feb"
Mar -> "Mar"
Apr -> "Apr"
May -> "May"
Jun -> "Jun"
Jul -> "Jul"
Aug -> "Aug"
Sep -> "Sep"
Oct -> "Oct"
Nov -> "Nov"
Dec -> "Dec"
{-| Month full name. -}
monthName : Month -> String
monthName month =
case month of
Jan -> "January"
Feb -> "February"
Mar -> "March"
Apr -> "April"
May -> "May"
Jun -> "June"
Jul -> "July"
Aug -> "August"
Sep -> "September"
Oct -> "October"
Nov -> "November"
Dec -> "December"
| 58138 | module Date.I18n.I_en_us where
{-| English values for day and month names.
@docs dayShort
@docs dayName
@docs monthShort
@docs monthName
Copyright (c) 2016 <NAME>
-}
import Date exposing (Day (..), Month (..))
{-| Day short name. -}
dayShort : Day -> String
dayShort day =
case day of
Mon -> "Mon"
Tue -> "Tue"
Wed -> "Wed"
Thu -> "Thu"
Fri -> "Fri"
Sat -> "Sat"
Sun -> "Sun"
{-| Day full name. -}
dayName : Day -> String
dayName day =
case day of
Mon -> "Monday"
Tue -> "Tuesday"
Wed -> "Wednesday"
Thu -> "Thursday"
Fri -> "Friday"
Sat -> "Saturday"
Sun -> "Sunday"
{-| Month short name. -}
monthShort : Month -> String
monthShort month =
case month of
Jan -> "Jan"
Feb -> "Feb"
Mar -> "Mar"
Apr -> "Apr"
May -> "May"
Jun -> "Jun"
Jul -> "Jul"
Aug -> "Aug"
Sep -> "Sep"
Oct -> "Oct"
Nov -> "Nov"
Dec -> "Dec"
{-| Month full name. -}
monthName : Month -> String
monthName month =
case month of
Jan -> "January"
Feb -> "February"
Mar -> "March"
Apr -> "April"
May -> "May"
Jun -> "June"
Jul -> "July"
Aug -> "August"
Sep -> "September"
Oct -> "October"
Nov -> "November"
Dec -> "December"
| true | module Date.I18n.I_en_us where
{-| English values for day and month names.
@docs dayShort
@docs dayName
@docs monthShort
@docs monthName
Copyright (c) 2016 PI:NAME:<NAME>END_PI
-}
import Date exposing (Day (..), Month (..))
{-| Day short name. -}
dayShort : Day -> String
dayShort day =
case day of
Mon -> "Mon"
Tue -> "Tue"
Wed -> "Wed"
Thu -> "Thu"
Fri -> "Fri"
Sat -> "Sat"
Sun -> "Sun"
{-| Day full name. -}
dayName : Day -> String
dayName day =
case day of
Mon -> "Monday"
Tue -> "Tuesday"
Wed -> "Wednesday"
Thu -> "Thursday"
Fri -> "Friday"
Sat -> "Saturday"
Sun -> "Sunday"
{-| Month short name. -}
monthShort : Month -> String
monthShort month =
case month of
Jan -> "Jan"
Feb -> "Feb"
Mar -> "Mar"
Apr -> "Apr"
May -> "May"
Jun -> "Jun"
Jul -> "Jul"
Aug -> "Aug"
Sep -> "Sep"
Oct -> "Oct"
Nov -> "Nov"
Dec -> "Dec"
{-| Month full name. -}
monthName : Month -> String
monthName month =
case month of
Jan -> "January"
Feb -> "February"
Mar -> "March"
Apr -> "April"
May -> "May"
Jun -> "June"
Jul -> "July"
Aug -> "August"
Sep -> "September"
Oct -> "October"
Nov -> "November"
Dec -> "December"
| elm |
[
{
"context": "\n\n OpenAPI spec version: 3.2.0-pre.0\n Contact: opensource@shinesolutions.com\n\n NOTE: This file is auto generated by the open",
"end": 202,
"score": 0.9999239445,
"start": 173,
"tag": "EMAIL",
"value": "opensource@shinesolutions.com"
},
{
"context": "d by the openapi-generator.\n https://github.com/openapitools/openapi-generator.git\n Do not edit this file ma",
"end": 301,
"score": 0.9996269345,
"start": 289,
"tag": "USERNAME",
"value": "openapitools"
}
] | clients/elm/generated/src/Request/Sling.elm | hoomaan-kh/swagger-aem | 39 | {-
Adobe Experience Manager (AEM) API
Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API
OpenAPI spec version: 3.2.0-pre.0
Contact: opensource@shinesolutions.com
NOTE: This file is auto generated by the openapi-generator.
https://github.com/openapitools/openapi-generator.git
Do not edit this file manually.
-}
module Request.Sling exposing (deleteAgent, deleteNode, getAgent, getAgents, getAuthorizableKeystore, getKeystore, getNode, getPackage, getPackageFilter, getQuery, getTruststore, getTruststoreInfo, postAgent, postAuthorizableKeystore, postAuthorizables, postConfigAdobeGraniteSamlAuthenticationHandler, postConfigApacheFelixJettyBasedHttpService, postConfigApacheHttpComponentsProxyConfiguration, postConfigApacheSlingDavExServlet, postConfigApacheSlingGetServlet, postConfigApacheSlingReferrerFilter, postNode, postNodeRw, postPath, postQuery, postTreeActivation, postTruststore, postTruststorePKCS12)
import Data.KeystoreInfo exposing (KeystoreInfo, keystoreInfoDecoder)
import Data.TruststoreInfo exposing (TruststoreInfo, truststoreInfoDecoder)
import Dict
import Http
import Json.Decode as Decode
basePath : String
basePath =
"http://localhost"
deleteAgent : String -> String -> Http.Request ()
deleteAgent runmode name =
{ method = "DELETE"
, url = basePath ++ "/etc/replication/agents." ++ runmode ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
deleteNode : String -> String -> Http.Request ()
deleteNode path name =
{ method = "DELETE"
, url = basePath ++ "/" ++ path ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getAgent : String -> String -> Http.Request ()
getAgent runmode name =
{ method = "GET"
, url = basePath ++ "/etc/replication/agents." ++ runmode ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getAgents : String -> Http.Request String
getAgents runmode =
{ method = "GET"
, url = basePath ++ "/etc/replication/agents." ++ runmode ++ ".-1.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getAuthorizableKeystore : String -> String -> Http.Request KeystoreInfo
getAuthorizableKeystore intermediatePath authorizableId =
{ method = "GET"
, url = basePath ++ "/" ++ intermediatePath ++ "/" ++ authorizableId ++ ".ks.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson keystoreInfoDecoder
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getKeystore : String -> String -> Http.Request String
getKeystore intermediatePath authorizableId =
{ method = "GET"
, url = basePath ++ "/" ++ intermediatePath ++ "/" ++ authorizableId ++ "/keystore/store.p12"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getNode : String -> String -> Http.Request ()
getNode path name =
{ method = "GET"
, url = basePath ++ "/" ++ path ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getPackage : String -> String -> String -> Http.Request String
getPackage group name version =
{ method = "GET"
, url = basePath ++ "/etc/packages/" ++ group ++ "/" ++ name ++ "-" ++ version ++ ".zip"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getPackageFilter : String -> String -> String -> Http.Request String
getPackageFilter group name version =
{ method = "GET"
, url = basePath ++ "/etc/packages/" ++ group ++ "/" ++ name ++ "-" ++ version ++ ".zip/jcr:content/vlt:definition/filter.tidy.2.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getQuery : Http.Request String
getQuery =
{ method = "GET"
, url = basePath ++ "/bin/querybuilder.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getTruststore : Http.Request String
getTruststore =
{ method = "GET"
, url = basePath ++ "/etc/truststore/truststore.p12"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getTruststoreInfo : Http.Request TruststoreInfo
getTruststoreInfo =
{ method = "GET"
, url = basePath ++ "/libs/granite/security/truststore.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson truststoreInfoDecoder
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postAgent : String -> String -> Http.Request ()
postAgent runmode name =
{ method = "POST"
, url = basePath ++ "/etc/replication/agents." ++ runmode ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postAuthorizableKeystore : String -> String -> Http.Request KeystoreInfo
postAuthorizableKeystore intermediatePath authorizableId =
{ method = "POST"
, url = basePath ++ "/" ++ intermediatePath ++ "/" ++ authorizableId ++ ".ks.html"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson keystoreInfoDecoder
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postAuthorizables : Http.Request String
postAuthorizables =
{ method = "POST"
, url = basePath ++ "/libs/granite/security/post/authorizables"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigAdobeGraniteSamlAuthenticationHandler : Http.Request ()
postConfigAdobeGraniteSamlAuthenticationHandler =
{ method = "POST"
, url = basePath ++ "/apps/system/config/com.adobe.granite.auth.saml.SamlAuthenticationHandler.config"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheFelixJettyBasedHttpService : Http.Request ()
postConfigApacheFelixJettyBasedHttpService =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.felix.http"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheHttpComponentsProxyConfiguration : Http.Request ()
postConfigApacheHttpComponentsProxyConfiguration =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.http.proxyconfigurator.config"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheSlingDavExServlet : Http.Request ()
postConfigApacheSlingDavExServlet =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.sling.jcr.davex.impl.servlets.SlingDavExServlet"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheSlingGetServlet : Http.Request ()
postConfigApacheSlingGetServlet =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.sling.servlets.get.DefaultGetServlet"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheSlingReferrerFilter : Http.Request ()
postConfigApacheSlingReferrerFilter =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.sling.security.impl.ReferrerFilter"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postNode : String -> String -> Http.Request ()
postNode path name =
{ method = "POST"
, url = basePath ++ "/" ++ path ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postNodeRw : String -> String -> Http.Request ()
postNodeRw path name =
{ method = "POST"
, url = basePath ++ "/" ++ path ++ "/" ++ name ++ ".rw.html"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postPath : String -> Http.Request ()
postPath path =
{ method = "POST"
, url = basePath ++ "/" ++ path ++ "/"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postQuery : Http.Request String
postQuery =
{ method = "POST"
, url = basePath ++ "/bin/querybuilder.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postTreeActivation : Http.Request ()
postTreeActivation =
{ method = "POST"
, url = basePath ++ "/etc/replication/treeactivation.html"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postTruststore : Http.Request String
postTruststore =
{ method = "POST"
, url = basePath ++ "/libs/granite/security/post/truststore"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postTruststorePKCS12 : Http.Request String
postTruststorePKCS12 =
{ method = "POST"
, url = basePath ++ "/etc/truststore"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
| 24116 | {-
Adobe Experience Manager (AEM) API
Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API
OpenAPI spec version: 3.2.0-pre.0
Contact: <EMAIL>
NOTE: This file is auto generated by the openapi-generator.
https://github.com/openapitools/openapi-generator.git
Do not edit this file manually.
-}
module Request.Sling exposing (deleteAgent, deleteNode, getAgent, getAgents, getAuthorizableKeystore, getKeystore, getNode, getPackage, getPackageFilter, getQuery, getTruststore, getTruststoreInfo, postAgent, postAuthorizableKeystore, postAuthorizables, postConfigAdobeGraniteSamlAuthenticationHandler, postConfigApacheFelixJettyBasedHttpService, postConfigApacheHttpComponentsProxyConfiguration, postConfigApacheSlingDavExServlet, postConfigApacheSlingGetServlet, postConfigApacheSlingReferrerFilter, postNode, postNodeRw, postPath, postQuery, postTreeActivation, postTruststore, postTruststorePKCS12)
import Data.KeystoreInfo exposing (KeystoreInfo, keystoreInfoDecoder)
import Data.TruststoreInfo exposing (TruststoreInfo, truststoreInfoDecoder)
import Dict
import Http
import Json.Decode as Decode
basePath : String
basePath =
"http://localhost"
deleteAgent : String -> String -> Http.Request ()
deleteAgent runmode name =
{ method = "DELETE"
, url = basePath ++ "/etc/replication/agents." ++ runmode ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
deleteNode : String -> String -> Http.Request ()
deleteNode path name =
{ method = "DELETE"
, url = basePath ++ "/" ++ path ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getAgent : String -> String -> Http.Request ()
getAgent runmode name =
{ method = "GET"
, url = basePath ++ "/etc/replication/agents." ++ runmode ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getAgents : String -> Http.Request String
getAgents runmode =
{ method = "GET"
, url = basePath ++ "/etc/replication/agents." ++ runmode ++ ".-1.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getAuthorizableKeystore : String -> String -> Http.Request KeystoreInfo
getAuthorizableKeystore intermediatePath authorizableId =
{ method = "GET"
, url = basePath ++ "/" ++ intermediatePath ++ "/" ++ authorizableId ++ ".ks.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson keystoreInfoDecoder
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getKeystore : String -> String -> Http.Request String
getKeystore intermediatePath authorizableId =
{ method = "GET"
, url = basePath ++ "/" ++ intermediatePath ++ "/" ++ authorizableId ++ "/keystore/store.p12"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getNode : String -> String -> Http.Request ()
getNode path name =
{ method = "GET"
, url = basePath ++ "/" ++ path ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getPackage : String -> String -> String -> Http.Request String
getPackage group name version =
{ method = "GET"
, url = basePath ++ "/etc/packages/" ++ group ++ "/" ++ name ++ "-" ++ version ++ ".zip"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getPackageFilter : String -> String -> String -> Http.Request String
getPackageFilter group name version =
{ method = "GET"
, url = basePath ++ "/etc/packages/" ++ group ++ "/" ++ name ++ "-" ++ version ++ ".zip/jcr:content/vlt:definition/filter.tidy.2.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getQuery : Http.Request String
getQuery =
{ method = "GET"
, url = basePath ++ "/bin/querybuilder.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getTruststore : Http.Request String
getTruststore =
{ method = "GET"
, url = basePath ++ "/etc/truststore/truststore.p12"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getTruststoreInfo : Http.Request TruststoreInfo
getTruststoreInfo =
{ method = "GET"
, url = basePath ++ "/libs/granite/security/truststore.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson truststoreInfoDecoder
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postAgent : String -> String -> Http.Request ()
postAgent runmode name =
{ method = "POST"
, url = basePath ++ "/etc/replication/agents." ++ runmode ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postAuthorizableKeystore : String -> String -> Http.Request KeystoreInfo
postAuthorizableKeystore intermediatePath authorizableId =
{ method = "POST"
, url = basePath ++ "/" ++ intermediatePath ++ "/" ++ authorizableId ++ ".ks.html"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson keystoreInfoDecoder
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postAuthorizables : Http.Request String
postAuthorizables =
{ method = "POST"
, url = basePath ++ "/libs/granite/security/post/authorizables"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigAdobeGraniteSamlAuthenticationHandler : Http.Request ()
postConfigAdobeGraniteSamlAuthenticationHandler =
{ method = "POST"
, url = basePath ++ "/apps/system/config/com.adobe.granite.auth.saml.SamlAuthenticationHandler.config"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheFelixJettyBasedHttpService : Http.Request ()
postConfigApacheFelixJettyBasedHttpService =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.felix.http"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheHttpComponentsProxyConfiguration : Http.Request ()
postConfigApacheHttpComponentsProxyConfiguration =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.http.proxyconfigurator.config"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheSlingDavExServlet : Http.Request ()
postConfigApacheSlingDavExServlet =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.sling.jcr.davex.impl.servlets.SlingDavExServlet"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheSlingGetServlet : Http.Request ()
postConfigApacheSlingGetServlet =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.sling.servlets.get.DefaultGetServlet"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheSlingReferrerFilter : Http.Request ()
postConfigApacheSlingReferrerFilter =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.sling.security.impl.ReferrerFilter"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postNode : String -> String -> Http.Request ()
postNode path name =
{ method = "POST"
, url = basePath ++ "/" ++ path ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postNodeRw : String -> String -> Http.Request ()
postNodeRw path name =
{ method = "POST"
, url = basePath ++ "/" ++ path ++ "/" ++ name ++ ".rw.html"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postPath : String -> Http.Request ()
postPath path =
{ method = "POST"
, url = basePath ++ "/" ++ path ++ "/"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postQuery : Http.Request String
postQuery =
{ method = "POST"
, url = basePath ++ "/bin/querybuilder.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postTreeActivation : Http.Request ()
postTreeActivation =
{ method = "POST"
, url = basePath ++ "/etc/replication/treeactivation.html"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postTruststore : Http.Request String
postTruststore =
{ method = "POST"
, url = basePath ++ "/libs/granite/security/post/truststore"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postTruststorePKCS12 : Http.Request String
postTruststorePKCS12 =
{ method = "POST"
, url = basePath ++ "/etc/truststore"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
| true | {-
Adobe Experience Manager (AEM) API
Swagger AEM is an OpenAPI specification for Adobe Experience Manager (AEM) API
OpenAPI spec version: 3.2.0-pre.0
Contact: PI:EMAIL:<EMAIL>END_PI
NOTE: This file is auto generated by the openapi-generator.
https://github.com/openapitools/openapi-generator.git
Do not edit this file manually.
-}
module Request.Sling exposing (deleteAgent, deleteNode, getAgent, getAgents, getAuthorizableKeystore, getKeystore, getNode, getPackage, getPackageFilter, getQuery, getTruststore, getTruststoreInfo, postAgent, postAuthorizableKeystore, postAuthorizables, postConfigAdobeGraniteSamlAuthenticationHandler, postConfigApacheFelixJettyBasedHttpService, postConfigApacheHttpComponentsProxyConfiguration, postConfigApacheSlingDavExServlet, postConfigApacheSlingGetServlet, postConfigApacheSlingReferrerFilter, postNode, postNodeRw, postPath, postQuery, postTreeActivation, postTruststore, postTruststorePKCS12)
import Data.KeystoreInfo exposing (KeystoreInfo, keystoreInfoDecoder)
import Data.TruststoreInfo exposing (TruststoreInfo, truststoreInfoDecoder)
import Dict
import Http
import Json.Decode as Decode
basePath : String
basePath =
"http://localhost"
deleteAgent : String -> String -> Http.Request ()
deleteAgent runmode name =
{ method = "DELETE"
, url = basePath ++ "/etc/replication/agents." ++ runmode ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
deleteNode : String -> String -> Http.Request ()
deleteNode path name =
{ method = "DELETE"
, url = basePath ++ "/" ++ path ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getAgent : String -> String -> Http.Request ()
getAgent runmode name =
{ method = "GET"
, url = basePath ++ "/etc/replication/agents." ++ runmode ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getAgents : String -> Http.Request String
getAgents runmode =
{ method = "GET"
, url = basePath ++ "/etc/replication/agents." ++ runmode ++ ".-1.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getAuthorizableKeystore : String -> String -> Http.Request KeystoreInfo
getAuthorizableKeystore intermediatePath authorizableId =
{ method = "GET"
, url = basePath ++ "/" ++ intermediatePath ++ "/" ++ authorizableId ++ ".ks.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson keystoreInfoDecoder
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getKeystore : String -> String -> Http.Request String
getKeystore intermediatePath authorizableId =
{ method = "GET"
, url = basePath ++ "/" ++ intermediatePath ++ "/" ++ authorizableId ++ "/keystore/store.p12"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getNode : String -> String -> Http.Request ()
getNode path name =
{ method = "GET"
, url = basePath ++ "/" ++ path ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getPackage : String -> String -> String -> Http.Request String
getPackage group name version =
{ method = "GET"
, url = basePath ++ "/etc/packages/" ++ group ++ "/" ++ name ++ "-" ++ version ++ ".zip"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getPackageFilter : String -> String -> String -> Http.Request String
getPackageFilter group name version =
{ method = "GET"
, url = basePath ++ "/etc/packages/" ++ group ++ "/" ++ name ++ "-" ++ version ++ ".zip/jcr:content/vlt:definition/filter.tidy.2.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getQuery : Http.Request String
getQuery =
{ method = "GET"
, url = basePath ++ "/bin/querybuilder.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getTruststore : Http.Request String
getTruststore =
{ method = "GET"
, url = basePath ++ "/etc/truststore/truststore.p12"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
getTruststoreInfo : Http.Request TruststoreInfo
getTruststoreInfo =
{ method = "GET"
, url = basePath ++ "/libs/granite/security/truststore.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson truststoreInfoDecoder
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postAgent : String -> String -> Http.Request ()
postAgent runmode name =
{ method = "POST"
, url = basePath ++ "/etc/replication/agents." ++ runmode ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postAuthorizableKeystore : String -> String -> Http.Request KeystoreInfo
postAuthorizableKeystore intermediatePath authorizableId =
{ method = "POST"
, url = basePath ++ "/" ++ intermediatePath ++ "/" ++ authorizableId ++ ".ks.html"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson keystoreInfoDecoder
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postAuthorizables : Http.Request String
postAuthorizables =
{ method = "POST"
, url = basePath ++ "/libs/granite/security/post/authorizables"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigAdobeGraniteSamlAuthenticationHandler : Http.Request ()
postConfigAdobeGraniteSamlAuthenticationHandler =
{ method = "POST"
, url = basePath ++ "/apps/system/config/com.adobe.granite.auth.saml.SamlAuthenticationHandler.config"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheFelixJettyBasedHttpService : Http.Request ()
postConfigApacheFelixJettyBasedHttpService =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.felix.http"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheHttpComponentsProxyConfiguration : Http.Request ()
postConfigApacheHttpComponentsProxyConfiguration =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.http.proxyconfigurator.config"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheSlingDavExServlet : Http.Request ()
postConfigApacheSlingDavExServlet =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.sling.jcr.davex.impl.servlets.SlingDavExServlet"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheSlingGetServlet : Http.Request ()
postConfigApacheSlingGetServlet =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.sling.servlets.get.DefaultGetServlet"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postConfigApacheSlingReferrerFilter : Http.Request ()
postConfigApacheSlingReferrerFilter =
{ method = "POST"
, url = basePath ++ "/apps/system/config/org.apache.sling.security.impl.ReferrerFilter"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postNode : String -> String -> Http.Request ()
postNode path name =
{ method = "POST"
, url = basePath ++ "/" ++ path ++ "/" ++ name
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postNodeRw : String -> String -> Http.Request ()
postNodeRw path name =
{ method = "POST"
, url = basePath ++ "/" ++ path ++ "/" ++ name ++ ".rw.html"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postPath : String -> Http.Request ()
postPath path =
{ method = "POST"
, url = basePath ++ "/" ++ path ++ "/"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postQuery : Http.Request String
postQuery =
{ method = "POST"
, url = basePath ++ "/bin/querybuilder.json"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postTreeActivation : Http.Request ()
postTreeActivation =
{ method = "POST"
, url = basePath ++ "/etc/replication/treeactivation.html"
, headers = []
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postTruststore : Http.Request String
postTruststore =
{ method = "POST"
, url = basePath ++ "/libs/granite/security/post/truststore"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
postTruststorePKCS12 : Http.Request String
postTruststorePKCS12 =
{ method = "POST"
, url = basePath ++ "/etc/truststore"
, headers = []
, body = Http.emptyBody
, expect = Http.expectJson Decode.string
, timeout = Just 30000
, withCredentials = False
}
|> Http.request
| elm |
[
{
"context": "H \"Sfânta Elena\"\nSI \"Slovenia\"\nSJ \"Svalbard și Jan Mayen\"\nSK \"Slovacia\"\nSL \"Sierra Leone\"\nSM \"San Marino",
"end": 3447,
"score": 0.6208795309,
"start": 3444,
"tag": "NAME",
"value": "May"
},
{
"context": "Sint Maarten (partea franceză)\"\n MG -> \"Madagascar\"\n MH -> \"Insulele Marshall\"\n MK -> ",
"end": 8276,
"score": 0.9955229163,
"start": 8269,
"tag": "NAME",
"value": "agascar"
},
{
"context": "a Elena\"\n SI -> \"Slovenia\"\n SJ -> \"Svalbard și Jan Mayen\"\n SK -> \"Slovacia\"\n ",
"end": 9836,
"score": 0.5759358406,
"start": 9833,
"tag": "NAME",
"value": "val"
},
{
"context": " SI -> \"Slovenia\"\n SJ -> \"Svalbard și Jan Mayen\"\n SK -> \"Slovacia\"\n SL -> \"Sierra L",
"end": 9853,
"score": 0.8999307156,
"start": 9844,
"tag": "NAME",
"value": "Jan Mayen"
}
] | src/Iso3166/Romanian.elm | rl-king/elm-3166-country-codes | 1 | module Iso3166.Romanian exposing (toName)
-- Generated by 'generate/Main.hs' do not edit by hand
{-|
@docs toName
-}
import Iso3166 exposing (..)
{-| Name for `CountryCode` in Romanian.
```
AD "Andorra"
AE "Emiratele Arabe Unite"
AF "Afganistan"
AG "Antigua și Barbuda"
AI "Anguilla"
AL "Albania"
AM "Armenia"
AO "Angola"
AQ "Antarctica"
AR "Argentina"
AS "Samoa americană"
AT "Austria"
AU "Australia"
AW "Aruba"
AX "Insulele Åland"
AZ "Azerbaidjan"
BA "Bosnia și Herțegovina"
BB "Barbados"
BD "Bangladesh"
BE "Belgia"
BF "Burkina Faso"
BG "Bulgaria"
BH "Bahrain"
BI "Burundi"
BJ "Benin"
BL "Saint Barthélemy"
BM "Bermude"
BN "Brunei"
BO "Bolivia"
BQ "Insulele Bonaire, Sint Eustatius și Saba"
BR "Brazilia"
BS "Bahamas"
BT "Bhutan"
BV "Insula Bouvet"
BW "Botswana"
BY "Belarus"
BZ "Belize"
CA "Canada"
CC "Insulele Cocos"
CD "Republica Democrată Congo"
CF "Republica Centrafricană"
CG "Congo"
CH "Elveția"
CI "Coasta de Fildeș"
CK "Insulele Cook"
CL "Chile"
CM "Camerun"
CN "Republica Populară Chineză"
CO "Columbia"
CR "Costa Rica"
CU "Cuba"
CV "Republica Capului Verde"
CW "Curaçao"
CX "Insula Crăciunului"
CY "Cipru"
CZ "Cehia"
DE "Germania"
DJ "Djibouti"
DK "Danemarca"
DM "Dominica"
DO "Republica Dominicană"
DZ "Algeria"
EC "Ecuador"
EE "Estonia"
EG "Egipt"
EH "Sahara Occidentală"
ER "Eritreea"
ES "Spania"
ET "Etiopia"
FI "Finlanda"
FJ "Fiji"
FK "Insulele Falkland"
FM "Micronezia"
FO "Insulele Feroe"
FR "Franța"
GA "Gabon"
GB "Regatul Unit"
GD "Grenada"
GE "Georgia"
GF "Guiana Franceză"
GG "Guernsey"
GH "Ghana"
GI "Gibraltar"
GL "Groenlanda"
GM "Gambia"
GN "Guineea"
GP "Guadelupa"
GQ "Guineea Ecuatorială"
GR "Grecia"
GS "Georgia de Sud și Insulele Sandwich de Sud"
GT_ "Guatemala"
GU "Guam"
GW "Guineea-Bissau"
GY "Guyana"
HK "Hong Kong"
HM "Insula Heard și Insulele McDonald"
HN "Honduras"
HR "Croația"
HT "Haiti"
HU "Ungaria"
ID "Indonezia"
IE "Republica Irlanda"
IL "Israel"
IM "Insula Man"
IN "India"
IO "Teritoriul Britanic din Oceanul Indian"
IQ "Irak"
IR "Iran"
IS "Islanda"
IT "Italia"
JE "Insula Jersey"
JM "Jamaica"
JO "Iordania"
JP "Japonia"
KE "Kenya"
KG "Kârgâzstan"
KH "Cambodgia"
KI "Kiribati"
KM "Comore"
KN "Sfântul Kitts și Nevis"
KP "Coreea de Nord"
KR "Coreea de Sud"
KW "Kuweit"
KY "Insulele Cayman"
KZ "Kazahstan"
LA "Laos"
LB "Liban"
LC "Sfânta Lucia"
LI "Liechtenstein"
LK "Sri Lanka"
LR "Liberia"
LS "Lesotho"
LT_ "Lituania"
LU "Luxemburg"
LV "Letonia"
LY "Libia"
MA "Maroc"
MC "Monaco"
MD "Republica Moldova"
ME "Muntenegru"
MF "Sint Maarten (partea franceză)"
MG "Madagascar"
MH "Insulele Marshall"
MK "Republica Macedonia"
ML "Mali"
MM "Myanmar"
MN "Mongolia"
MO "Macao"
MP "Insulele Mariane de Nord"
MQ "Martinica"
MR "Mauritania"
MS "Montserrat"
MT "Malta"
MU "Mauritius"
MV "Maldive"
MW "Malawi"
MX "Mexic"
MY "Malaezia"
MZ "Mozambic"
NA "Namibia"
NC "Noua Caledonie"
NE "Niger"
NF "Insula Norfolk"
NG "Nigeria"
NI "Nicaragua"
NL "Țările de Jos"
NO "Norvegia"
NP "Nepal"
NR "Nauru"
NU "Niue"
NZ "Noua Zeelandă"
OM "Oman"
PA "Panama"
PE "Peru"
PF "Polinezia franceză"
PG "Papua Noua Guinee"
PH "Filipine"
PK "Pakistan"
PL "Polonia"
PM "Sfântul Pierre și Miquelon"
PN "Pitcairn"
PR "Puerto Rico"
PS "Teritoriile Palestiniene Ocupate"
PT "Portugalia"
PW "Palau"
PY "Paraguay"
QA "Qatar"
RE "Réunion"
RO "România"
RS "Serbia"
RU "Rusia"
RW "Rwanda"
SA "Arabia Saudită"
SB "Insulele Solomon"
SC "Seychelles"
SD "Sudan"
SE "Suedia"
SG "Singapore"
SH "Sfânta Elena"
SI "Slovenia"
SJ "Svalbard și Jan Mayen"
SK "Slovacia"
SL "Sierra Leone"
SM "San Marino"
SN "Senegal"
SO "Somalia"
SR "Surinam"
SS "Sudanul de Sud"
ST "Sao Tome și Principe"
SV "El Salvador"
SX "Sint Maarten (partea olandeză)"
SY "Siria"
SZ "Swaziland"
TC "Insulele Turks și Caicos"
TD "Ciad"
TF "Teritoriile australe și antarctice franceze"
TG "Togo"
TH "Thailanda"
TJ "Tadjikistan"
TK "Tokelau"
TL "Timorul de Est"
TM "Turkmenistan"
TN "Tunisia"
TO "Tonga"
TR "Turcia"
TT "Trinidad și Tobago"
TV "Tuvalu"
TW "Taiwan"
TZ "Tanzania"
UA "Ucraina"
UG "Uganda"
UM "United States Minor Outlying Islands"
US "Statele Unite ale Americii"
UY "Uruguay"
UZ "Uzbekistan"
VA "Vatican"
VC "Sfântul Vincent și Grenadine"
VE "Venezuela"
VG "Insulele Virgine Britanice"
VI "Insulele Virgine Americane"
VN "Vietnam"
VU "Vanuatu"
WF "Wallis și Futuna"
WS "Samoa"
YE "Yemen"
YT "Mayotte"
ZA "Africa de Sud"
ZM "Zambia"
ZW "Zimbabwe"
```
-}
toName : CountryCode -> String
toName c =
case c of
AD -> "Andorra"
AE -> "Emiratele Arabe Unite"
AF -> "Afganistan"
AG -> "Antigua și Barbuda"
AI -> "Anguilla"
AL -> "Albania"
AM -> "Armenia"
AO -> "Angola"
AQ -> "Antarctica"
AR -> "Argentina"
AS -> "Samoa americană"
AT -> "Austria"
AU -> "Australia"
AW -> "Aruba"
AX -> "Insulele Åland"
AZ -> "Azerbaidjan"
BA -> "Bosnia și Herțegovina"
BB -> "Barbados"
BD -> "Bangladesh"
BE -> "Belgia"
BF -> "Burkina Faso"
BG -> "Bulgaria"
BH -> "Bahrain"
BI -> "Burundi"
BJ -> "Benin"
BL -> "Saint Barthélemy"
BM -> "Bermude"
BN -> "Brunei"
BO -> "Bolivia"
BQ -> "Insulele Bonaire, Sint Eustatius și Saba"
BR -> "Brazilia"
BS -> "Bahamas"
BT -> "Bhutan"
BV -> "Insula Bouvet"
BW -> "Botswana"
BY -> "Belarus"
BZ -> "Belize"
CA -> "Canada"
CC -> "Insulele Cocos"
CD -> "Republica Democrată Congo"
CF -> "Republica Centrafricană"
CG -> "Congo"
CH -> "Elveția"
CI -> "Coasta de Fildeș"
CK -> "Insulele Cook"
CL -> "Chile"
CM -> "Camerun"
CN -> "Republica Populară Chineză"
CO -> "Columbia"
CR -> "Costa Rica"
CU -> "Cuba"
CV -> "Republica Capului Verde"
CW -> "Curaçao"
CX -> "Insula Crăciunului"
CY -> "Cipru"
CZ -> "Cehia"
DE -> "Germania"
DJ -> "Djibouti"
DK -> "Danemarca"
DM -> "Dominica"
DO -> "Republica Dominicană"
DZ -> "Algeria"
EC -> "Ecuador"
EE -> "Estonia"
EG -> "Egipt"
EH -> "Sahara Occidentală"
ER -> "Eritreea"
ES -> "Spania"
ET -> "Etiopia"
FI -> "Finlanda"
FJ -> "Fiji"
FK -> "Insulele Falkland"
FM -> "Micronezia"
FO -> "Insulele Feroe"
FR -> "Franța"
GA -> "Gabon"
GB -> "Regatul Unit"
GD -> "Grenada"
GE -> "Georgia"
GF -> "Guiana Franceză"
GG -> "Guernsey"
GH -> "Ghana"
GI -> "Gibraltar"
GL -> "Groenlanda"
GM -> "Gambia"
GN -> "Guineea"
GP -> "Guadelupa"
GQ -> "Guineea Ecuatorială"
GR -> "Grecia"
GS -> "Georgia de Sud și Insulele Sandwich de Sud"
GT_ -> "Guatemala"
GU -> "Guam"
GW -> "Guineea-Bissau"
GY -> "Guyana"
HK -> "Hong Kong"
HM -> "Insula Heard și Insulele McDonald"
HN -> "Honduras"
HR -> "Croația"
HT -> "Haiti"
HU -> "Ungaria"
ID -> "Indonezia"
IE -> "Republica Irlanda"
IL -> "Israel"
IM -> "Insula Man"
IN -> "India"
IO -> "Teritoriul Britanic din Oceanul Indian"
IQ -> "Irak"
IR -> "Iran"
IS -> "Islanda"
IT -> "Italia"
JE -> "Insula Jersey"
JM -> "Jamaica"
JO -> "Iordania"
JP -> "Japonia"
KE -> "Kenya"
KG -> "Kârgâzstan"
KH -> "Cambodgia"
KI -> "Kiribati"
KM -> "Comore"
KN -> "Sfântul Kitts și Nevis"
KP -> "Coreea de Nord"
KR -> "Coreea de Sud"
KW -> "Kuweit"
KY -> "Insulele Cayman"
KZ -> "Kazahstan"
LA -> "Laos"
LB -> "Liban"
LC -> "Sfânta Lucia"
LI -> "Liechtenstein"
LK -> "Sri Lanka"
LR -> "Liberia"
LS -> "Lesotho"
LT_ -> "Lituania"
LU -> "Luxemburg"
LV -> "Letonia"
LY -> "Libia"
MA -> "Maroc"
MC -> "Monaco"
MD -> "Republica Moldova"
ME -> "Muntenegru"
MF -> "Sint Maarten (partea franceză)"
MG -> "Madagascar"
MH -> "Insulele Marshall"
MK -> "Republica Macedonia"
ML -> "Mali"
MM -> "Myanmar"
MN -> "Mongolia"
MO -> "Macao"
MP -> "Insulele Mariane de Nord"
MQ -> "Martinica"
MR -> "Mauritania"
MS -> "Montserrat"
MT -> "Malta"
MU -> "Mauritius"
MV -> "Maldive"
MW -> "Malawi"
MX -> "Mexic"
MY -> "Malaezia"
MZ -> "Mozambic"
NA -> "Namibia"
NC -> "Noua Caledonie"
NE -> "Niger"
NF -> "Insula Norfolk"
NG -> "Nigeria"
NI -> "Nicaragua"
NL -> "Țările de Jos"
NO -> "Norvegia"
NP -> "Nepal"
NR -> "Nauru"
NU -> "Niue"
NZ -> "Noua Zeelandă"
OM -> "Oman"
PA -> "Panama"
PE -> "Peru"
PF -> "Polinezia franceză"
PG -> "Papua Noua Guinee"
PH -> "Filipine"
PK -> "Pakistan"
PL -> "Polonia"
PM -> "Sfântul Pierre și Miquelon"
PN -> "Pitcairn"
PR -> "Puerto Rico"
PS -> "Teritoriile Palestiniene Ocupate"
PT -> "Portugalia"
PW -> "Palau"
PY -> "Paraguay"
QA -> "Qatar"
RE -> "Réunion"
RO -> "România"
RS -> "Serbia"
RU -> "Rusia"
RW -> "Rwanda"
SA -> "Arabia Saudită"
SB -> "Insulele Solomon"
SC -> "Seychelles"
SD -> "Sudan"
SE -> "Suedia"
SG -> "Singapore"
SH -> "Sfânta Elena"
SI -> "Slovenia"
SJ -> "Svalbard și Jan Mayen"
SK -> "Slovacia"
SL -> "Sierra Leone"
SM -> "San Marino"
SN -> "Senegal"
SO -> "Somalia"
SR -> "Surinam"
SS -> "Sudanul de Sud"
ST -> "Sao Tome și Principe"
SV -> "El Salvador"
SX -> "Sint Maarten (partea olandeză)"
SY -> "Siria"
SZ -> "Swaziland"
TC -> "Insulele Turks și Caicos"
TD -> "Ciad"
TF -> "Teritoriile australe și antarctice franceze"
TG -> "Togo"
TH -> "Thailanda"
TJ -> "Tadjikistan"
TK -> "Tokelau"
TL -> "Timorul de Est"
TM -> "Turkmenistan"
TN -> "Tunisia"
TO -> "Tonga"
TR -> "Turcia"
TT -> "Trinidad și Tobago"
TV -> "Tuvalu"
TW -> "Taiwan"
TZ -> "Tanzania"
UA -> "Ucraina"
UG -> "Uganda"
UM -> "United States Minor Outlying Islands"
US -> "Statele Unite ale Americii"
UY -> "Uruguay"
UZ -> "Uzbekistan"
VA -> "Vatican"
VC -> "Sfântul Vincent și Grenadine"
VE -> "Venezuela"
VG -> "Insulele Virgine Britanice"
VI -> "Insulele Virgine Americane"
VN -> "Vietnam"
VU -> "Vanuatu"
WF -> "Wallis și Futuna"
WS -> "Samoa"
YE -> "Yemen"
YT -> "Mayotte"
ZA -> "Africa de Sud"
ZM -> "Zambia"
ZW -> "Zimbabwe" | 37251 | module Iso3166.Romanian exposing (toName)
-- Generated by 'generate/Main.hs' do not edit by hand
{-|
@docs toName
-}
import Iso3166 exposing (..)
{-| Name for `CountryCode` in Romanian.
```
AD "Andorra"
AE "Emiratele Arabe Unite"
AF "Afganistan"
AG "Antigua și Barbuda"
AI "Anguilla"
AL "Albania"
AM "Armenia"
AO "Angola"
AQ "Antarctica"
AR "Argentina"
AS "Samoa americană"
AT "Austria"
AU "Australia"
AW "Aruba"
AX "Insulele Åland"
AZ "Azerbaidjan"
BA "Bosnia și Herțegovina"
BB "Barbados"
BD "Bangladesh"
BE "Belgia"
BF "Burkina Faso"
BG "Bulgaria"
BH "Bahrain"
BI "Burundi"
BJ "Benin"
BL "Saint Barthélemy"
BM "Bermude"
BN "Brunei"
BO "Bolivia"
BQ "Insulele Bonaire, Sint Eustatius și Saba"
BR "Brazilia"
BS "Bahamas"
BT "Bhutan"
BV "Insula Bouvet"
BW "Botswana"
BY "Belarus"
BZ "Belize"
CA "Canada"
CC "Insulele Cocos"
CD "Republica Democrată Congo"
CF "Republica Centrafricană"
CG "Congo"
CH "Elveția"
CI "Coasta de Fildeș"
CK "Insulele Cook"
CL "Chile"
CM "Camerun"
CN "Republica Populară Chineză"
CO "Columbia"
CR "Costa Rica"
CU "Cuba"
CV "Republica Capului Verde"
CW "Curaçao"
CX "Insula Crăciunului"
CY "Cipru"
CZ "Cehia"
DE "Germania"
DJ "Djibouti"
DK "Danemarca"
DM "Dominica"
DO "Republica Dominicană"
DZ "Algeria"
EC "Ecuador"
EE "Estonia"
EG "Egipt"
EH "Sahara Occidentală"
ER "Eritreea"
ES "Spania"
ET "Etiopia"
FI "Finlanda"
FJ "Fiji"
FK "Insulele Falkland"
FM "Micronezia"
FO "Insulele Feroe"
FR "Franța"
GA "Gabon"
GB "Regatul Unit"
GD "Grenada"
GE "Georgia"
GF "Guiana Franceză"
GG "Guernsey"
GH "Ghana"
GI "Gibraltar"
GL "Groenlanda"
GM "Gambia"
GN "Guineea"
GP "Guadelupa"
GQ "Guineea Ecuatorială"
GR "Grecia"
GS "Georgia de Sud și Insulele Sandwich de Sud"
GT_ "Guatemala"
GU "Guam"
GW "Guineea-Bissau"
GY "Guyana"
HK "Hong Kong"
HM "Insula Heard și Insulele McDonald"
HN "Honduras"
HR "Croația"
HT "Haiti"
HU "Ungaria"
ID "Indonezia"
IE "Republica Irlanda"
IL "Israel"
IM "Insula Man"
IN "India"
IO "Teritoriul Britanic din Oceanul Indian"
IQ "Irak"
IR "Iran"
IS "Islanda"
IT "Italia"
JE "Insula Jersey"
JM "Jamaica"
JO "Iordania"
JP "Japonia"
KE "Kenya"
KG "Kârgâzstan"
KH "Cambodgia"
KI "Kiribati"
KM "Comore"
KN "Sfântul Kitts și Nevis"
KP "Coreea de Nord"
KR "Coreea de Sud"
KW "Kuweit"
KY "Insulele Cayman"
KZ "Kazahstan"
LA "Laos"
LB "Liban"
LC "Sfânta Lucia"
LI "Liechtenstein"
LK "Sri Lanka"
LR "Liberia"
LS "Lesotho"
LT_ "Lituania"
LU "Luxemburg"
LV "Letonia"
LY "Libia"
MA "Maroc"
MC "Monaco"
MD "Republica Moldova"
ME "Muntenegru"
MF "Sint Maarten (partea franceză)"
MG "Madagascar"
MH "Insulele Marshall"
MK "Republica Macedonia"
ML "Mali"
MM "Myanmar"
MN "Mongolia"
MO "Macao"
MP "Insulele Mariane de Nord"
MQ "Martinica"
MR "Mauritania"
MS "Montserrat"
MT "Malta"
MU "Mauritius"
MV "Maldive"
MW "Malawi"
MX "Mexic"
MY "Malaezia"
MZ "Mozambic"
NA "Namibia"
NC "Noua Caledonie"
NE "Niger"
NF "Insula Norfolk"
NG "Nigeria"
NI "Nicaragua"
NL "Țările de Jos"
NO "Norvegia"
NP "Nepal"
NR "Nauru"
NU "Niue"
NZ "Noua Zeelandă"
OM "Oman"
PA "Panama"
PE "Peru"
PF "Polinezia franceză"
PG "Papua Noua Guinee"
PH "Filipine"
PK "Pakistan"
PL "Polonia"
PM "Sfântul Pierre și Miquelon"
PN "Pitcairn"
PR "Puerto Rico"
PS "Teritoriile Palestiniene Ocupate"
PT "Portugalia"
PW "Palau"
PY "Paraguay"
QA "Qatar"
RE "Réunion"
RO "România"
RS "Serbia"
RU "Rusia"
RW "Rwanda"
SA "Arabia Saudită"
SB "Insulele Solomon"
SC "Seychelles"
SD "Sudan"
SE "Suedia"
SG "Singapore"
SH "Sfânta Elena"
SI "Slovenia"
SJ "Svalbard și Jan <NAME>en"
SK "Slovacia"
SL "Sierra Leone"
SM "San Marino"
SN "Senegal"
SO "Somalia"
SR "Surinam"
SS "Sudanul de Sud"
ST "Sao Tome și Principe"
SV "El Salvador"
SX "Sint Maarten (partea olandeză)"
SY "Siria"
SZ "Swaziland"
TC "Insulele Turks și Caicos"
TD "Ciad"
TF "Teritoriile australe și antarctice franceze"
TG "Togo"
TH "Thailanda"
TJ "Tadjikistan"
TK "Tokelau"
TL "Timorul de Est"
TM "Turkmenistan"
TN "Tunisia"
TO "Tonga"
TR "Turcia"
TT "Trinidad și Tobago"
TV "Tuvalu"
TW "Taiwan"
TZ "Tanzania"
UA "Ucraina"
UG "Uganda"
UM "United States Minor Outlying Islands"
US "Statele Unite ale Americii"
UY "Uruguay"
UZ "Uzbekistan"
VA "Vatican"
VC "Sfântul Vincent și Grenadine"
VE "Venezuela"
VG "Insulele Virgine Britanice"
VI "Insulele Virgine Americane"
VN "Vietnam"
VU "Vanuatu"
WF "Wallis și Futuna"
WS "Samoa"
YE "Yemen"
YT "Mayotte"
ZA "Africa de Sud"
ZM "Zambia"
ZW "Zimbabwe"
```
-}
toName : CountryCode -> String
toName c =
case c of
AD -> "Andorra"
AE -> "Emiratele Arabe Unite"
AF -> "Afganistan"
AG -> "Antigua și Barbuda"
AI -> "Anguilla"
AL -> "Albania"
AM -> "Armenia"
AO -> "Angola"
AQ -> "Antarctica"
AR -> "Argentina"
AS -> "Samoa americană"
AT -> "Austria"
AU -> "Australia"
AW -> "Aruba"
AX -> "Insulele Åland"
AZ -> "Azerbaidjan"
BA -> "Bosnia și Herțegovina"
BB -> "Barbados"
BD -> "Bangladesh"
BE -> "Belgia"
BF -> "Burkina Faso"
BG -> "Bulgaria"
BH -> "Bahrain"
BI -> "Burundi"
BJ -> "Benin"
BL -> "Saint Barthélemy"
BM -> "Bermude"
BN -> "Brunei"
BO -> "Bolivia"
BQ -> "Insulele Bonaire, Sint Eustatius și Saba"
BR -> "Brazilia"
BS -> "Bahamas"
BT -> "Bhutan"
BV -> "Insula Bouvet"
BW -> "Botswana"
BY -> "Belarus"
BZ -> "Belize"
CA -> "Canada"
CC -> "Insulele Cocos"
CD -> "Republica Democrată Congo"
CF -> "Republica Centrafricană"
CG -> "Congo"
CH -> "Elveția"
CI -> "Coasta de Fildeș"
CK -> "Insulele Cook"
CL -> "Chile"
CM -> "Camerun"
CN -> "Republica Populară Chineză"
CO -> "Columbia"
CR -> "Costa Rica"
CU -> "Cuba"
CV -> "Republica Capului Verde"
CW -> "Curaçao"
CX -> "Insula Crăciunului"
CY -> "Cipru"
CZ -> "Cehia"
DE -> "Germania"
DJ -> "Djibouti"
DK -> "Danemarca"
DM -> "Dominica"
DO -> "Republica Dominicană"
DZ -> "Algeria"
EC -> "Ecuador"
EE -> "Estonia"
EG -> "Egipt"
EH -> "Sahara Occidentală"
ER -> "Eritreea"
ES -> "Spania"
ET -> "Etiopia"
FI -> "Finlanda"
FJ -> "Fiji"
FK -> "Insulele Falkland"
FM -> "Micronezia"
FO -> "Insulele Feroe"
FR -> "Franța"
GA -> "Gabon"
GB -> "Regatul Unit"
GD -> "Grenada"
GE -> "Georgia"
GF -> "Guiana Franceză"
GG -> "Guernsey"
GH -> "Ghana"
GI -> "Gibraltar"
GL -> "Groenlanda"
GM -> "Gambia"
GN -> "Guineea"
GP -> "Guadelupa"
GQ -> "Guineea Ecuatorială"
GR -> "Grecia"
GS -> "Georgia de Sud și Insulele Sandwich de Sud"
GT_ -> "Guatemala"
GU -> "Guam"
GW -> "Guineea-Bissau"
GY -> "Guyana"
HK -> "Hong Kong"
HM -> "Insula Heard și Insulele McDonald"
HN -> "Honduras"
HR -> "Croația"
HT -> "Haiti"
HU -> "Ungaria"
ID -> "Indonezia"
IE -> "Republica Irlanda"
IL -> "Israel"
IM -> "Insula Man"
IN -> "India"
IO -> "Teritoriul Britanic din Oceanul Indian"
IQ -> "Irak"
IR -> "Iran"
IS -> "Islanda"
IT -> "Italia"
JE -> "Insula Jersey"
JM -> "Jamaica"
JO -> "Iordania"
JP -> "Japonia"
KE -> "Kenya"
KG -> "Kârgâzstan"
KH -> "Cambodgia"
KI -> "Kiribati"
KM -> "Comore"
KN -> "Sfântul Kitts și Nevis"
KP -> "Coreea de Nord"
KR -> "Coreea de Sud"
KW -> "Kuweit"
KY -> "Insulele Cayman"
KZ -> "Kazahstan"
LA -> "Laos"
LB -> "Liban"
LC -> "Sfânta Lucia"
LI -> "Liechtenstein"
LK -> "Sri Lanka"
LR -> "Liberia"
LS -> "Lesotho"
LT_ -> "Lituania"
LU -> "Luxemburg"
LV -> "Letonia"
LY -> "Libia"
MA -> "Maroc"
MC -> "Monaco"
MD -> "Republica Moldova"
ME -> "Muntenegru"
MF -> "Sint Maarten (partea franceză)"
MG -> "Mad<NAME>"
MH -> "Insulele Marshall"
MK -> "Republica Macedonia"
ML -> "Mali"
MM -> "Myanmar"
MN -> "Mongolia"
MO -> "Macao"
MP -> "Insulele Mariane de Nord"
MQ -> "Martinica"
MR -> "Mauritania"
MS -> "Montserrat"
MT -> "Malta"
MU -> "Mauritius"
MV -> "Maldive"
MW -> "Malawi"
MX -> "Mexic"
MY -> "Malaezia"
MZ -> "Mozambic"
NA -> "Namibia"
NC -> "Noua Caledonie"
NE -> "Niger"
NF -> "Insula Norfolk"
NG -> "Nigeria"
NI -> "Nicaragua"
NL -> "Țările de Jos"
NO -> "Norvegia"
NP -> "Nepal"
NR -> "Nauru"
NU -> "Niue"
NZ -> "Noua Zeelandă"
OM -> "Oman"
PA -> "Panama"
PE -> "Peru"
PF -> "Polinezia franceză"
PG -> "Papua Noua Guinee"
PH -> "Filipine"
PK -> "Pakistan"
PL -> "Polonia"
PM -> "Sfântul Pierre și Miquelon"
PN -> "Pitcairn"
PR -> "Puerto Rico"
PS -> "Teritoriile Palestiniene Ocupate"
PT -> "Portugalia"
PW -> "Palau"
PY -> "Paraguay"
QA -> "Qatar"
RE -> "Réunion"
RO -> "România"
RS -> "Serbia"
RU -> "Rusia"
RW -> "Rwanda"
SA -> "Arabia Saudită"
SB -> "Insulele Solomon"
SC -> "Seychelles"
SD -> "Sudan"
SE -> "Suedia"
SG -> "Singapore"
SH -> "Sfânta Elena"
SI -> "Slovenia"
SJ -> "S<NAME>bard și <NAME>"
SK -> "Slovacia"
SL -> "Sierra Leone"
SM -> "San Marino"
SN -> "Senegal"
SO -> "Somalia"
SR -> "Surinam"
SS -> "Sudanul de Sud"
ST -> "Sao Tome și Principe"
SV -> "El Salvador"
SX -> "Sint Maarten (partea olandeză)"
SY -> "Siria"
SZ -> "Swaziland"
TC -> "Insulele Turks și Caicos"
TD -> "Ciad"
TF -> "Teritoriile australe și antarctice franceze"
TG -> "Togo"
TH -> "Thailanda"
TJ -> "Tadjikistan"
TK -> "Tokelau"
TL -> "Timorul de Est"
TM -> "Turkmenistan"
TN -> "Tunisia"
TO -> "Tonga"
TR -> "Turcia"
TT -> "Trinidad și Tobago"
TV -> "Tuvalu"
TW -> "Taiwan"
TZ -> "Tanzania"
UA -> "Ucraina"
UG -> "Uganda"
UM -> "United States Minor Outlying Islands"
US -> "Statele Unite ale Americii"
UY -> "Uruguay"
UZ -> "Uzbekistan"
VA -> "Vatican"
VC -> "Sfântul Vincent și Grenadine"
VE -> "Venezuela"
VG -> "Insulele Virgine Britanice"
VI -> "Insulele Virgine Americane"
VN -> "Vietnam"
VU -> "Vanuatu"
WF -> "Wallis și Futuna"
WS -> "Samoa"
YE -> "Yemen"
YT -> "Mayotte"
ZA -> "Africa de Sud"
ZM -> "Zambia"
ZW -> "Zimbabwe" | true | module Iso3166.Romanian exposing (toName)
-- Generated by 'generate/Main.hs' do not edit by hand
{-|
@docs toName
-}
import Iso3166 exposing (..)
{-| Name for `CountryCode` in Romanian.
```
AD "Andorra"
AE "Emiratele Arabe Unite"
AF "Afganistan"
AG "Antigua și Barbuda"
AI "Anguilla"
AL "Albania"
AM "Armenia"
AO "Angola"
AQ "Antarctica"
AR "Argentina"
AS "Samoa americană"
AT "Austria"
AU "Australia"
AW "Aruba"
AX "Insulele Åland"
AZ "Azerbaidjan"
BA "Bosnia și Herțegovina"
BB "Barbados"
BD "Bangladesh"
BE "Belgia"
BF "Burkina Faso"
BG "Bulgaria"
BH "Bahrain"
BI "Burundi"
BJ "Benin"
BL "Saint Barthélemy"
BM "Bermude"
BN "Brunei"
BO "Bolivia"
BQ "Insulele Bonaire, Sint Eustatius și Saba"
BR "Brazilia"
BS "Bahamas"
BT "Bhutan"
BV "Insula Bouvet"
BW "Botswana"
BY "Belarus"
BZ "Belize"
CA "Canada"
CC "Insulele Cocos"
CD "Republica Democrată Congo"
CF "Republica Centrafricană"
CG "Congo"
CH "Elveția"
CI "Coasta de Fildeș"
CK "Insulele Cook"
CL "Chile"
CM "Camerun"
CN "Republica Populară Chineză"
CO "Columbia"
CR "Costa Rica"
CU "Cuba"
CV "Republica Capului Verde"
CW "Curaçao"
CX "Insula Crăciunului"
CY "Cipru"
CZ "Cehia"
DE "Germania"
DJ "Djibouti"
DK "Danemarca"
DM "Dominica"
DO "Republica Dominicană"
DZ "Algeria"
EC "Ecuador"
EE "Estonia"
EG "Egipt"
EH "Sahara Occidentală"
ER "Eritreea"
ES "Spania"
ET "Etiopia"
FI "Finlanda"
FJ "Fiji"
FK "Insulele Falkland"
FM "Micronezia"
FO "Insulele Feroe"
FR "Franța"
GA "Gabon"
GB "Regatul Unit"
GD "Grenada"
GE "Georgia"
GF "Guiana Franceză"
GG "Guernsey"
GH "Ghana"
GI "Gibraltar"
GL "Groenlanda"
GM "Gambia"
GN "Guineea"
GP "Guadelupa"
GQ "Guineea Ecuatorială"
GR "Grecia"
GS "Georgia de Sud și Insulele Sandwich de Sud"
GT_ "Guatemala"
GU "Guam"
GW "Guineea-Bissau"
GY "Guyana"
HK "Hong Kong"
HM "Insula Heard și Insulele McDonald"
HN "Honduras"
HR "Croația"
HT "Haiti"
HU "Ungaria"
ID "Indonezia"
IE "Republica Irlanda"
IL "Israel"
IM "Insula Man"
IN "India"
IO "Teritoriul Britanic din Oceanul Indian"
IQ "Irak"
IR "Iran"
IS "Islanda"
IT "Italia"
JE "Insula Jersey"
JM "Jamaica"
JO "Iordania"
JP "Japonia"
KE "Kenya"
KG "Kârgâzstan"
KH "Cambodgia"
KI "Kiribati"
KM "Comore"
KN "Sfântul Kitts și Nevis"
KP "Coreea de Nord"
KR "Coreea de Sud"
KW "Kuweit"
KY "Insulele Cayman"
KZ "Kazahstan"
LA "Laos"
LB "Liban"
LC "Sfânta Lucia"
LI "Liechtenstein"
LK "Sri Lanka"
LR "Liberia"
LS "Lesotho"
LT_ "Lituania"
LU "Luxemburg"
LV "Letonia"
LY "Libia"
MA "Maroc"
MC "Monaco"
MD "Republica Moldova"
ME "Muntenegru"
MF "Sint Maarten (partea franceză)"
MG "Madagascar"
MH "Insulele Marshall"
MK "Republica Macedonia"
ML "Mali"
MM "Myanmar"
MN "Mongolia"
MO "Macao"
MP "Insulele Mariane de Nord"
MQ "Martinica"
MR "Mauritania"
MS "Montserrat"
MT "Malta"
MU "Mauritius"
MV "Maldive"
MW "Malawi"
MX "Mexic"
MY "Malaezia"
MZ "Mozambic"
NA "Namibia"
NC "Noua Caledonie"
NE "Niger"
NF "Insula Norfolk"
NG "Nigeria"
NI "Nicaragua"
NL "Țările de Jos"
NO "Norvegia"
NP "Nepal"
NR "Nauru"
NU "Niue"
NZ "Noua Zeelandă"
OM "Oman"
PA "Panama"
PE "Peru"
PF "Polinezia franceză"
PG "Papua Noua Guinee"
PH "Filipine"
PK "Pakistan"
PL "Polonia"
PM "Sfântul Pierre și Miquelon"
PN "Pitcairn"
PR "Puerto Rico"
PS "Teritoriile Palestiniene Ocupate"
PT "Portugalia"
PW "Palau"
PY "Paraguay"
QA "Qatar"
RE "Réunion"
RO "România"
RS "Serbia"
RU "Rusia"
RW "Rwanda"
SA "Arabia Saudită"
SB "Insulele Solomon"
SC "Seychelles"
SD "Sudan"
SE "Suedia"
SG "Singapore"
SH "Sfânta Elena"
SI "Slovenia"
SJ "Svalbard și Jan PI:NAME:<NAME>END_PIen"
SK "Slovacia"
SL "Sierra Leone"
SM "San Marino"
SN "Senegal"
SO "Somalia"
SR "Surinam"
SS "Sudanul de Sud"
ST "Sao Tome și Principe"
SV "El Salvador"
SX "Sint Maarten (partea olandeză)"
SY "Siria"
SZ "Swaziland"
TC "Insulele Turks și Caicos"
TD "Ciad"
TF "Teritoriile australe și antarctice franceze"
TG "Togo"
TH "Thailanda"
TJ "Tadjikistan"
TK "Tokelau"
TL "Timorul de Est"
TM "Turkmenistan"
TN "Tunisia"
TO "Tonga"
TR "Turcia"
TT "Trinidad și Tobago"
TV "Tuvalu"
TW "Taiwan"
TZ "Tanzania"
UA "Ucraina"
UG "Uganda"
UM "United States Minor Outlying Islands"
US "Statele Unite ale Americii"
UY "Uruguay"
UZ "Uzbekistan"
VA "Vatican"
VC "Sfântul Vincent și Grenadine"
VE "Venezuela"
VG "Insulele Virgine Britanice"
VI "Insulele Virgine Americane"
VN "Vietnam"
VU "Vanuatu"
WF "Wallis și Futuna"
WS "Samoa"
YE "Yemen"
YT "Mayotte"
ZA "Africa de Sud"
ZM "Zambia"
ZW "Zimbabwe"
```
-}
toName : CountryCode -> String
toName c =
case c of
AD -> "Andorra"
AE -> "Emiratele Arabe Unite"
AF -> "Afganistan"
AG -> "Antigua și Barbuda"
AI -> "Anguilla"
AL -> "Albania"
AM -> "Armenia"
AO -> "Angola"
AQ -> "Antarctica"
AR -> "Argentina"
AS -> "Samoa americană"
AT -> "Austria"
AU -> "Australia"
AW -> "Aruba"
AX -> "Insulele Åland"
AZ -> "Azerbaidjan"
BA -> "Bosnia și Herțegovina"
BB -> "Barbados"
BD -> "Bangladesh"
BE -> "Belgia"
BF -> "Burkina Faso"
BG -> "Bulgaria"
BH -> "Bahrain"
BI -> "Burundi"
BJ -> "Benin"
BL -> "Saint Barthélemy"
BM -> "Bermude"
BN -> "Brunei"
BO -> "Bolivia"
BQ -> "Insulele Bonaire, Sint Eustatius și Saba"
BR -> "Brazilia"
BS -> "Bahamas"
BT -> "Bhutan"
BV -> "Insula Bouvet"
BW -> "Botswana"
BY -> "Belarus"
BZ -> "Belize"
CA -> "Canada"
CC -> "Insulele Cocos"
CD -> "Republica Democrată Congo"
CF -> "Republica Centrafricană"
CG -> "Congo"
CH -> "Elveția"
CI -> "Coasta de Fildeș"
CK -> "Insulele Cook"
CL -> "Chile"
CM -> "Camerun"
CN -> "Republica Populară Chineză"
CO -> "Columbia"
CR -> "Costa Rica"
CU -> "Cuba"
CV -> "Republica Capului Verde"
CW -> "Curaçao"
CX -> "Insula Crăciunului"
CY -> "Cipru"
CZ -> "Cehia"
DE -> "Germania"
DJ -> "Djibouti"
DK -> "Danemarca"
DM -> "Dominica"
DO -> "Republica Dominicană"
DZ -> "Algeria"
EC -> "Ecuador"
EE -> "Estonia"
EG -> "Egipt"
EH -> "Sahara Occidentală"
ER -> "Eritreea"
ES -> "Spania"
ET -> "Etiopia"
FI -> "Finlanda"
FJ -> "Fiji"
FK -> "Insulele Falkland"
FM -> "Micronezia"
FO -> "Insulele Feroe"
FR -> "Franța"
GA -> "Gabon"
GB -> "Regatul Unit"
GD -> "Grenada"
GE -> "Georgia"
GF -> "Guiana Franceză"
GG -> "Guernsey"
GH -> "Ghana"
GI -> "Gibraltar"
GL -> "Groenlanda"
GM -> "Gambia"
GN -> "Guineea"
GP -> "Guadelupa"
GQ -> "Guineea Ecuatorială"
GR -> "Grecia"
GS -> "Georgia de Sud și Insulele Sandwich de Sud"
GT_ -> "Guatemala"
GU -> "Guam"
GW -> "Guineea-Bissau"
GY -> "Guyana"
HK -> "Hong Kong"
HM -> "Insula Heard și Insulele McDonald"
HN -> "Honduras"
HR -> "Croația"
HT -> "Haiti"
HU -> "Ungaria"
ID -> "Indonezia"
IE -> "Republica Irlanda"
IL -> "Israel"
IM -> "Insula Man"
IN -> "India"
IO -> "Teritoriul Britanic din Oceanul Indian"
IQ -> "Irak"
IR -> "Iran"
IS -> "Islanda"
IT -> "Italia"
JE -> "Insula Jersey"
JM -> "Jamaica"
JO -> "Iordania"
JP -> "Japonia"
KE -> "Kenya"
KG -> "Kârgâzstan"
KH -> "Cambodgia"
KI -> "Kiribati"
KM -> "Comore"
KN -> "Sfântul Kitts și Nevis"
KP -> "Coreea de Nord"
KR -> "Coreea de Sud"
KW -> "Kuweit"
KY -> "Insulele Cayman"
KZ -> "Kazahstan"
LA -> "Laos"
LB -> "Liban"
LC -> "Sfânta Lucia"
LI -> "Liechtenstein"
LK -> "Sri Lanka"
LR -> "Liberia"
LS -> "Lesotho"
LT_ -> "Lituania"
LU -> "Luxemburg"
LV -> "Letonia"
LY -> "Libia"
MA -> "Maroc"
MC -> "Monaco"
MD -> "Republica Moldova"
ME -> "Muntenegru"
MF -> "Sint Maarten (partea franceză)"
MG -> "MadPI:NAME:<NAME>END_PI"
MH -> "Insulele Marshall"
MK -> "Republica Macedonia"
ML -> "Mali"
MM -> "Myanmar"
MN -> "Mongolia"
MO -> "Macao"
MP -> "Insulele Mariane de Nord"
MQ -> "Martinica"
MR -> "Mauritania"
MS -> "Montserrat"
MT -> "Malta"
MU -> "Mauritius"
MV -> "Maldive"
MW -> "Malawi"
MX -> "Mexic"
MY -> "Malaezia"
MZ -> "Mozambic"
NA -> "Namibia"
NC -> "Noua Caledonie"
NE -> "Niger"
NF -> "Insula Norfolk"
NG -> "Nigeria"
NI -> "Nicaragua"
NL -> "Țările de Jos"
NO -> "Norvegia"
NP -> "Nepal"
NR -> "Nauru"
NU -> "Niue"
NZ -> "Noua Zeelandă"
OM -> "Oman"
PA -> "Panama"
PE -> "Peru"
PF -> "Polinezia franceză"
PG -> "Papua Noua Guinee"
PH -> "Filipine"
PK -> "Pakistan"
PL -> "Polonia"
PM -> "Sfântul Pierre și Miquelon"
PN -> "Pitcairn"
PR -> "Puerto Rico"
PS -> "Teritoriile Palestiniene Ocupate"
PT -> "Portugalia"
PW -> "Palau"
PY -> "Paraguay"
QA -> "Qatar"
RE -> "Réunion"
RO -> "România"
RS -> "Serbia"
RU -> "Rusia"
RW -> "Rwanda"
SA -> "Arabia Saudită"
SB -> "Insulele Solomon"
SC -> "Seychelles"
SD -> "Sudan"
SE -> "Suedia"
SG -> "Singapore"
SH -> "Sfânta Elena"
SI -> "Slovenia"
SJ -> "SPI:NAME:<NAME>END_PIbard și PI:NAME:<NAME>END_PI"
SK -> "Slovacia"
SL -> "Sierra Leone"
SM -> "San Marino"
SN -> "Senegal"
SO -> "Somalia"
SR -> "Surinam"
SS -> "Sudanul de Sud"
ST -> "Sao Tome și Principe"
SV -> "El Salvador"
SX -> "Sint Maarten (partea olandeză)"
SY -> "Siria"
SZ -> "Swaziland"
TC -> "Insulele Turks și Caicos"
TD -> "Ciad"
TF -> "Teritoriile australe și antarctice franceze"
TG -> "Togo"
TH -> "Thailanda"
TJ -> "Tadjikistan"
TK -> "Tokelau"
TL -> "Timorul de Est"
TM -> "Turkmenistan"
TN -> "Tunisia"
TO -> "Tonga"
TR -> "Turcia"
TT -> "Trinidad și Tobago"
TV -> "Tuvalu"
TW -> "Taiwan"
TZ -> "Tanzania"
UA -> "Ucraina"
UG -> "Uganda"
UM -> "United States Minor Outlying Islands"
US -> "Statele Unite ale Americii"
UY -> "Uruguay"
UZ -> "Uzbekistan"
VA -> "Vatican"
VC -> "Sfântul Vincent și Grenadine"
VE -> "Venezuela"
VG -> "Insulele Virgine Britanice"
VI -> "Insulele Virgine Americane"
VN -> "Vietnam"
VU -> "Vanuatu"
WF -> "Wallis și Futuna"
WS -> "Samoa"
YE -> "Yemen"
YT -> "Mayotte"
ZA -> "Africa de Sud"
ZM -> "Zambia"
ZW -> "Zimbabwe" | elm |
[
{
"context": "pPermissions =\n { creator = \"Fission\", name = \"Contacts\" }\n\n\nfsPermissions : Webnative.FileSystemPermissi",
"end": 915,
"score": 0.5219017863,
"start": 907,
"tag": "NAME",
"value": "Contacts"
}
] | src/Application/Radix.elm | fission-suite/contacts | 0 | module Radix exposing (..)
import Browser
import Browser.Navigation as Nav
import CAIP exposing (ChainIdCollection)
import ChainID exposing (ChainID)
import Contact exposing (Contact)
import Dict exposing (Dict)
import Page exposing (Page)
import RemoteData exposing (RemoteData(..))
import Time
import UUID
import Url exposing (Url)
import Webnative
import Webnative.Path as Path exposing (File, Path)
-- ⛩
type alias Flags =
{ seeds : List Int }
-- 🌳
type alias Model =
{ navKey : Nav.Key
, page : Page
, seeds : UUID.Seeds
, url : Url
, userData : UserData
}
-- 🌳 ~ USER DATA
type alias UserData =
{ blockchainIds : RemoteData String ChainIdCollection
, contacts : RemoteData String (List Contact)
, name : Maybe String
}
-- 🌳 ~ PERMISSIONS
appPermissions : Webnative.AppPermissions
appPermissions =
{ creator = "Fission", name = "Contacts" }
fsPermissions : Webnative.FileSystemPermissions
fsPermissions =
{ public =
{ directories = []
, files = []
}
, private =
{ directories = [ Path.directory [ "Documents", "Contacts" ] ]
, files = []
}
}
permissions : Webnative.Permissions
permissions =
{ app = Just appPermissions
, fs = Just fsPermissions
}
contactsPath : Path File
contactsPath =
Path.file [ "Documents", "Contacts", "Library.json" ]
blockchainsPath : Path File
blockchainsPath =
Path.file [ "Documents", "Contacts", "Blockchain Networks.json" ]
-- 📣
type Msg
= Bypassed
-----------------------------------------
-- 🐚
-----------------------------------------
| CopyToClipboard { notification : Maybe String, text : String }
| GetCurrentTimeFor (Time.Posix -> Msg)
| GotWebnativeResponse Webnative.Response
| SignIn
| SignOut
-----------------------------------------
-- Contacts
-----------------------------------------
| AddNewContact Page.NewContext Time.Posix
| GotUpdatedEditContext Page.EditContext
| GotUpdatedIndexContext Page.IndexContext
| GotUpdatedNewContext Page.NewContext
| RemoveContact { index : Int }
| UpdateContact Contact Page.EditContext Time.Posix
-----------------------------------------
-- Routing
-----------------------------------------
| UrlChanged Url
| UrlRequested Browser.UrlRequest
type alias Manager =
Model -> ( Model, Cmd Msg )
| 12104 | module Radix exposing (..)
import Browser
import Browser.Navigation as Nav
import CAIP exposing (ChainIdCollection)
import ChainID exposing (ChainID)
import Contact exposing (Contact)
import Dict exposing (Dict)
import Page exposing (Page)
import RemoteData exposing (RemoteData(..))
import Time
import UUID
import Url exposing (Url)
import Webnative
import Webnative.Path as Path exposing (File, Path)
-- ⛩
type alias Flags =
{ seeds : List Int }
-- 🌳
type alias Model =
{ navKey : Nav.Key
, page : Page
, seeds : UUID.Seeds
, url : Url
, userData : UserData
}
-- 🌳 ~ USER DATA
type alias UserData =
{ blockchainIds : RemoteData String ChainIdCollection
, contacts : RemoteData String (List Contact)
, name : Maybe String
}
-- 🌳 ~ PERMISSIONS
appPermissions : Webnative.AppPermissions
appPermissions =
{ creator = "Fission", name = "<NAME>" }
fsPermissions : Webnative.FileSystemPermissions
fsPermissions =
{ public =
{ directories = []
, files = []
}
, private =
{ directories = [ Path.directory [ "Documents", "Contacts" ] ]
, files = []
}
}
permissions : Webnative.Permissions
permissions =
{ app = Just appPermissions
, fs = Just fsPermissions
}
contactsPath : Path File
contactsPath =
Path.file [ "Documents", "Contacts", "Library.json" ]
blockchainsPath : Path File
blockchainsPath =
Path.file [ "Documents", "Contacts", "Blockchain Networks.json" ]
-- 📣
type Msg
= Bypassed
-----------------------------------------
-- 🐚
-----------------------------------------
| CopyToClipboard { notification : Maybe String, text : String }
| GetCurrentTimeFor (Time.Posix -> Msg)
| GotWebnativeResponse Webnative.Response
| SignIn
| SignOut
-----------------------------------------
-- Contacts
-----------------------------------------
| AddNewContact Page.NewContext Time.Posix
| GotUpdatedEditContext Page.EditContext
| GotUpdatedIndexContext Page.IndexContext
| GotUpdatedNewContext Page.NewContext
| RemoveContact { index : Int }
| UpdateContact Contact Page.EditContext Time.Posix
-----------------------------------------
-- Routing
-----------------------------------------
| UrlChanged Url
| UrlRequested Browser.UrlRequest
type alias Manager =
Model -> ( Model, Cmd Msg )
| true | module Radix exposing (..)
import Browser
import Browser.Navigation as Nav
import CAIP exposing (ChainIdCollection)
import ChainID exposing (ChainID)
import Contact exposing (Contact)
import Dict exposing (Dict)
import Page exposing (Page)
import RemoteData exposing (RemoteData(..))
import Time
import UUID
import Url exposing (Url)
import Webnative
import Webnative.Path as Path exposing (File, Path)
-- ⛩
type alias Flags =
{ seeds : List Int }
-- 🌳
type alias Model =
{ navKey : Nav.Key
, page : Page
, seeds : UUID.Seeds
, url : Url
, userData : UserData
}
-- 🌳 ~ USER DATA
type alias UserData =
{ blockchainIds : RemoteData String ChainIdCollection
, contacts : RemoteData String (List Contact)
, name : Maybe String
}
-- 🌳 ~ PERMISSIONS
appPermissions : Webnative.AppPermissions
appPermissions =
{ creator = "Fission", name = "PI:NAME:<NAME>END_PI" }
fsPermissions : Webnative.FileSystemPermissions
fsPermissions =
{ public =
{ directories = []
, files = []
}
, private =
{ directories = [ Path.directory [ "Documents", "Contacts" ] ]
, files = []
}
}
permissions : Webnative.Permissions
permissions =
{ app = Just appPermissions
, fs = Just fsPermissions
}
contactsPath : Path File
contactsPath =
Path.file [ "Documents", "Contacts", "Library.json" ]
blockchainsPath : Path File
blockchainsPath =
Path.file [ "Documents", "Contacts", "Blockchain Networks.json" ]
-- 📣
type Msg
= Bypassed
-----------------------------------------
-- 🐚
-----------------------------------------
| CopyToClipboard { notification : Maybe String, text : String }
| GetCurrentTimeFor (Time.Posix -> Msg)
| GotWebnativeResponse Webnative.Response
| SignIn
| SignOut
-----------------------------------------
-- Contacts
-----------------------------------------
| AddNewContact Page.NewContext Time.Posix
| GotUpdatedEditContext Page.EditContext
| GotUpdatedIndexContext Page.IndexContext
| GotUpdatedNewContext Page.NewContext
| RemoveContact { index : Int }
| UpdateContact Contact Page.EditContext Time.Posix
-----------------------------------------
-- Routing
-----------------------------------------
| UrlChanged Url
| UrlRequested Browser.UrlRequest
type alias Manager =
Model -> ( Model, Cmd Msg )
| elm |
[
{
"context": " \\() ->\n aggregateScorers [ \"Anna 21\" ]\n |> Expect.equal [ \"Anna (21",
"end": 288,
"score": 0.9996957779,
"start": 284,
"tag": "NAME",
"value": "Anna"
},
{
"context": " [ \"Anna 21\" ]\n |> Expect.equal [ \"Anna (21)\" ]\n , test \"adds brackets to goal tim",
"end": 334,
"score": 0.999576807,
"start": 330,
"tag": "NAME",
"value": "Anna"
},
{
"context": " \\() ->\n aggregateScorers [ \"Anna 13\", \"Lisa 17\" ]\n |> Expect.equal ",
"end": 477,
"score": 0.9997105598,
"start": 473,
"tag": "NAME",
"value": "Anna"
},
{
"context": "->\n aggregateScorers [ \"Anna 13\", \"Lisa 17\" ]\n |> Expect.equal [ \"Anna (13",
"end": 488,
"score": 0.9986118078,
"start": 484,
"tag": "NAME",
"value": "Lisa"
},
{
"context": "\", \"Lisa 17\" ]\n |> Expect.equal [ \"Anna (13)\", \"Lisa (17)\" ] \n , test \"adds comma",
"end": 534,
"score": 0.9995595813,
"start": 530,
"tag": "NAME",
"value": "Anna"
},
{
"context": "\n |> Expect.equal [ \"Anna (13)\", \"Lisa (17)\" ] \n , test \"adds comma separated go",
"end": 547,
"score": 0.8970066905,
"start": 544,
"tag": "NAME",
"value": "isa"
},
{
"context": " \\() ->\n aggregateScorers [ \"Anna 28\", \"Anna 32\" ]\n |> Expect.equal ",
"end": 691,
"score": 0.999750793,
"start": 687,
"tag": "NAME",
"value": "Anna"
},
{
"context": "->\n aggregateScorers [ \"Anna 28\", \"Anna 32\" ]\n |> Expect.equal [ \"Anna (28",
"end": 702,
"score": 0.9995992184,
"start": 698,
"tag": "NAME",
"value": "Anna"
},
{
"context": "\", \"Anna 32\" ]\n |> Expect.equal [ \"Anna (28, 32)\" ] \n , test \"o",
"end": 748,
"score": 0.9995878935,
"start": 744,
"tag": "NAME",
"value": "Anna"
},
{
"context": " \\() ->\n aggregateScorers [ \"Lisa 43\", \"Anna 47\" ]\n |> Expect.equal ",
"end": 882,
"score": 0.9992212057,
"start": 878,
"tag": "NAME",
"value": "Lisa"
},
{
"context": "->\n aggregateScorers [ \"Lisa 43\", \"Anna 47\" ]\n |> Expect.equal [ \"Anna (47",
"end": 893,
"score": 0.9995766878,
"start": 889,
"tag": "NAME",
"value": "Anna"
},
{
"context": "\", \"Anna 47\" ]\n |> Expect.equal [ \"Anna (47)\", \"Lisa (43)\" ] \n , test \"adds comma",
"end": 939,
"score": 0.999563992,
"start": 935,
"tag": "NAME",
"value": "Anna"
},
{
"context": "]\n |> Expect.equal [ \"Anna (47)\", \"Lisa (43)\" ] \n , test \"adds comma separated go",
"end": 952,
"score": 0.9629492164,
"start": 948,
"tag": "NAME",
"value": "Lisa"
},
{
"context": " \\() ->\n aggregateScorers [ \"Lisa 76\", \"Anna 78\", \"Anna 82\" ]\n |> Ex",
"end": 1117,
"score": 0.9994036555,
"start": 1113,
"tag": "NAME",
"value": "Lisa"
},
{
"context": "->\n aggregateScorers [ \"Lisa 76\", \"Anna 78\", \"Anna 82\" ]\n |> Expect.equal ",
"end": 1128,
"score": 0.9997127056,
"start": 1124,
"tag": "NAME",
"value": "Anna"
},
{
"context": " aggregateScorers [ \"Lisa 76\", \"Anna 78\", \"Anna 82\" ]\n |> Expect.equal [ \"Anna (78",
"end": 1139,
"score": 0.9994179606,
"start": 1135,
"tag": "NAME",
"value": "Anna"
},
{
"context": "\", \"Anna 82\" ]\n |> Expect.equal [ \"Anna (78, 82)\", \"Lisa (76)\" ] \n ",
"end": 1185,
"score": 0.9995859861,
"start": 1181,
"tag": "NAME",
"value": "Anna"
},
{
"context": " |> Expect.equal [ \"Anna (78, 82)\", \"Lisa (76)\" ] \n ]\n",
"end": 1202,
"score": 0.9817227721,
"start": 1198,
"tag": "NAME",
"value": "Lisa"
}
] | exercises/elm-2-a/tests/Tests.elm | ee7/exercism-research_experiment_1 | 8 | module Tests exposing (tests)
import Expect
import AggregateScorers exposing (..)
import Test exposing (..)
tests : Test
tests =
describe "AggregateScorers"
[ test "adds brackets to goal time for single scorer" <|
\() ->
aggregateScorers [ "Anna 21" ]
|> Expect.equal [ "Anna (21)" ]
, test "adds brackets to goal time for multiple unique scorers" <|
\() ->
aggregateScorers [ "Anna 13", "Lisa 17" ]
|> Expect.equal [ "Anna (13)", "Lisa (17)" ]
, test "adds comma separated goal times for duplicate scorers" <|
\() ->
aggregateScorers [ "Anna 28", "Anna 32" ]
|> Expect.equal [ "Anna (28, 32)" ]
, test "orders alphabetically" <|
\() ->
aggregateScorers [ "Lisa 43", "Anna 47" ]
|> Expect.equal [ "Anna (47)", "Lisa (43)" ]
, test "adds comma separated goal times for duplicates and maintain single scorers" <|
\() ->
aggregateScorers [ "Lisa 76", "Anna 78", "Anna 82" ]
|> Expect.equal [ "Anna (78, 82)", "Lisa (76)" ]
]
| 40727 | module Tests exposing (tests)
import Expect
import AggregateScorers exposing (..)
import Test exposing (..)
tests : Test
tests =
describe "AggregateScorers"
[ test "adds brackets to goal time for single scorer" <|
\() ->
aggregateScorers [ "<NAME> 21" ]
|> Expect.equal [ "<NAME> (21)" ]
, test "adds brackets to goal time for multiple unique scorers" <|
\() ->
aggregateScorers [ "<NAME> 13", "<NAME> 17" ]
|> Expect.equal [ "<NAME> (13)", "L<NAME> (17)" ]
, test "adds comma separated goal times for duplicate scorers" <|
\() ->
aggregateScorers [ "<NAME> 28", "<NAME> 32" ]
|> Expect.equal [ "<NAME> (28, 32)" ]
, test "orders alphabetically" <|
\() ->
aggregateScorers [ "<NAME> 43", "<NAME> 47" ]
|> Expect.equal [ "<NAME> (47)", "<NAME> (43)" ]
, test "adds comma separated goal times for duplicates and maintain single scorers" <|
\() ->
aggregateScorers [ "<NAME> 76", "<NAME> 78", "<NAME> 82" ]
|> Expect.equal [ "<NAME> (78, 82)", "<NAME> (76)" ]
]
| true | module Tests exposing (tests)
import Expect
import AggregateScorers exposing (..)
import Test exposing (..)
tests : Test
tests =
describe "AggregateScorers"
[ test "adds brackets to goal time for single scorer" <|
\() ->
aggregateScorers [ "PI:NAME:<NAME>END_PI 21" ]
|> Expect.equal [ "PI:NAME:<NAME>END_PI (21)" ]
, test "adds brackets to goal time for multiple unique scorers" <|
\() ->
aggregateScorers [ "PI:NAME:<NAME>END_PI 13", "PI:NAME:<NAME>END_PI 17" ]
|> Expect.equal [ "PI:NAME:<NAME>END_PI (13)", "LPI:NAME:<NAME>END_PI (17)" ]
, test "adds comma separated goal times for duplicate scorers" <|
\() ->
aggregateScorers [ "PI:NAME:<NAME>END_PI 28", "PI:NAME:<NAME>END_PI 32" ]
|> Expect.equal [ "PI:NAME:<NAME>END_PI (28, 32)" ]
, test "orders alphabetically" <|
\() ->
aggregateScorers [ "PI:NAME:<NAME>END_PI 43", "PI:NAME:<NAME>END_PI 47" ]
|> Expect.equal [ "PI:NAME:<NAME>END_PI (47)", "PI:NAME:<NAME>END_PI (43)" ]
, test "adds comma separated goal times for duplicates and maintain single scorers" <|
\() ->
aggregateScorers [ "PI:NAME:<NAME>END_PI 76", "PI:NAME:<NAME>END_PI 78", "PI:NAME:<NAME>END_PI 82" ]
|> Expect.equal [ "PI:NAME:<NAME>END_PI (78, 82)", "PI:NAME:<NAME>END_PI (76)" ]
]
| elm |
[
{
"context": " , Animator.event (Animator.seconds 1) Griffyndor\n , Animator.wait (Animator.sec",
"end": 1022,
"score": 0.7936178446,
"start": 1012,
"tag": "NAME",
"value": "Griffyndor"
},
{
"context": " , Animator.event (Animator.seconds 1) Slytherin\n , Animator.wait (Animator.sec",
"end": 1147,
"score": 0.7740617394,
"start": 1138,
"tag": "NAME",
"value": "Slytherin"
},
{
"context": " , Animator.event (Animator.seconds 1) Ravenclaw\n , Animator.wait (Animator.sec",
"end": 1272,
"score": 0.6151719689,
"start": 1263,
"tag": "NAME",
"value": "Ravenclaw"
},
{
"context": "Griffyndor ->\n Animator.at 400\n\n Slytherin ->\n Animator.at 700\n\n Ravenclaw",
"end": 11693,
"score": 0.9597212076,
"start": 11684,
"tag": "NAME",
"value": "Slytherin"
},
{
"context": " Slytherin ->\n Animator.at 700\n\n Ravenclaw ->\n Animator.at 1000\n\n\nbaseSpline =\n ",
"end": 11743,
"score": 0.9626668692,
"start": 11734,
"tag": "NAME",
"value": "Ravenclaw"
}
] | benchmarks/Benchmarks.elm | elm-review-bot/elm-animator | 0 | module Benchmarks exposing (suite)
import Animator
import Animator.Css
import Animator.Css2
import Array
import Benchmark exposing (..)
import Benchmark.Runner exposing (BenchmarkProgram, program)
import Internal.Bezier as Bezier
import Internal.Css as Css
import Internal.Css.Props
import Internal.Interpolate as Interpolate
import Internal.Spring as Spring
import Internal.Time as Time
import Internal.Timeline as Timeline
import Pixels
import Random
import Time
suite =
Benchmark.describe "Animator benchmarks"
[ -- springs
-- , randomness
-- , basicInterpolation
-- , floatComparison
-- , interpolationComponents
-- foldp
-- equalityCompare
cssGeneration
-- stringifying
]
foldp =
let
timeline =
Animator.init Hufflepuff
|> Animator.queue
[ Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Griffyndor
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Slytherin
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Ravenclaw
, Animator.wait (Animator.seconds 1)
]
|> Timeline.update (Time.millisToPosix 0)
|> Timeline.update (Time.millisToPosix 1400)
in
describe "foldp"
[ benchmark "new foldp" <|
\_ ->
Timeline.foldp
identity
{ start =
\_ ->
Hufflepuff
, dwellPeriod = \_ -> Nothing
, adjustor =
\_ ->
Timeline.linearDefault
, visit =
\lookup target targetTime maybeLookAhead state ->
Timeline.getEvent target
, lerp =
\_ maybePrevious target _ _ _ state ->
target
}
timeline
, benchmark "new all foldp" <|
\_ ->
Timeline.foldpAll
identity
{ start =
\_ ->
Hufflepuff
, dwellPeriod = \_ -> Nothing
, adjustor =
\_ ->
Timeline.linearDefault
, visit =
\lookup target targetTime maybeLookAhead state ->
Timeline.getEvent target
, lerp =
\_ maybePrevious target _ _ _ state ->
target
}
timeline
, benchmark "old foldp" <|
\_ ->
Timeline.foldpOld
identity
{ start =
\_ ->
Hufflepuff
, dwellPeriod = \_ -> Nothing
, adjustor =
\_ ->
Timeline.linearDefault
, visit =
\lookup target targetTime maybeLookAhead state ->
Timeline.getEvent target
, lerp =
\_ maybePrevious target _ _ _ state ->
target
}
timeline
, benchmark "Visit" <|
\_ ->
Interpolate.visit identity
(Timeline.Occurring (Interpolate.Pos Interpolate.standardDefault 20) (Time.millis 100) (Time.millis 900))
(Time.millis 500)
Nothing
{ position = Pixels.pixels 0
, velocity = Pixels.pixelsPerSecond 0
}
]
springs : Benchmark
springs =
let
steps =
List.repeat 0 20
in
describe "Springs"
[ benchmark "stepwise - 100 steps" <|
\_ ->
Spring.stepOver (Animator.millis (16 * 20))
{ stiffness = 180
, damping = 12
, mass = 1
}
300
{ velocity = 0
, position = 0
}
, benchmark "Analytical measure" <|
\_ ->
Spring.analytical
{ stiffness = 180
, damping = 12
, mass = 1
}
(Animator.millis (16 * 20))
300
{ velocity = 0
, position = 0
}
, benchmark "presolved differential equation" <|
\_ ->
let
t =
0.5
in
-- if you provide f(0) = 0; f'(0) = 0; f''(t) = -180(f(t) - 1) - 12f'(t) as input
-- this is the differential equation from wolfram alpha
-- f(t) = -1/2 e^(-6 t) (-2 e^(6 t) + sin(12 t) + 2 cos(12 t))
(-1 / 2 * e ^ (-6 * t)) * ((-2 * e ^ (6 * t)) + sin (12 * t) + 2 * cos (12 * t))
]
fract x =
x - toFloat (floor x)
{-| -}
randomness : Benchmark
randomness =
describe "Random number generator"
[ benchmark "elm/random - random float" <|
\_ ->
Random.initialSeed 8675309
|> Random.step (Random.float 0 1)
|> Tuple.first
, benchmark "scaled sine method" <|
-- learned this approach from https://thebookofshaders.com/10/
-- super cool!
-- and turns out 32x faster than elm/random
-- though elm/random has a much nicer distribution
\_ ->
let
seed =
8675309
in
(fract (sin seed * 100000.0) + 1.5707) / 3.1415
]
beforeMinus : Float -> Float -> Bool
beforeMinus one two =
(one - two) < 0
before : Float -> Float -> Bool
before one two =
one < two
timeOne =
Time.absolute (Time.millisToPosix 0)
timeTwo =
Time.absolute (Time.millisToPosix 500)
stringifying : Benchmark
stringifying =
let
point =
{ x = 893213.3
, y = 84923.3
}
x =
84923
bez =
Bezier.Spline point point point point
in
describe "Stringifying numbers"
[ benchmark "Bezier, convert each number to string" <|
\_ ->
Bezier.hash bez
, benchmark "Bezier, convert only one" <|
\_ ->
String.fromInt x
]
batman =
"batman"
superman =
"superman"
eightySeven =
87
twentythree =
23
equalityCompare : Benchmark
equalityCompare =
describe "Comparing equality checks for primitives"
[ benchmark "Strings equal" <|
\_ ->
batman == superman
, benchmark "Ints" <|
\_ ->
eightySeven == twentythree
, benchmark "Ints w/0 trick" <|
\_ ->
eightySeven - twentythree == 0
]
floatComparison : Benchmark
floatComparison =
describe "Comparing Floats"
[ benchmark "Standard" <|
\_ ->
before 5 20
, benchmark "(one - two) < 0 form" <|
\_ ->
beforeMinus 5 20
]
{-| -}
basicInterpolation : Benchmark
basicInterpolation =
let
timeline =
Animator.init Hufflepuff
|> Animator.queue
[ Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Griffyndor
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Slytherin
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Ravenclaw
, Animator.wait (Animator.seconds 1)
]
|> Timeline.update (Time.millisToPosix 0)
|> Timeline.update (Time.millisToPosix 1400)
in
describe "Interpolate to a point on a 4 event timeline"
[ benchmark "interpolate to position" <|
\_ ->
Interpolate.details timeline
(Interpolate.withStandardDefault << toPos)
, benchmark "capture frames(60fps)" <|
\_ ->
Timeline.capture 60
(Interpolate.withStandardDefault << toPos)
Interpolate.moving
timeline
, benchmark "capture frames(15fps)" <|
\_ ->
Timeline.capture 15
(Interpolate.withStandardDefault << toPos)
Interpolate.moving
timeline
]
cssGeneration =
let
timeline =
Animator.init Hufflepuff
|> Animator.queue
[ Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Griffyndor
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Slytherin
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Ravenclaw
, Animator.wait (Animator.seconds 1)
]
|> Timeline.update (Time.millisToPosix 0)
|> Timeline.update (Time.millisToPosix 1400)
in
describe "Css generation:4 event timeline"
[ benchmark "capture frames, 60fps, (old)" <|
\_ ->
Timeline.capture 60
(Interpolate.withStandardDefault << toPos)
Interpolate.moving
timeline
, benchmark "capture frames, 15fps, (old)" <|
\_ ->
Timeline.capture 15
(Interpolate.withStandardDefault << toPos)
Interpolate.moving
timeline
, benchmark "bezier-generation (new)" <|
\_ ->
Css.cssFromProps
timeline
toProps
]
toProps event =
-- let
-- base = toFloat state * 100
-- in
-- -- Interpolate.Pos Interpolate.standardDefault (toFloat (state * 100))
-- [ Css.Prop Internal.Css.Props.ids.opacity
-- (wave (Timeline.Repeat 5 (Animator.millis 200)) base (base + 100))
-- ]
case event of
Hufflepuff ->
[ Animator.Css2.opacity
(Animator.at 100)
]
Griffyndor ->
-- pos 400
[ Animator.Css2.opacity
(Animator.at 400)
]
Slytherin ->
-- pos 700
[ Animator.Css2.opacity
(Animator.at 700)
]
Ravenclaw ->
-- pos 1000
[ Animator.Css2.opacity
(Animator.at 1000)
]
pos state =
Interpolate.Pos Interpolate.standardDefault state
type House
= Hufflepuff
| Griffyndor
| Slytherin
| Ravenclaw
toPos event =
case event of
Hufflepuff ->
Animator.at 100
Griffyndor ->
Animator.at 400
Slytherin ->
Animator.at 700
Ravenclaw ->
Animator.at 1000
baseSpline =
Interpolate.createSpline
{ start =
{ x = 0
, y = 2
}
, startVelocity =
{ x = 1000
, y = 250
}
, departure =
Interpolate.standardDefault
, end =
{ x = 1000
, y = 1000
}
, endVelocity =
{ x = 1000
, y = 0
}
, arrival =
Interpolate.standardDefault
}
interpolationComponents =
describe "Interpolation"
[ benchmark "Create spline" <|
\_ ->
Interpolate.createSpline
{ start =
{ x = 0
, y = 2
}
, startVelocity =
{ x = 1000
, y = 250
}
, departure =
Interpolate.standardDefault
, end =
{ x = 1000
, y = 1000
}
, endVelocity =
{ x = 1000
, y = 0
}
, arrival =
Interpolate.standardDefault
}
, benchmark "Find x on spline" <|
\_ ->
Bezier.atX baseSpline 625
]
| 41077 | module Benchmarks exposing (suite)
import Animator
import Animator.Css
import Animator.Css2
import Array
import Benchmark exposing (..)
import Benchmark.Runner exposing (BenchmarkProgram, program)
import Internal.Bezier as Bezier
import Internal.Css as Css
import Internal.Css.Props
import Internal.Interpolate as Interpolate
import Internal.Spring as Spring
import Internal.Time as Time
import Internal.Timeline as Timeline
import Pixels
import Random
import Time
suite =
Benchmark.describe "Animator benchmarks"
[ -- springs
-- , randomness
-- , basicInterpolation
-- , floatComparison
-- , interpolationComponents
-- foldp
-- equalityCompare
cssGeneration
-- stringifying
]
foldp =
let
timeline =
Animator.init Hufflepuff
|> Animator.queue
[ Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) <NAME>
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) <NAME>
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) <NAME>
, Animator.wait (Animator.seconds 1)
]
|> Timeline.update (Time.millisToPosix 0)
|> Timeline.update (Time.millisToPosix 1400)
in
describe "foldp"
[ benchmark "new foldp" <|
\_ ->
Timeline.foldp
identity
{ start =
\_ ->
Hufflepuff
, dwellPeriod = \_ -> Nothing
, adjustor =
\_ ->
Timeline.linearDefault
, visit =
\lookup target targetTime maybeLookAhead state ->
Timeline.getEvent target
, lerp =
\_ maybePrevious target _ _ _ state ->
target
}
timeline
, benchmark "new all foldp" <|
\_ ->
Timeline.foldpAll
identity
{ start =
\_ ->
Hufflepuff
, dwellPeriod = \_ -> Nothing
, adjustor =
\_ ->
Timeline.linearDefault
, visit =
\lookup target targetTime maybeLookAhead state ->
Timeline.getEvent target
, lerp =
\_ maybePrevious target _ _ _ state ->
target
}
timeline
, benchmark "old foldp" <|
\_ ->
Timeline.foldpOld
identity
{ start =
\_ ->
Hufflepuff
, dwellPeriod = \_ -> Nothing
, adjustor =
\_ ->
Timeline.linearDefault
, visit =
\lookup target targetTime maybeLookAhead state ->
Timeline.getEvent target
, lerp =
\_ maybePrevious target _ _ _ state ->
target
}
timeline
, benchmark "Visit" <|
\_ ->
Interpolate.visit identity
(Timeline.Occurring (Interpolate.Pos Interpolate.standardDefault 20) (Time.millis 100) (Time.millis 900))
(Time.millis 500)
Nothing
{ position = Pixels.pixels 0
, velocity = Pixels.pixelsPerSecond 0
}
]
springs : Benchmark
springs =
let
steps =
List.repeat 0 20
in
describe "Springs"
[ benchmark "stepwise - 100 steps" <|
\_ ->
Spring.stepOver (Animator.millis (16 * 20))
{ stiffness = 180
, damping = 12
, mass = 1
}
300
{ velocity = 0
, position = 0
}
, benchmark "Analytical measure" <|
\_ ->
Spring.analytical
{ stiffness = 180
, damping = 12
, mass = 1
}
(Animator.millis (16 * 20))
300
{ velocity = 0
, position = 0
}
, benchmark "presolved differential equation" <|
\_ ->
let
t =
0.5
in
-- if you provide f(0) = 0; f'(0) = 0; f''(t) = -180(f(t) - 1) - 12f'(t) as input
-- this is the differential equation from wolfram alpha
-- f(t) = -1/2 e^(-6 t) (-2 e^(6 t) + sin(12 t) + 2 cos(12 t))
(-1 / 2 * e ^ (-6 * t)) * ((-2 * e ^ (6 * t)) + sin (12 * t) + 2 * cos (12 * t))
]
fract x =
x - toFloat (floor x)
{-| -}
randomness : Benchmark
randomness =
describe "Random number generator"
[ benchmark "elm/random - random float" <|
\_ ->
Random.initialSeed 8675309
|> Random.step (Random.float 0 1)
|> Tuple.first
, benchmark "scaled sine method" <|
-- learned this approach from https://thebookofshaders.com/10/
-- super cool!
-- and turns out 32x faster than elm/random
-- though elm/random has a much nicer distribution
\_ ->
let
seed =
8675309
in
(fract (sin seed * 100000.0) + 1.5707) / 3.1415
]
beforeMinus : Float -> Float -> Bool
beforeMinus one two =
(one - two) < 0
before : Float -> Float -> Bool
before one two =
one < two
timeOne =
Time.absolute (Time.millisToPosix 0)
timeTwo =
Time.absolute (Time.millisToPosix 500)
stringifying : Benchmark
stringifying =
let
point =
{ x = 893213.3
, y = 84923.3
}
x =
84923
bez =
Bezier.Spline point point point point
in
describe "Stringifying numbers"
[ benchmark "Bezier, convert each number to string" <|
\_ ->
Bezier.hash bez
, benchmark "Bezier, convert only one" <|
\_ ->
String.fromInt x
]
batman =
"batman"
superman =
"superman"
eightySeven =
87
twentythree =
23
equalityCompare : Benchmark
equalityCompare =
describe "Comparing equality checks for primitives"
[ benchmark "Strings equal" <|
\_ ->
batman == superman
, benchmark "Ints" <|
\_ ->
eightySeven == twentythree
, benchmark "Ints w/0 trick" <|
\_ ->
eightySeven - twentythree == 0
]
floatComparison : Benchmark
floatComparison =
describe "Comparing Floats"
[ benchmark "Standard" <|
\_ ->
before 5 20
, benchmark "(one - two) < 0 form" <|
\_ ->
beforeMinus 5 20
]
{-| -}
basicInterpolation : Benchmark
basicInterpolation =
let
timeline =
Animator.init Hufflepuff
|> Animator.queue
[ Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Griffyndor
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Slytherin
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Ravenclaw
, Animator.wait (Animator.seconds 1)
]
|> Timeline.update (Time.millisToPosix 0)
|> Timeline.update (Time.millisToPosix 1400)
in
describe "Interpolate to a point on a 4 event timeline"
[ benchmark "interpolate to position" <|
\_ ->
Interpolate.details timeline
(Interpolate.withStandardDefault << toPos)
, benchmark "capture frames(60fps)" <|
\_ ->
Timeline.capture 60
(Interpolate.withStandardDefault << toPos)
Interpolate.moving
timeline
, benchmark "capture frames(15fps)" <|
\_ ->
Timeline.capture 15
(Interpolate.withStandardDefault << toPos)
Interpolate.moving
timeline
]
cssGeneration =
let
timeline =
Animator.init Hufflepuff
|> Animator.queue
[ Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Griffyndor
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Slytherin
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Ravenclaw
, Animator.wait (Animator.seconds 1)
]
|> Timeline.update (Time.millisToPosix 0)
|> Timeline.update (Time.millisToPosix 1400)
in
describe "Css generation:4 event timeline"
[ benchmark "capture frames, 60fps, (old)" <|
\_ ->
Timeline.capture 60
(Interpolate.withStandardDefault << toPos)
Interpolate.moving
timeline
, benchmark "capture frames, 15fps, (old)" <|
\_ ->
Timeline.capture 15
(Interpolate.withStandardDefault << toPos)
Interpolate.moving
timeline
, benchmark "bezier-generation (new)" <|
\_ ->
Css.cssFromProps
timeline
toProps
]
toProps event =
-- let
-- base = toFloat state * 100
-- in
-- -- Interpolate.Pos Interpolate.standardDefault (toFloat (state * 100))
-- [ Css.Prop Internal.Css.Props.ids.opacity
-- (wave (Timeline.Repeat 5 (Animator.millis 200)) base (base + 100))
-- ]
case event of
Hufflepuff ->
[ Animator.Css2.opacity
(Animator.at 100)
]
Griffyndor ->
-- pos 400
[ Animator.Css2.opacity
(Animator.at 400)
]
Slytherin ->
-- pos 700
[ Animator.Css2.opacity
(Animator.at 700)
]
Ravenclaw ->
-- pos 1000
[ Animator.Css2.opacity
(Animator.at 1000)
]
pos state =
Interpolate.Pos Interpolate.standardDefault state
type House
= Hufflepuff
| Griffyndor
| Slytherin
| Ravenclaw
toPos event =
case event of
Hufflepuff ->
Animator.at 100
Griffyndor ->
Animator.at 400
<NAME> ->
Animator.at 700
<NAME> ->
Animator.at 1000
baseSpline =
Interpolate.createSpline
{ start =
{ x = 0
, y = 2
}
, startVelocity =
{ x = 1000
, y = 250
}
, departure =
Interpolate.standardDefault
, end =
{ x = 1000
, y = 1000
}
, endVelocity =
{ x = 1000
, y = 0
}
, arrival =
Interpolate.standardDefault
}
interpolationComponents =
describe "Interpolation"
[ benchmark "Create spline" <|
\_ ->
Interpolate.createSpline
{ start =
{ x = 0
, y = 2
}
, startVelocity =
{ x = 1000
, y = 250
}
, departure =
Interpolate.standardDefault
, end =
{ x = 1000
, y = 1000
}
, endVelocity =
{ x = 1000
, y = 0
}
, arrival =
Interpolate.standardDefault
}
, benchmark "Find x on spline" <|
\_ ->
Bezier.atX baseSpline 625
]
| true | module Benchmarks exposing (suite)
import Animator
import Animator.Css
import Animator.Css2
import Array
import Benchmark exposing (..)
import Benchmark.Runner exposing (BenchmarkProgram, program)
import Internal.Bezier as Bezier
import Internal.Css as Css
import Internal.Css.Props
import Internal.Interpolate as Interpolate
import Internal.Spring as Spring
import Internal.Time as Time
import Internal.Timeline as Timeline
import Pixels
import Random
import Time
suite =
Benchmark.describe "Animator benchmarks"
[ -- springs
-- , randomness
-- , basicInterpolation
-- , floatComparison
-- , interpolationComponents
-- foldp
-- equalityCompare
cssGeneration
-- stringifying
]
foldp =
let
timeline =
Animator.init Hufflepuff
|> Animator.queue
[ Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) PI:NAME:<NAME>END_PI
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) PI:NAME:<NAME>END_PI
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) PI:NAME:<NAME>END_PI
, Animator.wait (Animator.seconds 1)
]
|> Timeline.update (Time.millisToPosix 0)
|> Timeline.update (Time.millisToPosix 1400)
in
describe "foldp"
[ benchmark "new foldp" <|
\_ ->
Timeline.foldp
identity
{ start =
\_ ->
Hufflepuff
, dwellPeriod = \_ -> Nothing
, adjustor =
\_ ->
Timeline.linearDefault
, visit =
\lookup target targetTime maybeLookAhead state ->
Timeline.getEvent target
, lerp =
\_ maybePrevious target _ _ _ state ->
target
}
timeline
, benchmark "new all foldp" <|
\_ ->
Timeline.foldpAll
identity
{ start =
\_ ->
Hufflepuff
, dwellPeriod = \_ -> Nothing
, adjustor =
\_ ->
Timeline.linearDefault
, visit =
\lookup target targetTime maybeLookAhead state ->
Timeline.getEvent target
, lerp =
\_ maybePrevious target _ _ _ state ->
target
}
timeline
, benchmark "old foldp" <|
\_ ->
Timeline.foldpOld
identity
{ start =
\_ ->
Hufflepuff
, dwellPeriod = \_ -> Nothing
, adjustor =
\_ ->
Timeline.linearDefault
, visit =
\lookup target targetTime maybeLookAhead state ->
Timeline.getEvent target
, lerp =
\_ maybePrevious target _ _ _ state ->
target
}
timeline
, benchmark "Visit" <|
\_ ->
Interpolate.visit identity
(Timeline.Occurring (Interpolate.Pos Interpolate.standardDefault 20) (Time.millis 100) (Time.millis 900))
(Time.millis 500)
Nothing
{ position = Pixels.pixels 0
, velocity = Pixels.pixelsPerSecond 0
}
]
springs : Benchmark
springs =
let
steps =
List.repeat 0 20
in
describe "Springs"
[ benchmark "stepwise - 100 steps" <|
\_ ->
Spring.stepOver (Animator.millis (16 * 20))
{ stiffness = 180
, damping = 12
, mass = 1
}
300
{ velocity = 0
, position = 0
}
, benchmark "Analytical measure" <|
\_ ->
Spring.analytical
{ stiffness = 180
, damping = 12
, mass = 1
}
(Animator.millis (16 * 20))
300
{ velocity = 0
, position = 0
}
, benchmark "presolved differential equation" <|
\_ ->
let
t =
0.5
in
-- if you provide f(0) = 0; f'(0) = 0; f''(t) = -180(f(t) - 1) - 12f'(t) as input
-- this is the differential equation from wolfram alpha
-- f(t) = -1/2 e^(-6 t) (-2 e^(6 t) + sin(12 t) + 2 cos(12 t))
(-1 / 2 * e ^ (-6 * t)) * ((-2 * e ^ (6 * t)) + sin (12 * t) + 2 * cos (12 * t))
]
fract x =
x - toFloat (floor x)
{-| -}
randomness : Benchmark
randomness =
describe "Random number generator"
[ benchmark "elm/random - random float" <|
\_ ->
Random.initialSeed 8675309
|> Random.step (Random.float 0 1)
|> Tuple.first
, benchmark "scaled sine method" <|
-- learned this approach from https://thebookofshaders.com/10/
-- super cool!
-- and turns out 32x faster than elm/random
-- though elm/random has a much nicer distribution
\_ ->
let
seed =
8675309
in
(fract (sin seed * 100000.0) + 1.5707) / 3.1415
]
beforeMinus : Float -> Float -> Bool
beforeMinus one two =
(one - two) < 0
before : Float -> Float -> Bool
before one two =
one < two
timeOne =
Time.absolute (Time.millisToPosix 0)
timeTwo =
Time.absolute (Time.millisToPosix 500)
stringifying : Benchmark
stringifying =
let
point =
{ x = 893213.3
, y = 84923.3
}
x =
84923
bez =
Bezier.Spline point point point point
in
describe "Stringifying numbers"
[ benchmark "Bezier, convert each number to string" <|
\_ ->
Bezier.hash bez
, benchmark "Bezier, convert only one" <|
\_ ->
String.fromInt x
]
batman =
"batman"
superman =
"superman"
eightySeven =
87
twentythree =
23
equalityCompare : Benchmark
equalityCompare =
describe "Comparing equality checks for primitives"
[ benchmark "Strings equal" <|
\_ ->
batman == superman
, benchmark "Ints" <|
\_ ->
eightySeven == twentythree
, benchmark "Ints w/0 trick" <|
\_ ->
eightySeven - twentythree == 0
]
floatComparison : Benchmark
floatComparison =
describe "Comparing Floats"
[ benchmark "Standard" <|
\_ ->
before 5 20
, benchmark "(one - two) < 0 form" <|
\_ ->
beforeMinus 5 20
]
{-| -}
basicInterpolation : Benchmark
basicInterpolation =
let
timeline =
Animator.init Hufflepuff
|> Animator.queue
[ Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Griffyndor
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Slytherin
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Ravenclaw
, Animator.wait (Animator.seconds 1)
]
|> Timeline.update (Time.millisToPosix 0)
|> Timeline.update (Time.millisToPosix 1400)
in
describe "Interpolate to a point on a 4 event timeline"
[ benchmark "interpolate to position" <|
\_ ->
Interpolate.details timeline
(Interpolate.withStandardDefault << toPos)
, benchmark "capture frames(60fps)" <|
\_ ->
Timeline.capture 60
(Interpolate.withStandardDefault << toPos)
Interpolate.moving
timeline
, benchmark "capture frames(15fps)" <|
\_ ->
Timeline.capture 15
(Interpolate.withStandardDefault << toPos)
Interpolate.moving
timeline
]
cssGeneration =
let
timeline =
Animator.init Hufflepuff
|> Animator.queue
[ Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Griffyndor
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Slytherin
, Animator.wait (Animator.seconds 1)
, Animator.event (Animator.seconds 1) Ravenclaw
, Animator.wait (Animator.seconds 1)
]
|> Timeline.update (Time.millisToPosix 0)
|> Timeline.update (Time.millisToPosix 1400)
in
describe "Css generation:4 event timeline"
[ benchmark "capture frames, 60fps, (old)" <|
\_ ->
Timeline.capture 60
(Interpolate.withStandardDefault << toPos)
Interpolate.moving
timeline
, benchmark "capture frames, 15fps, (old)" <|
\_ ->
Timeline.capture 15
(Interpolate.withStandardDefault << toPos)
Interpolate.moving
timeline
, benchmark "bezier-generation (new)" <|
\_ ->
Css.cssFromProps
timeline
toProps
]
toProps event =
-- let
-- base = toFloat state * 100
-- in
-- -- Interpolate.Pos Interpolate.standardDefault (toFloat (state * 100))
-- [ Css.Prop Internal.Css.Props.ids.opacity
-- (wave (Timeline.Repeat 5 (Animator.millis 200)) base (base + 100))
-- ]
case event of
Hufflepuff ->
[ Animator.Css2.opacity
(Animator.at 100)
]
Griffyndor ->
-- pos 400
[ Animator.Css2.opacity
(Animator.at 400)
]
Slytherin ->
-- pos 700
[ Animator.Css2.opacity
(Animator.at 700)
]
Ravenclaw ->
-- pos 1000
[ Animator.Css2.opacity
(Animator.at 1000)
]
pos state =
Interpolate.Pos Interpolate.standardDefault state
type House
= Hufflepuff
| Griffyndor
| Slytherin
| Ravenclaw
toPos event =
case event of
Hufflepuff ->
Animator.at 100
Griffyndor ->
Animator.at 400
PI:NAME:<NAME>END_PI ->
Animator.at 700
PI:NAME:<NAME>END_PI ->
Animator.at 1000
baseSpline =
Interpolate.createSpline
{ start =
{ x = 0
, y = 2
}
, startVelocity =
{ x = 1000
, y = 250
}
, departure =
Interpolate.standardDefault
, end =
{ x = 1000
, y = 1000
}
, endVelocity =
{ x = 1000
, y = 0
}
, arrival =
Interpolate.standardDefault
}
interpolationComponents =
describe "Interpolation"
[ benchmark "Create spline" <|
\_ ->
Interpolate.createSpline
{ start =
{ x = 0
, y = 2
}
, startVelocity =
{ x = 1000
, y = 250
}
, departure =
Interpolate.standardDefault
, end =
{ x = 1000
, y = 1000
}
, endVelocity =
{ x = 1000
, y = 0
}
, arrival =
Interpolate.standardDefault
}
, benchmark "Find x on spline" <|
\_ ->
Bezier.atX baseSpline 625
]
| elm |
[
{
"context": "iate/Form.elm)\n * [Todo List](https://github.com/evancz/TodoFRP)\n\nI suspect a lot of this code could be s",
"end": 7346,
"score": 0.9944345355,
"start": 7340,
"tag": "USERNAME",
"value": "evancz"
},
{
"context": "rd entry, etc.\n\n## Thank you!\n\nHuge thank you to [Spiros Eliopoulos](https://github.com/seliopou) whose work\non [elm-",
"end": 7657,
"score": 0.9998759031,
"start": 7640,
"tag": "NAME",
"value": "Spiros Eliopoulos"
},
{
"context": "ank you to [Spiros Eliopoulos](https://github.com/seliopou) whose work\non [elm-d3](https://github.com/seliop",
"end": 7686,
"score": 0.9995679259,
"start": 7678,
"tag": "USERNAME",
"value": "seliopou"
},
{
"context": ") whose work\non [elm-d3](https://github.com/seliopou/elm-d3) led inspired the `signal` field\nof an `In",
"end": 7738,
"score": 0.5303145647,
"start": 7736,
"tag": "USERNAME",
"value": "ou"
},
{
"context": "` field\nof an `Input`. Another huge thank you to [Jeff Smitts](https://github.com/Apanatshka)\nfor talking throu",
"end": 7832,
"score": 0.9998782873,
"start": 7821,
"tag": "NAME",
"value": "Jeff Smitts"
},
{
"context": "https://github.com/Apanatshka)\nfor talking through Spiros's idea with me and inspiring the `handle` field o",
"end": 7891,
"score": 0.6324294209,
"start": 7885,
"tag": "NAME",
"value": "Spiros"
}
] | frontend/public/learn/Interactive-UI-Elements.elm | arsatiki/elm-lang.org | 0 | import Graphics.Input (Input, input, checkbox)
import Website.Skeleton (skeleton)
import Window
port title : String
port title = "Interactive UI Elements"
main = lift2 (skeleton "Learn")
(everything <~ check.signal)
Window.dimensions
check : Input Bool
check = input False
everything : Bool -> Int -> Element
everything isChecked wid =
let w = min 600 wid
box = checkbox check.handle identity isChecked
in flow down
[ width w intro
, container w 30 middle <| flow right [ box, box, box ]
, width w rest
]
intro = [markdown|
<h1><div style="text-align:center">Interactive UI Elements
<div style="padding-top:4px;font-size:0.5em;font-weight:normal">Using text fields, drop downs, buttons, etc.</div></div>
</h1>
Many UI elements are interactive. You can click on them, hover above them, type
into them. In Elm you handle all of these interactions with the
[`Graphics.Input`][gi] library.
At the core of this library is the concept of an `Input`. An `Input` is like a
[port](/learn/Ports.elm) that receives all of its events from the UI. When the
user clicks a button, the event goes to an `Input`. When the user types into a
field, the event goes to an `Input`. I think the best way to really understand
this approach is to see it in action! In this post we will start with an example
and then dive into how it works.
[gi]: http://library.elm-lang.org/catalog/elm-lang-Elm/latest/Graphics-Input
## A Minimal Example
We are going to make three synced checkboxes. Changing one of them will change
the two others:
|]
rest = [markdown|
Here is the code we need to make that happen. Don't worry about the details too
much yet. This is more to get a feel for the API so we know what we are working
towards when we dive into the details:
```haskell
import Graphics.Input (Input, input, checkbox)
check : Input Bool
check = input False
displayBoxes : Bool -> Element
displayBoxes isChecked =
let box = checkbox check.handle identity isChecked
in flow right [ box, box, box ]
main : Signal Element
main = displayBoxes <~ check.signal
```
The key things to notice before we go into the API itself is the `Input` named
`check`. All UI events are going to flow through `check`. It is used twice in
the rest of the code:
1. In `displayBoxes` we create a `box` that we display three times.
The definition of `box` refers to `check.handle` which means that all
`checkbox` events are going to be sent to the `check` input.
2. In `main` we pipe all of the events from the `check` input to our display.
As the user toggles between true and false, these events will guide what
we actually display on screen.
This is a very high level view of how things work, but it illustrates the
typical structure of interactive UI elements in Elm. Let's look at the API
in more detail.
## Inputs
The first thing we do when making an interactive UI element is to create an input:
```haskell
type Input a = { signal : Signal a, handle : Handle a }
```
An `Input` has two distinct parts. One is a `signal` of events coming from UI
elements. In our synced checkbox example, these are boolean values indicating
whether the box should be checked or not. The more subtle part of an `Input` is
the `handle`. All interactive UI elements will latch on to a handle and report
their events to the corresponding `Input`. The handle lets us get events from
the UI back into our program without any messy callbacks or event-listeners.
You create an `Input` with the `input` function, like this:
```haskell
input : a -> Input a
check : Input Bool
check = input False
```
The argument to `input` serves as the default value of the input’s
`signal`. So when we create the `check` input we get:
1. A signal called `check.signal` with the initial value `False`.
2. A handle called `check.handle`. Any UI element can refer to `check.handle`
which would send events to `check.signal`.
Now that we have a way to manage UI events, we need to actually create the
interactive UI elements.
## Interactive UI Elements
There are a bunch of interactive UI elements available in [`Graphics.Input`][gi]
and [`Graphics.Input.Field`][gif] from traditional buttons and drop downs to
functions that can make any `Element` clickable or hoverable. We will focus on
[the `checkbox` function][box] which does a great job illustrating the general
pattern used by interactive UI elements in Elm:
[gi]: http://library.elm-lang.org/catalog/elm-lang-Elm/latest/Graphics-Input
[gif]: http://library.elm-lang.org/catalog/elm-lang-Elm/latest/Graphics-Input-Field
[box]: http://library.elm-lang.org/catalog/elm-lang-Elm/latest/Graphics-Input#checkbox
```haskell
checkbox : Handle a -> (Bool -> a) -> Bool -> Element
checkbox handle processingFunction checked = ...
```
The three arguments work like this:
1. Clicking on a checkbox generates an event, and the handle specifies which
`Input` these events should be sent to. The generated event is a boolean
value that represents what the user *wants* the checkbox to be. Clicking an
unchecked box generates a `True` event, and clicking a checked box generates
a `False` event.
2. A way to process each event before sending it along to the `Input`
specified by the handle. This processing function lets us add
extra information to the event. A common thing to add is an ID to indicate
which checkbox has been clicked, so when there are four check boxes
reporting to the same `Input` we can send events like `(True, 1)` to
indicate that the first box wants to be checked. Adding extra information
is not always necessary, as in our synced checkbox example, so a common
processing function is `id` which passes the boolean value to the
specified `Input` unmodified.
3. The third argument is the actual state of the checkbox: whether it is
checked or not. This means `checkbox` is a [pure function][pure]! Whether
it is checked or not is an argument, so that information must live in the
model, not in the view!
[pure]: http://en.wikipedia.org/wiki/Pure_function
Breaking the concept of a checkbox into an `Input`, a `Handle`, and a `checkbox`
makes the flow of events very explicit. This same pattern is used by all
interactive UI elements, so you will see this again and again as you look at
more examples.
## Tons of Examples
Synced checkboxes are nice for an introductory example, but it is simple because
it really only has an input and a display section. There is not a lot to model
or update. I have created a bunch of examples to illustrate some more complex
situations. Start with the simple examples:
* [Text Fields](/edit/examples/Reactive/TextField.elm)
* [Passwords](/edit/examples/Reactive/Password.elm)
* [Checkboxes](/edit/examples/Reactive/CheckBox.elm)
* [Drop Downs](/edit/examples/Reactive/DropDown.elm)
* [Fields + HTTP](/edit/examples/Reactive/ZipCodes.elm)
* [Filtered Fields](/edit/examples/Reactive/KeepIf.elm)
And then take a look at some more complex examples:
* [Field Reversal](/edit/examples/Intermediate/TextReverse.elm)
* [Calculator](/edit/examples/Intermediate/Calculator.elm)
* [Sign-up Form](/edit/examples/Intermediate/Form.elm)
* [Todo List](https://github.com/evancz/TodoFRP)
I suspect a lot of this code could be shortened, and I hope to see some
libraries spring up in the [Elm Public Library](http://library.elm-lang.org)
to factor out common patterns like form-validation, password verification,
credit-card entry, etc.
## Thank you!
Huge thank you to [Spiros Eliopoulos](https://github.com/seliopou) whose work
on [elm-d3](https://github.com/seliopou/elm-d3) led inspired the `signal` field
of an `Input`. Another huge thank you to [Jeff Smitts](https://github.com/Apanatshka)
for talking through Spiros's idea with me and inspiring the `handle` field of
an `Input`. Finally thanks to everyone on [the mailing list][list] for
discussing and reviewing APIs, docs, and examples as the new UI elements library
came together!
[list]: https://groups.google.com/forum/#!forum/elm-discuss
|]
| 5971 | import Graphics.Input (Input, input, checkbox)
import Website.Skeleton (skeleton)
import Window
port title : String
port title = "Interactive UI Elements"
main = lift2 (skeleton "Learn")
(everything <~ check.signal)
Window.dimensions
check : Input Bool
check = input False
everything : Bool -> Int -> Element
everything isChecked wid =
let w = min 600 wid
box = checkbox check.handle identity isChecked
in flow down
[ width w intro
, container w 30 middle <| flow right [ box, box, box ]
, width w rest
]
intro = [markdown|
<h1><div style="text-align:center">Interactive UI Elements
<div style="padding-top:4px;font-size:0.5em;font-weight:normal">Using text fields, drop downs, buttons, etc.</div></div>
</h1>
Many UI elements are interactive. You can click on them, hover above them, type
into them. In Elm you handle all of these interactions with the
[`Graphics.Input`][gi] library.
At the core of this library is the concept of an `Input`. An `Input` is like a
[port](/learn/Ports.elm) that receives all of its events from the UI. When the
user clicks a button, the event goes to an `Input`. When the user types into a
field, the event goes to an `Input`. I think the best way to really understand
this approach is to see it in action! In this post we will start with an example
and then dive into how it works.
[gi]: http://library.elm-lang.org/catalog/elm-lang-Elm/latest/Graphics-Input
## A Minimal Example
We are going to make three synced checkboxes. Changing one of them will change
the two others:
|]
rest = [markdown|
Here is the code we need to make that happen. Don't worry about the details too
much yet. This is more to get a feel for the API so we know what we are working
towards when we dive into the details:
```haskell
import Graphics.Input (Input, input, checkbox)
check : Input Bool
check = input False
displayBoxes : Bool -> Element
displayBoxes isChecked =
let box = checkbox check.handle identity isChecked
in flow right [ box, box, box ]
main : Signal Element
main = displayBoxes <~ check.signal
```
The key things to notice before we go into the API itself is the `Input` named
`check`. All UI events are going to flow through `check`. It is used twice in
the rest of the code:
1. In `displayBoxes` we create a `box` that we display three times.
The definition of `box` refers to `check.handle` which means that all
`checkbox` events are going to be sent to the `check` input.
2. In `main` we pipe all of the events from the `check` input to our display.
As the user toggles between true and false, these events will guide what
we actually display on screen.
This is a very high level view of how things work, but it illustrates the
typical structure of interactive UI elements in Elm. Let's look at the API
in more detail.
## Inputs
The first thing we do when making an interactive UI element is to create an input:
```haskell
type Input a = { signal : Signal a, handle : Handle a }
```
An `Input` has two distinct parts. One is a `signal` of events coming from UI
elements. In our synced checkbox example, these are boolean values indicating
whether the box should be checked or not. The more subtle part of an `Input` is
the `handle`. All interactive UI elements will latch on to a handle and report
their events to the corresponding `Input`. The handle lets us get events from
the UI back into our program without any messy callbacks or event-listeners.
You create an `Input` with the `input` function, like this:
```haskell
input : a -> Input a
check : Input Bool
check = input False
```
The argument to `input` serves as the default value of the input’s
`signal`. So when we create the `check` input we get:
1. A signal called `check.signal` with the initial value `False`.
2. A handle called `check.handle`. Any UI element can refer to `check.handle`
which would send events to `check.signal`.
Now that we have a way to manage UI events, we need to actually create the
interactive UI elements.
## Interactive UI Elements
There are a bunch of interactive UI elements available in [`Graphics.Input`][gi]
and [`Graphics.Input.Field`][gif] from traditional buttons and drop downs to
functions that can make any `Element` clickable or hoverable. We will focus on
[the `checkbox` function][box] which does a great job illustrating the general
pattern used by interactive UI elements in Elm:
[gi]: http://library.elm-lang.org/catalog/elm-lang-Elm/latest/Graphics-Input
[gif]: http://library.elm-lang.org/catalog/elm-lang-Elm/latest/Graphics-Input-Field
[box]: http://library.elm-lang.org/catalog/elm-lang-Elm/latest/Graphics-Input#checkbox
```haskell
checkbox : Handle a -> (Bool -> a) -> Bool -> Element
checkbox handle processingFunction checked = ...
```
The three arguments work like this:
1. Clicking on a checkbox generates an event, and the handle specifies which
`Input` these events should be sent to. The generated event is a boolean
value that represents what the user *wants* the checkbox to be. Clicking an
unchecked box generates a `True` event, and clicking a checked box generates
a `False` event.
2. A way to process each event before sending it along to the `Input`
specified by the handle. This processing function lets us add
extra information to the event. A common thing to add is an ID to indicate
which checkbox has been clicked, so when there are four check boxes
reporting to the same `Input` we can send events like `(True, 1)` to
indicate that the first box wants to be checked. Adding extra information
is not always necessary, as in our synced checkbox example, so a common
processing function is `id` which passes the boolean value to the
specified `Input` unmodified.
3. The third argument is the actual state of the checkbox: whether it is
checked or not. This means `checkbox` is a [pure function][pure]! Whether
it is checked or not is an argument, so that information must live in the
model, not in the view!
[pure]: http://en.wikipedia.org/wiki/Pure_function
Breaking the concept of a checkbox into an `Input`, a `Handle`, and a `checkbox`
makes the flow of events very explicit. This same pattern is used by all
interactive UI elements, so you will see this again and again as you look at
more examples.
## Tons of Examples
Synced checkboxes are nice for an introductory example, but it is simple because
it really only has an input and a display section. There is not a lot to model
or update. I have created a bunch of examples to illustrate some more complex
situations. Start with the simple examples:
* [Text Fields](/edit/examples/Reactive/TextField.elm)
* [Passwords](/edit/examples/Reactive/Password.elm)
* [Checkboxes](/edit/examples/Reactive/CheckBox.elm)
* [Drop Downs](/edit/examples/Reactive/DropDown.elm)
* [Fields + HTTP](/edit/examples/Reactive/ZipCodes.elm)
* [Filtered Fields](/edit/examples/Reactive/KeepIf.elm)
And then take a look at some more complex examples:
* [Field Reversal](/edit/examples/Intermediate/TextReverse.elm)
* [Calculator](/edit/examples/Intermediate/Calculator.elm)
* [Sign-up Form](/edit/examples/Intermediate/Form.elm)
* [Todo List](https://github.com/evancz/TodoFRP)
I suspect a lot of this code could be shortened, and I hope to see some
libraries spring up in the [Elm Public Library](http://library.elm-lang.org)
to factor out common patterns like form-validation, password verification,
credit-card entry, etc.
## Thank you!
Huge thank you to [<NAME>](https://github.com/seliopou) whose work
on [elm-d3](https://github.com/seliopou/elm-d3) led inspired the `signal` field
of an `Input`. Another huge thank you to [<NAME>](https://github.com/Apanatshka)
for talking through <NAME>'s idea with me and inspiring the `handle` field of
an `Input`. Finally thanks to everyone on [the mailing list][list] for
discussing and reviewing APIs, docs, and examples as the new UI elements library
came together!
[list]: https://groups.google.com/forum/#!forum/elm-discuss
|]
| true | import Graphics.Input (Input, input, checkbox)
import Website.Skeleton (skeleton)
import Window
port title : String
port title = "Interactive UI Elements"
main = lift2 (skeleton "Learn")
(everything <~ check.signal)
Window.dimensions
check : Input Bool
check = input False
everything : Bool -> Int -> Element
everything isChecked wid =
let w = min 600 wid
box = checkbox check.handle identity isChecked
in flow down
[ width w intro
, container w 30 middle <| flow right [ box, box, box ]
, width w rest
]
intro = [markdown|
<h1><div style="text-align:center">Interactive UI Elements
<div style="padding-top:4px;font-size:0.5em;font-weight:normal">Using text fields, drop downs, buttons, etc.</div></div>
</h1>
Many UI elements are interactive. You can click on them, hover above them, type
into them. In Elm you handle all of these interactions with the
[`Graphics.Input`][gi] library.
At the core of this library is the concept of an `Input`. An `Input` is like a
[port](/learn/Ports.elm) that receives all of its events from the UI. When the
user clicks a button, the event goes to an `Input`. When the user types into a
field, the event goes to an `Input`. I think the best way to really understand
this approach is to see it in action! In this post we will start with an example
and then dive into how it works.
[gi]: http://library.elm-lang.org/catalog/elm-lang-Elm/latest/Graphics-Input
## A Minimal Example
We are going to make three synced checkboxes. Changing one of them will change
the two others:
|]
rest = [markdown|
Here is the code we need to make that happen. Don't worry about the details too
much yet. This is more to get a feel for the API so we know what we are working
towards when we dive into the details:
```haskell
import Graphics.Input (Input, input, checkbox)
check : Input Bool
check = input False
displayBoxes : Bool -> Element
displayBoxes isChecked =
let box = checkbox check.handle identity isChecked
in flow right [ box, box, box ]
main : Signal Element
main = displayBoxes <~ check.signal
```
The key things to notice before we go into the API itself is the `Input` named
`check`. All UI events are going to flow through `check`. It is used twice in
the rest of the code:
1. In `displayBoxes` we create a `box` that we display three times.
The definition of `box` refers to `check.handle` which means that all
`checkbox` events are going to be sent to the `check` input.
2. In `main` we pipe all of the events from the `check` input to our display.
As the user toggles between true and false, these events will guide what
we actually display on screen.
This is a very high level view of how things work, but it illustrates the
typical structure of interactive UI elements in Elm. Let's look at the API
in more detail.
## Inputs
The first thing we do when making an interactive UI element is to create an input:
```haskell
type Input a = { signal : Signal a, handle : Handle a }
```
An `Input` has two distinct parts. One is a `signal` of events coming from UI
elements. In our synced checkbox example, these are boolean values indicating
whether the box should be checked or not. The more subtle part of an `Input` is
the `handle`. All interactive UI elements will latch on to a handle and report
their events to the corresponding `Input`. The handle lets us get events from
the UI back into our program without any messy callbacks or event-listeners.
You create an `Input` with the `input` function, like this:
```haskell
input : a -> Input a
check : Input Bool
check = input False
```
The argument to `input` serves as the default value of the input’s
`signal`. So when we create the `check` input we get:
1. A signal called `check.signal` with the initial value `False`.
2. A handle called `check.handle`. Any UI element can refer to `check.handle`
which would send events to `check.signal`.
Now that we have a way to manage UI events, we need to actually create the
interactive UI elements.
## Interactive UI Elements
There are a bunch of interactive UI elements available in [`Graphics.Input`][gi]
and [`Graphics.Input.Field`][gif] from traditional buttons and drop downs to
functions that can make any `Element` clickable or hoverable. We will focus on
[the `checkbox` function][box] which does a great job illustrating the general
pattern used by interactive UI elements in Elm:
[gi]: http://library.elm-lang.org/catalog/elm-lang-Elm/latest/Graphics-Input
[gif]: http://library.elm-lang.org/catalog/elm-lang-Elm/latest/Graphics-Input-Field
[box]: http://library.elm-lang.org/catalog/elm-lang-Elm/latest/Graphics-Input#checkbox
```haskell
checkbox : Handle a -> (Bool -> a) -> Bool -> Element
checkbox handle processingFunction checked = ...
```
The three arguments work like this:
1. Clicking on a checkbox generates an event, and the handle specifies which
`Input` these events should be sent to. The generated event is a boolean
value that represents what the user *wants* the checkbox to be. Clicking an
unchecked box generates a `True` event, and clicking a checked box generates
a `False` event.
2. A way to process each event before sending it along to the `Input`
specified by the handle. This processing function lets us add
extra information to the event. A common thing to add is an ID to indicate
which checkbox has been clicked, so when there are four check boxes
reporting to the same `Input` we can send events like `(True, 1)` to
indicate that the first box wants to be checked. Adding extra information
is not always necessary, as in our synced checkbox example, so a common
processing function is `id` which passes the boolean value to the
specified `Input` unmodified.
3. The third argument is the actual state of the checkbox: whether it is
checked or not. This means `checkbox` is a [pure function][pure]! Whether
it is checked or not is an argument, so that information must live in the
model, not in the view!
[pure]: http://en.wikipedia.org/wiki/Pure_function
Breaking the concept of a checkbox into an `Input`, a `Handle`, and a `checkbox`
makes the flow of events very explicit. This same pattern is used by all
interactive UI elements, so you will see this again and again as you look at
more examples.
## Tons of Examples
Synced checkboxes are nice for an introductory example, but it is simple because
it really only has an input and a display section. There is not a lot to model
or update. I have created a bunch of examples to illustrate some more complex
situations. Start with the simple examples:
* [Text Fields](/edit/examples/Reactive/TextField.elm)
* [Passwords](/edit/examples/Reactive/Password.elm)
* [Checkboxes](/edit/examples/Reactive/CheckBox.elm)
* [Drop Downs](/edit/examples/Reactive/DropDown.elm)
* [Fields + HTTP](/edit/examples/Reactive/ZipCodes.elm)
* [Filtered Fields](/edit/examples/Reactive/KeepIf.elm)
And then take a look at some more complex examples:
* [Field Reversal](/edit/examples/Intermediate/TextReverse.elm)
* [Calculator](/edit/examples/Intermediate/Calculator.elm)
* [Sign-up Form](/edit/examples/Intermediate/Form.elm)
* [Todo List](https://github.com/evancz/TodoFRP)
I suspect a lot of this code could be shortened, and I hope to see some
libraries spring up in the [Elm Public Library](http://library.elm-lang.org)
to factor out common patterns like form-validation, password verification,
credit-card entry, etc.
## Thank you!
Huge thank you to [PI:NAME:<NAME>END_PI](https://github.com/seliopou) whose work
on [elm-d3](https://github.com/seliopou/elm-d3) led inspired the `signal` field
of an `Input`. Another huge thank you to [PI:NAME:<NAME>END_PI](https://github.com/Apanatshka)
for talking through PI:NAME:<NAME>END_PI's idea with me and inspiring the `handle` field of
an `Input`. Finally thanks to everyone on [the mailing list][list] for
discussing and reviewing APIs, docs, and examples as the new UI elements library
came together!
[list]: https://groups.google.com/forum/#!forum/elm-discuss
|]
| elm |
[
{
"context": "co/query?function=GLOBAL_QUOTE&symbol=CERN&apikey=7SSFN5A63GVQREZT\", expect = Http.expectJson GotResponse (map2 Stoc",
"end": 1983,
"score": 0.9985244274,
"start": 1967,
"tag": "KEY",
"value": "7SSFN5A63GVQREZT"
}
] | 2021/elm-learning/src/Main.elm | rafimo/2_power_5 | 0 | -- A Web-App which refreshes every 60s reading data from a REST API and rendering stock details
-- cerner_2tothe5th_2021
module Main exposing (..)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Http
import Json.Decode exposing (map2, field, string)
import Time
main = Browser.element { init = init , update = update, subscriptions = subscriptions, view = view }
-- MODEL
type Model = Failure | Loading | Success Stock
init : () -> (Model, Cmd Msg)
init _ = (Loading, getData)
-- UPDATE
type Msg = FetchAnother | GotResponse (Result Http.Error Stock) | Tick Time.Posix
type alias Stock = { price: String, volume: String }
update : Msg -> Model -> (Model, Cmd Msg)
update msg _ = case msg of
FetchAnother -> (Loading, getData)
GotResponse result -> case result of
Ok url -> (Success url, Cmd.none)
Err _ -> (Failure, Cmd.none)
Tick _ -> (Loading, getData)
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions _ = Time.every 60000 Tick
-- VIEW
view : Model -> Html Msg
view model = div [] [ h2 [] [ text "Current Stock" ] , viewGif model ]
viewGif : Model -> Html Msg
viewGif model = case model of
Failure -> div [] [ text "Sorry! Failure", button [ onClick FetchAnother ] [ text "Try Again!" ] ]
Loading -> text "Loading..."
Success url -> div [] [ button [ onClick FetchAnother, style "display" "block" ] [ text "Refresh" ], text ("Price: " ++ url.price), text ( " Volume: " ++ url.volume) ]
-- HTTP
getData : Cmd Msg
-- getData = Http.get { url = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&count=2", expect = Http.expectJson GotResponse (index 0 ( field "url" string )) }
getData = Http.get { url = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=CERN&apikey=7SSFN5A63GVQREZT", expect = Http.expectJson GotResponse (map2 Stock ( field "Global Quote" ( field "05. price" string )) ( field "Global Quote" ( field "06. volume" string )))}
| 46845 | -- A Web-App which refreshes every 60s reading data from a REST API and rendering stock details
-- cerner_2tothe5th_2021
module Main exposing (..)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Http
import Json.Decode exposing (map2, field, string)
import Time
main = Browser.element { init = init , update = update, subscriptions = subscriptions, view = view }
-- MODEL
type Model = Failure | Loading | Success Stock
init : () -> (Model, Cmd Msg)
init _ = (Loading, getData)
-- UPDATE
type Msg = FetchAnother | GotResponse (Result Http.Error Stock) | Tick Time.Posix
type alias Stock = { price: String, volume: String }
update : Msg -> Model -> (Model, Cmd Msg)
update msg _ = case msg of
FetchAnother -> (Loading, getData)
GotResponse result -> case result of
Ok url -> (Success url, Cmd.none)
Err _ -> (Failure, Cmd.none)
Tick _ -> (Loading, getData)
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions _ = Time.every 60000 Tick
-- VIEW
view : Model -> Html Msg
view model = div [] [ h2 [] [ text "Current Stock" ] , viewGif model ]
viewGif : Model -> Html Msg
viewGif model = case model of
Failure -> div [] [ text "Sorry! Failure", button [ onClick FetchAnother ] [ text "Try Again!" ] ]
Loading -> text "Loading..."
Success url -> div [] [ button [ onClick FetchAnother, style "display" "block" ] [ text "Refresh" ], text ("Price: " ++ url.price), text ( " Volume: " ++ url.volume) ]
-- HTTP
getData : Cmd Msg
-- getData = Http.get { url = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&count=2", expect = Http.expectJson GotResponse (index 0 ( field "url" string )) }
getData = Http.get { url = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=CERN&apikey=<KEY>", expect = Http.expectJson GotResponse (map2 Stock ( field "Global Quote" ( field "05. price" string )) ( field "Global Quote" ( field "06. volume" string )))}
| true | -- A Web-App which refreshes every 60s reading data from a REST API and rendering stock details
-- cerner_2tothe5th_2021
module Main exposing (..)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Http
import Json.Decode exposing (map2, field, string)
import Time
main = Browser.element { init = init , update = update, subscriptions = subscriptions, view = view }
-- MODEL
type Model = Failure | Loading | Success Stock
init : () -> (Model, Cmd Msg)
init _ = (Loading, getData)
-- UPDATE
type Msg = FetchAnother | GotResponse (Result Http.Error Stock) | Tick Time.Posix
type alias Stock = { price: String, volume: String }
update : Msg -> Model -> (Model, Cmd Msg)
update msg _ = case msg of
FetchAnother -> (Loading, getData)
GotResponse result -> case result of
Ok url -> (Success url, Cmd.none)
Err _ -> (Failure, Cmd.none)
Tick _ -> (Loading, getData)
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions _ = Time.every 60000 Tick
-- VIEW
view : Model -> Html Msg
view model = div [] [ h2 [] [ text "Current Stock" ] , viewGif model ]
viewGif : Model -> Html Msg
viewGif model = case model of
Failure -> div [] [ text "Sorry! Failure", button [ onClick FetchAnother ] [ text "Try Again!" ] ]
Loading -> text "Loading..."
Success url -> div [] [ button [ onClick FetchAnother, style "display" "block" ] [ text "Refresh" ], text ("Price: " ++ url.price), text ( " Volume: " ++ url.volume) ]
-- HTTP
getData : Cmd Msg
-- getData = Http.get { url = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&count=2", expect = Http.expectJson GotResponse (index 0 ( field "url" string )) }
getData = Http.get { url = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=CERN&apikey=PI:KEY:<KEY>END_PI", expect = Http.expectJson GotResponse (map2 Stock ( field "Global Quote" ( field "05. price" string )) ( field "Global Quote" ( field "06. volume" string )))}
| elm |
[
{
"context": "Id -> Floor\ninit id =\n { id = id\n , name = \"New Floor\"\n , ord = 0\n , objects = Dict.empty\n ",
"end": 831,
"score": 0.5456976295,
"start": 828,
"tag": "NAME",
"value": "New"
}
] | src/elm/Model/Floor.elm | khajaphysist/office-maker-client | 0 | module Model.Floor exposing (..)
import CoreType exposing (..)
import Date exposing (Date)
import Dict exposing (Dict)
import Model.Object as Object exposing (Object)
import Model.ObjectsChange as ObjectsChange exposing (ObjectModification, ObjectsChange)
import Model.ObjectsOperation as ObjectsOperation
import Regex exposing (Regex)
type alias FloorBase =
{ id : FloorId
, temporary : Bool
, name : String
, ord : Int
, update : Maybe { by : PersonId, at : Date }
}
type alias Detailed a =
{ a
| width : Int
, height : Int
, realSize : Maybe ( Int, Int )
, image : Maybe String
, flipImage : Bool
, objects : Dict ObjectId Object
}
type alias Floor =
Detailed FloorBase
init : FloorId -> Floor
init id =
{ id = id
, name = "New Floor"
, ord = 0
, objects = Dict.empty
, width = 7200
, height = 4560
, realSize = Just ( 10, 7 )
, temporary = False
, image = Nothing
, flipImage = False
, update = Nothing
}
empty : Floor
empty =
init ""
baseOf : Floor -> FloorBase
baseOf { id, temporary, name, ord, update } =
FloorBase id temporary name ord update
initWithOrder : FloorId -> Int -> Floor
initWithOrder id ord =
let
floor =
init id
in
{ floor
| ord = ord
}
changeName : String -> Floor -> Floor
changeName name floor =
{ floor | name = name }
changeOrd : Int -> Floor -> Floor
changeOrd ord floor =
{ floor | ord = ord }
setImage : String -> Int -> Int -> Floor -> Floor
setImage url width height floor =
{ floor
| width = width
, height = height
, image = Just url
}
changeRealSize : ( Int, Int ) -> Floor -> Floor
changeRealSize ( width, height ) floor =
{ floor
| realSize = Just ( width, height )
}
{- 10cm -> 8px -}
realToPixel : Int -> Int
realToPixel real =
Basics.floor (toFloat real * 80)
pixelToReal : Int -> Int
pixelToReal pixel =
Basics.floor (toFloat pixel / 80)
size : Floor -> Size
size floor =
case floor.realSize of
Just ( w, h ) ->
Size (realToPixel w) (realToPixel h)
Nothing ->
Size floor.width floor.height
name : Floor -> String
name floor =
floor.name
width : Floor -> Int
width floor =
size floor |> .width
height : Floor -> Int
height floor =
size floor |> .height
-- TODO confusing...
realSize : Floor -> ( Int, Int )
realSize floor =
case floor.realSize of
Just ( w, h ) ->
( w, h )
Nothing ->
( pixelToReal floor.width, pixelToReal floor.height )
src : String -> Floor -> Maybe String
src imageRoot floor =
case floor.image of
Just src ->
Just (imageRoot ++ "/floors/" ++ src)
Nothing ->
Nothing
changeId : FloorId -> Floor -> Floor
changeId id floor =
{ floor | id = id }
copy : FloorId -> Bool -> Floor -> Floor
copy id temporary floor =
{ floor
| id = id
, name =
if temporary then
"Temporary from " ++ floor.name
else
"Copy of " ++ floor.name
, update = Nothing
, objects = Dict.empty
, temporary = temporary
}
flip : Floor -> Floor
flip floor =
{ floor
| flipImage = not floor.flipImage
}
|> fullyChangeObjects (ObjectsOperation.flipObject <| size floor)
-- OBJECT OPERATIONS
move : List ObjectId -> Int -> ( Int, Int ) -> Floor -> Floor
move ids gridSize ( dx, dy ) floor =
partiallyChangeObjects
(moveObjects gridSize ( dx, dy ))
ids
floor
moveObjects : Int -> ( Int, Int ) -> Object -> Object
moveObjects gridSize ( dx, dy ) object =
let
pos =
Object.positionOf object
new =
ObjectsOperation.fitPositionToGrid
gridSize
(Position (pos.x + dx) (pos.y + dy))
in
Object.changePosition new object
paste : List ( Object, ObjectId ) -> Position -> Floor -> Floor
paste copiedWithNewIds base floor =
addObjects
(ObjectsOperation.pasteObjects floor.id base copiedWithNewIds)
floor
rotateObjects : List ObjectId -> Floor -> Floor
rotateObjects ids floor =
partiallyChangeObjects Object.rotate ids floor
changeObjectColor : List ObjectId -> String -> Floor -> Floor
changeObjectColor ids color floor =
partiallyChangeObjects (Object.changeColor color) ids floor
changeObjectBackgroundColor : List ObjectId -> String -> Floor -> Floor
changeObjectBackgroundColor ids color floor =
partiallyChangeObjects (Object.changeBackgroundColor color) ids floor
changeObjectShape : List ObjectId -> Object.Shape -> Floor -> Floor
changeObjectShape ids shape floor =
partiallyChangeObjects (Object.changeShape shape) ids floor
changeObjectName : List ObjectId -> String -> Floor -> Floor
changeObjectName ids name floor =
partiallyChangeObjects (Object.changeName name) ids floor
changeObjectFontSize : List ObjectId -> Float -> Floor -> Floor
changeObjectFontSize ids fontSize floor =
partiallyChangeObjects (Object.changeFontSize fontSize) ids floor
changeObjectUrl : List ObjectId -> String -> Floor -> Floor
changeObjectUrl ids url floor =
partiallyChangeObjects (Object.changeUrl url) ids floor
changeObjectsByChanges : ObjectsChange -> Floor -> Floor
changeObjectsByChanges change floor =
let
separated =
ObjectsChange.separate change
in
floor
|> addObjects separated.added
|> modifyObjects separated.modified
|> removeObjects (List.map Object.idOf separated.deleted)
toFirstNameOnly : List ObjectId -> Floor -> Floor
toFirstNameOnly ids floor =
let
change name =
case String.words name of
[] ->
""
x :: _ ->
x
f object =
Object.changeName (change (Object.nameOf object)) object
in
partiallyChangeObjects f ids floor
fullyChangeObjects : (Object -> Object) -> Floor -> Floor
fullyChangeObjects f floor =
{ floor
| objects =
Dict.map (\_ object -> f object) floor.objects
}
partiallyChangeObjects : (Object -> Object) -> List ObjectId -> Floor -> Floor
partiallyChangeObjects f ids floor =
{ floor
| objects =
ids
|> List.foldl
(\objectId dict -> Dict.update objectId (Maybe.map f) dict)
floor.objects
}
removeSpaces : List ObjectId -> Floor -> Floor
removeSpaces ids floor =
let
change name =
Regex.replace Regex.All whiteSpaces (\_ -> "") name
f object =
Object.changeName (change <| Object.nameOf object) object
in
partiallyChangeObjects f ids floor
whiteSpaces : Regex
whiteSpaces =
Regex.regex "[ \x0D\n\x3000]"
resizeObject : ObjectId -> Size -> Floor -> Floor
resizeObject id size floor =
partiallyChangeObjects (Object.changeSize size) [ id ] floor
setPerson : ObjectId -> PersonId -> Floor -> Floor
setPerson objectId personId floor =
setPeople [ ( objectId, personId ) ] floor
unsetPerson : ObjectId -> Floor -> Floor
unsetPerson objectId floor =
partiallyChangeObjects (Object.setPerson Nothing) [ objectId ] floor
setPeople : List ( ObjectId, PersonId ) -> Floor -> Floor
setPeople pairs floor =
let
f ( objectId, personId ) dict =
dict
|> Dict.update objectId (Maybe.map (Object.setPerson (Just personId)))
newObjects =
List.foldl f floor.objects pairs
in
{ floor | objects = newObjects }
objects : Floor -> List Object
objects floor =
Dict.values floor.objects
getObject : ObjectId -> Floor -> Maybe Object
getObject objectId floor =
Dict.get objectId floor.objects
getObjects : List ObjectId -> Floor -> List Object
getObjects ids floor =
ids
|> List.filterMap (\id -> getObject id floor)
setObjects : List Object -> Floor -> Floor
setObjects objects floor =
{ floor
| objects =
objectsDictFromList floor.id objects
}
{-| bad name!!
-}
addObjects : List Object -> Floor -> Floor
addObjects objects floor =
{ floor
| objects =
objects
|> filterObjectsInFloor floor.id
|> List.foldl (\object -> Dict.insert (Object.idOf object) object) floor.objects
}
modifyObjects : List ObjectModification -> Floor -> Floor
modifyObjects list floor =
{ floor
| objects =
list
|> List.foldl
(\mod dict ->
Dict.update
(Object.idOf mod.new)
(Maybe.map (Object.modifyAll mod.changes))
dict
)
floor.objects
}
removeObjects : List ObjectId -> Floor -> Floor
removeObjects objectIds floor =
{ floor
| objects =
List.foldl Dict.remove floor.objects objectIds
}
objectsDictFromList : FloorId -> List Object -> Dict ObjectId Object
objectsDictFromList floorId objects =
objects
|> filterObjectsInFloor floorId
|> List.map (\object -> ( Object.idOf object, object ))
|> Dict.fromList
filterObjectsInFloor : FloorId -> List Object -> List Object
filterObjectsInFloor floorId objects =
objects
|> List.filter (\object -> Object.floorIdOf object == floorId)
| 7568 | module Model.Floor exposing (..)
import CoreType exposing (..)
import Date exposing (Date)
import Dict exposing (Dict)
import Model.Object as Object exposing (Object)
import Model.ObjectsChange as ObjectsChange exposing (ObjectModification, ObjectsChange)
import Model.ObjectsOperation as ObjectsOperation
import Regex exposing (Regex)
type alias FloorBase =
{ id : FloorId
, temporary : Bool
, name : String
, ord : Int
, update : Maybe { by : PersonId, at : Date }
}
type alias Detailed a =
{ a
| width : Int
, height : Int
, realSize : Maybe ( Int, Int )
, image : Maybe String
, flipImage : Bool
, objects : Dict ObjectId Object
}
type alias Floor =
Detailed FloorBase
init : FloorId -> Floor
init id =
{ id = id
, name = "<NAME> Floor"
, ord = 0
, objects = Dict.empty
, width = 7200
, height = 4560
, realSize = Just ( 10, 7 )
, temporary = False
, image = Nothing
, flipImage = False
, update = Nothing
}
empty : Floor
empty =
init ""
baseOf : Floor -> FloorBase
baseOf { id, temporary, name, ord, update } =
FloorBase id temporary name ord update
initWithOrder : FloorId -> Int -> Floor
initWithOrder id ord =
let
floor =
init id
in
{ floor
| ord = ord
}
changeName : String -> Floor -> Floor
changeName name floor =
{ floor | name = name }
changeOrd : Int -> Floor -> Floor
changeOrd ord floor =
{ floor | ord = ord }
setImage : String -> Int -> Int -> Floor -> Floor
setImage url width height floor =
{ floor
| width = width
, height = height
, image = Just url
}
changeRealSize : ( Int, Int ) -> Floor -> Floor
changeRealSize ( width, height ) floor =
{ floor
| realSize = Just ( width, height )
}
{- 10cm -> 8px -}
realToPixel : Int -> Int
realToPixel real =
Basics.floor (toFloat real * 80)
pixelToReal : Int -> Int
pixelToReal pixel =
Basics.floor (toFloat pixel / 80)
size : Floor -> Size
size floor =
case floor.realSize of
Just ( w, h ) ->
Size (realToPixel w) (realToPixel h)
Nothing ->
Size floor.width floor.height
name : Floor -> String
name floor =
floor.name
width : Floor -> Int
width floor =
size floor |> .width
height : Floor -> Int
height floor =
size floor |> .height
-- TODO confusing...
realSize : Floor -> ( Int, Int )
realSize floor =
case floor.realSize of
Just ( w, h ) ->
( w, h )
Nothing ->
( pixelToReal floor.width, pixelToReal floor.height )
src : String -> Floor -> Maybe String
src imageRoot floor =
case floor.image of
Just src ->
Just (imageRoot ++ "/floors/" ++ src)
Nothing ->
Nothing
changeId : FloorId -> Floor -> Floor
changeId id floor =
{ floor | id = id }
copy : FloorId -> Bool -> Floor -> Floor
copy id temporary floor =
{ floor
| id = id
, name =
if temporary then
"Temporary from " ++ floor.name
else
"Copy of " ++ floor.name
, update = Nothing
, objects = Dict.empty
, temporary = temporary
}
flip : Floor -> Floor
flip floor =
{ floor
| flipImage = not floor.flipImage
}
|> fullyChangeObjects (ObjectsOperation.flipObject <| size floor)
-- OBJECT OPERATIONS
move : List ObjectId -> Int -> ( Int, Int ) -> Floor -> Floor
move ids gridSize ( dx, dy ) floor =
partiallyChangeObjects
(moveObjects gridSize ( dx, dy ))
ids
floor
moveObjects : Int -> ( Int, Int ) -> Object -> Object
moveObjects gridSize ( dx, dy ) object =
let
pos =
Object.positionOf object
new =
ObjectsOperation.fitPositionToGrid
gridSize
(Position (pos.x + dx) (pos.y + dy))
in
Object.changePosition new object
paste : List ( Object, ObjectId ) -> Position -> Floor -> Floor
paste copiedWithNewIds base floor =
addObjects
(ObjectsOperation.pasteObjects floor.id base copiedWithNewIds)
floor
rotateObjects : List ObjectId -> Floor -> Floor
rotateObjects ids floor =
partiallyChangeObjects Object.rotate ids floor
changeObjectColor : List ObjectId -> String -> Floor -> Floor
changeObjectColor ids color floor =
partiallyChangeObjects (Object.changeColor color) ids floor
changeObjectBackgroundColor : List ObjectId -> String -> Floor -> Floor
changeObjectBackgroundColor ids color floor =
partiallyChangeObjects (Object.changeBackgroundColor color) ids floor
changeObjectShape : List ObjectId -> Object.Shape -> Floor -> Floor
changeObjectShape ids shape floor =
partiallyChangeObjects (Object.changeShape shape) ids floor
changeObjectName : List ObjectId -> String -> Floor -> Floor
changeObjectName ids name floor =
partiallyChangeObjects (Object.changeName name) ids floor
changeObjectFontSize : List ObjectId -> Float -> Floor -> Floor
changeObjectFontSize ids fontSize floor =
partiallyChangeObjects (Object.changeFontSize fontSize) ids floor
changeObjectUrl : List ObjectId -> String -> Floor -> Floor
changeObjectUrl ids url floor =
partiallyChangeObjects (Object.changeUrl url) ids floor
changeObjectsByChanges : ObjectsChange -> Floor -> Floor
changeObjectsByChanges change floor =
let
separated =
ObjectsChange.separate change
in
floor
|> addObjects separated.added
|> modifyObjects separated.modified
|> removeObjects (List.map Object.idOf separated.deleted)
toFirstNameOnly : List ObjectId -> Floor -> Floor
toFirstNameOnly ids floor =
let
change name =
case String.words name of
[] ->
""
x :: _ ->
x
f object =
Object.changeName (change (Object.nameOf object)) object
in
partiallyChangeObjects f ids floor
fullyChangeObjects : (Object -> Object) -> Floor -> Floor
fullyChangeObjects f floor =
{ floor
| objects =
Dict.map (\_ object -> f object) floor.objects
}
partiallyChangeObjects : (Object -> Object) -> List ObjectId -> Floor -> Floor
partiallyChangeObjects f ids floor =
{ floor
| objects =
ids
|> List.foldl
(\objectId dict -> Dict.update objectId (Maybe.map f) dict)
floor.objects
}
removeSpaces : List ObjectId -> Floor -> Floor
removeSpaces ids floor =
let
change name =
Regex.replace Regex.All whiteSpaces (\_ -> "") name
f object =
Object.changeName (change <| Object.nameOf object) object
in
partiallyChangeObjects f ids floor
whiteSpaces : Regex
whiteSpaces =
Regex.regex "[ \x0D\n\x3000]"
resizeObject : ObjectId -> Size -> Floor -> Floor
resizeObject id size floor =
partiallyChangeObjects (Object.changeSize size) [ id ] floor
setPerson : ObjectId -> PersonId -> Floor -> Floor
setPerson objectId personId floor =
setPeople [ ( objectId, personId ) ] floor
unsetPerson : ObjectId -> Floor -> Floor
unsetPerson objectId floor =
partiallyChangeObjects (Object.setPerson Nothing) [ objectId ] floor
setPeople : List ( ObjectId, PersonId ) -> Floor -> Floor
setPeople pairs floor =
let
f ( objectId, personId ) dict =
dict
|> Dict.update objectId (Maybe.map (Object.setPerson (Just personId)))
newObjects =
List.foldl f floor.objects pairs
in
{ floor | objects = newObjects }
objects : Floor -> List Object
objects floor =
Dict.values floor.objects
getObject : ObjectId -> Floor -> Maybe Object
getObject objectId floor =
Dict.get objectId floor.objects
getObjects : List ObjectId -> Floor -> List Object
getObjects ids floor =
ids
|> List.filterMap (\id -> getObject id floor)
setObjects : List Object -> Floor -> Floor
setObjects objects floor =
{ floor
| objects =
objectsDictFromList floor.id objects
}
{-| bad name!!
-}
addObjects : List Object -> Floor -> Floor
addObjects objects floor =
{ floor
| objects =
objects
|> filterObjectsInFloor floor.id
|> List.foldl (\object -> Dict.insert (Object.idOf object) object) floor.objects
}
modifyObjects : List ObjectModification -> Floor -> Floor
modifyObjects list floor =
{ floor
| objects =
list
|> List.foldl
(\mod dict ->
Dict.update
(Object.idOf mod.new)
(Maybe.map (Object.modifyAll mod.changes))
dict
)
floor.objects
}
removeObjects : List ObjectId -> Floor -> Floor
removeObjects objectIds floor =
{ floor
| objects =
List.foldl Dict.remove floor.objects objectIds
}
objectsDictFromList : FloorId -> List Object -> Dict ObjectId Object
objectsDictFromList floorId objects =
objects
|> filterObjectsInFloor floorId
|> List.map (\object -> ( Object.idOf object, object ))
|> Dict.fromList
filterObjectsInFloor : FloorId -> List Object -> List Object
filterObjectsInFloor floorId objects =
objects
|> List.filter (\object -> Object.floorIdOf object == floorId)
| true | module Model.Floor exposing (..)
import CoreType exposing (..)
import Date exposing (Date)
import Dict exposing (Dict)
import Model.Object as Object exposing (Object)
import Model.ObjectsChange as ObjectsChange exposing (ObjectModification, ObjectsChange)
import Model.ObjectsOperation as ObjectsOperation
import Regex exposing (Regex)
type alias FloorBase =
{ id : FloorId
, temporary : Bool
, name : String
, ord : Int
, update : Maybe { by : PersonId, at : Date }
}
type alias Detailed a =
{ a
| width : Int
, height : Int
, realSize : Maybe ( Int, Int )
, image : Maybe String
, flipImage : Bool
, objects : Dict ObjectId Object
}
type alias Floor =
Detailed FloorBase
init : FloorId -> Floor
init id =
{ id = id
, name = "PI:NAME:<NAME>END_PI Floor"
, ord = 0
, objects = Dict.empty
, width = 7200
, height = 4560
, realSize = Just ( 10, 7 )
, temporary = False
, image = Nothing
, flipImage = False
, update = Nothing
}
empty : Floor
empty =
init ""
baseOf : Floor -> FloorBase
baseOf { id, temporary, name, ord, update } =
FloorBase id temporary name ord update
initWithOrder : FloorId -> Int -> Floor
initWithOrder id ord =
let
floor =
init id
in
{ floor
| ord = ord
}
changeName : String -> Floor -> Floor
changeName name floor =
{ floor | name = name }
changeOrd : Int -> Floor -> Floor
changeOrd ord floor =
{ floor | ord = ord }
setImage : String -> Int -> Int -> Floor -> Floor
setImage url width height floor =
{ floor
| width = width
, height = height
, image = Just url
}
changeRealSize : ( Int, Int ) -> Floor -> Floor
changeRealSize ( width, height ) floor =
{ floor
| realSize = Just ( width, height )
}
{- 10cm -> 8px -}
realToPixel : Int -> Int
realToPixel real =
Basics.floor (toFloat real * 80)
pixelToReal : Int -> Int
pixelToReal pixel =
Basics.floor (toFloat pixel / 80)
size : Floor -> Size
size floor =
case floor.realSize of
Just ( w, h ) ->
Size (realToPixel w) (realToPixel h)
Nothing ->
Size floor.width floor.height
name : Floor -> String
name floor =
floor.name
width : Floor -> Int
width floor =
size floor |> .width
height : Floor -> Int
height floor =
size floor |> .height
-- TODO confusing...
realSize : Floor -> ( Int, Int )
realSize floor =
case floor.realSize of
Just ( w, h ) ->
( w, h )
Nothing ->
( pixelToReal floor.width, pixelToReal floor.height )
src : String -> Floor -> Maybe String
src imageRoot floor =
case floor.image of
Just src ->
Just (imageRoot ++ "/floors/" ++ src)
Nothing ->
Nothing
changeId : FloorId -> Floor -> Floor
changeId id floor =
{ floor | id = id }
copy : FloorId -> Bool -> Floor -> Floor
copy id temporary floor =
{ floor
| id = id
, name =
if temporary then
"Temporary from " ++ floor.name
else
"Copy of " ++ floor.name
, update = Nothing
, objects = Dict.empty
, temporary = temporary
}
flip : Floor -> Floor
flip floor =
{ floor
| flipImage = not floor.flipImage
}
|> fullyChangeObjects (ObjectsOperation.flipObject <| size floor)
-- OBJECT OPERATIONS
move : List ObjectId -> Int -> ( Int, Int ) -> Floor -> Floor
move ids gridSize ( dx, dy ) floor =
partiallyChangeObjects
(moveObjects gridSize ( dx, dy ))
ids
floor
moveObjects : Int -> ( Int, Int ) -> Object -> Object
moveObjects gridSize ( dx, dy ) object =
let
pos =
Object.positionOf object
new =
ObjectsOperation.fitPositionToGrid
gridSize
(Position (pos.x + dx) (pos.y + dy))
in
Object.changePosition new object
paste : List ( Object, ObjectId ) -> Position -> Floor -> Floor
paste copiedWithNewIds base floor =
addObjects
(ObjectsOperation.pasteObjects floor.id base copiedWithNewIds)
floor
rotateObjects : List ObjectId -> Floor -> Floor
rotateObjects ids floor =
partiallyChangeObjects Object.rotate ids floor
changeObjectColor : List ObjectId -> String -> Floor -> Floor
changeObjectColor ids color floor =
partiallyChangeObjects (Object.changeColor color) ids floor
changeObjectBackgroundColor : List ObjectId -> String -> Floor -> Floor
changeObjectBackgroundColor ids color floor =
partiallyChangeObjects (Object.changeBackgroundColor color) ids floor
changeObjectShape : List ObjectId -> Object.Shape -> Floor -> Floor
changeObjectShape ids shape floor =
partiallyChangeObjects (Object.changeShape shape) ids floor
changeObjectName : List ObjectId -> String -> Floor -> Floor
changeObjectName ids name floor =
partiallyChangeObjects (Object.changeName name) ids floor
changeObjectFontSize : List ObjectId -> Float -> Floor -> Floor
changeObjectFontSize ids fontSize floor =
partiallyChangeObjects (Object.changeFontSize fontSize) ids floor
changeObjectUrl : List ObjectId -> String -> Floor -> Floor
changeObjectUrl ids url floor =
partiallyChangeObjects (Object.changeUrl url) ids floor
changeObjectsByChanges : ObjectsChange -> Floor -> Floor
changeObjectsByChanges change floor =
let
separated =
ObjectsChange.separate change
in
floor
|> addObjects separated.added
|> modifyObjects separated.modified
|> removeObjects (List.map Object.idOf separated.deleted)
toFirstNameOnly : List ObjectId -> Floor -> Floor
toFirstNameOnly ids floor =
let
change name =
case String.words name of
[] ->
""
x :: _ ->
x
f object =
Object.changeName (change (Object.nameOf object)) object
in
partiallyChangeObjects f ids floor
fullyChangeObjects : (Object -> Object) -> Floor -> Floor
fullyChangeObjects f floor =
{ floor
| objects =
Dict.map (\_ object -> f object) floor.objects
}
partiallyChangeObjects : (Object -> Object) -> List ObjectId -> Floor -> Floor
partiallyChangeObjects f ids floor =
{ floor
| objects =
ids
|> List.foldl
(\objectId dict -> Dict.update objectId (Maybe.map f) dict)
floor.objects
}
removeSpaces : List ObjectId -> Floor -> Floor
removeSpaces ids floor =
let
change name =
Regex.replace Regex.All whiteSpaces (\_ -> "") name
f object =
Object.changeName (change <| Object.nameOf object) object
in
partiallyChangeObjects f ids floor
whiteSpaces : Regex
whiteSpaces =
Regex.regex "[ \x0D\n\x3000]"
resizeObject : ObjectId -> Size -> Floor -> Floor
resizeObject id size floor =
partiallyChangeObjects (Object.changeSize size) [ id ] floor
setPerson : ObjectId -> PersonId -> Floor -> Floor
setPerson objectId personId floor =
setPeople [ ( objectId, personId ) ] floor
unsetPerson : ObjectId -> Floor -> Floor
unsetPerson objectId floor =
partiallyChangeObjects (Object.setPerson Nothing) [ objectId ] floor
setPeople : List ( ObjectId, PersonId ) -> Floor -> Floor
setPeople pairs floor =
let
f ( objectId, personId ) dict =
dict
|> Dict.update objectId (Maybe.map (Object.setPerson (Just personId)))
newObjects =
List.foldl f floor.objects pairs
in
{ floor | objects = newObjects }
objects : Floor -> List Object
objects floor =
Dict.values floor.objects
getObject : ObjectId -> Floor -> Maybe Object
getObject objectId floor =
Dict.get objectId floor.objects
getObjects : List ObjectId -> Floor -> List Object
getObjects ids floor =
ids
|> List.filterMap (\id -> getObject id floor)
setObjects : List Object -> Floor -> Floor
setObjects objects floor =
{ floor
| objects =
objectsDictFromList floor.id objects
}
{-| bad name!!
-}
addObjects : List Object -> Floor -> Floor
addObjects objects floor =
{ floor
| objects =
objects
|> filterObjectsInFloor floor.id
|> List.foldl (\object -> Dict.insert (Object.idOf object) object) floor.objects
}
modifyObjects : List ObjectModification -> Floor -> Floor
modifyObjects list floor =
{ floor
| objects =
list
|> List.foldl
(\mod dict ->
Dict.update
(Object.idOf mod.new)
(Maybe.map (Object.modifyAll mod.changes))
dict
)
floor.objects
}
removeObjects : List ObjectId -> Floor -> Floor
removeObjects objectIds floor =
{ floor
| objects =
List.foldl Dict.remove floor.objects objectIds
}
objectsDictFromList : FloorId -> List Object -> Dict ObjectId Object
objectsDictFromList floorId objects =
objects
|> filterObjectsInFloor floorId
|> List.map (\object -> ( Object.idOf object, object ))
|> Dict.fromList
filterObjectsInFloor : FloorId -> List Object -> List Object
filterObjectsInFloor floorId objects =
objects
|> List.filter (\object -> Object.floorIdOf object == floorId)
| elm |
[
{
"context": "g\n awsConfig =\n { awsSecretAccessKey = \"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY\"\n , awsRegion = \"us-east-1\"\n , acce",
"end": 2087,
"score": 0.9997582436,
"start": 2047,
"tag": "KEY",
"value": "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"
},
{
"context": "gn\"\n --> \"equal%3Dsign\"\n\n awsPercentEncode \"bob@example.com\"\n --> \"bob%40example.com\"\n\n-}\nawsPercentEncode",
"end": 7044,
"score": 0.9999235868,
"start": 7029,
"tag": "EMAIL",
"value": "bob@example.com"
}
] | src/AWS/Internal.elm | choonkeat/elm-aws | 0 | module AWS.Internal exposing (..)
import AWS.Types exposing (..)
import Base16
import Crypto.HMAC
import Crypto.Hash
import DateFormat
import Http
import Json.Decode
import Json.Encode
import Task exposing (Task)
import Time
import Url
import Url.Builder
import Word.Bytes
endpoint : Config -> Service -> Url.Url
endpoint { awsRegion } service =
let
urlWithoutRegion =
{ protocol = Url.Https
, host = serviceName service ++ ".amazonaws.com"
, port_ = Nothing
, path = "/"
, query = Nothing
, fragment = Nothing
}
in
case service of
ServiceIam ->
urlWithoutRegion
ServiceDynamoDB ->
{ urlWithoutRegion | host = serviceName service ++ "." ++ awsRegion ++ ".amazonaws.com" }
ServiceSES ->
{ urlWithoutRegion | host = serviceName service ++ "." ++ awsRegion ++ ".amazonaws.com" }
ServiceSQS url ->
url
serviceName : Service -> String
serviceName service =
case service of
ServiceIam ->
"iam"
ServiceDynamoDB ->
"dynamodb"
ServiceSES ->
"email"
ServiceSQS _ ->
"sqs"
algorithm =
"AWS4-HMAC-SHA256"
authorizationHeader : Config -> Signature -> String
authorizationHeader config signature =
String.join ""
[ algorithm
, " Credential="
, config.accessKeyId
, "/"
, signature.credentialScope
, ", SignedHeaders="
, signature.signedHeaders
, ", Signature="
, signature.text
]
{-| Signing AWS requests with Signature Version 4 <https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html>
import Time
import AWS.Types exposing (..)
nowMillisecond : Int
nowMillisecond =
1440938160000
requestDateTime : Time.Posix
requestDateTime =
Time.millisToPosix nowMillisecond
awsConfig : Config
awsConfig =
{ awsSecretAccessKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY"
, awsRegion = "us-east-1"
, accessKeyId = ""
, timeout = Just 1234
}
sign
awsConfig
ServiceIam
requestDateTime
{ method = "GET"
, query =
[ ( "Action", "ListUsers" )
, ( "Version", "2010-05-08" )
]
, headers =
[ ( "Content-Type", "application/x-www-form-urlencoded; charset=utf-8" )
]
, payload = ""
} |> Result.map .text
--> Ok "5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7"
NOTE: this function is only exposed to allow testing
-}
sign :
Config
-> Service
-> Time.Posix
->
{ method : String
, query : List ( String, String )
, headers : List ( String, String )
, payload : String
}
-> Result String Signature
sign config service now request =
let
url =
endpoint config service
yyyymmddThhmmssz =
DateFormat.format
[ DateFormat.yearNumber
, DateFormat.monthFixed
, DateFormat.dayOfMonthFixed
, DateFormat.text "T"
, DateFormat.hourMilitaryFixed
, DateFormat.minuteFixed
, DateFormat.secondFixed
, DateFormat.text "Z"
]
Time.utc
now
yyyymmdd =
DateFormat.format
[ DateFormat.yearNumber
, DateFormat.monthFixed
, DateFormat.dayOfMonthFixed
]
Time.utc
now
headers =
request.headers
|> List.append
[ ( "X-Amz-Date", yyyymmddThhmmssz )
, ( "Host", url.host )
]
credentialScope =
String.join "/" [ yyyymmdd, config.awsRegion, serviceName service, "aws4_request" ]
signedHeaders =
canonicalHeaderKeys headers
canonicalRequest =
String.join "\n"
[ request.method
, url.path
, canonicalQuery request.query
, canonicalHeaders headers
, signedHeaders
, Crypto.Hash.sha256 request.payload
]
stringToSign =
String.join "\n"
[ algorithm
, yyyymmddThhmmssz
, credentialScope
, Crypto.Hash.sha256 canonicalRequest
]
signingKey =
Word.Bytes.fromUTF8 ("AWS4" ++ config.awsSecretAccessKey)
|> (\k -> Crypto.HMAC.digestBytes Crypto.HMAC.sha256 k (Word.Bytes.fromUTF8 yyyymmdd))
|> (\k -> Crypto.HMAC.digestBytes Crypto.HMAC.sha256 k (Word.Bytes.fromUTF8 config.awsRegion))
|> (\k -> Crypto.HMAC.digestBytes Crypto.HMAC.sha256 k (Word.Bytes.fromUTF8 (serviceName service)))
|> (\k -> Crypto.HMAC.digestBytes Crypto.HMAC.sha256 k (Word.Bytes.fromUTF8 "aws4_request"))
result =
case List.head (List.filter (\( k, v ) -> String.toLower k == "host") request.headers) of
Nothing ->
-- ok, we can proceed to sign
Crypto.HMAC.digestBytes Crypto.HMAC.sha256 signingKey (Word.Bytes.fromUTF8 stringToSign)
|> Base16.encode
Just s ->
-- since the sign function is already a Result, let's fail explicitly
Err "Manually specifying `Host` header is not allowed by xhr2"
in
case result of
Err err ->
Err err
Ok text ->
Ok
{ text = String.toLower text
, credentialScope = credentialScope
, headers = headers
, signedHeaders = signedHeaders
, algorithm = algorithm
}
canonicalQuery : List ( String, String ) -> String
canonicalQuery keyValues =
List.sortBy (\( k, v ) -> k ++ v) keyValues
|> List.map (\( k, v ) -> awsPercentEncode k ++ "=" ++ awsPercentEncode v)
|> String.join "&"
canonicalHeaders : List ( String, String ) -> String
canonicalHeaders keyValues =
List.map (\( k, v ) -> ( String.toLower k, String.trim v )) keyValues
|> List.sortBy Tuple.first
|> List.map (\( k, v ) -> k ++ ":" ++ v ++ "\n")
|> String.join ""
canonicalHeaderKeys : List ( String, String ) -> String
canonicalHeaderKeys keyValues =
List.map (\( k, v ) -> String.toLower k) keyValues
|> List.sort
|> String.join ";"
{-|
awsPercentEncode "Az09-_.~!*'()"
--> "Az09-_.~%21%2A%27%28%29"
awsPercentEncode "space "
--> "space%20"
awsPercentEncode "🙂"
--> "%F0%9F%99%82"
awsPercentEncode "equal=sign"
--> "equal%3Dsign"
awsPercentEncode "bob@example.com"
--> "bob%40example.com"
-}
awsPercentEncode : String -> String
awsPercentEncode string =
Url.percentEncode string
|> String.replace "!" "%21"
|> String.replace "*" "%2A"
|> String.replace "'" "%27"
|> String.replace "(" "%28"
|> String.replace ")" "%29"
{-| If http response body does not contain expected String, return as Http.BadBody error
-}
stringMatchHttpResponse : String -> Http.Response String -> Result Http.Error ()
stringMatchHttpResponse needle resp =
let
matchResult haystack =
if String.contains needle haystack then
Ok ()
else
Err (Http.BadBody ("[" ++ needle ++ "] not found: " ++ haystack))
in
case resp of
Http.GoodStatus_ m s ->
matchResult s
Http.BadUrl_ s ->
Err (Http.BadUrl s)
Http.Timeout_ ->
Err Http.Timeout
Http.NetworkError_ ->
Err Http.NetworkError
Http.BadStatus_ m s ->
Err (Http.BadStatus m.statusCode)
{-| applies a decoder to response of `Http.task`
To do JSON decoding:
Http.task
{ resolver = Http.stringResolver (decodeHttpResponse (Json.Decode.decodeString thingDecoder) Json.Decode.errorToString)
, ...
}
To do XML decoding
Http.task
{ resolver = Http.stringResolver (decodeHttpResponse (Xml.Decode.decodeString thingDecoder) identity)
, ...
}
-}
decodeHttpResponse : (b -> Result e a) -> (e -> String) -> Http.Response b -> Result Http.Error a
decodeHttpResponse decode errorToString resp =
case resp of
Http.GoodStatus_ m s ->
decode s
|> Result.mapError (errorToString >> Http.BadBody)
Http.BadUrl_ s ->
Err (Http.BadUrl s)
Http.Timeout_ ->
Err Http.Timeout
Http.NetworkError_ ->
Err Http.NetworkError
Http.BadStatus_ m s ->
decode s
-- best effort attempt to decode the response body, but fallback to `Http.BadStatus`
|> Result.mapError (always (Http.BadStatus m.statusCode))
| 849 | module AWS.Internal exposing (..)
import AWS.Types exposing (..)
import Base16
import Crypto.HMAC
import Crypto.Hash
import DateFormat
import Http
import Json.Decode
import Json.Encode
import Task exposing (Task)
import Time
import Url
import Url.Builder
import Word.Bytes
endpoint : Config -> Service -> Url.Url
endpoint { awsRegion } service =
let
urlWithoutRegion =
{ protocol = Url.Https
, host = serviceName service ++ ".amazonaws.com"
, port_ = Nothing
, path = "/"
, query = Nothing
, fragment = Nothing
}
in
case service of
ServiceIam ->
urlWithoutRegion
ServiceDynamoDB ->
{ urlWithoutRegion | host = serviceName service ++ "." ++ awsRegion ++ ".amazonaws.com" }
ServiceSES ->
{ urlWithoutRegion | host = serviceName service ++ "." ++ awsRegion ++ ".amazonaws.com" }
ServiceSQS url ->
url
serviceName : Service -> String
serviceName service =
case service of
ServiceIam ->
"iam"
ServiceDynamoDB ->
"dynamodb"
ServiceSES ->
"email"
ServiceSQS _ ->
"sqs"
algorithm =
"AWS4-HMAC-SHA256"
authorizationHeader : Config -> Signature -> String
authorizationHeader config signature =
String.join ""
[ algorithm
, " Credential="
, config.accessKeyId
, "/"
, signature.credentialScope
, ", SignedHeaders="
, signature.signedHeaders
, ", Signature="
, signature.text
]
{-| Signing AWS requests with Signature Version 4 <https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html>
import Time
import AWS.Types exposing (..)
nowMillisecond : Int
nowMillisecond =
1440938160000
requestDateTime : Time.Posix
requestDateTime =
Time.millisToPosix nowMillisecond
awsConfig : Config
awsConfig =
{ awsSecretAccessKey = "<KEY>"
, awsRegion = "us-east-1"
, accessKeyId = ""
, timeout = Just 1234
}
sign
awsConfig
ServiceIam
requestDateTime
{ method = "GET"
, query =
[ ( "Action", "ListUsers" )
, ( "Version", "2010-05-08" )
]
, headers =
[ ( "Content-Type", "application/x-www-form-urlencoded; charset=utf-8" )
]
, payload = ""
} |> Result.map .text
--> Ok "5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7"
NOTE: this function is only exposed to allow testing
-}
sign :
Config
-> Service
-> Time.Posix
->
{ method : String
, query : List ( String, String )
, headers : List ( String, String )
, payload : String
}
-> Result String Signature
sign config service now request =
let
url =
endpoint config service
yyyymmddThhmmssz =
DateFormat.format
[ DateFormat.yearNumber
, DateFormat.monthFixed
, DateFormat.dayOfMonthFixed
, DateFormat.text "T"
, DateFormat.hourMilitaryFixed
, DateFormat.minuteFixed
, DateFormat.secondFixed
, DateFormat.text "Z"
]
Time.utc
now
yyyymmdd =
DateFormat.format
[ DateFormat.yearNumber
, DateFormat.monthFixed
, DateFormat.dayOfMonthFixed
]
Time.utc
now
headers =
request.headers
|> List.append
[ ( "X-Amz-Date", yyyymmddThhmmssz )
, ( "Host", url.host )
]
credentialScope =
String.join "/" [ yyyymmdd, config.awsRegion, serviceName service, "aws4_request" ]
signedHeaders =
canonicalHeaderKeys headers
canonicalRequest =
String.join "\n"
[ request.method
, url.path
, canonicalQuery request.query
, canonicalHeaders headers
, signedHeaders
, Crypto.Hash.sha256 request.payload
]
stringToSign =
String.join "\n"
[ algorithm
, yyyymmddThhmmssz
, credentialScope
, Crypto.Hash.sha256 canonicalRequest
]
signingKey =
Word.Bytes.fromUTF8 ("AWS4" ++ config.awsSecretAccessKey)
|> (\k -> Crypto.HMAC.digestBytes Crypto.HMAC.sha256 k (Word.Bytes.fromUTF8 yyyymmdd))
|> (\k -> Crypto.HMAC.digestBytes Crypto.HMAC.sha256 k (Word.Bytes.fromUTF8 config.awsRegion))
|> (\k -> Crypto.HMAC.digestBytes Crypto.HMAC.sha256 k (Word.Bytes.fromUTF8 (serviceName service)))
|> (\k -> Crypto.HMAC.digestBytes Crypto.HMAC.sha256 k (Word.Bytes.fromUTF8 "aws4_request"))
result =
case List.head (List.filter (\( k, v ) -> String.toLower k == "host") request.headers) of
Nothing ->
-- ok, we can proceed to sign
Crypto.HMAC.digestBytes Crypto.HMAC.sha256 signingKey (Word.Bytes.fromUTF8 stringToSign)
|> Base16.encode
Just s ->
-- since the sign function is already a Result, let's fail explicitly
Err "Manually specifying `Host` header is not allowed by xhr2"
in
case result of
Err err ->
Err err
Ok text ->
Ok
{ text = String.toLower text
, credentialScope = credentialScope
, headers = headers
, signedHeaders = signedHeaders
, algorithm = algorithm
}
canonicalQuery : List ( String, String ) -> String
canonicalQuery keyValues =
List.sortBy (\( k, v ) -> k ++ v) keyValues
|> List.map (\( k, v ) -> awsPercentEncode k ++ "=" ++ awsPercentEncode v)
|> String.join "&"
canonicalHeaders : List ( String, String ) -> String
canonicalHeaders keyValues =
List.map (\( k, v ) -> ( String.toLower k, String.trim v )) keyValues
|> List.sortBy Tuple.first
|> List.map (\( k, v ) -> k ++ ":" ++ v ++ "\n")
|> String.join ""
canonicalHeaderKeys : List ( String, String ) -> String
canonicalHeaderKeys keyValues =
List.map (\( k, v ) -> String.toLower k) keyValues
|> List.sort
|> String.join ";"
{-|
awsPercentEncode "Az09-_.~!*'()"
--> "Az09-_.~%21%2A%27%28%29"
awsPercentEncode "space "
--> "space%20"
awsPercentEncode "🙂"
--> "%F0%9F%99%82"
awsPercentEncode "equal=sign"
--> "equal%3Dsign"
awsPercentEncode "<EMAIL>"
--> "bob%40example.com"
-}
awsPercentEncode : String -> String
awsPercentEncode string =
Url.percentEncode string
|> String.replace "!" "%21"
|> String.replace "*" "%2A"
|> String.replace "'" "%27"
|> String.replace "(" "%28"
|> String.replace ")" "%29"
{-| If http response body does not contain expected String, return as Http.BadBody error
-}
stringMatchHttpResponse : String -> Http.Response String -> Result Http.Error ()
stringMatchHttpResponse needle resp =
let
matchResult haystack =
if String.contains needle haystack then
Ok ()
else
Err (Http.BadBody ("[" ++ needle ++ "] not found: " ++ haystack))
in
case resp of
Http.GoodStatus_ m s ->
matchResult s
Http.BadUrl_ s ->
Err (Http.BadUrl s)
Http.Timeout_ ->
Err Http.Timeout
Http.NetworkError_ ->
Err Http.NetworkError
Http.BadStatus_ m s ->
Err (Http.BadStatus m.statusCode)
{-| applies a decoder to response of `Http.task`
To do JSON decoding:
Http.task
{ resolver = Http.stringResolver (decodeHttpResponse (Json.Decode.decodeString thingDecoder) Json.Decode.errorToString)
, ...
}
To do XML decoding
Http.task
{ resolver = Http.stringResolver (decodeHttpResponse (Xml.Decode.decodeString thingDecoder) identity)
, ...
}
-}
decodeHttpResponse : (b -> Result e a) -> (e -> String) -> Http.Response b -> Result Http.Error a
decodeHttpResponse decode errorToString resp =
case resp of
Http.GoodStatus_ m s ->
decode s
|> Result.mapError (errorToString >> Http.BadBody)
Http.BadUrl_ s ->
Err (Http.BadUrl s)
Http.Timeout_ ->
Err Http.Timeout
Http.NetworkError_ ->
Err Http.NetworkError
Http.BadStatus_ m s ->
decode s
-- best effort attempt to decode the response body, but fallback to `Http.BadStatus`
|> Result.mapError (always (Http.BadStatus m.statusCode))
| true | module AWS.Internal exposing (..)
import AWS.Types exposing (..)
import Base16
import Crypto.HMAC
import Crypto.Hash
import DateFormat
import Http
import Json.Decode
import Json.Encode
import Task exposing (Task)
import Time
import Url
import Url.Builder
import Word.Bytes
endpoint : Config -> Service -> Url.Url
endpoint { awsRegion } service =
let
urlWithoutRegion =
{ protocol = Url.Https
, host = serviceName service ++ ".amazonaws.com"
, port_ = Nothing
, path = "/"
, query = Nothing
, fragment = Nothing
}
in
case service of
ServiceIam ->
urlWithoutRegion
ServiceDynamoDB ->
{ urlWithoutRegion | host = serviceName service ++ "." ++ awsRegion ++ ".amazonaws.com" }
ServiceSES ->
{ urlWithoutRegion | host = serviceName service ++ "." ++ awsRegion ++ ".amazonaws.com" }
ServiceSQS url ->
url
serviceName : Service -> String
serviceName service =
case service of
ServiceIam ->
"iam"
ServiceDynamoDB ->
"dynamodb"
ServiceSES ->
"email"
ServiceSQS _ ->
"sqs"
algorithm =
"AWS4-HMAC-SHA256"
authorizationHeader : Config -> Signature -> String
authorizationHeader config signature =
String.join ""
[ algorithm
, " Credential="
, config.accessKeyId
, "/"
, signature.credentialScope
, ", SignedHeaders="
, signature.signedHeaders
, ", Signature="
, signature.text
]
{-| Signing AWS requests with Signature Version 4 <https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html>
import Time
import AWS.Types exposing (..)
nowMillisecond : Int
nowMillisecond =
1440938160000
requestDateTime : Time.Posix
requestDateTime =
Time.millisToPosix nowMillisecond
awsConfig : Config
awsConfig =
{ awsSecretAccessKey = "PI:KEY:<KEY>END_PI"
, awsRegion = "us-east-1"
, accessKeyId = ""
, timeout = Just 1234
}
sign
awsConfig
ServiceIam
requestDateTime
{ method = "GET"
, query =
[ ( "Action", "ListUsers" )
, ( "Version", "2010-05-08" )
]
, headers =
[ ( "Content-Type", "application/x-www-form-urlencoded; charset=utf-8" )
]
, payload = ""
} |> Result.map .text
--> Ok "5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7"
NOTE: this function is only exposed to allow testing
-}
sign :
Config
-> Service
-> Time.Posix
->
{ method : String
, query : List ( String, String )
, headers : List ( String, String )
, payload : String
}
-> Result String Signature
sign config service now request =
let
url =
endpoint config service
yyyymmddThhmmssz =
DateFormat.format
[ DateFormat.yearNumber
, DateFormat.monthFixed
, DateFormat.dayOfMonthFixed
, DateFormat.text "T"
, DateFormat.hourMilitaryFixed
, DateFormat.minuteFixed
, DateFormat.secondFixed
, DateFormat.text "Z"
]
Time.utc
now
yyyymmdd =
DateFormat.format
[ DateFormat.yearNumber
, DateFormat.monthFixed
, DateFormat.dayOfMonthFixed
]
Time.utc
now
headers =
request.headers
|> List.append
[ ( "X-Amz-Date", yyyymmddThhmmssz )
, ( "Host", url.host )
]
credentialScope =
String.join "/" [ yyyymmdd, config.awsRegion, serviceName service, "aws4_request" ]
signedHeaders =
canonicalHeaderKeys headers
canonicalRequest =
String.join "\n"
[ request.method
, url.path
, canonicalQuery request.query
, canonicalHeaders headers
, signedHeaders
, Crypto.Hash.sha256 request.payload
]
stringToSign =
String.join "\n"
[ algorithm
, yyyymmddThhmmssz
, credentialScope
, Crypto.Hash.sha256 canonicalRequest
]
signingKey =
Word.Bytes.fromUTF8 ("AWS4" ++ config.awsSecretAccessKey)
|> (\k -> Crypto.HMAC.digestBytes Crypto.HMAC.sha256 k (Word.Bytes.fromUTF8 yyyymmdd))
|> (\k -> Crypto.HMAC.digestBytes Crypto.HMAC.sha256 k (Word.Bytes.fromUTF8 config.awsRegion))
|> (\k -> Crypto.HMAC.digestBytes Crypto.HMAC.sha256 k (Word.Bytes.fromUTF8 (serviceName service)))
|> (\k -> Crypto.HMAC.digestBytes Crypto.HMAC.sha256 k (Word.Bytes.fromUTF8 "aws4_request"))
result =
case List.head (List.filter (\( k, v ) -> String.toLower k == "host") request.headers) of
Nothing ->
-- ok, we can proceed to sign
Crypto.HMAC.digestBytes Crypto.HMAC.sha256 signingKey (Word.Bytes.fromUTF8 stringToSign)
|> Base16.encode
Just s ->
-- since the sign function is already a Result, let's fail explicitly
Err "Manually specifying `Host` header is not allowed by xhr2"
in
case result of
Err err ->
Err err
Ok text ->
Ok
{ text = String.toLower text
, credentialScope = credentialScope
, headers = headers
, signedHeaders = signedHeaders
, algorithm = algorithm
}
canonicalQuery : List ( String, String ) -> String
canonicalQuery keyValues =
List.sortBy (\( k, v ) -> k ++ v) keyValues
|> List.map (\( k, v ) -> awsPercentEncode k ++ "=" ++ awsPercentEncode v)
|> String.join "&"
canonicalHeaders : List ( String, String ) -> String
canonicalHeaders keyValues =
List.map (\( k, v ) -> ( String.toLower k, String.trim v )) keyValues
|> List.sortBy Tuple.first
|> List.map (\( k, v ) -> k ++ ":" ++ v ++ "\n")
|> String.join ""
canonicalHeaderKeys : List ( String, String ) -> String
canonicalHeaderKeys keyValues =
List.map (\( k, v ) -> String.toLower k) keyValues
|> List.sort
|> String.join ";"
{-|
awsPercentEncode "Az09-_.~!*'()"
--> "Az09-_.~%21%2A%27%28%29"
awsPercentEncode "space "
--> "space%20"
awsPercentEncode "🙂"
--> "%F0%9F%99%82"
awsPercentEncode "equal=sign"
--> "equal%3Dsign"
awsPercentEncode "PI:EMAIL:<EMAIL>END_PI"
--> "bob%40example.com"
-}
awsPercentEncode : String -> String
awsPercentEncode string =
Url.percentEncode string
|> String.replace "!" "%21"
|> String.replace "*" "%2A"
|> String.replace "'" "%27"
|> String.replace "(" "%28"
|> String.replace ")" "%29"
{-| If http response body does not contain expected String, return as Http.BadBody error
-}
stringMatchHttpResponse : String -> Http.Response String -> Result Http.Error ()
stringMatchHttpResponse needle resp =
let
matchResult haystack =
if String.contains needle haystack then
Ok ()
else
Err (Http.BadBody ("[" ++ needle ++ "] not found: " ++ haystack))
in
case resp of
Http.GoodStatus_ m s ->
matchResult s
Http.BadUrl_ s ->
Err (Http.BadUrl s)
Http.Timeout_ ->
Err Http.Timeout
Http.NetworkError_ ->
Err Http.NetworkError
Http.BadStatus_ m s ->
Err (Http.BadStatus m.statusCode)
{-| applies a decoder to response of `Http.task`
To do JSON decoding:
Http.task
{ resolver = Http.stringResolver (decodeHttpResponse (Json.Decode.decodeString thingDecoder) Json.Decode.errorToString)
, ...
}
To do XML decoding
Http.task
{ resolver = Http.stringResolver (decodeHttpResponse (Xml.Decode.decodeString thingDecoder) identity)
, ...
}
-}
decodeHttpResponse : (b -> Result e a) -> (e -> String) -> Http.Response b -> Result Http.Error a
decodeHttpResponse decode errorToString resp =
case resp of
Http.GoodStatus_ m s ->
decode s
|> Result.mapError (errorToString >> Http.BadBody)
Http.BadUrl_ s ->
Err (Http.BadUrl s)
Http.Timeout_ ->
Err Http.Timeout
Http.NetworkError_ ->
Err Http.NetworkError
Http.BadStatus_ m s ->
decode s
-- best effort attempt to decode the response body, but fallback to `Http.BadStatus`
|> Result.mapError (always (Http.BadStatus m.statusCode))
| elm |
[
{
"context": " , textField (FormField \"text\" \"name\" \"Smith, Co.\" model.name NameChanged True) model.errors\n ",
"end": 8705,
"score": 0.8216220737,
"start": 8696,
"tag": "NAME",
"value": "Smith, Co"
},
{
"context": " , name \"slug\"\n , placeholder \"smith-co\"\n , value slug\n ",
"end": 10439,
"score": 0.9923008084,
"start": 10431,
"tag": "USERNAME",
"value": "smith-co"
}
] | assets/elm/src/Page/NewSpace.elm | mindriot101/level | 928 | module Page.NewSpace exposing (Model, Msg(..), consumeEvent, init, setup, slugify, subscriptions, teardown, title, update, view)
import Avatar
import Beacon
import Browser.Navigation as Nav
import Connection exposing (Connection)
import Device exposing (Device)
import Event exposing (Event)
import Globals exposing (Globals)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onBlur, onClick, onInput)
import Id exposing (Id)
import Layout.UserDesktop
import Layout.UserMobile
import Mutation.CreateSpace as CreateSpace
import PageError exposing (PageError)
import Query.Viewer as Viewer
import Regex exposing (Regex)
import Repo exposing (Repo)
import Route
import Route.WelcomeTutorial
import Scroll
import Session exposing (Session)
import Space exposing (Space)
import Task exposing (Task)
import User exposing (User)
import ValidationError exposing (ValidationError, errorView, isInvalid)
import Vendor.Keys as Keys exposing (Modifier(..), enter, onKeydown, preventDefault)
-- MODEL
type alias Model =
{ viewerId : Id
, name : String
, slug : String
, errors : List ValidationError
, formState : FormState
-- MOBILE
, showNav : Bool
, showSidebar : Bool
}
type FormState
= Idle
| Submitting
type alias Data =
{ viewer : User
}
resolveData : Repo -> Model -> Maybe Data
resolveData repo model =
Maybe.map Data
(Repo.getUser model.viewerId repo)
-- PAGE PROPERTIES
title : String
title =
"Create a team"
-- LIFECYCLE
init : Globals -> Task PageError ( Globals, Model )
init globals =
case Session.getUserId globals.session of
Just viewerId ->
let
model =
Model
viewerId
""
""
[]
Idle
False
False
in
Task.succeed ( globals, model )
_ ->
Task.fail PageError.NotFound
setup : Model -> Cmd Msg
setup model =
Cmd.batch
[ Scroll.toDocumentTop NoOp
, Beacon.init
]
teardown : Model -> Cmd Msg
teardown model =
Beacon.destroy
-- UPDATE
type Msg
= NameChanged String
| SlugChanged String
| Submit
| Submitted (Result Session.Error ( Session, CreateSpace.Response ))
| NoOp
| ToggleKeyboardCommands
| ToggleNotifications
| InternalLinkClicked String
-- MOBILE
| NavToggled
| SidebarToggled
| ScrollTopClicked
update : Msg -> Globals -> Nav.Key -> Model -> ( ( Model, Cmd Msg ), Globals )
update msg globals navKey model =
case msg of
NameChanged val ->
( ( { model | name = val, slug = slugify val }, Cmd.none ), globals )
SlugChanged val ->
( ( { model | slug = val }, Cmd.none ), globals )
Submit ->
let
cmd =
globals.session
|> CreateSpace.request model.name model.slug
|> Task.attempt Submitted
in
( ( { model | formState = Submitting }, cmd ), globals )
Submitted (Ok ( newSession, CreateSpace.Success space )) ->
let
tutorialParams =
Route.WelcomeTutorial.init (Space.slug space) 1
in
( ( model, Route.pushUrl navKey (Route.WelcomeTutorial tutorialParams) )
, { globals | session = newSession }
)
Submitted (Ok ( newSession, CreateSpace.Invalid errors )) ->
( ( { model | errors = errors, formState = Idle }, Cmd.none )
, { globals | session = newSession }
)
Submitted (Err _) ->
( ( { model | formState = Idle }, Cmd.none ), globals )
NoOp ->
( ( model, Cmd.none ), globals )
ToggleKeyboardCommands ->
( ( model, Cmd.none ), { globals | showKeyboardCommands = not globals.showKeyboardCommands } )
ToggleNotifications ->
( ( model, Cmd.none ), { globals | showNotifications = not globals.showNotifications } )
InternalLinkClicked pathname ->
( ( model, Nav.pushUrl globals.navKey pathname ), globals )
NavToggled ->
( ( { model | showNav = not model.showNav }, Cmd.none ), globals )
SidebarToggled ->
( ( { model | showSidebar = not model.showSidebar }, Cmd.none ), globals )
ScrollTopClicked ->
( ( model, Scroll.toDocumentTop NoOp ), globals )
specialCharRegex : Regex
specialCharRegex =
Maybe.withDefault Regex.never <|
Regex.fromString "[^a-z0-9]+"
paddedDashRegex : Regex
paddedDashRegex =
Maybe.withDefault Regex.never <|
Regex.fromString "(^-|-$)"
slugify : String -> String
slugify name =
name
|> String.toLower
|> Regex.replace specialCharRegex (\_ -> "-")
|> Regex.replace paddedDashRegex (\_ -> "")
|> String.slice 0 20
-- EVENTS
consumeEvent : Event -> Model -> ( Model, Cmd Msg )
consumeEvent event model =
( model, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Sub Msg
subscriptions =
Sub.none
-- VIEW
type alias FormField =
{ type_ : String
, name : String
, placeholder : String
, value : String
, onInput : String -> Msg
, autofocus : Bool
}
view : Globals -> Model -> Html Msg
view globals model =
case resolveData globals.repo model of
Just data ->
resolvedView globals model data
Nothing ->
text "Something went wrong."
resolvedView : Globals -> Model -> Data -> Html Msg
resolvedView globals model data =
case globals.device of
Device.Desktop ->
resolvedDesktopView globals model data
Device.Mobile ->
resolvedMobileView globals model data
resolvedDesktopView : Globals -> Model -> Data -> Html Msg
resolvedDesktopView globals model data =
let
config =
{ globals = globals
, viewer = data.viewer
, onNoOp = NoOp
, onToggleKeyboardCommands = ToggleKeyboardCommands
, onPageClicked = NoOp
}
in
Layout.UserDesktop.layout config
[ div
[ classList
[ ( "mx-auto max-w-xs leading-normal py-24", True )
, ( "shake", not (List.isEmpty model.errors) )
]
]
[ div [ class "pb-6" ]
[ h1 [ class "pb-4 font-bold tracking-semi-tight text-3xl" ] [ text "Create a team" ]
, p [] [ text "Try Level free for 30 days. Once you create your team, you can invite your teammates to join you!" ]
]
, formFields model
, button
[ type_ "submit"
, class "btn btn-blue"
, onClick Submit
, disabled (model.formState == Submitting)
]
[ text "Create my team" ]
]
]
resolvedMobileView : Globals -> Model -> Data -> Html Msg
resolvedMobileView globals model data =
let
config =
{ globals = globals
, viewer = data.viewer
, title = "New Team"
, showNav = model.showNav
, onNavToggled = NavToggled
, onSidebarToggled = SidebarToggled
, onScrollTopClicked = ScrollTopClicked
, onNoOp = NoOp
, leftControl = Layout.UserMobile.Back Route.Spaces
, rightControl =
Layout.UserMobile.Custom <|
button
[ type_ "submit"
, class "btn btn-blue btn-md"
, onClick Submit
, disabled (model.formState == Submitting)
]
[ text "Create" ]
}
in
Layout.UserMobile.layout config
[ div
[ classList
[ ( "p-5", True )
, ( "shake", not (List.isEmpty model.errors) )
]
]
[ div [ class "pb-6" ]
[ p [] [ text "Try Level free for 30 days. Once you create your team, you can invite your teammates to join you!" ]
]
, formFields model
]
]
-- SHARED
formFields : Model -> Html Msg
formFields model =
div []
[ div [ class "pb-6" ]
[ label [ for "name", class "input-label" ] [ text "Name your team" ]
, textField (FormField "text" "name" "Smith, Co." model.name NameChanged True) model.errors
]
, div [ class "pb-6" ]
[ label [ for "slug", class "input-label" ] [ text "Pick your URL" ]
, slugField model.slug model.errors
]
]
textField : FormField -> List ValidationError -> Html Msg
textField field errors =
let
classes =
[ ( "input-field w-full", True )
, ( "input-field-error", isInvalid field.name errors )
]
in
div []
[ input
[ id field.name
, type_ field.type_
, classList classes
, name field.name
, placeholder field.placeholder
, value field.value
, onInput field.onInput
, autofocus field.autofocus
, onKeydown preventDefault [ ( [], enter, \event -> Submit ) ]
]
[]
, errorView field.name errors
]
slugField : String -> List ValidationError -> Html Msg
slugField slug errors =
let
classes =
[ ( "input-field inline-flex leading-none items-baseline", True )
, ( "input-field-error", isInvalid "slug" errors )
]
in
div []
[ div [ classList classes ]
[ label
[ for "slug"
, class "flex-none text-dusty-blue-darker select-none"
]
[ text "levelteams.com/" ]
, div [ class "flex-1" ]
[ input
[ id "slug"
, type_ "text"
, class "placeholder-blue w-full p-0 no-outline text-dusty-blue-darker"
, name "slug"
, placeholder "smith-co"
, value slug
, onInput SlugChanged
, onKeydown preventDefault [ ( [], enter, \event -> Submit ) ]
]
[]
]
]
, errorView "slug" errors
]
| 5421 | module Page.NewSpace exposing (Model, Msg(..), consumeEvent, init, setup, slugify, subscriptions, teardown, title, update, view)
import Avatar
import Beacon
import Browser.Navigation as Nav
import Connection exposing (Connection)
import Device exposing (Device)
import Event exposing (Event)
import Globals exposing (Globals)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onBlur, onClick, onInput)
import Id exposing (Id)
import Layout.UserDesktop
import Layout.UserMobile
import Mutation.CreateSpace as CreateSpace
import PageError exposing (PageError)
import Query.Viewer as Viewer
import Regex exposing (Regex)
import Repo exposing (Repo)
import Route
import Route.WelcomeTutorial
import Scroll
import Session exposing (Session)
import Space exposing (Space)
import Task exposing (Task)
import User exposing (User)
import ValidationError exposing (ValidationError, errorView, isInvalid)
import Vendor.Keys as Keys exposing (Modifier(..), enter, onKeydown, preventDefault)
-- MODEL
type alias Model =
{ viewerId : Id
, name : String
, slug : String
, errors : List ValidationError
, formState : FormState
-- MOBILE
, showNav : Bool
, showSidebar : Bool
}
type FormState
= Idle
| Submitting
type alias Data =
{ viewer : User
}
resolveData : Repo -> Model -> Maybe Data
resolveData repo model =
Maybe.map Data
(Repo.getUser model.viewerId repo)
-- PAGE PROPERTIES
title : String
title =
"Create a team"
-- LIFECYCLE
init : Globals -> Task PageError ( Globals, Model )
init globals =
case Session.getUserId globals.session of
Just viewerId ->
let
model =
Model
viewerId
""
""
[]
Idle
False
False
in
Task.succeed ( globals, model )
_ ->
Task.fail PageError.NotFound
setup : Model -> Cmd Msg
setup model =
Cmd.batch
[ Scroll.toDocumentTop NoOp
, Beacon.init
]
teardown : Model -> Cmd Msg
teardown model =
Beacon.destroy
-- UPDATE
type Msg
= NameChanged String
| SlugChanged String
| Submit
| Submitted (Result Session.Error ( Session, CreateSpace.Response ))
| NoOp
| ToggleKeyboardCommands
| ToggleNotifications
| InternalLinkClicked String
-- MOBILE
| NavToggled
| SidebarToggled
| ScrollTopClicked
update : Msg -> Globals -> Nav.Key -> Model -> ( ( Model, Cmd Msg ), Globals )
update msg globals navKey model =
case msg of
NameChanged val ->
( ( { model | name = val, slug = slugify val }, Cmd.none ), globals )
SlugChanged val ->
( ( { model | slug = val }, Cmd.none ), globals )
Submit ->
let
cmd =
globals.session
|> CreateSpace.request model.name model.slug
|> Task.attempt Submitted
in
( ( { model | formState = Submitting }, cmd ), globals )
Submitted (Ok ( newSession, CreateSpace.Success space )) ->
let
tutorialParams =
Route.WelcomeTutorial.init (Space.slug space) 1
in
( ( model, Route.pushUrl navKey (Route.WelcomeTutorial tutorialParams) )
, { globals | session = newSession }
)
Submitted (Ok ( newSession, CreateSpace.Invalid errors )) ->
( ( { model | errors = errors, formState = Idle }, Cmd.none )
, { globals | session = newSession }
)
Submitted (Err _) ->
( ( { model | formState = Idle }, Cmd.none ), globals )
NoOp ->
( ( model, Cmd.none ), globals )
ToggleKeyboardCommands ->
( ( model, Cmd.none ), { globals | showKeyboardCommands = not globals.showKeyboardCommands } )
ToggleNotifications ->
( ( model, Cmd.none ), { globals | showNotifications = not globals.showNotifications } )
InternalLinkClicked pathname ->
( ( model, Nav.pushUrl globals.navKey pathname ), globals )
NavToggled ->
( ( { model | showNav = not model.showNav }, Cmd.none ), globals )
SidebarToggled ->
( ( { model | showSidebar = not model.showSidebar }, Cmd.none ), globals )
ScrollTopClicked ->
( ( model, Scroll.toDocumentTop NoOp ), globals )
specialCharRegex : Regex
specialCharRegex =
Maybe.withDefault Regex.never <|
Regex.fromString "[^a-z0-9]+"
paddedDashRegex : Regex
paddedDashRegex =
Maybe.withDefault Regex.never <|
Regex.fromString "(^-|-$)"
slugify : String -> String
slugify name =
name
|> String.toLower
|> Regex.replace specialCharRegex (\_ -> "-")
|> Regex.replace paddedDashRegex (\_ -> "")
|> String.slice 0 20
-- EVENTS
consumeEvent : Event -> Model -> ( Model, Cmd Msg )
consumeEvent event model =
( model, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Sub Msg
subscriptions =
Sub.none
-- VIEW
type alias FormField =
{ type_ : String
, name : String
, placeholder : String
, value : String
, onInput : String -> Msg
, autofocus : Bool
}
view : Globals -> Model -> Html Msg
view globals model =
case resolveData globals.repo model of
Just data ->
resolvedView globals model data
Nothing ->
text "Something went wrong."
resolvedView : Globals -> Model -> Data -> Html Msg
resolvedView globals model data =
case globals.device of
Device.Desktop ->
resolvedDesktopView globals model data
Device.Mobile ->
resolvedMobileView globals model data
resolvedDesktopView : Globals -> Model -> Data -> Html Msg
resolvedDesktopView globals model data =
let
config =
{ globals = globals
, viewer = data.viewer
, onNoOp = NoOp
, onToggleKeyboardCommands = ToggleKeyboardCommands
, onPageClicked = NoOp
}
in
Layout.UserDesktop.layout config
[ div
[ classList
[ ( "mx-auto max-w-xs leading-normal py-24", True )
, ( "shake", not (List.isEmpty model.errors) )
]
]
[ div [ class "pb-6" ]
[ h1 [ class "pb-4 font-bold tracking-semi-tight text-3xl" ] [ text "Create a team" ]
, p [] [ text "Try Level free for 30 days. Once you create your team, you can invite your teammates to join you!" ]
]
, formFields model
, button
[ type_ "submit"
, class "btn btn-blue"
, onClick Submit
, disabled (model.formState == Submitting)
]
[ text "Create my team" ]
]
]
resolvedMobileView : Globals -> Model -> Data -> Html Msg
resolvedMobileView globals model data =
let
config =
{ globals = globals
, viewer = data.viewer
, title = "New Team"
, showNav = model.showNav
, onNavToggled = NavToggled
, onSidebarToggled = SidebarToggled
, onScrollTopClicked = ScrollTopClicked
, onNoOp = NoOp
, leftControl = Layout.UserMobile.Back Route.Spaces
, rightControl =
Layout.UserMobile.Custom <|
button
[ type_ "submit"
, class "btn btn-blue btn-md"
, onClick Submit
, disabled (model.formState == Submitting)
]
[ text "Create" ]
}
in
Layout.UserMobile.layout config
[ div
[ classList
[ ( "p-5", True )
, ( "shake", not (List.isEmpty model.errors) )
]
]
[ div [ class "pb-6" ]
[ p [] [ text "Try Level free for 30 days. Once you create your team, you can invite your teammates to join you!" ]
]
, formFields model
]
]
-- SHARED
formFields : Model -> Html Msg
formFields model =
div []
[ div [ class "pb-6" ]
[ label [ for "name", class "input-label" ] [ text "Name your team" ]
, textField (FormField "text" "name" "<NAME>." model.name NameChanged True) model.errors
]
, div [ class "pb-6" ]
[ label [ for "slug", class "input-label" ] [ text "Pick your URL" ]
, slugField model.slug model.errors
]
]
textField : FormField -> List ValidationError -> Html Msg
textField field errors =
let
classes =
[ ( "input-field w-full", True )
, ( "input-field-error", isInvalid field.name errors )
]
in
div []
[ input
[ id field.name
, type_ field.type_
, classList classes
, name field.name
, placeholder field.placeholder
, value field.value
, onInput field.onInput
, autofocus field.autofocus
, onKeydown preventDefault [ ( [], enter, \event -> Submit ) ]
]
[]
, errorView field.name errors
]
slugField : String -> List ValidationError -> Html Msg
slugField slug errors =
let
classes =
[ ( "input-field inline-flex leading-none items-baseline", True )
, ( "input-field-error", isInvalid "slug" errors )
]
in
div []
[ div [ classList classes ]
[ label
[ for "slug"
, class "flex-none text-dusty-blue-darker select-none"
]
[ text "levelteams.com/" ]
, div [ class "flex-1" ]
[ input
[ id "slug"
, type_ "text"
, class "placeholder-blue w-full p-0 no-outline text-dusty-blue-darker"
, name "slug"
, placeholder "smith-co"
, value slug
, onInput SlugChanged
, onKeydown preventDefault [ ( [], enter, \event -> Submit ) ]
]
[]
]
]
, errorView "slug" errors
]
| true | module Page.NewSpace exposing (Model, Msg(..), consumeEvent, init, setup, slugify, subscriptions, teardown, title, update, view)
import Avatar
import Beacon
import Browser.Navigation as Nav
import Connection exposing (Connection)
import Device exposing (Device)
import Event exposing (Event)
import Globals exposing (Globals)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onBlur, onClick, onInput)
import Id exposing (Id)
import Layout.UserDesktop
import Layout.UserMobile
import Mutation.CreateSpace as CreateSpace
import PageError exposing (PageError)
import Query.Viewer as Viewer
import Regex exposing (Regex)
import Repo exposing (Repo)
import Route
import Route.WelcomeTutorial
import Scroll
import Session exposing (Session)
import Space exposing (Space)
import Task exposing (Task)
import User exposing (User)
import ValidationError exposing (ValidationError, errorView, isInvalid)
import Vendor.Keys as Keys exposing (Modifier(..), enter, onKeydown, preventDefault)
-- MODEL
type alias Model =
{ viewerId : Id
, name : String
, slug : String
, errors : List ValidationError
, formState : FormState
-- MOBILE
, showNav : Bool
, showSidebar : Bool
}
type FormState
= Idle
| Submitting
type alias Data =
{ viewer : User
}
resolveData : Repo -> Model -> Maybe Data
resolveData repo model =
Maybe.map Data
(Repo.getUser model.viewerId repo)
-- PAGE PROPERTIES
title : String
title =
"Create a team"
-- LIFECYCLE
init : Globals -> Task PageError ( Globals, Model )
init globals =
case Session.getUserId globals.session of
Just viewerId ->
let
model =
Model
viewerId
""
""
[]
Idle
False
False
in
Task.succeed ( globals, model )
_ ->
Task.fail PageError.NotFound
setup : Model -> Cmd Msg
setup model =
Cmd.batch
[ Scroll.toDocumentTop NoOp
, Beacon.init
]
teardown : Model -> Cmd Msg
teardown model =
Beacon.destroy
-- UPDATE
type Msg
= NameChanged String
| SlugChanged String
| Submit
| Submitted (Result Session.Error ( Session, CreateSpace.Response ))
| NoOp
| ToggleKeyboardCommands
| ToggleNotifications
| InternalLinkClicked String
-- MOBILE
| NavToggled
| SidebarToggled
| ScrollTopClicked
update : Msg -> Globals -> Nav.Key -> Model -> ( ( Model, Cmd Msg ), Globals )
update msg globals navKey model =
case msg of
NameChanged val ->
( ( { model | name = val, slug = slugify val }, Cmd.none ), globals )
SlugChanged val ->
( ( { model | slug = val }, Cmd.none ), globals )
Submit ->
let
cmd =
globals.session
|> CreateSpace.request model.name model.slug
|> Task.attempt Submitted
in
( ( { model | formState = Submitting }, cmd ), globals )
Submitted (Ok ( newSession, CreateSpace.Success space )) ->
let
tutorialParams =
Route.WelcomeTutorial.init (Space.slug space) 1
in
( ( model, Route.pushUrl navKey (Route.WelcomeTutorial tutorialParams) )
, { globals | session = newSession }
)
Submitted (Ok ( newSession, CreateSpace.Invalid errors )) ->
( ( { model | errors = errors, formState = Idle }, Cmd.none )
, { globals | session = newSession }
)
Submitted (Err _) ->
( ( { model | formState = Idle }, Cmd.none ), globals )
NoOp ->
( ( model, Cmd.none ), globals )
ToggleKeyboardCommands ->
( ( model, Cmd.none ), { globals | showKeyboardCommands = not globals.showKeyboardCommands } )
ToggleNotifications ->
( ( model, Cmd.none ), { globals | showNotifications = not globals.showNotifications } )
InternalLinkClicked pathname ->
( ( model, Nav.pushUrl globals.navKey pathname ), globals )
NavToggled ->
( ( { model | showNav = not model.showNav }, Cmd.none ), globals )
SidebarToggled ->
( ( { model | showSidebar = not model.showSidebar }, Cmd.none ), globals )
ScrollTopClicked ->
( ( model, Scroll.toDocumentTop NoOp ), globals )
specialCharRegex : Regex
specialCharRegex =
Maybe.withDefault Regex.never <|
Regex.fromString "[^a-z0-9]+"
paddedDashRegex : Regex
paddedDashRegex =
Maybe.withDefault Regex.never <|
Regex.fromString "(^-|-$)"
slugify : String -> String
slugify name =
name
|> String.toLower
|> Regex.replace specialCharRegex (\_ -> "-")
|> Regex.replace paddedDashRegex (\_ -> "")
|> String.slice 0 20
-- EVENTS
consumeEvent : Event -> Model -> ( Model, Cmd Msg )
consumeEvent event model =
( model, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Sub Msg
subscriptions =
Sub.none
-- VIEW
type alias FormField =
{ type_ : String
, name : String
, placeholder : String
, value : String
, onInput : String -> Msg
, autofocus : Bool
}
view : Globals -> Model -> Html Msg
view globals model =
case resolveData globals.repo model of
Just data ->
resolvedView globals model data
Nothing ->
text "Something went wrong."
resolvedView : Globals -> Model -> Data -> Html Msg
resolvedView globals model data =
case globals.device of
Device.Desktop ->
resolvedDesktopView globals model data
Device.Mobile ->
resolvedMobileView globals model data
resolvedDesktopView : Globals -> Model -> Data -> Html Msg
resolvedDesktopView globals model data =
let
config =
{ globals = globals
, viewer = data.viewer
, onNoOp = NoOp
, onToggleKeyboardCommands = ToggleKeyboardCommands
, onPageClicked = NoOp
}
in
Layout.UserDesktop.layout config
[ div
[ classList
[ ( "mx-auto max-w-xs leading-normal py-24", True )
, ( "shake", not (List.isEmpty model.errors) )
]
]
[ div [ class "pb-6" ]
[ h1 [ class "pb-4 font-bold tracking-semi-tight text-3xl" ] [ text "Create a team" ]
, p [] [ text "Try Level free for 30 days. Once you create your team, you can invite your teammates to join you!" ]
]
, formFields model
, button
[ type_ "submit"
, class "btn btn-blue"
, onClick Submit
, disabled (model.formState == Submitting)
]
[ text "Create my team" ]
]
]
resolvedMobileView : Globals -> Model -> Data -> Html Msg
resolvedMobileView globals model data =
let
config =
{ globals = globals
, viewer = data.viewer
, title = "New Team"
, showNav = model.showNav
, onNavToggled = NavToggled
, onSidebarToggled = SidebarToggled
, onScrollTopClicked = ScrollTopClicked
, onNoOp = NoOp
, leftControl = Layout.UserMobile.Back Route.Spaces
, rightControl =
Layout.UserMobile.Custom <|
button
[ type_ "submit"
, class "btn btn-blue btn-md"
, onClick Submit
, disabled (model.formState == Submitting)
]
[ text "Create" ]
}
in
Layout.UserMobile.layout config
[ div
[ classList
[ ( "p-5", True )
, ( "shake", not (List.isEmpty model.errors) )
]
]
[ div [ class "pb-6" ]
[ p [] [ text "Try Level free for 30 days. Once you create your team, you can invite your teammates to join you!" ]
]
, formFields model
]
]
-- SHARED
formFields : Model -> Html Msg
formFields model =
div []
[ div [ class "pb-6" ]
[ label [ for "name", class "input-label" ] [ text "Name your team" ]
, textField (FormField "text" "name" "PI:NAME:<NAME>END_PI." model.name NameChanged True) model.errors
]
, div [ class "pb-6" ]
[ label [ for "slug", class "input-label" ] [ text "Pick your URL" ]
, slugField model.slug model.errors
]
]
textField : FormField -> List ValidationError -> Html Msg
textField field errors =
let
classes =
[ ( "input-field w-full", True )
, ( "input-field-error", isInvalid field.name errors )
]
in
div []
[ input
[ id field.name
, type_ field.type_
, classList classes
, name field.name
, placeholder field.placeholder
, value field.value
, onInput field.onInput
, autofocus field.autofocus
, onKeydown preventDefault [ ( [], enter, \event -> Submit ) ]
]
[]
, errorView field.name errors
]
slugField : String -> List ValidationError -> Html Msg
slugField slug errors =
let
classes =
[ ( "input-field inline-flex leading-none items-baseline", True )
, ( "input-field-error", isInvalid "slug" errors )
]
in
div []
[ div [ classList classes ]
[ label
[ for "slug"
, class "flex-none text-dusty-blue-darker select-none"
]
[ text "levelteams.com/" ]
, div [ class "flex-1" ]
[ input
[ id "slug"
, type_ "text"
, class "placeholder-blue w-full p-0 no-outline text-dusty-blue-darker"
, name "slug"
, placeholder "smith-co"
, value slug
, onInput SlugChanged
, onKeydown preventDefault [ ( [], enter, \event -> Submit ) ]
]
[]
]
]
, errorView "slug" errors
]
| elm |
[
{
"context": "docs codecIndexRecordEncoder\r\n\r\nCopyright (c) 2016 Robin Luiten\r\n-}\r\n\r\nimport Dict exposing (Dict)\r\nimport Json.E",
"end": 185,
"score": 0.9998289347,
"start": 173,
"tag": "NAME",
"value": "Robin Luiten"
}
] | src/Lunrelm/Json/Encoder.elm | rluiten/lunrelm | 1 | module Lunrelm.Json.Encoder (encoder, codecIndexRecordEncoder) where
{-| Encoder for Lunrelm Index.
@docs encoder
@docs codecIndexRecordEncoder
Copyright (c) 2016 Robin Luiten
-}
import Dict exposing (Dict)
import Json.Encode as Encode
import Set exposing (Set)
import Trie exposing (Trie)
import Trie.Json.Encoder as TrieEncoder
import Index
import IndexModel exposing (..)
{-| Encoder for Index a.
Only encoding fields required to recreate a working index.
The following fields are not saved as they are restored via
the provided Config on fromString.
* ref
* fields
* transformFactories
* filterFactories
The following fields are not saved because they are an
acceleration model, decoder needs to set it on fromString.
* corpusTokensIndex
The following fields are not saved because they are caches
and are cached as operationg requires
* transforms
* filters
* idfCache
Do not need an (a -> Encode.Value) because a is a document
type and that is never encoded from an Index.
-}
encoder : (Index doc) -> Encode.Value
encoder (Index irec) =
codecIndexRecordEncoder
{ indexVersion = irec.indexVersion
, indexType = irec.indexType
, documentStore = irec.documentStore
, corpusTokens = irec.corpusTokens
, tokenStore = irec.tokenStore
}
{-| Encode CodecIndexRecord. -}
codecIndexRecordEncoder : CodecIndexRecord -> Encode.Value
codecIndexRecordEncoder rec =
Encode.object
[ ("indexVersion", Encode.string rec.indexVersion)
, ("indexType", Encode.string rec.indexType)
, ("documentStore", documentStoreEncoder rec.documentStore)
, ("corpusTokens", corpusTokensEncoder rec.corpusTokens)
, ("tokenStore", tokenStore rec.tokenStore)
]
documentStoreEncoder : (Dict String (Set String)) -> Encode.Value
documentStoreEncoder dict =
Encode.object <|
List.map
(\(key, val) ->
( key
, Encode.list
(List.map Encode.string (Set.toList val))
)
)
(Dict.toList dict)
corpusTokensEncoder : Set String -> Encode.Value
corpusTokensEncoder setVal =
Encode.list (List.map Encode.string (Set.toList setVal))
tokenStore : Trie Float -> Encode.Value
tokenStore = TrieEncoder.encoder Encode.float
| 24315 | module Lunrelm.Json.Encoder (encoder, codecIndexRecordEncoder) where
{-| Encoder for Lunrelm Index.
@docs encoder
@docs codecIndexRecordEncoder
Copyright (c) 2016 <NAME>
-}
import Dict exposing (Dict)
import Json.Encode as Encode
import Set exposing (Set)
import Trie exposing (Trie)
import Trie.Json.Encoder as TrieEncoder
import Index
import IndexModel exposing (..)
{-| Encoder for Index a.
Only encoding fields required to recreate a working index.
The following fields are not saved as they are restored via
the provided Config on fromString.
* ref
* fields
* transformFactories
* filterFactories
The following fields are not saved because they are an
acceleration model, decoder needs to set it on fromString.
* corpusTokensIndex
The following fields are not saved because they are caches
and are cached as operationg requires
* transforms
* filters
* idfCache
Do not need an (a -> Encode.Value) because a is a document
type and that is never encoded from an Index.
-}
encoder : (Index doc) -> Encode.Value
encoder (Index irec) =
codecIndexRecordEncoder
{ indexVersion = irec.indexVersion
, indexType = irec.indexType
, documentStore = irec.documentStore
, corpusTokens = irec.corpusTokens
, tokenStore = irec.tokenStore
}
{-| Encode CodecIndexRecord. -}
codecIndexRecordEncoder : CodecIndexRecord -> Encode.Value
codecIndexRecordEncoder rec =
Encode.object
[ ("indexVersion", Encode.string rec.indexVersion)
, ("indexType", Encode.string rec.indexType)
, ("documentStore", documentStoreEncoder rec.documentStore)
, ("corpusTokens", corpusTokensEncoder rec.corpusTokens)
, ("tokenStore", tokenStore rec.tokenStore)
]
documentStoreEncoder : (Dict String (Set String)) -> Encode.Value
documentStoreEncoder dict =
Encode.object <|
List.map
(\(key, val) ->
( key
, Encode.list
(List.map Encode.string (Set.toList val))
)
)
(Dict.toList dict)
corpusTokensEncoder : Set String -> Encode.Value
corpusTokensEncoder setVal =
Encode.list (List.map Encode.string (Set.toList setVal))
tokenStore : Trie Float -> Encode.Value
tokenStore = TrieEncoder.encoder Encode.float
| true | module Lunrelm.Json.Encoder (encoder, codecIndexRecordEncoder) where
{-| Encoder for Lunrelm Index.
@docs encoder
@docs codecIndexRecordEncoder
Copyright (c) 2016 PI:NAME:<NAME>END_PI
-}
import Dict exposing (Dict)
import Json.Encode as Encode
import Set exposing (Set)
import Trie exposing (Trie)
import Trie.Json.Encoder as TrieEncoder
import Index
import IndexModel exposing (..)
{-| Encoder for Index a.
Only encoding fields required to recreate a working index.
The following fields are not saved as they are restored via
the provided Config on fromString.
* ref
* fields
* transformFactories
* filterFactories
The following fields are not saved because they are an
acceleration model, decoder needs to set it on fromString.
* corpusTokensIndex
The following fields are not saved because they are caches
and are cached as operationg requires
* transforms
* filters
* idfCache
Do not need an (a -> Encode.Value) because a is a document
type and that is never encoded from an Index.
-}
encoder : (Index doc) -> Encode.Value
encoder (Index irec) =
codecIndexRecordEncoder
{ indexVersion = irec.indexVersion
, indexType = irec.indexType
, documentStore = irec.documentStore
, corpusTokens = irec.corpusTokens
, tokenStore = irec.tokenStore
}
{-| Encode CodecIndexRecord. -}
codecIndexRecordEncoder : CodecIndexRecord -> Encode.Value
codecIndexRecordEncoder rec =
Encode.object
[ ("indexVersion", Encode.string rec.indexVersion)
, ("indexType", Encode.string rec.indexType)
, ("documentStore", documentStoreEncoder rec.documentStore)
, ("corpusTokens", corpusTokensEncoder rec.corpusTokens)
, ("tokenStore", tokenStore rec.tokenStore)
]
documentStoreEncoder : (Dict String (Set String)) -> Encode.Value
documentStoreEncoder dict =
Encode.object <|
List.map
(\(key, val) ->
( key
, Encode.list
(List.map Encode.string (Set.toList val))
)
)
(Dict.toList dict)
corpusTokensEncoder : Set String -> Encode.Value
corpusTokensEncoder setVal =
Encode.list (List.map Encode.string (Set.toList setVal))
tokenStore : Trie Float -> Encode.Value
tokenStore = TrieEncoder.encoder Encode.float
| elm |
[
{
"context": "text\" ]\n [ h1 [ id \"image-title\" ] [ text \"McKay & Greg\" ]\n , h3 [ id \"image-date\" ] [ text \"",
"end": 8546,
"score": 0.9980083704,
"start": 8541,
"tag": "NAME",
"value": "McKay"
},
{
"context": "\n [ h1 [ id \"image-title\" ] [ text \"McKay & Greg\" ]\n , h3 [ id \"image-date\" ] [ text \"Septe",
"end": 8553,
"score": 0.9785836935,
"start": 8549,
"tag": "NAME",
"value": "Greg"
}
] | src/WeddingSite.Web/wwwroot/elm/index.elm | gatkin/WeddingSite | 1 | import Browser
import Html exposing (Html, a, br, button, div, h1, h2, h3, h5, img, input, p, span, text)
import Html.Attributes exposing (class, disabled, href, id, placeholder, src, target, type_)
import Html.Events exposing (onClick, onInput)
import Http
import Json.Decode exposing (Decoder, field, list, string)
import Json.Encode as Encode
import Set exposing (Set)
import Task
import Time exposing (Posix, millisToPosix, posixToMillis)
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
-- MODEL
type alias GuestId = String
type GuestStatus
= Unregistered
| Attending
| NotAttending
type alias Guest =
{ id: GuestId
, name: String
, status: GuestStatus
, isSelected: Bool
, isVisible: Bool
}
type alias PlusOnePair = (String, String)
type alias GuestResponseModel =
{ id: GuestId
, name: String
}
type alias PlusOneResponseModel =
{ partnerAName: String
, partnerBName: String
}
type alias GetGuestListReponse =
{ guests: List GuestResponseModel
, plusOnes: List PlusOneResponseModel
}
type RsvpSubmissionStatus = NotSubmitted
| WaitingForResponse
| Submitted
type alias Countdown =
{ days: Int
, hours: Int
, minutes: Int
, seconds: Int
}
-- 5:00 PM CDT September 21, 2019
weddingDate : Posix
weddingDate = millisToPosix 1569103200000
millisecondsPerSecond : Int
millisecondsPerSecond = 1000
millisecondsPerMinute : Int
millisecondsPerMinute = millisecondsPerSecond * 60
millisecondsPerHour : Int
millisecondsPerHour = millisecondsPerMinute * 60
millisecondsPerDay : Int
millisecondsPerDay = millisecondsPerHour * 24
type alias Model =
{ guests: List Guest
, plusOnes: List PlusOnePair
, searchString: String
, rsvpSubmissionStatus: RsvpSubmissionStatus
, countdown: Countdown
}
init : () -> (Model, Cmd Msg)
init () =
( { guests = []
, plusOnes = []
, searchString = ""
, rsvpSubmissionStatus = NotSubmitted
, countdown = { days = 0, hours = 0, minutes = 0, seconds = 0 }
}
, initialCommand
)
-- UPDATE
type Msg = GuestListLoaded (Result Http.Error GetGuestListReponse)
| SelectGuest GuestId
| NewSearch String
| AttendingSubmitted
| NotAttendingSubmitted
| RsvpSubmissionResponse (Result Http.Error ())
| AddAnotherRsvp
| Tick Posix
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
GuestListLoaded result ->
case result of
Ok response ->
(onGuestListLoaded response model, Cmd.none)
Err _ ->
(model, Cmd.none)
SelectGuest guestId ->
(onGuestSelected guestId model, Cmd.none)
NewSearch searchString ->
(onNewSearch searchString model, Cmd.none)
AttendingSubmitted ->
onRsvpSubmitted True model
NotAttendingSubmitted ->
onRsvpSubmitted False model
RsvpSubmissionResponse result ->
case result of
Ok _ ->
(onRsvpSubmissionResponse model, Cmd.none)
Err _ ->
(model, Cmd.none)
AddAnotherRsvp ->
(onAddAnotherRsvp model, Cmd.none)
Tick currentTime ->
(onTick currentTime model , Cmd.none)
onGuestListLoaded : GetGuestListReponse -> Model -> Model
onGuestListLoaded response model =
let
guests = response.guests
|> List.map guestResponseModelToGuest
|> List.sortWith orderByName
plusOnes = response.plusOnes |> List.map plusOneResponseModelToPlusOnePair
in
{ model | guests = guests, plusOnes = plusOnes }
orderByName : Guest -> Guest -> Order
orderByName a b =
let
(aFirst, aLast) = getFirstAndLastName a
(bFirst, bLast) = getFirstAndLastName b
in
if aLast == bLast then
compare aFirst bFirst
else
compare aLast bLast
getFirstAndLastName : Guest -> (String, String)
getFirstAndLastName guest =
let
names = String.split " " guest.name
firstName = names |> List.head |> Maybe.withDefault guest.name
lastName = names |> List.drop 1 |> List.head |> Maybe.withDefault guest.name
in
(firstName, lastName)
guestResponseModelToGuest : GuestResponseModel -> Guest
guestResponseModelToGuest model =
{ id = model.id, name = model.name, status = Unregistered, isSelected = False, isVisible = True }
plusOneResponseModelToPlusOnePair : PlusOneResponseModel -> PlusOnePair
plusOneResponseModelToPlusOnePair model =
(model.partnerAName, model.partnerBName)
onGuestSelected : GuestId -> Model -> Model
onGuestSelected guestId model =
let
newGuestList = model.guests |> List.map (selectGuestIfIdMatches guestId)
in
{ model | guests = newGuestList }
selectGuestIfIdMatches : GuestId -> Guest -> Guest
selectGuestIfIdMatches guestId guest =
if guestId == guest.id then
{ guest | isSelected = not guest.isSelected }
else
guest
onNewSearch : String -> Model -> Model
onNewSearch searchString model =
let
cleanSearchString = searchString |> String.trim |> String.toLower
matchingPlusOneNames = getMatchingPlusOneNames cleanSearchString model.plusOnes
newGuestList = filterGuestsOnSearchString cleanSearchString matchingPlusOneNames model.guests
in
{ model | searchString = cleanSearchString, guests = newGuestList }
getMatchingPlusOneNames : String -> List PlusOnePair -> Set String
getMatchingPlusOneNames searchString plusOnes =
plusOnes
|> List.filterMap (getPlusOneNameIfMatchesSearchString searchString)
|> Set.fromList
getPlusOneNameIfMatchesSearchString : String -> PlusOnePair -> Maybe String
getPlusOneNameIfMatchesSearchString searchString (partnerA, partnerB) =
if doesGuestNameMatchSearchString searchString partnerA then
Just partnerB
else if doesGuestNameMatchSearchString searchString partnerB then
Just partnerA
else
Nothing
doesGuestNameMatchSearchString : String -> String -> Bool
doesGuestNameMatchSearchString searchString guestName =
guestName |> String.toLower |> String.contains searchString
filterGuestsOnSearchString : String -> Set String -> List Guest -> List Guest
filterGuestsOnSearchString searchString matchingPlusOneNames guestList =
guestList
|> List.map (\guest -> { guest | isVisible = doesGuestMatchSearchString searchString matchingPlusOneNames guest })
doesGuestMatchSearchString : String -> Set String -> Guest -> Bool
doesGuestMatchSearchString searchString matchingPlusOneNames guest =
String.isEmpty searchString
|| doesGuestNameMatchSearchString searchString guest.name
|| Set.member guest.name matchingPlusOneNames
onRsvpSubmitted : Bool -> Model -> (Model, Cmd Msg)
onRsvpSubmitted isAttending model =
({ model | rsvpSubmissionStatus = WaitingForResponse }, postRsvpRequest isAttending model.guests)
onRsvpSubmissionResponse : Model -> Model
onRsvpSubmissionResponse model =
{ model | rsvpSubmissionStatus = Submitted }
onAddAnotherRsvp : Model -> Model
onAddAnotherRsvp model =
let
newGuests = model.guests |> List.map (\guest -> {guest | isVisible = True, isSelected = False})
in
{ model | searchString = "", rsvpSubmissionStatus = NotSubmitted, guests = newGuests }
onTick : Posix -> Model -> Model
onTick currentTime model =
{ model | countdown = countdownFromTime weddingDate currentTime }
countdownFromTime : Posix -> Posix -> Countdown
countdownFromTime endTime currentTime =
let
currentTimeMs = posixToMillis currentTime
endTimeMs = posixToMillis endTime
timeDiffMs = endTimeMs - currentTimeMs
in
if timeDiffMs < 0 then
{ days = 0, hours = 0, minutes = 0, seconds = 0 }
else
{ days = timeDiffMs // millisecondsPerDay
, hours = (modBy millisecondsPerDay timeDiffMs) // millisecondsPerHour
, minutes = (modBy millisecondsPerHour timeDiffMs) // millisecondsPerMinute
, seconds = (modBy millisecondsPerMinute timeDiffMs) // millisecondsPerSecond
}
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every 1000 Tick
initialCommand : Cmd Msg
initialCommand =
Cmd.batch [ getGuestList, Task.perform Tick Time.now ]
-- VIEW
view : Model -> Html Msg
view model =
div [ class "container-fluid main-container" ]
[ heroImageView
, receptionDetailsView model
, registryDetailsView
, rsvpView model
]
heroImageView : Html Msg
heroImageView =
div [ class "row" ]
[ div [ id "hero-image-col", class "col-12" ]
[ img [ id "hero-image", src "images/Hero.jpg" ] []
, div [ id "image-text" ]
[ h1 [ id "image-title" ] [ text "McKay & Greg" ]
, h3 [ id "image-date" ] [ text "September 21, 2019" ]
, h3 [ id "image-location" ] [ text "Lincoln, NE" ]
]
]
]
receptionDetailsView : Model -> Html Msg
receptionDetailsView model =
div [ class "row details-row" ]
[ div [ class "col-sm-3" ] []
, div [ class "col-sm-6" ]
[ div [ id "reception-details", class "details-container" ]
[ h2 [] [ text "Wedding Reception" ]
, h5 [] [ text "5 PM | September 21, 2019" ]
, h5 [] [ text "Capital Vew Winery" ]
, p [] [ a [ target "_blank", href "https://goo.gl/maps/KPN95RXtjDjqaGK59" ] [ text "2361 Wittstruck Rd | Roca, NE | 68430" ] ]
, p [ class "details-paragraph" ]
[ text "The reception will be held at "
, a [ target "_blank", href "https://capitolviewwinery.com/" ] [ text "Capital View Winery" ]
, text ". Join us for food, wine, and yard games to celebrate our marriage."
]
, countdownView model.countdown
, br [] []
, a [ href "/#rsvp", id "rsvp-button", class "btn btn-lg" ] [ text "RSVP" ]
]
]
, div [ class "col-sm-3" ] [ ]
]
countdownView : Countdown -> Html Msg
countdownView countdown =
div [ id "countdown-container" ]
[ countdownComponentView countdown.days "days"
, countdownComponentView countdown.hours "hours"
, countdownComponentView countdown.minutes "minutes"
, countdownComponentView countdown.seconds "seconds"
]
countdownComponentView : Int -> String -> Html Msg
countdownComponentView value unit =
div [ class "countdown-component" ]
[ span [ class "countdown-value" ] [ text (String.fromInt value) ]
, br [] []
, span [ class "countdown-unit" ] [ text unit ]
]
registryDetailsView : Html Msg
registryDetailsView =
div [ id "registry-row", class "row details-row" ]
[ div [ class "col-sm-3" ] []
, div [ class "col-sm-6" ]
[ div [ class "details-container" ]
[ h2 [] [ text "Registry" ]
, p [ class "details-paragraph" ] [ text "The presence of your company is the only gift we could ever ask for. We will not be registering as we have everything we need to start the next chapter of our lives together." ]
]
]
, div [ class "col-sm-3" ] []
]
rsvpView : Model -> Html Msg
rsvpView model =
let
formView = if model.rsvpSubmissionStatus == Submitted then
completedFormView
else if String.isEmpty model.searchString then
noSearchStringView
else
incompleteFormView model
in
div [ id "rsvp", class "row details-row" ]
[ div [ class "col-12" ]
[ div [ class "details-container" ] [ formView ]
]
]
noSearchStringView : Html Msg
noSearchStringView =
div [ class "container-fluid" ]
[ titleView
, searchBarView False
]
incompleteFormView : Model -> Html Msg
incompleteFormView model =
let
inputDisabled = model.rsvpSubmissionStatus == WaitingForResponse
in
div [ class "container-fluid" ]
[ titleView
, searchBarView inputDisabled
, guestListView model.guests inputDisabled
, submitButtonView model.guests inputDisabled
]
completedFormView : Html Msg
completedFormView =
div [ class "container-fluid"]
[ titleView
, thankYouView
, addAnotherRsvpView
]
titleView : Html Msg
titleView =
div [ class "row", id "title-row" ]
[ div [ class "col-12"]
[ h1 [] [ text "RSVP" ]
, p [] [ text "Please search for your name and let us know if you can attend by September 1st" ]
]
]
searchBarView : Bool -> Html Msg
searchBarView inputDisabled =
div [ class "row", id "search-bar-row" ]
[ div [ class "col-sm-3" ] []
, div [ class "col-sm-6" ]
[ input [ class "form-control", placeholder "Search by your name", onInput NewSearch, disabled inputDisabled ] []
]
, div [ class "col-sm-3" ] []
]
guestListView : List Guest -> Bool -> Html Msg
guestListView guests inputDisabled =
let
guestViews = guests
|> List.filter (\guest -> guest.isVisible)
|> List.map (guestView inputDisabled)
in
div [ class "row" ]
[ div [ class "col-sm-2" ] []
, div [ class "col-sm-8", id "guest-list-container" ] guestViews
, div [ class "col-sm-2" ] []
]
guestView : Bool -> Guest -> Html Msg
guestView inputDisabled guest =
let
buttonOutline = if guest.isSelected then "selected-guest" else "unselected-guest"
buttonClass = "btn " ++ buttonOutline
in
div [ class "guest-name" ]
[ button [ class buttonClass, type_ "button", onClick (SelectGuest guest.id), disabled inputDisabled ]
[ text guest.name ]
]
submitButtonView : List Guest -> Bool -> Html Msg
submitButtonView guestList inputDisabled =
let
anySelectedGuests = guestList |> List.any (\guest -> guest.isVisible && guest.isSelected)
buttonsDisabled = inputDisabled || (not anySelectedGuests)
in
div [ class "submit-button-row row" ]
[ div [ class "col-sm-4" ] []
, div [ class "col-sm-4", id "submit-button-container" ]
[ button [ id "attending-button", class "submit-button btn", type_ "button", disabled buttonsDisabled, onClick AttendingSubmitted ]
[ text "Attending" ]
, button [ id "not-attending-button", class "submit-button btn", type_ "button", disabled buttonsDisabled, onClick NotAttendingSubmitted ]
[ span [ class "spinner-border spinner-border-sm" ] [], text "Not Attending" ]
]
, div [ class "col-4" ] []
]
thankYouView : Html Msg
thankYouView =
div [ class "row" ]
[ div [ class "col-sm-4" ] []
, div [ class "col-sm-4" ]
[ h3 [] [ text "Thank you for your response!" ]
]
, div [ class "col-sm-4" ] []
]
addAnotherRsvpView : Html Msg
addAnotherRsvpView =
div [ class "row add-another-rsvp-row" ]
[ div [ class "col-12" ]
[ button [ id "add-rsvp-btn", class "btn", type_ "button", onClick AddAnotherRsvp ] [ text "Add Another RSVP" ]
]
]
-- HTTP
getGuestList : Cmd Msg
getGuestList =
Http.get
{ url = "/Rsvp/Guests"
, expect = Http.expectJson GuestListLoaded getGuestListResponseDecoder
}
getGuestListResponseDecoder : Decoder GetGuestListReponse
getGuestListResponseDecoder =
Json.Decode.map2 GetGuestListReponse
(field "guests" (list guestResponseModelDecoder))
(field "plusOnes" (list plusOneResponseModelDecoder))
guestResponseModelDecoder : Decoder GuestResponseModel
guestResponseModelDecoder =
Json.Decode.map2 GuestResponseModel
(field "id" string)
(field "name" string)
plusOneResponseModelDecoder : Decoder PlusOneResponseModel
plusOneResponseModelDecoder =
Json.Decode.map2 PlusOneResponseModel
(field "partnerAName" string)
(field "partnerBName" string)
postRsvpRequest : Bool -> List Guest -> Cmd Msg
postRsvpRequest isAttending guests =
let
selectedGuestIds = getSelectedGuestIds guests
jsonRequest = Encode.object
[ ( "GuestIds", Encode.list Encode.string selectedGuestIds )
, ( "IsAttending", Encode.bool isAttending )
]
in
Http.post
{ url = "/Rsvp/Attendance"
, body = Http.jsonBody jsonRequest
, expect = Http.expectWhatever RsvpSubmissionResponse
}
getSelectedGuestIds : List Guest -> List GuestId
getSelectedGuestIds guests =
guests
|> List.filter (\guest -> guest.isSelected && guest.isVisible)
|> List.map (\guest -> guest.id)
| 34915 | import Browser
import Html exposing (Html, a, br, button, div, h1, h2, h3, h5, img, input, p, span, text)
import Html.Attributes exposing (class, disabled, href, id, placeholder, src, target, type_)
import Html.Events exposing (onClick, onInput)
import Http
import Json.Decode exposing (Decoder, field, list, string)
import Json.Encode as Encode
import Set exposing (Set)
import Task
import Time exposing (Posix, millisToPosix, posixToMillis)
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
-- MODEL
type alias GuestId = String
type GuestStatus
= Unregistered
| Attending
| NotAttending
type alias Guest =
{ id: GuestId
, name: String
, status: GuestStatus
, isSelected: Bool
, isVisible: Bool
}
type alias PlusOnePair = (String, String)
type alias GuestResponseModel =
{ id: GuestId
, name: String
}
type alias PlusOneResponseModel =
{ partnerAName: String
, partnerBName: String
}
type alias GetGuestListReponse =
{ guests: List GuestResponseModel
, plusOnes: List PlusOneResponseModel
}
type RsvpSubmissionStatus = NotSubmitted
| WaitingForResponse
| Submitted
type alias Countdown =
{ days: Int
, hours: Int
, minutes: Int
, seconds: Int
}
-- 5:00 PM CDT September 21, 2019
weddingDate : Posix
weddingDate = millisToPosix 1569103200000
millisecondsPerSecond : Int
millisecondsPerSecond = 1000
millisecondsPerMinute : Int
millisecondsPerMinute = millisecondsPerSecond * 60
millisecondsPerHour : Int
millisecondsPerHour = millisecondsPerMinute * 60
millisecondsPerDay : Int
millisecondsPerDay = millisecondsPerHour * 24
type alias Model =
{ guests: List Guest
, plusOnes: List PlusOnePair
, searchString: String
, rsvpSubmissionStatus: RsvpSubmissionStatus
, countdown: Countdown
}
init : () -> (Model, Cmd Msg)
init () =
( { guests = []
, plusOnes = []
, searchString = ""
, rsvpSubmissionStatus = NotSubmitted
, countdown = { days = 0, hours = 0, minutes = 0, seconds = 0 }
}
, initialCommand
)
-- UPDATE
type Msg = GuestListLoaded (Result Http.Error GetGuestListReponse)
| SelectGuest GuestId
| NewSearch String
| AttendingSubmitted
| NotAttendingSubmitted
| RsvpSubmissionResponse (Result Http.Error ())
| AddAnotherRsvp
| Tick Posix
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
GuestListLoaded result ->
case result of
Ok response ->
(onGuestListLoaded response model, Cmd.none)
Err _ ->
(model, Cmd.none)
SelectGuest guestId ->
(onGuestSelected guestId model, Cmd.none)
NewSearch searchString ->
(onNewSearch searchString model, Cmd.none)
AttendingSubmitted ->
onRsvpSubmitted True model
NotAttendingSubmitted ->
onRsvpSubmitted False model
RsvpSubmissionResponse result ->
case result of
Ok _ ->
(onRsvpSubmissionResponse model, Cmd.none)
Err _ ->
(model, Cmd.none)
AddAnotherRsvp ->
(onAddAnotherRsvp model, Cmd.none)
Tick currentTime ->
(onTick currentTime model , Cmd.none)
onGuestListLoaded : GetGuestListReponse -> Model -> Model
onGuestListLoaded response model =
let
guests = response.guests
|> List.map guestResponseModelToGuest
|> List.sortWith orderByName
plusOnes = response.plusOnes |> List.map plusOneResponseModelToPlusOnePair
in
{ model | guests = guests, plusOnes = plusOnes }
orderByName : Guest -> Guest -> Order
orderByName a b =
let
(aFirst, aLast) = getFirstAndLastName a
(bFirst, bLast) = getFirstAndLastName b
in
if aLast == bLast then
compare aFirst bFirst
else
compare aLast bLast
getFirstAndLastName : Guest -> (String, String)
getFirstAndLastName guest =
let
names = String.split " " guest.name
firstName = names |> List.head |> Maybe.withDefault guest.name
lastName = names |> List.drop 1 |> List.head |> Maybe.withDefault guest.name
in
(firstName, lastName)
guestResponseModelToGuest : GuestResponseModel -> Guest
guestResponseModelToGuest model =
{ id = model.id, name = model.name, status = Unregistered, isSelected = False, isVisible = True }
plusOneResponseModelToPlusOnePair : PlusOneResponseModel -> PlusOnePair
plusOneResponseModelToPlusOnePair model =
(model.partnerAName, model.partnerBName)
onGuestSelected : GuestId -> Model -> Model
onGuestSelected guestId model =
let
newGuestList = model.guests |> List.map (selectGuestIfIdMatches guestId)
in
{ model | guests = newGuestList }
selectGuestIfIdMatches : GuestId -> Guest -> Guest
selectGuestIfIdMatches guestId guest =
if guestId == guest.id then
{ guest | isSelected = not guest.isSelected }
else
guest
onNewSearch : String -> Model -> Model
onNewSearch searchString model =
let
cleanSearchString = searchString |> String.trim |> String.toLower
matchingPlusOneNames = getMatchingPlusOneNames cleanSearchString model.plusOnes
newGuestList = filterGuestsOnSearchString cleanSearchString matchingPlusOneNames model.guests
in
{ model | searchString = cleanSearchString, guests = newGuestList }
getMatchingPlusOneNames : String -> List PlusOnePair -> Set String
getMatchingPlusOneNames searchString plusOnes =
plusOnes
|> List.filterMap (getPlusOneNameIfMatchesSearchString searchString)
|> Set.fromList
getPlusOneNameIfMatchesSearchString : String -> PlusOnePair -> Maybe String
getPlusOneNameIfMatchesSearchString searchString (partnerA, partnerB) =
if doesGuestNameMatchSearchString searchString partnerA then
Just partnerB
else if doesGuestNameMatchSearchString searchString partnerB then
Just partnerA
else
Nothing
doesGuestNameMatchSearchString : String -> String -> Bool
doesGuestNameMatchSearchString searchString guestName =
guestName |> String.toLower |> String.contains searchString
filterGuestsOnSearchString : String -> Set String -> List Guest -> List Guest
filterGuestsOnSearchString searchString matchingPlusOneNames guestList =
guestList
|> List.map (\guest -> { guest | isVisible = doesGuestMatchSearchString searchString matchingPlusOneNames guest })
doesGuestMatchSearchString : String -> Set String -> Guest -> Bool
doesGuestMatchSearchString searchString matchingPlusOneNames guest =
String.isEmpty searchString
|| doesGuestNameMatchSearchString searchString guest.name
|| Set.member guest.name matchingPlusOneNames
onRsvpSubmitted : Bool -> Model -> (Model, Cmd Msg)
onRsvpSubmitted isAttending model =
({ model | rsvpSubmissionStatus = WaitingForResponse }, postRsvpRequest isAttending model.guests)
onRsvpSubmissionResponse : Model -> Model
onRsvpSubmissionResponse model =
{ model | rsvpSubmissionStatus = Submitted }
onAddAnotherRsvp : Model -> Model
onAddAnotherRsvp model =
let
newGuests = model.guests |> List.map (\guest -> {guest | isVisible = True, isSelected = False})
in
{ model | searchString = "", rsvpSubmissionStatus = NotSubmitted, guests = newGuests }
onTick : Posix -> Model -> Model
onTick currentTime model =
{ model | countdown = countdownFromTime weddingDate currentTime }
countdownFromTime : Posix -> Posix -> Countdown
countdownFromTime endTime currentTime =
let
currentTimeMs = posixToMillis currentTime
endTimeMs = posixToMillis endTime
timeDiffMs = endTimeMs - currentTimeMs
in
if timeDiffMs < 0 then
{ days = 0, hours = 0, minutes = 0, seconds = 0 }
else
{ days = timeDiffMs // millisecondsPerDay
, hours = (modBy millisecondsPerDay timeDiffMs) // millisecondsPerHour
, minutes = (modBy millisecondsPerHour timeDiffMs) // millisecondsPerMinute
, seconds = (modBy millisecondsPerMinute timeDiffMs) // millisecondsPerSecond
}
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every 1000 Tick
initialCommand : Cmd Msg
initialCommand =
Cmd.batch [ getGuestList, Task.perform Tick Time.now ]
-- VIEW
view : Model -> Html Msg
view model =
div [ class "container-fluid main-container" ]
[ heroImageView
, receptionDetailsView model
, registryDetailsView
, rsvpView model
]
heroImageView : Html Msg
heroImageView =
div [ class "row" ]
[ div [ id "hero-image-col", class "col-12" ]
[ img [ id "hero-image", src "images/Hero.jpg" ] []
, div [ id "image-text" ]
[ h1 [ id "image-title" ] [ text "<NAME> & <NAME>" ]
, h3 [ id "image-date" ] [ text "September 21, 2019" ]
, h3 [ id "image-location" ] [ text "Lincoln, NE" ]
]
]
]
receptionDetailsView : Model -> Html Msg
receptionDetailsView model =
div [ class "row details-row" ]
[ div [ class "col-sm-3" ] []
, div [ class "col-sm-6" ]
[ div [ id "reception-details", class "details-container" ]
[ h2 [] [ text "Wedding Reception" ]
, h5 [] [ text "5 PM | September 21, 2019" ]
, h5 [] [ text "Capital Vew Winery" ]
, p [] [ a [ target "_blank", href "https://goo.gl/maps/KPN95RXtjDjqaGK59" ] [ text "2361 Wittstruck Rd | Roca, NE | 68430" ] ]
, p [ class "details-paragraph" ]
[ text "The reception will be held at "
, a [ target "_blank", href "https://capitolviewwinery.com/" ] [ text "Capital View Winery" ]
, text ". Join us for food, wine, and yard games to celebrate our marriage."
]
, countdownView model.countdown
, br [] []
, a [ href "/#rsvp", id "rsvp-button", class "btn btn-lg" ] [ text "RSVP" ]
]
]
, div [ class "col-sm-3" ] [ ]
]
countdownView : Countdown -> Html Msg
countdownView countdown =
div [ id "countdown-container" ]
[ countdownComponentView countdown.days "days"
, countdownComponentView countdown.hours "hours"
, countdownComponentView countdown.minutes "minutes"
, countdownComponentView countdown.seconds "seconds"
]
countdownComponentView : Int -> String -> Html Msg
countdownComponentView value unit =
div [ class "countdown-component" ]
[ span [ class "countdown-value" ] [ text (String.fromInt value) ]
, br [] []
, span [ class "countdown-unit" ] [ text unit ]
]
registryDetailsView : Html Msg
registryDetailsView =
div [ id "registry-row", class "row details-row" ]
[ div [ class "col-sm-3" ] []
, div [ class "col-sm-6" ]
[ div [ class "details-container" ]
[ h2 [] [ text "Registry" ]
, p [ class "details-paragraph" ] [ text "The presence of your company is the only gift we could ever ask for. We will not be registering as we have everything we need to start the next chapter of our lives together." ]
]
]
, div [ class "col-sm-3" ] []
]
rsvpView : Model -> Html Msg
rsvpView model =
let
formView = if model.rsvpSubmissionStatus == Submitted then
completedFormView
else if String.isEmpty model.searchString then
noSearchStringView
else
incompleteFormView model
in
div [ id "rsvp", class "row details-row" ]
[ div [ class "col-12" ]
[ div [ class "details-container" ] [ formView ]
]
]
noSearchStringView : Html Msg
noSearchStringView =
div [ class "container-fluid" ]
[ titleView
, searchBarView False
]
incompleteFormView : Model -> Html Msg
incompleteFormView model =
let
inputDisabled = model.rsvpSubmissionStatus == WaitingForResponse
in
div [ class "container-fluid" ]
[ titleView
, searchBarView inputDisabled
, guestListView model.guests inputDisabled
, submitButtonView model.guests inputDisabled
]
completedFormView : Html Msg
completedFormView =
div [ class "container-fluid"]
[ titleView
, thankYouView
, addAnotherRsvpView
]
titleView : Html Msg
titleView =
div [ class "row", id "title-row" ]
[ div [ class "col-12"]
[ h1 [] [ text "RSVP" ]
, p [] [ text "Please search for your name and let us know if you can attend by September 1st" ]
]
]
searchBarView : Bool -> Html Msg
searchBarView inputDisabled =
div [ class "row", id "search-bar-row" ]
[ div [ class "col-sm-3" ] []
, div [ class "col-sm-6" ]
[ input [ class "form-control", placeholder "Search by your name", onInput NewSearch, disabled inputDisabled ] []
]
, div [ class "col-sm-3" ] []
]
guestListView : List Guest -> Bool -> Html Msg
guestListView guests inputDisabled =
let
guestViews = guests
|> List.filter (\guest -> guest.isVisible)
|> List.map (guestView inputDisabled)
in
div [ class "row" ]
[ div [ class "col-sm-2" ] []
, div [ class "col-sm-8", id "guest-list-container" ] guestViews
, div [ class "col-sm-2" ] []
]
guestView : Bool -> Guest -> Html Msg
guestView inputDisabled guest =
let
buttonOutline = if guest.isSelected then "selected-guest" else "unselected-guest"
buttonClass = "btn " ++ buttonOutline
in
div [ class "guest-name" ]
[ button [ class buttonClass, type_ "button", onClick (SelectGuest guest.id), disabled inputDisabled ]
[ text guest.name ]
]
submitButtonView : List Guest -> Bool -> Html Msg
submitButtonView guestList inputDisabled =
let
anySelectedGuests = guestList |> List.any (\guest -> guest.isVisible && guest.isSelected)
buttonsDisabled = inputDisabled || (not anySelectedGuests)
in
div [ class "submit-button-row row" ]
[ div [ class "col-sm-4" ] []
, div [ class "col-sm-4", id "submit-button-container" ]
[ button [ id "attending-button", class "submit-button btn", type_ "button", disabled buttonsDisabled, onClick AttendingSubmitted ]
[ text "Attending" ]
, button [ id "not-attending-button", class "submit-button btn", type_ "button", disabled buttonsDisabled, onClick NotAttendingSubmitted ]
[ span [ class "spinner-border spinner-border-sm" ] [], text "Not Attending" ]
]
, div [ class "col-4" ] []
]
thankYouView : Html Msg
thankYouView =
div [ class "row" ]
[ div [ class "col-sm-4" ] []
, div [ class "col-sm-4" ]
[ h3 [] [ text "Thank you for your response!" ]
]
, div [ class "col-sm-4" ] []
]
addAnotherRsvpView : Html Msg
addAnotherRsvpView =
div [ class "row add-another-rsvp-row" ]
[ div [ class "col-12" ]
[ button [ id "add-rsvp-btn", class "btn", type_ "button", onClick AddAnotherRsvp ] [ text "Add Another RSVP" ]
]
]
-- HTTP
getGuestList : Cmd Msg
getGuestList =
Http.get
{ url = "/Rsvp/Guests"
, expect = Http.expectJson GuestListLoaded getGuestListResponseDecoder
}
getGuestListResponseDecoder : Decoder GetGuestListReponse
getGuestListResponseDecoder =
Json.Decode.map2 GetGuestListReponse
(field "guests" (list guestResponseModelDecoder))
(field "plusOnes" (list plusOneResponseModelDecoder))
guestResponseModelDecoder : Decoder GuestResponseModel
guestResponseModelDecoder =
Json.Decode.map2 GuestResponseModel
(field "id" string)
(field "name" string)
plusOneResponseModelDecoder : Decoder PlusOneResponseModel
plusOneResponseModelDecoder =
Json.Decode.map2 PlusOneResponseModel
(field "partnerAName" string)
(field "partnerBName" string)
postRsvpRequest : Bool -> List Guest -> Cmd Msg
postRsvpRequest isAttending guests =
let
selectedGuestIds = getSelectedGuestIds guests
jsonRequest = Encode.object
[ ( "GuestIds", Encode.list Encode.string selectedGuestIds )
, ( "IsAttending", Encode.bool isAttending )
]
in
Http.post
{ url = "/Rsvp/Attendance"
, body = Http.jsonBody jsonRequest
, expect = Http.expectWhatever RsvpSubmissionResponse
}
getSelectedGuestIds : List Guest -> List GuestId
getSelectedGuestIds guests =
guests
|> List.filter (\guest -> guest.isSelected && guest.isVisible)
|> List.map (\guest -> guest.id)
| true | import Browser
import Html exposing (Html, a, br, button, div, h1, h2, h3, h5, img, input, p, span, text)
import Html.Attributes exposing (class, disabled, href, id, placeholder, src, target, type_)
import Html.Events exposing (onClick, onInput)
import Http
import Json.Decode exposing (Decoder, field, list, string)
import Json.Encode as Encode
import Set exposing (Set)
import Task
import Time exposing (Posix, millisToPosix, posixToMillis)
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
-- MODEL
type alias GuestId = String
type GuestStatus
= Unregistered
| Attending
| NotAttending
type alias Guest =
{ id: GuestId
, name: String
, status: GuestStatus
, isSelected: Bool
, isVisible: Bool
}
type alias PlusOnePair = (String, String)
type alias GuestResponseModel =
{ id: GuestId
, name: String
}
type alias PlusOneResponseModel =
{ partnerAName: String
, partnerBName: String
}
type alias GetGuestListReponse =
{ guests: List GuestResponseModel
, plusOnes: List PlusOneResponseModel
}
type RsvpSubmissionStatus = NotSubmitted
| WaitingForResponse
| Submitted
type alias Countdown =
{ days: Int
, hours: Int
, minutes: Int
, seconds: Int
}
-- 5:00 PM CDT September 21, 2019
weddingDate : Posix
weddingDate = millisToPosix 1569103200000
millisecondsPerSecond : Int
millisecondsPerSecond = 1000
millisecondsPerMinute : Int
millisecondsPerMinute = millisecondsPerSecond * 60
millisecondsPerHour : Int
millisecondsPerHour = millisecondsPerMinute * 60
millisecondsPerDay : Int
millisecondsPerDay = millisecondsPerHour * 24
type alias Model =
{ guests: List Guest
, plusOnes: List PlusOnePair
, searchString: String
, rsvpSubmissionStatus: RsvpSubmissionStatus
, countdown: Countdown
}
init : () -> (Model, Cmd Msg)
init () =
( { guests = []
, plusOnes = []
, searchString = ""
, rsvpSubmissionStatus = NotSubmitted
, countdown = { days = 0, hours = 0, minutes = 0, seconds = 0 }
}
, initialCommand
)
-- UPDATE
type Msg = GuestListLoaded (Result Http.Error GetGuestListReponse)
| SelectGuest GuestId
| NewSearch String
| AttendingSubmitted
| NotAttendingSubmitted
| RsvpSubmissionResponse (Result Http.Error ())
| AddAnotherRsvp
| Tick Posix
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
GuestListLoaded result ->
case result of
Ok response ->
(onGuestListLoaded response model, Cmd.none)
Err _ ->
(model, Cmd.none)
SelectGuest guestId ->
(onGuestSelected guestId model, Cmd.none)
NewSearch searchString ->
(onNewSearch searchString model, Cmd.none)
AttendingSubmitted ->
onRsvpSubmitted True model
NotAttendingSubmitted ->
onRsvpSubmitted False model
RsvpSubmissionResponse result ->
case result of
Ok _ ->
(onRsvpSubmissionResponse model, Cmd.none)
Err _ ->
(model, Cmd.none)
AddAnotherRsvp ->
(onAddAnotherRsvp model, Cmd.none)
Tick currentTime ->
(onTick currentTime model , Cmd.none)
onGuestListLoaded : GetGuestListReponse -> Model -> Model
onGuestListLoaded response model =
let
guests = response.guests
|> List.map guestResponseModelToGuest
|> List.sortWith orderByName
plusOnes = response.plusOnes |> List.map plusOneResponseModelToPlusOnePair
in
{ model | guests = guests, plusOnes = plusOnes }
orderByName : Guest -> Guest -> Order
orderByName a b =
let
(aFirst, aLast) = getFirstAndLastName a
(bFirst, bLast) = getFirstAndLastName b
in
if aLast == bLast then
compare aFirst bFirst
else
compare aLast bLast
getFirstAndLastName : Guest -> (String, String)
getFirstAndLastName guest =
let
names = String.split " " guest.name
firstName = names |> List.head |> Maybe.withDefault guest.name
lastName = names |> List.drop 1 |> List.head |> Maybe.withDefault guest.name
in
(firstName, lastName)
guestResponseModelToGuest : GuestResponseModel -> Guest
guestResponseModelToGuest model =
{ id = model.id, name = model.name, status = Unregistered, isSelected = False, isVisible = True }
plusOneResponseModelToPlusOnePair : PlusOneResponseModel -> PlusOnePair
plusOneResponseModelToPlusOnePair model =
(model.partnerAName, model.partnerBName)
onGuestSelected : GuestId -> Model -> Model
onGuestSelected guestId model =
let
newGuestList = model.guests |> List.map (selectGuestIfIdMatches guestId)
in
{ model | guests = newGuestList }
selectGuestIfIdMatches : GuestId -> Guest -> Guest
selectGuestIfIdMatches guestId guest =
if guestId == guest.id then
{ guest | isSelected = not guest.isSelected }
else
guest
onNewSearch : String -> Model -> Model
onNewSearch searchString model =
let
cleanSearchString = searchString |> String.trim |> String.toLower
matchingPlusOneNames = getMatchingPlusOneNames cleanSearchString model.plusOnes
newGuestList = filterGuestsOnSearchString cleanSearchString matchingPlusOneNames model.guests
in
{ model | searchString = cleanSearchString, guests = newGuestList }
getMatchingPlusOneNames : String -> List PlusOnePair -> Set String
getMatchingPlusOneNames searchString plusOnes =
plusOnes
|> List.filterMap (getPlusOneNameIfMatchesSearchString searchString)
|> Set.fromList
getPlusOneNameIfMatchesSearchString : String -> PlusOnePair -> Maybe String
getPlusOneNameIfMatchesSearchString searchString (partnerA, partnerB) =
if doesGuestNameMatchSearchString searchString partnerA then
Just partnerB
else if doesGuestNameMatchSearchString searchString partnerB then
Just partnerA
else
Nothing
doesGuestNameMatchSearchString : String -> String -> Bool
doesGuestNameMatchSearchString searchString guestName =
guestName |> String.toLower |> String.contains searchString
filterGuestsOnSearchString : String -> Set String -> List Guest -> List Guest
filterGuestsOnSearchString searchString matchingPlusOneNames guestList =
guestList
|> List.map (\guest -> { guest | isVisible = doesGuestMatchSearchString searchString matchingPlusOneNames guest })
doesGuestMatchSearchString : String -> Set String -> Guest -> Bool
doesGuestMatchSearchString searchString matchingPlusOneNames guest =
String.isEmpty searchString
|| doesGuestNameMatchSearchString searchString guest.name
|| Set.member guest.name matchingPlusOneNames
onRsvpSubmitted : Bool -> Model -> (Model, Cmd Msg)
onRsvpSubmitted isAttending model =
({ model | rsvpSubmissionStatus = WaitingForResponse }, postRsvpRequest isAttending model.guests)
onRsvpSubmissionResponse : Model -> Model
onRsvpSubmissionResponse model =
{ model | rsvpSubmissionStatus = Submitted }
onAddAnotherRsvp : Model -> Model
onAddAnotherRsvp model =
let
newGuests = model.guests |> List.map (\guest -> {guest | isVisible = True, isSelected = False})
in
{ model | searchString = "", rsvpSubmissionStatus = NotSubmitted, guests = newGuests }
onTick : Posix -> Model -> Model
onTick currentTime model =
{ model | countdown = countdownFromTime weddingDate currentTime }
countdownFromTime : Posix -> Posix -> Countdown
countdownFromTime endTime currentTime =
let
currentTimeMs = posixToMillis currentTime
endTimeMs = posixToMillis endTime
timeDiffMs = endTimeMs - currentTimeMs
in
if timeDiffMs < 0 then
{ days = 0, hours = 0, minutes = 0, seconds = 0 }
else
{ days = timeDiffMs // millisecondsPerDay
, hours = (modBy millisecondsPerDay timeDiffMs) // millisecondsPerHour
, minutes = (modBy millisecondsPerHour timeDiffMs) // millisecondsPerMinute
, seconds = (modBy millisecondsPerMinute timeDiffMs) // millisecondsPerSecond
}
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every 1000 Tick
initialCommand : Cmd Msg
initialCommand =
Cmd.batch [ getGuestList, Task.perform Tick Time.now ]
-- VIEW
view : Model -> Html Msg
view model =
div [ class "container-fluid main-container" ]
[ heroImageView
, receptionDetailsView model
, registryDetailsView
, rsvpView model
]
heroImageView : Html Msg
heroImageView =
div [ class "row" ]
[ div [ id "hero-image-col", class "col-12" ]
[ img [ id "hero-image", src "images/Hero.jpg" ] []
, div [ id "image-text" ]
[ h1 [ id "image-title" ] [ text "PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI" ]
, h3 [ id "image-date" ] [ text "September 21, 2019" ]
, h3 [ id "image-location" ] [ text "Lincoln, NE" ]
]
]
]
receptionDetailsView : Model -> Html Msg
receptionDetailsView model =
div [ class "row details-row" ]
[ div [ class "col-sm-3" ] []
, div [ class "col-sm-6" ]
[ div [ id "reception-details", class "details-container" ]
[ h2 [] [ text "Wedding Reception" ]
, h5 [] [ text "5 PM | September 21, 2019" ]
, h5 [] [ text "Capital Vew Winery" ]
, p [] [ a [ target "_blank", href "https://goo.gl/maps/KPN95RXtjDjqaGK59" ] [ text "2361 Wittstruck Rd | Roca, NE | 68430" ] ]
, p [ class "details-paragraph" ]
[ text "The reception will be held at "
, a [ target "_blank", href "https://capitolviewwinery.com/" ] [ text "Capital View Winery" ]
, text ". Join us for food, wine, and yard games to celebrate our marriage."
]
, countdownView model.countdown
, br [] []
, a [ href "/#rsvp", id "rsvp-button", class "btn btn-lg" ] [ text "RSVP" ]
]
]
, div [ class "col-sm-3" ] [ ]
]
countdownView : Countdown -> Html Msg
countdownView countdown =
div [ id "countdown-container" ]
[ countdownComponentView countdown.days "days"
, countdownComponentView countdown.hours "hours"
, countdownComponentView countdown.minutes "minutes"
, countdownComponentView countdown.seconds "seconds"
]
countdownComponentView : Int -> String -> Html Msg
countdownComponentView value unit =
div [ class "countdown-component" ]
[ span [ class "countdown-value" ] [ text (String.fromInt value) ]
, br [] []
, span [ class "countdown-unit" ] [ text unit ]
]
registryDetailsView : Html Msg
registryDetailsView =
div [ id "registry-row", class "row details-row" ]
[ div [ class "col-sm-3" ] []
, div [ class "col-sm-6" ]
[ div [ class "details-container" ]
[ h2 [] [ text "Registry" ]
, p [ class "details-paragraph" ] [ text "The presence of your company is the only gift we could ever ask for. We will not be registering as we have everything we need to start the next chapter of our lives together." ]
]
]
, div [ class "col-sm-3" ] []
]
rsvpView : Model -> Html Msg
rsvpView model =
let
formView = if model.rsvpSubmissionStatus == Submitted then
completedFormView
else if String.isEmpty model.searchString then
noSearchStringView
else
incompleteFormView model
in
div [ id "rsvp", class "row details-row" ]
[ div [ class "col-12" ]
[ div [ class "details-container" ] [ formView ]
]
]
noSearchStringView : Html Msg
noSearchStringView =
div [ class "container-fluid" ]
[ titleView
, searchBarView False
]
incompleteFormView : Model -> Html Msg
incompleteFormView model =
let
inputDisabled = model.rsvpSubmissionStatus == WaitingForResponse
in
div [ class "container-fluid" ]
[ titleView
, searchBarView inputDisabled
, guestListView model.guests inputDisabled
, submitButtonView model.guests inputDisabled
]
completedFormView : Html Msg
completedFormView =
div [ class "container-fluid"]
[ titleView
, thankYouView
, addAnotherRsvpView
]
titleView : Html Msg
titleView =
div [ class "row", id "title-row" ]
[ div [ class "col-12"]
[ h1 [] [ text "RSVP" ]
, p [] [ text "Please search for your name and let us know if you can attend by September 1st" ]
]
]
searchBarView : Bool -> Html Msg
searchBarView inputDisabled =
div [ class "row", id "search-bar-row" ]
[ div [ class "col-sm-3" ] []
, div [ class "col-sm-6" ]
[ input [ class "form-control", placeholder "Search by your name", onInput NewSearch, disabled inputDisabled ] []
]
, div [ class "col-sm-3" ] []
]
guestListView : List Guest -> Bool -> Html Msg
guestListView guests inputDisabled =
let
guestViews = guests
|> List.filter (\guest -> guest.isVisible)
|> List.map (guestView inputDisabled)
in
div [ class "row" ]
[ div [ class "col-sm-2" ] []
, div [ class "col-sm-8", id "guest-list-container" ] guestViews
, div [ class "col-sm-2" ] []
]
guestView : Bool -> Guest -> Html Msg
guestView inputDisabled guest =
let
buttonOutline = if guest.isSelected then "selected-guest" else "unselected-guest"
buttonClass = "btn " ++ buttonOutline
in
div [ class "guest-name" ]
[ button [ class buttonClass, type_ "button", onClick (SelectGuest guest.id), disabled inputDisabled ]
[ text guest.name ]
]
submitButtonView : List Guest -> Bool -> Html Msg
submitButtonView guestList inputDisabled =
let
anySelectedGuests = guestList |> List.any (\guest -> guest.isVisible && guest.isSelected)
buttonsDisabled = inputDisabled || (not anySelectedGuests)
in
div [ class "submit-button-row row" ]
[ div [ class "col-sm-4" ] []
, div [ class "col-sm-4", id "submit-button-container" ]
[ button [ id "attending-button", class "submit-button btn", type_ "button", disabled buttonsDisabled, onClick AttendingSubmitted ]
[ text "Attending" ]
, button [ id "not-attending-button", class "submit-button btn", type_ "button", disabled buttonsDisabled, onClick NotAttendingSubmitted ]
[ span [ class "spinner-border spinner-border-sm" ] [], text "Not Attending" ]
]
, div [ class "col-4" ] []
]
thankYouView : Html Msg
thankYouView =
div [ class "row" ]
[ div [ class "col-sm-4" ] []
, div [ class "col-sm-4" ]
[ h3 [] [ text "Thank you for your response!" ]
]
, div [ class "col-sm-4" ] []
]
addAnotherRsvpView : Html Msg
addAnotherRsvpView =
div [ class "row add-another-rsvp-row" ]
[ div [ class "col-12" ]
[ button [ id "add-rsvp-btn", class "btn", type_ "button", onClick AddAnotherRsvp ] [ text "Add Another RSVP" ]
]
]
-- HTTP
getGuestList : Cmd Msg
getGuestList =
Http.get
{ url = "/Rsvp/Guests"
, expect = Http.expectJson GuestListLoaded getGuestListResponseDecoder
}
getGuestListResponseDecoder : Decoder GetGuestListReponse
getGuestListResponseDecoder =
Json.Decode.map2 GetGuestListReponse
(field "guests" (list guestResponseModelDecoder))
(field "plusOnes" (list plusOneResponseModelDecoder))
guestResponseModelDecoder : Decoder GuestResponseModel
guestResponseModelDecoder =
Json.Decode.map2 GuestResponseModel
(field "id" string)
(field "name" string)
plusOneResponseModelDecoder : Decoder PlusOneResponseModel
plusOneResponseModelDecoder =
Json.Decode.map2 PlusOneResponseModel
(field "partnerAName" string)
(field "partnerBName" string)
postRsvpRequest : Bool -> List Guest -> Cmd Msg
postRsvpRequest isAttending guests =
let
selectedGuestIds = getSelectedGuestIds guests
jsonRequest = Encode.object
[ ( "GuestIds", Encode.list Encode.string selectedGuestIds )
, ( "IsAttending", Encode.bool isAttending )
]
in
Http.post
{ url = "/Rsvp/Attendance"
, body = Http.jsonBody jsonRequest
, expect = Http.expectWhatever RsvpSubmissionResponse
}
getSelectedGuestIds : List Guest -> List GuestId
getSelectedGuestIds guests =
guests
|> List.filter (\guest -> guest.isSelected && guest.isVisible)
|> List.map (\guest -> guest.id)
| elm |
[
{
"context": "------------------------\n\n Author : Nasy https://nasy.moe <Nasy>\n Date : ",
"end": 933,
"score": 0.7173410654,
"start": 929,
"tag": "NAME",
"value": "Nasy"
},
{
"context": "\n\n Author : Nasy https://nasy.moe <Nasy>\n Date : Mar 10, 2018\n Email ",
"end": 956,
"score": 0.6908664703,
"start": 952,
"tag": "USERNAME",
"value": "Nasy"
}
] | website/Msgs.elm | nasyxx/nasy.moe | 0 | {-
Excited without bugs, have fun ("▔□▔)/hi~♡ Nasy.
-----------------------------------------------
|
| * *
| . .
| .
| * ,
| .
|
| *
| |\___/|
| ) -( . '
| =\ - /=
| )===( *
| / - \
| |- |
| / - \ 0.|.0
| NASY___\__( (__/_____(\=/)__+1s____________
| ______|____) )______|______|______|______|_
| ___|______( (____|______|______|______|____
| ______|____\_|______|______|______|______|_
| ___|______|______|______|______|______|____
| ______|______|______|______|______|______|_
| ___|______|______|______|______|______|____
-----------------------------------------------
Author : Nasy https://nasy.moe <Nasy>
Date : Mar 10, 2018
Email : echo bmFzeXh4QGdtYWlsLmNvbQo= | base64 -D
Filename : Msgs.elm
Last modified by : Nasy
Last modified time : Mar 10, 2018
License : MIT
-----------------------------------------------
There are more things in heaven and earth, Horatio, than are dreamt.
From "Hamlet"
-}
module Msgs exposing (..)
import Models exposing (BlogModel, BlogsModel)
import RemoteData exposing (WebData)
type Msg
= OnFetchBlog (WebData BlogModel)
| OnFetchBlogs (WebData BlogsModel)
| SetUrl String
| OnLocationChange
| ChangeNavF
| ChangeNavN
| Up2Top
| InitComment
| 10778 | {-
Excited without bugs, have fun ("▔□▔)/hi~♡ Nasy.
-----------------------------------------------
|
| * *
| . .
| .
| * ,
| .
|
| *
| |\___/|
| ) -( . '
| =\ - /=
| )===( *
| / - \
| |- |
| / - \ 0.|.0
| NASY___\__( (__/_____(\=/)__+1s____________
| ______|____) )______|______|______|______|_
| ___|______( (____|______|______|______|____
| ______|____\_|______|______|______|______|_
| ___|______|______|______|______|______|____
| ______|______|______|______|______|______|_
| ___|______|______|______|______|______|____
-----------------------------------------------
Author : <NAME> https://nasy.moe <Nasy>
Date : Mar 10, 2018
Email : echo bmFzeXh4QGdtYWlsLmNvbQo= | base64 -D
Filename : Msgs.elm
Last modified by : Nasy
Last modified time : Mar 10, 2018
License : MIT
-----------------------------------------------
There are more things in heaven and earth, Horatio, than are dreamt.
From "Hamlet"
-}
module Msgs exposing (..)
import Models exposing (BlogModel, BlogsModel)
import RemoteData exposing (WebData)
type Msg
= OnFetchBlog (WebData BlogModel)
| OnFetchBlogs (WebData BlogsModel)
| SetUrl String
| OnLocationChange
| ChangeNavF
| ChangeNavN
| Up2Top
| InitComment
| true | {-
Excited without bugs, have fun ("▔□▔)/hi~♡ Nasy.
-----------------------------------------------
|
| * *
| . .
| .
| * ,
| .
|
| *
| |\___/|
| ) -( . '
| =\ - /=
| )===( *
| / - \
| |- |
| / - \ 0.|.0
| NASY___\__( (__/_____(\=/)__+1s____________
| ______|____) )______|______|______|______|_
| ___|______( (____|______|______|______|____
| ______|____\_|______|______|______|______|_
| ___|______|______|______|______|______|____
| ______|______|______|______|______|______|_
| ___|______|______|______|______|______|____
-----------------------------------------------
Author : PI:NAME:<NAME>END_PI https://nasy.moe <Nasy>
Date : Mar 10, 2018
Email : echo bmFzeXh4QGdtYWlsLmNvbQo= | base64 -D
Filename : Msgs.elm
Last modified by : Nasy
Last modified time : Mar 10, 2018
License : MIT
-----------------------------------------------
There are more things in heaven and earth, Horatio, than are dreamt.
From "Hamlet"
-}
module Msgs exposing (..)
import Models exposing (BlogModel, BlogsModel)
import RemoteData exposing (WebData)
type Msg
= OnFetchBlog (WebData BlogModel)
| OnFetchBlogs (WebData BlogsModel)
| SetUrl String
| OnLocationChange
| ChangeNavF
| ChangeNavN
| Up2Top
| InitComment
| elm |
[
{
"context": " { src = \"profile.jpg\", caption = \"Richard Feldman\" }\n , row MenuControls\n ",
"end": 5635,
"score": 0.9992316365,
"start": 5620,
"tag": "NAME",
"value": "Richard Feldman"
},
{
"context": " [ spacing 12 ]\n [ text \"rtfeldman\"\n , viewCaret menu\n ",
"end": 5746,
"score": 0.8274566531,
"start": 5737,
"tag": "NAME",
"value": "rtfeldman"
}
] | src/Home.elm | rtfeldman/style-elements-demo | 13 | module Home exposing (..)
import Color exposing (rgba)
import Element exposing (..)
import Element.Attributes exposing (..)
import Element.Events exposing (..)
import Html exposing (Html)
import Json.Decode
import Style exposing (..)
import Style.Color as Color
import Style.Font as Font
import Window
type Styles
= None
| Search
| Title
| ProfileBadge
| Menu
| Elm
| Navbar
| Main
| Backdrop
| MenuContents
| MenuControls
| MenuItem
| Caret
| GreenEmphasis
colors =
{ reactiveGreen = Color.rgb 85 175 106
, navbarBackground = Color.darkCharcoal
, mainBackground = Color.black
}
stylesheet : StyleSheet Styles variation
stylesheet =
Style.styleSheet
[ style None []
, style Main [ Color.background colors.mainBackground ]
, style ProfileBadge [ Color.text Color.white ]
, style Title [ Font.weight 400, Font.size 32 ]
, style GreenEmphasis [ Color.text colors.reactiveGreen ]
, style MenuContents [ Color.background colors.navbarBackground ]
, style MenuControls
[ cursor "pointer"
, Color.text Color.white
, hover [ Color.text colors.reactiveGreen ]
]
, style MenuItem
[ cursor "pointer"
, Color.text Color.white
, hover
[ Color.background colors.reactiveGreen
, Color.text Color.white
]
]
, style Elm
[ Font.typeface [ Font.font "Corsiva", Font.font "Georgia", Font.font "serif" ]
, Color.text Color.gray
, Font.italic
]
, style Navbar
[ Color.text Color.white
, Color.background colors.navbarBackground
, Font.typeface [ Font.font "helvetica" ]
, Font.size 24
]
, style Caret [ Font.size 12 ]
, style Menu
[ cursor "pointer"
, hover [ Color.text colors.reactiveGreen ]
]
]
main : Program { height : Int, width : Int } Model Msg
main =
Html.programWithFlags
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
subscriptions : Model -> Sub Msg
subscriptions _ =
Window.resizes Resize
init : { width : Int, height : Int } -> ( Model, Cmd Msg )
init flags =
( { menu = Closed, viewport = flags }, Cmd.none )
type alias Model =
{ menu : MenuState
, viewport : Window.Size
}
type MenuState
= Open
| Closed
type Msg
= ToggleMenu
| CloseMenu
| Resize Window.Size
update : Msg -> Model -> ( Model, Cmd msg )
update msg model =
case msg of
CloseMenu ->
( { model | menu = Closed }, Cmd.none )
ToggleMenu ->
( { model
| menu =
case model.menu of
Open ->
Closed
Closed ->
Open
}
, Cmd.none
)
Resize viewport ->
( { model | viewport = viewport }, Cmd.none )
onClickPreventDefault : msg -> Element.Attribute variation msg
onClickPreventDefault msg =
onWithOptions "click"
{ preventDefault = True, stopPropagation = True }
(Json.Decode.succeed msg)
view : Model -> Html Msg
view model =
Element.viewport stylesheet <|
column Main
[ onClick CloseMenu, height fill ]
[ viewNavbar model.viewport.width model.menu
, row None [ height fill, padding 20 ] [ backgroundImage ]
|> within
[ reactiveConfLogo [] ]
]
reactiveConfLogo : List (Element.Attribute variation msg) -> Element Styles variation msg
reactiveConfLogo attrs =
image None attrs { src = "reactive-logo.png", caption = "ReactiveConf" }
backgroundImage : Element Styles variation msg
backgroundImage =
image None [ width (percent 100) ] { src = "bratislava.jpg", caption = "Bratislava" }
pageLogo : Element Styles variation msg
pageLogo =
row Title
[ alignLeft
, width (fillPortion 1)
]
[ text "CSS"
, el GreenEmphasis [] (text " as bytecode")
]
builtWithElm : Element Styles variation msg
builtWithElm =
row Elm
[ width (fillPortion 1)
, center
]
[ text "Built with Elm!" ]
viewNavbar : Int -> MenuState -> Element Styles variation Msg
viewNavbar viewportWidth menu =
let
menuControls alignment =
[ row None
[ alignment
, width (fillPortion 1)
]
[ viewMenu menu ]
]
contents =
if viewportWidth < 640 then
menuControls center
else if viewportWidth < 1024 then
List.append [ pageLogo ] (menuControls alignRight)
else
List.append [ pageLogo, builtWithElm ] (menuControls alignRight)
in
row Navbar
[ width fill
, paddingLeft 24
, paddingRight 24
, paddingTop 16
, paddingBottom 16
, verticalCenter
]
contents
viewMenu : MenuState -> Element Styles variation Msg
viewMenu menu =
let
menuControls =
row Menu
[ spacing 16, onClickPreventDefault ToggleMenu ]
[ image ProfileBadge
[ width (px 32), height (px 32) ]
{ src = "profile.jpg", caption = "Richard Feldman" }
, row MenuControls
[ spacing 12 ]
[ text "rtfeldman"
, viewCaret menu
]
]
in
case menu of
Closed ->
menuControls
Open ->
menuControls
|> below [ menuContents ]
menuContents : Element Styles variation msg
menuContents =
column MenuContents
[ alignRight ]
(List.map viewMenuItem [ "Account", "Messages", "Sign Out" ])
viewMenuItem : String -> Element Styles variation msg
viewMenuItem caption =
el MenuItem [ padding 16 ] (text caption)
viewCaret : MenuState -> Element Styles variation msg
viewCaret menu =
let
caretText =
case menu of
Closed ->
"▼"
Open ->
"▲"
in
el Caret [ center, verticalCenter ] (text caretText)
| 55294 | module Home exposing (..)
import Color exposing (rgba)
import Element exposing (..)
import Element.Attributes exposing (..)
import Element.Events exposing (..)
import Html exposing (Html)
import Json.Decode
import Style exposing (..)
import Style.Color as Color
import Style.Font as Font
import Window
type Styles
= None
| Search
| Title
| ProfileBadge
| Menu
| Elm
| Navbar
| Main
| Backdrop
| MenuContents
| MenuControls
| MenuItem
| Caret
| GreenEmphasis
colors =
{ reactiveGreen = Color.rgb 85 175 106
, navbarBackground = Color.darkCharcoal
, mainBackground = Color.black
}
stylesheet : StyleSheet Styles variation
stylesheet =
Style.styleSheet
[ style None []
, style Main [ Color.background colors.mainBackground ]
, style ProfileBadge [ Color.text Color.white ]
, style Title [ Font.weight 400, Font.size 32 ]
, style GreenEmphasis [ Color.text colors.reactiveGreen ]
, style MenuContents [ Color.background colors.navbarBackground ]
, style MenuControls
[ cursor "pointer"
, Color.text Color.white
, hover [ Color.text colors.reactiveGreen ]
]
, style MenuItem
[ cursor "pointer"
, Color.text Color.white
, hover
[ Color.background colors.reactiveGreen
, Color.text Color.white
]
]
, style Elm
[ Font.typeface [ Font.font "Corsiva", Font.font "Georgia", Font.font "serif" ]
, Color.text Color.gray
, Font.italic
]
, style Navbar
[ Color.text Color.white
, Color.background colors.navbarBackground
, Font.typeface [ Font.font "helvetica" ]
, Font.size 24
]
, style Caret [ Font.size 12 ]
, style Menu
[ cursor "pointer"
, hover [ Color.text colors.reactiveGreen ]
]
]
main : Program { height : Int, width : Int } Model Msg
main =
Html.programWithFlags
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
subscriptions : Model -> Sub Msg
subscriptions _ =
Window.resizes Resize
init : { width : Int, height : Int } -> ( Model, Cmd Msg )
init flags =
( { menu = Closed, viewport = flags }, Cmd.none )
type alias Model =
{ menu : MenuState
, viewport : Window.Size
}
type MenuState
= Open
| Closed
type Msg
= ToggleMenu
| CloseMenu
| Resize Window.Size
update : Msg -> Model -> ( Model, Cmd msg )
update msg model =
case msg of
CloseMenu ->
( { model | menu = Closed }, Cmd.none )
ToggleMenu ->
( { model
| menu =
case model.menu of
Open ->
Closed
Closed ->
Open
}
, Cmd.none
)
Resize viewport ->
( { model | viewport = viewport }, Cmd.none )
onClickPreventDefault : msg -> Element.Attribute variation msg
onClickPreventDefault msg =
onWithOptions "click"
{ preventDefault = True, stopPropagation = True }
(Json.Decode.succeed msg)
view : Model -> Html Msg
view model =
Element.viewport stylesheet <|
column Main
[ onClick CloseMenu, height fill ]
[ viewNavbar model.viewport.width model.menu
, row None [ height fill, padding 20 ] [ backgroundImage ]
|> within
[ reactiveConfLogo [] ]
]
reactiveConfLogo : List (Element.Attribute variation msg) -> Element Styles variation msg
reactiveConfLogo attrs =
image None attrs { src = "reactive-logo.png", caption = "ReactiveConf" }
backgroundImage : Element Styles variation msg
backgroundImage =
image None [ width (percent 100) ] { src = "bratislava.jpg", caption = "Bratislava" }
pageLogo : Element Styles variation msg
pageLogo =
row Title
[ alignLeft
, width (fillPortion 1)
]
[ text "CSS"
, el GreenEmphasis [] (text " as bytecode")
]
builtWithElm : Element Styles variation msg
builtWithElm =
row Elm
[ width (fillPortion 1)
, center
]
[ text "Built with Elm!" ]
viewNavbar : Int -> MenuState -> Element Styles variation Msg
viewNavbar viewportWidth menu =
let
menuControls alignment =
[ row None
[ alignment
, width (fillPortion 1)
]
[ viewMenu menu ]
]
contents =
if viewportWidth < 640 then
menuControls center
else if viewportWidth < 1024 then
List.append [ pageLogo ] (menuControls alignRight)
else
List.append [ pageLogo, builtWithElm ] (menuControls alignRight)
in
row Navbar
[ width fill
, paddingLeft 24
, paddingRight 24
, paddingTop 16
, paddingBottom 16
, verticalCenter
]
contents
viewMenu : MenuState -> Element Styles variation Msg
viewMenu menu =
let
menuControls =
row Menu
[ spacing 16, onClickPreventDefault ToggleMenu ]
[ image ProfileBadge
[ width (px 32), height (px 32) ]
{ src = "profile.jpg", caption = "<NAME>" }
, row MenuControls
[ spacing 12 ]
[ text "<NAME>"
, viewCaret menu
]
]
in
case menu of
Closed ->
menuControls
Open ->
menuControls
|> below [ menuContents ]
menuContents : Element Styles variation msg
menuContents =
column MenuContents
[ alignRight ]
(List.map viewMenuItem [ "Account", "Messages", "Sign Out" ])
viewMenuItem : String -> Element Styles variation msg
viewMenuItem caption =
el MenuItem [ padding 16 ] (text caption)
viewCaret : MenuState -> Element Styles variation msg
viewCaret menu =
let
caretText =
case menu of
Closed ->
"▼"
Open ->
"▲"
in
el Caret [ center, verticalCenter ] (text caretText)
| true | module Home exposing (..)
import Color exposing (rgba)
import Element exposing (..)
import Element.Attributes exposing (..)
import Element.Events exposing (..)
import Html exposing (Html)
import Json.Decode
import Style exposing (..)
import Style.Color as Color
import Style.Font as Font
import Window
type Styles
= None
| Search
| Title
| ProfileBadge
| Menu
| Elm
| Navbar
| Main
| Backdrop
| MenuContents
| MenuControls
| MenuItem
| Caret
| GreenEmphasis
colors =
{ reactiveGreen = Color.rgb 85 175 106
, navbarBackground = Color.darkCharcoal
, mainBackground = Color.black
}
stylesheet : StyleSheet Styles variation
stylesheet =
Style.styleSheet
[ style None []
, style Main [ Color.background colors.mainBackground ]
, style ProfileBadge [ Color.text Color.white ]
, style Title [ Font.weight 400, Font.size 32 ]
, style GreenEmphasis [ Color.text colors.reactiveGreen ]
, style MenuContents [ Color.background colors.navbarBackground ]
, style MenuControls
[ cursor "pointer"
, Color.text Color.white
, hover [ Color.text colors.reactiveGreen ]
]
, style MenuItem
[ cursor "pointer"
, Color.text Color.white
, hover
[ Color.background colors.reactiveGreen
, Color.text Color.white
]
]
, style Elm
[ Font.typeface [ Font.font "Corsiva", Font.font "Georgia", Font.font "serif" ]
, Color.text Color.gray
, Font.italic
]
, style Navbar
[ Color.text Color.white
, Color.background colors.navbarBackground
, Font.typeface [ Font.font "helvetica" ]
, Font.size 24
]
, style Caret [ Font.size 12 ]
, style Menu
[ cursor "pointer"
, hover [ Color.text colors.reactiveGreen ]
]
]
main : Program { height : Int, width : Int } Model Msg
main =
Html.programWithFlags
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
subscriptions : Model -> Sub Msg
subscriptions _ =
Window.resizes Resize
init : { width : Int, height : Int } -> ( Model, Cmd Msg )
init flags =
( { menu = Closed, viewport = flags }, Cmd.none )
type alias Model =
{ menu : MenuState
, viewport : Window.Size
}
type MenuState
= Open
| Closed
type Msg
= ToggleMenu
| CloseMenu
| Resize Window.Size
update : Msg -> Model -> ( Model, Cmd msg )
update msg model =
case msg of
CloseMenu ->
( { model | menu = Closed }, Cmd.none )
ToggleMenu ->
( { model
| menu =
case model.menu of
Open ->
Closed
Closed ->
Open
}
, Cmd.none
)
Resize viewport ->
( { model | viewport = viewport }, Cmd.none )
onClickPreventDefault : msg -> Element.Attribute variation msg
onClickPreventDefault msg =
onWithOptions "click"
{ preventDefault = True, stopPropagation = True }
(Json.Decode.succeed msg)
view : Model -> Html Msg
view model =
Element.viewport stylesheet <|
column Main
[ onClick CloseMenu, height fill ]
[ viewNavbar model.viewport.width model.menu
, row None [ height fill, padding 20 ] [ backgroundImage ]
|> within
[ reactiveConfLogo [] ]
]
reactiveConfLogo : List (Element.Attribute variation msg) -> Element Styles variation msg
reactiveConfLogo attrs =
image None attrs { src = "reactive-logo.png", caption = "ReactiveConf" }
backgroundImage : Element Styles variation msg
backgroundImage =
image None [ width (percent 100) ] { src = "bratislava.jpg", caption = "Bratislava" }
pageLogo : Element Styles variation msg
pageLogo =
row Title
[ alignLeft
, width (fillPortion 1)
]
[ text "CSS"
, el GreenEmphasis [] (text " as bytecode")
]
builtWithElm : Element Styles variation msg
builtWithElm =
row Elm
[ width (fillPortion 1)
, center
]
[ text "Built with Elm!" ]
viewNavbar : Int -> MenuState -> Element Styles variation Msg
viewNavbar viewportWidth menu =
let
menuControls alignment =
[ row None
[ alignment
, width (fillPortion 1)
]
[ viewMenu menu ]
]
contents =
if viewportWidth < 640 then
menuControls center
else if viewportWidth < 1024 then
List.append [ pageLogo ] (menuControls alignRight)
else
List.append [ pageLogo, builtWithElm ] (menuControls alignRight)
in
row Navbar
[ width fill
, paddingLeft 24
, paddingRight 24
, paddingTop 16
, paddingBottom 16
, verticalCenter
]
contents
viewMenu : MenuState -> Element Styles variation Msg
viewMenu menu =
let
menuControls =
row Menu
[ spacing 16, onClickPreventDefault ToggleMenu ]
[ image ProfileBadge
[ width (px 32), height (px 32) ]
{ src = "profile.jpg", caption = "PI:NAME:<NAME>END_PI" }
, row MenuControls
[ spacing 12 ]
[ text "PI:NAME:<NAME>END_PI"
, viewCaret menu
]
]
in
case menu of
Closed ->
menuControls
Open ->
menuControls
|> below [ menuContents ]
menuContents : Element Styles variation msg
menuContents =
column MenuContents
[ alignRight ]
(List.map viewMenuItem [ "Account", "Messages", "Sign Out" ])
viewMenuItem : String -> Element Styles variation msg
viewMenuItem caption =
el MenuItem [ padding 16 ] (text caption)
viewCaret : MenuState -> Element Styles variation msg
viewCaret menu =
let
caretText =
case menu of
Closed ->
"▼"
Open ->
"▲"
in
el Caret [ center, verticalCenter ] (text caretText)
| elm |
[
{
"context": "ntact \"\n , Html.a [ A.href \"mailto:help@stcsfc.org?Subect=Psalm%20Slides\" ] [ Html.text \"help@stcsfc",
"end": 4851,
"score": 0.9999260306,
"start": 4836,
"tag": "EMAIL",
"value": "help@stcsfc.org"
},
{
"context": "@stcsfc.org?Subect=Psalm%20Slides\" ] [ Html.text \"help@stcsfc.org\" ]\n , Html.text \".\"\n ",
"end": 4905,
"score": 0.9999324679,
"start": 4890,
"tag": "EMAIL",
"value": "help@stcsfc.org"
},
{
"context": "mail: \"\n , Html.a [ A.href \"mailto:psalmodyandpraise@freechurch.org\" ] [ Html.text \"psalmodyandpraise@freechurch.org\"",
"end": 5527,
"score": 0.9999317527,
"start": 5495,
"tag": "EMAIL",
"value": "psalmodyandpraise@freechurch.org"
},
{
"context": ":psalmodyandpraise@freechurch.org\" ] [ Html.text \"psalmodyandpraise@freechurch.org\" ]\n , Html.text \".\"\n ",
"end": 5576,
"score": 0.9999308586,
"start": 5544,
"tag": "EMAIL",
"value": "psalmodyandpraise@freechurch.org"
}
] | site/src/Main.elm | stcolumbas/psalms | 2 | module Main exposing (..)
import Html exposing (Html, program)
import Html.Attributes as A
import Html.Events as E
-- Model
type alias Model =
{ step : Step
, fileFormat : FileFormat
, colour : Maybe Colour
, underlined : Maybe Underlined
, ratioOrResolution : Maybe RatioOrResolution
}
initialModel : Model
initialModel =
{ step = Intro
, fileFormat = None
, colour = Nothing
, underlined = Just True
, ratioOrResolution = Nothing
}
type Step
= Intro
| ChooseFileFormat
| ChooseOptions FileFormat
type FileFormat
= None
| PlainText
| PDF
| PowerPoint
| ProPresenter
type Colour
= BlackOnWhite
| WhiteOnBlack
type RatioOrResolution
= Ratio Ratio
| Resolution Resolution
type Ratio
= Four_Three
| Sixteen_Nine
type Resolution
= R_1080_1920
| R_720_1280
| R_768_1024
type alias Underlined =
Bool
-- Update
type Msg
= GetStartedClicked
| FormatClicked FileFormat
| ColourClicked Colour
| UnderlinedClicked Underlined
| RatioClicked Ratio
| ResolutionClicked Resolution
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
let
model_ =
case msg of
GetStartedClicked ->
{ model | step = ChooseFileFormat }
FormatClicked format ->
if model.fileFormat == format then
model
else
{ model
| step = ChooseOptions format
, fileFormat = format
, colour = Nothing
, underlined = Just True
, ratioOrResolution = Nothing
}
ColourClicked colour ->
{ model | colour = Just colour }
UnderlinedClicked u ->
{ model | underlined = Just u }
RatioClicked ratio ->
case model.fileFormat of
ProPresenter ->
{ model | fileFormat = None }
PlainText ->
{ model | fileFormat = None }
_ ->
{ model | ratioOrResolution = Just <| Ratio ratio }
ResolutionClicked resolution ->
case model.fileFormat of
PowerPoint ->
{ model | fileFormat = None }
PlainText ->
{ model | fileFormat = None }
_ ->
{ model | ratioOrResolution = Just <| Resolution resolution }
in
model_ ! []
-- View
view : Model -> Html Msg
view model =
Html.div [ A.class "w-screen h-screen flex flex-wrap p-8" ]
[ Html.div [ A.class "md:w-1/2 md:ml-auto" ]
[ Html.h1 [ A.class "my-8" ] [ Html.text "Psalms for Screens" ]
, viewHelp model
]
, Html.div [ A.class "md:w-1/3 md:mr-auto" ]
[ Html.div [ A.class "sm:h-8 md:h-64" ] []
, finalLink model
, Html.div [ A.class "h-8" ] []
]
]
viewHelp : Model -> Html Msg
viewHelp model =
case model.step of
Intro ->
Html.div [] [ introView True ]
ChooseFileFormat ->
Html.div [ A.class "pb-8" ]
[ introView False
, chooseFormat model.fileFormat
]
ChooseOptions format ->
Html.div [ A.class "pb-8" ]
[ introView False
, chooseFormat format
, case format of
PlainText ->
Html.text ""
_ ->
chooseOptions model format
]
introView : Bool -> Html Msg
introView showButton =
Html.div [ A.class "" ]
[ Html.div [ A.class "text-left" ]
[ Html.p [] [ Html.text "You can find both Sing Psalms and Scottish Psalter slides for your screens here. As an increasing number of churches use screens for their worship instead of printed psalters, these resources are here to make it easier for you to display the psalm words quickly and easily." ]
, Html.br [] []
, Html.p [] [ Html.text "The psalms are available in a full range of formats, so you can choose the precise version which best suits your needs. Just click the button below to begin." ]
, Html.br [] []
, Html.p []
[ Html.text "If you find a problem, need help or want to request an additional format, please contact "
, Html.a [ A.href "mailto:help@stcsfc.org?Subect=Psalm%20Slides" ] [ Html.text "help@stcsfc.org" ]
, Html.text "."
]
, Html.br [] []
, Html.p []
[ Html.text "\"Sing Psalms\" words are copyright of the Free Church of Scotland and are reproduced here at the request of, and with permission from, the Psalmody and Praise Committee. These files are distributed, solely, for non-commercial use. Copyright queries should be directed to the Clerk to the Psalmody and Praise Committee, Free Church of Scotland, 15 North Bank Street, The Mound, Edinburgh, EH1 2LP, or by email: "
, Html.a [ A.href "mailto:psalmodyandpraise@freechurch.org" ] [ Html.text "psalmodyandpraise@freechurch.org" ]
, Html.text "."
]
, Html.br [] []
, Html.p []
[ Html.text "For more information about our psalm singing tradition, and for full copyright permissions, please click "
, Html.a [ A.href "https://freechurch.org/resources/praise/sing-psalms" ] [ Html.text "here" ]
, Html.text "."
]
, spacer
]
, if showButton then
Html.div [ A.class "text-center py-8" ]
[ button
[ E.onClick GetStartedClicked
, A.class "bg-dark"
, A.id "get-started"
]
[ Html.text "Get Started" ]
]
else
Html.text ""
]
spacer : Html Msg
spacer =
Html.div [ A.class "sm:h-8 md:h-24" ] []
button : List (Html.Attribute Msg) -> List (Html Msg) -> Html Msg
button attrs nodes =
Html.button
(attrs
++ [ A.class buttonClasses ]
)
nodes
buttonClasses : String
buttonClasses =
"text-white text-lg font-bold py-4 px-6 rounded shadow max-w-md mx-1"
selectedButton : Bool -> List (Html.Attribute Msg) -> List (Html Msg) -> Html Msg
selectedButton bool attrs nodes =
if bool then
button ([ A.class "bg-dark text-stcs-red" ] ++ attrs) nodes
else
button ([ A.class "bg-dark" ] ++ attrs) nodes
optionListClasses : String
optionListClasses =
"pt-4"
chooseFormat : FileFormat -> Html Msg
chooseFormat format =
Html.div []
[ Html.h3 [ A.class "my-2" ] [ Html.text "Pick a Format" ]
, selectedButton (format == PlainText) [ A.id "plain-text", E.onClick <| FormatClicked PlainText ] [ Html.text "Plain Text" ]
, selectedButton (format == PDF) [ A.id "pdf", E.onClick <| FormatClicked PDF ] [ Html.text "PDF" ]
, selectedButton (format == PowerPoint) [ A.id "powerpoint", E.onClick <| FormatClicked PowerPoint ] [ Html.text "PowerPoint" ]
, selectedButton (format == ProPresenter) [ A.id "propresenter", E.onClick <| FormatClicked ProPresenter ] [ Html.text "ProPresenter" ]
]
chooseOptions : Model -> FileFormat -> Html Msg
chooseOptions model format =
Html.div []
[ Html.div [ A.class optionListClasses ]
[ Html.h4 [ A.class "my-2" ] [ Html.text "Colour" ]
, selectedButton (maybeBool model.colour BlackOnWhite) [ E.onClick <| ColourClicked BlackOnWhite ] [ Html.text "Black on White" ]
, selectedButton (maybeBool model.colour WhiteOnBlack) [ E.onClick <| ColourClicked WhiteOnBlack ] [ Html.text "White on Black" ]
]
, Html.div [ A.class optionListClasses ]
[ Html.h4 [ A.class "my-2" ] [ Html.text "Underlined" ]
, selectedButton (maybeBool model.underlined True) [ E.onClick <| UnderlinedClicked True ] [ Html.text "With underlining" ]
, selectedButton (maybeBool model.underlined False) [ E.onClick <| UnderlinedClicked False ] [ Html.text "Without underlining" ]
, Html.p [ A.class "pt-2" ] [ Html.text "(The underlined version has the text as printed in the Sing Psalms volumes - underlining indicates where syllables are run together.)" ]
]
, resolutionOrRatioList format model.ratioOrResolution
]
maybeBool : Maybe a -> a -> Bool
maybeBool maybeX1 x2 =
case maybeX1 of
Nothing ->
False
Just x1 ->
x1 == x2
resolutionOrRatioList : FileFormat -> Maybe RatioOrResolution -> Html Msg
resolutionOrRatioList format ratioOrResolution =
case ( format, ratioOrResolution ) of
( None, _ ) ->
Html.text ""
( PlainText, _ ) ->
Html.text ""
( PDF, Just ror ) ->
case ror of
Ratio r ->
ratiosList <| Just r
_ ->
Html.text ""
( PDF, Nothing ) ->
ratiosList Nothing
( PowerPoint, Just ror ) ->
case ror of
Ratio r ->
ratiosList <| Just r
_ ->
Html.text ""
( PowerPoint, Nothing ) ->
ratiosList Nothing
( ProPresenter, Just ror ) ->
case ror of
Resolution r ->
resolutionsList <| Just r
_ ->
Html.text ""
( ProPresenter, Nothing ) ->
resolutionsList Nothing
ratiosList : Maybe Ratio -> Html Msg
ratiosList ratio =
Html.div [ A.class optionListClasses ]
[ Html.h4 [ A.class "my-2" ] [ Html.text "Aspect Ratio" ]
, Html.p [] [ Html.text "" ]
, selectedButton (maybeBool ratio Four_Three) [ E.onClick <| RatioClicked Four_Three ] [ Html.text "4x3" ]
, selectedButton (maybeBool ratio Sixteen_Nine) [ E.onClick <| RatioClicked Sixteen_Nine ] [ Html.text "16x9 (widescreen)" ]
]
resolutionsList : Maybe Resolution -> Html Msg
resolutionsList res =
Html.div [ A.class optionListClasses ]
[ Html.h4 [ A.class "my-2" ] [ Html.text "Screen Resolution" ]
, Html.p [] [ Html.text "" ]
, selectedButton (maybeBool res R_1080_1920) [ E.onClick <| ResolutionClicked R_1080_1920 ] [ Html.text "1080x1920" ]
, selectedButton (maybeBool res R_720_1280) [ E.onClick <| ResolutionClicked R_720_1280 ] [ Html.text "720x1280" ]
, selectedButton (maybeBool res R_768_1024) [ E.onClick <| ResolutionClicked R_768_1024 ] [ Html.text "768x1024" ]
]
finalLink : Model -> Html Msg
finalLink model =
let
link =
makeLink model
in
case link of
Nothing ->
Html.text ""
Just l ->
Html.a
[ A.class ("w-full bg-dark " ++ buttonClasses)
, A.href l
, A.id "click-to-download"
]
[ Html.text "Click to download your Psalms" ]
type Link
= Link FileFormat Colour Underlined RatioOrResolution
makeLink : Model -> Maybe String
makeLink model =
case model.fileFormat of
None ->
Nothing
PlainText ->
Maybe.map3 (Link model.fileFormat)
(Just BlackOnWhite)
(Just True)
(Just <| Ratio Four_Three)
|> Maybe.map link2String
_ ->
Maybe.map3 (Link model.fileFormat)
model.colour
model.underlined
model.ratioOrResolution
|> Maybe.map link2String
link2String : Link -> String
link2String (Link format colour underlined ratioOrResolution) =
case format of
PlainText ->
"/output/PlainText.zip"
_ ->
"/output/"
++ formatString format
++ "/"
++ ratioOrResolutionString ratioOrResolution
++ "_"
++ colourString colour
++ underlinedString underlined
++ ".zip"
underlinedString : Bool -> String
underlinedString u =
if u then
"_underlined"
else
""
colourString : Colour -> String
colourString c =
case c of
BlackOnWhite ->
"b_w"
WhiteOnBlack ->
"w_b"
formatString : FileFormat -> String
formatString format =
case format of
None ->
""
PlainText ->
"PlainText"
PowerPoint ->
"PowerPoint"
PDF ->
"PDF"
ProPresenter ->
"ProPresenter5"
ratioOrResolutionString : RatioOrResolution -> String
ratioOrResolutionString r =
case r of
Ratio Four_Three ->
"4x3"
Ratio Sixteen_Nine ->
"16x9"
Resolution R_1080_1920 ->
"1080x1920"
Resolution R_720_1280 ->
"720x1280"
Resolution R_768_1024 ->
"768x1024"
-- Main
main : Program Never Model Msg
main =
program
{ init = init
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
init : ( Model, Cmd Msg )
init =
( initialModel, Cmd.none )
| 41733 | module Main exposing (..)
import Html exposing (Html, program)
import Html.Attributes as A
import Html.Events as E
-- Model
type alias Model =
{ step : Step
, fileFormat : FileFormat
, colour : Maybe Colour
, underlined : Maybe Underlined
, ratioOrResolution : Maybe RatioOrResolution
}
initialModel : Model
initialModel =
{ step = Intro
, fileFormat = None
, colour = Nothing
, underlined = Just True
, ratioOrResolution = Nothing
}
type Step
= Intro
| ChooseFileFormat
| ChooseOptions FileFormat
type FileFormat
= None
| PlainText
| PDF
| PowerPoint
| ProPresenter
type Colour
= BlackOnWhite
| WhiteOnBlack
type RatioOrResolution
= Ratio Ratio
| Resolution Resolution
type Ratio
= Four_Three
| Sixteen_Nine
type Resolution
= R_1080_1920
| R_720_1280
| R_768_1024
type alias Underlined =
Bool
-- Update
type Msg
= GetStartedClicked
| FormatClicked FileFormat
| ColourClicked Colour
| UnderlinedClicked Underlined
| RatioClicked Ratio
| ResolutionClicked Resolution
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
let
model_ =
case msg of
GetStartedClicked ->
{ model | step = ChooseFileFormat }
FormatClicked format ->
if model.fileFormat == format then
model
else
{ model
| step = ChooseOptions format
, fileFormat = format
, colour = Nothing
, underlined = Just True
, ratioOrResolution = Nothing
}
ColourClicked colour ->
{ model | colour = Just colour }
UnderlinedClicked u ->
{ model | underlined = Just u }
RatioClicked ratio ->
case model.fileFormat of
ProPresenter ->
{ model | fileFormat = None }
PlainText ->
{ model | fileFormat = None }
_ ->
{ model | ratioOrResolution = Just <| Ratio ratio }
ResolutionClicked resolution ->
case model.fileFormat of
PowerPoint ->
{ model | fileFormat = None }
PlainText ->
{ model | fileFormat = None }
_ ->
{ model | ratioOrResolution = Just <| Resolution resolution }
in
model_ ! []
-- View
view : Model -> Html Msg
view model =
Html.div [ A.class "w-screen h-screen flex flex-wrap p-8" ]
[ Html.div [ A.class "md:w-1/2 md:ml-auto" ]
[ Html.h1 [ A.class "my-8" ] [ Html.text "Psalms for Screens" ]
, viewHelp model
]
, Html.div [ A.class "md:w-1/3 md:mr-auto" ]
[ Html.div [ A.class "sm:h-8 md:h-64" ] []
, finalLink model
, Html.div [ A.class "h-8" ] []
]
]
viewHelp : Model -> Html Msg
viewHelp model =
case model.step of
Intro ->
Html.div [] [ introView True ]
ChooseFileFormat ->
Html.div [ A.class "pb-8" ]
[ introView False
, chooseFormat model.fileFormat
]
ChooseOptions format ->
Html.div [ A.class "pb-8" ]
[ introView False
, chooseFormat format
, case format of
PlainText ->
Html.text ""
_ ->
chooseOptions model format
]
introView : Bool -> Html Msg
introView showButton =
Html.div [ A.class "" ]
[ Html.div [ A.class "text-left" ]
[ Html.p [] [ Html.text "You can find both Sing Psalms and Scottish Psalter slides for your screens here. As an increasing number of churches use screens for their worship instead of printed psalters, these resources are here to make it easier for you to display the psalm words quickly and easily." ]
, Html.br [] []
, Html.p [] [ Html.text "The psalms are available in a full range of formats, so you can choose the precise version which best suits your needs. Just click the button below to begin." ]
, Html.br [] []
, Html.p []
[ Html.text "If you find a problem, need help or want to request an additional format, please contact "
, Html.a [ A.href "mailto:<EMAIL>?Subect=Psalm%20Slides" ] [ Html.text "<EMAIL>" ]
, Html.text "."
]
, Html.br [] []
, Html.p []
[ Html.text "\"Sing Psalms\" words are copyright of the Free Church of Scotland and are reproduced here at the request of, and with permission from, the Psalmody and Praise Committee. These files are distributed, solely, for non-commercial use. Copyright queries should be directed to the Clerk to the Psalmody and Praise Committee, Free Church of Scotland, 15 North Bank Street, The Mound, Edinburgh, EH1 2LP, or by email: "
, Html.a [ A.href "mailto:<EMAIL>" ] [ Html.text "<EMAIL>" ]
, Html.text "."
]
, Html.br [] []
, Html.p []
[ Html.text "For more information about our psalm singing tradition, and for full copyright permissions, please click "
, Html.a [ A.href "https://freechurch.org/resources/praise/sing-psalms" ] [ Html.text "here" ]
, Html.text "."
]
, spacer
]
, if showButton then
Html.div [ A.class "text-center py-8" ]
[ button
[ E.onClick GetStartedClicked
, A.class "bg-dark"
, A.id "get-started"
]
[ Html.text "Get Started" ]
]
else
Html.text ""
]
spacer : Html Msg
spacer =
Html.div [ A.class "sm:h-8 md:h-24" ] []
button : List (Html.Attribute Msg) -> List (Html Msg) -> Html Msg
button attrs nodes =
Html.button
(attrs
++ [ A.class buttonClasses ]
)
nodes
buttonClasses : String
buttonClasses =
"text-white text-lg font-bold py-4 px-6 rounded shadow max-w-md mx-1"
selectedButton : Bool -> List (Html.Attribute Msg) -> List (Html Msg) -> Html Msg
selectedButton bool attrs nodes =
if bool then
button ([ A.class "bg-dark text-stcs-red" ] ++ attrs) nodes
else
button ([ A.class "bg-dark" ] ++ attrs) nodes
optionListClasses : String
optionListClasses =
"pt-4"
chooseFormat : FileFormat -> Html Msg
chooseFormat format =
Html.div []
[ Html.h3 [ A.class "my-2" ] [ Html.text "Pick a Format" ]
, selectedButton (format == PlainText) [ A.id "plain-text", E.onClick <| FormatClicked PlainText ] [ Html.text "Plain Text" ]
, selectedButton (format == PDF) [ A.id "pdf", E.onClick <| FormatClicked PDF ] [ Html.text "PDF" ]
, selectedButton (format == PowerPoint) [ A.id "powerpoint", E.onClick <| FormatClicked PowerPoint ] [ Html.text "PowerPoint" ]
, selectedButton (format == ProPresenter) [ A.id "propresenter", E.onClick <| FormatClicked ProPresenter ] [ Html.text "ProPresenter" ]
]
chooseOptions : Model -> FileFormat -> Html Msg
chooseOptions model format =
Html.div []
[ Html.div [ A.class optionListClasses ]
[ Html.h4 [ A.class "my-2" ] [ Html.text "Colour" ]
, selectedButton (maybeBool model.colour BlackOnWhite) [ E.onClick <| ColourClicked BlackOnWhite ] [ Html.text "Black on White" ]
, selectedButton (maybeBool model.colour WhiteOnBlack) [ E.onClick <| ColourClicked WhiteOnBlack ] [ Html.text "White on Black" ]
]
, Html.div [ A.class optionListClasses ]
[ Html.h4 [ A.class "my-2" ] [ Html.text "Underlined" ]
, selectedButton (maybeBool model.underlined True) [ E.onClick <| UnderlinedClicked True ] [ Html.text "With underlining" ]
, selectedButton (maybeBool model.underlined False) [ E.onClick <| UnderlinedClicked False ] [ Html.text "Without underlining" ]
, Html.p [ A.class "pt-2" ] [ Html.text "(The underlined version has the text as printed in the Sing Psalms volumes - underlining indicates where syllables are run together.)" ]
]
, resolutionOrRatioList format model.ratioOrResolution
]
maybeBool : Maybe a -> a -> Bool
maybeBool maybeX1 x2 =
case maybeX1 of
Nothing ->
False
Just x1 ->
x1 == x2
resolutionOrRatioList : FileFormat -> Maybe RatioOrResolution -> Html Msg
resolutionOrRatioList format ratioOrResolution =
case ( format, ratioOrResolution ) of
( None, _ ) ->
Html.text ""
( PlainText, _ ) ->
Html.text ""
( PDF, Just ror ) ->
case ror of
Ratio r ->
ratiosList <| Just r
_ ->
Html.text ""
( PDF, Nothing ) ->
ratiosList Nothing
( PowerPoint, Just ror ) ->
case ror of
Ratio r ->
ratiosList <| Just r
_ ->
Html.text ""
( PowerPoint, Nothing ) ->
ratiosList Nothing
( ProPresenter, Just ror ) ->
case ror of
Resolution r ->
resolutionsList <| Just r
_ ->
Html.text ""
( ProPresenter, Nothing ) ->
resolutionsList Nothing
ratiosList : Maybe Ratio -> Html Msg
ratiosList ratio =
Html.div [ A.class optionListClasses ]
[ Html.h4 [ A.class "my-2" ] [ Html.text "Aspect Ratio" ]
, Html.p [] [ Html.text "" ]
, selectedButton (maybeBool ratio Four_Three) [ E.onClick <| RatioClicked Four_Three ] [ Html.text "4x3" ]
, selectedButton (maybeBool ratio Sixteen_Nine) [ E.onClick <| RatioClicked Sixteen_Nine ] [ Html.text "16x9 (widescreen)" ]
]
resolutionsList : Maybe Resolution -> Html Msg
resolutionsList res =
Html.div [ A.class optionListClasses ]
[ Html.h4 [ A.class "my-2" ] [ Html.text "Screen Resolution" ]
, Html.p [] [ Html.text "" ]
, selectedButton (maybeBool res R_1080_1920) [ E.onClick <| ResolutionClicked R_1080_1920 ] [ Html.text "1080x1920" ]
, selectedButton (maybeBool res R_720_1280) [ E.onClick <| ResolutionClicked R_720_1280 ] [ Html.text "720x1280" ]
, selectedButton (maybeBool res R_768_1024) [ E.onClick <| ResolutionClicked R_768_1024 ] [ Html.text "768x1024" ]
]
finalLink : Model -> Html Msg
finalLink model =
let
link =
makeLink model
in
case link of
Nothing ->
Html.text ""
Just l ->
Html.a
[ A.class ("w-full bg-dark " ++ buttonClasses)
, A.href l
, A.id "click-to-download"
]
[ Html.text "Click to download your Psalms" ]
type Link
= Link FileFormat Colour Underlined RatioOrResolution
makeLink : Model -> Maybe String
makeLink model =
case model.fileFormat of
None ->
Nothing
PlainText ->
Maybe.map3 (Link model.fileFormat)
(Just BlackOnWhite)
(Just True)
(Just <| Ratio Four_Three)
|> Maybe.map link2String
_ ->
Maybe.map3 (Link model.fileFormat)
model.colour
model.underlined
model.ratioOrResolution
|> Maybe.map link2String
link2String : Link -> String
link2String (Link format colour underlined ratioOrResolution) =
case format of
PlainText ->
"/output/PlainText.zip"
_ ->
"/output/"
++ formatString format
++ "/"
++ ratioOrResolutionString ratioOrResolution
++ "_"
++ colourString colour
++ underlinedString underlined
++ ".zip"
underlinedString : Bool -> String
underlinedString u =
if u then
"_underlined"
else
""
colourString : Colour -> String
colourString c =
case c of
BlackOnWhite ->
"b_w"
WhiteOnBlack ->
"w_b"
formatString : FileFormat -> String
formatString format =
case format of
None ->
""
PlainText ->
"PlainText"
PowerPoint ->
"PowerPoint"
PDF ->
"PDF"
ProPresenter ->
"ProPresenter5"
ratioOrResolutionString : RatioOrResolution -> String
ratioOrResolutionString r =
case r of
Ratio Four_Three ->
"4x3"
Ratio Sixteen_Nine ->
"16x9"
Resolution R_1080_1920 ->
"1080x1920"
Resolution R_720_1280 ->
"720x1280"
Resolution R_768_1024 ->
"768x1024"
-- Main
main : Program Never Model Msg
main =
program
{ init = init
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
init : ( Model, Cmd Msg )
init =
( initialModel, Cmd.none )
| true | module Main exposing (..)
import Html exposing (Html, program)
import Html.Attributes as A
import Html.Events as E
-- Model
type alias Model =
{ step : Step
, fileFormat : FileFormat
, colour : Maybe Colour
, underlined : Maybe Underlined
, ratioOrResolution : Maybe RatioOrResolution
}
initialModel : Model
initialModel =
{ step = Intro
, fileFormat = None
, colour = Nothing
, underlined = Just True
, ratioOrResolution = Nothing
}
type Step
= Intro
| ChooseFileFormat
| ChooseOptions FileFormat
type FileFormat
= None
| PlainText
| PDF
| PowerPoint
| ProPresenter
type Colour
= BlackOnWhite
| WhiteOnBlack
type RatioOrResolution
= Ratio Ratio
| Resolution Resolution
type Ratio
= Four_Three
| Sixteen_Nine
type Resolution
= R_1080_1920
| R_720_1280
| R_768_1024
type alias Underlined =
Bool
-- Update
type Msg
= GetStartedClicked
| FormatClicked FileFormat
| ColourClicked Colour
| UnderlinedClicked Underlined
| RatioClicked Ratio
| ResolutionClicked Resolution
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
let
model_ =
case msg of
GetStartedClicked ->
{ model | step = ChooseFileFormat }
FormatClicked format ->
if model.fileFormat == format then
model
else
{ model
| step = ChooseOptions format
, fileFormat = format
, colour = Nothing
, underlined = Just True
, ratioOrResolution = Nothing
}
ColourClicked colour ->
{ model | colour = Just colour }
UnderlinedClicked u ->
{ model | underlined = Just u }
RatioClicked ratio ->
case model.fileFormat of
ProPresenter ->
{ model | fileFormat = None }
PlainText ->
{ model | fileFormat = None }
_ ->
{ model | ratioOrResolution = Just <| Ratio ratio }
ResolutionClicked resolution ->
case model.fileFormat of
PowerPoint ->
{ model | fileFormat = None }
PlainText ->
{ model | fileFormat = None }
_ ->
{ model | ratioOrResolution = Just <| Resolution resolution }
in
model_ ! []
-- View
view : Model -> Html Msg
view model =
Html.div [ A.class "w-screen h-screen flex flex-wrap p-8" ]
[ Html.div [ A.class "md:w-1/2 md:ml-auto" ]
[ Html.h1 [ A.class "my-8" ] [ Html.text "Psalms for Screens" ]
, viewHelp model
]
, Html.div [ A.class "md:w-1/3 md:mr-auto" ]
[ Html.div [ A.class "sm:h-8 md:h-64" ] []
, finalLink model
, Html.div [ A.class "h-8" ] []
]
]
viewHelp : Model -> Html Msg
viewHelp model =
case model.step of
Intro ->
Html.div [] [ introView True ]
ChooseFileFormat ->
Html.div [ A.class "pb-8" ]
[ introView False
, chooseFormat model.fileFormat
]
ChooseOptions format ->
Html.div [ A.class "pb-8" ]
[ introView False
, chooseFormat format
, case format of
PlainText ->
Html.text ""
_ ->
chooseOptions model format
]
introView : Bool -> Html Msg
introView showButton =
Html.div [ A.class "" ]
[ Html.div [ A.class "text-left" ]
[ Html.p [] [ Html.text "You can find both Sing Psalms and Scottish Psalter slides for your screens here. As an increasing number of churches use screens for their worship instead of printed psalters, these resources are here to make it easier for you to display the psalm words quickly and easily." ]
, Html.br [] []
, Html.p [] [ Html.text "The psalms are available in a full range of formats, so you can choose the precise version which best suits your needs. Just click the button below to begin." ]
, Html.br [] []
, Html.p []
[ Html.text "If you find a problem, need help or want to request an additional format, please contact "
, Html.a [ A.href "mailto:PI:EMAIL:<EMAIL>END_PI?Subect=Psalm%20Slides" ] [ Html.text "PI:EMAIL:<EMAIL>END_PI" ]
, Html.text "."
]
, Html.br [] []
, Html.p []
[ Html.text "\"Sing Psalms\" words are copyright of the Free Church of Scotland and are reproduced here at the request of, and with permission from, the Psalmody and Praise Committee. These files are distributed, solely, for non-commercial use. Copyright queries should be directed to the Clerk to the Psalmody and Praise Committee, Free Church of Scotland, 15 North Bank Street, The Mound, Edinburgh, EH1 2LP, or by email: "
, Html.a [ A.href "mailto:PI:EMAIL:<EMAIL>END_PI" ] [ Html.text "PI:EMAIL:<EMAIL>END_PI" ]
, Html.text "."
]
, Html.br [] []
, Html.p []
[ Html.text "For more information about our psalm singing tradition, and for full copyright permissions, please click "
, Html.a [ A.href "https://freechurch.org/resources/praise/sing-psalms" ] [ Html.text "here" ]
, Html.text "."
]
, spacer
]
, if showButton then
Html.div [ A.class "text-center py-8" ]
[ button
[ E.onClick GetStartedClicked
, A.class "bg-dark"
, A.id "get-started"
]
[ Html.text "Get Started" ]
]
else
Html.text ""
]
spacer : Html Msg
spacer =
Html.div [ A.class "sm:h-8 md:h-24" ] []
button : List (Html.Attribute Msg) -> List (Html Msg) -> Html Msg
button attrs nodes =
Html.button
(attrs
++ [ A.class buttonClasses ]
)
nodes
buttonClasses : String
buttonClasses =
"text-white text-lg font-bold py-4 px-6 rounded shadow max-w-md mx-1"
selectedButton : Bool -> List (Html.Attribute Msg) -> List (Html Msg) -> Html Msg
selectedButton bool attrs nodes =
if bool then
button ([ A.class "bg-dark text-stcs-red" ] ++ attrs) nodes
else
button ([ A.class "bg-dark" ] ++ attrs) nodes
optionListClasses : String
optionListClasses =
"pt-4"
chooseFormat : FileFormat -> Html Msg
chooseFormat format =
Html.div []
[ Html.h3 [ A.class "my-2" ] [ Html.text "Pick a Format" ]
, selectedButton (format == PlainText) [ A.id "plain-text", E.onClick <| FormatClicked PlainText ] [ Html.text "Plain Text" ]
, selectedButton (format == PDF) [ A.id "pdf", E.onClick <| FormatClicked PDF ] [ Html.text "PDF" ]
, selectedButton (format == PowerPoint) [ A.id "powerpoint", E.onClick <| FormatClicked PowerPoint ] [ Html.text "PowerPoint" ]
, selectedButton (format == ProPresenter) [ A.id "propresenter", E.onClick <| FormatClicked ProPresenter ] [ Html.text "ProPresenter" ]
]
chooseOptions : Model -> FileFormat -> Html Msg
chooseOptions model format =
Html.div []
[ Html.div [ A.class optionListClasses ]
[ Html.h4 [ A.class "my-2" ] [ Html.text "Colour" ]
, selectedButton (maybeBool model.colour BlackOnWhite) [ E.onClick <| ColourClicked BlackOnWhite ] [ Html.text "Black on White" ]
, selectedButton (maybeBool model.colour WhiteOnBlack) [ E.onClick <| ColourClicked WhiteOnBlack ] [ Html.text "White on Black" ]
]
, Html.div [ A.class optionListClasses ]
[ Html.h4 [ A.class "my-2" ] [ Html.text "Underlined" ]
, selectedButton (maybeBool model.underlined True) [ E.onClick <| UnderlinedClicked True ] [ Html.text "With underlining" ]
, selectedButton (maybeBool model.underlined False) [ E.onClick <| UnderlinedClicked False ] [ Html.text "Without underlining" ]
, Html.p [ A.class "pt-2" ] [ Html.text "(The underlined version has the text as printed in the Sing Psalms volumes - underlining indicates where syllables are run together.)" ]
]
, resolutionOrRatioList format model.ratioOrResolution
]
maybeBool : Maybe a -> a -> Bool
maybeBool maybeX1 x2 =
case maybeX1 of
Nothing ->
False
Just x1 ->
x1 == x2
resolutionOrRatioList : FileFormat -> Maybe RatioOrResolution -> Html Msg
resolutionOrRatioList format ratioOrResolution =
case ( format, ratioOrResolution ) of
( None, _ ) ->
Html.text ""
( PlainText, _ ) ->
Html.text ""
( PDF, Just ror ) ->
case ror of
Ratio r ->
ratiosList <| Just r
_ ->
Html.text ""
( PDF, Nothing ) ->
ratiosList Nothing
( PowerPoint, Just ror ) ->
case ror of
Ratio r ->
ratiosList <| Just r
_ ->
Html.text ""
( PowerPoint, Nothing ) ->
ratiosList Nothing
( ProPresenter, Just ror ) ->
case ror of
Resolution r ->
resolutionsList <| Just r
_ ->
Html.text ""
( ProPresenter, Nothing ) ->
resolutionsList Nothing
ratiosList : Maybe Ratio -> Html Msg
ratiosList ratio =
Html.div [ A.class optionListClasses ]
[ Html.h4 [ A.class "my-2" ] [ Html.text "Aspect Ratio" ]
, Html.p [] [ Html.text "" ]
, selectedButton (maybeBool ratio Four_Three) [ E.onClick <| RatioClicked Four_Three ] [ Html.text "4x3" ]
, selectedButton (maybeBool ratio Sixteen_Nine) [ E.onClick <| RatioClicked Sixteen_Nine ] [ Html.text "16x9 (widescreen)" ]
]
resolutionsList : Maybe Resolution -> Html Msg
resolutionsList res =
Html.div [ A.class optionListClasses ]
[ Html.h4 [ A.class "my-2" ] [ Html.text "Screen Resolution" ]
, Html.p [] [ Html.text "" ]
, selectedButton (maybeBool res R_1080_1920) [ E.onClick <| ResolutionClicked R_1080_1920 ] [ Html.text "1080x1920" ]
, selectedButton (maybeBool res R_720_1280) [ E.onClick <| ResolutionClicked R_720_1280 ] [ Html.text "720x1280" ]
, selectedButton (maybeBool res R_768_1024) [ E.onClick <| ResolutionClicked R_768_1024 ] [ Html.text "768x1024" ]
]
finalLink : Model -> Html Msg
finalLink model =
let
link =
makeLink model
in
case link of
Nothing ->
Html.text ""
Just l ->
Html.a
[ A.class ("w-full bg-dark " ++ buttonClasses)
, A.href l
, A.id "click-to-download"
]
[ Html.text "Click to download your Psalms" ]
type Link
= Link FileFormat Colour Underlined RatioOrResolution
makeLink : Model -> Maybe String
makeLink model =
case model.fileFormat of
None ->
Nothing
PlainText ->
Maybe.map3 (Link model.fileFormat)
(Just BlackOnWhite)
(Just True)
(Just <| Ratio Four_Three)
|> Maybe.map link2String
_ ->
Maybe.map3 (Link model.fileFormat)
model.colour
model.underlined
model.ratioOrResolution
|> Maybe.map link2String
link2String : Link -> String
link2String (Link format colour underlined ratioOrResolution) =
case format of
PlainText ->
"/output/PlainText.zip"
_ ->
"/output/"
++ formatString format
++ "/"
++ ratioOrResolutionString ratioOrResolution
++ "_"
++ colourString colour
++ underlinedString underlined
++ ".zip"
underlinedString : Bool -> String
underlinedString u =
if u then
"_underlined"
else
""
colourString : Colour -> String
colourString c =
case c of
BlackOnWhite ->
"b_w"
WhiteOnBlack ->
"w_b"
formatString : FileFormat -> String
formatString format =
case format of
None ->
""
PlainText ->
"PlainText"
PowerPoint ->
"PowerPoint"
PDF ->
"PDF"
ProPresenter ->
"ProPresenter5"
ratioOrResolutionString : RatioOrResolution -> String
ratioOrResolutionString r =
case r of
Ratio Four_Three ->
"4x3"
Ratio Sixteen_Nine ->
"16x9"
Resolution R_1080_1920 ->
"1080x1920"
Resolution R_720_1280 ->
"720x1280"
Resolution R_768_1024 ->
"768x1024"
-- Main
main : Program Never Model Msg
main =
program
{ init = init
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
init : ( Model, Cmd Msg )
init =
( initialModel, Cmd.none )
| elm |
[
{
"context": "{- Copyright (C) 2018 Mark D. Blackwell.\n All rights reserved.\n This program is distr",
"end": 39,
"score": 0.9998586774,
"start": 22,
"tag": "NAME",
"value": "Mark D. Blackwell"
}
] | src/front-end/initialize/SongInitialize.elm | MarkDBlackwell/qplaylist-remember | 0 | {- Copyright (C) 2018 Mark D. Blackwell.
All rights reserved.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-}
module SongInitialize exposing
( likeOrCommentCountInit
, songCommentingOnNowMaybeInit
, songLikingNowMaybeInit
, songLikingOrCommentingInit
, songsRecentInit
)
import SongType
exposing
( Artist
, LikeOrCommentCount
, SongRemembered
, SongRememberedMaybe
, SongsRecent
, Time
, Timestamp
, Title
)
likeOrCommentCountInit : LikeOrCommentCount
likeOrCommentCountInit =
0
-- MODEL
artistInit : Artist
artistInit =
""
songCommentingOnNowMaybeInit : SongRememberedMaybe
songCommentingOnNowMaybeInit =
Nothing
songLikingNowMaybeInit : SongRememberedMaybe
songLikingNowMaybeInit =
Nothing
songLikingOrCommentingInit : SongRemembered
songLikingOrCommentingInit =
SongRemembered artistInit likeOrCommentCountInit timeInit timestampInit titleInit
songsRecentInit : SongsRecent
songsRecentInit =
[]
timeInit : Time
timeInit =
""
timestampInit : Timestamp
timestampInit =
""
titleInit : Title
titleInit =
""
| 6907 | {- Copyright (C) 2018 <NAME>.
All rights reserved.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-}
module SongInitialize exposing
( likeOrCommentCountInit
, songCommentingOnNowMaybeInit
, songLikingNowMaybeInit
, songLikingOrCommentingInit
, songsRecentInit
)
import SongType
exposing
( Artist
, LikeOrCommentCount
, SongRemembered
, SongRememberedMaybe
, SongsRecent
, Time
, Timestamp
, Title
)
likeOrCommentCountInit : LikeOrCommentCount
likeOrCommentCountInit =
0
-- MODEL
artistInit : Artist
artistInit =
""
songCommentingOnNowMaybeInit : SongRememberedMaybe
songCommentingOnNowMaybeInit =
Nothing
songLikingNowMaybeInit : SongRememberedMaybe
songLikingNowMaybeInit =
Nothing
songLikingOrCommentingInit : SongRemembered
songLikingOrCommentingInit =
SongRemembered artistInit likeOrCommentCountInit timeInit timestampInit titleInit
songsRecentInit : SongsRecent
songsRecentInit =
[]
timeInit : Time
timeInit =
""
timestampInit : Timestamp
timestampInit =
""
titleInit : Title
titleInit =
""
| true | {- Copyright (C) 2018 PI:NAME:<NAME>END_PI.
All rights reserved.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-}
module SongInitialize exposing
( likeOrCommentCountInit
, songCommentingOnNowMaybeInit
, songLikingNowMaybeInit
, songLikingOrCommentingInit
, songsRecentInit
)
import SongType
exposing
( Artist
, LikeOrCommentCount
, SongRemembered
, SongRememberedMaybe
, SongsRecent
, Time
, Timestamp
, Title
)
likeOrCommentCountInit : LikeOrCommentCount
likeOrCommentCountInit =
0
-- MODEL
artistInit : Artist
artistInit =
""
songCommentingOnNowMaybeInit : SongRememberedMaybe
songCommentingOnNowMaybeInit =
Nothing
songLikingNowMaybeInit : SongRememberedMaybe
songLikingNowMaybeInit =
Nothing
songLikingOrCommentingInit : SongRemembered
songLikingOrCommentingInit =
SongRemembered artistInit likeOrCommentCountInit timeInit timestampInit titleInit
songsRecentInit : SongsRecent
songsRecentInit =
[]
timeInit : Time
timeInit =
""
timestampInit : Timestamp
timestampInit =
""
titleInit : Title
titleInit =
""
| elm |
[
{
"context": "fig\n@docs getIndexSimpleConfig\n\nCopyright (c) 2016 Robin Luiten\n\n-}\n\nimport Index.Model as Model\n exposing\n ",
"end": 846,
"score": 0.9998511076,
"start": 834,
"tag": "NAME",
"value": "Robin Luiten"
}
] | src/Index/Defaults.elm | eniac314/elm-text-search | 43 | module Index.Defaults exposing
( indexVersion
, elmTextSearchIndexType
, defaultTransformFactories
, defaultFilterFactories
, defaultTokenTrimmerFuncCreator
, defaultStemmerFuncCreator
, defaultStopWordFilterFuncCreator
, defaultInitialTransformFactories
, getDefaultIndexConfig
, getIndexSimpleConfig
)
{-| Defaults for indexes and configurations.
## Index Storage Engine Version and Type
@docs indexVersion
@docs elmTextSearchIndexType
## Built in Transforms and Filters
@docs defaultTransformFactories
@docs defaultFilterFactories
@docs defaultTokenTrimmerFuncCreator
@docs defaultStemmerFuncCreator
@docs defaultStopWordFilterFuncCreator
@docs defaultInitialTransformFactories
## Config type adapters
@docs getDefaultIndexConfig
@docs getIndexSimpleConfig
Copyright (c) 2016 Robin Luiten
-}
import Index.Model as Model
exposing
( FilterFactory
, IndexSimpleConfig
, TransformFactory
)
import Index.Utils
import Stemmer
import StopWordFilter
import TokenProcessors
{-| The version of index, for loading a saved index.
This is not the same as package version.
This needs to change if the encoded format changes. Be careful of updates to
Trie package, if Trie encoding format changes this version needs to change as
well.
-}
indexVersion : String
indexVersion =
"1.1.0"
{-| The type of index defaults to using.
It defines the default token transforms and filters.
-}
elmTextSearchIndexType : String
elmTextSearchIndexType =
"-= ElmTextSearch Index Type 1 =-"
{-| Index default transform factories.
-}
defaultTransformFactories : List (TransformFactory doc)
defaultTransformFactories =
[ defaultStemmerFuncCreator
]
{-| Index default transform factories that apply before filters.
-}
defaultInitialTransformFactories : List (TransformFactory doc)
defaultInitialTransformFactories =
[ defaultTokenTrimmerFuncCreator
]
{-| Index default filter factories.
-}
defaultFilterFactories : List (FilterFactory doc)
defaultFilterFactories =
[ defaultStopWordFilterFuncCreator
]
{-| The default token trimmer transform function creator.
Normally applied first in transform functions.
-}
defaultTokenTrimmerFuncCreator : TransformFactory doc
defaultTokenTrimmerFuncCreator =
Index.Utils.createFuncCreator TokenProcessors.trimmer
{-| The default token stemmer transform function creator.
-}
defaultStemmerFuncCreator : TransformFactory doc
defaultStemmerFuncCreator =
Index.Utils.createFuncCreator Stemmer.stem
{-| The default stop word filter function creator.
-}
defaultStopWordFilterFuncCreator : FilterFactory doc
defaultStopWordFilterFuncCreator =
StopWordFilter.createDefaultFilterFunc
{-| Convert Index.Model.ModelSimpleConfig to Index.Model.Config
Filling in default values for fields not in SimpleConfig
This is the definition of the default index configuration.
-}
getDefaultIndexConfig : Model.ModelSimpleConfig doc -> Model.Config doc
getDefaultIndexConfig { indexType, ref, fields, listFields } =
{ indexType = indexType
, ref = ref
, fields = fields
, listFields = listFields
, initialTransformFactories = defaultInitialTransformFactories
, transformFactories = defaultTransformFactories
, filterFactories = defaultFilterFactories
}
{-| convert ElmTextSearch.IndexSimpleConfig to Index.Model.ModelSimpleConfig
-}
getIndexSimpleConfig : IndexSimpleConfig doc -> Model.ModelSimpleConfig doc
getIndexSimpleConfig { ref, fields, listFields } =
{ indexType = elmTextSearchIndexType
, ref = ref
, fields = fields
, listFields = listFields
}
| 59750 | module Index.Defaults exposing
( indexVersion
, elmTextSearchIndexType
, defaultTransformFactories
, defaultFilterFactories
, defaultTokenTrimmerFuncCreator
, defaultStemmerFuncCreator
, defaultStopWordFilterFuncCreator
, defaultInitialTransformFactories
, getDefaultIndexConfig
, getIndexSimpleConfig
)
{-| Defaults for indexes and configurations.
## Index Storage Engine Version and Type
@docs indexVersion
@docs elmTextSearchIndexType
## Built in Transforms and Filters
@docs defaultTransformFactories
@docs defaultFilterFactories
@docs defaultTokenTrimmerFuncCreator
@docs defaultStemmerFuncCreator
@docs defaultStopWordFilterFuncCreator
@docs defaultInitialTransformFactories
## Config type adapters
@docs getDefaultIndexConfig
@docs getIndexSimpleConfig
Copyright (c) 2016 <NAME>
-}
import Index.Model as Model
exposing
( FilterFactory
, IndexSimpleConfig
, TransformFactory
)
import Index.Utils
import Stemmer
import StopWordFilter
import TokenProcessors
{-| The version of index, for loading a saved index.
This is not the same as package version.
This needs to change if the encoded format changes. Be careful of updates to
Trie package, if Trie encoding format changes this version needs to change as
well.
-}
indexVersion : String
indexVersion =
"1.1.0"
{-| The type of index defaults to using.
It defines the default token transforms and filters.
-}
elmTextSearchIndexType : String
elmTextSearchIndexType =
"-= ElmTextSearch Index Type 1 =-"
{-| Index default transform factories.
-}
defaultTransformFactories : List (TransformFactory doc)
defaultTransformFactories =
[ defaultStemmerFuncCreator
]
{-| Index default transform factories that apply before filters.
-}
defaultInitialTransformFactories : List (TransformFactory doc)
defaultInitialTransformFactories =
[ defaultTokenTrimmerFuncCreator
]
{-| Index default filter factories.
-}
defaultFilterFactories : List (FilterFactory doc)
defaultFilterFactories =
[ defaultStopWordFilterFuncCreator
]
{-| The default token trimmer transform function creator.
Normally applied first in transform functions.
-}
defaultTokenTrimmerFuncCreator : TransformFactory doc
defaultTokenTrimmerFuncCreator =
Index.Utils.createFuncCreator TokenProcessors.trimmer
{-| The default token stemmer transform function creator.
-}
defaultStemmerFuncCreator : TransformFactory doc
defaultStemmerFuncCreator =
Index.Utils.createFuncCreator Stemmer.stem
{-| The default stop word filter function creator.
-}
defaultStopWordFilterFuncCreator : FilterFactory doc
defaultStopWordFilterFuncCreator =
StopWordFilter.createDefaultFilterFunc
{-| Convert Index.Model.ModelSimpleConfig to Index.Model.Config
Filling in default values for fields not in SimpleConfig
This is the definition of the default index configuration.
-}
getDefaultIndexConfig : Model.ModelSimpleConfig doc -> Model.Config doc
getDefaultIndexConfig { indexType, ref, fields, listFields } =
{ indexType = indexType
, ref = ref
, fields = fields
, listFields = listFields
, initialTransformFactories = defaultInitialTransformFactories
, transformFactories = defaultTransformFactories
, filterFactories = defaultFilterFactories
}
{-| convert ElmTextSearch.IndexSimpleConfig to Index.Model.ModelSimpleConfig
-}
getIndexSimpleConfig : IndexSimpleConfig doc -> Model.ModelSimpleConfig doc
getIndexSimpleConfig { ref, fields, listFields } =
{ indexType = elmTextSearchIndexType
, ref = ref
, fields = fields
, listFields = listFields
}
| true | module Index.Defaults exposing
( indexVersion
, elmTextSearchIndexType
, defaultTransformFactories
, defaultFilterFactories
, defaultTokenTrimmerFuncCreator
, defaultStemmerFuncCreator
, defaultStopWordFilterFuncCreator
, defaultInitialTransformFactories
, getDefaultIndexConfig
, getIndexSimpleConfig
)
{-| Defaults for indexes and configurations.
## Index Storage Engine Version and Type
@docs indexVersion
@docs elmTextSearchIndexType
## Built in Transforms and Filters
@docs defaultTransformFactories
@docs defaultFilterFactories
@docs defaultTokenTrimmerFuncCreator
@docs defaultStemmerFuncCreator
@docs defaultStopWordFilterFuncCreator
@docs defaultInitialTransformFactories
## Config type adapters
@docs getDefaultIndexConfig
@docs getIndexSimpleConfig
Copyright (c) 2016 PI:NAME:<NAME>END_PI
-}
import Index.Model as Model
exposing
( FilterFactory
, IndexSimpleConfig
, TransformFactory
)
import Index.Utils
import Stemmer
import StopWordFilter
import TokenProcessors
{-| The version of index, for loading a saved index.
This is not the same as package version.
This needs to change if the encoded format changes. Be careful of updates to
Trie package, if Trie encoding format changes this version needs to change as
well.
-}
indexVersion : String
indexVersion =
"1.1.0"
{-| The type of index defaults to using.
It defines the default token transforms and filters.
-}
elmTextSearchIndexType : String
elmTextSearchIndexType =
"-= ElmTextSearch Index Type 1 =-"
{-| Index default transform factories.
-}
defaultTransformFactories : List (TransformFactory doc)
defaultTransformFactories =
[ defaultStemmerFuncCreator
]
{-| Index default transform factories that apply before filters.
-}
defaultInitialTransformFactories : List (TransformFactory doc)
defaultInitialTransformFactories =
[ defaultTokenTrimmerFuncCreator
]
{-| Index default filter factories.
-}
defaultFilterFactories : List (FilterFactory doc)
defaultFilterFactories =
[ defaultStopWordFilterFuncCreator
]
{-| The default token trimmer transform function creator.
Normally applied first in transform functions.
-}
defaultTokenTrimmerFuncCreator : TransformFactory doc
defaultTokenTrimmerFuncCreator =
Index.Utils.createFuncCreator TokenProcessors.trimmer
{-| The default token stemmer transform function creator.
-}
defaultStemmerFuncCreator : TransformFactory doc
defaultStemmerFuncCreator =
Index.Utils.createFuncCreator Stemmer.stem
{-| The default stop word filter function creator.
-}
defaultStopWordFilterFuncCreator : FilterFactory doc
defaultStopWordFilterFuncCreator =
StopWordFilter.createDefaultFilterFunc
{-| Convert Index.Model.ModelSimpleConfig to Index.Model.Config
Filling in default values for fields not in SimpleConfig
This is the definition of the default index configuration.
-}
getDefaultIndexConfig : Model.ModelSimpleConfig doc -> Model.Config doc
getDefaultIndexConfig { indexType, ref, fields, listFields } =
{ indexType = indexType
, ref = ref
, fields = fields
, listFields = listFields
, initialTransformFactories = defaultInitialTransformFactories
, transformFactories = defaultTransformFactories
, filterFactories = defaultFilterFactories
}
{-| convert ElmTextSearch.IndexSimpleConfig to Index.Model.ModelSimpleConfig
-}
getIndexSimpleConfig : IndexSimpleConfig doc -> Model.ModelSimpleConfig doc
getIndexSimpleConfig { ref, fields, listFields } =
{ indexType = elmTextSearchIndexType
, ref = ref
, fields = fields
, listFields = listFields
}
| elm |
[
{
"context": "{- Copyright (C) 2018 Mark D. Blackwell.\n All rights reserved.\n This program is distr",
"end": 39,
"score": 0.9998537302,
"start": 22,
"tag": "NAME",
"value": "Mark D. Blackwell"
}
] | src/front-end/type/SongType.elm | MarkDBlackwell/qplaylist-remember | 0 | {- Copyright (C) 2018 Mark D. Blackwell.
All rights reserved.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-}
module SongType exposing
( Artist
, LikeOrCommentCount
, SongFieldString
, SongGroup(..)
, SongGroupLength
, SongRecent
, SongRecentBase
, SongRecentMaybe
, SongRecentOrRemembered
, SongRemembered
, SongRememberedMaybe
, SongTimeBase
, SongTimeExceptBase
, SongTimeless
, SongTimelessBase
, SongsRecent
, SongsRecentIndex
, SongsRecentOrRemembered
, SongsRecentOrRememberedIndex
, SongsRemembered
, SongsRememberedIndex
, SongsRememberedIndexList
, SongsRememberedIndexMaybe
, SongsRememberedMaybe
, SongsTimeless
, Time
, Timestamp
, Title
)
-- MODEL
type alias Artist =
SongFieldString
type alias LikeOrCommentCount =
Int
type alias SongFieldString =
String
type alias SongRecent =
--Keep order (for JSON decoding):
{ artist : Artist
, time : Time
, timestamp : Timestamp
, title : Title
}
type alias SongRecentBase a =
{ a
| artist : Artist
, time : Time
, timestamp : Timestamp
, title : Title
}
type alias SongRecentMaybe =
Maybe SongRecent
type alias SongRecentOrRemembered =
SongRemembered
type alias SongRemembered =
{ artist : Artist
, likeOrCommentCount : LikeOrCommentCount
, time : Time
, timestamp : Timestamp
, title : Title
}
type alias SongRememberedMaybe =
Maybe SongRemembered
type alias SongTimeBase a =
{ a
| time : Time
, timestamp : Timestamp
}
type alias SongTimeExceptBase a =
{ a
| artist : Artist
, likeOrCommentCount : LikeOrCommentCount
, title : Title
}
type alias SongTimeless =
{ artist : Artist
, title : Title
}
type alias SongTimelessBase a =
{ a
| artist : Artist
, title : Title
}
type alias SongsRecent =
List SongRecent
type alias SongsRecentIndex =
Int
type alias SongsRecentOrRemembered =
SongsRemembered
type alias SongsRemembered =
List SongRemembered
type alias SongsRememberedIndex =
Int
type alias SongsRememberedIndexList =
List SongsRememberedIndex
type alias SongsRememberedIndexMaybe =
Maybe SongsRememberedIndex
type alias SongsRememberedMaybe =
Maybe SongsRemembered
type alias SongsTimeless =
List SongTimeless
type alias SongsTimelessIndex =
Int
type alias Time =
SongFieldString
type alias Timestamp =
SongFieldString
type alias Title =
SongFieldString
-- VIEW
type SongGroup
= Recent
| Remembered
type alias SongGroupLength =
Int
type alias SongsRecentOrRememberedIndex =
Int
| 35383 | {- Copyright (C) 2018 <NAME>.
All rights reserved.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-}
module SongType exposing
( Artist
, LikeOrCommentCount
, SongFieldString
, SongGroup(..)
, SongGroupLength
, SongRecent
, SongRecentBase
, SongRecentMaybe
, SongRecentOrRemembered
, SongRemembered
, SongRememberedMaybe
, SongTimeBase
, SongTimeExceptBase
, SongTimeless
, SongTimelessBase
, SongsRecent
, SongsRecentIndex
, SongsRecentOrRemembered
, SongsRecentOrRememberedIndex
, SongsRemembered
, SongsRememberedIndex
, SongsRememberedIndexList
, SongsRememberedIndexMaybe
, SongsRememberedMaybe
, SongsTimeless
, Time
, Timestamp
, Title
)
-- MODEL
type alias Artist =
SongFieldString
type alias LikeOrCommentCount =
Int
type alias SongFieldString =
String
type alias SongRecent =
--Keep order (for JSON decoding):
{ artist : Artist
, time : Time
, timestamp : Timestamp
, title : Title
}
type alias SongRecentBase a =
{ a
| artist : Artist
, time : Time
, timestamp : Timestamp
, title : Title
}
type alias SongRecentMaybe =
Maybe SongRecent
type alias SongRecentOrRemembered =
SongRemembered
type alias SongRemembered =
{ artist : Artist
, likeOrCommentCount : LikeOrCommentCount
, time : Time
, timestamp : Timestamp
, title : Title
}
type alias SongRememberedMaybe =
Maybe SongRemembered
type alias SongTimeBase a =
{ a
| time : Time
, timestamp : Timestamp
}
type alias SongTimeExceptBase a =
{ a
| artist : Artist
, likeOrCommentCount : LikeOrCommentCount
, title : Title
}
type alias SongTimeless =
{ artist : Artist
, title : Title
}
type alias SongTimelessBase a =
{ a
| artist : Artist
, title : Title
}
type alias SongsRecent =
List SongRecent
type alias SongsRecentIndex =
Int
type alias SongsRecentOrRemembered =
SongsRemembered
type alias SongsRemembered =
List SongRemembered
type alias SongsRememberedIndex =
Int
type alias SongsRememberedIndexList =
List SongsRememberedIndex
type alias SongsRememberedIndexMaybe =
Maybe SongsRememberedIndex
type alias SongsRememberedMaybe =
Maybe SongsRemembered
type alias SongsTimeless =
List SongTimeless
type alias SongsTimelessIndex =
Int
type alias Time =
SongFieldString
type alias Timestamp =
SongFieldString
type alias Title =
SongFieldString
-- VIEW
type SongGroup
= Recent
| Remembered
type alias SongGroupLength =
Int
type alias SongsRecentOrRememberedIndex =
Int
| true | {- Copyright (C) 2018 PI:NAME:<NAME>END_PI.
All rights reserved.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-}
module SongType exposing
( Artist
, LikeOrCommentCount
, SongFieldString
, SongGroup(..)
, SongGroupLength
, SongRecent
, SongRecentBase
, SongRecentMaybe
, SongRecentOrRemembered
, SongRemembered
, SongRememberedMaybe
, SongTimeBase
, SongTimeExceptBase
, SongTimeless
, SongTimelessBase
, SongsRecent
, SongsRecentIndex
, SongsRecentOrRemembered
, SongsRecentOrRememberedIndex
, SongsRemembered
, SongsRememberedIndex
, SongsRememberedIndexList
, SongsRememberedIndexMaybe
, SongsRememberedMaybe
, SongsTimeless
, Time
, Timestamp
, Title
)
-- MODEL
type alias Artist =
SongFieldString
type alias LikeOrCommentCount =
Int
type alias SongFieldString =
String
type alias SongRecent =
--Keep order (for JSON decoding):
{ artist : Artist
, time : Time
, timestamp : Timestamp
, title : Title
}
type alias SongRecentBase a =
{ a
| artist : Artist
, time : Time
, timestamp : Timestamp
, title : Title
}
type alias SongRecentMaybe =
Maybe SongRecent
type alias SongRecentOrRemembered =
SongRemembered
type alias SongRemembered =
{ artist : Artist
, likeOrCommentCount : LikeOrCommentCount
, time : Time
, timestamp : Timestamp
, title : Title
}
type alias SongRememberedMaybe =
Maybe SongRemembered
type alias SongTimeBase a =
{ a
| time : Time
, timestamp : Timestamp
}
type alias SongTimeExceptBase a =
{ a
| artist : Artist
, likeOrCommentCount : LikeOrCommentCount
, title : Title
}
type alias SongTimeless =
{ artist : Artist
, title : Title
}
type alias SongTimelessBase a =
{ a
| artist : Artist
, title : Title
}
type alias SongsRecent =
List SongRecent
type alias SongsRecentIndex =
Int
type alias SongsRecentOrRemembered =
SongsRemembered
type alias SongsRemembered =
List SongRemembered
type alias SongsRememberedIndex =
Int
type alias SongsRememberedIndexList =
List SongsRememberedIndex
type alias SongsRememberedIndexMaybe =
Maybe SongsRememberedIndex
type alias SongsRememberedMaybe =
Maybe SongsRemembered
type alias SongsTimeless =
List SongTimeless
type alias SongsTimelessIndex =
Int
type alias Time =
SongFieldString
type alias Timestamp =
SongFieldString
type alias Title =
SongFieldString
-- VIEW
type SongGroup
= Recent
| Remembered
type alias SongGroupLength =
Int
type alias SongsRecentOrRememberedIndex =
Int
| elm |
[
{
"context": "idBlocks =\n Chart.Blocks.series Dots.cross \"Alice\" alice\n { title = \"Total Population\"\n ",
"end": 5700,
"score": 0.9943365455,
"start": 5695,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ks =\n Chart.Blocks.series Dots.cross \"Alice\" alice\n { title = \"Total Population\"\n , st",
"end": 5707,
"score": 0.946244359,
"start": 5702,
"tag": "NAME",
"value": "alice"
},
{
"context": "examples._\n\n - **junk**: Gets its name from\n [Edward Tufte's concept of \"chart junk\"](https://en.wikipedia.o",
"end": 9818,
"score": 0.9932510257,
"start": 9806,
"tag": "NAME",
"value": "Edward Tufte"
}
] | src/BarChart.elm | terezka/elm-charts-alpha | 7 | module BarChart exposing
( view1, view2, view3
, view, Series, SeriesConfig, series
, Style, solid, bordered, alternate
, viewCustom, Config
)
{-|
## Table of contents
### Quick start
- [view1](#view1) for visualizing a single data series.
- [view2](#view2) for visualizing two data series.
- [view3](#view3) for visualizing three data series.
- [view](#view) for visualizing *any* amount of data series.
### Customizing everything
- [viewCustom](#viewCustom) for configuring any other aspect of the chart (axis, grid, etc.).</br>
# Quick start
@docs view1, view2, view3
# Customizing blocks
@docs view, Series, SeriesConfig, series
@docs Style, solid, bordered, alternate
# Customizing everything
@docs viewCustom, Config
-}
import Svg
import Svg.Attributes
import Color
import Chart.Axis.Unit
import Chart.Axis.Dependent
import Chart.Axis.Independent
import Chart.Block
import Chart.Colors
import Chart.Container
import Chart.Element
import Chart.Events
import Chart.Grid
import Chart.Junk
import Chart.Legends
import Chart.Orientation
import Chart.Pattern
import Internal.Axis
import Internal.Axis.Dependent
import Internal.Axis.Independent
import Internal.Axis.Intersection
import Internal.Axis.Range
import Internal.Block
import Internal.Chart
import Internal.Container
import Internal.Element
import Internal.Junk
import Internal.Pattern
import Internal.Orientation
import Internal.Point as Point
import Internal.Utils as Utils
import Internal.Coordinate as Coordinate
import Internal.Svg as Svg
-- VIEW
{-|
** Show a blocks chart **
type alias Facts =
{ country : String, population : Float }
chart : Html msg
chart =
Chart.Blocks.view1 .country .population
[ Facts "Denmark" 5748769
, Facts "Sweden" 10142686
, Facts "Norway" 5295619
]
-}
view1 : (data -> String) -> (data -> Float) -> List data -> Svg.Svg msg
view1 toInd toDep =
viewCustom (defaultConfig toInd)
[ series
{ title = "Serie 1"
, style = solid Chart.Colors.pink
, variable = toDep
, pattern = False
}
]
{-|
** Show a blocks chart with two series **
type alias Facts =
{ country : String
, population : Float
, women : Float
}
chart : Html msg
chart =
Chart.Blocks.view1 .country .population .women
[ Facts "Denmark" 5.7 2.9
, Facts "Sweden" 10.1 5.0
, Facts "Norway" 5.2 2.6
]
-}
view2 : (data -> String) -> (data -> Float) -> (data -> Float) -> List data -> Svg.Svg msg
view2 toInd toDep1 toDep2 =
viewCustom (defaultConfig toInd)
[ series
{ title = "Serie 1"
, style = solid Chart.Colors.blue
, variable = toDep1
, pattern = False
}
, series
{ title = "Serie 2"
, style = solid Chart.Colors.pink
, variable = toDep2
, pattern = False
}
]
{-|
** Show a blocks chart with three series **
type alias Facts =
{ country : String
, population : Float
, women : Float
, children : Float
}
chart : Html msg
chart =
Chart.Blocks.view1 .country .population .women .children
[ Facts "Denmark" 5.7 2.9 0.9
, Facts "Sweden" 10.1 5.0 2.0
, Facts "Norway" 5.2 2.6 0.8
]
-}
view3 : (data -> String) -> (data -> Float) -> (data -> Float) -> (data -> Float) -> List data -> Svg.Svg msg
view3 toInd toDep1 toDep2 toDep3 =
viewCustom (defaultConfig toInd)
[ series
{ title = "Serie 1"
, style = solid Chart.Colors.blue
, variable = toDep1
, pattern = False
}
, series
{ title = "Serie 2"
, style = solid Chart.Colors.pink
, variable = toDep2
, pattern = False
}
, series
{ title = "Serie 3"
, style = solid Chart.Colors.cyanLight
, variable = toDep3
, pattern = False
}
]
-- VIEW / ANY AMOUNT
{-|
** Show any amount of lines **
chart : Html msg
chart =
Chart.Blocks.view .label [ denmark, norway, sweden, iceland ] data
denmark : Chart.Blocks.Series Data
denmark =
Chart.Blocks.series
{ title = "Denmark"
, style = Chart.Blocks.bordered Colors.pinkLight Colors.pink
, variable = .denmark
, pattern = False
}
norway : Chart.Blocks.Series Data
norway =
Chart.Blocks.series
{ title = "Norway"
, style = Chart.Blocks.bordered Colors.blueLight Colors.blue
, variable = .norway
, pattern = False
}
sweden : Chart.Blocks.Series Data
sweden =
Chart.Blocks.series
{ title = "Sweden"
, style = Chart.Blocks.bordered Colors.cyanLight Colors.cyan
, variable = .sweden
, pattern = False
}
iceland : Chart.Blocks.Series Data
iceland =
Chart.Blocks.series
{ title = "Iceland"
, style = Chart.Blocks.bordered Colors.goldLight Colors.gold
, variable = .iceland
, pattern = False
}
-}
view : (data -> String) -> List (Series data) -> List data -> Svg.Svg msg
view toInd =
viewCustom (defaultConfig toInd)
{-| This type represents the configuration of a series of blocks.
-}
type alias Series data =
Internal.Block.Series data
{-| -}
type alias SeriesConfig data =
{ title : String
, style : Style data
, variable : data -> Float
, pattern : Bool
}
{-| This is the configuration of visual properties of
a series of blocks.
** Examples of customizations **
solidBlocks : Chart.Blocks.Series Human
solidBlocks =
Chart.Blocks.series Dots.cross "Alice" alice
{ title = "Total Population"
, style = Chart.Blocks.solid Colors.purple
, variable = .population
, pattern = False
}
stripedBlocks : Chart.Blocks.Series Human
stripedBlocks =
Chart.Blocks.series
{ title = "Expected Population"
, style = Chart.Blocks.solid Colors.purple
, variable = .expectedPopulation
, pattern = True -- This makes it striped!
}
-}
series : SeriesConfig data -> Series data
series =
Internal.Block.series
-- STYLE
{-| The style of a block.
-}
type alias Style data =
Internal.Block.Style data
{-| A solid block. Pass the color.
-}
solid : Color.Color -> Style data
solid =
Internal.Block.solid
{-| A block with a border. Pass the main color and the border color respectively.
-}
bordered : Color.Color -> Color.Color -> Style data
bordered =
Internal.Block.bordered
{-|
Change the style of the block based on the index and data.
blockStyle : Chart.Blocks.Style Data
blockStyle =
Chart.Blocks.alternate isNumberThree
(Chart.Blocks.solid Chart.Colors.pinkLight) -- shown when condition is false
(Chart.Blocks.solid Chart.Colors.pink) -- shown when condition is true
isNumberThree : Int -> Data -> Bool
isNumberThree index _ =
index == 3
isHovered : Model -> Int -> Data -> Bool
isHovered model index datum =
datum == model.hovered
This is nice to use with `Chart.Events.isSeries`, `Chart.Events.isDatum`,
and `Chart.Events.isExactly` when working with events. See `Chart.Events`
for more information and examples.
See `viewCustom` for all other customizations.
-}
alternate : (Int -> data -> Bool) -> Style data -> Style data -> Style data
alternate =
Internal.Block.alternate
-- VIEW / CUSTOM
{-| -}
type alias Config data msg =
{ independentAxis : Chart.Axis.Independent.Config data msg
, dependentAxis : Chart.Axis.Dependent.Config msg
, container : Chart.Container.Config msg
, orientation : Chart.Orientation.Config
, legends : Chart.Legends.Config msg
, events : Chart.Events.Config Chart.Element.Block data msg
, grid : Chart.Grid.Config
, block : Chart.Block.Config
, junk : Chart.Junk.Config Chart.Element.Block msg
, pattern : Chart.Pattern.Config
}
{-|
** Available customizations **
Use with `viewCustom`.
- **x**: Customizes your independent axis.</br>
_See [`Chart.Axis.Independent`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Axis-Independent) for more information and examples._
- **y**: Customizes your dependent axis.</br>
_See [`Chart.Axis.Dependent`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Axis-Dependent) for more information and examples._
- **container**: Customizes the container of your chart.</br>
_See [`Chart.Container`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Container) for more information and examples._
- **legends**: Customizes your chart's legends.</br>
_See [`Chart.Legends`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Legends) for more information and examples._
- **events**: Customizes your chart's events, allowing you to easily
make your chart interactive (adding tooltips, selection states etc.).</br>
_See [`Chart.Events`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Events) for more information and examples._
- **grid**: Customizes the style of your grid.</br>
_See [`Chart.Grid`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Grid) for more information and examples._
- **block**: Customizes your block width and corner radius.</br>
_See [`Chart.Block`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Block) for more information and examples._
- **pattern**: Customizes your blocks pattern.</br>
_See [`Chart.Pattern`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Pattern) for more information and examples._
- **junk**: Gets its name from
[Edward Tufte's concept of "chart junk"](https://en.wikipedia.org/wiki/Chartjunk).
Here you are finally allowed set your creativity loose and add whatever
SVG or HTML fun you can imagine.</br>
_See [`Chart.Junk`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Junk) for more information and examples._
** Example configuration **
A good start would be to copy it and play around with customizations
available for each property.
chartConfig : Config Info msg
chartConfig =
{ independentAxis = Chart.Axis.Independent.default "Country" .country
, dependentAxis = Chart.Axis.Dependent.default "GDP" Chart.Axis.Unit.dollars
, container = Chart.Container.default "blocks-chart" 700 400
, orientation = Chart.Orientation.default
, legends = Chart.Legends.default
, events = Chart.Events.default
, grid = Chart.Grid.default
, block = Chart.Block.default
, junk = Chart.Junk.default
, pattern = Chart.Pattern.default
}
-}
viewCustom : Config data msg -> List (Series data) -> List data -> Svg.Svg msg
viewCustom config block data =
let
-- Data / System
seriesProps = List.map Internal.Block.seriesProps block
countOfSeries = toFloat (List.length block)
countOfData = toFloat (List.length data)
width =
Utils.apply4 system config.block countOfSeries countOfData <|
Internal.Orientation.chooses config.orientation
{ horizontal = Internal.Block.width Coordinate.lengthY Coordinate.scaleDataY
, vertical = Internal.Block.width Coordinate.lengthX Coordinate.scaleDataX
}
system = toSystem config horizontalAxis verticalAxis countOfData block data
dataPoints = toDataPoints config system countOfSeries countOfData width block data
dataPointsAll = List.concat dataPoints
-- Axes
( horizontalAxis, verticalAxis ) =
Internal.Orientation.chooses config.orientation
{ horizontal =
( Internal.Axis.Dependent.toNormal config.dependentAxis data
, Internal.Axis.Independent.toNormal config.independentAxis data
)
, vertical =
( Internal.Axis.Independent.toNormal config.independentAxis data
, Internal.Axis.Dependent.toNormal config.dependentAxis data
)
}
-- View
viewSeries data_ =
Svg.g [ Svg.Attributes.class "chart__group" ] <|
List.map2 (Internal.Block.viewSeries system config.orientation config.block width) block data_
viewLegends =
{ system = system
, config = config.legends
, defaults = { width = 10, offsetY = 0 }
, legends = \width_ ->
let legend bar =
{ sample = Svg.square bar.pattern width_ (Internal.Block.borderRadius config.block) (Internal.Block.fill bar.style) (Internal.Block.border bar.style)
, label = bar.title
}
in List.map legend seriesProps
}
in
Internal.Chart.view
{ container = config.container
, events = config.events
, defs = Internal.Pattern.toDefs config.pattern
, grid = config.grid
, series = Svg.g [ Svg.Attributes.class "chart__groups" ] (List.map viewSeries dataPoints)
, intersection =
Internal.Orientation.chooses config.orientation
{ horizontal = Internal.Axis.Intersection.custom Internal.Axis.Intersection.towardsZero .min
, vertical = Internal.Axis.Intersection.custom .min Internal.Axis.Intersection.towardsZero
}
, horizontalAxis = horizontalAxis
, verticalAxis = verticalAxis
, legends = viewLegends
, trends = Svg.text ""
, junk =
Internal.Junk.getLayers
{ orientation = config.orientation
, independent = Internal.Axis.Independent.title config.independentAxis
, dependent = Internal.Axis.Dependent.title config.dependentAxis
, offsetOne = width / 2
, offsetMany = width * toFloat (List.length block) / 2
}
system
config.junk
, orientation = config.orientation
}
dataPointsAll
system
-- INTERNAL
toDataPoints : Config data msg -> Coordinate.System -> Float -> Float -> Float -> List (Series data) -> List data -> List (List (Point.Point Internal.Element.Block data))
toDataPoints config system countOfSeries countOfData width seriesAll data =
let
coordinates =
Internal.Orientation.chooses config.orientation
{ horizontal = Coordinate.horizontalPoint
, vertical = Coordinate.verticalPoint
}
eachBar dataIndex datum seriesIndex series_ =
let offset = toFloat seriesIndex - countOfSeries / 2 + 0.5
independent = toFloat dataIndex + 1 + offset * width
dependent = Internal.Block.variable series_ datum
color = Internal.Block.color series_
label = Internal.Block.label series_
coordinates_ = coordinates independent dependent
in
{ coordinates = coordinates_
, element =
{ element = Internal.Element.block
, seriesIndex = seriesIndex
, label = label
, color = color
, independent = Internal.Axis.Independent.label config.independentAxis datum
, dependent = Internal.Axis.Dependent.unit config.dependentAxis dependent
}
, source = datum
}
eachSeries dataIndex datum =
List.indexedMap (eachBar dataIndex datum) seriesAll
in
List.indexedMap eachSeries data
toSystem : Config data msg -> Internal.Axis.Config Float data msg -> Internal.Axis.Config Float data msg -> Float -> List (Series data) -> List data -> Coordinate.System
toSystem config xAxis yAxis countOfData seriesAll data =
let
container = Internal.Container.properties identity config.container
frame = Coordinate.frame container.margin container.size.width container.size.height
value data_ = List.map (\a -> Internal.Block.variable a data_) seriesAll
values = List.concatMap value data
dependentRange =
{ min = Coordinate.minimumOrZero identity values
, max = Coordinate.maximumOrZero identity values
}
independentRange =
{ min = 0.5
, max = countOfData + 0.5
}
( xRange, yRange ) =
Internal.Orientation.chooses config.orientation
{ horizontal = ( dependentRange, independentRange )
, vertical = ( independentRange, dependentRange )
}
system =
{ frame = frame
, x = xRange
, y = yRange
, xData = xRange
, yData = yRange
, id = container.id
}
in
{ system
| x = Internal.Axis.Range.applyX (Internal.Axis.range xAxis) system
, y = Internal.Axis.Range.applyY (Internal.Axis.range yAxis) system
}
-- INTERNAL / DEFAULTS
defaultConfig : (data -> String) -> Config data msg
defaultConfig label =
{ independentAxis = Chart.Axis.Independent.default "" label
, dependentAxis = Chart.Axis.Dependent.default "" Chart.Axis.Unit.none
, container = Chart.Container.default "bar-chart" 700 400
, orientation = Chart.Orientation.default
, legends = Chart.Legends.default
, events = Chart.Events.default
, grid = Chart.Grid.default
, block = Chart.Block.default
, junk = Chart.Junk.default
, pattern = Chart.Pattern.default
}
| 5020 | module BarChart exposing
( view1, view2, view3
, view, Series, SeriesConfig, series
, Style, solid, bordered, alternate
, viewCustom, Config
)
{-|
## Table of contents
### Quick start
- [view1](#view1) for visualizing a single data series.
- [view2](#view2) for visualizing two data series.
- [view3](#view3) for visualizing three data series.
- [view](#view) for visualizing *any* amount of data series.
### Customizing everything
- [viewCustom](#viewCustom) for configuring any other aspect of the chart (axis, grid, etc.).</br>
# Quick start
@docs view1, view2, view3
# Customizing blocks
@docs view, Series, SeriesConfig, series
@docs Style, solid, bordered, alternate
# Customizing everything
@docs viewCustom, Config
-}
import Svg
import Svg.Attributes
import Color
import Chart.Axis.Unit
import Chart.Axis.Dependent
import Chart.Axis.Independent
import Chart.Block
import Chart.Colors
import Chart.Container
import Chart.Element
import Chart.Events
import Chart.Grid
import Chart.Junk
import Chart.Legends
import Chart.Orientation
import Chart.Pattern
import Internal.Axis
import Internal.Axis.Dependent
import Internal.Axis.Independent
import Internal.Axis.Intersection
import Internal.Axis.Range
import Internal.Block
import Internal.Chart
import Internal.Container
import Internal.Element
import Internal.Junk
import Internal.Pattern
import Internal.Orientation
import Internal.Point as Point
import Internal.Utils as Utils
import Internal.Coordinate as Coordinate
import Internal.Svg as Svg
-- VIEW
{-|
** Show a blocks chart **
type alias Facts =
{ country : String, population : Float }
chart : Html msg
chart =
Chart.Blocks.view1 .country .population
[ Facts "Denmark" 5748769
, Facts "Sweden" 10142686
, Facts "Norway" 5295619
]
-}
view1 : (data -> String) -> (data -> Float) -> List data -> Svg.Svg msg
view1 toInd toDep =
viewCustom (defaultConfig toInd)
[ series
{ title = "Serie 1"
, style = solid Chart.Colors.pink
, variable = toDep
, pattern = False
}
]
{-|
** Show a blocks chart with two series **
type alias Facts =
{ country : String
, population : Float
, women : Float
}
chart : Html msg
chart =
Chart.Blocks.view1 .country .population .women
[ Facts "Denmark" 5.7 2.9
, Facts "Sweden" 10.1 5.0
, Facts "Norway" 5.2 2.6
]
-}
view2 : (data -> String) -> (data -> Float) -> (data -> Float) -> List data -> Svg.Svg msg
view2 toInd toDep1 toDep2 =
viewCustom (defaultConfig toInd)
[ series
{ title = "Serie 1"
, style = solid Chart.Colors.blue
, variable = toDep1
, pattern = False
}
, series
{ title = "Serie 2"
, style = solid Chart.Colors.pink
, variable = toDep2
, pattern = False
}
]
{-|
** Show a blocks chart with three series **
type alias Facts =
{ country : String
, population : Float
, women : Float
, children : Float
}
chart : Html msg
chart =
Chart.Blocks.view1 .country .population .women .children
[ Facts "Denmark" 5.7 2.9 0.9
, Facts "Sweden" 10.1 5.0 2.0
, Facts "Norway" 5.2 2.6 0.8
]
-}
view3 : (data -> String) -> (data -> Float) -> (data -> Float) -> (data -> Float) -> List data -> Svg.Svg msg
view3 toInd toDep1 toDep2 toDep3 =
viewCustom (defaultConfig toInd)
[ series
{ title = "Serie 1"
, style = solid Chart.Colors.blue
, variable = toDep1
, pattern = False
}
, series
{ title = "Serie 2"
, style = solid Chart.Colors.pink
, variable = toDep2
, pattern = False
}
, series
{ title = "Serie 3"
, style = solid Chart.Colors.cyanLight
, variable = toDep3
, pattern = False
}
]
-- VIEW / ANY AMOUNT
{-|
** Show any amount of lines **
chart : Html msg
chart =
Chart.Blocks.view .label [ denmark, norway, sweden, iceland ] data
denmark : Chart.Blocks.Series Data
denmark =
Chart.Blocks.series
{ title = "Denmark"
, style = Chart.Blocks.bordered Colors.pinkLight Colors.pink
, variable = .denmark
, pattern = False
}
norway : Chart.Blocks.Series Data
norway =
Chart.Blocks.series
{ title = "Norway"
, style = Chart.Blocks.bordered Colors.blueLight Colors.blue
, variable = .norway
, pattern = False
}
sweden : Chart.Blocks.Series Data
sweden =
Chart.Blocks.series
{ title = "Sweden"
, style = Chart.Blocks.bordered Colors.cyanLight Colors.cyan
, variable = .sweden
, pattern = False
}
iceland : Chart.Blocks.Series Data
iceland =
Chart.Blocks.series
{ title = "Iceland"
, style = Chart.Blocks.bordered Colors.goldLight Colors.gold
, variable = .iceland
, pattern = False
}
-}
view : (data -> String) -> List (Series data) -> List data -> Svg.Svg msg
view toInd =
viewCustom (defaultConfig toInd)
{-| This type represents the configuration of a series of blocks.
-}
type alias Series data =
Internal.Block.Series data
{-| -}
type alias SeriesConfig data =
{ title : String
, style : Style data
, variable : data -> Float
, pattern : Bool
}
{-| This is the configuration of visual properties of
a series of blocks.
** Examples of customizations **
solidBlocks : Chart.Blocks.Series Human
solidBlocks =
Chart.Blocks.series Dots.cross "<NAME>" <NAME>
{ title = "Total Population"
, style = Chart.Blocks.solid Colors.purple
, variable = .population
, pattern = False
}
stripedBlocks : Chart.Blocks.Series Human
stripedBlocks =
Chart.Blocks.series
{ title = "Expected Population"
, style = Chart.Blocks.solid Colors.purple
, variable = .expectedPopulation
, pattern = True -- This makes it striped!
}
-}
series : SeriesConfig data -> Series data
series =
Internal.Block.series
-- STYLE
{-| The style of a block.
-}
type alias Style data =
Internal.Block.Style data
{-| A solid block. Pass the color.
-}
solid : Color.Color -> Style data
solid =
Internal.Block.solid
{-| A block with a border. Pass the main color and the border color respectively.
-}
bordered : Color.Color -> Color.Color -> Style data
bordered =
Internal.Block.bordered
{-|
Change the style of the block based on the index and data.
blockStyle : Chart.Blocks.Style Data
blockStyle =
Chart.Blocks.alternate isNumberThree
(Chart.Blocks.solid Chart.Colors.pinkLight) -- shown when condition is false
(Chart.Blocks.solid Chart.Colors.pink) -- shown when condition is true
isNumberThree : Int -> Data -> Bool
isNumberThree index _ =
index == 3
isHovered : Model -> Int -> Data -> Bool
isHovered model index datum =
datum == model.hovered
This is nice to use with `Chart.Events.isSeries`, `Chart.Events.isDatum`,
and `Chart.Events.isExactly` when working with events. See `Chart.Events`
for more information and examples.
See `viewCustom` for all other customizations.
-}
alternate : (Int -> data -> Bool) -> Style data -> Style data -> Style data
alternate =
Internal.Block.alternate
-- VIEW / CUSTOM
{-| -}
type alias Config data msg =
{ independentAxis : Chart.Axis.Independent.Config data msg
, dependentAxis : Chart.Axis.Dependent.Config msg
, container : Chart.Container.Config msg
, orientation : Chart.Orientation.Config
, legends : Chart.Legends.Config msg
, events : Chart.Events.Config Chart.Element.Block data msg
, grid : Chart.Grid.Config
, block : Chart.Block.Config
, junk : Chart.Junk.Config Chart.Element.Block msg
, pattern : Chart.Pattern.Config
}
{-|
** Available customizations **
Use with `viewCustom`.
- **x**: Customizes your independent axis.</br>
_See [`Chart.Axis.Independent`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Axis-Independent) for more information and examples._
- **y**: Customizes your dependent axis.</br>
_See [`Chart.Axis.Dependent`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Axis-Dependent) for more information and examples._
- **container**: Customizes the container of your chart.</br>
_See [`Chart.Container`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Container) for more information and examples._
- **legends**: Customizes your chart's legends.</br>
_See [`Chart.Legends`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Legends) for more information and examples._
- **events**: Customizes your chart's events, allowing you to easily
make your chart interactive (adding tooltips, selection states etc.).</br>
_See [`Chart.Events`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Events) for more information and examples._
- **grid**: Customizes the style of your grid.</br>
_See [`Chart.Grid`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Grid) for more information and examples._
- **block**: Customizes your block width and corner radius.</br>
_See [`Chart.Block`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Block) for more information and examples._
- **pattern**: Customizes your blocks pattern.</br>
_See [`Chart.Pattern`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Pattern) for more information and examples._
- **junk**: Gets its name from
[<NAME>'s concept of "chart junk"](https://en.wikipedia.org/wiki/Chartjunk).
Here you are finally allowed set your creativity loose and add whatever
SVG or HTML fun you can imagine.</br>
_See [`Chart.Junk`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Junk) for more information and examples._
** Example configuration **
A good start would be to copy it and play around with customizations
available for each property.
chartConfig : Config Info msg
chartConfig =
{ independentAxis = Chart.Axis.Independent.default "Country" .country
, dependentAxis = Chart.Axis.Dependent.default "GDP" Chart.Axis.Unit.dollars
, container = Chart.Container.default "blocks-chart" 700 400
, orientation = Chart.Orientation.default
, legends = Chart.Legends.default
, events = Chart.Events.default
, grid = Chart.Grid.default
, block = Chart.Block.default
, junk = Chart.Junk.default
, pattern = Chart.Pattern.default
}
-}
viewCustom : Config data msg -> List (Series data) -> List data -> Svg.Svg msg
viewCustom config block data =
let
-- Data / System
seriesProps = List.map Internal.Block.seriesProps block
countOfSeries = toFloat (List.length block)
countOfData = toFloat (List.length data)
width =
Utils.apply4 system config.block countOfSeries countOfData <|
Internal.Orientation.chooses config.orientation
{ horizontal = Internal.Block.width Coordinate.lengthY Coordinate.scaleDataY
, vertical = Internal.Block.width Coordinate.lengthX Coordinate.scaleDataX
}
system = toSystem config horizontalAxis verticalAxis countOfData block data
dataPoints = toDataPoints config system countOfSeries countOfData width block data
dataPointsAll = List.concat dataPoints
-- Axes
( horizontalAxis, verticalAxis ) =
Internal.Orientation.chooses config.orientation
{ horizontal =
( Internal.Axis.Dependent.toNormal config.dependentAxis data
, Internal.Axis.Independent.toNormal config.independentAxis data
)
, vertical =
( Internal.Axis.Independent.toNormal config.independentAxis data
, Internal.Axis.Dependent.toNormal config.dependentAxis data
)
}
-- View
viewSeries data_ =
Svg.g [ Svg.Attributes.class "chart__group" ] <|
List.map2 (Internal.Block.viewSeries system config.orientation config.block width) block data_
viewLegends =
{ system = system
, config = config.legends
, defaults = { width = 10, offsetY = 0 }
, legends = \width_ ->
let legend bar =
{ sample = Svg.square bar.pattern width_ (Internal.Block.borderRadius config.block) (Internal.Block.fill bar.style) (Internal.Block.border bar.style)
, label = bar.title
}
in List.map legend seriesProps
}
in
Internal.Chart.view
{ container = config.container
, events = config.events
, defs = Internal.Pattern.toDefs config.pattern
, grid = config.grid
, series = Svg.g [ Svg.Attributes.class "chart__groups" ] (List.map viewSeries dataPoints)
, intersection =
Internal.Orientation.chooses config.orientation
{ horizontal = Internal.Axis.Intersection.custom Internal.Axis.Intersection.towardsZero .min
, vertical = Internal.Axis.Intersection.custom .min Internal.Axis.Intersection.towardsZero
}
, horizontalAxis = horizontalAxis
, verticalAxis = verticalAxis
, legends = viewLegends
, trends = Svg.text ""
, junk =
Internal.Junk.getLayers
{ orientation = config.orientation
, independent = Internal.Axis.Independent.title config.independentAxis
, dependent = Internal.Axis.Dependent.title config.dependentAxis
, offsetOne = width / 2
, offsetMany = width * toFloat (List.length block) / 2
}
system
config.junk
, orientation = config.orientation
}
dataPointsAll
system
-- INTERNAL
toDataPoints : Config data msg -> Coordinate.System -> Float -> Float -> Float -> List (Series data) -> List data -> List (List (Point.Point Internal.Element.Block data))
toDataPoints config system countOfSeries countOfData width seriesAll data =
let
coordinates =
Internal.Orientation.chooses config.orientation
{ horizontal = Coordinate.horizontalPoint
, vertical = Coordinate.verticalPoint
}
eachBar dataIndex datum seriesIndex series_ =
let offset = toFloat seriesIndex - countOfSeries / 2 + 0.5
independent = toFloat dataIndex + 1 + offset * width
dependent = Internal.Block.variable series_ datum
color = Internal.Block.color series_
label = Internal.Block.label series_
coordinates_ = coordinates independent dependent
in
{ coordinates = coordinates_
, element =
{ element = Internal.Element.block
, seriesIndex = seriesIndex
, label = label
, color = color
, independent = Internal.Axis.Independent.label config.independentAxis datum
, dependent = Internal.Axis.Dependent.unit config.dependentAxis dependent
}
, source = datum
}
eachSeries dataIndex datum =
List.indexedMap (eachBar dataIndex datum) seriesAll
in
List.indexedMap eachSeries data
toSystem : Config data msg -> Internal.Axis.Config Float data msg -> Internal.Axis.Config Float data msg -> Float -> List (Series data) -> List data -> Coordinate.System
toSystem config xAxis yAxis countOfData seriesAll data =
let
container = Internal.Container.properties identity config.container
frame = Coordinate.frame container.margin container.size.width container.size.height
value data_ = List.map (\a -> Internal.Block.variable a data_) seriesAll
values = List.concatMap value data
dependentRange =
{ min = Coordinate.minimumOrZero identity values
, max = Coordinate.maximumOrZero identity values
}
independentRange =
{ min = 0.5
, max = countOfData + 0.5
}
( xRange, yRange ) =
Internal.Orientation.chooses config.orientation
{ horizontal = ( dependentRange, independentRange )
, vertical = ( independentRange, dependentRange )
}
system =
{ frame = frame
, x = xRange
, y = yRange
, xData = xRange
, yData = yRange
, id = container.id
}
in
{ system
| x = Internal.Axis.Range.applyX (Internal.Axis.range xAxis) system
, y = Internal.Axis.Range.applyY (Internal.Axis.range yAxis) system
}
-- INTERNAL / DEFAULTS
defaultConfig : (data -> String) -> Config data msg
defaultConfig label =
{ independentAxis = Chart.Axis.Independent.default "" label
, dependentAxis = Chart.Axis.Dependent.default "" Chart.Axis.Unit.none
, container = Chart.Container.default "bar-chart" 700 400
, orientation = Chart.Orientation.default
, legends = Chart.Legends.default
, events = Chart.Events.default
, grid = Chart.Grid.default
, block = Chart.Block.default
, junk = Chart.Junk.default
, pattern = Chart.Pattern.default
}
| true | module BarChart exposing
( view1, view2, view3
, view, Series, SeriesConfig, series
, Style, solid, bordered, alternate
, viewCustom, Config
)
{-|
## Table of contents
### Quick start
- [view1](#view1) for visualizing a single data series.
- [view2](#view2) for visualizing two data series.
- [view3](#view3) for visualizing three data series.
- [view](#view) for visualizing *any* amount of data series.
### Customizing everything
- [viewCustom](#viewCustom) for configuring any other aspect of the chart (axis, grid, etc.).</br>
# Quick start
@docs view1, view2, view3
# Customizing blocks
@docs view, Series, SeriesConfig, series
@docs Style, solid, bordered, alternate
# Customizing everything
@docs viewCustom, Config
-}
import Svg
import Svg.Attributes
import Color
import Chart.Axis.Unit
import Chart.Axis.Dependent
import Chart.Axis.Independent
import Chart.Block
import Chart.Colors
import Chart.Container
import Chart.Element
import Chart.Events
import Chart.Grid
import Chart.Junk
import Chart.Legends
import Chart.Orientation
import Chart.Pattern
import Internal.Axis
import Internal.Axis.Dependent
import Internal.Axis.Independent
import Internal.Axis.Intersection
import Internal.Axis.Range
import Internal.Block
import Internal.Chart
import Internal.Container
import Internal.Element
import Internal.Junk
import Internal.Pattern
import Internal.Orientation
import Internal.Point as Point
import Internal.Utils as Utils
import Internal.Coordinate as Coordinate
import Internal.Svg as Svg
-- VIEW
{-|
** Show a blocks chart **
type alias Facts =
{ country : String, population : Float }
chart : Html msg
chart =
Chart.Blocks.view1 .country .population
[ Facts "Denmark" 5748769
, Facts "Sweden" 10142686
, Facts "Norway" 5295619
]
-}
view1 : (data -> String) -> (data -> Float) -> List data -> Svg.Svg msg
view1 toInd toDep =
viewCustom (defaultConfig toInd)
[ series
{ title = "Serie 1"
, style = solid Chart.Colors.pink
, variable = toDep
, pattern = False
}
]
{-|
** Show a blocks chart with two series **
type alias Facts =
{ country : String
, population : Float
, women : Float
}
chart : Html msg
chart =
Chart.Blocks.view1 .country .population .women
[ Facts "Denmark" 5.7 2.9
, Facts "Sweden" 10.1 5.0
, Facts "Norway" 5.2 2.6
]
-}
view2 : (data -> String) -> (data -> Float) -> (data -> Float) -> List data -> Svg.Svg msg
view2 toInd toDep1 toDep2 =
viewCustom (defaultConfig toInd)
[ series
{ title = "Serie 1"
, style = solid Chart.Colors.blue
, variable = toDep1
, pattern = False
}
, series
{ title = "Serie 2"
, style = solid Chart.Colors.pink
, variable = toDep2
, pattern = False
}
]
{-|
** Show a blocks chart with three series **
type alias Facts =
{ country : String
, population : Float
, women : Float
, children : Float
}
chart : Html msg
chart =
Chart.Blocks.view1 .country .population .women .children
[ Facts "Denmark" 5.7 2.9 0.9
, Facts "Sweden" 10.1 5.0 2.0
, Facts "Norway" 5.2 2.6 0.8
]
-}
view3 : (data -> String) -> (data -> Float) -> (data -> Float) -> (data -> Float) -> List data -> Svg.Svg msg
view3 toInd toDep1 toDep2 toDep3 =
viewCustom (defaultConfig toInd)
[ series
{ title = "Serie 1"
, style = solid Chart.Colors.blue
, variable = toDep1
, pattern = False
}
, series
{ title = "Serie 2"
, style = solid Chart.Colors.pink
, variable = toDep2
, pattern = False
}
, series
{ title = "Serie 3"
, style = solid Chart.Colors.cyanLight
, variable = toDep3
, pattern = False
}
]
-- VIEW / ANY AMOUNT
{-|
** Show any amount of lines **
chart : Html msg
chart =
Chart.Blocks.view .label [ denmark, norway, sweden, iceland ] data
denmark : Chart.Blocks.Series Data
denmark =
Chart.Blocks.series
{ title = "Denmark"
, style = Chart.Blocks.bordered Colors.pinkLight Colors.pink
, variable = .denmark
, pattern = False
}
norway : Chart.Blocks.Series Data
norway =
Chart.Blocks.series
{ title = "Norway"
, style = Chart.Blocks.bordered Colors.blueLight Colors.blue
, variable = .norway
, pattern = False
}
sweden : Chart.Blocks.Series Data
sweden =
Chart.Blocks.series
{ title = "Sweden"
, style = Chart.Blocks.bordered Colors.cyanLight Colors.cyan
, variable = .sweden
, pattern = False
}
iceland : Chart.Blocks.Series Data
iceland =
Chart.Blocks.series
{ title = "Iceland"
, style = Chart.Blocks.bordered Colors.goldLight Colors.gold
, variable = .iceland
, pattern = False
}
-}
view : (data -> String) -> List (Series data) -> List data -> Svg.Svg msg
view toInd =
viewCustom (defaultConfig toInd)
{-| This type represents the configuration of a series of blocks.
-}
type alias Series data =
Internal.Block.Series data
{-| -}
type alias SeriesConfig data =
{ title : String
, style : Style data
, variable : data -> Float
, pattern : Bool
}
{-| This is the configuration of visual properties of
a series of blocks.
** Examples of customizations **
solidBlocks : Chart.Blocks.Series Human
solidBlocks =
Chart.Blocks.series Dots.cross "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI
{ title = "Total Population"
, style = Chart.Blocks.solid Colors.purple
, variable = .population
, pattern = False
}
stripedBlocks : Chart.Blocks.Series Human
stripedBlocks =
Chart.Blocks.series
{ title = "Expected Population"
, style = Chart.Blocks.solid Colors.purple
, variable = .expectedPopulation
, pattern = True -- This makes it striped!
}
-}
series : SeriesConfig data -> Series data
series =
Internal.Block.series
-- STYLE
{-| The style of a block.
-}
type alias Style data =
Internal.Block.Style data
{-| A solid block. Pass the color.
-}
solid : Color.Color -> Style data
solid =
Internal.Block.solid
{-| A block with a border. Pass the main color and the border color respectively.
-}
bordered : Color.Color -> Color.Color -> Style data
bordered =
Internal.Block.bordered
{-|
Change the style of the block based on the index and data.
blockStyle : Chart.Blocks.Style Data
blockStyle =
Chart.Blocks.alternate isNumberThree
(Chart.Blocks.solid Chart.Colors.pinkLight) -- shown when condition is false
(Chart.Blocks.solid Chart.Colors.pink) -- shown when condition is true
isNumberThree : Int -> Data -> Bool
isNumberThree index _ =
index == 3
isHovered : Model -> Int -> Data -> Bool
isHovered model index datum =
datum == model.hovered
This is nice to use with `Chart.Events.isSeries`, `Chart.Events.isDatum`,
and `Chart.Events.isExactly` when working with events. See `Chart.Events`
for more information and examples.
See `viewCustom` for all other customizations.
-}
alternate : (Int -> data -> Bool) -> Style data -> Style data -> Style data
alternate =
Internal.Block.alternate
-- VIEW / CUSTOM
{-| -}
type alias Config data msg =
{ independentAxis : Chart.Axis.Independent.Config data msg
, dependentAxis : Chart.Axis.Dependent.Config msg
, container : Chart.Container.Config msg
, orientation : Chart.Orientation.Config
, legends : Chart.Legends.Config msg
, events : Chart.Events.Config Chart.Element.Block data msg
, grid : Chart.Grid.Config
, block : Chart.Block.Config
, junk : Chart.Junk.Config Chart.Element.Block msg
, pattern : Chart.Pattern.Config
}
{-|
** Available customizations **
Use with `viewCustom`.
- **x**: Customizes your independent axis.</br>
_See [`Chart.Axis.Independent`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Axis-Independent) for more information and examples._
- **y**: Customizes your dependent axis.</br>
_See [`Chart.Axis.Dependent`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Axis-Dependent) for more information and examples._
- **container**: Customizes the container of your chart.</br>
_See [`Chart.Container`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Container) for more information and examples._
- **legends**: Customizes your chart's legends.</br>
_See [`Chart.Legends`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Legends) for more information and examples._
- **events**: Customizes your chart's events, allowing you to easily
make your chart interactive (adding tooltips, selection states etc.).</br>
_See [`Chart.Events`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Events) for more information and examples._
- **grid**: Customizes the style of your grid.</br>
_See [`Chart.Grid`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Grid) for more information and examples._
- **block**: Customizes your block width and corner radius.</br>
_See [`Chart.Block`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Block) for more information and examples._
- **pattern**: Customizes your blocks pattern.</br>
_See [`Chart.Pattern`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Pattern) for more information and examples._
- **junk**: Gets its name from
[PI:NAME:<NAME>END_PI's concept of "chart junk"](https://en.wikipedia.org/wiki/Chartjunk).
Here you are finally allowed set your creativity loose and add whatever
SVG or HTML fun you can imagine.</br>
_See [`Chart.Junk`](http://package.elm-lang.org/packages/terezka/line-charts/latest/Chart-Junk) for more information and examples._
** Example configuration **
A good start would be to copy it and play around with customizations
available for each property.
chartConfig : Config Info msg
chartConfig =
{ independentAxis = Chart.Axis.Independent.default "Country" .country
, dependentAxis = Chart.Axis.Dependent.default "GDP" Chart.Axis.Unit.dollars
, container = Chart.Container.default "blocks-chart" 700 400
, orientation = Chart.Orientation.default
, legends = Chart.Legends.default
, events = Chart.Events.default
, grid = Chart.Grid.default
, block = Chart.Block.default
, junk = Chart.Junk.default
, pattern = Chart.Pattern.default
}
-}
viewCustom : Config data msg -> List (Series data) -> List data -> Svg.Svg msg
viewCustom config block data =
let
-- Data / System
seriesProps = List.map Internal.Block.seriesProps block
countOfSeries = toFloat (List.length block)
countOfData = toFloat (List.length data)
width =
Utils.apply4 system config.block countOfSeries countOfData <|
Internal.Orientation.chooses config.orientation
{ horizontal = Internal.Block.width Coordinate.lengthY Coordinate.scaleDataY
, vertical = Internal.Block.width Coordinate.lengthX Coordinate.scaleDataX
}
system = toSystem config horizontalAxis verticalAxis countOfData block data
dataPoints = toDataPoints config system countOfSeries countOfData width block data
dataPointsAll = List.concat dataPoints
-- Axes
( horizontalAxis, verticalAxis ) =
Internal.Orientation.chooses config.orientation
{ horizontal =
( Internal.Axis.Dependent.toNormal config.dependentAxis data
, Internal.Axis.Independent.toNormal config.independentAxis data
)
, vertical =
( Internal.Axis.Independent.toNormal config.independentAxis data
, Internal.Axis.Dependent.toNormal config.dependentAxis data
)
}
-- View
viewSeries data_ =
Svg.g [ Svg.Attributes.class "chart__group" ] <|
List.map2 (Internal.Block.viewSeries system config.orientation config.block width) block data_
viewLegends =
{ system = system
, config = config.legends
, defaults = { width = 10, offsetY = 0 }
, legends = \width_ ->
let legend bar =
{ sample = Svg.square bar.pattern width_ (Internal.Block.borderRadius config.block) (Internal.Block.fill bar.style) (Internal.Block.border bar.style)
, label = bar.title
}
in List.map legend seriesProps
}
in
Internal.Chart.view
{ container = config.container
, events = config.events
, defs = Internal.Pattern.toDefs config.pattern
, grid = config.grid
, series = Svg.g [ Svg.Attributes.class "chart__groups" ] (List.map viewSeries dataPoints)
, intersection =
Internal.Orientation.chooses config.orientation
{ horizontal = Internal.Axis.Intersection.custom Internal.Axis.Intersection.towardsZero .min
, vertical = Internal.Axis.Intersection.custom .min Internal.Axis.Intersection.towardsZero
}
, horizontalAxis = horizontalAxis
, verticalAxis = verticalAxis
, legends = viewLegends
, trends = Svg.text ""
, junk =
Internal.Junk.getLayers
{ orientation = config.orientation
, independent = Internal.Axis.Independent.title config.independentAxis
, dependent = Internal.Axis.Dependent.title config.dependentAxis
, offsetOne = width / 2
, offsetMany = width * toFloat (List.length block) / 2
}
system
config.junk
, orientation = config.orientation
}
dataPointsAll
system
-- INTERNAL
toDataPoints : Config data msg -> Coordinate.System -> Float -> Float -> Float -> List (Series data) -> List data -> List (List (Point.Point Internal.Element.Block data))
toDataPoints config system countOfSeries countOfData width seriesAll data =
let
coordinates =
Internal.Orientation.chooses config.orientation
{ horizontal = Coordinate.horizontalPoint
, vertical = Coordinate.verticalPoint
}
eachBar dataIndex datum seriesIndex series_ =
let offset = toFloat seriesIndex - countOfSeries / 2 + 0.5
independent = toFloat dataIndex + 1 + offset * width
dependent = Internal.Block.variable series_ datum
color = Internal.Block.color series_
label = Internal.Block.label series_
coordinates_ = coordinates independent dependent
in
{ coordinates = coordinates_
, element =
{ element = Internal.Element.block
, seriesIndex = seriesIndex
, label = label
, color = color
, independent = Internal.Axis.Independent.label config.independentAxis datum
, dependent = Internal.Axis.Dependent.unit config.dependentAxis dependent
}
, source = datum
}
eachSeries dataIndex datum =
List.indexedMap (eachBar dataIndex datum) seriesAll
in
List.indexedMap eachSeries data
toSystem : Config data msg -> Internal.Axis.Config Float data msg -> Internal.Axis.Config Float data msg -> Float -> List (Series data) -> List data -> Coordinate.System
toSystem config xAxis yAxis countOfData seriesAll data =
let
container = Internal.Container.properties identity config.container
frame = Coordinate.frame container.margin container.size.width container.size.height
value data_ = List.map (\a -> Internal.Block.variable a data_) seriesAll
values = List.concatMap value data
dependentRange =
{ min = Coordinate.minimumOrZero identity values
, max = Coordinate.maximumOrZero identity values
}
independentRange =
{ min = 0.5
, max = countOfData + 0.5
}
( xRange, yRange ) =
Internal.Orientation.chooses config.orientation
{ horizontal = ( dependentRange, independentRange )
, vertical = ( independentRange, dependentRange )
}
system =
{ frame = frame
, x = xRange
, y = yRange
, xData = xRange
, yData = yRange
, id = container.id
}
in
{ system
| x = Internal.Axis.Range.applyX (Internal.Axis.range xAxis) system
, y = Internal.Axis.Range.applyY (Internal.Axis.range yAxis) system
}
-- INTERNAL / DEFAULTS
defaultConfig : (data -> String) -> Config data msg
defaultConfig label =
{ independentAxis = Chart.Axis.Independent.default "" label
, dependentAxis = Chart.Axis.Dependent.default "" Chart.Axis.Unit.none
, container = Chart.Container.default "bar-chart" 700 400
, orientation = Chart.Orientation.default
, legends = Chart.Legends.default
, events = Chart.Events.default
, grid = Chart.Grid.default
, block = Chart.Block.default
, junk = Chart.Junk.default
, pattern = Chart.Pattern.default
}
| elm |
[
{
"context": "> Person\naverage id =\n { id = id\n , name = \"Joe\"\n , age = 35\n , job = Just (Job.train Carpe",
"end": 1067,
"score": 0.9997065663,
"start": 1064,
"tag": "NAME",
"value": "Joe"
},
{
"context": " : Generator String\ngenName =\n Random.uniform \"Alexandria\" [ \"Bernard\", \"Marquita\", \"Noam\", \"Karl\" ]\n\n\ngenA",
"end": 4102,
"score": 0.9585234523,
"start": 4092,
"tag": "NAME",
"value": "Alexandria"
},
{
"context": "ring\ngenName =\n Random.uniform \"Alexandria\" [ \"Bernard\", \"Marquita\", \"Noam\", \"Karl\" ]\n\n\ngenAge : Generat",
"end": 4114,
"score": 0.9996845126,
"start": 4107,
"tag": "NAME",
"value": "Bernard"
},
{
"context": "e =\n Random.uniform \"Alexandria\" [ \"Bernard\", \"Marquita\", \"Noam\", \"Karl\" ]\n\n\ngenAge : Generator Int\ngenAg",
"end": 4126,
"score": 0.9992558956,
"start": 4118,
"tag": "NAME",
"value": "Marquita"
},
{
"context": "om.uniform \"Alexandria\" [ \"Bernard\", \"Marquita\", \"Noam\", \"Karl\" ]\n\n\ngenAge : Generator Int\ngenAge =\n ",
"end": 4134,
"score": 0.9997467995,
"start": 4130,
"tag": "NAME",
"value": "Noam"
},
{
"context": "rm \"Alexandria\" [ \"Bernard\", \"Marquita\", \"Noam\", \"Karl\" ]\n\n\ngenAge : Generator Int\ngenAge =\n Random.i",
"end": 4142,
"score": 0.9997212291,
"start": 4138,
"tag": "NAME",
"value": "Karl"
}
] | src/Person.elm | thebritican/leader-game | 2 | module Person exposing (Interest, Person, average, canGoToCollege, generate, housingScore, isQualified, wantsTertiaryEducation)
import Housing exposing (Housing, Location(..))
import Job exposing (Job, Title(..))
import Random exposing (Generator)
import Random.Extra as Random exposing (andMap)
type Interest
= Medical
| Engineering
| SocialWork
| Teaching
| Trade
| Unknown
type TertiaryQualification
= TradeDegree
| EngineeringDegree
| SocialWorkDegree
| MedicalDegree
| TeachingDegree
type alias Person =
{ id : Int
, name : String
, age : Int
, job : Maybe Job
, hasPrimaryEducation : Bool
, hasSecondaryEducation : Bool
, tertiaryQualifications : List TertiaryQualification
-- wants
, interest : Interest
, wantsLivingRoom : Bool
, wantsFlexRoom : Bool
-- needs
, prescriptionsNeeded : Int
, surgeriesNeeded : Int
, needsHospitalization : Bool
, house : Maybe Housing
}
average : Int -> Person
average id =
{ id = id
, name = "Joe"
, age = 35
, job = Just (Job.train Carpenter)
, hasPrimaryEducation = True
, hasSecondaryEducation = True
, tertiaryQualifications = [ TradeDegree ]
-- wants
, interest = Trade
, wantsLivingRoom = True
, wantsFlexRoom = False
-- needs
, prescriptionsNeeded = 1
, surgeriesNeeded = 0
, needsHospitalization = False
, house = Nothing
}
-- QUERY
housingScore : Person -> Float
housingScore person =
case person.house of
Just house ->
Housing.score house
Nothing ->
0
wantsTertiaryEducation : Person -> Bool
wantsTertiaryEducation person =
not <|
case person.interest of
Medical ->
List.member MedicalDegree person.tertiaryQualifications
Engineering ->
List.member EngineeringDegree person.tertiaryQualifications
SocialWork ->
List.member SocialWorkDegree person.tertiaryQualifications
Teaching ->
List.member TeachingDegree person.tertiaryQualifications
Trade ->
List.member TradeDegree person.tertiaryQualifications
Unknown ->
True
canGoToCollege : Person -> Bool
canGoToCollege person =
person.job == Nothing && person.hasPrimaryEducation && person.hasSecondaryEducation && wantsTertiaryEducation person
isQualified : Job.Title -> Person -> Bool
isQualified title person =
case title of
Farmer ->
person.hasSecondaryEducation
Doctor ->
List.member MedicalDegree person.tertiaryQualifications
Nurse ->
List.member MedicalDegree person.tertiaryQualifications
CivilEngineer ->
List.member EngineeringDegree person.tertiaryQualifications
Programmer ->
List.member EngineeringDegree person.tertiaryQualifications
SocialWorker ->
List.member SocialWorkDegree person.tertiaryQualifications
Teacher ->
List.member TeachingDegree person.tertiaryQualifications
Professor ->
List.member TeachingDegree person.tertiaryQualifications
Carpenter ->
List.member TradeDegree person.tertiaryQualifications
Electrician ->
List.member TradeDegree person.tertiaryQualifications
generate : Generator Person
generate =
Random.map Person genId
|> andMap genName
|> andMap genAge
|> andMap genJob
|> andMap genPrimaryEducation
|> andMap genSecondaryEducation
|> andMap genTertiaryEducation
|> andMap genInterest
|> andMap genWantsLivingRoom
|> andMap genWantsFlexRoom
|> andMap genPrescriptionsNeeded
|> andMap genSurgeriesNeeded
|> andMap genNeedsHospitalization
|> andMap genHousing
genId : Generator Int
genId =
Random.int Random.minInt Random.maxInt
genName : Generator String
genName =
Random.uniform "Alexandria" [ "Bernard", "Marquita", "Noam", "Karl" ]
genAge : Generator Int
genAge =
Random.int 0 100
genJob : Generator (Maybe Job)
genJob =
Random.map2
(\n job ->
if n < 10 then
Nothing
else
Just job
)
(Random.int 1 100)
Job.generate
genPrimaryEducation : Generator Bool
genPrimaryEducation =
Random.map (\n -> n < 90) (Random.int 1 100)
genSecondaryEducation : Generator Bool
genSecondaryEducation =
Random.map (\n -> n < 75) (Random.int 1 100)
generateQualification : Generator TertiaryQualification
generateQualification =
Random.uniform TradeDegree
[ EngineeringDegree
, SocialWorkDegree
, MedicalDegree
, TeachingDegree
]
genTertiaryEducation : Generator (List TertiaryQualification)
genTertiaryEducation =
Random.int 1 3
|> Random.andThen (\len -> Random.list len generateQualification)
genInterest : Generator Interest
genInterest =
Random.uniform Trade
[ Medical
, Engineering
, SocialWork
, Teaching
, Unknown
]
genWantsLivingRoom : Generator Bool
genWantsLivingRoom =
Random.bool
genWantsFlexRoom : Generator Bool
genWantsFlexRoom =
Random.bool
genPrescriptionsNeeded : Generator Int
genPrescriptionsNeeded =
Random.int 0 5
genSurgeriesNeeded : Generator Int
genSurgeriesNeeded =
Random.int 0 2
genNeedsHospitalization : Generator Bool
genNeedsHospitalization =
Random.map (\n -> n < 5) (Random.int 1 100)
genHousing : Generator (Maybe Housing)
genHousing =
Random.constant (Just (Housing.buildHouse Urban))
| 47652 | module Person exposing (Interest, Person, average, canGoToCollege, generate, housingScore, isQualified, wantsTertiaryEducation)
import Housing exposing (Housing, Location(..))
import Job exposing (Job, Title(..))
import Random exposing (Generator)
import Random.Extra as Random exposing (andMap)
type Interest
= Medical
| Engineering
| SocialWork
| Teaching
| Trade
| Unknown
type TertiaryQualification
= TradeDegree
| EngineeringDegree
| SocialWorkDegree
| MedicalDegree
| TeachingDegree
type alias Person =
{ id : Int
, name : String
, age : Int
, job : Maybe Job
, hasPrimaryEducation : Bool
, hasSecondaryEducation : Bool
, tertiaryQualifications : List TertiaryQualification
-- wants
, interest : Interest
, wantsLivingRoom : Bool
, wantsFlexRoom : Bool
-- needs
, prescriptionsNeeded : Int
, surgeriesNeeded : Int
, needsHospitalization : Bool
, house : Maybe Housing
}
average : Int -> Person
average id =
{ id = id
, name = "<NAME>"
, age = 35
, job = Just (Job.train Carpenter)
, hasPrimaryEducation = True
, hasSecondaryEducation = True
, tertiaryQualifications = [ TradeDegree ]
-- wants
, interest = Trade
, wantsLivingRoom = True
, wantsFlexRoom = False
-- needs
, prescriptionsNeeded = 1
, surgeriesNeeded = 0
, needsHospitalization = False
, house = Nothing
}
-- QUERY
housingScore : Person -> Float
housingScore person =
case person.house of
Just house ->
Housing.score house
Nothing ->
0
wantsTertiaryEducation : Person -> Bool
wantsTertiaryEducation person =
not <|
case person.interest of
Medical ->
List.member MedicalDegree person.tertiaryQualifications
Engineering ->
List.member EngineeringDegree person.tertiaryQualifications
SocialWork ->
List.member SocialWorkDegree person.tertiaryQualifications
Teaching ->
List.member TeachingDegree person.tertiaryQualifications
Trade ->
List.member TradeDegree person.tertiaryQualifications
Unknown ->
True
canGoToCollege : Person -> Bool
canGoToCollege person =
person.job == Nothing && person.hasPrimaryEducation && person.hasSecondaryEducation && wantsTertiaryEducation person
isQualified : Job.Title -> Person -> Bool
isQualified title person =
case title of
Farmer ->
person.hasSecondaryEducation
Doctor ->
List.member MedicalDegree person.tertiaryQualifications
Nurse ->
List.member MedicalDegree person.tertiaryQualifications
CivilEngineer ->
List.member EngineeringDegree person.tertiaryQualifications
Programmer ->
List.member EngineeringDegree person.tertiaryQualifications
SocialWorker ->
List.member SocialWorkDegree person.tertiaryQualifications
Teacher ->
List.member TeachingDegree person.tertiaryQualifications
Professor ->
List.member TeachingDegree person.tertiaryQualifications
Carpenter ->
List.member TradeDegree person.tertiaryQualifications
Electrician ->
List.member TradeDegree person.tertiaryQualifications
generate : Generator Person
generate =
Random.map Person genId
|> andMap genName
|> andMap genAge
|> andMap genJob
|> andMap genPrimaryEducation
|> andMap genSecondaryEducation
|> andMap genTertiaryEducation
|> andMap genInterest
|> andMap genWantsLivingRoom
|> andMap genWantsFlexRoom
|> andMap genPrescriptionsNeeded
|> andMap genSurgeriesNeeded
|> andMap genNeedsHospitalization
|> andMap genHousing
genId : Generator Int
genId =
Random.int Random.minInt Random.maxInt
genName : Generator String
genName =
Random.uniform "<NAME>" [ "<NAME>", "<NAME>", "<NAME>", "<NAME>" ]
genAge : Generator Int
genAge =
Random.int 0 100
genJob : Generator (Maybe Job)
genJob =
Random.map2
(\n job ->
if n < 10 then
Nothing
else
Just job
)
(Random.int 1 100)
Job.generate
genPrimaryEducation : Generator Bool
genPrimaryEducation =
Random.map (\n -> n < 90) (Random.int 1 100)
genSecondaryEducation : Generator Bool
genSecondaryEducation =
Random.map (\n -> n < 75) (Random.int 1 100)
generateQualification : Generator TertiaryQualification
generateQualification =
Random.uniform TradeDegree
[ EngineeringDegree
, SocialWorkDegree
, MedicalDegree
, TeachingDegree
]
genTertiaryEducation : Generator (List TertiaryQualification)
genTertiaryEducation =
Random.int 1 3
|> Random.andThen (\len -> Random.list len generateQualification)
genInterest : Generator Interest
genInterest =
Random.uniform Trade
[ Medical
, Engineering
, SocialWork
, Teaching
, Unknown
]
genWantsLivingRoom : Generator Bool
genWantsLivingRoom =
Random.bool
genWantsFlexRoom : Generator Bool
genWantsFlexRoom =
Random.bool
genPrescriptionsNeeded : Generator Int
genPrescriptionsNeeded =
Random.int 0 5
genSurgeriesNeeded : Generator Int
genSurgeriesNeeded =
Random.int 0 2
genNeedsHospitalization : Generator Bool
genNeedsHospitalization =
Random.map (\n -> n < 5) (Random.int 1 100)
genHousing : Generator (Maybe Housing)
genHousing =
Random.constant (Just (Housing.buildHouse Urban))
| true | module Person exposing (Interest, Person, average, canGoToCollege, generate, housingScore, isQualified, wantsTertiaryEducation)
import Housing exposing (Housing, Location(..))
import Job exposing (Job, Title(..))
import Random exposing (Generator)
import Random.Extra as Random exposing (andMap)
type Interest
= Medical
| Engineering
| SocialWork
| Teaching
| Trade
| Unknown
type TertiaryQualification
= TradeDegree
| EngineeringDegree
| SocialWorkDegree
| MedicalDegree
| TeachingDegree
type alias Person =
{ id : Int
, name : String
, age : Int
, job : Maybe Job
, hasPrimaryEducation : Bool
, hasSecondaryEducation : Bool
, tertiaryQualifications : List TertiaryQualification
-- wants
, interest : Interest
, wantsLivingRoom : Bool
, wantsFlexRoom : Bool
-- needs
, prescriptionsNeeded : Int
, surgeriesNeeded : Int
, needsHospitalization : Bool
, house : Maybe Housing
}
average : Int -> Person
average id =
{ id = id
, name = "PI:NAME:<NAME>END_PI"
, age = 35
, job = Just (Job.train Carpenter)
, hasPrimaryEducation = True
, hasSecondaryEducation = True
, tertiaryQualifications = [ TradeDegree ]
-- wants
, interest = Trade
, wantsLivingRoom = True
, wantsFlexRoom = False
-- needs
, prescriptionsNeeded = 1
, surgeriesNeeded = 0
, needsHospitalization = False
, house = Nothing
}
-- QUERY
housingScore : Person -> Float
housingScore person =
case person.house of
Just house ->
Housing.score house
Nothing ->
0
wantsTertiaryEducation : Person -> Bool
wantsTertiaryEducation person =
not <|
case person.interest of
Medical ->
List.member MedicalDegree person.tertiaryQualifications
Engineering ->
List.member EngineeringDegree person.tertiaryQualifications
SocialWork ->
List.member SocialWorkDegree person.tertiaryQualifications
Teaching ->
List.member TeachingDegree person.tertiaryQualifications
Trade ->
List.member TradeDegree person.tertiaryQualifications
Unknown ->
True
canGoToCollege : Person -> Bool
canGoToCollege person =
person.job == Nothing && person.hasPrimaryEducation && person.hasSecondaryEducation && wantsTertiaryEducation person
isQualified : Job.Title -> Person -> Bool
isQualified title person =
case title of
Farmer ->
person.hasSecondaryEducation
Doctor ->
List.member MedicalDegree person.tertiaryQualifications
Nurse ->
List.member MedicalDegree person.tertiaryQualifications
CivilEngineer ->
List.member EngineeringDegree person.tertiaryQualifications
Programmer ->
List.member EngineeringDegree person.tertiaryQualifications
SocialWorker ->
List.member SocialWorkDegree person.tertiaryQualifications
Teacher ->
List.member TeachingDegree person.tertiaryQualifications
Professor ->
List.member TeachingDegree person.tertiaryQualifications
Carpenter ->
List.member TradeDegree person.tertiaryQualifications
Electrician ->
List.member TradeDegree person.tertiaryQualifications
generate : Generator Person
generate =
Random.map Person genId
|> andMap genName
|> andMap genAge
|> andMap genJob
|> andMap genPrimaryEducation
|> andMap genSecondaryEducation
|> andMap genTertiaryEducation
|> andMap genInterest
|> andMap genWantsLivingRoom
|> andMap genWantsFlexRoom
|> andMap genPrescriptionsNeeded
|> andMap genSurgeriesNeeded
|> andMap genNeedsHospitalization
|> andMap genHousing
genId : Generator Int
genId =
Random.int Random.minInt Random.maxInt
genName : Generator String
genName =
Random.uniform "PI:NAME:<NAME>END_PI" [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ]
genAge : Generator Int
genAge =
Random.int 0 100
genJob : Generator (Maybe Job)
genJob =
Random.map2
(\n job ->
if n < 10 then
Nothing
else
Just job
)
(Random.int 1 100)
Job.generate
genPrimaryEducation : Generator Bool
genPrimaryEducation =
Random.map (\n -> n < 90) (Random.int 1 100)
genSecondaryEducation : Generator Bool
genSecondaryEducation =
Random.map (\n -> n < 75) (Random.int 1 100)
generateQualification : Generator TertiaryQualification
generateQualification =
Random.uniform TradeDegree
[ EngineeringDegree
, SocialWorkDegree
, MedicalDegree
, TeachingDegree
]
genTertiaryEducation : Generator (List TertiaryQualification)
genTertiaryEducation =
Random.int 1 3
|> Random.andThen (\len -> Random.list len generateQualification)
genInterest : Generator Interest
genInterest =
Random.uniform Trade
[ Medical
, Engineering
, SocialWork
, Teaching
, Unknown
]
genWantsLivingRoom : Generator Bool
genWantsLivingRoom =
Random.bool
genWantsFlexRoom : Generator Bool
genWantsFlexRoom =
Random.bool
genPrescriptionsNeeded : Generator Int
genPrescriptionsNeeded =
Random.int 0 5
genSurgeriesNeeded : Generator Int
genSurgeriesNeeded =
Random.int 0 2
genNeedsHospitalization : Generator Bool
genNeedsHospitalization =
Random.map (\n -> n < 5) (Random.int 1 100)
genHousing : Generator (Maybe Housing)
genHousing =
Random.constant (Just (Housing.buildHouse Urban))
| elm |
[
{
"context": " , HA.alt \"Photo de Malika Alouani et Nicolas Leyri\"\n ",
"end": 1353,
"score": 0.9998631477,
"start": 1339,
"tag": "NAME",
"value": "Malika Alouani"
},
{
"context": " , HA.alt \"Photo de Malika Alouani et Nicolas Leyri\"\n ]\n ",
"end": 1370,
"score": 0.9998509288,
"start": 1357,
"tag": "NAME",
"value": "Nicolas Leyri"
},
{
"context": "s voudraient empêcher de mourir définitivement » (Célestin Freinet).\" ]\n , H.p [] [ H.tex",
"end": 1879,
"score": 0.998667419,
"start": 1863,
"tag": "NAME",
"value": "Célestin Freinet"
},
{
"context": " ]\n , H.p [] [ H.text \"Malika : enseignante formatrice, conseillère au numériqu",
"end": 1938,
"score": 0.9992877841,
"start": 1932,
"tag": "NAME",
"value": "Malika"
},
{
"context": " ]\n , H.p [] [ H.text \"Nicolas : coordonnateur REP à Fontenay-sous-Bois, je suis",
"end": 2245,
"score": 0.9990282655,
"start": 2238,
"tag": "NAME",
"value": "Nicolas"
},
{
"context": " ce monde qu’une idée dont l’heure est arrivée » (Victor Hugo).\" ]\n ]\n ",
"end": 2548,
"score": 0.9996377826,
"start": 2537,
"tag": "NAME",
"value": "Victor Hugo"
},
{
"context": " , HA.alt \"Photo de Nicolas Leyri en train de se filmer sur son smartphone\"\n ",
"end": 4399,
"score": 0.9989479184,
"start": 4386,
"tag": "NAME",
"value": "Nicolas Leyri"
}
] | src/Page/About.elm | magopian/ClasseA12 | 3 | module Page.About exposing (Model, Msg(..), init, update, view)
import Data.Session exposing (Session)
import Html as H
import Html.Attributes as HA
type alias Model =
{}
type Msg
= NoOp
init : Session -> ( Model, Cmd Msg )
init session =
( {}, Cmd.none )
update : Session -> Msg -> Model -> ( Model, Cmd Msg )
update _ msg model =
( model, Cmd.none )
view : Session -> Model -> ( String, List (H.Html Msg) )
view _ model =
( "Classe à 12 ?"
, [ H.div [ HA.class "hero" ]
[ H.div [ HA.class "hero__container" ]
[ H.img [ HA.src "/logo_ca12.png" , HA.class "hero__logo" ] []
, H.h1 [] [ H.text "Classe à 12 ?" ]
, H.p [] [ H.text "Prêt ? Filmez ! Partagez !" ]
]
]
, H.div [ HA.class "main" ]
[ H.div [ HA.class "section article article__full" ]
[ H.div [ HA.class "article__content" ]
[ H.div [ HA.class "container" ]
[ H.div [ HA.class "article__image" ]
[ H.img
[ HA.src "http://res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_1440,w_720,f_auto,q_auto/v1/1436014/aaa54f1f-f314-4d46-9fa5-f3b48835db45_htkbm2.jpg"
, HA.alt "Photo de Malika Alouani et Nicolas Leyri"
]
[]
]
, H.div [ HA.class "richtext" ]
[ H.h3 [ HA.class "title is-3" ] [ H.text "Qui sommes-nous ?" ]
, H.em [] [ H.text "« Ne vous laissez pas arrêter par ceux qui, devant l’imperfection de ce que vous réalisez, ne manqueront pas de prôner les méthodes du passé qu’ils voudraient empêcher de mourir définitivement » (Célestin Freinet)." ]
, H.p [] [ H.text "Malika : enseignante formatrice, conseillère au numérique à la Direction du numérique éducatif et à la délégation académique au numérique de Versailles, j’ai accepté de quitter la classe pour accompagner les nouveaux usages pédagogiques avec le numérique." ]
, H.p [] [ H.text "Nicolas : coordonnateur REP à Fontenay-sous-Bois, je suis passionné par les problématiques de l’éducation prioritaire, l’innovation, les nouvelles technologies et la vidéo." ]
, H.em [] [ H.text "« Rien n’est plus fort en ce monde qu’une idée dont l’heure est arrivée » (Victor Hugo)." ]
]
]
, H.div [ HA.class "container" ]
[ H.div [ HA.class "article__image" ]
[ H.img
[ HA.src "http://res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_1440,w_720,f_auto,q_auto/v1/1436014/IMG_5702_nv6pjl.png"
, HA.alt "Photo d'élèves dans une classe"
]
[]
]
, H.div [ HA.class "richtext" ]
[ H.h3 [ HA.class "title is-3" ] [ H.text "Un nouveau service, pour quoi faire ?" ]
, H.em [] [ H.text "Partager pour apprendre et progresser en équipe" ]
, H.p [] [ H.text "Ce projet en cours de développement, co-construit avec les enseignants des classes dédoublées (CP et CE1), a pour objectif de valoriser les retours d’expérience et les échanges de pratiques personnalisées, via un produit numérique de type réseau social." ]
, H.p [] [ H.text "Que vous soyez novice ou expérimenté, nous vous proposons une plateforme vidéo permettant de partager vos expériences pédagogiques auprès de vos collègues, facilement et dans le respect des pratiques de chacun." ]
]
]
, H.div [ HA.class "container" ]
[ H.div [ HA.class "article__image" ]
[ H.img
[ HA.src "http://res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_1440,w_720,f_auto,q_auto/v1/1436014/2eaa8893-502a-439f-90ba-e0842eb72284_h4p2cg.jpg"
, HA.alt "Photo de Nicolas Leyri en train de se filmer sur son smartphone"
]
[]
]
, H.div [ HA.class "richtext" ]
[ H.h3 [ HA.class "title is-3" ] [ H.text "Comment participer ?" ]
, H.em [] [ H.text "Venez comme vous êtes, avec votre envie et vos idées !" ]
, H.p [] [ H.text "Vous avez envie d'échanger et de partager des outils, des pratiques, des gestes professionnels avec vos collègues ? Rien de plus simple avec Classe à 12 ! Postez une courte vidéo de 1 à 2 mn en format paysage et c'est parti !" ]
, H.p []
[ H.text "N'oubliez pas de remplir et de nous envoyer un formulaire de droit à l'image pour vos élèves, les parents ou vous-mêmes, selon la situation, que vous pouvez "
, H.a [ HA.href "http://eduscol.education.fr/internet-responsable/ressources/boite-a-outils.html" ] [ H.text "trouver ici." ]
]
]
]
, H.div [ HA.class "container" ]
[ H.div [ HA.class "article__image" ]
[ H.img
[ HA.src "http://res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_1440,w_720,f_auto,q_auto/v1/1436014/9ba429e2-d343-4e7e-a6de-fc0918beff54_rskzrf.png"
, HA.alt "Photo d'un casier de rangements de feutres de couleur"
]
[]
]
, H.div [ HA.class "richtext" ]
[ H.h3 [ HA.class "title is-3" ] [ H.text "Quel sujet traiter dans ma vidéo ?" ]
, H.em [] [ H.text "Toute contribution est précieuse, mutualisons nos expériences et nos intelligences !" ]
, H.p [] [ H.text "Avec ou sans élève, racontez votre classe, décrivez son aménagement, partagez votre organisation avec vos collègues, montrez une séance pédagogique, parlez d'un jeu ou d'un livre qui vous a plu... tout est permis ! Regardez les exemples déjà proposés sur le site ! Et... si le sujet a déjà été traité, n'hésitez pas à donner votre propre point de vue ! Nous nous enrichirons mutuellement." ]
]
]
]
]
]
]
)
| 43586 | module Page.About exposing (Model, Msg(..), init, update, view)
import Data.Session exposing (Session)
import Html as H
import Html.Attributes as HA
type alias Model =
{}
type Msg
= NoOp
init : Session -> ( Model, Cmd Msg )
init session =
( {}, Cmd.none )
update : Session -> Msg -> Model -> ( Model, Cmd Msg )
update _ msg model =
( model, Cmd.none )
view : Session -> Model -> ( String, List (H.Html Msg) )
view _ model =
( "Classe à 12 ?"
, [ H.div [ HA.class "hero" ]
[ H.div [ HA.class "hero__container" ]
[ H.img [ HA.src "/logo_ca12.png" , HA.class "hero__logo" ] []
, H.h1 [] [ H.text "Classe à 12 ?" ]
, H.p [] [ H.text "Prêt ? Filmez ! Partagez !" ]
]
]
, H.div [ HA.class "main" ]
[ H.div [ HA.class "section article article__full" ]
[ H.div [ HA.class "article__content" ]
[ H.div [ HA.class "container" ]
[ H.div [ HA.class "article__image" ]
[ H.img
[ HA.src "http://res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_1440,w_720,f_auto,q_auto/v1/1436014/aaa54f1f-f314-4d46-9fa5-f3b48835db45_htkbm2.jpg"
, HA.alt "Photo de <NAME> et <NAME>"
]
[]
]
, H.div [ HA.class "richtext" ]
[ H.h3 [ HA.class "title is-3" ] [ H.text "Qui sommes-nous ?" ]
, H.em [] [ H.text "« Ne vous laissez pas arrêter par ceux qui, devant l’imperfection de ce que vous réalisez, ne manqueront pas de prôner les méthodes du passé qu’ils voudraient empêcher de mourir définitivement » (<NAME>)." ]
, H.p [] [ H.text "<NAME> : enseignante formatrice, conseillère au numérique à la Direction du numérique éducatif et à la délégation académique au numérique de Versailles, j’ai accepté de quitter la classe pour accompagner les nouveaux usages pédagogiques avec le numérique." ]
, H.p [] [ H.text "<NAME> : coordonnateur REP à Fontenay-sous-Bois, je suis passionné par les problématiques de l’éducation prioritaire, l’innovation, les nouvelles technologies et la vidéo." ]
, H.em [] [ H.text "« Rien n’est plus fort en ce monde qu’une idée dont l’heure est arrivée » (<NAME>)." ]
]
]
, H.div [ HA.class "container" ]
[ H.div [ HA.class "article__image" ]
[ H.img
[ HA.src "http://res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_1440,w_720,f_auto,q_auto/v1/1436014/IMG_5702_nv6pjl.png"
, HA.alt "Photo d'élèves dans une classe"
]
[]
]
, H.div [ HA.class "richtext" ]
[ H.h3 [ HA.class "title is-3" ] [ H.text "Un nouveau service, pour quoi faire ?" ]
, H.em [] [ H.text "Partager pour apprendre et progresser en équipe" ]
, H.p [] [ H.text "Ce projet en cours de développement, co-construit avec les enseignants des classes dédoublées (CP et CE1), a pour objectif de valoriser les retours d’expérience et les échanges de pratiques personnalisées, via un produit numérique de type réseau social." ]
, H.p [] [ H.text "Que vous soyez novice ou expérimenté, nous vous proposons une plateforme vidéo permettant de partager vos expériences pédagogiques auprès de vos collègues, facilement et dans le respect des pratiques de chacun." ]
]
]
, H.div [ HA.class "container" ]
[ H.div [ HA.class "article__image" ]
[ H.img
[ HA.src "http://res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_1440,w_720,f_auto,q_auto/v1/1436014/2eaa8893-502a-439f-90ba-e0842eb72284_h4p2cg.jpg"
, HA.alt "Photo de <NAME> en train de se filmer sur son smartphone"
]
[]
]
, H.div [ HA.class "richtext" ]
[ H.h3 [ HA.class "title is-3" ] [ H.text "Comment participer ?" ]
, H.em [] [ H.text "Venez comme vous êtes, avec votre envie et vos idées !" ]
, H.p [] [ H.text "Vous avez envie d'échanger et de partager des outils, des pratiques, des gestes professionnels avec vos collègues ? Rien de plus simple avec Classe à 12 ! Postez une courte vidéo de 1 à 2 mn en format paysage et c'est parti !" ]
, H.p []
[ H.text "N'oubliez pas de remplir et de nous envoyer un formulaire de droit à l'image pour vos élèves, les parents ou vous-mêmes, selon la situation, que vous pouvez "
, H.a [ HA.href "http://eduscol.education.fr/internet-responsable/ressources/boite-a-outils.html" ] [ H.text "trouver ici." ]
]
]
]
, H.div [ HA.class "container" ]
[ H.div [ HA.class "article__image" ]
[ H.img
[ HA.src "http://res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_1440,w_720,f_auto,q_auto/v1/1436014/9ba429e2-d343-4e7e-a6de-fc0918beff54_rskzrf.png"
, HA.alt "Photo d'un casier de rangements de feutres de couleur"
]
[]
]
, H.div [ HA.class "richtext" ]
[ H.h3 [ HA.class "title is-3" ] [ H.text "Quel sujet traiter dans ma vidéo ?" ]
, H.em [] [ H.text "Toute contribution est précieuse, mutualisons nos expériences et nos intelligences !" ]
, H.p [] [ H.text "Avec ou sans élève, racontez votre classe, décrivez son aménagement, partagez votre organisation avec vos collègues, montrez une séance pédagogique, parlez d'un jeu ou d'un livre qui vous a plu... tout est permis ! Regardez les exemples déjà proposés sur le site ! Et... si le sujet a déjà été traité, n'hésitez pas à donner votre propre point de vue ! Nous nous enrichirons mutuellement." ]
]
]
]
]
]
]
)
| true | module Page.About exposing (Model, Msg(..), init, update, view)
import Data.Session exposing (Session)
import Html as H
import Html.Attributes as HA
type alias Model =
{}
type Msg
= NoOp
init : Session -> ( Model, Cmd Msg )
init session =
( {}, Cmd.none )
update : Session -> Msg -> Model -> ( Model, Cmd Msg )
update _ msg model =
( model, Cmd.none )
view : Session -> Model -> ( String, List (H.Html Msg) )
view _ model =
( "Classe à 12 ?"
, [ H.div [ HA.class "hero" ]
[ H.div [ HA.class "hero__container" ]
[ H.img [ HA.src "/logo_ca12.png" , HA.class "hero__logo" ] []
, H.h1 [] [ H.text "Classe à 12 ?" ]
, H.p [] [ H.text "Prêt ? Filmez ! Partagez !" ]
]
]
, H.div [ HA.class "main" ]
[ H.div [ HA.class "section article article__full" ]
[ H.div [ HA.class "article__content" ]
[ H.div [ HA.class "container" ]
[ H.div [ HA.class "article__image" ]
[ H.img
[ HA.src "http://res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_1440,w_720,f_auto,q_auto/v1/1436014/aaa54f1f-f314-4d46-9fa5-f3b48835db45_htkbm2.jpg"
, HA.alt "Photo de PI:NAME:<NAME>END_PI et PI:NAME:<NAME>END_PI"
]
[]
]
, H.div [ HA.class "richtext" ]
[ H.h3 [ HA.class "title is-3" ] [ H.text "Qui sommes-nous ?" ]
, H.em [] [ H.text "« Ne vous laissez pas arrêter par ceux qui, devant l’imperfection de ce que vous réalisez, ne manqueront pas de prôner les méthodes du passé qu’ils voudraient empêcher de mourir définitivement » (PI:NAME:<NAME>END_PI)." ]
, H.p [] [ H.text "PI:NAME:<NAME>END_PI : enseignante formatrice, conseillère au numérique à la Direction du numérique éducatif et à la délégation académique au numérique de Versailles, j’ai accepté de quitter la classe pour accompagner les nouveaux usages pédagogiques avec le numérique." ]
, H.p [] [ H.text "PI:NAME:<NAME>END_PI : coordonnateur REP à Fontenay-sous-Bois, je suis passionné par les problématiques de l’éducation prioritaire, l’innovation, les nouvelles technologies et la vidéo." ]
, H.em [] [ H.text "« Rien n’est plus fort en ce monde qu’une idée dont l’heure est arrivée » (PI:NAME:<NAME>END_PI)." ]
]
]
, H.div [ HA.class "container" ]
[ H.div [ HA.class "article__image" ]
[ H.img
[ HA.src "http://res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_1440,w_720,f_auto,q_auto/v1/1436014/IMG_5702_nv6pjl.png"
, HA.alt "Photo d'élèves dans une classe"
]
[]
]
, H.div [ HA.class "richtext" ]
[ H.h3 [ HA.class "title is-3" ] [ H.text "Un nouveau service, pour quoi faire ?" ]
, H.em [] [ H.text "Partager pour apprendre et progresser en équipe" ]
, H.p [] [ H.text "Ce projet en cours de développement, co-construit avec les enseignants des classes dédoublées (CP et CE1), a pour objectif de valoriser les retours d’expérience et les échanges de pratiques personnalisées, via un produit numérique de type réseau social." ]
, H.p [] [ H.text "Que vous soyez novice ou expérimenté, nous vous proposons une plateforme vidéo permettant de partager vos expériences pédagogiques auprès de vos collègues, facilement et dans le respect des pratiques de chacun." ]
]
]
, H.div [ HA.class "container" ]
[ H.div [ HA.class "article__image" ]
[ H.img
[ HA.src "http://res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_1440,w_720,f_auto,q_auto/v1/1436014/2eaa8893-502a-439f-90ba-e0842eb72284_h4p2cg.jpg"
, HA.alt "Photo de PI:NAME:<NAME>END_PI en train de se filmer sur son smartphone"
]
[]
]
, H.div [ HA.class "richtext" ]
[ H.h3 [ HA.class "title is-3" ] [ H.text "Comment participer ?" ]
, H.em [] [ H.text "Venez comme vous êtes, avec votre envie et vos idées !" ]
, H.p [] [ H.text "Vous avez envie d'échanger et de partager des outils, des pratiques, des gestes professionnels avec vos collègues ? Rien de plus simple avec Classe à 12 ! Postez une courte vidéo de 1 à 2 mn en format paysage et c'est parti !" ]
, H.p []
[ H.text "N'oubliez pas de remplir et de nous envoyer un formulaire de droit à l'image pour vos élèves, les parents ou vous-mêmes, selon la situation, que vous pouvez "
, H.a [ HA.href "http://eduscol.education.fr/internet-responsable/ressources/boite-a-outils.html" ] [ H.text "trouver ici." ]
]
]
]
, H.div [ HA.class "container" ]
[ H.div [ HA.class "article__image" ]
[ H.img
[ HA.src "http://res.cloudinary.com/hrscywv4p/image/upload/c_limit,fl_lossy,h_1440,w_720,f_auto,q_auto/v1/1436014/9ba429e2-d343-4e7e-a6de-fc0918beff54_rskzrf.png"
, HA.alt "Photo d'un casier de rangements de feutres de couleur"
]
[]
]
, H.div [ HA.class "richtext" ]
[ H.h3 [ HA.class "title is-3" ] [ H.text "Quel sujet traiter dans ma vidéo ?" ]
, H.em [] [ H.text "Toute contribution est précieuse, mutualisons nos expériences et nos intelligences !" ]
, H.p [] [ H.text "Avec ou sans élève, racontez votre classe, décrivez son aménagement, partagez votre organisation avec vos collègues, montrez une séance pédagogique, parlez d'un jeu ou d'un livre qui vous a plu... tout est permis ! Regardez les exemples déjà proposés sur le site ! Et... si le sujet a déjà été traité, n'hésitez pas à donner votre propre point de vue ! Nous nous enrichirons mutuellement." ]
]
]
]
]
]
]
)
| elm |
[
{
"context": "bootstrap/4.0.0/css/bootstrap.min.css\" integrity=\"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\">\n </head>\n <bo",
"end": 2912,
"score": 0.9995874763,
"start": 2841,
"tag": "KEY",
"value": "sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
},
{
"context": "IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm\" crossorigin=\"anonymous\">\n </head>\n <body>\n <h1>Hello, w",
"end": 2936,
"score": 0.9614527822,
"start": 2927,
"tag": "KEY",
"value": "anonymous"
}
] | src/Page/GettingStarted.elm | JoeMarion/elm-bootstrap.info | 0 | module Page.GettingStarted exposing (view)
import Html exposing (..)
import Html.Attributes exposing (..)
import Util
view : (String -> msg) -> List (Html msg)
view pageMsg =
[ Util.simplePageHeader
"Getting started"
"""A brief overview of Elm Bootstrap, how to use it and some examples."""
, Util.pageContent
(quickStart
++ embedding
++ conventions
++ example
)
]
quickStart : List (Html msg)
quickStart =
[ h2 [] [ text "Quick start"]
, p [] [ text """The easiest way to get started is to use the Bootstrap.CDN module to inline the Bootstrap CSS.
This way you can quickly get up and running using elm-reactor."""]
, h4 [] [ text "Start a new project" ]
, Util.code setupCode
, h4 [] [ text "Module code" ]
, p [] [ text "Create a Main.elm file with the following content"]
, Util.code quickStartCode
, h4 [] [ text "Running the example" ]
, Util.code runQuickStartCode
, p [] [ text "Navigate to http://localhost:8000/Main.elm"]
, Util.calloutWarning
[ p [] [ text """Don't use this method when you want to deploy your app for real life usage.
It's not very efficient, the payload for your page will be pretty big and you want get the benefits of caching the CSS.""" ]
]
]
setupCode : Html msg
setupCode =
Util.toMarkdown """
```bash
mkdir bootstrap-example
cd bootstrap-example
elm-package install --yes rundis/elm-bootstrap
```
"""
quickStartCode : Html msg
quickStartCode =
Util.toMarkdownElm """
module Main exposing (main)
import Html exposing (..)
import Bootstrap.CDN as CDN
import Bootstrap.Grid as Grid
main =
Grid.container []
[ CDN.stylesheet -- creates an inline style node with the Bootstrap CSS
, Grid.row []
[ Grid.col []
[ text "Some content for my view here..."]
]
]
"""
runQuickStartCode : Html msg
runQuickStartCode =
Util.toMarkdown """
```bash
elm-reactor
```
"""
embedding : List (Html msg)
embedding =
[ h2 [] [ text "Embedding" ]
, p [] [ text """For any serious web application you will be embedding your Elm application in an Html page.
When you do, just remember to add the CSS, either as a server asset or just use a CDN.""" ]
, Util.code embeddingCode
]
embeddingCode : Html msg
embeddingCode =
Util.toMarkdown """
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<h1>Hello, world!</h1>
<!-- Your Elm application -->
<script src="elm.js"></script>
</body>
</html>
"""
conventions : List (Html msg)
conventions =
[ h2 [] [ text "Conventions" ]
, p [] [ text """Just a small note of conventions promoted when using Elm Bootstrap and a quick overview of common conventions used by Elm Bootstrap itself.""" ]
, h3 [] [ text "Alias imports" ]
, Util.code aliasCode
, Util.calloutInfo
[ text """By aliasing your Bootstrap related imports, it will usually be easier to read your code and understand where different functions are coming from.
You also reduce the chance of naming conflicts with other libraries.
The API for Elm Bootstrap has been designed with aliasing in mind and you will see aliases used throughout in all the examples.
"""
]
, h3 [] [ text "Options and attributes" ]
, p [] [ text """Most Html element creating functions in Elm bootstrap take two list arguments. The first is a list of options, the second is a list of child items or a list of child elements.
It's probably easier to illustrate with an annotated Code example first to explain further.""" ]
, Util.code optionsCode
, Util.calloutInfo
[ ul []
[ textLi "You create/specify options, by calling functions on the relevant module."
, textLi "<module>.attrs is an escape hatch offered to allow you to provide further customizations when the exposed options are not sufficient for your use case."
, textLi "Options are passed in as list, if you specify the same option more than once, the last one will be the one that is applied."
, li []
[ text "When you specify options that address the same area, the same logic applies"
, ul []
[ textLi "If you specify an option that says that for the smallest screensize you should center vertically."
, textLi "Then you add another option saying that for the smallest screensize you should center content top, the last one of these will be the one applied."
]
]
, textLi "Many elements have default options, which you can override by specifying options in the options list argument."
]
]
]
aliasCode : Html msg
aliasCode =
Util.toMarkdownElm """
import Bootstrap.Grid as Grid
import Bootstrap.Grid.Row as Row
import Bootstrap.Grid.Col as Col
myViewFn =
Grid.row [ Row.centerXs ]
[ Grid.col [ Col.xs2 ]
[ text "Col 1" ]
, Grid.col [ Col.xs4 ]
[ text "Col 2" ]
]
"""
optionsCode : Html msg
optionsCode =
Util.toMarkdownElm """
Grid.row
[ Row.centerXs ] -- Row.centerXs creates a Row.Option
-- The second argument to row is a list of Grid.Column items
[ Col.col
[ Col.xs12
, Col.attrs [ class "custom-class" ] -- <module>.attrs function, creates an option to specify a list of custom Elm Html attributes.
]
[ text "Some full width column."]
]
"""
example : List (Html msg)
example =
[ h2 [] [ text "Example page" ]
, p [] [ text """In the example below we've made a super simple single page application.
It contains basic navigation and a couple of example pages. """ ]
, iframe
[ src "https://ellie-app.com/embed/53W4KNyCZa1/0"
, style
[ ("width","100%")
, ("height","600px")
, ("border", "0")
, ("border-radius","3px")
, ("overflow","hidden")
]
, attribute "sandbox" "allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
]
[]
]
textLi : String -> Html msg
textLi str =
li [] [ text str]
| 4922 | module Page.GettingStarted exposing (view)
import Html exposing (..)
import Html.Attributes exposing (..)
import Util
view : (String -> msg) -> List (Html msg)
view pageMsg =
[ Util.simplePageHeader
"Getting started"
"""A brief overview of Elm Bootstrap, how to use it and some examples."""
, Util.pageContent
(quickStart
++ embedding
++ conventions
++ example
)
]
quickStart : List (Html msg)
quickStart =
[ h2 [] [ text "Quick start"]
, p [] [ text """The easiest way to get started is to use the Bootstrap.CDN module to inline the Bootstrap CSS.
This way you can quickly get up and running using elm-reactor."""]
, h4 [] [ text "Start a new project" ]
, Util.code setupCode
, h4 [] [ text "Module code" ]
, p [] [ text "Create a Main.elm file with the following content"]
, Util.code quickStartCode
, h4 [] [ text "Running the example" ]
, Util.code runQuickStartCode
, p [] [ text "Navigate to http://localhost:8000/Main.elm"]
, Util.calloutWarning
[ p [] [ text """Don't use this method when you want to deploy your app for real life usage.
It's not very efficient, the payload for your page will be pretty big and you want get the benefits of caching the CSS.""" ]
]
]
setupCode : Html msg
setupCode =
Util.toMarkdown """
```bash
mkdir bootstrap-example
cd bootstrap-example
elm-package install --yes rundis/elm-bootstrap
```
"""
quickStartCode : Html msg
quickStartCode =
Util.toMarkdownElm """
module Main exposing (main)
import Html exposing (..)
import Bootstrap.CDN as CDN
import Bootstrap.Grid as Grid
main =
Grid.container []
[ CDN.stylesheet -- creates an inline style node with the Bootstrap CSS
, Grid.row []
[ Grid.col []
[ text "Some content for my view here..."]
]
]
"""
runQuickStartCode : Html msg
runQuickStartCode =
Util.toMarkdown """
```bash
elm-reactor
```
"""
embedding : List (Html msg)
embedding =
[ h2 [] [ text "Embedding" ]
, p [] [ text """For any serious web application you will be embedding your Elm application in an Html page.
When you do, just remember to add the CSS, either as a server asset or just use a CDN.""" ]
, Util.code embeddingCode
]
embeddingCode : Html msg
embeddingCode =
Util.toMarkdown """
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="<KEY>">
</head>
<body>
<h1>Hello, world!</h1>
<!-- Your Elm application -->
<script src="elm.js"></script>
</body>
</html>
"""
conventions : List (Html msg)
conventions =
[ h2 [] [ text "Conventions" ]
, p [] [ text """Just a small note of conventions promoted when using Elm Bootstrap and a quick overview of common conventions used by Elm Bootstrap itself.""" ]
, h3 [] [ text "Alias imports" ]
, Util.code aliasCode
, Util.calloutInfo
[ text """By aliasing your Bootstrap related imports, it will usually be easier to read your code and understand where different functions are coming from.
You also reduce the chance of naming conflicts with other libraries.
The API for Elm Bootstrap has been designed with aliasing in mind and you will see aliases used throughout in all the examples.
"""
]
, h3 [] [ text "Options and attributes" ]
, p [] [ text """Most Html element creating functions in Elm bootstrap take two list arguments. The first is a list of options, the second is a list of child items or a list of child elements.
It's probably easier to illustrate with an annotated Code example first to explain further.""" ]
, Util.code optionsCode
, Util.calloutInfo
[ ul []
[ textLi "You create/specify options, by calling functions on the relevant module."
, textLi "<module>.attrs is an escape hatch offered to allow you to provide further customizations when the exposed options are not sufficient for your use case."
, textLi "Options are passed in as list, if you specify the same option more than once, the last one will be the one that is applied."
, li []
[ text "When you specify options that address the same area, the same logic applies"
, ul []
[ textLi "If you specify an option that says that for the smallest screensize you should center vertically."
, textLi "Then you add another option saying that for the smallest screensize you should center content top, the last one of these will be the one applied."
]
]
, textLi "Many elements have default options, which you can override by specifying options in the options list argument."
]
]
]
aliasCode : Html msg
aliasCode =
Util.toMarkdownElm """
import Bootstrap.Grid as Grid
import Bootstrap.Grid.Row as Row
import Bootstrap.Grid.Col as Col
myViewFn =
Grid.row [ Row.centerXs ]
[ Grid.col [ Col.xs2 ]
[ text "Col 1" ]
, Grid.col [ Col.xs4 ]
[ text "Col 2" ]
]
"""
optionsCode : Html msg
optionsCode =
Util.toMarkdownElm """
Grid.row
[ Row.centerXs ] -- Row.centerXs creates a Row.Option
-- The second argument to row is a list of Grid.Column items
[ Col.col
[ Col.xs12
, Col.attrs [ class "custom-class" ] -- <module>.attrs function, creates an option to specify a list of custom Elm Html attributes.
]
[ text "Some full width column."]
]
"""
example : List (Html msg)
example =
[ h2 [] [ text "Example page" ]
, p [] [ text """In the example below we've made a super simple single page application.
It contains basic navigation and a couple of example pages. """ ]
, iframe
[ src "https://ellie-app.com/embed/53W4KNyCZa1/0"
, style
[ ("width","100%")
, ("height","600px")
, ("border", "0")
, ("border-radius","3px")
, ("overflow","hidden")
]
, attribute "sandbox" "allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
]
[]
]
textLi : String -> Html msg
textLi str =
li [] [ text str]
| true | module Page.GettingStarted exposing (view)
import Html exposing (..)
import Html.Attributes exposing (..)
import Util
view : (String -> msg) -> List (Html msg)
view pageMsg =
[ Util.simplePageHeader
"Getting started"
"""A brief overview of Elm Bootstrap, how to use it and some examples."""
, Util.pageContent
(quickStart
++ embedding
++ conventions
++ example
)
]
quickStart : List (Html msg)
quickStart =
[ h2 [] [ text "Quick start"]
, p [] [ text """The easiest way to get started is to use the Bootstrap.CDN module to inline the Bootstrap CSS.
This way you can quickly get up and running using elm-reactor."""]
, h4 [] [ text "Start a new project" ]
, Util.code setupCode
, h4 [] [ text "Module code" ]
, p [] [ text "Create a Main.elm file with the following content"]
, Util.code quickStartCode
, h4 [] [ text "Running the example" ]
, Util.code runQuickStartCode
, p [] [ text "Navigate to http://localhost:8000/Main.elm"]
, Util.calloutWarning
[ p [] [ text """Don't use this method when you want to deploy your app for real life usage.
It's not very efficient, the payload for your page will be pretty big and you want get the benefits of caching the CSS.""" ]
]
]
setupCode : Html msg
setupCode =
Util.toMarkdown """
```bash
mkdir bootstrap-example
cd bootstrap-example
elm-package install --yes rundis/elm-bootstrap
```
"""
quickStartCode : Html msg
quickStartCode =
Util.toMarkdownElm """
module Main exposing (main)
import Html exposing (..)
import Bootstrap.CDN as CDN
import Bootstrap.Grid as Grid
main =
Grid.container []
[ CDN.stylesheet -- creates an inline style node with the Bootstrap CSS
, Grid.row []
[ Grid.col []
[ text "Some content for my view here..."]
]
]
"""
runQuickStartCode : Html msg
runQuickStartCode =
Util.toMarkdown """
```bash
elm-reactor
```
"""
embedding : List (Html msg)
embedding =
[ h2 [] [ text "Embedding" ]
, p [] [ text """For any serious web application you will be embedding your Elm application in an Html page.
When you do, just remember to add the CSS, either as a server asset or just use a CDN.""" ]
, Util.code embeddingCode
]
embeddingCode : Html msg
embeddingCode =
Util.toMarkdown """
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="PI:KEY:<KEY>END_PI" crossorigin="PI:KEY:<KEY>END_PI">
</head>
<body>
<h1>Hello, world!</h1>
<!-- Your Elm application -->
<script src="elm.js"></script>
</body>
</html>
"""
conventions : List (Html msg)
conventions =
[ h2 [] [ text "Conventions" ]
, p [] [ text """Just a small note of conventions promoted when using Elm Bootstrap and a quick overview of common conventions used by Elm Bootstrap itself.""" ]
, h3 [] [ text "Alias imports" ]
, Util.code aliasCode
, Util.calloutInfo
[ text """By aliasing your Bootstrap related imports, it will usually be easier to read your code and understand where different functions are coming from.
You also reduce the chance of naming conflicts with other libraries.
The API for Elm Bootstrap has been designed with aliasing in mind and you will see aliases used throughout in all the examples.
"""
]
, h3 [] [ text "Options and attributes" ]
, p [] [ text """Most Html element creating functions in Elm bootstrap take two list arguments. The first is a list of options, the second is a list of child items or a list of child elements.
It's probably easier to illustrate with an annotated Code example first to explain further.""" ]
, Util.code optionsCode
, Util.calloutInfo
[ ul []
[ textLi "You create/specify options, by calling functions on the relevant module."
, textLi "<module>.attrs is an escape hatch offered to allow you to provide further customizations when the exposed options are not sufficient for your use case."
, textLi "Options are passed in as list, if you specify the same option more than once, the last one will be the one that is applied."
, li []
[ text "When you specify options that address the same area, the same logic applies"
, ul []
[ textLi "If you specify an option that says that for the smallest screensize you should center vertically."
, textLi "Then you add another option saying that for the smallest screensize you should center content top, the last one of these will be the one applied."
]
]
, textLi "Many elements have default options, which you can override by specifying options in the options list argument."
]
]
]
aliasCode : Html msg
aliasCode =
Util.toMarkdownElm """
import Bootstrap.Grid as Grid
import Bootstrap.Grid.Row as Row
import Bootstrap.Grid.Col as Col
myViewFn =
Grid.row [ Row.centerXs ]
[ Grid.col [ Col.xs2 ]
[ text "Col 1" ]
, Grid.col [ Col.xs4 ]
[ text "Col 2" ]
]
"""
optionsCode : Html msg
optionsCode =
Util.toMarkdownElm """
Grid.row
[ Row.centerXs ] -- Row.centerXs creates a Row.Option
-- The second argument to row is a list of Grid.Column items
[ Col.col
[ Col.xs12
, Col.attrs [ class "custom-class" ] -- <module>.attrs function, creates an option to specify a list of custom Elm Html attributes.
]
[ text "Some full width column."]
]
"""
example : List (Html msg)
example =
[ h2 [] [ text "Example page" ]
, p [] [ text """In the example below we've made a super simple single page application.
It contains basic navigation and a couple of example pages. """ ]
, iframe
[ src "https://ellie-app.com/embed/53W4KNyCZa1/0"
, style
[ ("width","100%")
, ("height","600px")
, ("border", "0")
, ("border-radius","3px")
, ("overflow","hidden")
]
, attribute "sandbox" "allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
]
[]
]
textLi : String -> Html msg
textLi str =
li [] [ text str]
| elm |
[
{
"context": " ->\n { name = CamelCaseName.build \"droid\"\n , description = Nothing\n ",
"end": 3261,
"score": 0.8900327682,
"start": 3260,
"tag": "NAME",
"value": "d"
},
{
"context": "->\n { name = CamelCaseName.build \"droid\"\n , description = Nothing\n ",
"end": 3265,
"score": 0.373606354,
"start": 3261,
"tag": "NAME",
"value": "roid"
},
{
"context": " ->\n { name = CamelCaseName.build \"droid\"\n , description = Nothing\n ",
"end": 3898,
"score": 0.8249057531,
"start": 3897,
"tag": "NAME",
"value": "d"
},
{
"context": "->\n { name = CamelCaseName.build \"droid\"\n , description = Nothing\n ",
"end": 3902,
"score": 0.3747890294,
"start": 3898,
"tag": "NAME",
"value": "roid"
}
] | generator/tests/Generator/FieldTests.elm | cllns/elm-graphql | 1 | module Generator.FieldTests exposing (all)
import Dict
import Expect
import Graphql.Generator.Context as Context exposing (Context, stub)
import Graphql.Generator.Field as Field
import Graphql.Parser.CamelCaseName as CamelCaseName
import Graphql.Parser.ClassCaseName as ClassCaseName exposing (ClassCaseName)
import Graphql.Parser.Scalar as Scalar exposing (Scalar)
import Graphql.Parser.Type as Type exposing (TypeDefinition, TypeReference)
import Test exposing (..)
contextWith maybeInterfaceLookup =
-- Context.stub
{ stub
| query = "RootQueryObject" |> ClassCaseName.build
, apiSubmodule = [ "Api" ]
, interfaces = maybeInterfaceLookup |> Maybe.withDefault Dict.empty
}
-- Context.context { query = "RootQueryObject", mutation = Nothing, subscription = Nothing, apiSubmodule = [ "Api" ], interfaces = Dict.empty }
all : Test
all =
describe "field generator"
[ test "simple scalar converts for query" <|
\() ->
meField
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""me : SelectionSet String RootQuery
me =
Object.selectionForField "String" "me" [] (Decode.string)
"""
, test "converts for object" <|
\() ->
meField
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "Foo")
|> Expect.equal
"""me : SelectionSet String Api.Object.Foo
me =
Object.selectionForField "String" "me" [] (Decode.string)
"""
, test "simple object with no args" <|
\() ->
{ name = CamelCaseName.build "droid"
, description = Nothing
, typeRef = Type.TypeReference (Type.ObjectRef "Droid") Type.NonNullable
, args = []
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""droid : SelectionSet decodesTo Api.Object.Droid
-> SelectionSet decodesTo RootQuery
droid object_ =
Object.selectionForCompositeField "droid" [] (object_) (identity)
"""
, test "simple interface with no args" <|
\() ->
{ name = CamelCaseName.build "hero"
, description = Nothing
, typeRef = Type.TypeReference (Type.InterfaceRef "Character") Type.NonNullable
, args = []
}
|> Field.generateForObject
(contextWith
(Just (Dict.fromList [ ( "Character", [ ClassCaseName.build "Human", ClassCaseName.build "Droid" ] ) ]))
)
(ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""hero : SelectionSet decodesTo Api.Interface.Character
-> SelectionSet decodesTo RootQuery
hero object_ =
Object.selectionForCompositeField "hero" [] (object_) (identity)
"""
, test "simple object with no args for object" <|
\() ->
{ name = CamelCaseName.build "droid"
, description = Nothing
, typeRef = Type.TypeReference (Type.ObjectRef "Droid") Type.NonNullable
, args = []
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "Foo")
|> Expect.equal
"""droid : SelectionSet decodesTo Api.Object.Droid
-> SelectionSet decodesTo Api.Object.Foo
droid object_ =
Object.selectionForCompositeField "droid" [] (object_) (identity)
"""
, test "list of objects with no args" <|
\() ->
{ name = CamelCaseName.build "droid"
, description = Nothing
, typeRef = Type.TypeReference (Type.List (Type.TypeReference (Type.ObjectRef "Droid") Type.NonNullable)) Type.NonNullable
, args = []
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "Foo")
|> Expect.equal
"""droid : SelectionSet decodesTo Api.Object.Droid
-> SelectionSet (List decodesTo) Api.Object.Foo
droid object_ =
Object.selectionForCompositeField "droid" [] (object_) (identity >> Decode.list)
"""
, test "with required args" <|
\() ->
{ name = CamelCaseName.build "human"
, description = Nothing
, typeRef = Type.TypeReference (Type.ObjectRef "Human") Type.NonNullable
, args =
[ { name = CamelCaseName.build "id"
, description = Nothing
, typeRef = Type.TypeReference (Type.Scalar Scalar.String) Type.NonNullable
}
]
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""type alias HumanRequiredArguments = { id : String }
human : HumanRequiredArguments
-> SelectionSet decodesTo Api.Object.Human
-> SelectionSet decodesTo RootQuery
human requiredArgs object_ =
Object.selectionForCompositeField "human" [ Argument.required "id" requiredArgs.id (Encode.string) ] (object_) (identity)
"""
, test "with optional args" <|
\() ->
{ name = CamelCaseName.build "menuItems"
, description = Nothing
, typeRef = Type.TypeReference (Type.List (Type.TypeReference (Type.ObjectRef "MenuItem") Type.NonNullable)) Type.NonNullable
, args =
[ { name = CamelCaseName.build "contains"
, description = Nothing
, typeRef = Type.TypeReference (Type.Scalar Scalar.String) Type.Nullable
}
]
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""type alias MenuItemsOptionalArguments = { contains : OptionalArgument String }
menuItems : (MenuItemsOptionalArguments -> MenuItemsOptionalArguments)
-> SelectionSet decodesTo Api.Object.MenuItem
-> SelectionSet (List decodesTo) RootQuery
menuItems fillInOptionals object_ =
let
filledInOptionals =
fillInOptionals { contains = Absent }
optionalArgs =
[ Argument.optional "contains" filledInOptionals.contains (Encode.string) ]
|> List.filterMap identity
in
Object.selectionForCompositeField "menuItems" optionalArgs (object_) (identity >> Decode.list)
"""
, test "normalizes reserved names" <|
\() ->
{ name = CamelCaseName.build "type"
, description = Nothing
, typeRef = Type.TypeReference (Type.Scalar Scalar.String) Type.NonNullable
, args = []
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "TreeEntry")
|> Expect.equal
"""type_ : SelectionSet String Api.Object.TreeEntry
type_ =
Object.selectionForField "String" "type" [] (Decode.string)
"""
]
meField : Type.Field
meField =
{ name = CamelCaseName.build "me"
, description = Nothing
, typeRef = Type.TypeReference (Type.Scalar Scalar.String) Type.NonNullable
, args = []
}
| 18269 | module Generator.FieldTests exposing (all)
import Dict
import Expect
import Graphql.Generator.Context as Context exposing (Context, stub)
import Graphql.Generator.Field as Field
import Graphql.Parser.CamelCaseName as CamelCaseName
import Graphql.Parser.ClassCaseName as ClassCaseName exposing (ClassCaseName)
import Graphql.Parser.Scalar as Scalar exposing (Scalar)
import Graphql.Parser.Type as Type exposing (TypeDefinition, TypeReference)
import Test exposing (..)
contextWith maybeInterfaceLookup =
-- Context.stub
{ stub
| query = "RootQueryObject" |> ClassCaseName.build
, apiSubmodule = [ "Api" ]
, interfaces = maybeInterfaceLookup |> Maybe.withDefault Dict.empty
}
-- Context.context { query = "RootQueryObject", mutation = Nothing, subscription = Nothing, apiSubmodule = [ "Api" ], interfaces = Dict.empty }
all : Test
all =
describe "field generator"
[ test "simple scalar converts for query" <|
\() ->
meField
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""me : SelectionSet String RootQuery
me =
Object.selectionForField "String" "me" [] (Decode.string)
"""
, test "converts for object" <|
\() ->
meField
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "Foo")
|> Expect.equal
"""me : SelectionSet String Api.Object.Foo
me =
Object.selectionForField "String" "me" [] (Decode.string)
"""
, test "simple object with no args" <|
\() ->
{ name = CamelCaseName.build "droid"
, description = Nothing
, typeRef = Type.TypeReference (Type.ObjectRef "Droid") Type.NonNullable
, args = []
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""droid : SelectionSet decodesTo Api.Object.Droid
-> SelectionSet decodesTo RootQuery
droid object_ =
Object.selectionForCompositeField "droid" [] (object_) (identity)
"""
, test "simple interface with no args" <|
\() ->
{ name = CamelCaseName.build "hero"
, description = Nothing
, typeRef = Type.TypeReference (Type.InterfaceRef "Character") Type.NonNullable
, args = []
}
|> Field.generateForObject
(contextWith
(Just (Dict.fromList [ ( "Character", [ ClassCaseName.build "Human", ClassCaseName.build "Droid" ] ) ]))
)
(ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""hero : SelectionSet decodesTo Api.Interface.Character
-> SelectionSet decodesTo RootQuery
hero object_ =
Object.selectionForCompositeField "hero" [] (object_) (identity)
"""
, test "simple object with no args for object" <|
\() ->
{ name = CamelCaseName.build "<NAME> <NAME>"
, description = Nothing
, typeRef = Type.TypeReference (Type.ObjectRef "Droid") Type.NonNullable
, args = []
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "Foo")
|> Expect.equal
"""droid : SelectionSet decodesTo Api.Object.Droid
-> SelectionSet decodesTo Api.Object.Foo
droid object_ =
Object.selectionForCompositeField "droid" [] (object_) (identity)
"""
, test "list of objects with no args" <|
\() ->
{ name = CamelCaseName.build "<NAME> <NAME>"
, description = Nothing
, typeRef = Type.TypeReference (Type.List (Type.TypeReference (Type.ObjectRef "Droid") Type.NonNullable)) Type.NonNullable
, args = []
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "Foo")
|> Expect.equal
"""droid : SelectionSet decodesTo Api.Object.Droid
-> SelectionSet (List decodesTo) Api.Object.Foo
droid object_ =
Object.selectionForCompositeField "droid" [] (object_) (identity >> Decode.list)
"""
, test "with required args" <|
\() ->
{ name = CamelCaseName.build "human"
, description = Nothing
, typeRef = Type.TypeReference (Type.ObjectRef "Human") Type.NonNullable
, args =
[ { name = CamelCaseName.build "id"
, description = Nothing
, typeRef = Type.TypeReference (Type.Scalar Scalar.String) Type.NonNullable
}
]
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""type alias HumanRequiredArguments = { id : String }
human : HumanRequiredArguments
-> SelectionSet decodesTo Api.Object.Human
-> SelectionSet decodesTo RootQuery
human requiredArgs object_ =
Object.selectionForCompositeField "human" [ Argument.required "id" requiredArgs.id (Encode.string) ] (object_) (identity)
"""
, test "with optional args" <|
\() ->
{ name = CamelCaseName.build "menuItems"
, description = Nothing
, typeRef = Type.TypeReference (Type.List (Type.TypeReference (Type.ObjectRef "MenuItem") Type.NonNullable)) Type.NonNullable
, args =
[ { name = CamelCaseName.build "contains"
, description = Nothing
, typeRef = Type.TypeReference (Type.Scalar Scalar.String) Type.Nullable
}
]
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""type alias MenuItemsOptionalArguments = { contains : OptionalArgument String }
menuItems : (MenuItemsOptionalArguments -> MenuItemsOptionalArguments)
-> SelectionSet decodesTo Api.Object.MenuItem
-> SelectionSet (List decodesTo) RootQuery
menuItems fillInOptionals object_ =
let
filledInOptionals =
fillInOptionals { contains = Absent }
optionalArgs =
[ Argument.optional "contains" filledInOptionals.contains (Encode.string) ]
|> List.filterMap identity
in
Object.selectionForCompositeField "menuItems" optionalArgs (object_) (identity >> Decode.list)
"""
, test "normalizes reserved names" <|
\() ->
{ name = CamelCaseName.build "type"
, description = Nothing
, typeRef = Type.TypeReference (Type.Scalar Scalar.String) Type.NonNullable
, args = []
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "TreeEntry")
|> Expect.equal
"""type_ : SelectionSet String Api.Object.TreeEntry
type_ =
Object.selectionForField "String" "type" [] (Decode.string)
"""
]
meField : Type.Field
meField =
{ name = CamelCaseName.build "me"
, description = Nothing
, typeRef = Type.TypeReference (Type.Scalar Scalar.String) Type.NonNullable
, args = []
}
| true | module Generator.FieldTests exposing (all)
import Dict
import Expect
import Graphql.Generator.Context as Context exposing (Context, stub)
import Graphql.Generator.Field as Field
import Graphql.Parser.CamelCaseName as CamelCaseName
import Graphql.Parser.ClassCaseName as ClassCaseName exposing (ClassCaseName)
import Graphql.Parser.Scalar as Scalar exposing (Scalar)
import Graphql.Parser.Type as Type exposing (TypeDefinition, TypeReference)
import Test exposing (..)
contextWith maybeInterfaceLookup =
-- Context.stub
{ stub
| query = "RootQueryObject" |> ClassCaseName.build
, apiSubmodule = [ "Api" ]
, interfaces = maybeInterfaceLookup |> Maybe.withDefault Dict.empty
}
-- Context.context { query = "RootQueryObject", mutation = Nothing, subscription = Nothing, apiSubmodule = [ "Api" ], interfaces = Dict.empty }
all : Test
all =
describe "field generator"
[ test "simple scalar converts for query" <|
\() ->
meField
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""me : SelectionSet String RootQuery
me =
Object.selectionForField "String" "me" [] (Decode.string)
"""
, test "converts for object" <|
\() ->
meField
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "Foo")
|> Expect.equal
"""me : SelectionSet String Api.Object.Foo
me =
Object.selectionForField "String" "me" [] (Decode.string)
"""
, test "simple object with no args" <|
\() ->
{ name = CamelCaseName.build "droid"
, description = Nothing
, typeRef = Type.TypeReference (Type.ObjectRef "Droid") Type.NonNullable
, args = []
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""droid : SelectionSet decodesTo Api.Object.Droid
-> SelectionSet decodesTo RootQuery
droid object_ =
Object.selectionForCompositeField "droid" [] (object_) (identity)
"""
, test "simple interface with no args" <|
\() ->
{ name = CamelCaseName.build "hero"
, description = Nothing
, typeRef = Type.TypeReference (Type.InterfaceRef "Character") Type.NonNullable
, args = []
}
|> Field.generateForObject
(contextWith
(Just (Dict.fromList [ ( "Character", [ ClassCaseName.build "Human", ClassCaseName.build "Droid" ] ) ]))
)
(ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""hero : SelectionSet decodesTo Api.Interface.Character
-> SelectionSet decodesTo RootQuery
hero object_ =
Object.selectionForCompositeField "hero" [] (object_) (identity)
"""
, test "simple object with no args for object" <|
\() ->
{ name = CamelCaseName.build "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
, description = Nothing
, typeRef = Type.TypeReference (Type.ObjectRef "Droid") Type.NonNullable
, args = []
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "Foo")
|> Expect.equal
"""droid : SelectionSet decodesTo Api.Object.Droid
-> SelectionSet decodesTo Api.Object.Foo
droid object_ =
Object.selectionForCompositeField "droid" [] (object_) (identity)
"""
, test "list of objects with no args" <|
\() ->
{ name = CamelCaseName.build "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
, description = Nothing
, typeRef = Type.TypeReference (Type.List (Type.TypeReference (Type.ObjectRef "Droid") Type.NonNullable)) Type.NonNullable
, args = []
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "Foo")
|> Expect.equal
"""droid : SelectionSet decodesTo Api.Object.Droid
-> SelectionSet (List decodesTo) Api.Object.Foo
droid object_ =
Object.selectionForCompositeField "droid" [] (object_) (identity >> Decode.list)
"""
, test "with required args" <|
\() ->
{ name = CamelCaseName.build "human"
, description = Nothing
, typeRef = Type.TypeReference (Type.ObjectRef "Human") Type.NonNullable
, args =
[ { name = CamelCaseName.build "id"
, description = Nothing
, typeRef = Type.TypeReference (Type.Scalar Scalar.String) Type.NonNullable
}
]
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""type alias HumanRequiredArguments = { id : String }
human : HumanRequiredArguments
-> SelectionSet decodesTo Api.Object.Human
-> SelectionSet decodesTo RootQuery
human requiredArgs object_ =
Object.selectionForCompositeField "human" [ Argument.required "id" requiredArgs.id (Encode.string) ] (object_) (identity)
"""
, test "with optional args" <|
\() ->
{ name = CamelCaseName.build "menuItems"
, description = Nothing
, typeRef = Type.TypeReference (Type.List (Type.TypeReference (Type.ObjectRef "MenuItem") Type.NonNullable)) Type.NonNullable
, args =
[ { name = CamelCaseName.build "contains"
, description = Nothing
, typeRef = Type.TypeReference (Type.Scalar Scalar.String) Type.Nullable
}
]
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "RootQueryObject")
|> Expect.equal
"""type alias MenuItemsOptionalArguments = { contains : OptionalArgument String }
menuItems : (MenuItemsOptionalArguments -> MenuItemsOptionalArguments)
-> SelectionSet decodesTo Api.Object.MenuItem
-> SelectionSet (List decodesTo) RootQuery
menuItems fillInOptionals object_ =
let
filledInOptionals =
fillInOptionals { contains = Absent }
optionalArgs =
[ Argument.optional "contains" filledInOptionals.contains (Encode.string) ]
|> List.filterMap identity
in
Object.selectionForCompositeField "menuItems" optionalArgs (object_) (identity >> Decode.list)
"""
, test "normalizes reserved names" <|
\() ->
{ name = CamelCaseName.build "type"
, description = Nothing
, typeRef = Type.TypeReference (Type.Scalar Scalar.String) Type.NonNullable
, args = []
}
|> Field.generateForObject (contextWith Nothing) (ClassCaseName.build "TreeEntry")
|> Expect.equal
"""type_ : SelectionSet String Api.Object.TreeEntry
type_ =
Object.selectionForField "String" "type" [] (Decode.string)
"""
]
meField : Type.Field
meField =
{ name = CamelCaseName.build "me"
, description = Nothing
, typeRef = Type.TypeReference (Type.Scalar Scalar.String) Type.NonNullable
, args = []
}
| elm |
[
{
"context": "s\n\nYou just render it like this\n\n```\n<bio\n name=\"Dillon Kearns\"\n photo=\"https://avatars2.githubusercontent.com/",
"end": 7998,
"score": 0.9999026656,
"start": 7985,
"tag": "NAME",
"value": "Dillon Kearns"
},
{
"context": "tars2.githubusercontent.com/u/1384166\"\n twitter=\"dillontkearns\"\n github=\"dillonkearns\"\n>\nDillon really likes bu",
"end": 8083,
"score": 0.9996483922,
"start": 8070,
"tag": "USERNAME",
"value": "dillontkearns"
},
{
"context": "om/u/1384166\"\n twitter=\"dillontkearns\"\n github=\"dillonkearns\"\n>\nDillon really likes building things with Elm! ",
"end": 8107,
"score": 0.9996473193,
"start": 8095,
"tag": "USERNAME",
"value": "dillonkearns"
},
{
"context": "nd you get a custom view like this!\n\n<bio\n name=\"Dillon Kearns\"\n photo=\"https://avatars2.githubusercontent.com/",
"end": 8304,
"score": 0.9998987317,
"start": 8291,
"tag": "NAME",
"value": "Dillon Kearns"
},
{
"context": "tars2.githubusercontent.com/u/1384166\"\n twitter=\"dillontkearns\"\n github=\"dillonkearns\"\n>\nDillon really likes bu",
"end": 8389,
"score": 0.9996654987,
"start": 8376,
"tag": "USERNAME",
"value": "dillontkearns"
},
{
"context": "om/u/1384166\"\n twitter=\"dillontkearns\"\n github=\"dillonkearns\"\n>\nDillon really likes building things with Elm! ",
"end": 8413,
"score": 0.999671936,
"start": 8401,
"tag": "USERNAME",
"value": "dillonkearns"
}
] | examples/src/CustomHtmlBlockSignupForm.elm | bgins/elm-markdown | 0 | module CustomHtmlBlockSignupForm exposing (main)
import Browser
import Element exposing (Element)
import Element.Background
import Element.Border
import Element.Font as Font
import Element.Input
import Element.Region
import Html exposing (Attribute, Html)
import Html.Attributes
import Markdown.Block exposing (Block, Inline, InlineStyle)
import Markdown.Html
import Markdown.Parser
view : Model -> { title : String, body : List (Html Msg) }
view model =
{ title = "dillonkearns/elm-markdown demo"
, body =
[ Element.layout [ Element.width Element.fill ]
(Element.row [ Element.width Element.fill ]
[ Element.Input.multiline [ Element.width (Element.px 400) ]
{ onChange = OnMarkdownInput
, text = model
, placeholder = Nothing
, label = Element.Input.labelHidden "Markdown input"
, spellcheck = False
}
, case markdownView model of
Ok rendered ->
Element.column
[ Element.spacing 30
, Element.padding 80
, Element.width (Element.fill |> Element.maximum 1000)
, Element.centerX
]
rendered
Err errors ->
Element.text errors
]
)
]
}
markdownView : String -> Result String (List (Element Msg))
markdownView markdown =
markdown
|> Markdown.Parser.parse
|> Result.mapError (\error -> error |> List.map Markdown.Parser.deadEndToString |> String.join "\n")
|> Result.andThen (Markdown.Parser.render renderer)
renderer : Markdown.Parser.Renderer (Element Msg)
renderer =
{ heading = heading
, raw =
Element.paragraph
[ Element.spacing 15 ]
, thematicBreak = Element.none
, plain = Element.text
, bold = \content -> Element.row [ Font.bold ] [ Element.text content ]
, italic = \content -> Element.row [ Font.italic ] [ Element.text content ]
, code = code
, link =
\{ title, destination } body ->
Element.newTabLink
[ Element.htmlAttribute (Html.Attributes.style "display" "inline-flex") ]
{ url = destination
, label =
Element.paragraph
[ Font.color (Element.rgb255 0 0 255)
]
body
}
|> Ok
, image =
\image body ->
Element.image [ Element.width Element.fill ] { src = image.src, description = body }
|> Ok
, list =
\items ->
Element.column [ Element.spacing 15 ]
(items
|> List.map
(\itemBlocks ->
Element.row [ Element.spacing 5 ]
[ Element.el
[ Element.alignTop ]
(Element.text "•")
, itemBlocks
]
)
)
, codeBlock = codeBlock
, html =
Markdown.Html.oneOf
[ Markdown.Html.tag "bio"
(\name photoUrl twitter github dribbble renderedChildren ->
bioView renderedChildren name photoUrl twitter github dribbble
)
|> Markdown.Html.withAttribute "name"
|> Markdown.Html.withAttribute "photo"
|> Markdown.Html.withOptionalAttribute "twitter"
|> Markdown.Html.withOptionalAttribute "github"
|> Markdown.Html.withOptionalAttribute "dribbble"
]
}
bioView renderedChildren name photoUrl twitter github dribbble =
Element.column
[ Element.Border.shadow
{ offset = ( 0.3, 0.3 )
, size = 2
, blur = 0.5
, color = Element.rgba255 0 0 0 0.22
}
, Element.padding 20
, Element.spacing 30
, Element.centerX
, Font.center
]
(Element.row [ Element.spacing 20 ]
[ avatarView photoUrl
, Element.el
[ Font.bold
, Font.size 30
]
(Element.text name)
, icons twitter github dribbble
]
:: renderedChildren
)
icons twitter github dribbble =
Element.row []
([ twitter
|> Maybe.map
(\twitterHandle ->
Element.link []
{ url = "https://twitter.com/" ++ twitterHandle
, label =
Element.image [] { src = "https://i.imgur.com/tXSoThF.png", description = "Twitter Logo" }
}
)
, github
|> Maybe.map
(\twitterHandle ->
Element.link []
{ url = "https://github.com/" ++ twitterHandle
, label =
Element.image [] { src = "https://i.imgur.com/0o48UoR.png", description = "Github Logo" }
}
)
, dribbble
|> Maybe.map
(\dribbbleHandle ->
Element.link []
{ url = "https://dribbble.com/" ++ dribbbleHandle
, label =
Element.image [] { src = "https://i.imgur.com/1AGmwO3.png", description = "Dribbble Logo" }
}
)
]
|> List.filterMap identity
)
avatarView avatarUrl =
Element.image [ Element.width Element.fill ]
{ src = avatarUrl, description = "Avatar image" }
|> Element.el
[ Element.width (Element.px 80) ]
rawTextToId rawText =
rawText
|> String.toLower
|> String.replace " " ""
heading : { level : Int, rawText : String, children : List (Element msg) } -> Element msg
heading { level, rawText, children } =
Element.paragraph
[ Font.size
(case level of
1 ->
36
2 ->
24
_ ->
20
)
, Font.bold
, Font.family [ Font.typeface "Montserrat" ]
, Element.Region.heading level
, Element.htmlAttribute
(Html.Attributes.attribute "name" (rawTextToId rawText))
, Font.center
, Element.htmlAttribute
(Html.Attributes.id (rawTextToId rawText))
]
children
code : String -> Element msg
code snippet =
Element.el
[ Element.Background.color
(Element.rgba 0 0 0 0.04)
, Element.Border.rounded 2
, Element.paddingXY 5 3
, Font.family
[ Font.external
{ url = "https://fonts.googleapis.com/css?family=Source+Code+Pro"
, name = "Source Code Pro"
}
]
]
(Element.text snippet)
codeBlock : { body : String, language : Maybe String } -> Element msg
codeBlock details =
Element.el
[ Element.Background.color (Element.rgba 0 0 0 0.03)
, Element.htmlAttribute (Html.Attributes.style "white-space" "pre")
, Element.padding 20
, Element.width Element.fill
, Font.family
[ Font.external
{ url = "https://fonts.googleapis.com/css?family=Source+Code+Pro"
, name = "Source Code Pro"
}
]
]
(Element.text details.body)
markdownBody =
"""# Custom HTML Renderers
You just render it like this
```
<bio
name="Dillon Kearns"
photo="https://avatars2.githubusercontent.com/u/1384166"
twitter="dillontkearns"
github="dillonkearns"
>
Dillon really likes building things with Elm! Here are some links
- [Articles](https://incrementalelm.com/articles)
</bio>
```
And you get a custom view like this!
<bio
name="Dillon Kearns"
photo="https://avatars2.githubusercontent.com/u/1384166"
twitter="dillontkearns"
github="dillonkearns"
>
Dillon really likes building things with Elm! Here are some links
- [Articles](https://incrementalelm.com/articles)
</bio>
Note that these attributes are all optional. Try removing them and see what happens!
Or you can add `dribbble="something"` and see that icon show up if it's provided.
"""
type Msg
= OnMarkdownInput String
type alias Flags =
()
type alias Model =
String
main : Platform.Program Flags Model Msg
main =
Browser.document
{ init = \flags -> ( markdownBody, Cmd.none )
, view = view
, update = update
, subscriptions = \model -> Sub.none
}
update msg model =
case msg of
OnMarkdownInput newMarkdown ->
( newMarkdown, Cmd.none )
| 17192 | module CustomHtmlBlockSignupForm exposing (main)
import Browser
import Element exposing (Element)
import Element.Background
import Element.Border
import Element.Font as Font
import Element.Input
import Element.Region
import Html exposing (Attribute, Html)
import Html.Attributes
import Markdown.Block exposing (Block, Inline, InlineStyle)
import Markdown.Html
import Markdown.Parser
view : Model -> { title : String, body : List (Html Msg) }
view model =
{ title = "dillonkearns/elm-markdown demo"
, body =
[ Element.layout [ Element.width Element.fill ]
(Element.row [ Element.width Element.fill ]
[ Element.Input.multiline [ Element.width (Element.px 400) ]
{ onChange = OnMarkdownInput
, text = model
, placeholder = Nothing
, label = Element.Input.labelHidden "Markdown input"
, spellcheck = False
}
, case markdownView model of
Ok rendered ->
Element.column
[ Element.spacing 30
, Element.padding 80
, Element.width (Element.fill |> Element.maximum 1000)
, Element.centerX
]
rendered
Err errors ->
Element.text errors
]
)
]
}
markdownView : String -> Result String (List (Element Msg))
markdownView markdown =
markdown
|> Markdown.Parser.parse
|> Result.mapError (\error -> error |> List.map Markdown.Parser.deadEndToString |> String.join "\n")
|> Result.andThen (Markdown.Parser.render renderer)
renderer : Markdown.Parser.Renderer (Element Msg)
renderer =
{ heading = heading
, raw =
Element.paragraph
[ Element.spacing 15 ]
, thematicBreak = Element.none
, plain = Element.text
, bold = \content -> Element.row [ Font.bold ] [ Element.text content ]
, italic = \content -> Element.row [ Font.italic ] [ Element.text content ]
, code = code
, link =
\{ title, destination } body ->
Element.newTabLink
[ Element.htmlAttribute (Html.Attributes.style "display" "inline-flex") ]
{ url = destination
, label =
Element.paragraph
[ Font.color (Element.rgb255 0 0 255)
]
body
}
|> Ok
, image =
\image body ->
Element.image [ Element.width Element.fill ] { src = image.src, description = body }
|> Ok
, list =
\items ->
Element.column [ Element.spacing 15 ]
(items
|> List.map
(\itemBlocks ->
Element.row [ Element.spacing 5 ]
[ Element.el
[ Element.alignTop ]
(Element.text "•")
, itemBlocks
]
)
)
, codeBlock = codeBlock
, html =
Markdown.Html.oneOf
[ Markdown.Html.tag "bio"
(\name photoUrl twitter github dribbble renderedChildren ->
bioView renderedChildren name photoUrl twitter github dribbble
)
|> Markdown.Html.withAttribute "name"
|> Markdown.Html.withAttribute "photo"
|> Markdown.Html.withOptionalAttribute "twitter"
|> Markdown.Html.withOptionalAttribute "github"
|> Markdown.Html.withOptionalAttribute "dribbble"
]
}
bioView renderedChildren name photoUrl twitter github dribbble =
Element.column
[ Element.Border.shadow
{ offset = ( 0.3, 0.3 )
, size = 2
, blur = 0.5
, color = Element.rgba255 0 0 0 0.22
}
, Element.padding 20
, Element.spacing 30
, Element.centerX
, Font.center
]
(Element.row [ Element.spacing 20 ]
[ avatarView photoUrl
, Element.el
[ Font.bold
, Font.size 30
]
(Element.text name)
, icons twitter github dribbble
]
:: renderedChildren
)
icons twitter github dribbble =
Element.row []
([ twitter
|> Maybe.map
(\twitterHandle ->
Element.link []
{ url = "https://twitter.com/" ++ twitterHandle
, label =
Element.image [] { src = "https://i.imgur.com/tXSoThF.png", description = "Twitter Logo" }
}
)
, github
|> Maybe.map
(\twitterHandle ->
Element.link []
{ url = "https://github.com/" ++ twitterHandle
, label =
Element.image [] { src = "https://i.imgur.com/0o48UoR.png", description = "Github Logo" }
}
)
, dribbble
|> Maybe.map
(\dribbbleHandle ->
Element.link []
{ url = "https://dribbble.com/" ++ dribbbleHandle
, label =
Element.image [] { src = "https://i.imgur.com/1AGmwO3.png", description = "Dribbble Logo" }
}
)
]
|> List.filterMap identity
)
avatarView avatarUrl =
Element.image [ Element.width Element.fill ]
{ src = avatarUrl, description = "Avatar image" }
|> Element.el
[ Element.width (Element.px 80) ]
rawTextToId rawText =
rawText
|> String.toLower
|> String.replace " " ""
heading : { level : Int, rawText : String, children : List (Element msg) } -> Element msg
heading { level, rawText, children } =
Element.paragraph
[ Font.size
(case level of
1 ->
36
2 ->
24
_ ->
20
)
, Font.bold
, Font.family [ Font.typeface "Montserrat" ]
, Element.Region.heading level
, Element.htmlAttribute
(Html.Attributes.attribute "name" (rawTextToId rawText))
, Font.center
, Element.htmlAttribute
(Html.Attributes.id (rawTextToId rawText))
]
children
code : String -> Element msg
code snippet =
Element.el
[ Element.Background.color
(Element.rgba 0 0 0 0.04)
, Element.Border.rounded 2
, Element.paddingXY 5 3
, Font.family
[ Font.external
{ url = "https://fonts.googleapis.com/css?family=Source+Code+Pro"
, name = "Source Code Pro"
}
]
]
(Element.text snippet)
codeBlock : { body : String, language : Maybe String } -> Element msg
codeBlock details =
Element.el
[ Element.Background.color (Element.rgba 0 0 0 0.03)
, Element.htmlAttribute (Html.Attributes.style "white-space" "pre")
, Element.padding 20
, Element.width Element.fill
, Font.family
[ Font.external
{ url = "https://fonts.googleapis.com/css?family=Source+Code+Pro"
, name = "Source Code Pro"
}
]
]
(Element.text details.body)
markdownBody =
"""# Custom HTML Renderers
You just render it like this
```
<bio
name="<NAME>"
photo="https://avatars2.githubusercontent.com/u/1384166"
twitter="dillontkearns"
github="dillonkearns"
>
Dillon really likes building things with Elm! Here are some links
- [Articles](https://incrementalelm.com/articles)
</bio>
```
And you get a custom view like this!
<bio
name="<NAME>"
photo="https://avatars2.githubusercontent.com/u/1384166"
twitter="dillontkearns"
github="dillonkearns"
>
Dillon really likes building things with Elm! Here are some links
- [Articles](https://incrementalelm.com/articles)
</bio>
Note that these attributes are all optional. Try removing them and see what happens!
Or you can add `dribbble="something"` and see that icon show up if it's provided.
"""
type Msg
= OnMarkdownInput String
type alias Flags =
()
type alias Model =
String
main : Platform.Program Flags Model Msg
main =
Browser.document
{ init = \flags -> ( markdownBody, Cmd.none )
, view = view
, update = update
, subscriptions = \model -> Sub.none
}
update msg model =
case msg of
OnMarkdownInput newMarkdown ->
( newMarkdown, Cmd.none )
| true | module CustomHtmlBlockSignupForm exposing (main)
import Browser
import Element exposing (Element)
import Element.Background
import Element.Border
import Element.Font as Font
import Element.Input
import Element.Region
import Html exposing (Attribute, Html)
import Html.Attributes
import Markdown.Block exposing (Block, Inline, InlineStyle)
import Markdown.Html
import Markdown.Parser
view : Model -> { title : String, body : List (Html Msg) }
view model =
{ title = "dillonkearns/elm-markdown demo"
, body =
[ Element.layout [ Element.width Element.fill ]
(Element.row [ Element.width Element.fill ]
[ Element.Input.multiline [ Element.width (Element.px 400) ]
{ onChange = OnMarkdownInput
, text = model
, placeholder = Nothing
, label = Element.Input.labelHidden "Markdown input"
, spellcheck = False
}
, case markdownView model of
Ok rendered ->
Element.column
[ Element.spacing 30
, Element.padding 80
, Element.width (Element.fill |> Element.maximum 1000)
, Element.centerX
]
rendered
Err errors ->
Element.text errors
]
)
]
}
markdownView : String -> Result String (List (Element Msg))
markdownView markdown =
markdown
|> Markdown.Parser.parse
|> Result.mapError (\error -> error |> List.map Markdown.Parser.deadEndToString |> String.join "\n")
|> Result.andThen (Markdown.Parser.render renderer)
renderer : Markdown.Parser.Renderer (Element Msg)
renderer =
{ heading = heading
, raw =
Element.paragraph
[ Element.spacing 15 ]
, thematicBreak = Element.none
, plain = Element.text
, bold = \content -> Element.row [ Font.bold ] [ Element.text content ]
, italic = \content -> Element.row [ Font.italic ] [ Element.text content ]
, code = code
, link =
\{ title, destination } body ->
Element.newTabLink
[ Element.htmlAttribute (Html.Attributes.style "display" "inline-flex") ]
{ url = destination
, label =
Element.paragraph
[ Font.color (Element.rgb255 0 0 255)
]
body
}
|> Ok
, image =
\image body ->
Element.image [ Element.width Element.fill ] { src = image.src, description = body }
|> Ok
, list =
\items ->
Element.column [ Element.spacing 15 ]
(items
|> List.map
(\itemBlocks ->
Element.row [ Element.spacing 5 ]
[ Element.el
[ Element.alignTop ]
(Element.text "•")
, itemBlocks
]
)
)
, codeBlock = codeBlock
, html =
Markdown.Html.oneOf
[ Markdown.Html.tag "bio"
(\name photoUrl twitter github dribbble renderedChildren ->
bioView renderedChildren name photoUrl twitter github dribbble
)
|> Markdown.Html.withAttribute "name"
|> Markdown.Html.withAttribute "photo"
|> Markdown.Html.withOptionalAttribute "twitter"
|> Markdown.Html.withOptionalAttribute "github"
|> Markdown.Html.withOptionalAttribute "dribbble"
]
}
bioView renderedChildren name photoUrl twitter github dribbble =
Element.column
[ Element.Border.shadow
{ offset = ( 0.3, 0.3 )
, size = 2
, blur = 0.5
, color = Element.rgba255 0 0 0 0.22
}
, Element.padding 20
, Element.spacing 30
, Element.centerX
, Font.center
]
(Element.row [ Element.spacing 20 ]
[ avatarView photoUrl
, Element.el
[ Font.bold
, Font.size 30
]
(Element.text name)
, icons twitter github dribbble
]
:: renderedChildren
)
icons twitter github dribbble =
Element.row []
([ twitter
|> Maybe.map
(\twitterHandle ->
Element.link []
{ url = "https://twitter.com/" ++ twitterHandle
, label =
Element.image [] { src = "https://i.imgur.com/tXSoThF.png", description = "Twitter Logo" }
}
)
, github
|> Maybe.map
(\twitterHandle ->
Element.link []
{ url = "https://github.com/" ++ twitterHandle
, label =
Element.image [] { src = "https://i.imgur.com/0o48UoR.png", description = "Github Logo" }
}
)
, dribbble
|> Maybe.map
(\dribbbleHandle ->
Element.link []
{ url = "https://dribbble.com/" ++ dribbbleHandle
, label =
Element.image [] { src = "https://i.imgur.com/1AGmwO3.png", description = "Dribbble Logo" }
}
)
]
|> List.filterMap identity
)
avatarView avatarUrl =
Element.image [ Element.width Element.fill ]
{ src = avatarUrl, description = "Avatar image" }
|> Element.el
[ Element.width (Element.px 80) ]
rawTextToId rawText =
rawText
|> String.toLower
|> String.replace " " ""
heading : { level : Int, rawText : String, children : List (Element msg) } -> Element msg
heading { level, rawText, children } =
Element.paragraph
[ Font.size
(case level of
1 ->
36
2 ->
24
_ ->
20
)
, Font.bold
, Font.family [ Font.typeface "Montserrat" ]
, Element.Region.heading level
, Element.htmlAttribute
(Html.Attributes.attribute "name" (rawTextToId rawText))
, Font.center
, Element.htmlAttribute
(Html.Attributes.id (rawTextToId rawText))
]
children
code : String -> Element msg
code snippet =
Element.el
[ Element.Background.color
(Element.rgba 0 0 0 0.04)
, Element.Border.rounded 2
, Element.paddingXY 5 3
, Font.family
[ Font.external
{ url = "https://fonts.googleapis.com/css?family=Source+Code+Pro"
, name = "Source Code Pro"
}
]
]
(Element.text snippet)
codeBlock : { body : String, language : Maybe String } -> Element msg
codeBlock details =
Element.el
[ Element.Background.color (Element.rgba 0 0 0 0.03)
, Element.htmlAttribute (Html.Attributes.style "white-space" "pre")
, Element.padding 20
, Element.width Element.fill
, Font.family
[ Font.external
{ url = "https://fonts.googleapis.com/css?family=Source+Code+Pro"
, name = "Source Code Pro"
}
]
]
(Element.text details.body)
markdownBody =
"""# Custom HTML Renderers
You just render it like this
```
<bio
name="PI:NAME:<NAME>END_PI"
photo="https://avatars2.githubusercontent.com/u/1384166"
twitter="dillontkearns"
github="dillonkearns"
>
Dillon really likes building things with Elm! Here are some links
- [Articles](https://incrementalelm.com/articles)
</bio>
```
And you get a custom view like this!
<bio
name="PI:NAME:<NAME>END_PI"
photo="https://avatars2.githubusercontent.com/u/1384166"
twitter="dillontkearns"
github="dillonkearns"
>
Dillon really likes building things with Elm! Here are some links
- [Articles](https://incrementalelm.com/articles)
</bio>
Note that these attributes are all optional. Try removing them and see what happens!
Or you can add `dribbble="something"` and see that icon show up if it's provided.
"""
type Msg
= OnMarkdownInput String
type alias Flags =
()
type alias Model =
String
main : Platform.Program Flags Model Msg
main =
Browser.document
{ init = \flags -> ( markdownBody, Cmd.none )
, view = view
, update = update
, subscriptions = \model -> Sub.none
}
update msg model =
case msg of
OnMarkdownInput newMarkdown ->
( newMarkdown, Cmd.none )
| elm |
[
{
"context": " ++ firstname\n in\n \"Olla, Anna\"\n |> Expect.equal (directoryNa",
"end": 3185,
"score": 0.9706062078,
"start": 3175,
"tag": "NAME",
"value": "Olla, Anna"
},
{
"context": " |> Expect.equal (directoryName { firstname = \"Anna\", surname = \"Olla\" })\n , test \"more comple",
"end": 3257,
"score": 0.9995682836,
"start": 3253,
"tag": "NAME",
"value": "Anna"
},
{
"context": "l (directoryName { firstname = \"Anna\", surname = \"Olla\" })\n , test \"more complex structures can a",
"end": 3275,
"score": 0.9990380406,
"start": 3271,
"tag": "NAME",
"value": "Olla"
},
{
"context": " in\n \"Car: ABC-123 to Doe, John\"\n |> Expect.equal (sales",
"end": 3864,
"score": 0.9981396794,
"start": 3861,
"tag": "NAME",
"value": "Doe"
},
{
"context": " in\n \"Car: ABC-123 to Doe, John\"\n |> Expect.equal (salesRecord",
"end": 3870,
"score": 0.9811830521,
"start": 3866,
"tag": "NAME",
"value": "John"
},
{
"context": "ut <| SoldToPerson (Car \"ABC-123\") { firstname = \"John\", surname = \"Doe\" })\n ]\n",
"end": 3980,
"score": 0.9983936548,
"start": 3976,
"tag": "NAME",
"value": "John"
},
{
"context": " (Car \"ABC-123\") { firstname = \"John\", surname = \"Doe\" })\n ]\n",
"end": 3997,
"score": 0.9985556006,
"start": 3994,
"tag": "NAME",
"value": "Doe"
}
] | tests/Koans21AboutPatternMatching.elm | alexandru-calinoiu/elm-koans | 0 | module Koans21AboutPatternMatching exposing (testSuite)
import Expect
import Utils.Blank exposing (..)
import Utils.Test exposing (describe, test)
type Vehicle
= Car String -- license plate
| Motorbike String -- license plate
| Bycicle
type alias Person =
{ firstname : String
, surname : String
}
type alias Company =
{ name : String
, taxId : String
}
type SalesRecord
= SoldToPerson Vehicle Person
| SoldToCompany Vehicle Company
testSuite =
describe "About PatternMatching"
[ test "variables we do not care about are marked with wildcard notation '_'" <|
\() ->
let
realAnswerTo : a -> Int
realAnswerTo _ =
42
in
42
|> Expect.equal (realAnswerTo [ "life", "universe", "everything" ])
, test "integers can be matched (floats are not recommended)" <|
\() ->
let
isZero : Int -> Bool
isZero i =
case i of
0 ->
True
_ ->
False
in
False
|> Expect.equal (isZero -1)
, test "strings can be matched" <|
\() ->
let
isCool : String -> Bool
isCool s =
case s of
"cool" ->
True
_ ->
False
in
True
|> Expect.equal (isCool "cool")
, test
"list head can be matched separately from the rest"
<|
\() ->
let
sizeOfList : List a -> Int
sizeOfList list =
case list of
_ :: rest ->
1 + sizeOfList rest
[] ->
0
in
2
|> Expect.equal (sizeOfList [ 1, 2 ])
, test "Union types can be pattern matched" <|
\() ->
let
licensePlate : Vehicle -> Maybe String
licensePlate vehicle =
case vehicle of
Car lp ->
Just lp
Motorbike lp ->
Just lp
Bycicle ->
Nothing
in
Just "MZ/X"
|> Expect.equal (licensePlate (Motorbike "MZ/X"))
, test "Records can be pattern matched" <|
\() ->
let
directoryName : Person -> String
directoryName { firstname, surname } =
surname ++ ", " ++ firstname
in
"Olla, Anna"
|> Expect.equal (directoryName { firstname = "Anna", surname = "Olla" })
, test "more complex structures can also be matched" <|
\() ->
let
salesRecordPrintout : SalesRecord -> String
salesRecordPrintout salesRecord =
case salesRecord of
SoldToPerson (Car licensePlate) { firstname, surname } ->
"Car: " ++ licensePlate ++ " to " ++ surname ++ ", " ++ firstname
_ ->
"do not care"
in
"Car: ABC-123 to Doe, John"
|> Expect.equal (salesRecordPrintout <| SoldToPerson (Car "ABC-123") { firstname = "John", surname = "Doe" })
]
| 49113 | module Koans21AboutPatternMatching exposing (testSuite)
import Expect
import Utils.Blank exposing (..)
import Utils.Test exposing (describe, test)
type Vehicle
= Car String -- license plate
| Motorbike String -- license plate
| Bycicle
type alias Person =
{ firstname : String
, surname : String
}
type alias Company =
{ name : String
, taxId : String
}
type SalesRecord
= SoldToPerson Vehicle Person
| SoldToCompany Vehicle Company
testSuite =
describe "About PatternMatching"
[ test "variables we do not care about are marked with wildcard notation '_'" <|
\() ->
let
realAnswerTo : a -> Int
realAnswerTo _ =
42
in
42
|> Expect.equal (realAnswerTo [ "life", "universe", "everything" ])
, test "integers can be matched (floats are not recommended)" <|
\() ->
let
isZero : Int -> Bool
isZero i =
case i of
0 ->
True
_ ->
False
in
False
|> Expect.equal (isZero -1)
, test "strings can be matched" <|
\() ->
let
isCool : String -> Bool
isCool s =
case s of
"cool" ->
True
_ ->
False
in
True
|> Expect.equal (isCool "cool")
, test
"list head can be matched separately from the rest"
<|
\() ->
let
sizeOfList : List a -> Int
sizeOfList list =
case list of
_ :: rest ->
1 + sizeOfList rest
[] ->
0
in
2
|> Expect.equal (sizeOfList [ 1, 2 ])
, test "Union types can be pattern matched" <|
\() ->
let
licensePlate : Vehicle -> Maybe String
licensePlate vehicle =
case vehicle of
Car lp ->
Just lp
Motorbike lp ->
Just lp
Bycicle ->
Nothing
in
Just "MZ/X"
|> Expect.equal (licensePlate (Motorbike "MZ/X"))
, test "Records can be pattern matched" <|
\() ->
let
directoryName : Person -> String
directoryName { firstname, surname } =
surname ++ ", " ++ firstname
in
"<NAME>"
|> Expect.equal (directoryName { firstname = "<NAME>", surname = "<NAME>" })
, test "more complex structures can also be matched" <|
\() ->
let
salesRecordPrintout : SalesRecord -> String
salesRecordPrintout salesRecord =
case salesRecord of
SoldToPerson (Car licensePlate) { firstname, surname } ->
"Car: " ++ licensePlate ++ " to " ++ surname ++ ", " ++ firstname
_ ->
"do not care"
in
"Car: ABC-123 to <NAME>, <NAME>"
|> Expect.equal (salesRecordPrintout <| SoldToPerson (Car "ABC-123") { firstname = "<NAME>", surname = "<NAME>" })
]
| true | module Koans21AboutPatternMatching exposing (testSuite)
import Expect
import Utils.Blank exposing (..)
import Utils.Test exposing (describe, test)
type Vehicle
= Car String -- license plate
| Motorbike String -- license plate
| Bycicle
type alias Person =
{ firstname : String
, surname : String
}
type alias Company =
{ name : String
, taxId : String
}
type SalesRecord
= SoldToPerson Vehicle Person
| SoldToCompany Vehicle Company
testSuite =
describe "About PatternMatching"
[ test "variables we do not care about are marked with wildcard notation '_'" <|
\() ->
let
realAnswerTo : a -> Int
realAnswerTo _ =
42
in
42
|> Expect.equal (realAnswerTo [ "life", "universe", "everything" ])
, test "integers can be matched (floats are not recommended)" <|
\() ->
let
isZero : Int -> Bool
isZero i =
case i of
0 ->
True
_ ->
False
in
False
|> Expect.equal (isZero -1)
, test "strings can be matched" <|
\() ->
let
isCool : String -> Bool
isCool s =
case s of
"cool" ->
True
_ ->
False
in
True
|> Expect.equal (isCool "cool")
, test
"list head can be matched separately from the rest"
<|
\() ->
let
sizeOfList : List a -> Int
sizeOfList list =
case list of
_ :: rest ->
1 + sizeOfList rest
[] ->
0
in
2
|> Expect.equal (sizeOfList [ 1, 2 ])
, test "Union types can be pattern matched" <|
\() ->
let
licensePlate : Vehicle -> Maybe String
licensePlate vehicle =
case vehicle of
Car lp ->
Just lp
Motorbike lp ->
Just lp
Bycicle ->
Nothing
in
Just "MZ/X"
|> Expect.equal (licensePlate (Motorbike "MZ/X"))
, test "Records can be pattern matched" <|
\() ->
let
directoryName : Person -> String
directoryName { firstname, surname } =
surname ++ ", " ++ firstname
in
"PI:NAME:<NAME>END_PI"
|> Expect.equal (directoryName { firstname = "PI:NAME:<NAME>END_PI", surname = "PI:NAME:<NAME>END_PI" })
, test "more complex structures can also be matched" <|
\() ->
let
salesRecordPrintout : SalesRecord -> String
salesRecordPrintout salesRecord =
case salesRecord of
SoldToPerson (Car licensePlate) { firstname, surname } ->
"Car: " ++ licensePlate ++ " to " ++ surname ++ ", " ++ firstname
_ ->
"do not care"
in
"Car: ABC-123 to PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI"
|> Expect.equal (salesRecordPrintout <| SoldToPerson (Car "ABC-123") { firstname = "PI:NAME:<NAME>END_PI", surname = "PI:NAME:<NAME>END_PI" })
]
| elm |
[
{
"context": "\n\n_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/E",
"end": 1979,
"score": 0.9997286797,
"start": 1972,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": "Chart Result\" width=\"540\" src=\"https://github.com/terezka/line-charts/blob/master/images/linechart1.png?raw",
"end": 2604,
"score": 0.9995921254,
"start": 2597,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": "\n\n_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/E",
"end": 2724,
"score": 0.9997053742,
"start": 2717,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": "Chart Result\" width=\"540\" src=\"https://github.com/terezka/line-charts/blob/master/images/linechart2.png?raw",
"end": 3721,
"score": 0.9996814132,
"start": 3714,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": "\n\n_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/E",
"end": 3841,
"score": 0.9996829033,
"start": 3834,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": "g\n chart =\n Chart.Lines.view3 .age .weight alice bob chuck\n\n\n<img alt=\"Chart Result\" width=\"540\" s",
"end": 4248,
"score": 0.815962553,
"start": 4243,
"tag": "NAME",
"value": "alice"
},
{
"context": "chart =\n Chart.Lines.view3 .age .weight alice bob chuck\n\n\n<img alt=\"Chart Result\" width=\"540\" src=\"",
"end": 4252,
"score": 0.6037599444,
"start": 4249,
"tag": "NAME",
"value": "bob"
},
{
"context": "Chart Result\" width=\"540\" src=\"https://github.com/terezka/line-charts/blob/master/images/linechart3.png?raw",
"end": 4328,
"score": 0.9990300536,
"start": 4321,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": "\n\n_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/E",
"end": 4448,
"score": 0.9996866584,
"start": 4441,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": " [ Chart.Lines.line Colors.purple Dots.cross \"Alice\" alice\n , Chart.Lines.line Colors.blue Dot",
"end": 5094,
"score": 0.7347643971,
"start": 5089,
"tag": "NAME",
"value": "Alice"
},
{
"context": " Chart.Lines.line Colors.purple Dots.cross \"Alice\" alice\n , Chart.Lines.line Colors.blue Dots.squar",
"end": 5101,
"score": 0.522089839,
"start": 5096,
"tag": "NAME",
"value": "alice"
},
{
"context": " , Chart.Lines.line Colors.blue Dots.square \"Bobby\" bobby\n , Chart.Lines.line Colors.cyan Dot",
"end": 5159,
"score": 0.8616448641,
"start": 5154,
"tag": "NAME",
"value": "Bobby"
},
{
"context": ", Chart.Lines.line Colors.blue Dots.square \"Bobby\" bobby\n , Chart.Lines.line Colors.cyan Dots.circl",
"end": 5166,
"score": 0.7515918016,
"start": 5161,
"tag": "NAME",
"value": "bobby"
},
{
"context": "Chart Result\" width=\"540\" src=\"https://github.com/terezka/line-charts/blob/master/images/linechart4.png?raw",
"end": 5311,
"score": 0.9996740222,
"start": 5304,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": "\n\n_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/E",
"end": 5431,
"score": 0.9996548295,
"start": 5424,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": "\n Chart.Lines.line Colors.purple Dots.cross \"Alice\" alice\n\n\n dashedLine : Chart.Lines.Series Huma",
"end": 6082,
"score": 0.9958518744,
"start": 6077,
"tag": "NAME",
"value": "Alice"
},
{
"context": " Chart.Lines.line Colors.purple Dots.cross \"Alice\" alice\n\n\n dashedLine : Chart.Lines.Series Human\n d",
"end": 6089,
"score": 0.9838433862,
"start": 6084,
"tag": "NAME",
"value": "alice"
},
{
"context": " [ Chart.Lines.line Colors.pinkLight Dots.plus \"Alice\" alice\n , Chart.Lines.line Colors.goldLigh",
"end": 6542,
"score": 0.9939135909,
"start": 6537,
"tag": "NAME",
"value": "Alice"
},
{
"context": "hart.Lines.line Colors.pinkLight Dots.plus \"Alice\" alice\n , Chart.Lines.line Colors.goldLight Dots.",
"end": 6549,
"score": 0.8797275424,
"start": 6544,
"tag": "NAME",
"value": "alice"
},
{
"context": ", Chart.Lines.line Colors.goldLight Dots.diamond \"Bobby\" bobby\n , Chart.Lines.line Colors.blueLigh",
"end": 6613,
"score": 0.9698876143,
"start": 6608,
"tag": "NAME",
"value": "Bobby"
},
{
"context": "Chart Result\" width=\"540\" src=\"https://github.com/terezka/line-charts/blob/master/images/linechart7.png?raw",
"end": 6769,
"score": 0.9995161891,
"start": 6762,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": "\n\n_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/E",
"end": 6889,
"score": 0.9116525054,
"start": 6882,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": " [ Chart.Lines.line Colors.pinkLight Dots.plus \"Alice\" alice\n , Chart.Lines.line Colors.goldLigh",
"end": 7858,
"score": 0.7468160987,
"start": 7853,
"tag": "NAME",
"value": "Alice"
},
{
"context": ", Chart.Lines.line Colors.goldLight Dots.diamond \"Bobby\" bobby\n , Chart.Lines.line Colors.blueLigh",
"end": 7929,
"score": 0.651093781,
"start": 7924,
"tag": "NAME",
"value": "Bobby"
},
{
"context": "Chart Result\" width=\"540\" src=\"https://github.com/terezka/line-charts/blob/master/images/linechart5.png?raw",
"end": 8406,
"score": 0.9974554181,
"start": 8399,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": "\n\n_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/E",
"end": 8526,
"score": 0.9970749021,
"start": 8519,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": "examples._\n\n - **junk**: Gets its name from\n [Edward Tufte's concept of \"chart junk\"](https://en.wikipedia.o",
"end": 11221,
"score": 0.9952233434,
"start": 11209,
"tag": "NAME",
"value": "Edward Tufte"
},
{
"context": "\n\n_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/E",
"end": 12231,
"score": 0.9957055449,
"start": 12224,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": " , Chart.Lines.line Colors.pinkLight Dots.plus \"Alice\" alice\n , Chart.Lines.line Colors.goldLigh",
"end": 13215,
"score": 0.9509583712,
"start": 13210,
"tag": "NAME",
"value": "Alice"
},
{
"context": ", Chart.Lines.line Colors.goldLight Dots.diamond \"Bobby\" bobby\n ]\n\n chartConfig : Config Info m",
"end": 13286,
"score": 0.9923607707,
"start": 13281,
"tag": "NAME",
"value": "Bobby"
},
{
"context": "Chart Result\" width=\"540\" src=\"https://github.com/terezka/line-charts/blob/master/images/linechart6.png?raw",
"end": 13902,
"score": 0.9995973706,
"start": 13895,
"tag": "USERNAME",
"value": "terezka"
},
{
"context": "\n\n_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/E",
"end": 14022,
"score": 0.9994090199,
"start": 14015,
"tag": "USERNAME",
"value": "terezka"
}
] | src/LineChart.elm | terezka/elm-charts-alpha | 7 | module LineChart exposing
( view1, view2, view3
, view, Series, line, plain, dashed
, viewCustom, Config
)
{-|
## Table of contents
### Quick start
- [view1](#view1) for visualizing a single data series.
- [view2](#view2) for visualizing two data series.
- [view3](#view3) for visualizing three data series.
### Customizing lines
- [view](#view) for visualizing *any* amount of data series.
- [line](#line) for configuring color, dot etc. of a line representing a data series.
- [dash](#dash) for configuring color, dot etc. of a *dashed* line representing a data series.
### Customizing everything
- [viewCustom](#viewCustom) for configuring any other aspect of the chart (axis, area, etc.).
# Quick start
@docs view1, view2, view3
# Customizing lines
@docs view, Series, line, plain, dashed
# Customizing everything
@docs viewCustom, Config
-}
import Html
import Svg
import Chart.Junk as Junk
import Chart.Area as Area
import Chart.Axis as Axis
import Chart.Axis.Unit as Unit
import Chart.Dot as Dots
import Chart.Grid as Grid
import Chart.Line as Line
import Chart.Colors as Colors
import Chart.Events as Events
import Chart.Element as Element
import Chart.Legends as Legends
import Chart.Container as Container
import Chart.Interpolation as Interpolation
import Chart.Axis.Intersection as Intersection
import Internal.Chart
import Internal.Area
import Internal.Axis
import Internal.Junk
import Internal.Line
import Internal.Element
import Internal.Events
import Internal.Container
import Internal.Axis.Range
import Internal.Orientation
import Internal.Svg as Svg
import Internal.Point as Point
import Internal.Utils as Utils
import Internal.Coordinate as Coordinate
import Color
-- VIEW / SIMPLE
{-|
** Show a line chart **
type alias Point =
{ x : Float, y : Float }
chart : Html msg
chart =
Chart.Lines.view1 .x .y
[ Point 0 2, Point 5 5, Point 10 10 ]
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example1.elm)._
** Choosing your variables **
Notice that we provide `.x` and `.y` to specify which data we want to show.
So if we had more complex data structures, like a human with an `age`, `weight`,
`height`, and `income`, we can easily pick which two properties we want to plot:
chart : Html msg
chart =
Chart.Lines.view1 .age .weight
[ Human 4 24 0.94 0
, Human 25 75 1.73 25000
, Human 43 83 1.75 40000
]
-- Try changing .weight to .height
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart1.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example2.elm)._
** Use any function to determine inputs **
Rather than using data like `.weight` directly, you can make a
function like `bmi human = human.weight / human.height ^ 2` and create a
chart of `.age` vs `bmi`. This allows you to keep your data set nice and minimal!
** The whole chart is just a function **
`view1` is just a function, so it will update as your data changes.
If you get more data points or some data points are changed, the chart
refreshes automatically!
-}
view1 : (data -> Float) -> (data -> Float) -> List data -> Svg.Svg msg
view1 toX toY dataset =
view toX toY <| defaultLines [ dataset ]
{-|
** Show a line chart with two lines **
Say you have two humans and you would like to see how their weight relates
to their age. Here's how you could plot it.
chart : Html msg
chart =
Chart.Lines.view2 .age .weight alice chuck
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart2.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example3.elm)._
-}
view2 : (data -> Float) -> (data -> Float) -> List data -> List data -> Svg.Svg msg
view2 toX toY dataset1 dataset2 =
view toX toY <| defaultLines [ dataset1, dataset2 ]
{-|
** Show a line chart with three lines **
It works just like `view1` and `view2`.
chart : Html msg
chart =
Chart.Lines.view3 .age .weight alice bob chuck
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart3.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example4.elm)._
But what if you have more people? What if you have _four_ people?! In that case,
check out `view`.
-}
view3 : (data -> Float) -> (data -> Float) -> List data -> List data -> List data -> Svg.Svg msg
view3 toX toY dataset1 dataset2 dataset3 =
view toX toY <| defaultLines [ dataset1, dataset2, dataset3 ]
-- VIEW
{-|
** Show any amount of lines **
If you want to change the color, the dot, or the title of a line, then see
the `line` function.
chart : Html msg
chart =
Chart.Lines.view .age .height
[ Chart.Lines.line Colors.purple Dots.cross "Alice" alice
, Chart.Lines.line Colors.blue Dots.square "Bobby" bobby
, Chart.Lines.line Colors.cyan Dots.circle "Chuck" chuck
]
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart4.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example5.elm)._
See `viewCustom` for all other customizations.
-}
view : (data -> Float) -> (data -> Float) -> List (Series data) -> Svg.Svg msg
view toX toY =
viewCustom (defaultConfig toX toY)
{-| This type represents the visual configuration of a _series_ of data.
Definition of _series_:
> a number of events, objects, or people of a similar or related kind coming one after another.
** Examples of customizations **
See the `line` and `dash` functions for more information!
solidLine : Chart.Lines.Series Human
solidLine =
Chart.Lines.line Colors.purple Dots.cross "Alice" alice
dashedLine : Chart.Lines.Series Human
dashedLine =
Chart.Lines.dash Colors.purpleLight Dots.none "Average" [ 4, 2 ] average
-}
type alias Series data =
Internal.Line.Series data
{-|
** Customize a solid line **
Try changing the color or explore all the available dot shapes from `Chart.Lines.Dot`!
chart : Html msg
chart =
Chart.Lines.view .age .weight
[ Chart.Lines.line Colors.pinkLight Dots.plus "Alice" alice
, Chart.Lines.line Colors.goldLight Dots.diamond "Bobby" bobby
, Chart.Lines.line Colors.blueLight Dots.square "Chuck" chuck
]
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart7.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example6.elm)._
** Regarding the title **
The string title will show up in the legends. If you are interested in
customizing your legends, dot size or line width, check out `viewCustom`.
-}
line : Color.Color -> Dots.Shape -> String -> List data -> Series data
line =
Internal.Line.line
{-| -}
plain : Color.Color -> String -> List data -> Series data
plain =
Internal.Line.plain
{-|
** Customize a dashed line **
Works just like `line`, except it takes another argument which is an array of
floats describing your dashing pattern. I recommend typing in random numbers and seeing what
happens, but you alternativelly you can see the SVG `stroke-dasharray`
[documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray)
for examples of patterns.
chart : Html msg
chart =
Chart.Lines.view .age .height
[ Chart.Lines.line Colors.pinkLight Dots.plus "Alice" alice
, Chart.Lines.line Colors.goldLight Dots.diamond "Bobby" bobby
, Chart.Lines.line Colors.blueLight Dots.square "Chuck" chuck
, dashedLine
]
dashedLine : Chart.Lines.Series Human
dashedLine =
Chart.Lines.dashed Colors.purpleLight Dots.none "Average" [ 4, 2 ] average
-- ^^^^^^^^
-- (Scroll to the left to see the pattern!)
-- Try passing different numbers!
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart5.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example7.elm)._
** When should I use a dashed line? **
Dashed lines are especially good for visualizing processed data like
averages or predicted values.
-}
dashed : Color.Color -> String -> List Float -> List data -> Series data
dashed =
Internal.Line.dashed
-- VIEW / CUSTOM
{-|
** Available customizations **
Use with `viewCustom`.
- **x**: Customizes your horizontal axis.</br>
_See [`Chart.Axis`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Axis) for more information and examples._
- **y**: Customizes your vertical axis.</br>
_See [`Chart.Axis`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Axis) for more information and examples._
- **intersection**: Determines where your axes meet.</br>
_See [`Chart.Axis.Intersection`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Axis-Intersection) for more information and examples._
- **interpolation**: Customizes the curve of your Chart.</br>
_See [`Chart.Interpolation`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Interpolation) for more information and examples._
- **container**: Customizes the container of your chart.</br>
_See [`Chart.Container`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Container) for more information and examples._
- **legends**: Customizes your chart's legends.</br>
_See [`Chart.Legends`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Legends) for more information and examples._
- **events**: Customizes your chart's events, allowing you to easily
make your chart interactive (adding tooltips, selection states etc.).</br>
_See [`Chart.Events`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Events) for more information and examples._
- **grid**: Customizes the style of your grid.</br>
_See [`Chart.Grid`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Grid) for more information and examples._
- **area**: Customizes the area under your line.</br>
_See [`Chart.Area`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Area) for more information and examples._
- **line**: Customizes your lines' width and color.</br>
_See [`Chart.Line`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Line) for more information and examples._
- **dots**: Customizes your dots' size and style.</br>
_See `Chart.Dot` for more information and examples._
- **junk**: Gets its name from
[Edward Tufte's concept of "chart junk"](https://en.wikipedia.org/wiki/Chartjunk).
Here you are finally allowed set your creativity loose and add whatever
SVG or HTML fun you can imagine.</br>
_See [`Chart.Junk`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart.Junk) for more information and examples._
** Example configuration **
A good start would be to copy it and play around with customizations
available for each property.
chartConfig : Config Info msg
chartConfig =
{ y = Axis.default 400 "Age" .age
, x = Axis.default 700 "Weight" .weight
, container = Container.default "line-chart-1"
, interpolation = Interpolation.default
, intersection = Intersection.default
, legends = Legends.default
, events = Events.default
, junk = Junk.default
, grid = Grid.default
, area = Area.default
, line = Line.default
, dots = Dots.default
}
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example8.elm)._
-}
type alias Config data msg =
{ x : Axis.Config Float data msg
, y : Axis.Config (Maybe Float) data msg
, container : Container.Config msg
, intersection : Intersection.Config
, interpolation : Interpolation.Config
, legends : Legends.Config msg
, events : Events.Config Element.LineDot data msg
, area : Area.Config
, grid : Grid.Config
, line : Line.Config data
, dots : Dots.Config data
, junk : Junk.Config Element.LineDot msg
}
{-|
** Customize everything **
See the `Config` type for information about the available customizations.
Or copy and play with the example below. No one will tell.
** Example customiztion **
The example below makes the line chart an area chart.
chart : Html msg
chart =
Chart.Lines.viewCustom chartConfig
[ Chart.Lines.line Colors.blueLight Dots.square "Chuck" chuck
, Chart.Lines.line Colors.pinkLight Dots.plus "Alice" alice
, Chart.Lines.line Colors.goldLight Dots.diamond "Bobby" bobby
]
chartConfig : Config Info msg
chartConfig =
{ y = Axis.default 400 "Age" .age
, x = Axis.default 700 "Weight" .weight
, container = Container.default "line-chart-1"
, interpolation = Interpolation.default
, intersection = Intersection.default
, legends = Legends.default
, events = Events.default
, junk = Junk.default
, grid = Grid.default
, area = Area.stacked 0.5 -- Changed from the default!
, line = Line.default
, dots = Dots.default
}
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart6.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example9.elm)._
** Speaking of area charts **
Remember that area charts are for data where the area under the curve _matters_.
Typically, this would be when you have a quantity accumulating over time.
Think profit over time or velocity over time!
In the case of profit over time, the area under the curve shows the total amount
of money earned in that time frame.<br/>
If the that total amount is not important for the relationship you're
trying to visualize, it's best to leave it out!
-}
viewCustom : Config data msg -> List (Series data) -> Html.Html msg
viewCustom config series =
let
-- Data / System
data = toDataPoints config series
dataSafe = List.map (List.filter (Internal.Element.isReal << .element)) data
dataAll = List.concat data
dataAllSafe = List.concat dataSafe
system = toSystem config dataAllSafe
-- View
viewLines =
Internal.Line.view
{ system = system
, interpolation = config.interpolation
, dotsConfig = config.dots
, lineConfig = config.line
, area = config.area
}
viewLegends =
{ system = system
, config = config.legends
, defaults = { width = 30, offsetY = 10 }
, legends = \width ->
let legend serie data_ =
{ sample = Internal.Line.viewSample config.dots config.line config.area system serie data_ width
, label = Internal.Line.label serie
}
in List.map2 legend series dataSafe
}
in
Internal.Chart.view
{ container = config.container
, events = config.events
, defs = []
, grid = config.grid
, series = viewLines series data
, intersection = config.intersection
, horizontalAxis = config.x
, verticalAxis = config.y
, legends = viewLegends
, trends = Svg.text ""
, junk =
Internal.Junk.getLayers
{ orientation = Internal.Orientation.Vertical
, independent = Internal.Axis.title config.x
, dependent = Internal.Axis.title config.y
, offsetOne = 15
, offsetMany = 15
}
system
config.junk
, orientation = Internal.Orientation.Vertical
}
dataAll
system
-- INTERNAL
toDataPoints : Config data msg -> List (Series data) -> List (List (Point.Point Element.LineDot data))
toDataPoints config series =
let
data =
List.indexedMap eachSerie series
eachSerie seriesIndex serie =
List.map (eachDatum seriesIndex serie) (Internal.Line.data serie)
eachDatum seriesIndex serie datum =
case ( Internal.Axis.variable config.x datum, Internal.Axis.variable config.y datum ) of
( x, Just y ) ->
{ source = datum
, coordinates = Coordinate.Point x y
, element =
{ element = Internal.Element.lineDot True
, label = Internal.Line.label serie
, color = Internal.Line.colorBase serie
, independent = Internal.Axis.unit config.x x
, dependent = Internal.Axis.unit config.y y
, seriesIndex = seriesIndex
}
}
( x, Nothing ) ->
{ source = datum
, coordinates = Coordinate.Point x 0
, element =
{ element = Internal.Element.lineDot False
, label = Internal.Line.label serie
, color = Internal.Line.colorBase serie
, independent = Internal.Axis.unit config.x x
, dependent = "-"
, seriesIndex = seriesIndex
}
}
in
case config.area of
Internal.Area.None -> data
Internal.Area.Normal _ -> data
Internal.Area.Stacked _ -> stack data
Internal.Area.Percentage _ -> data -- TODO Not used
stack : List (List (Point.Point Element.LineDot data)) -> List (List (Point.Point Element.LineDot data))
stack dataset =
let
stackBelows dataset_ result =
case dataset_ of
data :: belows ->
stackBelows belows <|
List.foldl addBelows data belows :: result
[] ->
result
in
List.reverse (stackBelows dataset [])
addBelows : List (Point.Point Element.LineDot data) -> List (Point.Point Element.LineDot data) -> List (Point.Point Element.LineDot data)
addBelows alldata dataBelowAll =
let
iterate datum0 dataTop dataBelowTop result =
case ( dataTop, dataBelowTop ) of
( datum1 :: data, datumBelow :: dataBelow ) ->
-- if the data point is after the point below, add it
if datum1.coordinates.x > datumBelow.coordinates.x
then
if Internal.Element.isReal datumBelow.element then
iterate datum0 (datum1 :: data) dataBelow (add datumBelow datum0 :: result)
else
iterate datum0 (datum1 :: data) dataBelow (add datumBelow datum0 :: result)
-- if not, try the next
else iterate datum1 data (datumBelow :: dataBelow) result
( [], datumBelow :: dataBelow ) ->
-- if the data point is after the point below, add it
if datum0.coordinates.x <= datumBelow.coordinates.x
then iterate datum0 [] dataBelow (add datumBelow datum0 :: result)
-- if not, try the next
else iterate datum0 [] dataBelow (datumBelow :: result)
( datum1 :: data, [] ) ->
result
( [], [] ) ->
result
add below datum =
setY below (below.coordinates.y + datum.coordinates.y)
in
List.reverse <| Maybe.withDefault [] <| Utils.withFirst alldata <| \first rest ->
iterate first rest dataBelowAll []
setY : Point.Point Element.LineDot data -> Float -> Point.Point Element.LineDot data
setY datum y =
{ datum | coordinates = Coordinate.Point datum.coordinates.x y }
toSystem : Config data msg -> List (Point.Point Element.LineDot data) -> Coordinate.System
toSystem config data =
let
container = Internal.Container.properties identity config.container
hasArea = Internal.Area.hasArea config.area
frame = Coordinate.frame container.margin container.size.width container.size.height
xRange = Coordinate.range (.coordinates >> .x) data
yRange = Coordinate.range (.coordinates >> .y) data
system =
{ frame = frame
, x = xRange
, y = adjustDomainRange yRange
, xData = xRange
, yData = yRange
, id = container.id
}
adjustDomainRange domain =
if hasArea
then Coordinate.ground domain
else domain
in
{ system
| x = Internal.Axis.Range.applyX (Internal.Axis.range config.x) system
, y = Internal.Axis.Range.applyY (Internal.Axis.range config.y) system
}
-- INTERNAL / DEFAULTS
defaultConfig : (data -> Float) -> (data -> Float) -> Config data msg
defaultConfig toX toY =
{ x = Axis.default "" Unit.none toX
, y = Axis.default "" Unit.none (Just << toY)
, container = Container.default "line-chart-1" 700 400
, interpolation = Interpolation.default
, intersection = Intersection.default
, legends = Legends.default
, events = Events.default
, junk = Junk.default
, grid = Grid.default
, area = Area.default
, line = Line.default
, dots = Dots.default
}
defaultLines : List (List data) -> List (Series data)
defaultLines =
List.map4 Internal.Line.line defaultColors defaultShapes defaultLabel
defaultColors : List Color.Color
defaultColors =
[ Colors.pink
, Colors.blue
, Colors.gold
]
defaultShapes : List Dots.Shape
defaultShapes =
[ Dots.circle
, Dots.triangle
, Dots.cross
]
defaultLabel : List String
defaultLabel =
[ "First"
, "Second"
, "Third"
]
| 29319 | module LineChart exposing
( view1, view2, view3
, view, Series, line, plain, dashed
, viewCustom, Config
)
{-|
## Table of contents
### Quick start
- [view1](#view1) for visualizing a single data series.
- [view2](#view2) for visualizing two data series.
- [view3](#view3) for visualizing three data series.
### Customizing lines
- [view](#view) for visualizing *any* amount of data series.
- [line](#line) for configuring color, dot etc. of a line representing a data series.
- [dash](#dash) for configuring color, dot etc. of a *dashed* line representing a data series.
### Customizing everything
- [viewCustom](#viewCustom) for configuring any other aspect of the chart (axis, area, etc.).
# Quick start
@docs view1, view2, view3
# Customizing lines
@docs view, Series, line, plain, dashed
# Customizing everything
@docs viewCustom, Config
-}
import Html
import Svg
import Chart.Junk as Junk
import Chart.Area as Area
import Chart.Axis as Axis
import Chart.Axis.Unit as Unit
import Chart.Dot as Dots
import Chart.Grid as Grid
import Chart.Line as Line
import Chart.Colors as Colors
import Chart.Events as Events
import Chart.Element as Element
import Chart.Legends as Legends
import Chart.Container as Container
import Chart.Interpolation as Interpolation
import Chart.Axis.Intersection as Intersection
import Internal.Chart
import Internal.Area
import Internal.Axis
import Internal.Junk
import Internal.Line
import Internal.Element
import Internal.Events
import Internal.Container
import Internal.Axis.Range
import Internal.Orientation
import Internal.Svg as Svg
import Internal.Point as Point
import Internal.Utils as Utils
import Internal.Coordinate as Coordinate
import Color
-- VIEW / SIMPLE
{-|
** Show a line chart **
type alias Point =
{ x : Float, y : Float }
chart : Html msg
chart =
Chart.Lines.view1 .x .y
[ Point 0 2, Point 5 5, Point 10 10 ]
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example1.elm)._
** Choosing your variables **
Notice that we provide `.x` and `.y` to specify which data we want to show.
So if we had more complex data structures, like a human with an `age`, `weight`,
`height`, and `income`, we can easily pick which two properties we want to plot:
chart : Html msg
chart =
Chart.Lines.view1 .age .weight
[ Human 4 24 0.94 0
, Human 25 75 1.73 25000
, Human 43 83 1.75 40000
]
-- Try changing .weight to .height
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart1.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example2.elm)._
** Use any function to determine inputs **
Rather than using data like `.weight` directly, you can make a
function like `bmi human = human.weight / human.height ^ 2` and create a
chart of `.age` vs `bmi`. This allows you to keep your data set nice and minimal!
** The whole chart is just a function **
`view1` is just a function, so it will update as your data changes.
If you get more data points or some data points are changed, the chart
refreshes automatically!
-}
view1 : (data -> Float) -> (data -> Float) -> List data -> Svg.Svg msg
view1 toX toY dataset =
view toX toY <| defaultLines [ dataset ]
{-|
** Show a line chart with two lines **
Say you have two humans and you would like to see how their weight relates
to their age. Here's how you could plot it.
chart : Html msg
chart =
Chart.Lines.view2 .age .weight alice chuck
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart2.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example3.elm)._
-}
view2 : (data -> Float) -> (data -> Float) -> List data -> List data -> Svg.Svg msg
view2 toX toY dataset1 dataset2 =
view toX toY <| defaultLines [ dataset1, dataset2 ]
{-|
** Show a line chart with three lines **
It works just like `view1` and `view2`.
chart : Html msg
chart =
Chart.Lines.view3 .age .weight <NAME> <NAME> chuck
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart3.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example4.elm)._
But what if you have more people? What if you have _four_ people?! In that case,
check out `view`.
-}
view3 : (data -> Float) -> (data -> Float) -> List data -> List data -> List data -> Svg.Svg msg
view3 toX toY dataset1 dataset2 dataset3 =
view toX toY <| defaultLines [ dataset1, dataset2, dataset3 ]
-- VIEW
{-|
** Show any amount of lines **
If you want to change the color, the dot, or the title of a line, then see
the `line` function.
chart : Html msg
chart =
Chart.Lines.view .age .height
[ Chart.Lines.line Colors.purple Dots.cross "<NAME>" <NAME>
, Chart.Lines.line Colors.blue Dots.square "<NAME>" <NAME>
, Chart.Lines.line Colors.cyan Dots.circle "Chuck" chuck
]
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart4.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example5.elm)._
See `viewCustom` for all other customizations.
-}
view : (data -> Float) -> (data -> Float) -> List (Series data) -> Svg.Svg msg
view toX toY =
viewCustom (defaultConfig toX toY)
{-| This type represents the visual configuration of a _series_ of data.
Definition of _series_:
> a number of events, objects, or people of a similar or related kind coming one after another.
** Examples of customizations **
See the `line` and `dash` functions for more information!
solidLine : Chart.Lines.Series Human
solidLine =
Chart.Lines.line Colors.purple Dots.cross "<NAME>" <NAME>
dashedLine : Chart.Lines.Series Human
dashedLine =
Chart.Lines.dash Colors.purpleLight Dots.none "Average" [ 4, 2 ] average
-}
type alias Series data =
Internal.Line.Series data
{-|
** Customize a solid line **
Try changing the color or explore all the available dot shapes from `Chart.Lines.Dot`!
chart : Html msg
chart =
Chart.Lines.view .age .weight
[ Chart.Lines.line Colors.pinkLight Dots.plus "<NAME>" <NAME>
, Chart.Lines.line Colors.goldLight Dots.diamond "<NAME>" bobby
, Chart.Lines.line Colors.blueLight Dots.square "Chuck" chuck
]
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart7.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example6.elm)._
** Regarding the title **
The string title will show up in the legends. If you are interested in
customizing your legends, dot size or line width, check out `viewCustom`.
-}
line : Color.Color -> Dots.Shape -> String -> List data -> Series data
line =
Internal.Line.line
{-| -}
plain : Color.Color -> String -> List data -> Series data
plain =
Internal.Line.plain
{-|
** Customize a dashed line **
Works just like `line`, except it takes another argument which is an array of
floats describing your dashing pattern. I recommend typing in random numbers and seeing what
happens, but you alternativelly you can see the SVG `stroke-dasharray`
[documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray)
for examples of patterns.
chart : Html msg
chart =
Chart.Lines.view .age .height
[ Chart.Lines.line Colors.pinkLight Dots.plus "<NAME>" alice
, Chart.Lines.line Colors.goldLight Dots.diamond "<NAME>" bobby
, Chart.Lines.line Colors.blueLight Dots.square "Chuck" chuck
, dashedLine
]
dashedLine : Chart.Lines.Series Human
dashedLine =
Chart.Lines.dashed Colors.purpleLight Dots.none "Average" [ 4, 2 ] average
-- ^^^^^^^^
-- (Scroll to the left to see the pattern!)
-- Try passing different numbers!
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart5.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example7.elm)._
** When should I use a dashed line? **
Dashed lines are especially good for visualizing processed data like
averages or predicted values.
-}
dashed : Color.Color -> String -> List Float -> List data -> Series data
dashed =
Internal.Line.dashed
-- VIEW / CUSTOM
{-|
** Available customizations **
Use with `viewCustom`.
- **x**: Customizes your horizontal axis.</br>
_See [`Chart.Axis`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Axis) for more information and examples._
- **y**: Customizes your vertical axis.</br>
_See [`Chart.Axis`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Axis) for more information and examples._
- **intersection**: Determines where your axes meet.</br>
_See [`Chart.Axis.Intersection`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Axis-Intersection) for more information and examples._
- **interpolation**: Customizes the curve of your Chart.</br>
_See [`Chart.Interpolation`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Interpolation) for more information and examples._
- **container**: Customizes the container of your chart.</br>
_See [`Chart.Container`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Container) for more information and examples._
- **legends**: Customizes your chart's legends.</br>
_See [`Chart.Legends`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Legends) for more information and examples._
- **events**: Customizes your chart's events, allowing you to easily
make your chart interactive (adding tooltips, selection states etc.).</br>
_See [`Chart.Events`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Events) for more information and examples._
- **grid**: Customizes the style of your grid.</br>
_See [`Chart.Grid`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Grid) for more information and examples._
- **area**: Customizes the area under your line.</br>
_See [`Chart.Area`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Area) for more information and examples._
- **line**: Customizes your lines' width and color.</br>
_See [`Chart.Line`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Line) for more information and examples._
- **dots**: Customizes your dots' size and style.</br>
_See `Chart.Dot` for more information and examples._
- **junk**: Gets its name from
[<NAME>'s concept of "chart junk"](https://en.wikipedia.org/wiki/Chartjunk).
Here you are finally allowed set your creativity loose and add whatever
SVG or HTML fun you can imagine.</br>
_See [`Chart.Junk`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart.Junk) for more information and examples._
** Example configuration **
A good start would be to copy it and play around with customizations
available for each property.
chartConfig : Config Info msg
chartConfig =
{ y = Axis.default 400 "Age" .age
, x = Axis.default 700 "Weight" .weight
, container = Container.default "line-chart-1"
, interpolation = Interpolation.default
, intersection = Intersection.default
, legends = Legends.default
, events = Events.default
, junk = Junk.default
, grid = Grid.default
, area = Area.default
, line = Line.default
, dots = Dots.default
}
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example8.elm)._
-}
type alias Config data msg =
{ x : Axis.Config Float data msg
, y : Axis.Config (Maybe Float) data msg
, container : Container.Config msg
, intersection : Intersection.Config
, interpolation : Interpolation.Config
, legends : Legends.Config msg
, events : Events.Config Element.LineDot data msg
, area : Area.Config
, grid : Grid.Config
, line : Line.Config data
, dots : Dots.Config data
, junk : Junk.Config Element.LineDot msg
}
{-|
** Customize everything **
See the `Config` type for information about the available customizations.
Or copy and play with the example below. No one will tell.
** Example customiztion **
The example below makes the line chart an area chart.
chart : Html msg
chart =
Chart.Lines.viewCustom chartConfig
[ Chart.Lines.line Colors.blueLight Dots.square "Chuck" chuck
, Chart.Lines.line Colors.pinkLight Dots.plus "<NAME>" alice
, Chart.Lines.line Colors.goldLight Dots.diamond "<NAME>" bobby
]
chartConfig : Config Info msg
chartConfig =
{ y = Axis.default 400 "Age" .age
, x = Axis.default 700 "Weight" .weight
, container = Container.default "line-chart-1"
, interpolation = Interpolation.default
, intersection = Intersection.default
, legends = Legends.default
, events = Events.default
, junk = Junk.default
, grid = Grid.default
, area = Area.stacked 0.5 -- Changed from the default!
, line = Line.default
, dots = Dots.default
}
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart6.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example9.elm)._
** Speaking of area charts **
Remember that area charts are for data where the area under the curve _matters_.
Typically, this would be when you have a quantity accumulating over time.
Think profit over time or velocity over time!
In the case of profit over time, the area under the curve shows the total amount
of money earned in that time frame.<br/>
If the that total amount is not important for the relationship you're
trying to visualize, it's best to leave it out!
-}
viewCustom : Config data msg -> List (Series data) -> Html.Html msg
viewCustom config series =
let
-- Data / System
data = toDataPoints config series
dataSafe = List.map (List.filter (Internal.Element.isReal << .element)) data
dataAll = List.concat data
dataAllSafe = List.concat dataSafe
system = toSystem config dataAllSafe
-- View
viewLines =
Internal.Line.view
{ system = system
, interpolation = config.interpolation
, dotsConfig = config.dots
, lineConfig = config.line
, area = config.area
}
viewLegends =
{ system = system
, config = config.legends
, defaults = { width = 30, offsetY = 10 }
, legends = \width ->
let legend serie data_ =
{ sample = Internal.Line.viewSample config.dots config.line config.area system serie data_ width
, label = Internal.Line.label serie
}
in List.map2 legend series dataSafe
}
in
Internal.Chart.view
{ container = config.container
, events = config.events
, defs = []
, grid = config.grid
, series = viewLines series data
, intersection = config.intersection
, horizontalAxis = config.x
, verticalAxis = config.y
, legends = viewLegends
, trends = Svg.text ""
, junk =
Internal.Junk.getLayers
{ orientation = Internal.Orientation.Vertical
, independent = Internal.Axis.title config.x
, dependent = Internal.Axis.title config.y
, offsetOne = 15
, offsetMany = 15
}
system
config.junk
, orientation = Internal.Orientation.Vertical
}
dataAll
system
-- INTERNAL
toDataPoints : Config data msg -> List (Series data) -> List (List (Point.Point Element.LineDot data))
toDataPoints config series =
let
data =
List.indexedMap eachSerie series
eachSerie seriesIndex serie =
List.map (eachDatum seriesIndex serie) (Internal.Line.data serie)
eachDatum seriesIndex serie datum =
case ( Internal.Axis.variable config.x datum, Internal.Axis.variable config.y datum ) of
( x, Just y ) ->
{ source = datum
, coordinates = Coordinate.Point x y
, element =
{ element = Internal.Element.lineDot True
, label = Internal.Line.label serie
, color = Internal.Line.colorBase serie
, independent = Internal.Axis.unit config.x x
, dependent = Internal.Axis.unit config.y y
, seriesIndex = seriesIndex
}
}
( x, Nothing ) ->
{ source = datum
, coordinates = Coordinate.Point x 0
, element =
{ element = Internal.Element.lineDot False
, label = Internal.Line.label serie
, color = Internal.Line.colorBase serie
, independent = Internal.Axis.unit config.x x
, dependent = "-"
, seriesIndex = seriesIndex
}
}
in
case config.area of
Internal.Area.None -> data
Internal.Area.Normal _ -> data
Internal.Area.Stacked _ -> stack data
Internal.Area.Percentage _ -> data -- TODO Not used
stack : List (List (Point.Point Element.LineDot data)) -> List (List (Point.Point Element.LineDot data))
stack dataset =
let
stackBelows dataset_ result =
case dataset_ of
data :: belows ->
stackBelows belows <|
List.foldl addBelows data belows :: result
[] ->
result
in
List.reverse (stackBelows dataset [])
addBelows : List (Point.Point Element.LineDot data) -> List (Point.Point Element.LineDot data) -> List (Point.Point Element.LineDot data)
addBelows alldata dataBelowAll =
let
iterate datum0 dataTop dataBelowTop result =
case ( dataTop, dataBelowTop ) of
( datum1 :: data, datumBelow :: dataBelow ) ->
-- if the data point is after the point below, add it
if datum1.coordinates.x > datumBelow.coordinates.x
then
if Internal.Element.isReal datumBelow.element then
iterate datum0 (datum1 :: data) dataBelow (add datumBelow datum0 :: result)
else
iterate datum0 (datum1 :: data) dataBelow (add datumBelow datum0 :: result)
-- if not, try the next
else iterate datum1 data (datumBelow :: dataBelow) result
( [], datumBelow :: dataBelow ) ->
-- if the data point is after the point below, add it
if datum0.coordinates.x <= datumBelow.coordinates.x
then iterate datum0 [] dataBelow (add datumBelow datum0 :: result)
-- if not, try the next
else iterate datum0 [] dataBelow (datumBelow :: result)
( datum1 :: data, [] ) ->
result
( [], [] ) ->
result
add below datum =
setY below (below.coordinates.y + datum.coordinates.y)
in
List.reverse <| Maybe.withDefault [] <| Utils.withFirst alldata <| \first rest ->
iterate first rest dataBelowAll []
setY : Point.Point Element.LineDot data -> Float -> Point.Point Element.LineDot data
setY datum y =
{ datum | coordinates = Coordinate.Point datum.coordinates.x y }
toSystem : Config data msg -> List (Point.Point Element.LineDot data) -> Coordinate.System
toSystem config data =
let
container = Internal.Container.properties identity config.container
hasArea = Internal.Area.hasArea config.area
frame = Coordinate.frame container.margin container.size.width container.size.height
xRange = Coordinate.range (.coordinates >> .x) data
yRange = Coordinate.range (.coordinates >> .y) data
system =
{ frame = frame
, x = xRange
, y = adjustDomainRange yRange
, xData = xRange
, yData = yRange
, id = container.id
}
adjustDomainRange domain =
if hasArea
then Coordinate.ground domain
else domain
in
{ system
| x = Internal.Axis.Range.applyX (Internal.Axis.range config.x) system
, y = Internal.Axis.Range.applyY (Internal.Axis.range config.y) system
}
-- INTERNAL / DEFAULTS
defaultConfig : (data -> Float) -> (data -> Float) -> Config data msg
defaultConfig toX toY =
{ x = Axis.default "" Unit.none toX
, y = Axis.default "" Unit.none (Just << toY)
, container = Container.default "line-chart-1" 700 400
, interpolation = Interpolation.default
, intersection = Intersection.default
, legends = Legends.default
, events = Events.default
, junk = Junk.default
, grid = Grid.default
, area = Area.default
, line = Line.default
, dots = Dots.default
}
defaultLines : List (List data) -> List (Series data)
defaultLines =
List.map4 Internal.Line.line defaultColors defaultShapes defaultLabel
defaultColors : List Color.Color
defaultColors =
[ Colors.pink
, Colors.blue
, Colors.gold
]
defaultShapes : List Dots.Shape
defaultShapes =
[ Dots.circle
, Dots.triangle
, Dots.cross
]
defaultLabel : List String
defaultLabel =
[ "First"
, "Second"
, "Third"
]
| true | module LineChart exposing
( view1, view2, view3
, view, Series, line, plain, dashed
, viewCustom, Config
)
{-|
## Table of contents
### Quick start
- [view1](#view1) for visualizing a single data series.
- [view2](#view2) for visualizing two data series.
- [view3](#view3) for visualizing three data series.
### Customizing lines
- [view](#view) for visualizing *any* amount of data series.
- [line](#line) for configuring color, dot etc. of a line representing a data series.
- [dash](#dash) for configuring color, dot etc. of a *dashed* line representing a data series.
### Customizing everything
- [viewCustom](#viewCustom) for configuring any other aspect of the chart (axis, area, etc.).
# Quick start
@docs view1, view2, view3
# Customizing lines
@docs view, Series, line, plain, dashed
# Customizing everything
@docs viewCustom, Config
-}
import Html
import Svg
import Chart.Junk as Junk
import Chart.Area as Area
import Chart.Axis as Axis
import Chart.Axis.Unit as Unit
import Chart.Dot as Dots
import Chart.Grid as Grid
import Chart.Line as Line
import Chart.Colors as Colors
import Chart.Events as Events
import Chart.Element as Element
import Chart.Legends as Legends
import Chart.Container as Container
import Chart.Interpolation as Interpolation
import Chart.Axis.Intersection as Intersection
import Internal.Chart
import Internal.Area
import Internal.Axis
import Internal.Junk
import Internal.Line
import Internal.Element
import Internal.Events
import Internal.Container
import Internal.Axis.Range
import Internal.Orientation
import Internal.Svg as Svg
import Internal.Point as Point
import Internal.Utils as Utils
import Internal.Coordinate as Coordinate
import Color
-- VIEW / SIMPLE
{-|
** Show a line chart **
type alias Point =
{ x : Float, y : Float }
chart : Html msg
chart =
Chart.Lines.view1 .x .y
[ Point 0 2, Point 5 5, Point 10 10 ]
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example1.elm)._
** Choosing your variables **
Notice that we provide `.x` and `.y` to specify which data we want to show.
So if we had more complex data structures, like a human with an `age`, `weight`,
`height`, and `income`, we can easily pick which two properties we want to plot:
chart : Html msg
chart =
Chart.Lines.view1 .age .weight
[ Human 4 24 0.94 0
, Human 25 75 1.73 25000
, Human 43 83 1.75 40000
]
-- Try changing .weight to .height
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart1.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example2.elm)._
** Use any function to determine inputs **
Rather than using data like `.weight` directly, you can make a
function like `bmi human = human.weight / human.height ^ 2` and create a
chart of `.age` vs `bmi`. This allows you to keep your data set nice and minimal!
** The whole chart is just a function **
`view1` is just a function, so it will update as your data changes.
If you get more data points or some data points are changed, the chart
refreshes automatically!
-}
view1 : (data -> Float) -> (data -> Float) -> List data -> Svg.Svg msg
view1 toX toY dataset =
view toX toY <| defaultLines [ dataset ]
{-|
** Show a line chart with two lines **
Say you have two humans and you would like to see how their weight relates
to their age. Here's how you could plot it.
chart : Html msg
chart =
Chart.Lines.view2 .age .weight alice chuck
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart2.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example3.elm)._
-}
view2 : (data -> Float) -> (data -> Float) -> List data -> List data -> Svg.Svg msg
view2 toX toY dataset1 dataset2 =
view toX toY <| defaultLines [ dataset1, dataset2 ]
{-|
** Show a line chart with three lines **
It works just like `view1` and `view2`.
chart : Html msg
chart =
Chart.Lines.view3 .age .weight PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI chuck
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart3.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example4.elm)._
But what if you have more people? What if you have _four_ people?! In that case,
check out `view`.
-}
view3 : (data -> Float) -> (data -> Float) -> List data -> List data -> List data -> Svg.Svg msg
view3 toX toY dataset1 dataset2 dataset3 =
view toX toY <| defaultLines [ dataset1, dataset2, dataset3 ]
-- VIEW
{-|
** Show any amount of lines **
If you want to change the color, the dot, or the title of a line, then see
the `line` function.
chart : Html msg
chart =
Chart.Lines.view .age .height
[ Chart.Lines.line Colors.purple Dots.cross "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI
, Chart.Lines.line Colors.blue Dots.square "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI
, Chart.Lines.line Colors.cyan Dots.circle "Chuck" chuck
]
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart4.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example5.elm)._
See `viewCustom` for all other customizations.
-}
view : (data -> Float) -> (data -> Float) -> List (Series data) -> Svg.Svg msg
view toX toY =
viewCustom (defaultConfig toX toY)
{-| This type represents the visual configuration of a _series_ of data.
Definition of _series_:
> a number of events, objects, or people of a similar or related kind coming one after another.
** Examples of customizations **
See the `line` and `dash` functions for more information!
solidLine : Chart.Lines.Series Human
solidLine =
Chart.Lines.line Colors.purple Dots.cross "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI
dashedLine : Chart.Lines.Series Human
dashedLine =
Chart.Lines.dash Colors.purpleLight Dots.none "Average" [ 4, 2 ] average
-}
type alias Series data =
Internal.Line.Series data
{-|
** Customize a solid line **
Try changing the color or explore all the available dot shapes from `Chart.Lines.Dot`!
chart : Html msg
chart =
Chart.Lines.view .age .weight
[ Chart.Lines.line Colors.pinkLight Dots.plus "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI
, Chart.Lines.line Colors.goldLight Dots.diamond "PI:NAME:<NAME>END_PI" bobby
, Chart.Lines.line Colors.blueLight Dots.square "Chuck" chuck
]
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart7.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example6.elm)._
** Regarding the title **
The string title will show up in the legends. If you are interested in
customizing your legends, dot size or line width, check out `viewCustom`.
-}
line : Color.Color -> Dots.Shape -> String -> List data -> Series data
line =
Internal.Line.line
{-| -}
plain : Color.Color -> String -> List data -> Series data
plain =
Internal.Line.plain
{-|
** Customize a dashed line **
Works just like `line`, except it takes another argument which is an array of
floats describing your dashing pattern. I recommend typing in random numbers and seeing what
happens, but you alternativelly you can see the SVG `stroke-dasharray`
[documentation](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray)
for examples of patterns.
chart : Html msg
chart =
Chart.Lines.view .age .height
[ Chart.Lines.line Colors.pinkLight Dots.plus "PI:NAME:<NAME>END_PI" alice
, Chart.Lines.line Colors.goldLight Dots.diamond "PI:NAME:<NAME>END_PI" bobby
, Chart.Lines.line Colors.blueLight Dots.square "Chuck" chuck
, dashedLine
]
dashedLine : Chart.Lines.Series Human
dashedLine =
Chart.Lines.dashed Colors.purpleLight Dots.none "Average" [ 4, 2 ] average
-- ^^^^^^^^
-- (Scroll to the left to see the pattern!)
-- Try passing different numbers!
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart5.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example7.elm)._
** When should I use a dashed line? **
Dashed lines are especially good for visualizing processed data like
averages or predicted values.
-}
dashed : Color.Color -> String -> List Float -> List data -> Series data
dashed =
Internal.Line.dashed
-- VIEW / CUSTOM
{-|
** Available customizations **
Use with `viewCustom`.
- **x**: Customizes your horizontal axis.</br>
_See [`Chart.Axis`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Axis) for more information and examples._
- **y**: Customizes your vertical axis.</br>
_See [`Chart.Axis`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Axis) for more information and examples._
- **intersection**: Determines where your axes meet.</br>
_See [`Chart.Axis.Intersection`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Axis-Intersection) for more information and examples._
- **interpolation**: Customizes the curve of your Chart.</br>
_See [`Chart.Interpolation`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Interpolation) for more information and examples._
- **container**: Customizes the container of your chart.</br>
_See [`Chart.Container`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Container) for more information and examples._
- **legends**: Customizes your chart's legends.</br>
_See [`Chart.Legends`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Legends) for more information and examples._
- **events**: Customizes your chart's events, allowing you to easily
make your chart interactive (adding tooltips, selection states etc.).</br>
_See [`Chart.Events`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Events) for more information and examples._
- **grid**: Customizes the style of your grid.</br>
_See [`Chart.Grid`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Grid) for more information and examples._
- **area**: Customizes the area under your line.</br>
_See [`Chart.Area`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Area) for more information and examples._
- **line**: Customizes your lines' width and color.</br>
_See [`Chart.Line`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart-Line) for more information and examples._
- **dots**: Customizes your dots' size and style.</br>
_See `Chart.Dot` for more information and examples._
- **junk**: Gets its name from
[PI:NAME:<NAME>END_PI's concept of "chart junk"](https://en.wikipedia.org/wiki/Chartjunk).
Here you are finally allowed set your creativity loose and add whatever
SVG or HTML fun you can imagine.</br>
_See [`Chart.Junk`](http://package.elm-lang.org/packages/terezka/line-charts/latest/LineChart.Junk) for more information and examples._
** Example configuration **
A good start would be to copy it and play around with customizations
available for each property.
chartConfig : Config Info msg
chartConfig =
{ y = Axis.default 400 "Age" .age
, x = Axis.default 700 "Weight" .weight
, container = Container.default "line-chart-1"
, interpolation = Interpolation.default
, intersection = Intersection.default
, legends = Legends.default
, events = Events.default
, junk = Junk.default
, grid = Grid.default
, area = Area.default
, line = Line.default
, dots = Dots.default
}
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example8.elm)._
-}
type alias Config data msg =
{ x : Axis.Config Float data msg
, y : Axis.Config (Maybe Float) data msg
, container : Container.Config msg
, intersection : Intersection.Config
, interpolation : Interpolation.Config
, legends : Legends.Config msg
, events : Events.Config Element.LineDot data msg
, area : Area.Config
, grid : Grid.Config
, line : Line.Config data
, dots : Dots.Config data
, junk : Junk.Config Element.LineDot msg
}
{-|
** Customize everything **
See the `Config` type for information about the available customizations.
Or copy and play with the example below. No one will tell.
** Example customiztion **
The example below makes the line chart an area chart.
chart : Html msg
chart =
Chart.Lines.viewCustom chartConfig
[ Chart.Lines.line Colors.blueLight Dots.square "Chuck" chuck
, Chart.Lines.line Colors.pinkLight Dots.plus "PI:NAME:<NAME>END_PI" alice
, Chart.Lines.line Colors.goldLight Dots.diamond "PI:NAME:<NAME>END_PI" bobby
]
chartConfig : Config Info msg
chartConfig =
{ y = Axis.default 400 "Age" .age
, x = Axis.default 700 "Weight" .weight
, container = Container.default "line-chart-1"
, interpolation = Interpolation.default
, intersection = Intersection.default
, legends = Legends.default
, events = Events.default
, junk = Junk.default
, grid = Grid.default
, area = Area.stacked 0.5 -- Changed from the default!
, line = Line.default
, dots = Dots.default
}
<img alt="Chart Result" width="540" src="https://github.com/terezka/line-charts/blob/master/images/linechart6.png?raw=true"></src>
_See the full example [here](https://github.com/terezka/line-charts/blob/master/examples/Docs/LineChart/Example9.elm)._
** Speaking of area charts **
Remember that area charts are for data where the area under the curve _matters_.
Typically, this would be when you have a quantity accumulating over time.
Think profit over time or velocity over time!
In the case of profit over time, the area under the curve shows the total amount
of money earned in that time frame.<br/>
If the that total amount is not important for the relationship you're
trying to visualize, it's best to leave it out!
-}
viewCustom : Config data msg -> List (Series data) -> Html.Html msg
viewCustom config series =
let
-- Data / System
data = toDataPoints config series
dataSafe = List.map (List.filter (Internal.Element.isReal << .element)) data
dataAll = List.concat data
dataAllSafe = List.concat dataSafe
system = toSystem config dataAllSafe
-- View
viewLines =
Internal.Line.view
{ system = system
, interpolation = config.interpolation
, dotsConfig = config.dots
, lineConfig = config.line
, area = config.area
}
viewLegends =
{ system = system
, config = config.legends
, defaults = { width = 30, offsetY = 10 }
, legends = \width ->
let legend serie data_ =
{ sample = Internal.Line.viewSample config.dots config.line config.area system serie data_ width
, label = Internal.Line.label serie
}
in List.map2 legend series dataSafe
}
in
Internal.Chart.view
{ container = config.container
, events = config.events
, defs = []
, grid = config.grid
, series = viewLines series data
, intersection = config.intersection
, horizontalAxis = config.x
, verticalAxis = config.y
, legends = viewLegends
, trends = Svg.text ""
, junk =
Internal.Junk.getLayers
{ orientation = Internal.Orientation.Vertical
, independent = Internal.Axis.title config.x
, dependent = Internal.Axis.title config.y
, offsetOne = 15
, offsetMany = 15
}
system
config.junk
, orientation = Internal.Orientation.Vertical
}
dataAll
system
-- INTERNAL
toDataPoints : Config data msg -> List (Series data) -> List (List (Point.Point Element.LineDot data))
toDataPoints config series =
let
data =
List.indexedMap eachSerie series
eachSerie seriesIndex serie =
List.map (eachDatum seriesIndex serie) (Internal.Line.data serie)
eachDatum seriesIndex serie datum =
case ( Internal.Axis.variable config.x datum, Internal.Axis.variable config.y datum ) of
( x, Just y ) ->
{ source = datum
, coordinates = Coordinate.Point x y
, element =
{ element = Internal.Element.lineDot True
, label = Internal.Line.label serie
, color = Internal.Line.colorBase serie
, independent = Internal.Axis.unit config.x x
, dependent = Internal.Axis.unit config.y y
, seriesIndex = seriesIndex
}
}
( x, Nothing ) ->
{ source = datum
, coordinates = Coordinate.Point x 0
, element =
{ element = Internal.Element.lineDot False
, label = Internal.Line.label serie
, color = Internal.Line.colorBase serie
, independent = Internal.Axis.unit config.x x
, dependent = "-"
, seriesIndex = seriesIndex
}
}
in
case config.area of
Internal.Area.None -> data
Internal.Area.Normal _ -> data
Internal.Area.Stacked _ -> stack data
Internal.Area.Percentage _ -> data -- TODO Not used
stack : List (List (Point.Point Element.LineDot data)) -> List (List (Point.Point Element.LineDot data))
stack dataset =
let
stackBelows dataset_ result =
case dataset_ of
data :: belows ->
stackBelows belows <|
List.foldl addBelows data belows :: result
[] ->
result
in
List.reverse (stackBelows dataset [])
addBelows : List (Point.Point Element.LineDot data) -> List (Point.Point Element.LineDot data) -> List (Point.Point Element.LineDot data)
addBelows alldata dataBelowAll =
let
iterate datum0 dataTop dataBelowTop result =
case ( dataTop, dataBelowTop ) of
( datum1 :: data, datumBelow :: dataBelow ) ->
-- if the data point is after the point below, add it
if datum1.coordinates.x > datumBelow.coordinates.x
then
if Internal.Element.isReal datumBelow.element then
iterate datum0 (datum1 :: data) dataBelow (add datumBelow datum0 :: result)
else
iterate datum0 (datum1 :: data) dataBelow (add datumBelow datum0 :: result)
-- if not, try the next
else iterate datum1 data (datumBelow :: dataBelow) result
( [], datumBelow :: dataBelow ) ->
-- if the data point is after the point below, add it
if datum0.coordinates.x <= datumBelow.coordinates.x
then iterate datum0 [] dataBelow (add datumBelow datum0 :: result)
-- if not, try the next
else iterate datum0 [] dataBelow (datumBelow :: result)
( datum1 :: data, [] ) ->
result
( [], [] ) ->
result
add below datum =
setY below (below.coordinates.y + datum.coordinates.y)
in
List.reverse <| Maybe.withDefault [] <| Utils.withFirst alldata <| \first rest ->
iterate first rest dataBelowAll []
setY : Point.Point Element.LineDot data -> Float -> Point.Point Element.LineDot data
setY datum y =
{ datum | coordinates = Coordinate.Point datum.coordinates.x y }
toSystem : Config data msg -> List (Point.Point Element.LineDot data) -> Coordinate.System
toSystem config data =
let
container = Internal.Container.properties identity config.container
hasArea = Internal.Area.hasArea config.area
frame = Coordinate.frame container.margin container.size.width container.size.height
xRange = Coordinate.range (.coordinates >> .x) data
yRange = Coordinate.range (.coordinates >> .y) data
system =
{ frame = frame
, x = xRange
, y = adjustDomainRange yRange
, xData = xRange
, yData = yRange
, id = container.id
}
adjustDomainRange domain =
if hasArea
then Coordinate.ground domain
else domain
in
{ system
| x = Internal.Axis.Range.applyX (Internal.Axis.range config.x) system
, y = Internal.Axis.Range.applyY (Internal.Axis.range config.y) system
}
-- INTERNAL / DEFAULTS
defaultConfig : (data -> Float) -> (data -> Float) -> Config data msg
defaultConfig toX toY =
{ x = Axis.default "" Unit.none toX
, y = Axis.default "" Unit.none (Just << toY)
, container = Container.default "line-chart-1" 700 400
, interpolation = Interpolation.default
, intersection = Intersection.default
, legends = Legends.default
, events = Events.default
, junk = Junk.default
, grid = Grid.default
, area = Area.default
, line = Line.default
, dots = Dots.default
}
defaultLines : List (List data) -> List (Series data)
defaultLines =
List.map4 Internal.Line.line defaultColors defaultShapes defaultLabel
defaultColors : List Color.Color
defaultColors =
[ Colors.pink
, Colors.blue
, Colors.gold
]
defaultShapes : List Dots.Shape
defaultShapes =
[ Dots.circle
, Dots.triangle
, Dots.cross
]
defaultLabel : List String
defaultLabel =
[ "First"
, "Second"
, "Third"
]
| elm |
[
{
"context": " adapted from \"Game Physics Engine Development\" by Ian Millington.\n<https://www.amazon.it/Game-Physics-Engine-Devel",
"end": 227,
"score": 0.999725163,
"start": 213,
"tag": "NAME",
"value": "Ian Millington"
},
{
"context": "s are available on Github at:\n<https://github.com/idmillington/cyclone-physics>\n\nAbout stability \"Slops\":\n<http:",
"end": 398,
"score": 0.9911298752,
"start": 386,
"tag": "USERNAME",
"value": "idmillington"
}
] | src/Physics.elm | Viir/sunny-land | 126 | module Physics exposing
( Contact(..)
, ContactData
, PhysicsBody
, Wall
, addImpulse
, step
)
{-| Game physics.
Most of the code is adapted from "Game Physics Engine Development" by Ian Millington.
<https://www.amazon.it/Game-Physics-Engine-Development-Commercial-Grade/dp/0123819768>
Original C++ sources are available on Github at:
<https://github.com/idmillington/cyclone-physics>
About stability "Slops":
<http://allenchou.net/2014/01/game-physics-stability-slops/>
-}
import AltMath.Vector2 as Vec2 exposing (Vec2, vec2)
import Bitwise as B
import Dict exposing (Dict)
import Vector2.Extra as Vec2
{-| Walls and ground in the game. They have a direction: if p2 > p1 the contact normal points "up".
-}
type alias Wall =
{ p1 : Vec2, p2 : Vec2, normal : Vec2 }
{-| A "physics body" is the set of attributes of a game entity which contributes to physics simulation.
-}
type alias PhysicsBody a =
{ a
| id : Int
, p : Vec2
, v : Vec2
, a : Vec2
, cumulativeImpulse : Vec2
, cumulativeContact : Vec2
, radius : Float
, restitution : Float
, contactTestBitMask : Int
, categoryBitMask : Int
, affectedByGravity : Bool
, affectedByContact : Bool
}
type alias ContactData =
{ normal : Vec2
, penetration : Float
}
type Contact a
= BetweenBodies Int Int ContactData
| WithWall Int ContactData
step :
{ b | friction : Vec2, g : Vec2 }
-> Float
-> List Wall
-> Dict Int (PhysicsBody a)
-> ( Dict Int (PhysicsBody a), List (Contact a) )
step config dt walls bodies =
let
newBodies =
Dict.map (\_ body -> integrate config dt body) bodies
contacts =
Dict.foldl
(\_ body accum ->
accum
|> computeContactWithWalls body walls
|> computeContactWithEntities body newBodies
)
[]
newBodies
in
( resolveContacts contacts newBodies, contacts )
integrate : { b | friction : Vec2, g : Vec2 } -> Float -> PhysicsBody a -> PhysicsBody a
integrate config dt body =
let
-- TODO integrate with dt
a =
body.a
|> Vec2.add body.cumulativeImpulse
|> (if body.affectedByGravity then
Vec2.add config.g
else
Vec2.add Vec2.zero
)
in
{ body
| p = Vec2.add body.p body.v
, v =
Vec2.add body.v a
-- Stokes' drag https://stackoverflow.com/a/667090
|> Vec2.add (Vec2.mul config.friction body.v)
, cumulativeImpulse = Vec2.zero
, cumulativeContact = Vec2.zero
}
-- iterate: List (Contact a) -> Dict Int (PhysicsBody a) -> Dict Int (PhysicsBody a)
-- iterate contacts entities =
resolveContacts :
List (Contact a)
-> Dict Int (PhysicsBody a)
-> Dict Int (PhysicsBody a)
resolveContacts contacts bodies =
List.foldl
(\contact accum ->
case contact of
WithWall id contact_ ->
case Dict.get id accum of
Just body ->
let
newBody =
if body.affectedByContact then
resolveBodyVsWallContact contact_ body
else
body
in
accum
|> Dict.insert id newBody
_ ->
accum
BetweenBodies id1 id2 contact_ ->
case ( Dict.get id1 accum, Dict.get id2 accum ) of
( Just body1, Just body2 ) ->
let
( newBody1, newBody2 ) =
if not body1.affectedByContact || not body2.affectedByContact then
-- Do not resolve contact, let entity logic to handle it
( body1, body2 )
else
resolveBodyVsBodyContact contact_ body1 body2
in
accum
|> Dict.insert newBody1.id newBody1
|> Dict.insert newBody2.id newBody2
( _, _ ) ->
accum
)
bodies
contacts
computeContactWithWalls :
PhysicsBody a
-> List Wall
-> List (Contact a)
-> List (Contact a)
computeContactWithWalls body walls accum =
List.foldl
(\wall accumContact ->
case contactWithWall body wall of
Just contact ->
contact :: accumContact
Nothing ->
accumContact
)
accum
walls
computeContactWithEntities :
PhysicsBody a
-> Dict Int (PhysicsBody a)
-> List (Contact a)
-> List (Contact a)
computeContactWithEntities body others accum =
Dict.foldl
(\id other accumContact ->
-- Make sure to:
-- * Skip certain entity-vs-entity combinations according to contactTestBitMask
-- * Don't check with itself
-- * Do not generate (M,N) (N,M) contact dupes
if B.and body.categoryBitMask other.contactTestBitMask /= 0 && B.and other.categoryBitMask body.contactTestBitMask /= 0 && body.id < id then
case contactWithBody body other of
Just contact ->
contact :: accumContact
Nothing ->
accumContact
else
accumContact
)
accum
others
-- COLLISION RESOLUTION
slop =
0.005
{-| Resolve contact between two physics bodies (circles).
-}
resolveBodyVsBodyContact : ContactData -> PhysicsBody a -> PhysicsBody a -> ( PhysicsBody a, PhysicsBody a )
resolveBodyVsBodyContact { normal, penetration } body1 body2 =
let
-- Bodies relative velocity along normal
vel =
Vec2.dot (Vec2.sub body2.v body1.v) normal
in
if vel > 0 then
-- Do not resolve if bodies are separating
( body1, body2 )
else
let
-- Halve velocity to distribute it equally between both bodies
impulse =
Vec2.scale (-1 * vel / 2) normal
in
( { body1
| v = Vec2.sub body1.v impulse
, p = Vec2.sub body1.p (Vec2.scale (max (penetration / 2 - slop) 0.0) normal)
, cumulativeContact = Vec2.add body1.cumulativeContact impulse
}
, { body2
| v = Vec2.add body2.v impulse
, p = Vec2.add body2.p (Vec2.scale (max (penetration / 2 - slop) 0.0) normal)
, cumulativeContact = Vec2.add body2.cumulativeContact impulse
}
)
{-| Resolve contact between physics body (circle) and wall (segment).
-}
resolveBodyVsWallContact : ContactData -> PhysicsBody a -> PhysicsBody a
resolveBodyVsWallContact { normal, penetration } body1 =
let
-- Wall has zero velocity, ignore
vel =
Vec2.dot body1.v normal
in
if vel > 0 then
-- Do not resolve if body is separating from wall
body1
else
let
impulse =
Vec2.scale (-1 * vel) normal
in
{ body1
| v = Vec2.add body1.v impulse
, p = Vec2.add body1.p (Vec2.scale (max (penetration - slop) 0.0) normal)
, cumulativeContact = Vec2.add body1.cumulativeContact impulse
}
-- COLLISION DETECTION
{-| Calculate intersection between physics body (circle) and wall (segment).
See: <https://stackoverflow.com/a/1079478>
-}
contactWithWall : PhysicsBody a -> Wall -> Maybe (Contact a)
contactWithWall body wall =
-- Check if body is coming from behind/below the wall
if Vec2.dot body.v wall.normal > 0 then
Nothing
else
let
-- Vector to start of wall to body center
dir =
Vec2.sub body.p wall.p1
-- Distance from body position along normal
distanceSq =
Vec2.projection dir wall.normal
|> Vec2.lengthSquared
in
if distanceSq <= body.radius ^ 2 then
let
w =
Vec2.sub wall.p2 wall.p1
edgeDistance =
Vec2.dot dir (Vec2.normalize w)
in
-- On p1 edge or past p2 edge?
if edgeDistance < 0 || edgeDistance > Vec2.length w then
-- Let fall
Nothing
else
-- Not on edges, body is touching wall
Just
(WithWall
body.id
{ normal = wall.normal
, penetration = body.radius - sqrt distanceSq
}
)
else
-- Body not touching wall
Nothing
{-| Calculate contact between two physics bodies (circles).
-}
contactWithBody : PhysicsBody a -> PhysicsBody a -> Maybe (Contact a)
contactWithBody body1 body2 =
let
v =
Vec2.sub body2.p body1.p
in
if Vec2.lengthSquared v > (body1.radius + body2.radius) ^ 2 then
Nothing
else
let
d =
Vec2.length v
in
if d /= 0 then
-- Touching
Just
(BetweenBodies
body1.id
body2.id
{ normal = Vec2.normalize v
, penetration = (body1.radius + body2.radius) - d
}
)
else
-- Bodies perfectly overlap, arbitrary pick one
Just
(BetweenBodies
body1.id
body2.id
{ normal = vec2 1 0
, penetration = body1.radius
}
)
{-| Apply accelaration to a physics body.
-}
addImpulse :
Vec2
-> PhysicsBody a
-> PhysicsBody a
addImpulse value body =
{ body
| cumulativeImpulse = Vec2.add body.cumulativeImpulse value
}
| 49009 | module Physics exposing
( Contact(..)
, ContactData
, PhysicsBody
, Wall
, addImpulse
, step
)
{-| Game physics.
Most of the code is adapted from "Game Physics Engine Development" by <NAME>.
<https://www.amazon.it/Game-Physics-Engine-Development-Commercial-Grade/dp/0123819768>
Original C++ sources are available on Github at:
<https://github.com/idmillington/cyclone-physics>
About stability "Slops":
<http://allenchou.net/2014/01/game-physics-stability-slops/>
-}
import AltMath.Vector2 as Vec2 exposing (Vec2, vec2)
import Bitwise as B
import Dict exposing (Dict)
import Vector2.Extra as Vec2
{-| Walls and ground in the game. They have a direction: if p2 > p1 the contact normal points "up".
-}
type alias Wall =
{ p1 : Vec2, p2 : Vec2, normal : Vec2 }
{-| A "physics body" is the set of attributes of a game entity which contributes to physics simulation.
-}
type alias PhysicsBody a =
{ a
| id : Int
, p : Vec2
, v : Vec2
, a : Vec2
, cumulativeImpulse : Vec2
, cumulativeContact : Vec2
, radius : Float
, restitution : Float
, contactTestBitMask : Int
, categoryBitMask : Int
, affectedByGravity : Bool
, affectedByContact : Bool
}
type alias ContactData =
{ normal : Vec2
, penetration : Float
}
type Contact a
= BetweenBodies Int Int ContactData
| WithWall Int ContactData
step :
{ b | friction : Vec2, g : Vec2 }
-> Float
-> List Wall
-> Dict Int (PhysicsBody a)
-> ( Dict Int (PhysicsBody a), List (Contact a) )
step config dt walls bodies =
let
newBodies =
Dict.map (\_ body -> integrate config dt body) bodies
contacts =
Dict.foldl
(\_ body accum ->
accum
|> computeContactWithWalls body walls
|> computeContactWithEntities body newBodies
)
[]
newBodies
in
( resolveContacts contacts newBodies, contacts )
integrate : { b | friction : Vec2, g : Vec2 } -> Float -> PhysicsBody a -> PhysicsBody a
integrate config dt body =
let
-- TODO integrate with dt
a =
body.a
|> Vec2.add body.cumulativeImpulse
|> (if body.affectedByGravity then
Vec2.add config.g
else
Vec2.add Vec2.zero
)
in
{ body
| p = Vec2.add body.p body.v
, v =
Vec2.add body.v a
-- Stokes' drag https://stackoverflow.com/a/667090
|> Vec2.add (Vec2.mul config.friction body.v)
, cumulativeImpulse = Vec2.zero
, cumulativeContact = Vec2.zero
}
-- iterate: List (Contact a) -> Dict Int (PhysicsBody a) -> Dict Int (PhysicsBody a)
-- iterate contacts entities =
resolveContacts :
List (Contact a)
-> Dict Int (PhysicsBody a)
-> Dict Int (PhysicsBody a)
resolveContacts contacts bodies =
List.foldl
(\contact accum ->
case contact of
WithWall id contact_ ->
case Dict.get id accum of
Just body ->
let
newBody =
if body.affectedByContact then
resolveBodyVsWallContact contact_ body
else
body
in
accum
|> Dict.insert id newBody
_ ->
accum
BetweenBodies id1 id2 contact_ ->
case ( Dict.get id1 accum, Dict.get id2 accum ) of
( Just body1, Just body2 ) ->
let
( newBody1, newBody2 ) =
if not body1.affectedByContact || not body2.affectedByContact then
-- Do not resolve contact, let entity logic to handle it
( body1, body2 )
else
resolveBodyVsBodyContact contact_ body1 body2
in
accum
|> Dict.insert newBody1.id newBody1
|> Dict.insert newBody2.id newBody2
( _, _ ) ->
accum
)
bodies
contacts
computeContactWithWalls :
PhysicsBody a
-> List Wall
-> List (Contact a)
-> List (Contact a)
computeContactWithWalls body walls accum =
List.foldl
(\wall accumContact ->
case contactWithWall body wall of
Just contact ->
contact :: accumContact
Nothing ->
accumContact
)
accum
walls
computeContactWithEntities :
PhysicsBody a
-> Dict Int (PhysicsBody a)
-> List (Contact a)
-> List (Contact a)
computeContactWithEntities body others accum =
Dict.foldl
(\id other accumContact ->
-- Make sure to:
-- * Skip certain entity-vs-entity combinations according to contactTestBitMask
-- * Don't check with itself
-- * Do not generate (M,N) (N,M) contact dupes
if B.and body.categoryBitMask other.contactTestBitMask /= 0 && B.and other.categoryBitMask body.contactTestBitMask /= 0 && body.id < id then
case contactWithBody body other of
Just contact ->
contact :: accumContact
Nothing ->
accumContact
else
accumContact
)
accum
others
-- COLLISION RESOLUTION
slop =
0.005
{-| Resolve contact between two physics bodies (circles).
-}
resolveBodyVsBodyContact : ContactData -> PhysicsBody a -> PhysicsBody a -> ( PhysicsBody a, PhysicsBody a )
resolveBodyVsBodyContact { normal, penetration } body1 body2 =
let
-- Bodies relative velocity along normal
vel =
Vec2.dot (Vec2.sub body2.v body1.v) normal
in
if vel > 0 then
-- Do not resolve if bodies are separating
( body1, body2 )
else
let
-- Halve velocity to distribute it equally between both bodies
impulse =
Vec2.scale (-1 * vel / 2) normal
in
( { body1
| v = Vec2.sub body1.v impulse
, p = Vec2.sub body1.p (Vec2.scale (max (penetration / 2 - slop) 0.0) normal)
, cumulativeContact = Vec2.add body1.cumulativeContact impulse
}
, { body2
| v = Vec2.add body2.v impulse
, p = Vec2.add body2.p (Vec2.scale (max (penetration / 2 - slop) 0.0) normal)
, cumulativeContact = Vec2.add body2.cumulativeContact impulse
}
)
{-| Resolve contact between physics body (circle) and wall (segment).
-}
resolveBodyVsWallContact : ContactData -> PhysicsBody a -> PhysicsBody a
resolveBodyVsWallContact { normal, penetration } body1 =
let
-- Wall has zero velocity, ignore
vel =
Vec2.dot body1.v normal
in
if vel > 0 then
-- Do not resolve if body is separating from wall
body1
else
let
impulse =
Vec2.scale (-1 * vel) normal
in
{ body1
| v = Vec2.add body1.v impulse
, p = Vec2.add body1.p (Vec2.scale (max (penetration - slop) 0.0) normal)
, cumulativeContact = Vec2.add body1.cumulativeContact impulse
}
-- COLLISION DETECTION
{-| Calculate intersection between physics body (circle) and wall (segment).
See: <https://stackoverflow.com/a/1079478>
-}
contactWithWall : PhysicsBody a -> Wall -> Maybe (Contact a)
contactWithWall body wall =
-- Check if body is coming from behind/below the wall
if Vec2.dot body.v wall.normal > 0 then
Nothing
else
let
-- Vector to start of wall to body center
dir =
Vec2.sub body.p wall.p1
-- Distance from body position along normal
distanceSq =
Vec2.projection dir wall.normal
|> Vec2.lengthSquared
in
if distanceSq <= body.radius ^ 2 then
let
w =
Vec2.sub wall.p2 wall.p1
edgeDistance =
Vec2.dot dir (Vec2.normalize w)
in
-- On p1 edge or past p2 edge?
if edgeDistance < 0 || edgeDistance > Vec2.length w then
-- Let fall
Nothing
else
-- Not on edges, body is touching wall
Just
(WithWall
body.id
{ normal = wall.normal
, penetration = body.radius - sqrt distanceSq
}
)
else
-- Body not touching wall
Nothing
{-| Calculate contact between two physics bodies (circles).
-}
contactWithBody : PhysicsBody a -> PhysicsBody a -> Maybe (Contact a)
contactWithBody body1 body2 =
let
v =
Vec2.sub body2.p body1.p
in
if Vec2.lengthSquared v > (body1.radius + body2.radius) ^ 2 then
Nothing
else
let
d =
Vec2.length v
in
if d /= 0 then
-- Touching
Just
(BetweenBodies
body1.id
body2.id
{ normal = Vec2.normalize v
, penetration = (body1.radius + body2.radius) - d
}
)
else
-- Bodies perfectly overlap, arbitrary pick one
Just
(BetweenBodies
body1.id
body2.id
{ normal = vec2 1 0
, penetration = body1.radius
}
)
{-| Apply accelaration to a physics body.
-}
addImpulse :
Vec2
-> PhysicsBody a
-> PhysicsBody a
addImpulse value body =
{ body
| cumulativeImpulse = Vec2.add body.cumulativeImpulse value
}
| true | module Physics exposing
( Contact(..)
, ContactData
, PhysicsBody
, Wall
, addImpulse
, step
)
{-| Game physics.
Most of the code is adapted from "Game Physics Engine Development" by PI:NAME:<NAME>END_PI.
<https://www.amazon.it/Game-Physics-Engine-Development-Commercial-Grade/dp/0123819768>
Original C++ sources are available on Github at:
<https://github.com/idmillington/cyclone-physics>
About stability "Slops":
<http://allenchou.net/2014/01/game-physics-stability-slops/>
-}
import AltMath.Vector2 as Vec2 exposing (Vec2, vec2)
import Bitwise as B
import Dict exposing (Dict)
import Vector2.Extra as Vec2
{-| Walls and ground in the game. They have a direction: if p2 > p1 the contact normal points "up".
-}
type alias Wall =
{ p1 : Vec2, p2 : Vec2, normal : Vec2 }
{-| A "physics body" is the set of attributes of a game entity which contributes to physics simulation.
-}
type alias PhysicsBody a =
{ a
| id : Int
, p : Vec2
, v : Vec2
, a : Vec2
, cumulativeImpulse : Vec2
, cumulativeContact : Vec2
, radius : Float
, restitution : Float
, contactTestBitMask : Int
, categoryBitMask : Int
, affectedByGravity : Bool
, affectedByContact : Bool
}
type alias ContactData =
{ normal : Vec2
, penetration : Float
}
type Contact a
= BetweenBodies Int Int ContactData
| WithWall Int ContactData
step :
{ b | friction : Vec2, g : Vec2 }
-> Float
-> List Wall
-> Dict Int (PhysicsBody a)
-> ( Dict Int (PhysicsBody a), List (Contact a) )
step config dt walls bodies =
let
newBodies =
Dict.map (\_ body -> integrate config dt body) bodies
contacts =
Dict.foldl
(\_ body accum ->
accum
|> computeContactWithWalls body walls
|> computeContactWithEntities body newBodies
)
[]
newBodies
in
( resolveContacts contacts newBodies, contacts )
integrate : { b | friction : Vec2, g : Vec2 } -> Float -> PhysicsBody a -> PhysicsBody a
integrate config dt body =
let
-- TODO integrate with dt
a =
body.a
|> Vec2.add body.cumulativeImpulse
|> (if body.affectedByGravity then
Vec2.add config.g
else
Vec2.add Vec2.zero
)
in
{ body
| p = Vec2.add body.p body.v
, v =
Vec2.add body.v a
-- Stokes' drag https://stackoverflow.com/a/667090
|> Vec2.add (Vec2.mul config.friction body.v)
, cumulativeImpulse = Vec2.zero
, cumulativeContact = Vec2.zero
}
-- iterate: List (Contact a) -> Dict Int (PhysicsBody a) -> Dict Int (PhysicsBody a)
-- iterate contacts entities =
resolveContacts :
List (Contact a)
-> Dict Int (PhysicsBody a)
-> Dict Int (PhysicsBody a)
resolveContacts contacts bodies =
List.foldl
(\contact accum ->
case contact of
WithWall id contact_ ->
case Dict.get id accum of
Just body ->
let
newBody =
if body.affectedByContact then
resolveBodyVsWallContact contact_ body
else
body
in
accum
|> Dict.insert id newBody
_ ->
accum
BetweenBodies id1 id2 contact_ ->
case ( Dict.get id1 accum, Dict.get id2 accum ) of
( Just body1, Just body2 ) ->
let
( newBody1, newBody2 ) =
if not body1.affectedByContact || not body2.affectedByContact then
-- Do not resolve contact, let entity logic to handle it
( body1, body2 )
else
resolveBodyVsBodyContact contact_ body1 body2
in
accum
|> Dict.insert newBody1.id newBody1
|> Dict.insert newBody2.id newBody2
( _, _ ) ->
accum
)
bodies
contacts
computeContactWithWalls :
PhysicsBody a
-> List Wall
-> List (Contact a)
-> List (Contact a)
computeContactWithWalls body walls accum =
List.foldl
(\wall accumContact ->
case contactWithWall body wall of
Just contact ->
contact :: accumContact
Nothing ->
accumContact
)
accum
walls
computeContactWithEntities :
PhysicsBody a
-> Dict Int (PhysicsBody a)
-> List (Contact a)
-> List (Contact a)
computeContactWithEntities body others accum =
Dict.foldl
(\id other accumContact ->
-- Make sure to:
-- * Skip certain entity-vs-entity combinations according to contactTestBitMask
-- * Don't check with itself
-- * Do not generate (M,N) (N,M) contact dupes
if B.and body.categoryBitMask other.contactTestBitMask /= 0 && B.and other.categoryBitMask body.contactTestBitMask /= 0 && body.id < id then
case contactWithBody body other of
Just contact ->
contact :: accumContact
Nothing ->
accumContact
else
accumContact
)
accum
others
-- COLLISION RESOLUTION
slop =
0.005
{-| Resolve contact between two physics bodies (circles).
-}
resolveBodyVsBodyContact : ContactData -> PhysicsBody a -> PhysicsBody a -> ( PhysicsBody a, PhysicsBody a )
resolveBodyVsBodyContact { normal, penetration } body1 body2 =
let
-- Bodies relative velocity along normal
vel =
Vec2.dot (Vec2.sub body2.v body1.v) normal
in
if vel > 0 then
-- Do not resolve if bodies are separating
( body1, body2 )
else
let
-- Halve velocity to distribute it equally between both bodies
impulse =
Vec2.scale (-1 * vel / 2) normal
in
( { body1
| v = Vec2.sub body1.v impulse
, p = Vec2.sub body1.p (Vec2.scale (max (penetration / 2 - slop) 0.0) normal)
, cumulativeContact = Vec2.add body1.cumulativeContact impulse
}
, { body2
| v = Vec2.add body2.v impulse
, p = Vec2.add body2.p (Vec2.scale (max (penetration / 2 - slop) 0.0) normal)
, cumulativeContact = Vec2.add body2.cumulativeContact impulse
}
)
{-| Resolve contact between physics body (circle) and wall (segment).
-}
resolveBodyVsWallContact : ContactData -> PhysicsBody a -> PhysicsBody a
resolveBodyVsWallContact { normal, penetration } body1 =
let
-- Wall has zero velocity, ignore
vel =
Vec2.dot body1.v normal
in
if vel > 0 then
-- Do not resolve if body is separating from wall
body1
else
let
impulse =
Vec2.scale (-1 * vel) normal
in
{ body1
| v = Vec2.add body1.v impulse
, p = Vec2.add body1.p (Vec2.scale (max (penetration - slop) 0.0) normal)
, cumulativeContact = Vec2.add body1.cumulativeContact impulse
}
-- COLLISION DETECTION
{-| Calculate intersection between physics body (circle) and wall (segment).
See: <https://stackoverflow.com/a/1079478>
-}
contactWithWall : PhysicsBody a -> Wall -> Maybe (Contact a)
contactWithWall body wall =
-- Check if body is coming from behind/below the wall
if Vec2.dot body.v wall.normal > 0 then
Nothing
else
let
-- Vector to start of wall to body center
dir =
Vec2.sub body.p wall.p1
-- Distance from body position along normal
distanceSq =
Vec2.projection dir wall.normal
|> Vec2.lengthSquared
in
if distanceSq <= body.radius ^ 2 then
let
w =
Vec2.sub wall.p2 wall.p1
edgeDistance =
Vec2.dot dir (Vec2.normalize w)
in
-- On p1 edge or past p2 edge?
if edgeDistance < 0 || edgeDistance > Vec2.length w then
-- Let fall
Nothing
else
-- Not on edges, body is touching wall
Just
(WithWall
body.id
{ normal = wall.normal
, penetration = body.radius - sqrt distanceSq
}
)
else
-- Body not touching wall
Nothing
{-| Calculate contact between two physics bodies (circles).
-}
contactWithBody : PhysicsBody a -> PhysicsBody a -> Maybe (Contact a)
contactWithBody body1 body2 =
let
v =
Vec2.sub body2.p body1.p
in
if Vec2.lengthSquared v > (body1.radius + body2.radius) ^ 2 then
Nothing
else
let
d =
Vec2.length v
in
if d /= 0 then
-- Touching
Just
(BetweenBodies
body1.id
body2.id
{ normal = Vec2.normalize v
, penetration = (body1.radius + body2.radius) - d
}
)
else
-- Bodies perfectly overlap, arbitrary pick one
Just
(BetweenBodies
body1.id
body2.id
{ normal = vec2 1 0
, penetration = body1.radius
}
)
{-| Apply accelaration to a physics body.
-}
addImpulse :
Vec2
-> PhysicsBody a
-> PhysicsBody a
addImpulse value body =
{ body
| cumulativeImpulse = Vec2.add body.cumulativeImpulse value
}
| elm |
[
{
"context": "\"5\" ]\n\n [ Result \"1-0\" ]\n\n [ White \"Judit Polgar\" ]\n\n [ Black \"Garry Kasparov\"]\n\n [ ",
"end": 1937,
"score": 0.9998602271,
"start": 1925,
"tag": "NAME",
"value": "Judit Polgar"
},
{
"context": " [ White \"Judit Polgar\" ]\n\n [ Black \"Garry Kasparov\"]\n\n [ ECO \"C67\" ]\n\n [ WhiteElo \"268",
"end": 1973,
"score": 0.9998633265,
"start": 1959,
"tag": "NAME",
"value": "Garry Kasparov"
}
] | src/Pgn.elm | shnewto/pgn | 2 | module Pgn exposing
( Pgn, TagPair, Move
, parse, parseMove, parseMoves, parseTagPair, parseTagPairs
, parseErrorToString
)
{-| This is a library for parsing "Portable Game Notation" (PGN) for standard chess. PGN is a plain text standard for recording chess games. For more information check out [the Wikipedia entry on PGN](https://en.wikipedia.org/wiki/Portable_Game_Notation) or [the PGN spec itself](https://ia802908.us.archive.org/26/items/pgn-standard-1994-03-12/PGN_standard_1994-03-12.txt).
# Data Structures
@docs Pgn, TagPair, Move
# The Parsers
@docs parse, parseMove, parseMoves, parseTagPair, parseTagPairs
# Errors
@docs parseErrorToString
-}
import List.Extra
import Parser
exposing
( (|.)
, (|=)
, DeadEnd
, Nestable(..)
, Parser
, Problem(..)
, Step(..)
, andThen
, backtrackable
, chompWhile
, getChompedString
, lineComment
, loop
, map
, multiComment
, oneOf
, spaces
, succeed
, symbol
, variable
)
import Pgn.Reference as Ref
import Set
{- Public Data Structures -}
{-| The `Pgn` object represents a complete PGN. The tag pairs (or roster) typically contain archival or supplemental information for the game itself. And then there are the moves of the game itself.
-}
type alias Pgn =
{ tagPairs : List TagPair
, moves : List Move
}
{-| The `TagPair` strcuture should minimally contain what is also known as the "Seven Tag Roster" (STR). The tag pairs can extend beyond the standard seven however. A good example of a the tag pairs describing a game looks like this:
[ Event "Russia - The Rest of the World" ]
[ Site "Moscow RUS" ]
[ Date "2002.09.09" ]
[ EventDate "2002.09.08" ]
[ Round "5" ]
[ Result "1-0" ]
[ White "Judit Polgar" ]
[ Black "Garry Kasparov"]
[ ECO "C67" ]
[ WhiteElo "2681" ]
[ BlackElo "2838" ]
[ PlyCount "84" ]
Each statement (starting with `[` and ending with `]`) is a tag pair. So the tag pair `[Result "1-0"]` would be represented in the data structure as `{ title: "Result", value: "1-0"}`
It's **important** to note that tag pairs are treated something like key, value pairs and the value must be in quotes!
-}
type alias TagPair =
{ title : String
, value : String
}
{-| The `Move` data structure contains the move number and the move of each player.
A move in PGN like `42. Rxg7 Kc8` would be represented in this data structure as `{ number: "42", white: "Rxg7", black: "Kc8"}`
-}
type alias Move =
{ number : String
, white : String
, black : String
}
{- Parsers -}
{-| The `parse` function expects a complete PGN as a string and returns either a PGN or a [`DeadEnd`](https://package.elm-lang.org/packages/elm/parser/latest/Parser#DeadEnd) error.
For more information from any errors you see, check out the `parseErrorToString` function.
-}
parse : String -> Result (List DeadEnd) Pgn
parse pgn =
Parser.run game pgn
{-| The `parseMove` function accepts input in the shape of a single line of [Movetext](https://en.wikipedia.org/wiki/Portable_Game_Notation#Movetext), i.e. `1. e4 e5`
parseMove "1. e4 e5" ==
Ok { number = "1", white = "e4", black = "e5" }
-}
parseMove : String -> Result (List DeadEnd) Move
parseMove t =
Parser.run move t
{-| The `parseMoves` function accepts string input in the shape of a multiple lines of [Movetext](https://en.wikipedia.org/wiki/Portable_Game_Notation#Movetext), i.e. `1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6`
parseMoves "1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6" ==
Ok
[ { number = "1"
, white = "e4"
, black = "e5"
}
, { number = "2", white = "Nf3", black = "Nc6" }
, { number = "3", white = "Bb5", black = "Nf6" }
]
-}
parseMoves : String -> Result (List DeadEnd) (List Move)
parseMoves t =
Parser.run moves t
{-| The `parseTagPair` function accepts string input in the shape of a single tag pair, i.e. `[EventDate "2002.09.08"]`
parseTagPair "[EventDate \"2002.09.08\"]" ==
Ok { title = "EventDate", value = "2002.09.08" }
-}
parseTagPair : String -> Result (List DeadEnd) TagPair
parseTagPair r =
Parser.run tagPair r
{-| The `parseTagPairs` function accepts string input in the shape of a series of tag pairs, i.e. `[EventDate "2002.09.08"] [Round "5"]`
parseTagPairs "[EventDate \"2002.09.08\"] [Round \"5\"]" ==
Ok
[ { title = "EventDate"
, value = "2002.09.08"
}
, { title = "Round", value = "5" }
]
-}
parseTagPairs : String -> Result (List DeadEnd) (List TagPair)
parseTagPairs r =
Parser.run tagPairs r
{- Errors -}
{-| The `parseErrorToString` is to help pinpoint what's causing issues with a parse. It simply produces a string for human consumption that describes what the parser thinks went wrong, followed by the line of the error then a `^` below where it thinks the problem is. For example, attempting to parse this invalid tag pair:
[EventTitle After the title, everything else in the tag pair needs to be in quotes!]
would result in this output:
error on row: 1, col: 13. Problem: Expecting: \"
> [EventTitle After the title everything else in the tag pair needs to be in quotes!]
^
-}
parseErrorToString : String -> List DeadEnd -> String
parseErrorToString source deadEnds =
let
rows =
String.split "\n" source
in
deadEnds
|> List.map
(\de ->
let
row =
rows |> List.Extra.getAt (de.row - 1) |> Maybe.withDefault ""
update a _ =
( a ++ " ", [] )
{- start with spaces to cover the lenght of the row's leading characters "> " -}
inital =
" "
--
( spacesToProblem, _ ) =
List.Extra.mapAccuml update inital <| List.range 1 (de.col - 1)
in
"\n\nerror on row: "
++ String.fromInt de.row
++ ", col: "
++ String.fromInt de.col
++ ". Problem: "
++ problemToString de.problem
++ "\n"
++ "> "
++ row
++ "\n"
++ spacesToProblem
++ "^"
)
|> String.join ""
{- Internal -}
charIsWhitespace : Char -> Bool
charIsWhitespace c =
c == ' ' || c == '\t' || c == '\n' || c == '\u{000D}'
tagPair : Parser TagPair
tagPair =
succeed TagPair
|. spaces
|. symbol "["
|. spaces
|= (getChompedString <| chompWhile (\c -> not <| charIsWhitespace c))
|. spaces
|= (getChompedString <| multiComment "\"" "\"" Nestable)
|. spaces
|. symbol "]"
|. spaces
|> andThen (\p -> succeed <| { p | value = String.filter (\c -> c /= '"') p.value })
tagPairs : Parser (List TagPair)
tagPairs =
let
pairs items =
oneOf
[ succeed (\item -> Loop (item :: items))
|= tagPair
, succeed ()
|> map (\_ -> Done <| List.reverse items)
]
in
loop [] pairs
maybeCommentBlock : Parser (Maybe String)
maybeCommentBlock =
oneOf
[ succeed Just
|= (getChompedString <| multiComment "{" "}" Nestable)
, succeed Nothing
]
{-| Exlude all the gotcha variations of the EOF result string
I've seen that confuse the parser:
[ "1/2-1/2", "0-1", "1-0", "1", "0", "-", "/", "2", "-1", "-0" ]
-}
movetext : Parser String
movetext =
variable
{ start = \c -> List.member c <| String.toList Ref.movetextChars
, inner = \c -> List.member c <| String.toList Ref.movetextChars
, reserved = Set.fromList <| [ "1/2-1/2", "0-1", "1-0", "1", "0", "-", "/", "2", "-1", "-0", "1-", "0-" ]
}
moveNumber : Parser String
moveNumber =
variable
{ start = \c -> Char.isDigit c
, inner = \c -> Char.isDigit c || c == '.'
, reserved = Set.fromList [ "1-0", "0-1", "1/2-1/2" ]
}
|> andThen
(\v ->
succeed <| String.filter Char.isDigit v
)
move : Parser Move
move =
let
optional : Parser a -> Parser ()
optional parser =
oneOf
[ succeed ()
|. parser
, succeed ()
]
enforcedWhitespace =
oneOf
[ symbol " "
, symbol "\t"
, symbol "\n"
, symbol "\u{000D}"
]
in
succeed Move
|. spaces
|= backtrackable (moveNumber |. enforcedWhitespace)
|. spaces
|. maybeCommentBlock
|. spaces
|= movetext
|. spaces
|. maybeCommentBlock
|. spaces
|. optional (backtrackable (moveNumber |. enforcedWhitespace))
|. spaces
|. maybeCommentBlock
|. spaces
|= (getChompedString <| optional <| movetext)
|. spaces
|. maybeCommentBlock
|. spaces
|. (optional <| lineComment ";")
|. spaces
moves : Parser (List Move)
moves =
let
turnsHelp items =
oneOf
[ succeed (\item -> Loop (item :: items))
|= backtrackable move
, succeed ()
|> map (\_ -> Done <| List.reverse items)
]
in
loop [] turnsHelp
result : Parser String
result =
let
-- this is silly
condition c =
c == '1' || c == '2' || c == '0' || c == '/' || c == '-' || c == ' ' || c == '\t'
in
succeed identity
|= (getChompedString <| chompWhile <| condition)
game : Parser Pgn
game =
succeed Pgn
|= tagPairs
|= moves
|. result
problemToString : Problem -> String
problemToString problem =
case problem of
Expecting s ->
"Expecting: " ++ s
ExpectingInt ->
"ExpectingInt"
ExpectingHex ->
"ExpectingHex"
ExpectingOctal ->
"ExpectingOctal"
ExpectingBinary ->
"ExpectingBinary"
ExpectingFloat ->
"ExpectingFloat"
ExpectingNumber ->
"ExpectingNumber"
ExpectingVariable ->
"ExpectingVariable"
ExpectingSymbol s ->
"ExpectingSymbol: " ++ s
ExpectingKeyword s ->
"ExpectingKeyword: " ++ s
ExpectingEnd ->
"ExpectingEnd"
UnexpectedChar ->
"UnexpectedChar"
Problem s ->
"Problem: " ++ s
BadRepeat ->
"BadRepeat"
| 56017 | module Pgn exposing
( Pgn, TagPair, Move
, parse, parseMove, parseMoves, parseTagPair, parseTagPairs
, parseErrorToString
)
{-| This is a library for parsing "Portable Game Notation" (PGN) for standard chess. PGN is a plain text standard for recording chess games. For more information check out [the Wikipedia entry on PGN](https://en.wikipedia.org/wiki/Portable_Game_Notation) or [the PGN spec itself](https://ia802908.us.archive.org/26/items/pgn-standard-1994-03-12/PGN_standard_1994-03-12.txt).
# Data Structures
@docs Pgn, TagPair, Move
# The Parsers
@docs parse, parseMove, parseMoves, parseTagPair, parseTagPairs
# Errors
@docs parseErrorToString
-}
import List.Extra
import Parser
exposing
( (|.)
, (|=)
, DeadEnd
, Nestable(..)
, Parser
, Problem(..)
, Step(..)
, andThen
, backtrackable
, chompWhile
, getChompedString
, lineComment
, loop
, map
, multiComment
, oneOf
, spaces
, succeed
, symbol
, variable
)
import Pgn.Reference as Ref
import Set
{- Public Data Structures -}
{-| The `Pgn` object represents a complete PGN. The tag pairs (or roster) typically contain archival or supplemental information for the game itself. And then there are the moves of the game itself.
-}
type alias Pgn =
{ tagPairs : List TagPair
, moves : List Move
}
{-| The `TagPair` strcuture should minimally contain what is also known as the "Seven Tag Roster" (STR). The tag pairs can extend beyond the standard seven however. A good example of a the tag pairs describing a game looks like this:
[ Event "Russia - The Rest of the World" ]
[ Site "Moscow RUS" ]
[ Date "2002.09.09" ]
[ EventDate "2002.09.08" ]
[ Round "5" ]
[ Result "1-0" ]
[ White "<NAME>" ]
[ Black "<NAME>"]
[ ECO "C67" ]
[ WhiteElo "2681" ]
[ BlackElo "2838" ]
[ PlyCount "84" ]
Each statement (starting with `[` and ending with `]`) is a tag pair. So the tag pair `[Result "1-0"]` would be represented in the data structure as `{ title: "Result", value: "1-0"}`
It's **important** to note that tag pairs are treated something like key, value pairs and the value must be in quotes!
-}
type alias TagPair =
{ title : String
, value : String
}
{-| The `Move` data structure contains the move number and the move of each player.
A move in PGN like `42. Rxg7 Kc8` would be represented in this data structure as `{ number: "42", white: "Rxg7", black: "Kc8"}`
-}
type alias Move =
{ number : String
, white : String
, black : String
}
{- Parsers -}
{-| The `parse` function expects a complete PGN as a string and returns either a PGN or a [`DeadEnd`](https://package.elm-lang.org/packages/elm/parser/latest/Parser#DeadEnd) error.
For more information from any errors you see, check out the `parseErrorToString` function.
-}
parse : String -> Result (List DeadEnd) Pgn
parse pgn =
Parser.run game pgn
{-| The `parseMove` function accepts input in the shape of a single line of [Movetext](https://en.wikipedia.org/wiki/Portable_Game_Notation#Movetext), i.e. `1. e4 e5`
parseMove "1. e4 e5" ==
Ok { number = "1", white = "e4", black = "e5" }
-}
parseMove : String -> Result (List DeadEnd) Move
parseMove t =
Parser.run move t
{-| The `parseMoves` function accepts string input in the shape of a multiple lines of [Movetext](https://en.wikipedia.org/wiki/Portable_Game_Notation#Movetext), i.e. `1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6`
parseMoves "1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6" ==
Ok
[ { number = "1"
, white = "e4"
, black = "e5"
}
, { number = "2", white = "Nf3", black = "Nc6" }
, { number = "3", white = "Bb5", black = "Nf6" }
]
-}
parseMoves : String -> Result (List DeadEnd) (List Move)
parseMoves t =
Parser.run moves t
{-| The `parseTagPair` function accepts string input in the shape of a single tag pair, i.e. `[EventDate "2002.09.08"]`
parseTagPair "[EventDate \"2002.09.08\"]" ==
Ok { title = "EventDate", value = "2002.09.08" }
-}
parseTagPair : String -> Result (List DeadEnd) TagPair
parseTagPair r =
Parser.run tagPair r
{-| The `parseTagPairs` function accepts string input in the shape of a series of tag pairs, i.e. `[EventDate "2002.09.08"] [Round "5"]`
parseTagPairs "[EventDate \"2002.09.08\"] [Round \"5\"]" ==
Ok
[ { title = "EventDate"
, value = "2002.09.08"
}
, { title = "Round", value = "5" }
]
-}
parseTagPairs : String -> Result (List DeadEnd) (List TagPair)
parseTagPairs r =
Parser.run tagPairs r
{- Errors -}
{-| The `parseErrorToString` is to help pinpoint what's causing issues with a parse. It simply produces a string for human consumption that describes what the parser thinks went wrong, followed by the line of the error then a `^` below where it thinks the problem is. For example, attempting to parse this invalid tag pair:
[EventTitle After the title, everything else in the tag pair needs to be in quotes!]
would result in this output:
error on row: 1, col: 13. Problem: Expecting: \"
> [EventTitle After the title everything else in the tag pair needs to be in quotes!]
^
-}
parseErrorToString : String -> List DeadEnd -> String
parseErrorToString source deadEnds =
let
rows =
String.split "\n" source
in
deadEnds
|> List.map
(\de ->
let
row =
rows |> List.Extra.getAt (de.row - 1) |> Maybe.withDefault ""
update a _ =
( a ++ " ", [] )
{- start with spaces to cover the lenght of the row's leading characters "> " -}
inital =
" "
--
( spacesToProblem, _ ) =
List.Extra.mapAccuml update inital <| List.range 1 (de.col - 1)
in
"\n\nerror on row: "
++ String.fromInt de.row
++ ", col: "
++ String.fromInt de.col
++ ". Problem: "
++ problemToString de.problem
++ "\n"
++ "> "
++ row
++ "\n"
++ spacesToProblem
++ "^"
)
|> String.join ""
{- Internal -}
charIsWhitespace : Char -> Bool
charIsWhitespace c =
c == ' ' || c == '\t' || c == '\n' || c == '\u{000D}'
tagPair : Parser TagPair
tagPair =
succeed TagPair
|. spaces
|. symbol "["
|. spaces
|= (getChompedString <| chompWhile (\c -> not <| charIsWhitespace c))
|. spaces
|= (getChompedString <| multiComment "\"" "\"" Nestable)
|. spaces
|. symbol "]"
|. spaces
|> andThen (\p -> succeed <| { p | value = String.filter (\c -> c /= '"') p.value })
tagPairs : Parser (List TagPair)
tagPairs =
let
pairs items =
oneOf
[ succeed (\item -> Loop (item :: items))
|= tagPair
, succeed ()
|> map (\_ -> Done <| List.reverse items)
]
in
loop [] pairs
maybeCommentBlock : Parser (Maybe String)
maybeCommentBlock =
oneOf
[ succeed Just
|= (getChompedString <| multiComment "{" "}" Nestable)
, succeed Nothing
]
{-| Exlude all the gotcha variations of the EOF result string
I've seen that confuse the parser:
[ "1/2-1/2", "0-1", "1-0", "1", "0", "-", "/", "2", "-1", "-0" ]
-}
movetext : Parser String
movetext =
variable
{ start = \c -> List.member c <| String.toList Ref.movetextChars
, inner = \c -> List.member c <| String.toList Ref.movetextChars
, reserved = Set.fromList <| [ "1/2-1/2", "0-1", "1-0", "1", "0", "-", "/", "2", "-1", "-0", "1-", "0-" ]
}
moveNumber : Parser String
moveNumber =
variable
{ start = \c -> Char.isDigit c
, inner = \c -> Char.isDigit c || c == '.'
, reserved = Set.fromList [ "1-0", "0-1", "1/2-1/2" ]
}
|> andThen
(\v ->
succeed <| String.filter Char.isDigit v
)
move : Parser Move
move =
let
optional : Parser a -> Parser ()
optional parser =
oneOf
[ succeed ()
|. parser
, succeed ()
]
enforcedWhitespace =
oneOf
[ symbol " "
, symbol "\t"
, symbol "\n"
, symbol "\u{000D}"
]
in
succeed Move
|. spaces
|= backtrackable (moveNumber |. enforcedWhitespace)
|. spaces
|. maybeCommentBlock
|. spaces
|= movetext
|. spaces
|. maybeCommentBlock
|. spaces
|. optional (backtrackable (moveNumber |. enforcedWhitespace))
|. spaces
|. maybeCommentBlock
|. spaces
|= (getChompedString <| optional <| movetext)
|. spaces
|. maybeCommentBlock
|. spaces
|. (optional <| lineComment ";")
|. spaces
moves : Parser (List Move)
moves =
let
turnsHelp items =
oneOf
[ succeed (\item -> Loop (item :: items))
|= backtrackable move
, succeed ()
|> map (\_ -> Done <| List.reverse items)
]
in
loop [] turnsHelp
result : Parser String
result =
let
-- this is silly
condition c =
c == '1' || c == '2' || c == '0' || c == '/' || c == '-' || c == ' ' || c == '\t'
in
succeed identity
|= (getChompedString <| chompWhile <| condition)
game : Parser Pgn
game =
succeed Pgn
|= tagPairs
|= moves
|. result
problemToString : Problem -> String
problemToString problem =
case problem of
Expecting s ->
"Expecting: " ++ s
ExpectingInt ->
"ExpectingInt"
ExpectingHex ->
"ExpectingHex"
ExpectingOctal ->
"ExpectingOctal"
ExpectingBinary ->
"ExpectingBinary"
ExpectingFloat ->
"ExpectingFloat"
ExpectingNumber ->
"ExpectingNumber"
ExpectingVariable ->
"ExpectingVariable"
ExpectingSymbol s ->
"ExpectingSymbol: " ++ s
ExpectingKeyword s ->
"ExpectingKeyword: " ++ s
ExpectingEnd ->
"ExpectingEnd"
UnexpectedChar ->
"UnexpectedChar"
Problem s ->
"Problem: " ++ s
BadRepeat ->
"BadRepeat"
| true | module Pgn exposing
( Pgn, TagPair, Move
, parse, parseMove, parseMoves, parseTagPair, parseTagPairs
, parseErrorToString
)
{-| This is a library for parsing "Portable Game Notation" (PGN) for standard chess. PGN is a plain text standard for recording chess games. For more information check out [the Wikipedia entry on PGN](https://en.wikipedia.org/wiki/Portable_Game_Notation) or [the PGN spec itself](https://ia802908.us.archive.org/26/items/pgn-standard-1994-03-12/PGN_standard_1994-03-12.txt).
# Data Structures
@docs Pgn, TagPair, Move
# The Parsers
@docs parse, parseMove, parseMoves, parseTagPair, parseTagPairs
# Errors
@docs parseErrorToString
-}
import List.Extra
import Parser
exposing
( (|.)
, (|=)
, DeadEnd
, Nestable(..)
, Parser
, Problem(..)
, Step(..)
, andThen
, backtrackable
, chompWhile
, getChompedString
, lineComment
, loop
, map
, multiComment
, oneOf
, spaces
, succeed
, symbol
, variable
)
import Pgn.Reference as Ref
import Set
{- Public Data Structures -}
{-| The `Pgn` object represents a complete PGN. The tag pairs (or roster) typically contain archival or supplemental information for the game itself. And then there are the moves of the game itself.
-}
type alias Pgn =
{ tagPairs : List TagPair
, moves : List Move
}
{-| The `TagPair` strcuture should minimally contain what is also known as the "Seven Tag Roster" (STR). The tag pairs can extend beyond the standard seven however. A good example of a the tag pairs describing a game looks like this:
[ Event "Russia - The Rest of the World" ]
[ Site "Moscow RUS" ]
[ Date "2002.09.09" ]
[ EventDate "2002.09.08" ]
[ Round "5" ]
[ Result "1-0" ]
[ White "PI:NAME:<NAME>END_PI" ]
[ Black "PI:NAME:<NAME>END_PI"]
[ ECO "C67" ]
[ WhiteElo "2681" ]
[ BlackElo "2838" ]
[ PlyCount "84" ]
Each statement (starting with `[` and ending with `]`) is a tag pair. So the tag pair `[Result "1-0"]` would be represented in the data structure as `{ title: "Result", value: "1-0"}`
It's **important** to note that tag pairs are treated something like key, value pairs and the value must be in quotes!
-}
type alias TagPair =
{ title : String
, value : String
}
{-| The `Move` data structure contains the move number and the move of each player.
A move in PGN like `42. Rxg7 Kc8` would be represented in this data structure as `{ number: "42", white: "Rxg7", black: "Kc8"}`
-}
type alias Move =
{ number : String
, white : String
, black : String
}
{- Parsers -}
{-| The `parse` function expects a complete PGN as a string and returns either a PGN or a [`DeadEnd`](https://package.elm-lang.org/packages/elm/parser/latest/Parser#DeadEnd) error.
For more information from any errors you see, check out the `parseErrorToString` function.
-}
parse : String -> Result (List DeadEnd) Pgn
parse pgn =
Parser.run game pgn
{-| The `parseMove` function accepts input in the shape of a single line of [Movetext](https://en.wikipedia.org/wiki/Portable_Game_Notation#Movetext), i.e. `1. e4 e5`
parseMove "1. e4 e5" ==
Ok { number = "1", white = "e4", black = "e5" }
-}
parseMove : String -> Result (List DeadEnd) Move
parseMove t =
Parser.run move t
{-| The `parseMoves` function accepts string input in the shape of a multiple lines of [Movetext](https://en.wikipedia.org/wiki/Portable_Game_Notation#Movetext), i.e. `1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6`
parseMoves "1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6" ==
Ok
[ { number = "1"
, white = "e4"
, black = "e5"
}
, { number = "2", white = "Nf3", black = "Nc6" }
, { number = "3", white = "Bb5", black = "Nf6" }
]
-}
parseMoves : String -> Result (List DeadEnd) (List Move)
parseMoves t =
Parser.run moves t
{-| The `parseTagPair` function accepts string input in the shape of a single tag pair, i.e. `[EventDate "2002.09.08"]`
parseTagPair "[EventDate \"2002.09.08\"]" ==
Ok { title = "EventDate", value = "2002.09.08" }
-}
parseTagPair : String -> Result (List DeadEnd) TagPair
parseTagPair r =
Parser.run tagPair r
{-| The `parseTagPairs` function accepts string input in the shape of a series of tag pairs, i.e. `[EventDate "2002.09.08"] [Round "5"]`
parseTagPairs "[EventDate \"2002.09.08\"] [Round \"5\"]" ==
Ok
[ { title = "EventDate"
, value = "2002.09.08"
}
, { title = "Round", value = "5" }
]
-}
parseTagPairs : String -> Result (List DeadEnd) (List TagPair)
parseTagPairs r =
Parser.run tagPairs r
{- Errors -}
{-| The `parseErrorToString` is to help pinpoint what's causing issues with a parse. It simply produces a string for human consumption that describes what the parser thinks went wrong, followed by the line of the error then a `^` below where it thinks the problem is. For example, attempting to parse this invalid tag pair:
[EventTitle After the title, everything else in the tag pair needs to be in quotes!]
would result in this output:
error on row: 1, col: 13. Problem: Expecting: \"
> [EventTitle After the title everything else in the tag pair needs to be in quotes!]
^
-}
parseErrorToString : String -> List DeadEnd -> String
parseErrorToString source deadEnds =
let
rows =
String.split "\n" source
in
deadEnds
|> List.map
(\de ->
let
row =
rows |> List.Extra.getAt (de.row - 1) |> Maybe.withDefault ""
update a _ =
( a ++ " ", [] )
{- start with spaces to cover the lenght of the row's leading characters "> " -}
inital =
" "
--
( spacesToProblem, _ ) =
List.Extra.mapAccuml update inital <| List.range 1 (de.col - 1)
in
"\n\nerror on row: "
++ String.fromInt de.row
++ ", col: "
++ String.fromInt de.col
++ ". Problem: "
++ problemToString de.problem
++ "\n"
++ "> "
++ row
++ "\n"
++ spacesToProblem
++ "^"
)
|> String.join ""
{- Internal -}
charIsWhitespace : Char -> Bool
charIsWhitespace c =
c == ' ' || c == '\t' || c == '\n' || c == '\u{000D}'
tagPair : Parser TagPair
tagPair =
succeed TagPair
|. spaces
|. symbol "["
|. spaces
|= (getChompedString <| chompWhile (\c -> not <| charIsWhitespace c))
|. spaces
|= (getChompedString <| multiComment "\"" "\"" Nestable)
|. spaces
|. symbol "]"
|. spaces
|> andThen (\p -> succeed <| { p | value = String.filter (\c -> c /= '"') p.value })
tagPairs : Parser (List TagPair)
tagPairs =
let
pairs items =
oneOf
[ succeed (\item -> Loop (item :: items))
|= tagPair
, succeed ()
|> map (\_ -> Done <| List.reverse items)
]
in
loop [] pairs
maybeCommentBlock : Parser (Maybe String)
maybeCommentBlock =
oneOf
[ succeed Just
|= (getChompedString <| multiComment "{" "}" Nestable)
, succeed Nothing
]
{-| Exlude all the gotcha variations of the EOF result string
I've seen that confuse the parser:
[ "1/2-1/2", "0-1", "1-0", "1", "0", "-", "/", "2", "-1", "-0" ]
-}
movetext : Parser String
movetext =
variable
{ start = \c -> List.member c <| String.toList Ref.movetextChars
, inner = \c -> List.member c <| String.toList Ref.movetextChars
, reserved = Set.fromList <| [ "1/2-1/2", "0-1", "1-0", "1", "0", "-", "/", "2", "-1", "-0", "1-", "0-" ]
}
moveNumber : Parser String
moveNumber =
variable
{ start = \c -> Char.isDigit c
, inner = \c -> Char.isDigit c || c == '.'
, reserved = Set.fromList [ "1-0", "0-1", "1/2-1/2" ]
}
|> andThen
(\v ->
succeed <| String.filter Char.isDigit v
)
move : Parser Move
move =
let
optional : Parser a -> Parser ()
optional parser =
oneOf
[ succeed ()
|. parser
, succeed ()
]
enforcedWhitespace =
oneOf
[ symbol " "
, symbol "\t"
, symbol "\n"
, symbol "\u{000D}"
]
in
succeed Move
|. spaces
|= backtrackable (moveNumber |. enforcedWhitespace)
|. spaces
|. maybeCommentBlock
|. spaces
|= movetext
|. spaces
|. maybeCommentBlock
|. spaces
|. optional (backtrackable (moveNumber |. enforcedWhitespace))
|. spaces
|. maybeCommentBlock
|. spaces
|= (getChompedString <| optional <| movetext)
|. spaces
|. maybeCommentBlock
|. spaces
|. (optional <| lineComment ";")
|. spaces
moves : Parser (List Move)
moves =
let
turnsHelp items =
oneOf
[ succeed (\item -> Loop (item :: items))
|= backtrackable move
, succeed ()
|> map (\_ -> Done <| List.reverse items)
]
in
loop [] turnsHelp
result : Parser String
result =
let
-- this is silly
condition c =
c == '1' || c == '2' || c == '0' || c == '/' || c == '-' || c == ' ' || c == '\t'
in
succeed identity
|= (getChompedString <| chompWhile <| condition)
game : Parser Pgn
game =
succeed Pgn
|= tagPairs
|= moves
|. result
problemToString : Problem -> String
problemToString problem =
case problem of
Expecting s ->
"Expecting: " ++ s
ExpectingInt ->
"ExpectingInt"
ExpectingHex ->
"ExpectingHex"
ExpectingOctal ->
"ExpectingOctal"
ExpectingBinary ->
"ExpectingBinary"
ExpectingFloat ->
"ExpectingFloat"
ExpectingNumber ->
"ExpectingNumber"
ExpectingVariable ->
"ExpectingVariable"
ExpectingSymbol s ->
"ExpectingSymbol: " ++ s
ExpectingKeyword s ->
"ExpectingKeyword: " ++ s
ExpectingEnd ->
"ExpectingEnd"
UnexpectedChar ->
"UnexpectedChar"
Problem s ->
"Problem: " ++ s
BadRepeat ->
"BadRepeat"
| elm |
[
{
"context": "sien\"* is a brand created by two French nationals, Joseph (the CEO) and Yannick, (the co-founder), for a Ke",
"end": 343,
"score": 0.9996049404,
"start": 337,
"tag": "NAME",
"value": "Joseph"
},
{
"context": "ated by two French nationals, Joseph (the CEO) and Yannick, (the co-founder), for a Kebab restaurant in Mont",
"end": 365,
"score": 0.9997860789,
"start": 358,
"tag": "NAME",
"value": "Yannick"
}
] | examples/dsm/src/Docs.elm | jgrenat/elm-ui-explorer | 0 | module Docs exposing (about, principles, toMarkdown)
import Html
import Html.Attributes exposing (class)
import Markdown
toMarkdown : String -> Html.Html msg
toMarkdown text =
Markdown.toHtml [ class "content" ] text
about : String
about =
"""
# About Tasty
*"Le grec parisien"* is a brand created by two French nationals, Joseph (the CEO) and Yannick, (the co-founder), for a Kebab restaurant in Montreal.
**Tasty** is the name of the Design System for digital products and experiences around the restaurant.
The system is composed of guidelines, components and code examples.
![Preview](https://www.jerome-kalumbu.com/sites/default/files/logo-duo.jpg)
"""
principles : String
principles =
"""
# Design Principles
- #### Classy;
- #### Premium;
- #### Quality;
- #### Professional;
- #### Simple.
![Preview](https://www.jerome-kalumbu.com/sites/default/files/stylescape.jpg)
"""
| 29210 | module Docs exposing (about, principles, toMarkdown)
import Html
import Html.Attributes exposing (class)
import Markdown
toMarkdown : String -> Html.Html msg
toMarkdown text =
Markdown.toHtml [ class "content" ] text
about : String
about =
"""
# About Tasty
*"Le grec parisien"* is a brand created by two French nationals, <NAME> (the CEO) and <NAME>, (the co-founder), for a Kebab restaurant in Montreal.
**Tasty** is the name of the Design System for digital products and experiences around the restaurant.
The system is composed of guidelines, components and code examples.
![Preview](https://www.jerome-kalumbu.com/sites/default/files/logo-duo.jpg)
"""
principles : String
principles =
"""
# Design Principles
- #### Classy;
- #### Premium;
- #### Quality;
- #### Professional;
- #### Simple.
![Preview](https://www.jerome-kalumbu.com/sites/default/files/stylescape.jpg)
"""
| true | module Docs exposing (about, principles, toMarkdown)
import Html
import Html.Attributes exposing (class)
import Markdown
toMarkdown : String -> Html.Html msg
toMarkdown text =
Markdown.toHtml [ class "content" ] text
about : String
about =
"""
# About Tasty
*"Le grec parisien"* is a brand created by two French nationals, PI:NAME:<NAME>END_PI (the CEO) and PI:NAME:<NAME>END_PI, (the co-founder), for a Kebab restaurant in Montreal.
**Tasty** is the name of the Design System for digital products and experiences around the restaurant.
The system is composed of guidelines, components and code examples.
![Preview](https://www.jerome-kalumbu.com/sites/default/files/logo-duo.jpg)
"""
principles : String
principles =
"""
# Design Principles
- #### Classy;
- #### Premium;
- #### Quality;
- #### Professional;
- #### Simple.
![Preview](https://www.jerome-kalumbu.com/sites/default/files/stylescape.jpg)
"""
| elm |
[
{
"context": "= 1\n , url = \"http://localhost:1337/84.210.50.24:20000/api?command={\\\"id\\\":1,\\\"method\\\":\\\"info\\\",\\",
"end": 425,
"score": 0.999243021,
"start": 416,
"tag": "IP_ADDRESS",
"value": "210.50.24"
},
{
"context": ":[]}&nocache=1521910258052\"\n , name = \"pengane\"\n , uptime = -1\n , cards = ",
"end": 541,
"score": 0.9846858978,
"start": 534,
"tag": "NAME",
"value": "pengane"
},
{
"context": " }\n\n banken =\n Banken \"1JhrSWPuHgV71vzPZdNiQyamVYotuyKD4H\" 0.0 0.0\n in\n { pengane = pengane\n ",
"end": 680,
"score": 0.9252880812,
"start": 646,
"tag": "KEY",
"value": "1JhrSWPuHgV71vzPZdNiQyamVYotuyKD4H"
}
] | src/models/Model.elm | knutnyg/minermaster | 0 | module Model exposing (..)
import Node exposing (..)
import Messages exposing (..)
import Task exposing (..)
import Time exposing (..)
import Api exposing (..)
import Banken exposing (..)
type alias Model =
{ pengane : Node
, knutminer : Maybe Node
, banken : Banken
}
init : ( Model, Cmd Msg )
init =
let
pengane =
{ id = 1
, url = "http://localhost:1337/84.210.50.24:20000/api?command={\"id\":1,\"method\":\"info\",\"params\":[]}&nocache=1521910258052"
, name = "pengane"
, uptime = -1
, cards = []
}
banken =
Banken "1JhrSWPuHgV71vzPZdNiQyamVYotuyKD4H" 0.0 0.0
in
{ pengane = pengane
, knutminer = Nothing
, banken = banken
}
! [ (fetch pengane), (fetchCards pengane), (fetchWalletBalance banken) ]
| 12158 | module Model exposing (..)
import Node exposing (..)
import Messages exposing (..)
import Task exposing (..)
import Time exposing (..)
import Api exposing (..)
import Banken exposing (..)
type alias Model =
{ pengane : Node
, knutminer : Maybe Node
, banken : Banken
}
init : ( Model, Cmd Msg )
init =
let
pengane =
{ id = 1
, url = "http://localhost:1337/84.210.50.24:20000/api?command={\"id\":1,\"method\":\"info\",\"params\":[]}&nocache=1521910258052"
, name = "<NAME>"
, uptime = -1
, cards = []
}
banken =
Banken "<KEY>" 0.0 0.0
in
{ pengane = pengane
, knutminer = Nothing
, banken = banken
}
! [ (fetch pengane), (fetchCards pengane), (fetchWalletBalance banken) ]
| true | module Model exposing (..)
import Node exposing (..)
import Messages exposing (..)
import Task exposing (..)
import Time exposing (..)
import Api exposing (..)
import Banken exposing (..)
type alias Model =
{ pengane : Node
, knutminer : Maybe Node
, banken : Banken
}
init : ( Model, Cmd Msg )
init =
let
pengane =
{ id = 1
, url = "http://localhost:1337/84.210.50.24:20000/api?command={\"id\":1,\"method\":\"info\",\"params\":[]}&nocache=1521910258052"
, name = "PI:NAME:<NAME>END_PI"
, uptime = -1
, cards = []
}
banken =
Banken "PI:KEY:<KEY>END_PI" 0.0 0.0
in
{ pengane = pengane
, knutminer = Nothing
, banken = banken
}
! [ (fetch pengane), (fetchCards pengane), (fetchWalletBalance banken) ]
| elm |
[
{
"context": "t below the Cliff House, also owned by\n Adolph Sutro at the time. Shortly after closing, a fire in 196",
"end": 2038,
"score": 0.9998720288,
"start": 2026,
"tag": "NAME",
"value": "Adolph Sutro"
},
{
"context": "pg\"\n , title = title\n , author = \"A story by Nancy Drew\"\n , lead = lead\n , copyLead = \"Before it bu",
"end": 2634,
"score": 0.9998846054,
"start": 2624,
"tag": "NAME",
"value": "Nancy Drew"
}
] | src/Article/PhotoEssay/Article.elm | paulfioravanti/tachyons-components | 0 | module Article.PhotoEssay.Article exposing
( Article
, Photo
, example
, image009
, image010
, image011
, image012
, image013
)
type alias Article =
{ backgroundImageUrl : String
, title : String
, author : String
, lead : String
, copyLead : String
, copy : String
}
type alias Photo =
{ url : String
, caption : String
}
image009 : Photo
image009 =
{ url = "https://mrmrs.github.io/photos/009.jpg"
, caption = ""
}
image010 : Photo
image010 =
{ url = "https://mrmrs.github.io/photos/010.jpg"
, caption =
"Photo of a dusk skyline above a grassy rockface covered in trees."
}
image011 : Photo
image011 =
let
caption =
"""
Photo of the sea and sky on the horizon with the
foundations of a demolished house.
"""
in
{ url = "https://mrmrs.github.io/photos/011.jpg"
, caption = caption
}
image012 : Photo
image012 =
let
caption =
"""
Photo of the sea with mist covering the rocky
formations near the shore.
"""
in
{ url = "https://mrmrs.github.io/photos/012.jpg"
, caption = caption
}
image013 : Photo
image013 =
let
caption =
"""
Photo of the foundations of a building on a cliff overlooking
a lighthouse.
"""
in
{ url = "https://mrmrs.github.io/photos/013.jpg"
, caption = caption
}
example : Article
example =
let
title =
"""
A Night Taking Photos at San Francisco’s Spooky Ruins
of the Sutro Baths
"""
lead =
"""
On March 14, 1896, the Sutro Baths were opened to the public as the
world's largest indoor swimming pool establishment.
"""
copy =
"""
filled a small beach inlet below the Cliff House, also owned by
Adolph Sutro at the time. Shortly after closing, a fire in 1966
destroyed the building while it was in the process of being
demolished. All that remains of the site are concrete walls,
blocked off stairs and passageways, and a tunnel with a deep
crevice in the middle. The cause of the fire was arson. Shortly
afterwards, the developer left San Francisco and claimed
insurance money.
"""
in
{ backgroundImageUrl = "https://mrmrs.github.io/photos/display.jpg"
, title = title
, author = "A story by Nancy Drew"
, lead = lead
, copyLead = "Before it burned to the ground, the structure "
, copy = copy
}
| 9830 | module Article.PhotoEssay.Article exposing
( Article
, Photo
, example
, image009
, image010
, image011
, image012
, image013
)
type alias Article =
{ backgroundImageUrl : String
, title : String
, author : String
, lead : String
, copyLead : String
, copy : String
}
type alias Photo =
{ url : String
, caption : String
}
image009 : Photo
image009 =
{ url = "https://mrmrs.github.io/photos/009.jpg"
, caption = ""
}
image010 : Photo
image010 =
{ url = "https://mrmrs.github.io/photos/010.jpg"
, caption =
"Photo of a dusk skyline above a grassy rockface covered in trees."
}
image011 : Photo
image011 =
let
caption =
"""
Photo of the sea and sky on the horizon with the
foundations of a demolished house.
"""
in
{ url = "https://mrmrs.github.io/photos/011.jpg"
, caption = caption
}
image012 : Photo
image012 =
let
caption =
"""
Photo of the sea with mist covering the rocky
formations near the shore.
"""
in
{ url = "https://mrmrs.github.io/photos/012.jpg"
, caption = caption
}
image013 : Photo
image013 =
let
caption =
"""
Photo of the foundations of a building on a cliff overlooking
a lighthouse.
"""
in
{ url = "https://mrmrs.github.io/photos/013.jpg"
, caption = caption
}
example : Article
example =
let
title =
"""
A Night Taking Photos at San Francisco’s Spooky Ruins
of the Sutro Baths
"""
lead =
"""
On March 14, 1896, the Sutro Baths were opened to the public as the
world's largest indoor swimming pool establishment.
"""
copy =
"""
filled a small beach inlet below the Cliff House, also owned by
<NAME> at the time. Shortly after closing, a fire in 1966
destroyed the building while it was in the process of being
demolished. All that remains of the site are concrete walls,
blocked off stairs and passageways, and a tunnel with a deep
crevice in the middle. The cause of the fire was arson. Shortly
afterwards, the developer left San Francisco and claimed
insurance money.
"""
in
{ backgroundImageUrl = "https://mrmrs.github.io/photos/display.jpg"
, title = title
, author = "A story by <NAME>"
, lead = lead
, copyLead = "Before it burned to the ground, the structure "
, copy = copy
}
| true | module Article.PhotoEssay.Article exposing
( Article
, Photo
, example
, image009
, image010
, image011
, image012
, image013
)
type alias Article =
{ backgroundImageUrl : String
, title : String
, author : String
, lead : String
, copyLead : String
, copy : String
}
type alias Photo =
{ url : String
, caption : String
}
image009 : Photo
image009 =
{ url = "https://mrmrs.github.io/photos/009.jpg"
, caption = ""
}
image010 : Photo
image010 =
{ url = "https://mrmrs.github.io/photos/010.jpg"
, caption =
"Photo of a dusk skyline above a grassy rockface covered in trees."
}
image011 : Photo
image011 =
let
caption =
"""
Photo of the sea and sky on the horizon with the
foundations of a demolished house.
"""
in
{ url = "https://mrmrs.github.io/photos/011.jpg"
, caption = caption
}
image012 : Photo
image012 =
let
caption =
"""
Photo of the sea with mist covering the rocky
formations near the shore.
"""
in
{ url = "https://mrmrs.github.io/photos/012.jpg"
, caption = caption
}
image013 : Photo
image013 =
let
caption =
"""
Photo of the foundations of a building on a cliff overlooking
a lighthouse.
"""
in
{ url = "https://mrmrs.github.io/photos/013.jpg"
, caption = caption
}
example : Article
example =
let
title =
"""
A Night Taking Photos at San Francisco’s Spooky Ruins
of the Sutro Baths
"""
lead =
"""
On March 14, 1896, the Sutro Baths were opened to the public as the
world's largest indoor swimming pool establishment.
"""
copy =
"""
filled a small beach inlet below the Cliff House, also owned by
PI:NAME:<NAME>END_PI at the time. Shortly after closing, a fire in 1966
destroyed the building while it was in the process of being
demolished. All that remains of the site are concrete walls,
blocked off stairs and passageways, and a tunnel with a deep
crevice in the middle. The cause of the fire was arson. Shortly
afterwards, the developer left San Francisco and claimed
insurance money.
"""
in
{ backgroundImageUrl = "https://mrmrs.github.io/photos/display.jpg"
, title = title
, author = "A story by PI:NAME:<NAME>END_PI"
, lead = lead
, copyLead = "Before it burned to the ground, the structure "
, copy = copy
}
| elm |
[
{
"context": "hourBalanceOfCurrentMonth = Nothing\n , user = { firstName = \"\", lastName = \"\", previousBalance = 0 }\n , ",
"end": 5184,
"score": 0.9955840707,
"start": 5175,
"tag": "NAME",
"value": "firstName"
},
{
"context": "rentMonth = Nothing\n , user = { firstName = \"\", lastName = \"\", previousBalance = 0 }\n , holidays = []\n ",
"end": 5199,
"score": 0.9980613589,
"start": 5191,
"tag": "NAME",
"value": "lastName"
}
] | tests/DateUtilsTest.elm | deiga/finnish-harvest-hours | 0 | module DateUtilsTest exposing (all)
import Date exposing (Unit(..), fromCalendarDate, fromPosix)
import Time exposing (millisToPosix, utc)
import DateUtils exposing (..)
import Expect
import Material
import Model exposing (..)
import Test exposing (..)
import Time exposing (Month(..))
all : Test
all =
describe "Date utils"
[ test "only entries within current month are added up" <|
\() ->
let
model =
{ initialModel
| currentDate = fromCalendarDate 2017 Mar 5
, today = fromCalendarDate 2017 Mar 2
, entries =
[ DateEntries (fromCalendarDate 2017 Feb 28)
[ Entry 2.5 123, Entry 7 234 ]
, DateEntries (fromCalendarDate 2017 Mar 1)
[ Entry 5 123, Entry 2.5 234 ]
, DateEntries (fromCalendarDate 2017 Mar 2)
[ Entry 2.5 123, Entry 5 234 ]
, DateEntries (fromCalendarDate 2017 Apr 1)
[ Entry 2.5 123, Entry 7 234 ]
]
}
in
hourBalanceOfCurrentMonth model
|> Expect.equal 0
, test "day has only special task entries" <|
\() ->
let
specialTasks =
{ kiky = [ { id = 123 } ]
, ignore = [ { id = 234 } ]
}
dateEntries =
DateEntries (fromCalendarDate 2017 Feb 28)
[ Entry 2.5 123, Entry 7 234 ]
in
dayHasOnlySpecialTasks dateEntries specialTasks
|> Expect.true "Expected the day to have only special task entries."
, test "day has no task entries" <|
\() ->
let
specialTasks =
{ kiky = [ { id = 123 } ]
, ignore = [ { id = 234 } ]
}
dateEntries =
DateEntries (fromCalendarDate 2017 Feb 28)
[]
in
dayHasOnlySpecialTasks dateEntries specialTasks
|> Expect.false "Expected the day to have no special task entries."
, test "day has special and normal task entries" <|
\() ->
let
specialTasks =
{ kiky = [ { id = 123 } ]
, ignore = [ { id = 234 } ]
}
dateEntries =
DateEntries (fromCalendarDate 2017 Feb 28)
[ Entry 2.5 123, Entry 2.5 234, Entry 2 1000 ]
in
dayHasOnlySpecialTasks dateEntries specialTasks
|> Expect.false "Expected the day to have also normal task entries."
, describe "dateInCurrentMonth"
[ test "start of month" <|
\_ ->
dateInCurrentMonth (fromCalendarDate 2017 Mar 1) (fromCalendarDate 2017 Mar 1)
|> Expect.true "First of March should be within March"
, test "end of month" <|
\_ ->
dateInCurrentMonth (fromCalendarDate 2017 Mar 31) (fromCalendarDate 2017 Mar 1)
|> Expect.true "Last of March should be within March"
, test "not in month" <|
\_ ->
dateInCurrentMonth (fromCalendarDate 2017 Jun 31) (fromCalendarDate 2017 Mar 1)
|> Expect.false "Last of June should not be within March"
]
, describe "totalHoursForMonth"
[
test "March should have 15 hours" <|
\_ ->
let
model =
{ initialModel
| currentDate = fromCalendarDate 2017 Mar 5
, today = fromCalendarDate 2017 Mar 2
, entries =
[ DateEntries (fromCalendarDate 2017 Mar 1)
[ Entry 5 123, Entry 2.5 234 ]
, DateEntries (fromCalendarDate 2017 Mar 2)
[ Entry 2.5 123, Entry 5 234 ]
]
}
in
totalHoursForMonth model
|> Expect.equal 15
]
]
initialModel : Model
initialModel =
{ httpError = Ok ()
, loading = True
, today = fromPosix utc (millisToPosix 0)
, currentDate = fromPosix utc (millisToPosix 0)
, entries = []
, totalHours = Nothing
, kikyHours = Nothing
, hourBalanceOfCurrentMonth = Nothing
, user = { firstName = "", lastName = "", previousBalance = 0 }
, holidays = []
, specialTasks =
{ ignore = []
, kiky = []
}
, previousBalanceString = ""
, previousBalance = 0
, mdc = Material.defaultModel
, showDialog = False
}
| 4473 | module DateUtilsTest exposing (all)
import Date exposing (Unit(..), fromCalendarDate, fromPosix)
import Time exposing (millisToPosix, utc)
import DateUtils exposing (..)
import Expect
import Material
import Model exposing (..)
import Test exposing (..)
import Time exposing (Month(..))
all : Test
all =
describe "Date utils"
[ test "only entries within current month are added up" <|
\() ->
let
model =
{ initialModel
| currentDate = fromCalendarDate 2017 Mar 5
, today = fromCalendarDate 2017 Mar 2
, entries =
[ DateEntries (fromCalendarDate 2017 Feb 28)
[ Entry 2.5 123, Entry 7 234 ]
, DateEntries (fromCalendarDate 2017 Mar 1)
[ Entry 5 123, Entry 2.5 234 ]
, DateEntries (fromCalendarDate 2017 Mar 2)
[ Entry 2.5 123, Entry 5 234 ]
, DateEntries (fromCalendarDate 2017 Apr 1)
[ Entry 2.5 123, Entry 7 234 ]
]
}
in
hourBalanceOfCurrentMonth model
|> Expect.equal 0
, test "day has only special task entries" <|
\() ->
let
specialTasks =
{ kiky = [ { id = 123 } ]
, ignore = [ { id = 234 } ]
}
dateEntries =
DateEntries (fromCalendarDate 2017 Feb 28)
[ Entry 2.5 123, Entry 7 234 ]
in
dayHasOnlySpecialTasks dateEntries specialTasks
|> Expect.true "Expected the day to have only special task entries."
, test "day has no task entries" <|
\() ->
let
specialTasks =
{ kiky = [ { id = 123 } ]
, ignore = [ { id = 234 } ]
}
dateEntries =
DateEntries (fromCalendarDate 2017 Feb 28)
[]
in
dayHasOnlySpecialTasks dateEntries specialTasks
|> Expect.false "Expected the day to have no special task entries."
, test "day has special and normal task entries" <|
\() ->
let
specialTasks =
{ kiky = [ { id = 123 } ]
, ignore = [ { id = 234 } ]
}
dateEntries =
DateEntries (fromCalendarDate 2017 Feb 28)
[ Entry 2.5 123, Entry 2.5 234, Entry 2 1000 ]
in
dayHasOnlySpecialTasks dateEntries specialTasks
|> Expect.false "Expected the day to have also normal task entries."
, describe "dateInCurrentMonth"
[ test "start of month" <|
\_ ->
dateInCurrentMonth (fromCalendarDate 2017 Mar 1) (fromCalendarDate 2017 Mar 1)
|> Expect.true "First of March should be within March"
, test "end of month" <|
\_ ->
dateInCurrentMonth (fromCalendarDate 2017 Mar 31) (fromCalendarDate 2017 Mar 1)
|> Expect.true "Last of March should be within March"
, test "not in month" <|
\_ ->
dateInCurrentMonth (fromCalendarDate 2017 Jun 31) (fromCalendarDate 2017 Mar 1)
|> Expect.false "Last of June should not be within March"
]
, describe "totalHoursForMonth"
[
test "March should have 15 hours" <|
\_ ->
let
model =
{ initialModel
| currentDate = fromCalendarDate 2017 Mar 5
, today = fromCalendarDate 2017 Mar 2
, entries =
[ DateEntries (fromCalendarDate 2017 Mar 1)
[ Entry 5 123, Entry 2.5 234 ]
, DateEntries (fromCalendarDate 2017 Mar 2)
[ Entry 2.5 123, Entry 5 234 ]
]
}
in
totalHoursForMonth model
|> Expect.equal 15
]
]
initialModel : Model
initialModel =
{ httpError = Ok ()
, loading = True
, today = fromPosix utc (millisToPosix 0)
, currentDate = fromPosix utc (millisToPosix 0)
, entries = []
, totalHours = Nothing
, kikyHours = Nothing
, hourBalanceOfCurrentMonth = Nothing
, user = { <NAME> = "", <NAME> = "", previousBalance = 0 }
, holidays = []
, specialTasks =
{ ignore = []
, kiky = []
}
, previousBalanceString = ""
, previousBalance = 0
, mdc = Material.defaultModel
, showDialog = False
}
| true | module DateUtilsTest exposing (all)
import Date exposing (Unit(..), fromCalendarDate, fromPosix)
import Time exposing (millisToPosix, utc)
import DateUtils exposing (..)
import Expect
import Material
import Model exposing (..)
import Test exposing (..)
import Time exposing (Month(..))
all : Test
all =
describe "Date utils"
[ test "only entries within current month are added up" <|
\() ->
let
model =
{ initialModel
| currentDate = fromCalendarDate 2017 Mar 5
, today = fromCalendarDate 2017 Mar 2
, entries =
[ DateEntries (fromCalendarDate 2017 Feb 28)
[ Entry 2.5 123, Entry 7 234 ]
, DateEntries (fromCalendarDate 2017 Mar 1)
[ Entry 5 123, Entry 2.5 234 ]
, DateEntries (fromCalendarDate 2017 Mar 2)
[ Entry 2.5 123, Entry 5 234 ]
, DateEntries (fromCalendarDate 2017 Apr 1)
[ Entry 2.5 123, Entry 7 234 ]
]
}
in
hourBalanceOfCurrentMonth model
|> Expect.equal 0
, test "day has only special task entries" <|
\() ->
let
specialTasks =
{ kiky = [ { id = 123 } ]
, ignore = [ { id = 234 } ]
}
dateEntries =
DateEntries (fromCalendarDate 2017 Feb 28)
[ Entry 2.5 123, Entry 7 234 ]
in
dayHasOnlySpecialTasks dateEntries specialTasks
|> Expect.true "Expected the day to have only special task entries."
, test "day has no task entries" <|
\() ->
let
specialTasks =
{ kiky = [ { id = 123 } ]
, ignore = [ { id = 234 } ]
}
dateEntries =
DateEntries (fromCalendarDate 2017 Feb 28)
[]
in
dayHasOnlySpecialTasks dateEntries specialTasks
|> Expect.false "Expected the day to have no special task entries."
, test "day has special and normal task entries" <|
\() ->
let
specialTasks =
{ kiky = [ { id = 123 } ]
, ignore = [ { id = 234 } ]
}
dateEntries =
DateEntries (fromCalendarDate 2017 Feb 28)
[ Entry 2.5 123, Entry 2.5 234, Entry 2 1000 ]
in
dayHasOnlySpecialTasks dateEntries specialTasks
|> Expect.false "Expected the day to have also normal task entries."
, describe "dateInCurrentMonth"
[ test "start of month" <|
\_ ->
dateInCurrentMonth (fromCalendarDate 2017 Mar 1) (fromCalendarDate 2017 Mar 1)
|> Expect.true "First of March should be within March"
, test "end of month" <|
\_ ->
dateInCurrentMonth (fromCalendarDate 2017 Mar 31) (fromCalendarDate 2017 Mar 1)
|> Expect.true "Last of March should be within March"
, test "not in month" <|
\_ ->
dateInCurrentMonth (fromCalendarDate 2017 Jun 31) (fromCalendarDate 2017 Mar 1)
|> Expect.false "Last of June should not be within March"
]
, describe "totalHoursForMonth"
[
test "March should have 15 hours" <|
\_ ->
let
model =
{ initialModel
| currentDate = fromCalendarDate 2017 Mar 5
, today = fromCalendarDate 2017 Mar 2
, entries =
[ DateEntries (fromCalendarDate 2017 Mar 1)
[ Entry 5 123, Entry 2.5 234 ]
, DateEntries (fromCalendarDate 2017 Mar 2)
[ Entry 2.5 123, Entry 5 234 ]
]
}
in
totalHoursForMonth model
|> Expect.equal 15
]
]
initialModel : Model
initialModel =
{ httpError = Ok ()
, loading = True
, today = fromPosix utc (millisToPosix 0)
, currentDate = fromPosix utc (millisToPosix 0)
, entries = []
, totalHours = Nothing
, kikyHours = Nothing
, hourBalanceOfCurrentMonth = Nothing
, user = { PI:NAME:<NAME>END_PI = "", PI:NAME:<NAME>END_PI = "", previousBalance = 0 }
, holidays = []
, specialTasks =
{ ignore = []
, kiky = []
}
, previousBalanceString = ""
, previousBalance = 0
, mdc = Material.defaultModel
, showDialog = False
}
| elm |
[
{
"context": "\n-- ]\n-- (text \"My Name is Spartacus\")\n-- , row\n-- [ --Content.ver",
"end": 2771,
"score": 0.9985404015,
"start": 2762,
"tag": "NAME",
"value": "Spartacus"
}
] | experiments/Slim/SlimMaster.elm | CurrySoftware/style-elements | 493 | module Main exposing (..)
import AnimationFrame
import Color exposing (Color)
import Element exposing (..)
import Element.Attributes exposing (..)
import Element.Color as Color
import Element.Font as Font
import Element.Shadow as Shadow
import Html
import Html.Attributes
import Html.Events
import Input as Input
import Internal.Style as Internal
import Mouse
import Time exposing (Time)
main =
Html.program
{ init =
( Debug.log "init"
{ timeline = 0
, trackingMouse = False
}
, Cmd.none
)
, view = view
, update = update
, subscriptions =
\model -> Sub.none
}
type Msg
= NoOp
update msg model =
case msg of
NoOp ->
( model, Cmd.none )
{- Revised Alignment
alignLeft, alignRight, center, verticalCenter, alignTop, alignBottom all apply to the element they are attached to.
spread, spreadVertically, and spacing all apply to children.
-}
view model =
layout [] <|
column []
[ row
[ height (px 100)
, Color.background Color.green
, Color.text Color.white
, spaceEvenly
]
[ el
[ link "http://zombo.com"
--height (px 8000)
-- alignTop
]
(text "Hello World!!")
, el
[--height (px 8000)
-- alignTop
]
(text "Hello World!!")
, el
[--height (px 8000)
-- alignTop
]
(text "Hello World!! BLABLABLABLABLABLBALA")
]
, el [] (text "MAIN CONTENT")
, Input.text [ center, width (px 800) ]
{ text = "Helloooooo!"
, onChange = always NoOp
, placeholder = Nothing
, label = Input.LabelOnRight empty
}
]
-- column []
-- [ row
-- [ Color.background Color.white
-- , height (px 80)
-- , center
-- -- , Content.verticalCenter
-- ]
-- [ el
-- [ --Content.verticalCenter
-- -- , Content.alignLeft
-- moveDown 80
-- , Color.background Color.blue
-- , Color.text Color.white
-- ]
-- (text "My Logo")
-- , el
-- [ --Content.verticalCenter
-- -- , Content.center
-- Font.center
-- -- , center
-- ]
-- (text "My Name is Spartacus")
-- , row
-- [ --Content.verticalCenter
-- -- , Content.alignRight
-- Color.background Color.yellow
-- ]
-- [ text "hello!"
-- , text "hello!"
-- , el
-- [ --Content.verticalCenter
-- below
-- (el [ Color.background Color.blue ] (text "I am below, yup!"))
-- ]
-- (text "hello!")
-- ]
-- ]
-- , el
-- [ Font.family
-- [ Font.typeface "Inconsolata"
-- , Font.monospace
-- ]
-- , Color.background Color.blue
-- , Color.text Color.white
-- , paddingXY 30 50
-- , center
-- , width (px 600)
-- ]
-- (text Internal.rules)
-- , textPage
-- [ spacing 10
-- , center
-- , Color.background Color.lightGrey
-- ]
-- [ el
-- [ width (px 50)
-- , height (px 50)
-- , Color.background Color.blue
-- , alignLeft
-- ]
-- empty
-- , paragraph []
-- [ text ipsum
-- ]
-- , paragraph []
-- [ text ipsum
-- ]
-- , paragraph []
-- [ text ipsum
-- ]
-- , el
-- [ width (px 50)
-- , height (px 50)
-- , Color.background Color.blue
-- , alignLeft
-- ]
-- empty
-- , paragraph []
-- [ text ipsum
-- ]
-- ]
-- , column [ spacing 20, padding 20, width (px 200), Color.background Color.grey ]
-- [ el [ width fill, height (px 20), Color.background Color.blue ] empty
-- , el [ width expand, height (px 20), Color.background Color.blue ] empty
-- , el [ width fill, height (px 20), Color.background Color.blue ] empty
-- ]
-- ]
-- view model =
-- layoutWith []
-- { modal = el [] empty
-- , content =
-- column []
-- }
-- view model =
-- layoutWith
-- { modal = el [] empty
-- , attributes = []
-- }
-- <|
-- column [] []
| 37245 | module Main exposing (..)
import AnimationFrame
import Color exposing (Color)
import Element exposing (..)
import Element.Attributes exposing (..)
import Element.Color as Color
import Element.Font as Font
import Element.Shadow as Shadow
import Html
import Html.Attributes
import Html.Events
import Input as Input
import Internal.Style as Internal
import Mouse
import Time exposing (Time)
main =
Html.program
{ init =
( Debug.log "init"
{ timeline = 0
, trackingMouse = False
}
, Cmd.none
)
, view = view
, update = update
, subscriptions =
\model -> Sub.none
}
type Msg
= NoOp
update msg model =
case msg of
NoOp ->
( model, Cmd.none )
{- Revised Alignment
alignLeft, alignRight, center, verticalCenter, alignTop, alignBottom all apply to the element they are attached to.
spread, spreadVertically, and spacing all apply to children.
-}
view model =
layout [] <|
column []
[ row
[ height (px 100)
, Color.background Color.green
, Color.text Color.white
, spaceEvenly
]
[ el
[ link "http://zombo.com"
--height (px 8000)
-- alignTop
]
(text "Hello World!!")
, el
[--height (px 8000)
-- alignTop
]
(text "Hello World!!")
, el
[--height (px 8000)
-- alignTop
]
(text "Hello World!! BLABLABLABLABLABLBALA")
]
, el [] (text "MAIN CONTENT")
, Input.text [ center, width (px 800) ]
{ text = "Helloooooo!"
, onChange = always NoOp
, placeholder = Nothing
, label = Input.LabelOnRight empty
}
]
-- column []
-- [ row
-- [ Color.background Color.white
-- , height (px 80)
-- , center
-- -- , Content.verticalCenter
-- ]
-- [ el
-- [ --Content.verticalCenter
-- -- , Content.alignLeft
-- moveDown 80
-- , Color.background Color.blue
-- , Color.text Color.white
-- ]
-- (text "My Logo")
-- , el
-- [ --Content.verticalCenter
-- -- , Content.center
-- Font.center
-- -- , center
-- ]
-- (text "My Name is <NAME>")
-- , row
-- [ --Content.verticalCenter
-- -- , Content.alignRight
-- Color.background Color.yellow
-- ]
-- [ text "hello!"
-- , text "hello!"
-- , el
-- [ --Content.verticalCenter
-- below
-- (el [ Color.background Color.blue ] (text "I am below, yup!"))
-- ]
-- (text "hello!")
-- ]
-- ]
-- , el
-- [ Font.family
-- [ Font.typeface "Inconsolata"
-- , Font.monospace
-- ]
-- , Color.background Color.blue
-- , Color.text Color.white
-- , paddingXY 30 50
-- , center
-- , width (px 600)
-- ]
-- (text Internal.rules)
-- , textPage
-- [ spacing 10
-- , center
-- , Color.background Color.lightGrey
-- ]
-- [ el
-- [ width (px 50)
-- , height (px 50)
-- , Color.background Color.blue
-- , alignLeft
-- ]
-- empty
-- , paragraph []
-- [ text ipsum
-- ]
-- , paragraph []
-- [ text ipsum
-- ]
-- , paragraph []
-- [ text ipsum
-- ]
-- , el
-- [ width (px 50)
-- , height (px 50)
-- , Color.background Color.blue
-- , alignLeft
-- ]
-- empty
-- , paragraph []
-- [ text ipsum
-- ]
-- ]
-- , column [ spacing 20, padding 20, width (px 200), Color.background Color.grey ]
-- [ el [ width fill, height (px 20), Color.background Color.blue ] empty
-- , el [ width expand, height (px 20), Color.background Color.blue ] empty
-- , el [ width fill, height (px 20), Color.background Color.blue ] empty
-- ]
-- ]
-- view model =
-- layoutWith []
-- { modal = el [] empty
-- , content =
-- column []
-- }
-- view model =
-- layoutWith
-- { modal = el [] empty
-- , attributes = []
-- }
-- <|
-- column [] []
| true | module Main exposing (..)
import AnimationFrame
import Color exposing (Color)
import Element exposing (..)
import Element.Attributes exposing (..)
import Element.Color as Color
import Element.Font as Font
import Element.Shadow as Shadow
import Html
import Html.Attributes
import Html.Events
import Input as Input
import Internal.Style as Internal
import Mouse
import Time exposing (Time)
main =
Html.program
{ init =
( Debug.log "init"
{ timeline = 0
, trackingMouse = False
}
, Cmd.none
)
, view = view
, update = update
, subscriptions =
\model -> Sub.none
}
type Msg
= NoOp
update msg model =
case msg of
NoOp ->
( model, Cmd.none )
{- Revised Alignment
alignLeft, alignRight, center, verticalCenter, alignTop, alignBottom all apply to the element they are attached to.
spread, spreadVertically, and spacing all apply to children.
-}
view model =
layout [] <|
column []
[ row
[ height (px 100)
, Color.background Color.green
, Color.text Color.white
, spaceEvenly
]
[ el
[ link "http://zombo.com"
--height (px 8000)
-- alignTop
]
(text "Hello World!!")
, el
[--height (px 8000)
-- alignTop
]
(text "Hello World!!")
, el
[--height (px 8000)
-- alignTop
]
(text "Hello World!! BLABLABLABLABLABLBALA")
]
, el [] (text "MAIN CONTENT")
, Input.text [ center, width (px 800) ]
{ text = "Helloooooo!"
, onChange = always NoOp
, placeholder = Nothing
, label = Input.LabelOnRight empty
}
]
-- column []
-- [ row
-- [ Color.background Color.white
-- , height (px 80)
-- , center
-- -- , Content.verticalCenter
-- ]
-- [ el
-- [ --Content.verticalCenter
-- -- , Content.alignLeft
-- moveDown 80
-- , Color.background Color.blue
-- , Color.text Color.white
-- ]
-- (text "My Logo")
-- , el
-- [ --Content.verticalCenter
-- -- , Content.center
-- Font.center
-- -- , center
-- ]
-- (text "My Name is PI:NAME:<NAME>END_PI")
-- , row
-- [ --Content.verticalCenter
-- -- , Content.alignRight
-- Color.background Color.yellow
-- ]
-- [ text "hello!"
-- , text "hello!"
-- , el
-- [ --Content.verticalCenter
-- below
-- (el [ Color.background Color.blue ] (text "I am below, yup!"))
-- ]
-- (text "hello!")
-- ]
-- ]
-- , el
-- [ Font.family
-- [ Font.typeface "Inconsolata"
-- , Font.monospace
-- ]
-- , Color.background Color.blue
-- , Color.text Color.white
-- , paddingXY 30 50
-- , center
-- , width (px 600)
-- ]
-- (text Internal.rules)
-- , textPage
-- [ spacing 10
-- , center
-- , Color.background Color.lightGrey
-- ]
-- [ el
-- [ width (px 50)
-- , height (px 50)
-- , Color.background Color.blue
-- , alignLeft
-- ]
-- empty
-- , paragraph []
-- [ text ipsum
-- ]
-- , paragraph []
-- [ text ipsum
-- ]
-- , paragraph []
-- [ text ipsum
-- ]
-- , el
-- [ width (px 50)
-- , height (px 50)
-- , Color.background Color.blue
-- , alignLeft
-- ]
-- empty
-- , paragraph []
-- [ text ipsum
-- ]
-- ]
-- , column [ spacing 20, padding 20, width (px 200), Color.background Color.grey ]
-- [ el [ width fill, height (px 20), Color.background Color.blue ] empty
-- , el [ width expand, height (px 20), Color.background Color.blue ] empty
-- , el [ width fill, height (px 20), Color.background Color.blue ] empty
-- ]
-- ]
-- view model =
-- layoutWith []
-- { modal = el [] empty
-- , content =
-- column []
-- }
-- view model =
-- layoutWith
-- { modal = el [] empty
-- , attributes = []
-- }
-- <|
-- column [] []
| elm |
[
{
"context": "hor\n [ ( \"Development\", [ \"Simon Olander Sahlén\" ] )\n , ( \"Icons\", [ \"Simo",
"end": 1550,
"score": 0.999894619,
"start": 1530,
"tag": "NAME",
"value": "Simon Olander Sahlén"
},
{
"context": "hlén\" ] )\n , ( \"Icons\", [ \"Simon Olander Sahlén\" ] )\n , ( \"UX counselling\"",
"end": 1616,
"score": 0.9998930693,
"start": 1596,
"tag": "NAME",
"value": "Simon Olander Sahlén"
},
{
"context": "( \"UX counselling\"\n , [ \"Anita Chainiau\"\n , \"Anton Håkanson\"\n ",
"end": 1712,
"score": 0.9998874664,
"start": 1698,
"tag": "NAME",
"value": "Anita Chainiau"
},
{
"context": "[ \"Anita Chainiau\"\n , \"Anton Håkanson\"\n ]\n ",
"end": 1759,
"score": 0.9998868108,
"start": 1745,
"tag": "NAME",
"value": "Anton Håkanson"
},
{
"context": " { label = text \"https://github.com/simonolander/elm-funge\"\n , url = \"https",
"end": 2226,
"score": 0.8056426048,
"start": 2214,
"tag": "USERNAME",
"value": "simonolander"
},
{
"context": " , url = \"https://github.com/simonolander/elm-funge\"\n }\n ",
"end": 2302,
"score": 0.8627362251,
"start": 2290,
"tag": "USERNAME",
"value": "simonolander"
},
{
"context": " playTesters =\n [ \"Anita Chainiau\"\n , \"Anton Håkanson\"\n ",
"end": 2459,
"score": 0.9998552203,
"start": 2445,
"tag": "NAME",
"value": "Anita Chainiau"
},
{
"context": " [ \"Anita Chainiau\"\n , \"Anton Håkanson\"\n , \"Isac Olander Sahlén\"\n",
"end": 2502,
"score": 0.9998500943,
"start": 2488,
"tag": "NAME",
"value": "Anton Håkanson"
},
{
"context": " , \"Anton Håkanson\"\n , \"Isac Olander Sahlén\"\n , \"Adelie Fournier\"\n ",
"end": 2550,
"score": 0.9998614788,
"start": 2531,
"tag": "NAME",
"value": "Isac Olander Sahlén"
},
{
"context": " \"Isac Olander Sahlén\"\n , \"Adelie Fournier\"\n , \"Benjamin Becquet\"\n ",
"end": 2594,
"score": 0.9998642206,
"start": 2579,
"tag": "NAME",
"value": "Adelie Fournier"
},
{
"context": " , \"Adelie Fournier\"\n , \"Benjamin Becquet\"\n , \"Erik Bodin\"\n ",
"end": 2639,
"score": 0.999851346,
"start": 2623,
"tag": "NAME",
"value": "Benjamin Becquet"
},
{
"context": " , \"Benjamin Becquet\"\n , \"Erik Bodin\"\n , \"Anton Pervorsek\"\n ",
"end": 2678,
"score": 0.999866128,
"start": 2668,
"tag": "NAME",
"value": "Erik Bodin"
},
{
"context": " , \"Erik Bodin\"\n , \"Anton Pervorsek\"\n , \"Edvin Wallin\"\n ",
"end": 2722,
"score": 0.9998649955,
"start": 2707,
"tag": "NAME",
"value": "Anton Pervorsek"
},
{
"context": " , \"Anton Pervorsek\"\n , \"Edvin Wallin\"\n , \"Carl-Henrik Klåvus\"\n ",
"end": 2763,
"score": 0.9998586178,
"start": 2751,
"tag": "NAME",
"value": "Edvin Wallin"
},
{
"context": " , \"Edvin Wallin\"\n , \"Carl-Henrik Klåvus\"\n , \"Johan von Konow\"\n ",
"end": 2810,
"score": 0.9998458624,
"start": 2792,
"tag": "NAME",
"value": "Carl-Henrik Klåvus"
},
{
"context": ", \"Carl-Henrik Klåvus\"\n , \"Johan von Konow\"\n , \"Harald Nicander\"\n ",
"end": 2854,
"score": 0.9998556972,
"start": 2839,
"tag": "NAME",
"value": "Johan von Konow"
},
{
"context": " , \"Johan von Konow\"\n , \"Harald Nicander\"\n , \"Karin Aldheimer\"\n ",
"end": 2898,
"score": 0.9998502731,
"start": 2883,
"tag": "NAME",
"value": "Harald Nicander"
},
{
"context": " , \"Harald Nicander\"\n , \"Karin Aldheimer\"\n , \"Malin Molin\"\n ",
"end": 2942,
"score": 0.9998582006,
"start": 2927,
"tag": "NAME",
"value": "Karin Aldheimer"
},
{
"context": " , \"Karin Aldheimer\"\n , \"Malin Molin\"\n ]\n\n c",
"end": 2982,
"score": 0.9998557568,
"start": 2971,
"tag": "NAME",
"value": "Malin Molin"
}
] | src/Page/Credits.elm | simonolander/elm-funge | 0 | module Page.Credits exposing (Model, Msg, init, load, subscriptions, update, view)
import ApplicationName exposing (applicationName)
import Basics.Extra exposing (flip, uncurry)
import Browser exposing (Document)
import Color
import Data.Session exposing (Session)
import Element exposing (..)
import Element.Background as Background
import Element.Font as Font exposing (Font)
import Html.Attributes
import Json.Encode as Encode
import View.Constant exposing (color, size)
import View.Header
import View.Layout
import View.Scewn
-- MODEL
type alias Model =
{ session : Session
}
type alias Msg =
()
init : Session -> ( Model, Cmd Msg )
init session =
( { session = session }, Cmd.none )
load : Model -> ( Model, Cmd Msg )
load =
flip Tuple.pair Cmd.none
-- UPDATE
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
( model, Cmd.none )
localStorageResponseUpdate : ( String, Encode.Value ) -> Model -> ( Model, Cmd Msg )
localStorageResponseUpdate ( key, value ) model =
( model, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
view : Model -> Document Msg
view model =
let
body =
column
[ width (maximum 1000 fill)
, height fill
, padding 60
, spacing 80
, centerX
]
[ section "Credits"
(taskAndAuthor
[ ( "Development", [ "Simon Olander Sahlén" ] )
, ( "Icons", [ "Simon Olander Sahlén" ] )
, ( "UX counselling"
, [ "Anita Chainiau"
, "Anton Håkanson"
]
)
, ( "Music", [] )
]
)
, section "Source"
(link
[ centerX
, mouseOver [ Font.color color.font.linkHover ]
, Font.color color.font.link
]
{ label = text "https://github.com/simonolander/elm-funge"
, url = "https://github.com/simonolander/elm-funge"
}
)
, let
playTesters =
[ "Anita Chainiau"
, "Anton Håkanson"
, "Isac Olander Sahlén"
, "Adelie Fournier"
, "Benjamin Becquet"
, "Erik Bodin"
, "Anton Pervorsek"
, "Edvin Wallin"
, "Carl-Henrik Klåvus"
, "Johan von Konow"
, "Harald Nicander"
, "Karin Aldheimer"
, "Malin Molin"
]
color index =
let
t =
toFloat index / toFloat (List.length playTesters)
{ red, green, blue, alpha } =
Color.hsl t 1 0.75
|> Color.toRgba
in
Font.color (rgba red green blue alpha)
in
section "Play testing"
(playTesters
|> List.map (String.replace " " "\u{00A0}")
|> List.sort
|> List.map text
|> List.indexedMap
(\index ->
el
[ mouseOver [ color index ]
, padding 10
]
)
|> List.intersperse (text " ")
|> paragraph [ Font.center ]
)
, section "Special thanks"
([ ( "Zachtronics"
, [ text "For making "
, link
[ Font.color color.font.link
, mouseOver [ Font.color color.font.linkHover ]
]
{ label = text "TIS-100"
, url = "http://www.zachtronics.com/tis-100/"
}
, text " and "
, link
[ Font.color color.font.link
, mouseOver [ Font.color color.font.linkHover ]
]
{ label = text "Shenzhen I/O"
, url = "http://www.zachtronics.com/shenzhen-io/"
}
, text ", games I enjoyed and that inspired this work."
]
)
, ( "Befunge"
, [ text "For inspiring the computer language of this game." ]
)
]
|> List.map (Tuple.mapFirst (text >> el [ Font.size 24, Font.center, width fill ]))
|> List.map (Tuple.mapSecond (paragraph [ Font.size 20, Font.center, width fill ]))
|> List.map (\( a, b ) -> [ a, b ])
|> List.map (column [ width fill, spacing 20 ])
|> column [ width fill, spacing 30 ]
)
]
content =
View.Layout.layout <|
View.Scewn.view
{ north = Just <| View.Header.view model.session
, center = Just body
, south = Nothing
, east = Nothing
, west = Nothing
, modal = Nothing
}
in
{ body = [ content ]
, title = String.concat [ "Credits", " - ", applicationName ]
}
section : String -> Element msg -> Element msg
section title element =
column
[ width fill
, spacing 40
]
[ el
[ Font.center
, size.font.section.title
, width fill
]
(text title)
, element
]
taskAndAuthor : List ( String, List String ) -> Element msg
taskAndAuthor tasks =
let
top task author =
row [ width fill, htmlAttribute (Html.Attributes.class "dotted") ]
[ el
[ alignLeft
, Background.color (rgb 0 0 0)
, paddingEach { left = 0, top = 0, right = 11, bottom = 0 }
]
(text task)
, el
[ mouseOver [ Font.color color.font.subtle ]
, alignRight
, Background.color (rgb 0 0 0)
, paddingEach { left = 11, top = 0, right = 0, bottom = 0 }
]
(text author)
]
in
tasks
|> List.map (Tuple.mapSecond List.sort)
|> List.map
(\( task, authors ) ->
case authors of
[ author ] ->
top task author
[] ->
top task "null"
author :: tail ->
tail
|> List.map
(text
>> el
[ width fill
, Font.alignRight
, mouseOver [ Font.color color.font.subtle ]
]
)
|> (::) (top task author)
|> column [ width fill ]
)
|> column [ width fill, centerX, spacing 20 ]
| 29921 | module Page.Credits exposing (Model, Msg, init, load, subscriptions, update, view)
import ApplicationName exposing (applicationName)
import Basics.Extra exposing (flip, uncurry)
import Browser exposing (Document)
import Color
import Data.Session exposing (Session)
import Element exposing (..)
import Element.Background as Background
import Element.Font as Font exposing (Font)
import Html.Attributes
import Json.Encode as Encode
import View.Constant exposing (color, size)
import View.Header
import View.Layout
import View.Scewn
-- MODEL
type alias Model =
{ session : Session
}
type alias Msg =
()
init : Session -> ( Model, Cmd Msg )
init session =
( { session = session }, Cmd.none )
load : Model -> ( Model, Cmd Msg )
load =
flip Tuple.pair Cmd.none
-- UPDATE
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
( model, Cmd.none )
localStorageResponseUpdate : ( String, Encode.Value ) -> Model -> ( Model, Cmd Msg )
localStorageResponseUpdate ( key, value ) model =
( model, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
view : Model -> Document Msg
view model =
let
body =
column
[ width (maximum 1000 fill)
, height fill
, padding 60
, spacing 80
, centerX
]
[ section "Credits"
(taskAndAuthor
[ ( "Development", [ "<NAME>" ] )
, ( "Icons", [ "<NAME>" ] )
, ( "UX counselling"
, [ "<NAME>"
, "<NAME>"
]
)
, ( "Music", [] )
]
)
, section "Source"
(link
[ centerX
, mouseOver [ Font.color color.font.linkHover ]
, Font.color color.font.link
]
{ label = text "https://github.com/simonolander/elm-funge"
, url = "https://github.com/simonolander/elm-funge"
}
)
, let
playTesters =
[ "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
]
color index =
let
t =
toFloat index / toFloat (List.length playTesters)
{ red, green, blue, alpha } =
Color.hsl t 1 0.75
|> Color.toRgba
in
Font.color (rgba red green blue alpha)
in
section "Play testing"
(playTesters
|> List.map (String.replace " " "\u{00A0}")
|> List.sort
|> List.map text
|> List.indexedMap
(\index ->
el
[ mouseOver [ color index ]
, padding 10
]
)
|> List.intersperse (text " ")
|> paragraph [ Font.center ]
)
, section "Special thanks"
([ ( "Zachtronics"
, [ text "For making "
, link
[ Font.color color.font.link
, mouseOver [ Font.color color.font.linkHover ]
]
{ label = text "TIS-100"
, url = "http://www.zachtronics.com/tis-100/"
}
, text " and "
, link
[ Font.color color.font.link
, mouseOver [ Font.color color.font.linkHover ]
]
{ label = text "Shenzhen I/O"
, url = "http://www.zachtronics.com/shenzhen-io/"
}
, text ", games I enjoyed and that inspired this work."
]
)
, ( "Befunge"
, [ text "For inspiring the computer language of this game." ]
)
]
|> List.map (Tuple.mapFirst (text >> el [ Font.size 24, Font.center, width fill ]))
|> List.map (Tuple.mapSecond (paragraph [ Font.size 20, Font.center, width fill ]))
|> List.map (\( a, b ) -> [ a, b ])
|> List.map (column [ width fill, spacing 20 ])
|> column [ width fill, spacing 30 ]
)
]
content =
View.Layout.layout <|
View.Scewn.view
{ north = Just <| View.Header.view model.session
, center = Just body
, south = Nothing
, east = Nothing
, west = Nothing
, modal = Nothing
}
in
{ body = [ content ]
, title = String.concat [ "Credits", " - ", applicationName ]
}
section : String -> Element msg -> Element msg
section title element =
column
[ width fill
, spacing 40
]
[ el
[ Font.center
, size.font.section.title
, width fill
]
(text title)
, element
]
taskAndAuthor : List ( String, List String ) -> Element msg
taskAndAuthor tasks =
let
top task author =
row [ width fill, htmlAttribute (Html.Attributes.class "dotted") ]
[ el
[ alignLeft
, Background.color (rgb 0 0 0)
, paddingEach { left = 0, top = 0, right = 11, bottom = 0 }
]
(text task)
, el
[ mouseOver [ Font.color color.font.subtle ]
, alignRight
, Background.color (rgb 0 0 0)
, paddingEach { left = 11, top = 0, right = 0, bottom = 0 }
]
(text author)
]
in
tasks
|> List.map (Tuple.mapSecond List.sort)
|> List.map
(\( task, authors ) ->
case authors of
[ author ] ->
top task author
[] ->
top task "null"
author :: tail ->
tail
|> List.map
(text
>> el
[ width fill
, Font.alignRight
, mouseOver [ Font.color color.font.subtle ]
]
)
|> (::) (top task author)
|> column [ width fill ]
)
|> column [ width fill, centerX, spacing 20 ]
| true | module Page.Credits exposing (Model, Msg, init, load, subscriptions, update, view)
import ApplicationName exposing (applicationName)
import Basics.Extra exposing (flip, uncurry)
import Browser exposing (Document)
import Color
import Data.Session exposing (Session)
import Element exposing (..)
import Element.Background as Background
import Element.Font as Font exposing (Font)
import Html.Attributes
import Json.Encode as Encode
import View.Constant exposing (color, size)
import View.Header
import View.Layout
import View.Scewn
-- MODEL
type alias Model =
{ session : Session
}
type alias Msg =
()
init : Session -> ( Model, Cmd Msg )
init session =
( { session = session }, Cmd.none )
load : Model -> ( Model, Cmd Msg )
load =
flip Tuple.pair Cmd.none
-- UPDATE
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
( model, Cmd.none )
localStorageResponseUpdate : ( String, Encode.Value ) -> Model -> ( Model, Cmd Msg )
localStorageResponseUpdate ( key, value ) model =
( model, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
view : Model -> Document Msg
view model =
let
body =
column
[ width (maximum 1000 fill)
, height fill
, padding 60
, spacing 80
, centerX
]
[ section "Credits"
(taskAndAuthor
[ ( "Development", [ "PI:NAME:<NAME>END_PI" ] )
, ( "Icons", [ "PI:NAME:<NAME>END_PI" ] )
, ( "UX counselling"
, [ "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
]
)
, ( "Music", [] )
]
)
, section "Source"
(link
[ centerX
, mouseOver [ Font.color color.font.linkHover ]
, Font.color color.font.link
]
{ label = text "https://github.com/simonolander/elm-funge"
, url = "https://github.com/simonolander/elm-funge"
}
)
, let
playTesters =
[ "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
]
color index =
let
t =
toFloat index / toFloat (List.length playTesters)
{ red, green, blue, alpha } =
Color.hsl t 1 0.75
|> Color.toRgba
in
Font.color (rgba red green blue alpha)
in
section "Play testing"
(playTesters
|> List.map (String.replace " " "\u{00A0}")
|> List.sort
|> List.map text
|> List.indexedMap
(\index ->
el
[ mouseOver [ color index ]
, padding 10
]
)
|> List.intersperse (text " ")
|> paragraph [ Font.center ]
)
, section "Special thanks"
([ ( "Zachtronics"
, [ text "For making "
, link
[ Font.color color.font.link
, mouseOver [ Font.color color.font.linkHover ]
]
{ label = text "TIS-100"
, url = "http://www.zachtronics.com/tis-100/"
}
, text " and "
, link
[ Font.color color.font.link
, mouseOver [ Font.color color.font.linkHover ]
]
{ label = text "Shenzhen I/O"
, url = "http://www.zachtronics.com/shenzhen-io/"
}
, text ", games I enjoyed and that inspired this work."
]
)
, ( "Befunge"
, [ text "For inspiring the computer language of this game." ]
)
]
|> List.map (Tuple.mapFirst (text >> el [ Font.size 24, Font.center, width fill ]))
|> List.map (Tuple.mapSecond (paragraph [ Font.size 20, Font.center, width fill ]))
|> List.map (\( a, b ) -> [ a, b ])
|> List.map (column [ width fill, spacing 20 ])
|> column [ width fill, spacing 30 ]
)
]
content =
View.Layout.layout <|
View.Scewn.view
{ north = Just <| View.Header.view model.session
, center = Just body
, south = Nothing
, east = Nothing
, west = Nothing
, modal = Nothing
}
in
{ body = [ content ]
, title = String.concat [ "Credits", " - ", applicationName ]
}
section : String -> Element msg -> Element msg
section title element =
column
[ width fill
, spacing 40
]
[ el
[ Font.center
, size.font.section.title
, width fill
]
(text title)
, element
]
taskAndAuthor : List ( String, List String ) -> Element msg
taskAndAuthor tasks =
let
top task author =
row [ width fill, htmlAttribute (Html.Attributes.class "dotted") ]
[ el
[ alignLeft
, Background.color (rgb 0 0 0)
, paddingEach { left = 0, top = 0, right = 11, bottom = 0 }
]
(text task)
, el
[ mouseOver [ Font.color color.font.subtle ]
, alignRight
, Background.color (rgb 0 0 0)
, paddingEach { left = 11, top = 0, right = 0, bottom = 0 }
]
(text author)
]
in
tasks
|> List.map (Tuple.mapSecond List.sort)
|> List.map
(\( task, authors ) ->
case authors of
[ author ] ->
top task author
[] ->
top task "null"
author :: tail ->
tail
|> List.map
(text
>> el
[ width fill
, Font.alignRight
, mouseOver [ Font.color color.font.subtle ]
]
)
|> (::) (top task author)
|> column [ width fill ]
)
|> column [ width fill, centerX, spacing 20 ]
| elm |
[
{
"context": "Mdl\n }\n\nmodel : Model\nmodel =\n { message = \"Hello World\"\n , appName = \"Sample\"\n , tabName = \"Tab1\"\n",
"end": 587,
"score": 0.6345540285,
"start": 576,
"tag": "NAME",
"value": "Hello World"
}
] | Layout-example.elm | glennular/elm-mdl-layout-starter | 0 | module LayoutExample exposing (..)
import Html exposing (..)
import Material
import Material.Color as Color
import Material.Icon as Icon
import Material.Grid as Grid exposing (grid, size, cell, Device(..))
import Material.Layout as Layout
import Material.Options as Options exposing (css)
import Material.Scheme
import Material.Typography as Typography
type alias Mdl =
Material.Model
-- MODEL
type alias Model =
{ message : String
, appName : String
, tabName : String
, color : Color.Hue
, mdl : Mdl
}
model : Model
model =
{ message = "Hello World"
, appName = "Sample"
, tabName = "Tab1"
, color = Color.Indigo
, mdl = Material.model
}
-- UPDATE
type Msg
= Mdl (Material.Msg Msg)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Mdl msg_ ->
Material.update Mdl msg_ model
-- VIEW
layout : Model -> Html Msg
layout model =
Material.Scheme.top <|
Layout.render Mdl
model.mdl
[ Layout.fixedHeader ]
{ header = [ header model ]
, drawer = drawer model
, tabs = ( tabs model, [Color.background (Color.color model.color Color.S400)])
, main = [ body model ]
}
body : Model -> Html Msg
body model =
let
title : Grid.Cell Msg
title =
cell [ size Desktop 12, size Tablet 8, size Phone 4 ]
[ Options.styled div
[ Typography.left, Typography.display3 ]
[ text model.tabName ]
]
boxed : List (Options.Property a b)
boxed =
[ css "margin" "auto"
, css "padding-left" "8%"
, css "padding-right" "8%"
]
body : String
body = String.repeat 30 "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse at justo augue. "
bodyCells : List (Grid.Cell Msg)
bodyCells =
cell [ size Desktop 6, size Tablet 8, size Phone 4 ]
[ Options.styled div [] [ text body ] ]
|> List.repeat 3
in
grid boxed
(title :: bodyCells)
body2 : Model -> Html Msg
body2 model =
grid [ Options.css "max-width" "1080px" ]
[ cell
[ size All 8 ]
[ div [] [ text model.message]]
]
header : Model -> Html Msg
header model =
Layout.row
[ Color.background (Color.color model.color Color.S500)]
[ Layout.title [] [ text model.appName ]
, Layout.spacer
, Layout.navigation []
[ Layout.link [ ] [ Icon.i "photo" ]
, Layout.link [] [ text "link 2" ]
, Layout.link [] [ text "link 3" ]]
]
drawer : Model -> List (Html Msg)
drawer model =
[ Layout.title [] [ text model.appName ]
, Layout.navigation
[]
[ Layout.link [] [ text "link 1" ]
, Layout.link [] [ text "link 2" ]
, Layout.link [] [ text "link 3" ]
]
]
tabs : Model -> List (Html Msg)
tabs model =
[ text "Tab1"
, text "Tab2"
, text "Tab3"
]
-- MAIN
main : Program Never Model Msg
main =
Html.program
{ init = ( model, Cmd.none )
, view = layout
, subscriptions = always Sub.none
, update = update
}
| 60449 | module LayoutExample exposing (..)
import Html exposing (..)
import Material
import Material.Color as Color
import Material.Icon as Icon
import Material.Grid as Grid exposing (grid, size, cell, Device(..))
import Material.Layout as Layout
import Material.Options as Options exposing (css)
import Material.Scheme
import Material.Typography as Typography
type alias Mdl =
Material.Model
-- MODEL
type alias Model =
{ message : String
, appName : String
, tabName : String
, color : Color.Hue
, mdl : Mdl
}
model : Model
model =
{ message = "<NAME>"
, appName = "Sample"
, tabName = "Tab1"
, color = Color.Indigo
, mdl = Material.model
}
-- UPDATE
type Msg
= Mdl (Material.Msg Msg)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Mdl msg_ ->
Material.update Mdl msg_ model
-- VIEW
layout : Model -> Html Msg
layout model =
Material.Scheme.top <|
Layout.render Mdl
model.mdl
[ Layout.fixedHeader ]
{ header = [ header model ]
, drawer = drawer model
, tabs = ( tabs model, [Color.background (Color.color model.color Color.S400)])
, main = [ body model ]
}
body : Model -> Html Msg
body model =
let
title : Grid.Cell Msg
title =
cell [ size Desktop 12, size Tablet 8, size Phone 4 ]
[ Options.styled div
[ Typography.left, Typography.display3 ]
[ text model.tabName ]
]
boxed : List (Options.Property a b)
boxed =
[ css "margin" "auto"
, css "padding-left" "8%"
, css "padding-right" "8%"
]
body : String
body = String.repeat 30 "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse at justo augue. "
bodyCells : List (Grid.Cell Msg)
bodyCells =
cell [ size Desktop 6, size Tablet 8, size Phone 4 ]
[ Options.styled div [] [ text body ] ]
|> List.repeat 3
in
grid boxed
(title :: bodyCells)
body2 : Model -> Html Msg
body2 model =
grid [ Options.css "max-width" "1080px" ]
[ cell
[ size All 8 ]
[ div [] [ text model.message]]
]
header : Model -> Html Msg
header model =
Layout.row
[ Color.background (Color.color model.color Color.S500)]
[ Layout.title [] [ text model.appName ]
, Layout.spacer
, Layout.navigation []
[ Layout.link [ ] [ Icon.i "photo" ]
, Layout.link [] [ text "link 2" ]
, Layout.link [] [ text "link 3" ]]
]
drawer : Model -> List (Html Msg)
drawer model =
[ Layout.title [] [ text model.appName ]
, Layout.navigation
[]
[ Layout.link [] [ text "link 1" ]
, Layout.link [] [ text "link 2" ]
, Layout.link [] [ text "link 3" ]
]
]
tabs : Model -> List (Html Msg)
tabs model =
[ text "Tab1"
, text "Tab2"
, text "Tab3"
]
-- MAIN
main : Program Never Model Msg
main =
Html.program
{ init = ( model, Cmd.none )
, view = layout
, subscriptions = always Sub.none
, update = update
}
| true | module LayoutExample exposing (..)
import Html exposing (..)
import Material
import Material.Color as Color
import Material.Icon as Icon
import Material.Grid as Grid exposing (grid, size, cell, Device(..))
import Material.Layout as Layout
import Material.Options as Options exposing (css)
import Material.Scheme
import Material.Typography as Typography
type alias Mdl =
Material.Model
-- MODEL
type alias Model =
{ message : String
, appName : String
, tabName : String
, color : Color.Hue
, mdl : Mdl
}
model : Model
model =
{ message = "PI:NAME:<NAME>END_PI"
, appName = "Sample"
, tabName = "Tab1"
, color = Color.Indigo
, mdl = Material.model
}
-- UPDATE
type Msg
= Mdl (Material.Msg Msg)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Mdl msg_ ->
Material.update Mdl msg_ model
-- VIEW
layout : Model -> Html Msg
layout model =
Material.Scheme.top <|
Layout.render Mdl
model.mdl
[ Layout.fixedHeader ]
{ header = [ header model ]
, drawer = drawer model
, tabs = ( tabs model, [Color.background (Color.color model.color Color.S400)])
, main = [ body model ]
}
body : Model -> Html Msg
body model =
let
title : Grid.Cell Msg
title =
cell [ size Desktop 12, size Tablet 8, size Phone 4 ]
[ Options.styled div
[ Typography.left, Typography.display3 ]
[ text model.tabName ]
]
boxed : List (Options.Property a b)
boxed =
[ css "margin" "auto"
, css "padding-left" "8%"
, css "padding-right" "8%"
]
body : String
body = String.repeat 30 "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse at justo augue. "
bodyCells : List (Grid.Cell Msg)
bodyCells =
cell [ size Desktop 6, size Tablet 8, size Phone 4 ]
[ Options.styled div [] [ text body ] ]
|> List.repeat 3
in
grid boxed
(title :: bodyCells)
body2 : Model -> Html Msg
body2 model =
grid [ Options.css "max-width" "1080px" ]
[ cell
[ size All 8 ]
[ div [] [ text model.message]]
]
header : Model -> Html Msg
header model =
Layout.row
[ Color.background (Color.color model.color Color.S500)]
[ Layout.title [] [ text model.appName ]
, Layout.spacer
, Layout.navigation []
[ Layout.link [ ] [ Icon.i "photo" ]
, Layout.link [] [ text "link 2" ]
, Layout.link [] [ text "link 3" ]]
]
drawer : Model -> List (Html Msg)
drawer model =
[ Layout.title [] [ text model.appName ]
, Layout.navigation
[]
[ Layout.link [] [ text "link 1" ]
, Layout.link [] [ text "link 2" ]
, Layout.link [] [ text "link 3" ]
]
]
tabs : Model -> List (Html Msg)
tabs model =
[ text "Tab1"
, text "Tab2"
, text "Tab3"
]
-- MAIN
main : Program Never Model Msg
main =
Html.program
{ init = ( model, Cmd.none )
, view = layout
, subscriptions = always Sub.none
, update = update
}
| elm |
[
{
"context": "use the expected value didn't split the space in \"Betty Botter\"\n String.split \" \" \"Betty Botter bought some b",
"end": 5135,
"score": 0.9026089311,
"start": 5123,
"tag": "NAME",
"value": "Betty Botter"
},
{
"context": "the space in \"Betty Botter\"\n String.split \" \" \"Betty Botter bought some butter\"\n |> Expect.equal [ \"Be",
"end": 5171,
"score": 0.9968928695,
"start": 5159,
"tag": "NAME",
"value": "Betty Botter"
},
{
"context": "er bought some butter\"\n |> Expect.equal [ \"Betty Botter\", \"bought\", \"some\", \"butter\" ]\n\n {-\n\n [ \"Be",
"end": 5231,
"score": 0.9863089919,
"start": 5219,
"tag": "NAME",
"value": "Betty Botter"
},
{
"context": "er\", \"bought\", \"some\", \"butter\" ]\n\n {-\n\n [ \"Betty\", \"Botter\", \"bought\", \"some\", \"butter\" ]\n ╷\n ",
"end": 5284,
"score": 0.9975224733,
"start": 5279,
"tag": "NAME",
"value": "Betty"
},
{
"context": "ght\", \"some\", \"butter\" ]\n\n {-\n\n [ \"Betty\", \"Botter\", \"bought\", \"some\", \"butter\" ]\n ╷\n │ Expect",
"end": 5294,
"score": 0.9745397568,
"start": 5288,
"tag": "NAME",
"value": "Botter"
},
{
"context": " \"butter\" ]\n ╷\n │ Expect.equal\n ╵\n [ \"Betty Botter\", \"bought\", \"some\", \"butter\" ]\n\n -}\n\nDo not eq",
"end": 5376,
"score": 0.9983232617,
"start": 5364,
"tag": "NAME",
"value": "Betty Botter"
}
] | fixtures/elm-home/0.19.0/package/elm-explorations/test/1.1.0/src/Expect.elm | kazk/node-test-runner | 0 | module Expect exposing
( Expectation, equal, notEqual, all
, lessThan, atMost, greaterThan, atLeast
, FloatingPointTolerance(..), within, notWithin
, true, false
, ok, err, equalLists, equalDicts, equalSets
, pass, fail, onFail
)
{-| A library to create `Expectation`s, which describe a claim to be tested.
## Quick Reference
- [`equal`](#equal) `(arg2 == arg1)`
- [`notEqual`](#notEqual) `(arg2 /= arg1)`
- [`lessThan`](#lessThan) `(arg2 < arg1)`
- [`atMost`](#atMost) `(arg2 <= arg1)`
- [`greaterThan`](#greaterThan) `(arg2 > arg1)`
- [`atLeast`](#atLeast) `(arg2 >= arg1)`
- [`true`](#true) `(arg == True)`
- [`false`](#false) `(arg == False)`
- [Floating Point Comparisons](#floating-point-comparisons)
## Basic Expectations
@docs Expectation, equal, notEqual, all
## Numeric Comparisons
@docs lessThan, atMost, greaterThan, atLeast
## Floating Point Comparisons
These functions allow you to compare `Float` values up to a specified rounding error, which may be relative, absolute,
or both. For an in-depth look, see our [Guide to Floating Point Comparison](#guide-to-floating-point-comparison).
@docs FloatingPointTolerance, within, notWithin
## Booleans
@docs true, false
## Collections
@docs ok, err, equalLists, equalDicts, equalSets
## Customizing
These functions will let you build your own expectations.
@docs pass, fail, onFail
## Guide to Floating Point Comparison
In general, if you are multiplying, you want relative tolerance, and if you're adding,
you want absolute tolerance. If you are doing both, you want both kinds of tolerance,
or to split the calculation into smaller parts for testing.
### Absolute Tolerance
Let's say we want to figure out if our estimation of pi is precise enough.
Is `3.14` within `0.01` of `pi`? Yes, because `3.13 < pi < 3.15`.
test "3.14 approximates pi with absolute precision" <|
\_ ->
3.14 |> Expect.within (Absolute 0.01) pi
### Relative Tolerance
What if we also want to know if our circle circumference estimation is close enough?
Let's say our circle has a radius of `r` meters. The formula for circle circumference is `C=2*r*pi`.
To make the calculations a bit easier ([ahem](https://tauday.com/tau-manifesto)), we'll look at half the circumference; `C/2=r*pi`.
Is `r * 3.14` within `0.01` of `r * pi`?
That depends, what does `r` equal? If `r` is `0.01`mm, or `0.00001` meters, we're comparing
`0.00001 * 3.14 - 0.01 < r * pi < 0.00001 * 3.14 + 0.01` or `-0.0099686 < 0.0000314159 < 0.0100314`.
That's a huge tolerance! A circumference that is _a thousand times longer_ than we expected would pass that test!
On the other hand, if `r` is very large, we're going to need many more digits of pi.
For an absolute tolerance of `0.01` and a pi estimation of `3.14`, this expectation only passes if `r < 2*pi`.
If we use a relative tolerance of `0.01` instead, the circle area comparison becomes much better. Is `r * 3.14` within
`1%` of `r * pi`? Yes! In fact, three digits of pi approximation is always good enough for a 0.1% relative tolerance,
as long as `r` isn't [too close to zero](https://en.wikipedia.org/wiki/Denormal_number).
fuzz
(floatRange 0.000001 100000)
"Circle half-circumference with relative tolerance"
(\r -> r * 3.14 |> Expect.within (Relative 0.001) (r * pi))
### Trouble with Numbers Near Zero
If you are adding things near zero, you probably want absolute tolerance. If you're comparing values between `-1` and `1`, you should consider using absolute tolerance.
For example: Is `1 + 2 - 3` within `1%` of `0`? Well, if `1`, `2` and `3` have any amount of rounding error, you might not get exactly zero. What is `1%` above and below `0`? Zero. We just lost all tolerance. Even if we hard-code the numbers, we might not get exactly zero; `0.1 + 0.2` rounds to a value just above `0.3`, since computers, counting in binary, cannot write down any of those three numbers using a finite number of digits, just like we cannot write `0.333...` exactly in base 10.
Another example is comparing values that are on either side of zero. `0.0001` is more than `100%` away from `-0.0001`. In fact, `infinity` is closer to `0.0001` than `0.0001` is to `-0.0001`, if you are using a relative tolerance. Twice as close, actually. So even though both `0.0001` and `-0.0001` could be considered very close to zero, they are very far apart relative to each other. The same argument applies for any number of zeroes.
-}
import Dict exposing (Dict)
import Set exposing (Set)
import Test.Expectation
import Test.Internal as Internal
import Test.Runner.Failure exposing (InvalidReason(..), Reason(..))
{-| The result of a single test run: either a [`pass`](#pass) or a
[`fail`](#fail).
-}
type alias Expectation =
Test.Expectation.Expectation
{-| Passes if the arguments are equal.
Expect.equal 0 (List.length [])
-- Passes because (0 == 0) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because the expected value didn't split the space in "Betty Botter"
String.split " " "Betty Botter bought some butter"
|> Expect.equal [ "Betty Botter", "bought", "some", "butter" ]
{-
[ "Betty", "Botter", "bought", "some", "butter" ]
╷
│ Expect.equal
╵
[ "Betty Botter", "bought", "some", "butter" ]
-}
Do not equate `Float` values; use [`within`](#within) instead.
-}
equal : a -> a -> Expectation
equal =
equateWith "Expect.equal" (==)
{-| Passes if the arguments are not equal.
-- Passes because (11 /= 100) is True
90 + 10
|> Expect.notEqual 11
-- Fails because (100 /= 100) is False
90 + 10
|> Expect.notEqual 100
{-
100
╷
│ Expect.notEqual
╵
100
-}
-}
notEqual : a -> a -> Expectation
notEqual =
equateWith "Expect.notEqual" (/=)
{-| Passes if the second argument is less than the first.
Expect.lessThan 1 (List.length [])
-- Passes because (0 < 1) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 < -1) is False
List.length []
|> Expect.lessThan -1
{-
0
╷
│ Expect.lessThan
╵
-1
-}
Do not equate `Float` values; use [`notWithin`](#notWithin) instead.
-}
lessThan : comparable -> comparable -> Expectation
lessThan =
compareWith "Expect.lessThan" (<)
{-| Passes if the second argument is less than or equal to the first.
Expect.atMost 1 (List.length [])
-- Passes because (0 <= 1) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 <= -3) is False
List.length []
|> Expect.atMost -3
{-
0
╷
│ Expect.atMost
╵
-3
-}
-}
atMost : comparable -> comparable -> Expectation
atMost =
compareWith "Expect.atMost" (<=)
{-| Passes if the second argument is greater than the first.
Expect.greaterThan -2 List.length []
-- Passes because (0 > -2) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 > 1) is False
List.length []
|> Expect.greaterThan 1
{-
0
╷
│ Expect.greaterThan
╵
1
-}
-}
greaterThan : comparable -> comparable -> Expectation
greaterThan =
compareWith "Expect.greaterThan" (>)
{-| Passes if the second argument is greater than or equal to the first.
Expect.atLeast -2 (List.length [])
-- Passes because (0 >= -2) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 >= 3) is False
List.length []
|> Expect.atLeast 3
{-
0
╷
│ Expect.atLeast
╵
3
-}
-}
atLeast : comparable -> comparable -> Expectation
atLeast =
compareWith "Expect.atLeast" (>=)
{-| A type to describe how close a floating point number must be to the expected value for the test to pass. This may be
specified as absolute or relative.
`AbsoluteOrRelative` tolerance uses a logical OR between the absolute (specified first) and relative tolerance. If you
want a logical AND, use [`Expect.all`](#all).
-}
type FloatingPointTolerance
= Absolute Float
| Relative Float
| AbsoluteOrRelative Float Float
{-| Passes if the second and third arguments are equal within a tolerance
specified by the first argument. This is intended to avoid failing because of
minor inaccuracies introduced by floating point arithmetic.
-- Fails because 0.1 + 0.2 == 0.30000000000000004 (0.1 is non-terminating in base 2)
0.1 + 0.2 |> Expect.equal 0.3
-- So instead write this test, which passes
0.1 + 0.2 |> Expect.within (Absolute 0.000000001) 0.3
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because 3.14 is not close enough to pi
3.14 |> Expect.within (Absolute 0.0001) pi
{-
3.14
╷
│ Expect.within Absolute 0.0001
╵
3.141592653589793
-}
-}
within : FloatingPointTolerance -> Float -> Float -> Expectation
within tolerance lower upper =
nonNegativeToleranceError tolerance "within" <|
compareWith ("Expect.within " ++ Internal.toString tolerance)
(withinCompare tolerance)
lower
upper
{-| Passes if (and only if) a call to `within` with the same arguments would have failed.
-}
notWithin : FloatingPointTolerance -> Float -> Float -> Expectation
notWithin tolerance lower upper =
nonNegativeToleranceError tolerance "notWithin" <|
compareWith ("Expect.notWithin " ++ Internal.toString tolerance)
(\a b -> not <| withinCompare tolerance a b)
lower
upper
{-| Passes if the argument is 'True', and otherwise fails with the given message.
Expect.true "Expected the list to be empty." (List.isEmpty [])
-- Passes because (List.isEmpty []) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because List.isEmpty returns False, but we expect True.
List.isEmpty [ 42 ]
|> Expect.true "Expected the list to be empty."
{-
Expected the list to be empty.
-}
-}
true : String -> Bool -> Expectation
true message bool =
if bool then
pass
else
fail message
{-| Passes if the argument is 'False', and otherwise fails with the given message.
Expect.false "Expected the list not to be empty." (List.isEmpty [ 42 ])
-- Passes because (List.isEmpty [ 42 ]) is False
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (List.isEmpty []) is True
List.isEmpty []
|> Expect.false "Expected the list not to be empty."
{-
Expected the list not to be empty.
-}
-}
false : String -> Bool -> Expectation
false message bool =
if bool then
fail message
else
pass
{-| Passes if the
[`Result`](https://package.elm-lang.org/packages/lang/core/latest/Result) is
an `Ok` rather than `Err`. This is useful for tests where you expect not to see
an error, but you don't care what the actual result is.
_(Tip: If your function returns a `Maybe` instead, consider `Expect.notEqual Nothing`.)_
-- Passes
String.toInt "not an int"
|> Expect.err
Test failures will be printed with the unexpected `Ok` value contrasting with
any `Err`.
-- Fails
String.toInt "20"
|> Expect.err
{-
Ok 20
╷
│ Expect.err
╵
Err _
-}
-}
ok : Result a b -> Expectation
ok result =
case result of
Ok _ ->
pass
Err _ ->
{ description = "Expect.ok"
, reason = Comparison "Ok _" (Internal.toString result)
}
|> Test.Expectation.fail
{-| Passes if the
[`Result`](http://package.elm-lang.org/packages/elm-lang/core/latest/Result) is
an `Err` rather than `Ok`. This is useful for tests where you expect to get an
error but you don't care what the actual error is.
_(Tip: If your function returns a `Maybe` instead, consider `Expect.equal Nothing`.)_
-- Passes
String.toInt "not an int"
|> Expect.err
Test failures will be printed with the unexpected `Ok` value contrasting with
any `Err`.
-- Fails
String.toInt "20"
|> Expect.err
{-
Ok 20
╷
│ Expect.err
╵
Err _
-}
-}
err : Result a b -> Expectation
err result =
case result of
Ok _ ->
{ description = "Expect.err"
, reason = Comparison "Err _" (Internal.toString result)
}
|> Test.Expectation.fail
Err _ ->
pass
{-| Passes if the arguments are equal lists.
-- Passes
[ 1, 2, 3 ]
|> Expect.equalLists [ 1, 2, 3 ]
Failures resemble code written in pipeline style, so you can tell
which argument is which, and reports which index the lists first
differed at or which list was longer:
-- Fails
[ 1, 2, 4, 6 ]
|> Expect.equalLists [ 1, 2, 5 ]
{-
[1,2,4,6]
first diff at index index 2: +`4`, -`5`
╷
│ Expect.equalLists
╵
first diff at index index 2: +`5`, -`4`
[1,2,5]
-}
-}
equalLists : List a -> List a -> Expectation
equalLists expected actual =
if expected == actual then
pass
else
{ description = "Expect.equalLists"
, reason = ListDiff (List.map Internal.toString expected) (List.map Internal.toString actual)
}
|> Test.Expectation.fail
{-| Passes if the arguments are equal dicts.
-- Passes
Dict.fromList [ ( 1, "one" ), ( 2, "two" ) ]
|> Expect.equalDicts (Dict.fromList [ ( 1, "one" ), ( 2, "two" ) ])
Failures resemble code written in pipeline style, so you can tell
which argument is which, and reports which keys were missing from
or added to each dict:
-- Fails
(Dict.fromList [ ( 1, "one" ), ( 2, "too" ) ])
|> Expect.equalDicts (Dict.fromList [ ( 1, "one" ), ( 2, "two" ), ( 3, "three" ) ])
{-
Dict.fromList [(1,"one"),(2,"too")]
diff: -[ (2,"two"), (3,"three") ] +[ (2,"too") ]
╷
│ Expect.equalDicts
╵
diff: +[ (2,"two"), (3,"three") ] -[ (2,"too") ]
Dict.fromList [(1,"one"),(2,"two"),(3,"three")]
-}
-}
equalDicts : Dict comparable a -> Dict comparable a -> Expectation
equalDicts expected actual =
if Dict.toList expected == Dict.toList actual then
pass
else
let
differ dict k v diffs =
if Dict.get k dict == Just v then
diffs
else
( k, v ) :: diffs
missingKeys =
Dict.foldr (differ actual) [] expected
extraKeys =
Dict.foldr (differ expected) [] actual
in
reportCollectionFailure "Expect.equalDicts" expected actual missingKeys extraKeys
{-| Passes if the arguments are equal sets.
-- Passes
Set.fromList [ 1, 2 ]
|> Expect.equalSets (Set.fromList [ 1, 2 ])
Failures resemble code written in pipeline style, so you can tell
which argument is which, and reports which keys were missing from
or added to each set:
-- Fails
(Set.fromList [ 1, 2, 4, 6 ])
|> Expect.equalSets (Set.fromList [ 1, 2, 5 ])
{-
Set.fromList [1,2,4,6]
diff: -[ 5 ] +[ 4, 6 ]
╷
│ Expect.equalSets
╵
diff: +[ 5 ] -[ 4, 6 ]
Set.fromList [1,2,5]
-}
-}
equalSets : Set comparable -> Set comparable -> Expectation
equalSets expected actual =
if Set.toList expected == Set.toList actual then
pass
else
let
missingKeys =
Set.diff expected actual
|> Set.toList
extraKeys =
Set.diff actual expected
|> Set.toList
in
reportCollectionFailure "Expect.equalSets" expected actual missingKeys extraKeys
{-| Always passes.
import Json.Decode exposing (decodeString, int)
import Test exposing (test)
import Expect
test "Json.Decode.int can decode the number 42." <|
\_ ->
case decodeString int "42" of
Ok _ ->
Expect.pass
Err err ->
Expect.fail err
-}
pass : Expectation
pass =
Test.Expectation.Pass
{-| Fails with the given message.
import Json.Decode exposing (decodeString, int)
import Test exposing (test)
import Expect
test "Json.Decode.int can decode the number 42." <|
\_ ->
case decodeString int "42" of
Ok _ ->
Expect.pass
Err err ->
Expect.fail err
-}
fail : String -> Expectation
fail str =
Test.Expectation.fail { description = str, reason = Custom }
{-| If the given expectation fails, replace its failure message with a custom one.
"something"
|> Expect.equal "something else"
|> Expect.onFail "thought those two strings would be the same"
-}
onFail : String -> Expectation -> Expectation
onFail str expectation =
case expectation of
Test.Expectation.Pass ->
expectation
Test.Expectation.Fail failure ->
Test.Expectation.Fail { failure | description = str, reason = Custom }
{-| Passes if each of the given functions passes when applied to the subject.
Passing an empty list is assumed to be a mistake, so `Expect.all []`
will always return a failed expectation no matter what else it is passed.
Expect.all
[ Expect.greaterThan -2
, Expect.lessThan 5
]
(List.length [])
-- Passes because (0 > -2) is True and (0 < 5) is also True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 < -10) is False
List.length []
|> Expect.all
[ Expect.greaterThan -2
, Expect.lessThan -10
, Expect.equal 0
]
{-
0
╷
│ Expect.lessThan
╵
-10
-}
-}
all : List (subject -> Expectation) -> subject -> Expectation
all list query =
if List.isEmpty list then
Test.Expectation.fail
{ reason = Invalid EmptyList
, description = "Expect.all was given an empty list. You must make at least one expectation to have a valid test!"
}
else
allHelp list query
allHelp : List (subject -> Expectation) -> subject -> Expectation
allHelp list query =
case list of
[] ->
pass
check :: rest ->
case check query of
Test.Expectation.Pass ->
allHelp rest query
outcome ->
outcome
{---- Private helper functions ----}
reportFailure : String -> String -> String -> Expectation
reportFailure comparison expected actual =
{ description = comparison
-- We may need to wrap expected and actual in quotes to maintain 0.18 behavior
, reason = Comparison expected actual
}
|> Test.Expectation.fail
reportCollectionFailure : String -> a -> b -> List c -> List d -> Expectation
reportCollectionFailure comparison expected actual missingKeys extraKeys =
{ description = comparison
, reason =
{ expected = Internal.toString expected
, actual = Internal.toString actual
, extra = List.map Internal.toString extraKeys
, missing = List.map Internal.toString missingKeys
}
|> CollectionDiff
}
|> Test.Expectation.fail
{-| String arg is label, e.g. "Expect.equal".
-}
equateWith : String -> (a -> b -> Bool) -> b -> a -> Expectation
equateWith reason comparison b a =
let
isJust x =
case x of
Just _ ->
True
Nothing ->
False
isFloat x =
isJust (String.toFloat x) && not (isJust (String.toInt x))
usesFloats =
isFloat (Internal.toString a) || isFloat (Internal.toString b)
floatError =
if String.contains reason "not" then
"Do not use Expect.notEqual with floats. Use Float.notWithin instead."
else
"Do not use Expect.equal with floats. Use Float.within instead."
in
if usesFloats then
fail floatError
else
testWith Equality reason comparison b a
compareWith : String -> (a -> b -> Bool) -> b -> a -> Expectation
compareWith =
testWith Comparison
testWith : (String -> String -> Reason) -> String -> (a -> b -> Bool) -> b -> a -> Expectation
testWith makeReason label runTest expected actual =
if runTest actual expected then
pass
else
{ description = label
, reason = makeReason (Internal.toString expected) (Internal.toString actual)
}
|> Test.Expectation.fail
{---- Private *floating point* helper functions ----}
absolute : FloatingPointTolerance -> Float
absolute tolerance =
case tolerance of
Absolute val ->
val
AbsoluteOrRelative val _ ->
val
_ ->
0
relative : FloatingPointTolerance -> Float
relative tolerance =
case tolerance of
Relative val ->
val
AbsoluteOrRelative _ val ->
val
_ ->
0
nonNegativeToleranceError : FloatingPointTolerance -> String -> Expectation -> Expectation
nonNegativeToleranceError tolerance name result =
if absolute tolerance < 0 && relative tolerance < 0 then
Test.Expectation.fail { description = "Expect." ++ name ++ " was given negative absolute and relative tolerances", reason = Custom }
else if absolute tolerance < 0 then
Test.Expectation.fail { description = "Expect." ++ name ++ " was given a negative absolute tolerance", reason = Custom }
else if relative tolerance < 0 then
Test.Expectation.fail { description = "Expect." ++ name ++ " was given a negative relative tolerance", reason = Custom }
else
result
withinCompare : FloatingPointTolerance -> Float -> Float -> Bool
withinCompare tolerance a b =
let
withinAbsoluteTolerance =
a - absolute tolerance <= b && b <= a + absolute tolerance
withinRelativeTolerance =
(a - abs (a * relative tolerance) <= b && b <= a + abs (a * relative tolerance))
|| (b - abs (b * relative tolerance) <= a && a <= b + abs (b * relative tolerance))
in
(a == b) || withinAbsoluteTolerance || withinRelativeTolerance
| 36710 | module Expect exposing
( Expectation, equal, notEqual, all
, lessThan, atMost, greaterThan, atLeast
, FloatingPointTolerance(..), within, notWithin
, true, false
, ok, err, equalLists, equalDicts, equalSets
, pass, fail, onFail
)
{-| A library to create `Expectation`s, which describe a claim to be tested.
## Quick Reference
- [`equal`](#equal) `(arg2 == arg1)`
- [`notEqual`](#notEqual) `(arg2 /= arg1)`
- [`lessThan`](#lessThan) `(arg2 < arg1)`
- [`atMost`](#atMost) `(arg2 <= arg1)`
- [`greaterThan`](#greaterThan) `(arg2 > arg1)`
- [`atLeast`](#atLeast) `(arg2 >= arg1)`
- [`true`](#true) `(arg == True)`
- [`false`](#false) `(arg == False)`
- [Floating Point Comparisons](#floating-point-comparisons)
## Basic Expectations
@docs Expectation, equal, notEqual, all
## Numeric Comparisons
@docs lessThan, atMost, greaterThan, atLeast
## Floating Point Comparisons
These functions allow you to compare `Float` values up to a specified rounding error, which may be relative, absolute,
or both. For an in-depth look, see our [Guide to Floating Point Comparison](#guide-to-floating-point-comparison).
@docs FloatingPointTolerance, within, notWithin
## Booleans
@docs true, false
## Collections
@docs ok, err, equalLists, equalDicts, equalSets
## Customizing
These functions will let you build your own expectations.
@docs pass, fail, onFail
## Guide to Floating Point Comparison
In general, if you are multiplying, you want relative tolerance, and if you're adding,
you want absolute tolerance. If you are doing both, you want both kinds of tolerance,
or to split the calculation into smaller parts for testing.
### Absolute Tolerance
Let's say we want to figure out if our estimation of pi is precise enough.
Is `3.14` within `0.01` of `pi`? Yes, because `3.13 < pi < 3.15`.
test "3.14 approximates pi with absolute precision" <|
\_ ->
3.14 |> Expect.within (Absolute 0.01) pi
### Relative Tolerance
What if we also want to know if our circle circumference estimation is close enough?
Let's say our circle has a radius of `r` meters. The formula for circle circumference is `C=2*r*pi`.
To make the calculations a bit easier ([ahem](https://tauday.com/tau-manifesto)), we'll look at half the circumference; `C/2=r*pi`.
Is `r * 3.14` within `0.01` of `r * pi`?
That depends, what does `r` equal? If `r` is `0.01`mm, or `0.00001` meters, we're comparing
`0.00001 * 3.14 - 0.01 < r * pi < 0.00001 * 3.14 + 0.01` or `-0.0099686 < 0.0000314159 < 0.0100314`.
That's a huge tolerance! A circumference that is _a thousand times longer_ than we expected would pass that test!
On the other hand, if `r` is very large, we're going to need many more digits of pi.
For an absolute tolerance of `0.01` and a pi estimation of `3.14`, this expectation only passes if `r < 2*pi`.
If we use a relative tolerance of `0.01` instead, the circle area comparison becomes much better. Is `r * 3.14` within
`1%` of `r * pi`? Yes! In fact, three digits of pi approximation is always good enough for a 0.1% relative tolerance,
as long as `r` isn't [too close to zero](https://en.wikipedia.org/wiki/Denormal_number).
fuzz
(floatRange 0.000001 100000)
"Circle half-circumference with relative tolerance"
(\r -> r * 3.14 |> Expect.within (Relative 0.001) (r * pi))
### Trouble with Numbers Near Zero
If you are adding things near zero, you probably want absolute tolerance. If you're comparing values between `-1` and `1`, you should consider using absolute tolerance.
For example: Is `1 + 2 - 3` within `1%` of `0`? Well, if `1`, `2` and `3` have any amount of rounding error, you might not get exactly zero. What is `1%` above and below `0`? Zero. We just lost all tolerance. Even if we hard-code the numbers, we might not get exactly zero; `0.1 + 0.2` rounds to a value just above `0.3`, since computers, counting in binary, cannot write down any of those three numbers using a finite number of digits, just like we cannot write `0.333...` exactly in base 10.
Another example is comparing values that are on either side of zero. `0.0001` is more than `100%` away from `-0.0001`. In fact, `infinity` is closer to `0.0001` than `0.0001` is to `-0.0001`, if you are using a relative tolerance. Twice as close, actually. So even though both `0.0001` and `-0.0001` could be considered very close to zero, they are very far apart relative to each other. The same argument applies for any number of zeroes.
-}
import Dict exposing (Dict)
import Set exposing (Set)
import Test.Expectation
import Test.Internal as Internal
import Test.Runner.Failure exposing (InvalidReason(..), Reason(..))
{-| The result of a single test run: either a [`pass`](#pass) or a
[`fail`](#fail).
-}
type alias Expectation =
Test.Expectation.Expectation
{-| Passes if the arguments are equal.
Expect.equal 0 (List.length [])
-- Passes because (0 == 0) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because the expected value didn't split the space in "<NAME>"
String.split " " "<NAME> bought some butter"
|> Expect.equal [ "<NAME>", "bought", "some", "butter" ]
{-
[ "<NAME>", "<NAME>", "bought", "some", "butter" ]
╷
│ Expect.equal
╵
[ "<NAME>", "bought", "some", "butter" ]
-}
Do not equate `Float` values; use [`within`](#within) instead.
-}
equal : a -> a -> Expectation
equal =
equateWith "Expect.equal" (==)
{-| Passes if the arguments are not equal.
-- Passes because (11 /= 100) is True
90 + 10
|> Expect.notEqual 11
-- Fails because (100 /= 100) is False
90 + 10
|> Expect.notEqual 100
{-
100
╷
│ Expect.notEqual
╵
100
-}
-}
notEqual : a -> a -> Expectation
notEqual =
equateWith "Expect.notEqual" (/=)
{-| Passes if the second argument is less than the first.
Expect.lessThan 1 (List.length [])
-- Passes because (0 < 1) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 < -1) is False
List.length []
|> Expect.lessThan -1
{-
0
╷
│ Expect.lessThan
╵
-1
-}
Do not equate `Float` values; use [`notWithin`](#notWithin) instead.
-}
lessThan : comparable -> comparable -> Expectation
lessThan =
compareWith "Expect.lessThan" (<)
{-| Passes if the second argument is less than or equal to the first.
Expect.atMost 1 (List.length [])
-- Passes because (0 <= 1) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 <= -3) is False
List.length []
|> Expect.atMost -3
{-
0
╷
│ Expect.atMost
╵
-3
-}
-}
atMost : comparable -> comparable -> Expectation
atMost =
compareWith "Expect.atMost" (<=)
{-| Passes if the second argument is greater than the first.
Expect.greaterThan -2 List.length []
-- Passes because (0 > -2) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 > 1) is False
List.length []
|> Expect.greaterThan 1
{-
0
╷
│ Expect.greaterThan
╵
1
-}
-}
greaterThan : comparable -> comparable -> Expectation
greaterThan =
compareWith "Expect.greaterThan" (>)
{-| Passes if the second argument is greater than or equal to the first.
Expect.atLeast -2 (List.length [])
-- Passes because (0 >= -2) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 >= 3) is False
List.length []
|> Expect.atLeast 3
{-
0
╷
│ Expect.atLeast
╵
3
-}
-}
atLeast : comparable -> comparable -> Expectation
atLeast =
compareWith "Expect.atLeast" (>=)
{-| A type to describe how close a floating point number must be to the expected value for the test to pass. This may be
specified as absolute or relative.
`AbsoluteOrRelative` tolerance uses a logical OR between the absolute (specified first) and relative tolerance. If you
want a logical AND, use [`Expect.all`](#all).
-}
type FloatingPointTolerance
= Absolute Float
| Relative Float
| AbsoluteOrRelative Float Float
{-| Passes if the second and third arguments are equal within a tolerance
specified by the first argument. This is intended to avoid failing because of
minor inaccuracies introduced by floating point arithmetic.
-- Fails because 0.1 + 0.2 == 0.30000000000000004 (0.1 is non-terminating in base 2)
0.1 + 0.2 |> Expect.equal 0.3
-- So instead write this test, which passes
0.1 + 0.2 |> Expect.within (Absolute 0.000000001) 0.3
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because 3.14 is not close enough to pi
3.14 |> Expect.within (Absolute 0.0001) pi
{-
3.14
╷
│ Expect.within Absolute 0.0001
╵
3.141592653589793
-}
-}
within : FloatingPointTolerance -> Float -> Float -> Expectation
within tolerance lower upper =
nonNegativeToleranceError tolerance "within" <|
compareWith ("Expect.within " ++ Internal.toString tolerance)
(withinCompare tolerance)
lower
upper
{-| Passes if (and only if) a call to `within` with the same arguments would have failed.
-}
notWithin : FloatingPointTolerance -> Float -> Float -> Expectation
notWithin tolerance lower upper =
nonNegativeToleranceError tolerance "notWithin" <|
compareWith ("Expect.notWithin " ++ Internal.toString tolerance)
(\a b -> not <| withinCompare tolerance a b)
lower
upper
{-| Passes if the argument is 'True', and otherwise fails with the given message.
Expect.true "Expected the list to be empty." (List.isEmpty [])
-- Passes because (List.isEmpty []) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because List.isEmpty returns False, but we expect True.
List.isEmpty [ 42 ]
|> Expect.true "Expected the list to be empty."
{-
Expected the list to be empty.
-}
-}
true : String -> Bool -> Expectation
true message bool =
if bool then
pass
else
fail message
{-| Passes if the argument is 'False', and otherwise fails with the given message.
Expect.false "Expected the list not to be empty." (List.isEmpty [ 42 ])
-- Passes because (List.isEmpty [ 42 ]) is False
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (List.isEmpty []) is True
List.isEmpty []
|> Expect.false "Expected the list not to be empty."
{-
Expected the list not to be empty.
-}
-}
false : String -> Bool -> Expectation
false message bool =
if bool then
fail message
else
pass
{-| Passes if the
[`Result`](https://package.elm-lang.org/packages/lang/core/latest/Result) is
an `Ok` rather than `Err`. This is useful for tests where you expect not to see
an error, but you don't care what the actual result is.
_(Tip: If your function returns a `Maybe` instead, consider `Expect.notEqual Nothing`.)_
-- Passes
String.toInt "not an int"
|> Expect.err
Test failures will be printed with the unexpected `Ok` value contrasting with
any `Err`.
-- Fails
String.toInt "20"
|> Expect.err
{-
Ok 20
╷
│ Expect.err
╵
Err _
-}
-}
ok : Result a b -> Expectation
ok result =
case result of
Ok _ ->
pass
Err _ ->
{ description = "Expect.ok"
, reason = Comparison "Ok _" (Internal.toString result)
}
|> Test.Expectation.fail
{-| Passes if the
[`Result`](http://package.elm-lang.org/packages/elm-lang/core/latest/Result) is
an `Err` rather than `Ok`. This is useful for tests where you expect to get an
error but you don't care what the actual error is.
_(Tip: If your function returns a `Maybe` instead, consider `Expect.equal Nothing`.)_
-- Passes
String.toInt "not an int"
|> Expect.err
Test failures will be printed with the unexpected `Ok` value contrasting with
any `Err`.
-- Fails
String.toInt "20"
|> Expect.err
{-
Ok 20
╷
│ Expect.err
╵
Err _
-}
-}
err : Result a b -> Expectation
err result =
case result of
Ok _ ->
{ description = "Expect.err"
, reason = Comparison "Err _" (Internal.toString result)
}
|> Test.Expectation.fail
Err _ ->
pass
{-| Passes if the arguments are equal lists.
-- Passes
[ 1, 2, 3 ]
|> Expect.equalLists [ 1, 2, 3 ]
Failures resemble code written in pipeline style, so you can tell
which argument is which, and reports which index the lists first
differed at or which list was longer:
-- Fails
[ 1, 2, 4, 6 ]
|> Expect.equalLists [ 1, 2, 5 ]
{-
[1,2,4,6]
first diff at index index 2: +`4`, -`5`
╷
│ Expect.equalLists
╵
first diff at index index 2: +`5`, -`4`
[1,2,5]
-}
-}
equalLists : List a -> List a -> Expectation
equalLists expected actual =
if expected == actual then
pass
else
{ description = "Expect.equalLists"
, reason = ListDiff (List.map Internal.toString expected) (List.map Internal.toString actual)
}
|> Test.Expectation.fail
{-| Passes if the arguments are equal dicts.
-- Passes
Dict.fromList [ ( 1, "one" ), ( 2, "two" ) ]
|> Expect.equalDicts (Dict.fromList [ ( 1, "one" ), ( 2, "two" ) ])
Failures resemble code written in pipeline style, so you can tell
which argument is which, and reports which keys were missing from
or added to each dict:
-- Fails
(Dict.fromList [ ( 1, "one" ), ( 2, "too" ) ])
|> Expect.equalDicts (Dict.fromList [ ( 1, "one" ), ( 2, "two" ), ( 3, "three" ) ])
{-
Dict.fromList [(1,"one"),(2,"too")]
diff: -[ (2,"two"), (3,"three") ] +[ (2,"too") ]
╷
│ Expect.equalDicts
╵
diff: +[ (2,"two"), (3,"three") ] -[ (2,"too") ]
Dict.fromList [(1,"one"),(2,"two"),(3,"three")]
-}
-}
equalDicts : Dict comparable a -> Dict comparable a -> Expectation
equalDicts expected actual =
if Dict.toList expected == Dict.toList actual then
pass
else
let
differ dict k v diffs =
if Dict.get k dict == Just v then
diffs
else
( k, v ) :: diffs
missingKeys =
Dict.foldr (differ actual) [] expected
extraKeys =
Dict.foldr (differ expected) [] actual
in
reportCollectionFailure "Expect.equalDicts" expected actual missingKeys extraKeys
{-| Passes if the arguments are equal sets.
-- Passes
Set.fromList [ 1, 2 ]
|> Expect.equalSets (Set.fromList [ 1, 2 ])
Failures resemble code written in pipeline style, so you can tell
which argument is which, and reports which keys were missing from
or added to each set:
-- Fails
(Set.fromList [ 1, 2, 4, 6 ])
|> Expect.equalSets (Set.fromList [ 1, 2, 5 ])
{-
Set.fromList [1,2,4,6]
diff: -[ 5 ] +[ 4, 6 ]
╷
│ Expect.equalSets
╵
diff: +[ 5 ] -[ 4, 6 ]
Set.fromList [1,2,5]
-}
-}
equalSets : Set comparable -> Set comparable -> Expectation
equalSets expected actual =
if Set.toList expected == Set.toList actual then
pass
else
let
missingKeys =
Set.diff expected actual
|> Set.toList
extraKeys =
Set.diff actual expected
|> Set.toList
in
reportCollectionFailure "Expect.equalSets" expected actual missingKeys extraKeys
{-| Always passes.
import Json.Decode exposing (decodeString, int)
import Test exposing (test)
import Expect
test "Json.Decode.int can decode the number 42." <|
\_ ->
case decodeString int "42" of
Ok _ ->
Expect.pass
Err err ->
Expect.fail err
-}
pass : Expectation
pass =
Test.Expectation.Pass
{-| Fails with the given message.
import Json.Decode exposing (decodeString, int)
import Test exposing (test)
import Expect
test "Json.Decode.int can decode the number 42." <|
\_ ->
case decodeString int "42" of
Ok _ ->
Expect.pass
Err err ->
Expect.fail err
-}
fail : String -> Expectation
fail str =
Test.Expectation.fail { description = str, reason = Custom }
{-| If the given expectation fails, replace its failure message with a custom one.
"something"
|> Expect.equal "something else"
|> Expect.onFail "thought those two strings would be the same"
-}
onFail : String -> Expectation -> Expectation
onFail str expectation =
case expectation of
Test.Expectation.Pass ->
expectation
Test.Expectation.Fail failure ->
Test.Expectation.Fail { failure | description = str, reason = Custom }
{-| Passes if each of the given functions passes when applied to the subject.
Passing an empty list is assumed to be a mistake, so `Expect.all []`
will always return a failed expectation no matter what else it is passed.
Expect.all
[ Expect.greaterThan -2
, Expect.lessThan 5
]
(List.length [])
-- Passes because (0 > -2) is True and (0 < 5) is also True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 < -10) is False
List.length []
|> Expect.all
[ Expect.greaterThan -2
, Expect.lessThan -10
, Expect.equal 0
]
{-
0
╷
│ Expect.lessThan
╵
-10
-}
-}
all : List (subject -> Expectation) -> subject -> Expectation
all list query =
if List.isEmpty list then
Test.Expectation.fail
{ reason = Invalid EmptyList
, description = "Expect.all was given an empty list. You must make at least one expectation to have a valid test!"
}
else
allHelp list query
allHelp : List (subject -> Expectation) -> subject -> Expectation
allHelp list query =
case list of
[] ->
pass
check :: rest ->
case check query of
Test.Expectation.Pass ->
allHelp rest query
outcome ->
outcome
{---- Private helper functions ----}
reportFailure : String -> String -> String -> Expectation
reportFailure comparison expected actual =
{ description = comparison
-- We may need to wrap expected and actual in quotes to maintain 0.18 behavior
, reason = Comparison expected actual
}
|> Test.Expectation.fail
reportCollectionFailure : String -> a -> b -> List c -> List d -> Expectation
reportCollectionFailure comparison expected actual missingKeys extraKeys =
{ description = comparison
, reason =
{ expected = Internal.toString expected
, actual = Internal.toString actual
, extra = List.map Internal.toString extraKeys
, missing = List.map Internal.toString missingKeys
}
|> CollectionDiff
}
|> Test.Expectation.fail
{-| String arg is label, e.g. "Expect.equal".
-}
equateWith : String -> (a -> b -> Bool) -> b -> a -> Expectation
equateWith reason comparison b a =
let
isJust x =
case x of
Just _ ->
True
Nothing ->
False
isFloat x =
isJust (String.toFloat x) && not (isJust (String.toInt x))
usesFloats =
isFloat (Internal.toString a) || isFloat (Internal.toString b)
floatError =
if String.contains reason "not" then
"Do not use Expect.notEqual with floats. Use Float.notWithin instead."
else
"Do not use Expect.equal with floats. Use Float.within instead."
in
if usesFloats then
fail floatError
else
testWith Equality reason comparison b a
compareWith : String -> (a -> b -> Bool) -> b -> a -> Expectation
compareWith =
testWith Comparison
testWith : (String -> String -> Reason) -> String -> (a -> b -> Bool) -> b -> a -> Expectation
testWith makeReason label runTest expected actual =
if runTest actual expected then
pass
else
{ description = label
, reason = makeReason (Internal.toString expected) (Internal.toString actual)
}
|> Test.Expectation.fail
{---- Private *floating point* helper functions ----}
absolute : FloatingPointTolerance -> Float
absolute tolerance =
case tolerance of
Absolute val ->
val
AbsoluteOrRelative val _ ->
val
_ ->
0
relative : FloatingPointTolerance -> Float
relative tolerance =
case tolerance of
Relative val ->
val
AbsoluteOrRelative _ val ->
val
_ ->
0
nonNegativeToleranceError : FloatingPointTolerance -> String -> Expectation -> Expectation
nonNegativeToleranceError tolerance name result =
if absolute tolerance < 0 && relative tolerance < 0 then
Test.Expectation.fail { description = "Expect." ++ name ++ " was given negative absolute and relative tolerances", reason = Custom }
else if absolute tolerance < 0 then
Test.Expectation.fail { description = "Expect." ++ name ++ " was given a negative absolute tolerance", reason = Custom }
else if relative tolerance < 0 then
Test.Expectation.fail { description = "Expect." ++ name ++ " was given a negative relative tolerance", reason = Custom }
else
result
withinCompare : FloatingPointTolerance -> Float -> Float -> Bool
withinCompare tolerance a b =
let
withinAbsoluteTolerance =
a - absolute tolerance <= b && b <= a + absolute tolerance
withinRelativeTolerance =
(a - abs (a * relative tolerance) <= b && b <= a + abs (a * relative tolerance))
|| (b - abs (b * relative tolerance) <= a && a <= b + abs (b * relative tolerance))
in
(a == b) || withinAbsoluteTolerance || withinRelativeTolerance
| true | module Expect exposing
( Expectation, equal, notEqual, all
, lessThan, atMost, greaterThan, atLeast
, FloatingPointTolerance(..), within, notWithin
, true, false
, ok, err, equalLists, equalDicts, equalSets
, pass, fail, onFail
)
{-| A library to create `Expectation`s, which describe a claim to be tested.
## Quick Reference
- [`equal`](#equal) `(arg2 == arg1)`
- [`notEqual`](#notEqual) `(arg2 /= arg1)`
- [`lessThan`](#lessThan) `(arg2 < arg1)`
- [`atMost`](#atMost) `(arg2 <= arg1)`
- [`greaterThan`](#greaterThan) `(arg2 > arg1)`
- [`atLeast`](#atLeast) `(arg2 >= arg1)`
- [`true`](#true) `(arg == True)`
- [`false`](#false) `(arg == False)`
- [Floating Point Comparisons](#floating-point-comparisons)
## Basic Expectations
@docs Expectation, equal, notEqual, all
## Numeric Comparisons
@docs lessThan, atMost, greaterThan, atLeast
## Floating Point Comparisons
These functions allow you to compare `Float` values up to a specified rounding error, which may be relative, absolute,
or both. For an in-depth look, see our [Guide to Floating Point Comparison](#guide-to-floating-point-comparison).
@docs FloatingPointTolerance, within, notWithin
## Booleans
@docs true, false
## Collections
@docs ok, err, equalLists, equalDicts, equalSets
## Customizing
These functions will let you build your own expectations.
@docs pass, fail, onFail
## Guide to Floating Point Comparison
In general, if you are multiplying, you want relative tolerance, and if you're adding,
you want absolute tolerance. If you are doing both, you want both kinds of tolerance,
or to split the calculation into smaller parts for testing.
### Absolute Tolerance
Let's say we want to figure out if our estimation of pi is precise enough.
Is `3.14` within `0.01` of `pi`? Yes, because `3.13 < pi < 3.15`.
test "3.14 approximates pi with absolute precision" <|
\_ ->
3.14 |> Expect.within (Absolute 0.01) pi
### Relative Tolerance
What if we also want to know if our circle circumference estimation is close enough?
Let's say our circle has a radius of `r` meters. The formula for circle circumference is `C=2*r*pi`.
To make the calculations a bit easier ([ahem](https://tauday.com/tau-manifesto)), we'll look at half the circumference; `C/2=r*pi`.
Is `r * 3.14` within `0.01` of `r * pi`?
That depends, what does `r` equal? If `r` is `0.01`mm, or `0.00001` meters, we're comparing
`0.00001 * 3.14 - 0.01 < r * pi < 0.00001 * 3.14 + 0.01` or `-0.0099686 < 0.0000314159 < 0.0100314`.
That's a huge tolerance! A circumference that is _a thousand times longer_ than we expected would pass that test!
On the other hand, if `r` is very large, we're going to need many more digits of pi.
For an absolute tolerance of `0.01` and a pi estimation of `3.14`, this expectation only passes if `r < 2*pi`.
If we use a relative tolerance of `0.01` instead, the circle area comparison becomes much better. Is `r * 3.14` within
`1%` of `r * pi`? Yes! In fact, three digits of pi approximation is always good enough for a 0.1% relative tolerance,
as long as `r` isn't [too close to zero](https://en.wikipedia.org/wiki/Denormal_number).
fuzz
(floatRange 0.000001 100000)
"Circle half-circumference with relative tolerance"
(\r -> r * 3.14 |> Expect.within (Relative 0.001) (r * pi))
### Trouble with Numbers Near Zero
If you are adding things near zero, you probably want absolute tolerance. If you're comparing values between `-1` and `1`, you should consider using absolute tolerance.
For example: Is `1 + 2 - 3` within `1%` of `0`? Well, if `1`, `2` and `3` have any amount of rounding error, you might not get exactly zero. What is `1%` above and below `0`? Zero. We just lost all tolerance. Even if we hard-code the numbers, we might not get exactly zero; `0.1 + 0.2` rounds to a value just above `0.3`, since computers, counting in binary, cannot write down any of those three numbers using a finite number of digits, just like we cannot write `0.333...` exactly in base 10.
Another example is comparing values that are on either side of zero. `0.0001` is more than `100%` away from `-0.0001`. In fact, `infinity` is closer to `0.0001` than `0.0001` is to `-0.0001`, if you are using a relative tolerance. Twice as close, actually. So even though both `0.0001` and `-0.0001` could be considered very close to zero, they are very far apart relative to each other. The same argument applies for any number of zeroes.
-}
import Dict exposing (Dict)
import Set exposing (Set)
import Test.Expectation
import Test.Internal as Internal
import Test.Runner.Failure exposing (InvalidReason(..), Reason(..))
{-| The result of a single test run: either a [`pass`](#pass) or a
[`fail`](#fail).
-}
type alias Expectation =
Test.Expectation.Expectation
{-| Passes if the arguments are equal.
Expect.equal 0 (List.length [])
-- Passes because (0 == 0) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because the expected value didn't split the space in "PI:NAME:<NAME>END_PI"
String.split " " "PI:NAME:<NAME>END_PI bought some butter"
|> Expect.equal [ "PI:NAME:<NAME>END_PI", "bought", "some", "butter" ]
{-
[ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "bought", "some", "butter" ]
╷
│ Expect.equal
╵
[ "PI:NAME:<NAME>END_PI", "bought", "some", "butter" ]
-}
Do not equate `Float` values; use [`within`](#within) instead.
-}
equal : a -> a -> Expectation
equal =
equateWith "Expect.equal" (==)
{-| Passes if the arguments are not equal.
-- Passes because (11 /= 100) is True
90 + 10
|> Expect.notEqual 11
-- Fails because (100 /= 100) is False
90 + 10
|> Expect.notEqual 100
{-
100
╷
│ Expect.notEqual
╵
100
-}
-}
notEqual : a -> a -> Expectation
notEqual =
equateWith "Expect.notEqual" (/=)
{-| Passes if the second argument is less than the first.
Expect.lessThan 1 (List.length [])
-- Passes because (0 < 1) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 < -1) is False
List.length []
|> Expect.lessThan -1
{-
0
╷
│ Expect.lessThan
╵
-1
-}
Do not equate `Float` values; use [`notWithin`](#notWithin) instead.
-}
lessThan : comparable -> comparable -> Expectation
lessThan =
compareWith "Expect.lessThan" (<)
{-| Passes if the second argument is less than or equal to the first.
Expect.atMost 1 (List.length [])
-- Passes because (0 <= 1) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 <= -3) is False
List.length []
|> Expect.atMost -3
{-
0
╷
│ Expect.atMost
╵
-3
-}
-}
atMost : comparable -> comparable -> Expectation
atMost =
compareWith "Expect.atMost" (<=)
{-| Passes if the second argument is greater than the first.
Expect.greaterThan -2 List.length []
-- Passes because (0 > -2) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 > 1) is False
List.length []
|> Expect.greaterThan 1
{-
0
╷
│ Expect.greaterThan
╵
1
-}
-}
greaterThan : comparable -> comparable -> Expectation
greaterThan =
compareWith "Expect.greaterThan" (>)
{-| Passes if the second argument is greater than or equal to the first.
Expect.atLeast -2 (List.length [])
-- Passes because (0 >= -2) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 >= 3) is False
List.length []
|> Expect.atLeast 3
{-
0
╷
│ Expect.atLeast
╵
3
-}
-}
atLeast : comparable -> comparable -> Expectation
atLeast =
compareWith "Expect.atLeast" (>=)
{-| A type to describe how close a floating point number must be to the expected value for the test to pass. This may be
specified as absolute or relative.
`AbsoluteOrRelative` tolerance uses a logical OR between the absolute (specified first) and relative tolerance. If you
want a logical AND, use [`Expect.all`](#all).
-}
type FloatingPointTolerance
= Absolute Float
| Relative Float
| AbsoluteOrRelative Float Float
{-| Passes if the second and third arguments are equal within a tolerance
specified by the first argument. This is intended to avoid failing because of
minor inaccuracies introduced by floating point arithmetic.
-- Fails because 0.1 + 0.2 == 0.30000000000000004 (0.1 is non-terminating in base 2)
0.1 + 0.2 |> Expect.equal 0.3
-- So instead write this test, which passes
0.1 + 0.2 |> Expect.within (Absolute 0.000000001) 0.3
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because 3.14 is not close enough to pi
3.14 |> Expect.within (Absolute 0.0001) pi
{-
3.14
╷
│ Expect.within Absolute 0.0001
╵
3.141592653589793
-}
-}
within : FloatingPointTolerance -> Float -> Float -> Expectation
within tolerance lower upper =
nonNegativeToleranceError tolerance "within" <|
compareWith ("Expect.within " ++ Internal.toString tolerance)
(withinCompare tolerance)
lower
upper
{-| Passes if (and only if) a call to `within` with the same arguments would have failed.
-}
notWithin : FloatingPointTolerance -> Float -> Float -> Expectation
notWithin tolerance lower upper =
nonNegativeToleranceError tolerance "notWithin" <|
compareWith ("Expect.notWithin " ++ Internal.toString tolerance)
(\a b -> not <| withinCompare tolerance a b)
lower
upper
{-| Passes if the argument is 'True', and otherwise fails with the given message.
Expect.true "Expected the list to be empty." (List.isEmpty [])
-- Passes because (List.isEmpty []) is True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because List.isEmpty returns False, but we expect True.
List.isEmpty [ 42 ]
|> Expect.true "Expected the list to be empty."
{-
Expected the list to be empty.
-}
-}
true : String -> Bool -> Expectation
true message bool =
if bool then
pass
else
fail message
{-| Passes if the argument is 'False', and otherwise fails with the given message.
Expect.false "Expected the list not to be empty." (List.isEmpty [ 42 ])
-- Passes because (List.isEmpty [ 42 ]) is False
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (List.isEmpty []) is True
List.isEmpty []
|> Expect.false "Expected the list not to be empty."
{-
Expected the list not to be empty.
-}
-}
false : String -> Bool -> Expectation
false message bool =
if bool then
fail message
else
pass
{-| Passes if the
[`Result`](https://package.elm-lang.org/packages/lang/core/latest/Result) is
an `Ok` rather than `Err`. This is useful for tests where you expect not to see
an error, but you don't care what the actual result is.
_(Tip: If your function returns a `Maybe` instead, consider `Expect.notEqual Nothing`.)_
-- Passes
String.toInt "not an int"
|> Expect.err
Test failures will be printed with the unexpected `Ok` value contrasting with
any `Err`.
-- Fails
String.toInt "20"
|> Expect.err
{-
Ok 20
╷
│ Expect.err
╵
Err _
-}
-}
ok : Result a b -> Expectation
ok result =
case result of
Ok _ ->
pass
Err _ ->
{ description = "Expect.ok"
, reason = Comparison "Ok _" (Internal.toString result)
}
|> Test.Expectation.fail
{-| Passes if the
[`Result`](http://package.elm-lang.org/packages/elm-lang/core/latest/Result) is
an `Err` rather than `Ok`. This is useful for tests where you expect to get an
error but you don't care what the actual error is.
_(Tip: If your function returns a `Maybe` instead, consider `Expect.equal Nothing`.)_
-- Passes
String.toInt "not an int"
|> Expect.err
Test failures will be printed with the unexpected `Ok` value contrasting with
any `Err`.
-- Fails
String.toInt "20"
|> Expect.err
{-
Ok 20
╷
│ Expect.err
╵
Err _
-}
-}
err : Result a b -> Expectation
err result =
case result of
Ok _ ->
{ description = "Expect.err"
, reason = Comparison "Err _" (Internal.toString result)
}
|> Test.Expectation.fail
Err _ ->
pass
{-| Passes if the arguments are equal lists.
-- Passes
[ 1, 2, 3 ]
|> Expect.equalLists [ 1, 2, 3 ]
Failures resemble code written in pipeline style, so you can tell
which argument is which, and reports which index the lists first
differed at or which list was longer:
-- Fails
[ 1, 2, 4, 6 ]
|> Expect.equalLists [ 1, 2, 5 ]
{-
[1,2,4,6]
first diff at index index 2: +`4`, -`5`
╷
│ Expect.equalLists
╵
first diff at index index 2: +`5`, -`4`
[1,2,5]
-}
-}
equalLists : List a -> List a -> Expectation
equalLists expected actual =
if expected == actual then
pass
else
{ description = "Expect.equalLists"
, reason = ListDiff (List.map Internal.toString expected) (List.map Internal.toString actual)
}
|> Test.Expectation.fail
{-| Passes if the arguments are equal dicts.
-- Passes
Dict.fromList [ ( 1, "one" ), ( 2, "two" ) ]
|> Expect.equalDicts (Dict.fromList [ ( 1, "one" ), ( 2, "two" ) ])
Failures resemble code written in pipeline style, so you can tell
which argument is which, and reports which keys were missing from
or added to each dict:
-- Fails
(Dict.fromList [ ( 1, "one" ), ( 2, "too" ) ])
|> Expect.equalDicts (Dict.fromList [ ( 1, "one" ), ( 2, "two" ), ( 3, "three" ) ])
{-
Dict.fromList [(1,"one"),(2,"too")]
diff: -[ (2,"two"), (3,"three") ] +[ (2,"too") ]
╷
│ Expect.equalDicts
╵
diff: +[ (2,"two"), (3,"three") ] -[ (2,"too") ]
Dict.fromList [(1,"one"),(2,"two"),(3,"three")]
-}
-}
equalDicts : Dict comparable a -> Dict comparable a -> Expectation
equalDicts expected actual =
if Dict.toList expected == Dict.toList actual then
pass
else
let
differ dict k v diffs =
if Dict.get k dict == Just v then
diffs
else
( k, v ) :: diffs
missingKeys =
Dict.foldr (differ actual) [] expected
extraKeys =
Dict.foldr (differ expected) [] actual
in
reportCollectionFailure "Expect.equalDicts" expected actual missingKeys extraKeys
{-| Passes if the arguments are equal sets.
-- Passes
Set.fromList [ 1, 2 ]
|> Expect.equalSets (Set.fromList [ 1, 2 ])
Failures resemble code written in pipeline style, so you can tell
which argument is which, and reports which keys were missing from
or added to each set:
-- Fails
(Set.fromList [ 1, 2, 4, 6 ])
|> Expect.equalSets (Set.fromList [ 1, 2, 5 ])
{-
Set.fromList [1,2,4,6]
diff: -[ 5 ] +[ 4, 6 ]
╷
│ Expect.equalSets
╵
diff: +[ 5 ] -[ 4, 6 ]
Set.fromList [1,2,5]
-}
-}
equalSets : Set comparable -> Set comparable -> Expectation
equalSets expected actual =
if Set.toList expected == Set.toList actual then
pass
else
let
missingKeys =
Set.diff expected actual
|> Set.toList
extraKeys =
Set.diff actual expected
|> Set.toList
in
reportCollectionFailure "Expect.equalSets" expected actual missingKeys extraKeys
{-| Always passes.
import Json.Decode exposing (decodeString, int)
import Test exposing (test)
import Expect
test "Json.Decode.int can decode the number 42." <|
\_ ->
case decodeString int "42" of
Ok _ ->
Expect.pass
Err err ->
Expect.fail err
-}
pass : Expectation
pass =
Test.Expectation.Pass
{-| Fails with the given message.
import Json.Decode exposing (decodeString, int)
import Test exposing (test)
import Expect
test "Json.Decode.int can decode the number 42." <|
\_ ->
case decodeString int "42" of
Ok _ ->
Expect.pass
Err err ->
Expect.fail err
-}
fail : String -> Expectation
fail str =
Test.Expectation.fail { description = str, reason = Custom }
{-| If the given expectation fails, replace its failure message with a custom one.
"something"
|> Expect.equal "something else"
|> Expect.onFail "thought those two strings would be the same"
-}
onFail : String -> Expectation -> Expectation
onFail str expectation =
case expectation of
Test.Expectation.Pass ->
expectation
Test.Expectation.Fail failure ->
Test.Expectation.Fail { failure | description = str, reason = Custom }
{-| Passes if each of the given functions passes when applied to the subject.
Passing an empty list is assumed to be a mistake, so `Expect.all []`
will always return a failed expectation no matter what else it is passed.
Expect.all
[ Expect.greaterThan -2
, Expect.lessThan 5
]
(List.length [])
-- Passes because (0 > -2) is True and (0 < 5) is also True
Failures resemble code written in pipeline style, so you can tell
which argument is which:
-- Fails because (0 < -10) is False
List.length []
|> Expect.all
[ Expect.greaterThan -2
, Expect.lessThan -10
, Expect.equal 0
]
{-
0
╷
│ Expect.lessThan
╵
-10
-}
-}
all : List (subject -> Expectation) -> subject -> Expectation
all list query =
if List.isEmpty list then
Test.Expectation.fail
{ reason = Invalid EmptyList
, description = "Expect.all was given an empty list. You must make at least one expectation to have a valid test!"
}
else
allHelp list query
allHelp : List (subject -> Expectation) -> subject -> Expectation
allHelp list query =
case list of
[] ->
pass
check :: rest ->
case check query of
Test.Expectation.Pass ->
allHelp rest query
outcome ->
outcome
{---- Private helper functions ----}
reportFailure : String -> String -> String -> Expectation
reportFailure comparison expected actual =
{ description = comparison
-- We may need to wrap expected and actual in quotes to maintain 0.18 behavior
, reason = Comparison expected actual
}
|> Test.Expectation.fail
reportCollectionFailure : String -> a -> b -> List c -> List d -> Expectation
reportCollectionFailure comparison expected actual missingKeys extraKeys =
{ description = comparison
, reason =
{ expected = Internal.toString expected
, actual = Internal.toString actual
, extra = List.map Internal.toString extraKeys
, missing = List.map Internal.toString missingKeys
}
|> CollectionDiff
}
|> Test.Expectation.fail
{-| String arg is label, e.g. "Expect.equal".
-}
equateWith : String -> (a -> b -> Bool) -> b -> a -> Expectation
equateWith reason comparison b a =
let
isJust x =
case x of
Just _ ->
True
Nothing ->
False
isFloat x =
isJust (String.toFloat x) && not (isJust (String.toInt x))
usesFloats =
isFloat (Internal.toString a) || isFloat (Internal.toString b)
floatError =
if String.contains reason "not" then
"Do not use Expect.notEqual with floats. Use Float.notWithin instead."
else
"Do not use Expect.equal with floats. Use Float.within instead."
in
if usesFloats then
fail floatError
else
testWith Equality reason comparison b a
compareWith : String -> (a -> b -> Bool) -> b -> a -> Expectation
compareWith =
testWith Comparison
testWith : (String -> String -> Reason) -> String -> (a -> b -> Bool) -> b -> a -> Expectation
testWith makeReason label runTest expected actual =
if runTest actual expected then
pass
else
{ description = label
, reason = makeReason (Internal.toString expected) (Internal.toString actual)
}
|> Test.Expectation.fail
{---- Private *floating point* helper functions ----}
absolute : FloatingPointTolerance -> Float
absolute tolerance =
case tolerance of
Absolute val ->
val
AbsoluteOrRelative val _ ->
val
_ ->
0
relative : FloatingPointTolerance -> Float
relative tolerance =
case tolerance of
Relative val ->
val
AbsoluteOrRelative _ val ->
val
_ ->
0
nonNegativeToleranceError : FloatingPointTolerance -> String -> Expectation -> Expectation
nonNegativeToleranceError tolerance name result =
if absolute tolerance < 0 && relative tolerance < 0 then
Test.Expectation.fail { description = "Expect." ++ name ++ " was given negative absolute and relative tolerances", reason = Custom }
else if absolute tolerance < 0 then
Test.Expectation.fail { description = "Expect." ++ name ++ " was given a negative absolute tolerance", reason = Custom }
else if relative tolerance < 0 then
Test.Expectation.fail { description = "Expect." ++ name ++ " was given a negative relative tolerance", reason = Custom }
else
result
withinCompare : FloatingPointTolerance -> Float -> Float -> Bool
withinCompare tolerance a b =
let
withinAbsoluteTolerance =
a - absolute tolerance <= b && b <= a + absolute tolerance
withinRelativeTolerance =
(a - abs (a * relative tolerance) <= b && b <= a + abs (a * relative tolerance))
|| (b - abs (b * relative tolerance) <= a && a <= b + abs (b * relative tolerance))
in
(a == b) || withinAbsoluteTolerance || withinRelativeTolerance
| elm |
[
{
"context": " |> fire (Prepared { recipient = \"Mert\", amount = 42 })\n |> log\n ",
"end": 375,
"score": 0.9997209311,
"start": 371,
"tag": "NAME",
"value": "Mert"
},
{
"context": "pect.equalLists\n [ Sent \"Hi Mert, your next invoice for $42 is ready\"\n ",
"end": 500,
"score": 0.9993121624,
"start": 496,
"tag": "NAME",
"value": "Mert"
},
{
"context": " , Prepared { recipient = \"Mert\", amount = 42 }\n ]\n ",
"end": 592,
"score": 0.9997532368,
"start": 588,
"tag": "NAME",
"value": "Mert"
},
{
"context": " |> fire (Prepared { recipient = \"Mert\", amount = 42 })\n |> fire (Pre",
"end": 869,
"score": 0.9997096658,
"start": 865,
"tag": "NAME",
"value": "Mert"
},
{
"context": " |> fire (Prepared { recipient = \"Mert\", amount = 100 })\n |> log\n ",
"end": 944,
"score": 0.9997547269,
"start": 940,
"tag": "NAME",
"value": "Mert"
},
{
"context": "pect.equalLists\n [ Sent \"Hi Mert, your next invoice for $100 is ready\"\n ",
"end": 1070,
"score": 0.9988152981,
"start": 1066,
"tag": "NAME",
"value": "Mert"
},
{
"context": " , Prepared { recipient = \"Mert\", amount = 100 }\n , Sent \"",
"end": 1163,
"score": 0.9996763468,
"start": 1159,
"tag": "NAME",
"value": "Mert"
},
{
"context": "nt = 100 }\n , Sent \"Welcome Mert, your first invoice for $42 is ready\"\n ",
"end": 1225,
"score": 0.9997000098,
"start": 1221,
"tag": "NAME",
"value": "Mert"
},
{
"context": " , Prepared { recipient = \"Mert\", amount = 42 }\n ]\n ",
"end": 1318,
"score": 0.9997463822,
"start": 1314,
"tag": "NAME",
"value": "Mert"
},
{
"context": " |> fire (Prepared { recipient = \"Mert\", amount = 42 })\n |> fire (Pre",
"end": 1583,
"score": 0.9996588826,
"start": 1579,
"tag": "NAME",
"value": "Mert"
},
{
"context": " |> fire (Prepared { recipient = \"Mert\", amount = 100 })\n |> fire (Pr",
"end": 1658,
"score": 0.9997364283,
"start": 1654,
"tag": "NAME",
"value": "Mert"
},
{
"context": " |> fire (Prepared { recipient = \"Betül\", amount = 2 })\n |> fire (Prep",
"end": 1735,
"score": 0.999548912,
"start": 1730,
"tag": "NAME",
"value": "Betül"
},
{
"context": " |> fire (Prepared { recipient = \"Mert\", amount = 66 })\n |> log\n ",
"end": 1809,
"score": 0.999684453,
"start": 1805,
"tag": "NAME",
"value": "Mert"
},
{
"context": "pect.equalLists\n [ Sent \"Hi Mert, your next invoice for $66 is ready\"\n ",
"end": 1934,
"score": 0.9994610548,
"start": 1930,
"tag": "NAME",
"value": "Mert"
},
{
"context": " , Prepared { recipient = \"Mert\", amount = 66 }\n , Sent \"W",
"end": 2026,
"score": 0.9997648001,
"start": 2022,
"tag": "NAME",
"value": "Mert"
},
{
"context": "unt = 66 }\n , Sent \"Welcome Betül, your first invoice for $2 is ready\"\n ",
"end": 2088,
"score": 0.9994800687,
"start": 2083,
"tag": "NAME",
"value": "Betül"
},
{
"context": " , Prepared { recipient = \"Betül\", amount = 2 }\n , Sent \"Hi",
"end": 2181,
"score": 0.9996013641,
"start": 2176,
"tag": "NAME",
"value": "Betül"
},
{
"context": "\", amount = 2 }\n , Sent \"Hi Mert, your next invoice for $100 is ready\"\n ",
"end": 2236,
"score": 0.9991483688,
"start": 2232,
"tag": "NAME",
"value": "Mert"
},
{
"context": " , Prepared { recipient = \"Mert\", amount = 100 }\n , Sent \"",
"end": 2329,
"score": 0.9997055531,
"start": 2325,
"tag": "NAME",
"value": "Mert"
},
{
"context": "nt = 100 }\n , Sent \"Welcome Mert, your first invoice for $42 is ready\"\n ",
"end": 2391,
"score": 0.9997143745,
"start": 2387,
"tag": "NAME",
"value": "Mert"
},
{
"context": " , Prepared { recipient = \"Mert\", amount = 42 }\n ]\n ",
"end": 2484,
"score": 0.9983599186,
"start": 2480,
"tag": "NAME",
"value": "Mert"
}
] | tests/InvoiceMailingTest.elm | edgerunner/elm-behavioral | 5 | module InvoiceMailingTest exposing (suite)
import Behavior exposing (..)
import Expect
import InvoiceMailing exposing (..)
import Set
import Test exposing (..)
suite : Test
suite =
describe "Invoicing scenario"
[ test "invoices get sent" <|
\_ ->
initialize [ sendInvoices ]
|> fire (Prepared { recipient = "Mert", amount = 42 })
|> log
|> Expect.equalLists
[ Sent "Hi Mert, your next invoice for $42 is ready"
, Prepared { recipient = "Mert", amount = 42 }
]
, test "first invoices get sent with a different template" <|
\_ ->
initialize [ sendInvoices, firstInvoicesUseDifferentTemplate Set.empty ]
|> fire (Prepared { recipient = "Mert", amount = 42 })
|> fire (Prepared { recipient = "Mert", amount = 100 })
|> log
|> Expect.equalLists
[ Sent "Hi Mert, your next invoice for $100 is ready"
, Prepared { recipient = "Mert", amount = 100 }
, Sent "Welcome Mert, your first invoice for $42 is ready"
, Prepared { recipient = "Mert", amount = 42 }
]
, test "everybody gets their own first emails" <|
\_ ->
initialize [ sendInvoices, firstInvoicesUseDifferentTemplate Set.empty ]
|> fire (Prepared { recipient = "Mert", amount = 42 })
|> fire (Prepared { recipient = "Mert", amount = 100 })
|> fire (Prepared { recipient = "Betül", amount = 2 })
|> fire (Prepared { recipient = "Mert", amount = 66 })
|> log
|> Expect.equalLists
[ Sent "Hi Mert, your next invoice for $66 is ready"
, Prepared { recipient = "Mert", amount = 66 }
, Sent "Welcome Betül, your first invoice for $2 is ready"
, Prepared { recipient = "Betül", amount = 2 }
, Sent "Hi Mert, your next invoice for $100 is ready"
, Prepared { recipient = "Mert", amount = 100 }
, Sent "Welcome Mert, your first invoice for $42 is ready"
, Prepared { recipient = "Mert", amount = 42 }
]
]
| 22419 | module InvoiceMailingTest exposing (suite)
import Behavior exposing (..)
import Expect
import InvoiceMailing exposing (..)
import Set
import Test exposing (..)
suite : Test
suite =
describe "Invoicing scenario"
[ test "invoices get sent" <|
\_ ->
initialize [ sendInvoices ]
|> fire (Prepared { recipient = "<NAME>", amount = 42 })
|> log
|> Expect.equalLists
[ Sent "Hi <NAME>, your next invoice for $42 is ready"
, Prepared { recipient = "<NAME>", amount = 42 }
]
, test "first invoices get sent with a different template" <|
\_ ->
initialize [ sendInvoices, firstInvoicesUseDifferentTemplate Set.empty ]
|> fire (Prepared { recipient = "<NAME>", amount = 42 })
|> fire (Prepared { recipient = "<NAME>", amount = 100 })
|> log
|> Expect.equalLists
[ Sent "Hi <NAME>, your next invoice for $100 is ready"
, Prepared { recipient = "<NAME>", amount = 100 }
, Sent "Welcome <NAME>, your first invoice for $42 is ready"
, Prepared { recipient = "<NAME>", amount = 42 }
]
, test "everybody gets their own first emails" <|
\_ ->
initialize [ sendInvoices, firstInvoicesUseDifferentTemplate Set.empty ]
|> fire (Prepared { recipient = "<NAME>", amount = 42 })
|> fire (Prepared { recipient = "<NAME>", amount = 100 })
|> fire (Prepared { recipient = "<NAME>", amount = 2 })
|> fire (Prepared { recipient = "<NAME>", amount = 66 })
|> log
|> Expect.equalLists
[ Sent "Hi <NAME>, your next invoice for $66 is ready"
, Prepared { recipient = "<NAME>", amount = 66 }
, Sent "Welcome <NAME>, your first invoice for $2 is ready"
, Prepared { recipient = "<NAME>", amount = 2 }
, Sent "Hi <NAME>, your next invoice for $100 is ready"
, Prepared { recipient = "<NAME>", amount = 100 }
, Sent "Welcome <NAME>, your first invoice for $42 is ready"
, Prepared { recipient = "<NAME>", amount = 42 }
]
]
| true | module InvoiceMailingTest exposing (suite)
import Behavior exposing (..)
import Expect
import InvoiceMailing exposing (..)
import Set
import Test exposing (..)
suite : Test
suite =
describe "Invoicing scenario"
[ test "invoices get sent" <|
\_ ->
initialize [ sendInvoices ]
|> fire (Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 42 })
|> log
|> Expect.equalLists
[ Sent "Hi PI:NAME:<NAME>END_PI, your next invoice for $42 is ready"
, Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 42 }
]
, test "first invoices get sent with a different template" <|
\_ ->
initialize [ sendInvoices, firstInvoicesUseDifferentTemplate Set.empty ]
|> fire (Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 42 })
|> fire (Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 100 })
|> log
|> Expect.equalLists
[ Sent "Hi PI:NAME:<NAME>END_PI, your next invoice for $100 is ready"
, Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 100 }
, Sent "Welcome PI:NAME:<NAME>END_PI, your first invoice for $42 is ready"
, Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 42 }
]
, test "everybody gets their own first emails" <|
\_ ->
initialize [ sendInvoices, firstInvoicesUseDifferentTemplate Set.empty ]
|> fire (Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 42 })
|> fire (Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 100 })
|> fire (Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 2 })
|> fire (Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 66 })
|> log
|> Expect.equalLists
[ Sent "Hi PI:NAME:<NAME>END_PI, your next invoice for $66 is ready"
, Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 66 }
, Sent "Welcome PI:NAME:<NAME>END_PI, your first invoice for $2 is ready"
, Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 2 }
, Sent "Hi PI:NAME:<NAME>END_PI, your next invoice for $100 is ready"
, Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 100 }
, Sent "Welcome PI:NAME:<NAME>END_PI, your first invoice for $42 is ready"
, Prepared { recipient = "PI:NAME:<NAME>END_PI", amount = 42 }
]
]
| elm |
[
{
"context": " model.name\n |> Expect.equal \"Awesome Person\"\n ]\n )\n\nNote: Bad things will happen if",
"end": 2591,
"score": 0.9974361062,
"start": 2577,
"tag": "NAME",
"value": "Awesome Person"
}
] | src/Elmer/Spy/Matchers.elm | jbwatkins/elmer | 44 | module Elmer.Spy.Matchers exposing
( Arg
, Call
, stringArg
, intArg
, floatArg
, boolArg
, typedArg
, functionArg
, anyArg
, argThat
, wasCalled
, wasCalledWith
, calls
, hasArgs
)
{-| Matchers for making expectations about Spies.
# General Expectations
@docs wasCalled, wasCalledWith
# Expectations About Calls
@docs Call, calls, hasArgs
# Argument Matchers
@docs Arg, argThat, anyArg, stringArg, intArg, floatArg, boolArg, typedArg, functionArg
-}
import Expect
import Test.Runner
import Elmer exposing (Matcher)
import Elmer.Spy exposing (Calls)
import Elmer.Spy.Arg as Arg
import Elmer.Spy.Call as Call
import Elmer.Message exposing (..)
import Elmer.Message.Failure as Failure
import Elmer.Value.Native as Native
import Elmer.Errors as Errors exposing (failWith)
{-| Represents an expected function argument.
-}
type alias Arg =
Arg.Arg
{-| Represents a particular call to a spy.
-}
type alias Call =
List Arg
{-| Expect that a spy was called some number of times.
This is shorthand for:
Spy.expect "my-spy" (calls <|
Elmer.hasLength 2
)
-}
wasCalled : Int -> Matcher Calls
wasCalled expectedCallCount =
\spy ->
let
callCount = List.length spy.calls
in
if callCount == expectedCallCount then
Expect.pass
else
failWith <| Errors.wrongNumberOfSpyCalls spy.name expectedCallCount callCount
{-| Matches an argument with the given string.
-}
stringArg : String -> Arg
stringArg =
Arg.StringArg
{-| Matches an argument with the given integer.
-}
intArg : Int -> Arg
intArg =
Arg.IntArg
{-| Matches an argument with the given float value.
-}
floatArg : Float -> Arg
floatArg =
Arg.FloatArg
{-| Matches an argument with the given boolean value.
-}
boolArg : Bool -> Arg
boolArg =
Arg.BoolArg
{-| Matches an argument with the given typed value.
Note: You may not match what you want if your typed value contains a function reference.
-}
typedArg : a -> Arg
typedArg item =
Native.cast item
|> Arg.TypedArg
{-| Matches an argument that is a function.
-}
functionArg : Arg
functionArg =
Arg.FunctionArg
{-| Matches any argument.
-}
anyArg : Arg
anyArg =
Arg.AnyArg
{-| Matches an argument whose value satisfies the given matcher.
Suppose you want to expect that the second argument to a function is a record
with a specific value for its name attribute. You could do something like this:
Spy.expect "my-spy" (
wasCalledWith
[ anyArg
, argThat <|
\model ->
model.name
|> Expect.equal "Awesome Person"
]
)
Note: Bad things will happen if you provide a matcher to `argThat` for a type
that is different from that of the argument you are trying to match.
-}
argThat : Matcher a -> Arg
argThat matcher =
Native.cast matcher
|> Arg.ArgThat
{-| Make expectations about the calls recorded by this spy.
Here's how you would expect that exactly 2 of the calls had a certain argument.
Spy.expect "my-spy" (
calls <| Elmer.exactly 2 <|
hasArgs
[ stringArg "some argument"
]
)
-}
calls : Matcher (List Call) -> Matcher Calls
calls callMatcher =
\spy ->
case Test.Runner.getFailureReason <| callMatcher spy.calls of
Just failure ->
Expect.fail <|
format
[ note <| "Expectation for " ++ spy.name ++ " failed."
, note <| Failure.format [ failure ]
]
Nothing ->
Expect.pass
{-| Expect that a call has some arguments.
Use `hasArgs` in conjunction with `calls` to make an expectation about the args
of a specific call.
Spy.expect "my-spy" (
calls <| Elmer.atIndex 2 <| hasArgs
[ stringArg "Some String"
, typedArg someTypedValue
]
)
-}
hasArgs : List Arg -> Matcher Call
hasArgs args =
\call ->
evaluateCalls Nothing args [ call ]
{-| Expect that a spy was called at least once with the given arguments.
Spy.expect "my-spy" (
wasCalledWith
[ stringArg "Some String"
, typedArg someTypedValue
]
)
This is shorthand for:
Spy.expect "my-spy" (
calls <| Elmer.some <| hasArgs
[ stringArg "Some String"
, typedArg someTypedValue
]
)
-}
wasCalledWith : List Arg -> Matcher Calls
wasCalledWith args =
\spy ->
evaluateCalls (Just spy.name) args spy.calls
evaluateCalls : Maybe String -> List Arg -> Matcher (List (List Arg))
evaluateCalls maybeSpyName args =
\callsArgList ->
if List.isEmpty callsArgList then
noCallsFailure maybeSpyName args
else
let
failingCalls =
callsArgList
|> List.filter (\callArgs ->
not <| Call.matches args callArgs
)
in
if List.length failingCalls < List.length callsArgList then
Expect.pass
else
Expect.fail <|
format <|
List.append
[ fact (calledWithMessage maybeSpyName) <| Call.asString args
, fact "but it was called with" <| String.join "\n\n" (List.map Call.asString callsArgList)
]
(argThatFailureMessages failingCalls args)
noCallsFailure : Maybe String -> List Arg -> Expect.Expectation
noCallsFailure maybeSpyName args =
Expect.fail <|
format
[ fact (calledWithMessage maybeSpyName) <| Call.asString args
, note "but it was not called"
]
argThatFailureMessages : List (List Arg) -> List Arg -> List Message
argThatFailureMessages callsArgList args =
let
failureMessages =
callsArgList
|> List.map (Call.argThatFailures args)
|> List.concat
|> List.map note
in
if List.isEmpty failureMessages then
[]
else
note "An argThat matcher failed:" ::
failureMessages
calledWithMessage : Maybe String -> String
calledWithMessage maybeSpyName =
case maybeSpyName of
Just spyName ->
"Expected spy " ++ spyName ++ " to have been called with"
Nothing ->
"Expected spy to have been called with"
| 51713 | module Elmer.Spy.Matchers exposing
( Arg
, Call
, stringArg
, intArg
, floatArg
, boolArg
, typedArg
, functionArg
, anyArg
, argThat
, wasCalled
, wasCalledWith
, calls
, hasArgs
)
{-| Matchers for making expectations about Spies.
# General Expectations
@docs wasCalled, wasCalledWith
# Expectations About Calls
@docs Call, calls, hasArgs
# Argument Matchers
@docs Arg, argThat, anyArg, stringArg, intArg, floatArg, boolArg, typedArg, functionArg
-}
import Expect
import Test.Runner
import Elmer exposing (Matcher)
import Elmer.Spy exposing (Calls)
import Elmer.Spy.Arg as Arg
import Elmer.Spy.Call as Call
import Elmer.Message exposing (..)
import Elmer.Message.Failure as Failure
import Elmer.Value.Native as Native
import Elmer.Errors as Errors exposing (failWith)
{-| Represents an expected function argument.
-}
type alias Arg =
Arg.Arg
{-| Represents a particular call to a spy.
-}
type alias Call =
List Arg
{-| Expect that a spy was called some number of times.
This is shorthand for:
Spy.expect "my-spy" (calls <|
Elmer.hasLength 2
)
-}
wasCalled : Int -> Matcher Calls
wasCalled expectedCallCount =
\spy ->
let
callCount = List.length spy.calls
in
if callCount == expectedCallCount then
Expect.pass
else
failWith <| Errors.wrongNumberOfSpyCalls spy.name expectedCallCount callCount
{-| Matches an argument with the given string.
-}
stringArg : String -> Arg
stringArg =
Arg.StringArg
{-| Matches an argument with the given integer.
-}
intArg : Int -> Arg
intArg =
Arg.IntArg
{-| Matches an argument with the given float value.
-}
floatArg : Float -> Arg
floatArg =
Arg.FloatArg
{-| Matches an argument with the given boolean value.
-}
boolArg : Bool -> Arg
boolArg =
Arg.BoolArg
{-| Matches an argument with the given typed value.
Note: You may not match what you want if your typed value contains a function reference.
-}
typedArg : a -> Arg
typedArg item =
Native.cast item
|> Arg.TypedArg
{-| Matches an argument that is a function.
-}
functionArg : Arg
functionArg =
Arg.FunctionArg
{-| Matches any argument.
-}
anyArg : Arg
anyArg =
Arg.AnyArg
{-| Matches an argument whose value satisfies the given matcher.
Suppose you want to expect that the second argument to a function is a record
with a specific value for its name attribute. You could do something like this:
Spy.expect "my-spy" (
wasCalledWith
[ anyArg
, argThat <|
\model ->
model.name
|> Expect.equal "<NAME>"
]
)
Note: Bad things will happen if you provide a matcher to `argThat` for a type
that is different from that of the argument you are trying to match.
-}
argThat : Matcher a -> Arg
argThat matcher =
Native.cast matcher
|> Arg.ArgThat
{-| Make expectations about the calls recorded by this spy.
Here's how you would expect that exactly 2 of the calls had a certain argument.
Spy.expect "my-spy" (
calls <| Elmer.exactly 2 <|
hasArgs
[ stringArg "some argument"
]
)
-}
calls : Matcher (List Call) -> Matcher Calls
calls callMatcher =
\spy ->
case Test.Runner.getFailureReason <| callMatcher spy.calls of
Just failure ->
Expect.fail <|
format
[ note <| "Expectation for " ++ spy.name ++ " failed."
, note <| Failure.format [ failure ]
]
Nothing ->
Expect.pass
{-| Expect that a call has some arguments.
Use `hasArgs` in conjunction with `calls` to make an expectation about the args
of a specific call.
Spy.expect "my-spy" (
calls <| Elmer.atIndex 2 <| hasArgs
[ stringArg "Some String"
, typedArg someTypedValue
]
)
-}
hasArgs : List Arg -> Matcher Call
hasArgs args =
\call ->
evaluateCalls Nothing args [ call ]
{-| Expect that a spy was called at least once with the given arguments.
Spy.expect "my-spy" (
wasCalledWith
[ stringArg "Some String"
, typedArg someTypedValue
]
)
This is shorthand for:
Spy.expect "my-spy" (
calls <| Elmer.some <| hasArgs
[ stringArg "Some String"
, typedArg someTypedValue
]
)
-}
wasCalledWith : List Arg -> Matcher Calls
wasCalledWith args =
\spy ->
evaluateCalls (Just spy.name) args spy.calls
evaluateCalls : Maybe String -> List Arg -> Matcher (List (List Arg))
evaluateCalls maybeSpyName args =
\callsArgList ->
if List.isEmpty callsArgList then
noCallsFailure maybeSpyName args
else
let
failingCalls =
callsArgList
|> List.filter (\callArgs ->
not <| Call.matches args callArgs
)
in
if List.length failingCalls < List.length callsArgList then
Expect.pass
else
Expect.fail <|
format <|
List.append
[ fact (calledWithMessage maybeSpyName) <| Call.asString args
, fact "but it was called with" <| String.join "\n\n" (List.map Call.asString callsArgList)
]
(argThatFailureMessages failingCalls args)
noCallsFailure : Maybe String -> List Arg -> Expect.Expectation
noCallsFailure maybeSpyName args =
Expect.fail <|
format
[ fact (calledWithMessage maybeSpyName) <| Call.asString args
, note "but it was not called"
]
argThatFailureMessages : List (List Arg) -> List Arg -> List Message
argThatFailureMessages callsArgList args =
let
failureMessages =
callsArgList
|> List.map (Call.argThatFailures args)
|> List.concat
|> List.map note
in
if List.isEmpty failureMessages then
[]
else
note "An argThat matcher failed:" ::
failureMessages
calledWithMessage : Maybe String -> String
calledWithMessage maybeSpyName =
case maybeSpyName of
Just spyName ->
"Expected spy " ++ spyName ++ " to have been called with"
Nothing ->
"Expected spy to have been called with"
| true | module Elmer.Spy.Matchers exposing
( Arg
, Call
, stringArg
, intArg
, floatArg
, boolArg
, typedArg
, functionArg
, anyArg
, argThat
, wasCalled
, wasCalledWith
, calls
, hasArgs
)
{-| Matchers for making expectations about Spies.
# General Expectations
@docs wasCalled, wasCalledWith
# Expectations About Calls
@docs Call, calls, hasArgs
# Argument Matchers
@docs Arg, argThat, anyArg, stringArg, intArg, floatArg, boolArg, typedArg, functionArg
-}
import Expect
import Test.Runner
import Elmer exposing (Matcher)
import Elmer.Spy exposing (Calls)
import Elmer.Spy.Arg as Arg
import Elmer.Spy.Call as Call
import Elmer.Message exposing (..)
import Elmer.Message.Failure as Failure
import Elmer.Value.Native as Native
import Elmer.Errors as Errors exposing (failWith)
{-| Represents an expected function argument.
-}
type alias Arg =
Arg.Arg
{-| Represents a particular call to a spy.
-}
type alias Call =
List Arg
{-| Expect that a spy was called some number of times.
This is shorthand for:
Spy.expect "my-spy" (calls <|
Elmer.hasLength 2
)
-}
wasCalled : Int -> Matcher Calls
wasCalled expectedCallCount =
\spy ->
let
callCount = List.length spy.calls
in
if callCount == expectedCallCount then
Expect.pass
else
failWith <| Errors.wrongNumberOfSpyCalls spy.name expectedCallCount callCount
{-| Matches an argument with the given string.
-}
stringArg : String -> Arg
stringArg =
Arg.StringArg
{-| Matches an argument with the given integer.
-}
intArg : Int -> Arg
intArg =
Arg.IntArg
{-| Matches an argument with the given float value.
-}
floatArg : Float -> Arg
floatArg =
Arg.FloatArg
{-| Matches an argument with the given boolean value.
-}
boolArg : Bool -> Arg
boolArg =
Arg.BoolArg
{-| Matches an argument with the given typed value.
Note: You may not match what you want if your typed value contains a function reference.
-}
typedArg : a -> Arg
typedArg item =
Native.cast item
|> Arg.TypedArg
{-| Matches an argument that is a function.
-}
functionArg : Arg
functionArg =
Arg.FunctionArg
{-| Matches any argument.
-}
anyArg : Arg
anyArg =
Arg.AnyArg
{-| Matches an argument whose value satisfies the given matcher.
Suppose you want to expect that the second argument to a function is a record
with a specific value for its name attribute. You could do something like this:
Spy.expect "my-spy" (
wasCalledWith
[ anyArg
, argThat <|
\model ->
model.name
|> Expect.equal "PI:NAME:<NAME>END_PI"
]
)
Note: Bad things will happen if you provide a matcher to `argThat` for a type
that is different from that of the argument you are trying to match.
-}
argThat : Matcher a -> Arg
argThat matcher =
Native.cast matcher
|> Arg.ArgThat
{-| Make expectations about the calls recorded by this spy.
Here's how you would expect that exactly 2 of the calls had a certain argument.
Spy.expect "my-spy" (
calls <| Elmer.exactly 2 <|
hasArgs
[ stringArg "some argument"
]
)
-}
calls : Matcher (List Call) -> Matcher Calls
calls callMatcher =
\spy ->
case Test.Runner.getFailureReason <| callMatcher spy.calls of
Just failure ->
Expect.fail <|
format
[ note <| "Expectation for " ++ spy.name ++ " failed."
, note <| Failure.format [ failure ]
]
Nothing ->
Expect.pass
{-| Expect that a call has some arguments.
Use `hasArgs` in conjunction with `calls` to make an expectation about the args
of a specific call.
Spy.expect "my-spy" (
calls <| Elmer.atIndex 2 <| hasArgs
[ stringArg "Some String"
, typedArg someTypedValue
]
)
-}
hasArgs : List Arg -> Matcher Call
hasArgs args =
\call ->
evaluateCalls Nothing args [ call ]
{-| Expect that a spy was called at least once with the given arguments.
Spy.expect "my-spy" (
wasCalledWith
[ stringArg "Some String"
, typedArg someTypedValue
]
)
This is shorthand for:
Spy.expect "my-spy" (
calls <| Elmer.some <| hasArgs
[ stringArg "Some String"
, typedArg someTypedValue
]
)
-}
wasCalledWith : List Arg -> Matcher Calls
wasCalledWith args =
\spy ->
evaluateCalls (Just spy.name) args spy.calls
evaluateCalls : Maybe String -> List Arg -> Matcher (List (List Arg))
evaluateCalls maybeSpyName args =
\callsArgList ->
if List.isEmpty callsArgList then
noCallsFailure maybeSpyName args
else
let
failingCalls =
callsArgList
|> List.filter (\callArgs ->
not <| Call.matches args callArgs
)
in
if List.length failingCalls < List.length callsArgList then
Expect.pass
else
Expect.fail <|
format <|
List.append
[ fact (calledWithMessage maybeSpyName) <| Call.asString args
, fact "but it was called with" <| String.join "\n\n" (List.map Call.asString callsArgList)
]
(argThatFailureMessages failingCalls args)
noCallsFailure : Maybe String -> List Arg -> Expect.Expectation
noCallsFailure maybeSpyName args =
Expect.fail <|
format
[ fact (calledWithMessage maybeSpyName) <| Call.asString args
, note "but it was not called"
]
argThatFailureMessages : List (List Arg) -> List Arg -> List Message
argThatFailureMessages callsArgList args =
let
failureMessages =
callsArgList
|> List.map (Call.argThatFailures args)
|> List.concat
|> List.map note
in
if List.isEmpty failureMessages then
[]
else
note "An argThat matcher failed:" ::
failureMessages
calledWithMessage : Maybe String -> String
calledWithMessage maybeSpyName =
case maybeSpyName of
Just spyName ->
"Expected spy " ++ spyName ++ " to have been called with"
Nothing ->
"Expected spy to have been called with"
| elm |
[
{
"context": "----------\n elm review\n\ncd ~/.github; git clone git@github.com:jfmengels/elm-review-unused.git\nelm-review --conf",
"end": 563,
"score": 0.9981765747,
"start": 549,
"tag": "EMAIL",
"value": "git@github.com"
},
{
"context": "lm review\n\ncd ~/.github; git clone git@github.com:jfmengels/elm-review-unused.git\nelm-review --config ~/.gith",
"end": 573,
"score": 0.9994829893,
"start": 564,
"tag": "USERNAME",
"value": "jfmengels"
},
{
"context": "-- or --\n\nelm-review init\ncd review && elm install jfmengels/elm-review-unused\ncp ~/.github/elm-review-unused/",
"end": 714,
"score": 0.7296000719,
"start": 705,
"tag": "USERNAME",
"value": "jfmengels"
}
] | chunks/chunks.elm | jpalardy/dotfiles | 32 | module Whatever exposing (..)
{--
-------------------------------------------------
divider
-------------------------------------------------
--}
add : Int -> Int -> Int
add x y =
x + y
{-| subtract
-}
sub : Int -> Int -> Int
sub x y =
x - y
{--
-------------------------------------------------
HTTP placeholder
-------------------------------------------------
--}
Process.sleep 2000
|> Task.perform (\_ -> Message (Ok value))
{--
-------------------------------------------------
elm review
cd ~/.github; git clone git@github.com:jfmengels/elm-review-unused.git
elm-review --config ~/.github/elm-review-unused/example/
-- or --
elm-review init
cd review && elm install jfmengels/elm-review-unused
cp ~/.github/elm-review-unused/example/src/ReviewConfig.elm src/ReviewConfig.elm
-------------------------------------------------
--}
-- -------------------------------------------------
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
type Msg
= NoOp
type alias Model =
{ value : String }
init : () -> ( Model, Cmd Msg )
init _ =
( { value = "nothing yet" }, Cmd.none )
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
NoOp ->
( model, Cmd.none )
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
view : Model -> Html Msg
view model =
text model.value
main : Program () Model Msg
main =
Browser.element
{ init = init
, subscriptions = subscriptions
, update = update
, view = view
}
{--
-------------------------------------------------
ports
-------------------------------------------------
--}
-- => in
port portName : (Decode.Value -> msg) -> Sub msg
-- subscriptions _ =
-- let
-- decodeTo : (_ -> Msg) -> Decode.Value -> Msg
-- decodeTo msg value =
-- case Decode.decodeValue _ value of
-- Ok _ ->
-- msg _
--
-- Err error ->
-- _
-- in
-- Sub.batch
-- [ ...
-- , portName (decodeTo MessageName)
-- , ...
-- ]
| 5573 | module Whatever exposing (..)
{--
-------------------------------------------------
divider
-------------------------------------------------
--}
add : Int -> Int -> Int
add x y =
x + y
{-| subtract
-}
sub : Int -> Int -> Int
sub x y =
x - y
{--
-------------------------------------------------
HTTP placeholder
-------------------------------------------------
--}
Process.sleep 2000
|> Task.perform (\_ -> Message (Ok value))
{--
-------------------------------------------------
elm review
cd ~/.github; git clone <EMAIL>:jfmengels/elm-review-unused.git
elm-review --config ~/.github/elm-review-unused/example/
-- or --
elm-review init
cd review && elm install jfmengels/elm-review-unused
cp ~/.github/elm-review-unused/example/src/ReviewConfig.elm src/ReviewConfig.elm
-------------------------------------------------
--}
-- -------------------------------------------------
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
type Msg
= NoOp
type alias Model =
{ value : String }
init : () -> ( Model, Cmd Msg )
init _ =
( { value = "nothing yet" }, Cmd.none )
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
NoOp ->
( model, Cmd.none )
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
view : Model -> Html Msg
view model =
text model.value
main : Program () Model Msg
main =
Browser.element
{ init = init
, subscriptions = subscriptions
, update = update
, view = view
}
{--
-------------------------------------------------
ports
-------------------------------------------------
--}
-- => in
port portName : (Decode.Value -> msg) -> Sub msg
-- subscriptions _ =
-- let
-- decodeTo : (_ -> Msg) -> Decode.Value -> Msg
-- decodeTo msg value =
-- case Decode.decodeValue _ value of
-- Ok _ ->
-- msg _
--
-- Err error ->
-- _
-- in
-- Sub.batch
-- [ ...
-- , portName (decodeTo MessageName)
-- , ...
-- ]
| true | module Whatever exposing (..)
{--
-------------------------------------------------
divider
-------------------------------------------------
--}
add : Int -> Int -> Int
add x y =
x + y
{-| subtract
-}
sub : Int -> Int -> Int
sub x y =
x - y
{--
-------------------------------------------------
HTTP placeholder
-------------------------------------------------
--}
Process.sleep 2000
|> Task.perform (\_ -> Message (Ok value))
{--
-------------------------------------------------
elm review
cd ~/.github; git clone PI:EMAIL:<EMAIL>END_PI:jfmengels/elm-review-unused.git
elm-review --config ~/.github/elm-review-unused/example/
-- or --
elm-review init
cd review && elm install jfmengels/elm-review-unused
cp ~/.github/elm-review-unused/example/src/ReviewConfig.elm src/ReviewConfig.elm
-------------------------------------------------
--}
-- -------------------------------------------------
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
type Msg
= NoOp
type alias Model =
{ value : String }
init : () -> ( Model, Cmd Msg )
init _ =
( { value = "nothing yet" }, Cmd.none )
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
NoOp ->
( model, Cmd.none )
subscriptions : Model -> Sub Msg
subscriptions _ =
Sub.none
view : Model -> Html Msg
view model =
text model.value
main : Program () Model Msg
main =
Browser.element
{ init = init
, subscriptions = subscriptions
, update = update
, view = view
}
{--
-------------------------------------------------
ports
-------------------------------------------------
--}
-- => in
port portName : (Decode.Value -> msg) -> Sub msg
-- subscriptions _ =
-- let
-- decodeTo : (_ -> Msg) -> Decode.Value -> Msg
-- decodeTo msg value =
-- case Decode.decodeValue _ value of
-- Ok _ ->
-- msg _
--
-- Err error ->
-- _
-- in
-- Sub.batch
-- [ ...
-- , portName (decodeTo MessageName)
-- , ...
-- ]
| elm |
[
{
"context": ": Tutor.Tutor\n tutor =\n { id = \"abcd1234\"\n , admin = Tutor.LvlTutor\n ",
"end": 342,
"score": 0.444170475,
"start": 334,
"tag": "KEY",
"value": "abcd1234"
},
{
"context": " , admin = Tutor.LvlTutor\n , name = \"Test Name\"\n , dateOfBirth = Date.fromWeekDate 20",
"end": 412,
"score": 0.9881808162,
"start": 403,
"tag": "NAME",
"value": "Test Name"
},
{
"context": "mWeekDate 2020 10 Time.Tue\n , email = \"test@email.com\"\n , gender = Utils.Male\n , ",
"end": 583,
"score": 0.9999268651,
"start": 569,
"tag": "EMAIL",
"value": "test@email.com"
},
{
"context": " , status = Tutor.Active\n , password = Nothing\n }\n in\n test \"Decode and encode ",
"end": 724,
"score": 0.9983021617,
"start": 717,
"tag": "PASSWORD",
"value": "Nothing"
}
] | frontend/tests/TestTutor.elm | owenl131/elm-portal | 0 | module TestTutor exposing (..)
import Date
import Expect
import Fuzz exposing (Fuzzer, int, list, string)
import Http exposing (Expect)
import Json.Decode
import Json.Encode
import Test exposing (..)
import Time
import Tutor
import Utils
suite : Test
suite =
let
tutor : Tutor.Tutor
tutor =
{ id = "abcd1234"
, admin = Tutor.LvlTutor
, name = "Test Name"
, dateOfBirth = Date.fromWeekDate 2000 1 Time.Mon
, dateOfRegistration = Date.fromWeekDate 2020 10 Time.Tue
, email = "test@email.com"
, gender = Utils.Male
, school = "Test school"
, status = Tutor.Active
, password = Nothing
}
in
test "Decode and encode tutor json"
(\_ ->
tutor
|> Tutor.tutorEncoder
|> Json.Encode.encode 2
|> Json.Decode.decodeString Tutor.tutorDecoder
|> Expect.all
[ Expect.ok
, Result.toMaybe >> Maybe.withDefault Tutor.emptyTutor >> Expect.equal tutor
]
)
| 43891 | module TestTutor exposing (..)
import Date
import Expect
import Fuzz exposing (Fuzzer, int, list, string)
import Http exposing (Expect)
import Json.Decode
import Json.Encode
import Test exposing (..)
import Time
import Tutor
import Utils
suite : Test
suite =
let
tutor : Tutor.Tutor
tutor =
{ id = "<KEY>"
, admin = Tutor.LvlTutor
, name = "<NAME>"
, dateOfBirth = Date.fromWeekDate 2000 1 Time.Mon
, dateOfRegistration = Date.fromWeekDate 2020 10 Time.Tue
, email = "<EMAIL>"
, gender = Utils.Male
, school = "Test school"
, status = Tutor.Active
, password = <PASSWORD>
}
in
test "Decode and encode tutor json"
(\_ ->
tutor
|> Tutor.tutorEncoder
|> Json.Encode.encode 2
|> Json.Decode.decodeString Tutor.tutorDecoder
|> Expect.all
[ Expect.ok
, Result.toMaybe >> Maybe.withDefault Tutor.emptyTutor >> Expect.equal tutor
]
)
| true | module TestTutor exposing (..)
import Date
import Expect
import Fuzz exposing (Fuzzer, int, list, string)
import Http exposing (Expect)
import Json.Decode
import Json.Encode
import Test exposing (..)
import Time
import Tutor
import Utils
suite : Test
suite =
let
tutor : Tutor.Tutor
tutor =
{ id = "PI:KEY:<KEY>END_PI"
, admin = Tutor.LvlTutor
, name = "PI:NAME:<NAME>END_PI"
, dateOfBirth = Date.fromWeekDate 2000 1 Time.Mon
, dateOfRegistration = Date.fromWeekDate 2020 10 Time.Tue
, email = "PI:EMAIL:<EMAIL>END_PI"
, gender = Utils.Male
, school = "Test school"
, status = Tutor.Active
, password = PI:PASSWORD:<PASSWORD>END_PI
}
in
test "Decode and encode tutor json"
(\_ ->
tutor
|> Tutor.tutorEncoder
|> Json.Encode.encode 2
|> Json.Decode.decodeString Tutor.tutorDecoder
|> Expect.all
[ Expect.ok
, Result.toMaybe >> Maybe.withDefault Tutor.emptyTutor >> Expect.equal tutor
]
)
| elm |
[
{
"context": "-- Copyright (c) 2017 Daan Wendelen\n-- All rights reserved.\n-- \n-- Redistribution and",
"end": 35,
"score": 0.9998174906,
"start": 22,
"tag": "NAME",
"value": "Daan Wendelen"
}
] | day10/day10a.elm | dwendelen/adventofcode_2017 | 0 | -- Copyright (c) 2017 Daan Wendelen
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
--
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- * Neither the name of the copyright holder nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Html exposing (..)
import Dict exposing (..)
import Array exposing (..)
import Debug exposing (..)
main = text <| toString <| solve input
size = 256
-- solve: List Int -> String
solve input =
let
initial = List.range 0 (size - 1)
(list, index) = execute input 0 0 initial
indexFirstElement = (size - index) % size
indexSecondElement = (size - index + 1) % size
array = Array.fromList list
e1 = Array.get indexFirstElement array
e2 = Array.get indexSecondElement array
in
Maybe.map2 (*) e1 e2
execute commands skipSize index list =
case commands of
[] -> (list, index)
cmd::tail ->
let
toSwap = List.take cmd list
rest = List.drop cmd list
newList = List.append (List.reverse toSwap) rest
offset = (cmd + skipSize) % size
offsetList1 = List.drop offset newList
offsetList2 = List.take offset newList
offsetList = List.append offsetList1 offsetList2
newIndex = (index + offset) % size
in
execute tail (skipSize + 1) newIndex offsetList
input2 = [3,4,1,5]
input = [212,254,178,237,2,0,1,54,167,92,117,125,255,61,159,164]
zip: List a -> List b -> List (a, b)
zip list1 list2 =
zip2 list1 list2 []
zip2: List a -> List b -> List(a, b) -> List(a, b)
zip2 list1 list2 acc =
case list1 of
[] -> acc
head1::tail1 ->
case list2 of
[] -> acc
head2::tail2 ->
zip2 tail1 tail2 (List.append acc [(head1, head2)])
toIntOrZero: String -> Int
toIntOrZero char =
case (String.toInt char) of
Ok a ->
a
Err _ ->
0
outerProduct: List a -> List (a, a)
outerProduct list =
List.concatMap (\e ->
List.map (\i -> (e, i)) list
) list
histogram: List comparable -> Dict comparable Int
histogram list =
List.foldl histo_inc Dict.empty list
histo_inc: comparable -> Dict comparable Int -> Dict comparable Int
histo_inc dir dict =
if Dict.member dir dict then
Dict.update dir (Maybe.map ((+) 1)) dict
else
Dict.insert dir 1 dict
| 42595 | -- Copyright (c) 2017 <NAME>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
--
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- * Neither the name of the copyright holder nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Html exposing (..)
import Dict exposing (..)
import Array exposing (..)
import Debug exposing (..)
main = text <| toString <| solve input
size = 256
-- solve: List Int -> String
solve input =
let
initial = List.range 0 (size - 1)
(list, index) = execute input 0 0 initial
indexFirstElement = (size - index) % size
indexSecondElement = (size - index + 1) % size
array = Array.fromList list
e1 = Array.get indexFirstElement array
e2 = Array.get indexSecondElement array
in
Maybe.map2 (*) e1 e2
execute commands skipSize index list =
case commands of
[] -> (list, index)
cmd::tail ->
let
toSwap = List.take cmd list
rest = List.drop cmd list
newList = List.append (List.reverse toSwap) rest
offset = (cmd + skipSize) % size
offsetList1 = List.drop offset newList
offsetList2 = List.take offset newList
offsetList = List.append offsetList1 offsetList2
newIndex = (index + offset) % size
in
execute tail (skipSize + 1) newIndex offsetList
input2 = [3,4,1,5]
input = [212,254,178,237,2,0,1,54,167,92,117,125,255,61,159,164]
zip: List a -> List b -> List (a, b)
zip list1 list2 =
zip2 list1 list2 []
zip2: List a -> List b -> List(a, b) -> List(a, b)
zip2 list1 list2 acc =
case list1 of
[] -> acc
head1::tail1 ->
case list2 of
[] -> acc
head2::tail2 ->
zip2 tail1 tail2 (List.append acc [(head1, head2)])
toIntOrZero: String -> Int
toIntOrZero char =
case (String.toInt char) of
Ok a ->
a
Err _ ->
0
outerProduct: List a -> List (a, a)
outerProduct list =
List.concatMap (\e ->
List.map (\i -> (e, i)) list
) list
histogram: List comparable -> Dict comparable Int
histogram list =
List.foldl histo_inc Dict.empty list
histo_inc: comparable -> Dict comparable Int -> Dict comparable Int
histo_inc dir dict =
if Dict.member dir dict then
Dict.update dir (Maybe.map ((+) 1)) dict
else
Dict.insert dir 1 dict
| true | -- Copyright (c) 2017 PI:NAME:<NAME>END_PI
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
--
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- * Neither the name of the copyright holder nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Html exposing (..)
import Dict exposing (..)
import Array exposing (..)
import Debug exposing (..)
main = text <| toString <| solve input
size = 256
-- solve: List Int -> String
solve input =
let
initial = List.range 0 (size - 1)
(list, index) = execute input 0 0 initial
indexFirstElement = (size - index) % size
indexSecondElement = (size - index + 1) % size
array = Array.fromList list
e1 = Array.get indexFirstElement array
e2 = Array.get indexSecondElement array
in
Maybe.map2 (*) e1 e2
execute commands skipSize index list =
case commands of
[] -> (list, index)
cmd::tail ->
let
toSwap = List.take cmd list
rest = List.drop cmd list
newList = List.append (List.reverse toSwap) rest
offset = (cmd + skipSize) % size
offsetList1 = List.drop offset newList
offsetList2 = List.take offset newList
offsetList = List.append offsetList1 offsetList2
newIndex = (index + offset) % size
in
execute tail (skipSize + 1) newIndex offsetList
input2 = [3,4,1,5]
input = [212,254,178,237,2,0,1,54,167,92,117,125,255,61,159,164]
zip: List a -> List b -> List (a, b)
zip list1 list2 =
zip2 list1 list2 []
zip2: List a -> List b -> List(a, b) -> List(a, b)
zip2 list1 list2 acc =
case list1 of
[] -> acc
head1::tail1 ->
case list2 of
[] -> acc
head2::tail2 ->
zip2 tail1 tail2 (List.append acc [(head1, head2)])
toIntOrZero: String -> Int
toIntOrZero char =
case (String.toInt char) of
Ok a ->
a
Err _ ->
0
outerProduct: List a -> List (a, a)
outerProduct list =
List.concatMap (\e ->
List.map (\i -> (e, i)) list
) list
histogram: List comparable -> Dict comparable Int
histogram list =
List.foldl histo_inc Dict.empty list
histo_inc: comparable -> Dict comparable Int -> Dict comparable Int
histo_inc dir dict =
if Dict.member dir dict then
Dict.update dir (Maybe.map ((+) 1)) dict
else
Dict.insert dir 1 dict
| elm |
[
{
"context": "pty\n | mobsters = [ createMobster \"Sulu\", createMobster \"Kirk\", createMobster \"Spock\", cr",
"end": 1537,
"score": 0.9941132069,
"start": 1533,
"tag": "NAME",
"value": "Sulu"
},
{
"context": "mobsters = [ createMobster \"Sulu\", createMobster \"Kirk\", createMobster \"Spock\", createMobster \"McCoy\" ]\n",
"end": 1559,
"score": 0.9985202551,
"start": 1555,
"tag": "NAME",
"value": "Kirk"
},
{
"context": "ster \"Sulu\", createMobster \"Kirk\", createMobster \"Spock\", createMobster \"McCoy\" ]\n }\n ",
"end": 1582,
"score": 0.9976620674,
"start": 1577,
"tag": "NAME",
"value": "Spock"
},
{
"context": "ter \"Kirk\", createMobster \"Spock\", createMobster \"McCoy\" ]\n }\n (CompleteGoal 0 Driv",
"end": 1605,
"score": 0.9326598644,
"start": 1600,
"tag": "NAME",
"value": "McCoy"
},
{
"context": "mobsters =\n [ Mobster.Mobster \"Sulu\" fakeExperience2\n , createMobs",
"end": 1753,
"score": 0.9835127592,
"start": 1749,
"tag": "NAME",
"value": "Sulu"
},
{
"context": "eExperience2\n , createMobster \"Kirk\"\n , createMobster \"Spock\"\n ",
"end": 1812,
"score": 0.9987291098,
"start": 1808,
"tag": "NAME",
"value": "Kirk"
},
{
"context": "bster \"Kirk\"\n , createMobster \"Spock\"\n , createMobster \"McCoy\"\n ",
"end": 1856,
"score": 0.9976406693,
"start": 1851,
"tag": "NAME",
"value": "Spock"
},
{
"context": "ster \"Spock\"\n , createMobster \"McCoy\"\n ]\n }\n ]\n\n\n",
"end": 1900,
"score": 0.9379024506,
"start": 1895,
"tag": "NAME",
"value": "McCoy"
},
{
"context": "r is removed\"\n { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters }\n ",
"end": 2116,
"score": 0.998355031,
"start": 2112,
"tag": "NAME",
"value": "Kirk"
},
{
"context": "oved\"\n { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters }\n (Bench 1)",
"end": 2125,
"score": 0.9817581177,
"start": 2120,
"tag": "NAME",
"value": "Spock"
},
{
"context": " { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters }\n (Bench 1)\n ",
"end": 2134,
"score": 0.7914431691,
"start": 2129,
"tag": "NAME",
"value": "McCoy"
},
{
"context": " (Bench 1)\n { empty | mobsters = [ \"Kirk\", \"McCoy\" ] |> toMobsters, inactiveMobsters = [ \"",
"end": 2216,
"score": 0.9968931079,
"start": 2212,
"tag": "NAME",
"value": "Kirk"
},
{
"context": "ch 1)\n { empty | mobsters = [ \"Kirk\", \"McCoy\" ] |> toMobsters, inactiveMobsters = [ \"Spock\" ] ",
"end": 2225,
"score": 0.931067884,
"start": 2220,
"tag": "NAME",
"value": "McCoy"
},
{
"context": "\", \"McCoy\" ] |> toMobsters, inactiveMobsters = [ \"Spock\" ] |> toMobsters, nextDriver = 0 }\n , test",
"end": 2271,
"score": 0.9823069572,
"start": 2266,
"tag": "NAME",
"value": "Spock"
},
{
"context": " end of list\"\n { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters, nextDriver = ",
"end": 2457,
"score": 0.9980355501,
"start": 2453,
"tag": "NAME",
"value": "Kirk"
},
{
"context": "list\"\n { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters, nextDriver = 2 }\n ",
"end": 2466,
"score": 0.9853253961,
"start": 2461,
"tag": "NAME",
"value": "Spock"
},
{
"context": " { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters, nextDriver = 2 }\n (B",
"end": 2475,
"score": 0.9281176925,
"start": 2470,
"tag": "NAME",
"value": "McCoy"
},
{
"context": " (Bench 2)\n { empty | mobsters = [ \"Kirk\", \"Spock\" ] |> toMobsters, inactiveMobsters = [ \"",
"end": 2573,
"score": 0.9972889423,
"start": 2569,
"tag": "NAME",
"value": "Kirk"
},
{
"context": "ch 2)\n { empty | mobsters = [ \"Kirk\", \"Spock\" ] |> toMobsters, inactiveMobsters = [ \"McCoy\" ] ",
"end": 2582,
"score": 0.9751061797,
"start": 2577,
"tag": "NAME",
"value": "Spock"
},
{
"context": "\", \"Spock\" ] |> toMobsters, inactiveMobsters = [ \"McCoy\" ] |> toMobsters, nextDriver = 0 }\n , t",
"end": 2625,
"score": 0.5218364596,
"start": 2623,
"tag": "NAME",
"value": "Mc"
},
{
"context": "Spock\" ] |> toMobsters, inactiveMobsters = [ \"McCoy\" ] |> toMobsters, nextDriver = 0 }\n , test",
"end": 2628,
"score": 0.5901154876,
"start": 2627,
"tag": "NAME",
"value": "y"
},
{
"context": " empty bench\"\n { empty | mobsters = [ \"Spock\" ] |> toMobsters }\n (Bench 0)\n ",
"end": 2772,
"score": 0.9847346544,
"start": 2767,
"tag": "NAME",
"value": "Spock"
},
{
"context": "ch 0)\n { empty | inactiveMobsters = [ \"Spock\" ] |> toMobsters }\n , testOperation \"moves",
"end": 2863,
"score": 0.9722076654,
"start": 2858,
"tag": "NAME",
"value": "Spock"
},
{
"context": "orrect index\"\n { empty | mobsters = [ \"Spock\", \"Sulu\" ] |> toMobsters }\n (Bench 0)\n",
"end": 2991,
"score": 0.9718333483,
"start": 2986,
"tag": "NAME",
"value": "Spock"
},
{
"context": "dex\"\n { empty | mobsters = [ \"Spock\", \"Sulu\" ] |> toMobsters }\n (Bench 0)\n ",
"end": 2999,
"score": 0.9234884381,
"start": 2995,
"tag": "NAME",
"value": "Sulu"
},
{
"context": " (Bench 0)\n { empty | mobsters = [ \"Sulu\" ] |> toMobsters, inactiveMobsters = [ \"Spock\" ] ",
"end": 3081,
"score": 0.9245971441,
"start": 3077,
"tag": "NAME",
"value": "Sulu"
},
{
"context": "= [ \"Sulu\" ] |> toMobsters, inactiveMobsters = [ \"Spock\" ] |> toMobsters }\n , testOperations \"puts",
"end": 3127,
"score": 0.929079175,
"start": 3122,
"tag": "NAME",
"value": "Spock"
},
{
"context": "ey are added\"\n { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters }\n ",
"end": 3261,
"score": 0.9982583523,
"start": 3257,
"tag": "NAME",
"value": "Kirk"
},
{
"context": "dded\"\n { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters }\n [ (Bench ",
"end": 3270,
"score": 0.9871942997,
"start": 3265,
"tag": "NAME",
"value": "Spock"
},
{
"context": " { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters }\n [ (Bench 1), (Benc",
"end": 3279,
"score": 0.9058386683,
"start": 3274,
"tag": "NAME",
"value": "McCoy"
},
{
"context": ", (Bench 1) ]\n { empty | mobsters = [ \"Kirk\" ] |> toMobsters, inactiveMobsters = [ \"Spock\", \"",
"end": 3376,
"score": 0.9987370968,
"start": 3372,
"tag": "NAME",
"value": "Kirk"
},
{
"context": "= [ \"Kirk\" ] |> toMobsters, inactiveMobsters = [ \"Spock\", \"McCoy\" ] |> toMobsters }\n ]\n\n\nrotateInC",
"end": 3422,
"score": 0.9497141242,
"start": 3417,
"tag": "NAME",
"value": "Spock"
},
{
"context": "\" ] |> toMobsters, inactiveMobsters = [ \"Spock\", \"McCoy\" ] |> toMobsters }\n ]\n\n\nrotateInCases : Te",
"end": 3431,
"score": 0.7693558335,
"start": 3426,
"tag": "NAME",
"value": "McCoy"
},
{
"context": "tion\"\n { empty | inactiveMobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters }\n ",
"end": 3629,
"score": 0.9955624342,
"start": 3625,
"tag": "NAME",
"value": "Kirk"
},
{
"context": " { empty | inactiveMobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters }\n (RotateIn",
"end": 3638,
"score": 0.9595658779,
"start": 3633,
"tag": "NAME",
"value": "Spock"
},
{
"context": " { empty | inactiveMobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters }\n (RotateIn 2)\n ",
"end": 3647,
"score": 0.7847236991,
"start": 3642,
"tag": "NAME",
"value": "McCoy"
},
{
"context": "In 2)\n { empty | inactiveMobsters = [ \"Kirk\", \"Spock\" ] |> toMobsters, mobsters = [ \"McCoy\" ]",
"end": 3740,
"score": 0.9945987463,
"start": 3736,
"tag": "NAME",
"value": "Kirk"
},
{
"context": " { empty | inactiveMobsters = [ \"Kirk\", \"Spock\" ] |> toMobsters, mobsters = [ \"McCoy\" ] |> toMob",
"end": 3749,
"score": 0.9795774221,
"start": 3744,
"tag": "NAME",
"value": "Spock"
},
{
"context": " [ \"Kirk\", \"Spock\" ] |> toMobsters, mobsters = [ \"McCoy\" ] |> toMobsters }\n , testOperation \"ad",
"end": 3784,
"score": 0.5447314382,
"start": 3782,
"tag": "NAME",
"value": "Mc"
},
{
"context": " next driver\"\n { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters, inactiveMobst",
"end": 3926,
"score": 0.9994407892,
"start": 3922,
"tag": "NAME",
"value": "Kirk"
},
{
"context": "iver\"\n { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters, inactiveMobsters = [ \"",
"end": 3935,
"score": 0.9953677654,
"start": 3930,
"tag": "NAME",
"value": "Spock"
},
{
"context": " { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters, inactiveMobsters = [ \"Sulu\" ] |",
"end": 3944,
"score": 0.9354278445,
"start": 3939,
"tag": "NAME",
"value": "McCoy"
},
{
"context": ", \"McCoy\" ] |> toMobsters, inactiveMobsters = [ \"Sulu\" ] |> toMobsters, nextDriver = 1 }\n (R",
"end": 3989,
"score": 0.5372248888,
"start": 3986,
"tag": "NAME",
"value": "ulu"
},
{
"context": " (RotateIn 0)\n { empty | mobsters = [ \"Kirk\", \"Spock\", \"Sulu\", \"McCoy\" ] |> toMobsters, nextD",
"end": 4090,
"score": 0.9996175766,
"start": 4086,
"tag": "NAME",
"value": "Kirk"
},
{
"context": "In 0)\n { empty | mobsters = [ \"Kirk\", \"Spock\", \"Sulu\", \"McCoy\" ] |> toMobsters, nextDriver = 1",
"end": 4099,
"score": 0.9982028008,
"start": 4094,
"tag": "NAME",
"value": "Spock"
},
{
"context": " { empty | mobsters = [ \"Kirk\", \"Spock\", \"Sulu\", \"McCoy\" ] |> toMobsters, nextDriver = 1 }\n ",
"end": 4107,
"score": 0.7091377974,
"start": 4104,
"tag": "NAME",
"value": "ulu"
},
{
"context": " { empty | mobsters = [ \"Kirk\", \"Spock\", \"Sulu\", \"McCoy\" ] |> toMobsters, nextDriver = 1 }\n ]\n\n\nre",
"end": 4116,
"score": 0.7999194264,
"start": 4111,
"tag": "NAME",
"value": "McCoy"
},
{
"context": "ters\"\n { empty | inactiveMobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters }\n ",
"end": 4344,
"score": 0.9993728399,
"start": 4340,
"tag": "NAME",
"value": "Kirk"
},
{
"context": " { empty | inactiveMobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters }\n (Remove 1",
"end": 4353,
"score": 0.9955276251,
"start": 4348,
"tag": "NAME",
"value": "Spock"
},
{
"context": " { empty | inactiveMobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters }\n (Remove 1)\n ",
"end": 4362,
"score": 0.9245966077,
"start": 4357,
"tag": "NAME",
"value": "McCoy"
},
{
"context": "ve 1)\n { empty | inactiveMobsters = [ \"Kirk\", \"McCoy\" ] |> toMobsters }\n ]\n\n\nrotateCas",
"end": 4453,
"score": 0.9976984859,
"start": 4449,
"tag": "NAME",
"value": "Kirk"
},
{
"context": " { empty | inactiveMobsters = [ \"Kirk\", \"McCoy\" ] |> toMobsters }\n ]\n\n\nrotateCase1 : Test",
"end": 4462,
"score": 0.9214841723,
"start": 4457,
"tag": "NAME",
"value": "McCoy"
},
{
"context": " startList =\n { empty | mobsters = [ \"Jane Doe\", \"John Smith\" ] |> toMobsters, nextDriver = 0 }\n",
"end": 4599,
"score": 0.9998588562,
"start": 4591,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "=\n { empty | mobsters = [ \"Jane Doe\", \"John Smith\" ] |> toMobsters, nextDriver = 0 }\n in\n ",
"end": 4613,
"score": 0.9998533726,
"start": 4603,
"tag": "NAME",
"value": "John Smith"
},
{
"context": " startList =\n { empty | mobsters = [ \"Jane Doe\", \"John Smith\" ] |> toMobsters, nextDriver = 1 }\n",
"end": 4890,
"score": 0.9998717308,
"start": 4882,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "=\n { empty | mobsters = [ \"Jane Doe\", \"John Smith\" ] |> toMobsters, nextDriver = 1 }\n in\n ",
"end": 4904,
"score": 0.9998618364,
"start": 4894,
"tag": "NAME",
"value": "John Smith"
},
{
"context": " startList =\n { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters, nextDriver = ",
"end": 5174,
"score": 0.9996376038,
"start": 5170,
"tag": "NAME",
"value": "Kirk"
},
{
"context": "ist =\n { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters, nextDriver = 1 }\n i",
"end": 5183,
"score": 0.9987616539,
"start": 5178,
"tag": "NAME",
"value": "Spock"
},
{
"context": " { empty | mobsters = [ \"Kirk\", \"Spock\", \"McCoy\" ] |> toMobsters, nextDriver = 1 }\n in\n ",
"end": 5192,
"score": 0.9863844514,
"start": 5187,
"tag": "NAME",
"value": "McCoy"
},
{
"context": "mpty\"\n Mobster.empty\n (Add \"John Doe\")\n { empty | mobsters = [ \"John Doe\" ]",
"end": 7718,
"score": 0.9998566508,
"start": 7710,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "d \"John Doe\")\n { empty | mobsters = [ \"John Doe\" ] |> toMobsters }\n , testOperations \"add ",
"end": 7765,
"score": 0.9998703003,
"start": 7757,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "gs\"\n Mobster.empty\n [ (Add \"Jane Doe\"), (Add \"John Smith\") ]\n { empty | mob",
"end": 7881,
"score": 0.9998762012,
"start": 7873,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "bster.empty\n [ (Add \"Jane Doe\"), (Add \"John Smith\") ]\n { empty | mobsters = [ \"Jane Doe\"",
"end": 7901,
"score": 0.9998583198,
"start": 7891,
"tag": "NAME",
"value": "John Smith"
},
{
"context": "ohn Smith\") ]\n { empty | mobsters = [ \"Jane Doe\", \"John Smith\" ] |> toMobsters, nextDriver = 0 }\n",
"end": 7950,
"score": 0.9998691082,
"start": 7942,
"tag": "NAME",
"value": "Jane Doe"
},
{
"context": "]\n { empty | mobsters = [ \"Jane Doe\", \"John Smith\" ] |> toMobsters, nextDriver = 0 }\n ]\n\n\nte",
"end": 7964,
"score": 0.9998583794,
"start": 7954,
"tag": "NAME",
"value": "John Smith"
}
] | tests/MobsterOperationTests.elm | tempotimer/tempo | 0 | module MobsterOperationTests exposing (all)
import Test exposing (..)
import Expect
import Roster.Data as Mobster exposing (RosterData, empty)
import Roster.Operation exposing (MobsterOperation(..), updateMoblist)
import TestHelpers exposing (toMobsters)
import Roster.RpgRole exposing (..)
fakeExperience =
{ driver = [ { complete = False, description = "driver goal" } ]
, navigator = [ { complete = False, description = "navigator goal" } ]
, mobber = [ { complete = False, description = "mobber goal" } ]
, researcher = [ { complete = False, description = "researcher goal" } ]
, sponsor = [ { complete = False, description = "sponsor goal" } ]
}
fakeExperience2 =
{ driver = [ { complete = True, description = "driver goal" } ]
, navigator = [ { complete = False, description = "navigator goal" } ]
, mobber = [ { complete = False, description = "mobber goal" } ]
, researcher = [ { complete = False, description = "researcher goal" } ]
, sponsor = [ { complete = False, description = "sponsor goal" } ]
}
createMobster : String -> Mobster.Mobster
createMobster name =
Mobster.Mobster name fakeExperience
all : Test
all =
describe "mobster operation" [ benchCases, rotateInCases, removeCases, rotateCases, moveCases, addCases, completeGoalCases ]
completeGoalCases : Test
completeGoalCases =
describe "complete goal"
[ testOperation "driver doesn't change when navigator is removed"
{ empty
| mobsters = [ createMobster "Sulu", createMobster "Kirk", createMobster "Spock", createMobster "McCoy" ]
}
(CompleteGoal 0 Driver 0)
{ empty
| mobsters =
[ Mobster.Mobster "Sulu" fakeExperience2
, createMobster "Kirk"
, createMobster "Spock"
, createMobster "McCoy"
]
}
]
benchCases : Test
benchCases =
describe "bench"
[ testOperation "driver doesn't change when navigator is removed"
{ empty | mobsters = [ "Kirk", "Spock", "McCoy" ] |> toMobsters }
(Bench 1)
{ empty | mobsters = [ "Kirk", "McCoy" ] |> toMobsters, inactiveMobsters = [ "Spock" ] |> toMobsters, nextDriver = 0 }
, testOperation "wraps around list for next driver when nextDriver is removed and was at end of list"
{ empty | mobsters = [ "Kirk", "Spock", "McCoy" ] |> toMobsters, nextDriver = 2 }
(Bench 2)
{ empty | mobsters = [ "Kirk", "Spock" ] |> toMobsters, inactiveMobsters = [ "McCoy" ] |> toMobsters, nextDriver = 0 }
, testOperation "moves a single mobster to an empty bench"
{ empty | mobsters = [ "Spock" ] |> toMobsters }
(Bench 0)
{ empty | inactiveMobsters = [ "Spock" ] |> toMobsters }
, testOperation "moves the mobster with the correct index"
{ empty | mobsters = [ "Spock", "Sulu" ] |> toMobsters }
(Bench 0)
{ empty | mobsters = [ "Sulu" ] |> toMobsters, inactiveMobsters = [ "Spock" ] |> toMobsters }
, testOperations "puts mobsters on bench in order they are added"
{ empty | mobsters = [ "Kirk", "Spock", "McCoy" ] |> toMobsters }
[ (Bench 1), (Bench 1) ]
{ empty | mobsters = [ "Kirk" ] |> toMobsters, inactiveMobsters = [ "Spock", "McCoy" ] |> toMobsters }
]
rotateInCases : Test
rotateInCases =
describe "rotate in"
[ testOperation "puts mobster back in rotation"
{ empty | inactiveMobsters = [ "Kirk", "Spock", "McCoy" ] |> toMobsters }
(RotateIn 2)
{ empty | inactiveMobsters = [ "Kirk", "Spock" ] |> toMobsters, mobsters = [ "McCoy" ] |> toMobsters }
, testOperation "adds mobsters back in rotation below the next driver"
{ empty | mobsters = [ "Kirk", "Spock", "McCoy" ] |> toMobsters, inactiveMobsters = [ "Sulu" ] |> toMobsters, nextDriver = 1 }
(RotateIn 0)
{ empty | mobsters = [ "Kirk", "Spock", "Sulu", "McCoy" ] |> toMobsters, nextDriver = 1 }
]
removeCases : Test
removeCases =
describe "remove"
[ testOperation "removes an item from bench with no active mobsters"
{ empty | inactiveMobsters = [ "Kirk", "Spock", "McCoy" ] |> toMobsters }
(Remove 1)
{ empty | inactiveMobsters = [ "Kirk", "McCoy" ] |> toMobsters }
]
rotateCase1 : Test
rotateCase1 =
let
startList =
{ empty | mobsters = [ "Jane Doe", "John Smith" ] |> toMobsters, nextDriver = 0 }
in
testOperation "without wrapping"
startList
NextTurn
{ startList | nextDriver = 1 }
rotateCase2 : Test
rotateCase2 =
let
startList =
{ empty | mobsters = [ "Jane Doe", "John Smith" ] |> toMobsters, nextDriver = 1 }
in
testOperation "with wrapping"
startList
NextTurn
{ startList | nextDriver = 0 }
rotateCase3 : Test
rotateCase3 =
let
startList =
{ empty | mobsters = [ "Kirk", "Spock", "McCoy" ] |> toMobsters, nextDriver = 1 }
in
testOperation "rewind"
startList
RewindTurn
{ startList | nextDriver = 0 }
rotateCases : Test
rotateCases =
describe "rotate" [ rotateCase1, rotateCase2, rotateCase3 ]
moveCases : Test
moveCases =
describe "move"
[ testOperation "single item list"
{ empty | mobsters = [ "only item" ] |> toMobsters, nextDriver = 0 }
(Move 0 0)
{ empty | mobsters = [ "only item" ] |> toMobsters, nextDriver = 0 }
, testOperation "index not in list"
{ empty | mobsters = [ "a", "b", "d", "c" ] |> toMobsters, nextDriver = 0 }
(Move 4 3)
{ empty | mobsters = [ "a", "b", "d", "c" ] |> toMobsters, nextDriver = 0 }
, testOperation "multiple items without wrapping"
{ empty | mobsters = [ "a", "b", "d", "c" ] |> toMobsters, nextDriver = 0 }
(Move 3 2)
{ empty | mobsters = [ "a", "b", "c", "d" ] |> toMobsters, nextDriver = 0 }
, testOperation "placing it below hovered slot when moving from higher to lower"
{ empty | mobsters = [ "a", "b", "c" ] |> toMobsters, nextDriver = 0 }
(Move 0 1)
{ empty | mobsters = [ "b", "a", "c" ] |> toMobsters, nextDriver = 0 }
, testOperation "to specific position one up"
{ empty | mobsters = [ "a", "b", "c", "d" ] |> toMobsters, nextDriver = 0 }
(Move 3 2)
{ empty | mobsters = [ "a", "b", "d", "c" ] |> toMobsters, nextDriver = 0 }
, testOperation "to specific position two up"
{ empty | mobsters = [ "a", "b", "c", "d" ] |> toMobsters, nextDriver = 0 }
(Move 3 1)
{ empty | mobsters = [ "a", "d", "b", "c" ] |> toMobsters, nextDriver = 0 }
, testOperation "down below the last item in list"
{ empty | mobsters = [ "a", "b", "c", "d" ] |> toMobsters, nextDriver = 0 }
(Move 0 3)
{ empty | mobsters = [ "b", "c", "d", "a" ] |> toMobsters, nextDriver = 0 }
, testOperation "to specific position several slots away"
{ empty | mobsters = [ "a", "b", "c", "d", "e", "f", "g" ] |> toMobsters, nextDriver = 0 }
(Move 6 0)
{ empty | mobsters = [ "g", "a", "b", "c", "d", "e", "f" ] |> toMobsters, nextDriver = 0 }
]
addCases : Test
addCases =
describe "add"
[ testOperation "add to empty"
Mobster.empty
(Add "John Doe")
{ empty | mobsters = [ "John Doe" ] |> toMobsters }
, testOperations "add two things"
Mobster.empty
[ (Add "Jane Doe"), (Add "John Smith") ]
{ empty | mobsters = [ "Jane Doe", "John Smith" ] |> toMobsters, nextDriver = 0 }
]
testOperation : String -> RosterData -> MobsterOperation -> RosterData -> Test
testOperation description startList operation expectedResult =
test description <|
\() ->
startList
|> updateMoblist operation
|> Expect.equal expectedResult
testOperations : String -> RosterData -> List MobsterOperation -> RosterData -> Test
testOperations description startList operations expectedResult =
test description <|
\() ->
List.foldl updateMoblist startList operations
|> Expect.equal expectedResult
| 54083 | module MobsterOperationTests exposing (all)
import Test exposing (..)
import Expect
import Roster.Data as Mobster exposing (RosterData, empty)
import Roster.Operation exposing (MobsterOperation(..), updateMoblist)
import TestHelpers exposing (toMobsters)
import Roster.RpgRole exposing (..)
fakeExperience =
{ driver = [ { complete = False, description = "driver goal" } ]
, navigator = [ { complete = False, description = "navigator goal" } ]
, mobber = [ { complete = False, description = "mobber goal" } ]
, researcher = [ { complete = False, description = "researcher goal" } ]
, sponsor = [ { complete = False, description = "sponsor goal" } ]
}
fakeExperience2 =
{ driver = [ { complete = True, description = "driver goal" } ]
, navigator = [ { complete = False, description = "navigator goal" } ]
, mobber = [ { complete = False, description = "mobber goal" } ]
, researcher = [ { complete = False, description = "researcher goal" } ]
, sponsor = [ { complete = False, description = "sponsor goal" } ]
}
createMobster : String -> Mobster.Mobster
createMobster name =
Mobster.Mobster name fakeExperience
all : Test
all =
describe "mobster operation" [ benchCases, rotateInCases, removeCases, rotateCases, moveCases, addCases, completeGoalCases ]
completeGoalCases : Test
completeGoalCases =
describe "complete goal"
[ testOperation "driver doesn't change when navigator is removed"
{ empty
| mobsters = [ createMobster "<NAME>", createMobster "<NAME>", createMobster "<NAME>", createMobster "<NAME>" ]
}
(CompleteGoal 0 Driver 0)
{ empty
| mobsters =
[ Mobster.Mobster "<NAME>" fakeExperience2
, createMobster "<NAME>"
, createMobster "<NAME>"
, createMobster "<NAME>"
]
}
]
benchCases : Test
benchCases =
describe "bench"
[ testOperation "driver doesn't change when navigator is removed"
{ empty | mobsters = [ "<NAME>", "<NAME>", "<NAME>" ] |> toMobsters }
(Bench 1)
{ empty | mobsters = [ "<NAME>", "<NAME>" ] |> toMobsters, inactiveMobsters = [ "<NAME>" ] |> toMobsters, nextDriver = 0 }
, testOperation "wraps around list for next driver when nextDriver is removed and was at end of list"
{ empty | mobsters = [ "<NAME>", "<NAME>", "<NAME>" ] |> toMobsters, nextDriver = 2 }
(Bench 2)
{ empty | mobsters = [ "<NAME>", "<NAME>" ] |> toMobsters, inactiveMobsters = [ "<NAME>Co<NAME>" ] |> toMobsters, nextDriver = 0 }
, testOperation "moves a single mobster to an empty bench"
{ empty | mobsters = [ "<NAME>" ] |> toMobsters }
(Bench 0)
{ empty | inactiveMobsters = [ "<NAME>" ] |> toMobsters }
, testOperation "moves the mobster with the correct index"
{ empty | mobsters = [ "<NAME>", "<NAME>" ] |> toMobsters }
(Bench 0)
{ empty | mobsters = [ "<NAME>" ] |> toMobsters, inactiveMobsters = [ "<NAME>" ] |> toMobsters }
, testOperations "puts mobsters on bench in order they are added"
{ empty | mobsters = [ "<NAME>", "<NAME>", "<NAME>" ] |> toMobsters }
[ (Bench 1), (Bench 1) ]
{ empty | mobsters = [ "<NAME>" ] |> toMobsters, inactiveMobsters = [ "<NAME>", "<NAME>" ] |> toMobsters }
]
rotateInCases : Test
rotateInCases =
describe "rotate in"
[ testOperation "puts mobster back in rotation"
{ empty | inactiveMobsters = [ "<NAME>", "<NAME>", "<NAME>" ] |> toMobsters }
(RotateIn 2)
{ empty | inactiveMobsters = [ "<NAME>", "<NAME>" ] |> toMobsters, mobsters = [ "<NAME>Coy" ] |> toMobsters }
, testOperation "adds mobsters back in rotation below the next driver"
{ empty | mobsters = [ "<NAME>", "<NAME>", "<NAME>" ] |> toMobsters, inactiveMobsters = [ "S<NAME>" ] |> toMobsters, nextDriver = 1 }
(RotateIn 0)
{ empty | mobsters = [ "<NAME>", "<NAME>", "S<NAME>", "<NAME>" ] |> toMobsters, nextDriver = 1 }
]
removeCases : Test
removeCases =
describe "remove"
[ testOperation "removes an item from bench with no active mobsters"
{ empty | inactiveMobsters = [ "<NAME>", "<NAME>", "<NAME>" ] |> toMobsters }
(Remove 1)
{ empty | inactiveMobsters = [ "<NAME>", "<NAME>" ] |> toMobsters }
]
rotateCase1 : Test
rotateCase1 =
let
startList =
{ empty | mobsters = [ "<NAME>", "<NAME>" ] |> toMobsters, nextDriver = 0 }
in
testOperation "without wrapping"
startList
NextTurn
{ startList | nextDriver = 1 }
rotateCase2 : Test
rotateCase2 =
let
startList =
{ empty | mobsters = [ "<NAME>", "<NAME>" ] |> toMobsters, nextDriver = 1 }
in
testOperation "with wrapping"
startList
NextTurn
{ startList | nextDriver = 0 }
rotateCase3 : Test
rotateCase3 =
let
startList =
{ empty | mobsters = [ "<NAME>", "<NAME>", "<NAME>" ] |> toMobsters, nextDriver = 1 }
in
testOperation "rewind"
startList
RewindTurn
{ startList | nextDriver = 0 }
rotateCases : Test
rotateCases =
describe "rotate" [ rotateCase1, rotateCase2, rotateCase3 ]
moveCases : Test
moveCases =
describe "move"
[ testOperation "single item list"
{ empty | mobsters = [ "only item" ] |> toMobsters, nextDriver = 0 }
(Move 0 0)
{ empty | mobsters = [ "only item" ] |> toMobsters, nextDriver = 0 }
, testOperation "index not in list"
{ empty | mobsters = [ "a", "b", "d", "c" ] |> toMobsters, nextDriver = 0 }
(Move 4 3)
{ empty | mobsters = [ "a", "b", "d", "c" ] |> toMobsters, nextDriver = 0 }
, testOperation "multiple items without wrapping"
{ empty | mobsters = [ "a", "b", "d", "c" ] |> toMobsters, nextDriver = 0 }
(Move 3 2)
{ empty | mobsters = [ "a", "b", "c", "d" ] |> toMobsters, nextDriver = 0 }
, testOperation "placing it below hovered slot when moving from higher to lower"
{ empty | mobsters = [ "a", "b", "c" ] |> toMobsters, nextDriver = 0 }
(Move 0 1)
{ empty | mobsters = [ "b", "a", "c" ] |> toMobsters, nextDriver = 0 }
, testOperation "to specific position one up"
{ empty | mobsters = [ "a", "b", "c", "d" ] |> toMobsters, nextDriver = 0 }
(Move 3 2)
{ empty | mobsters = [ "a", "b", "d", "c" ] |> toMobsters, nextDriver = 0 }
, testOperation "to specific position two up"
{ empty | mobsters = [ "a", "b", "c", "d" ] |> toMobsters, nextDriver = 0 }
(Move 3 1)
{ empty | mobsters = [ "a", "d", "b", "c" ] |> toMobsters, nextDriver = 0 }
, testOperation "down below the last item in list"
{ empty | mobsters = [ "a", "b", "c", "d" ] |> toMobsters, nextDriver = 0 }
(Move 0 3)
{ empty | mobsters = [ "b", "c", "d", "a" ] |> toMobsters, nextDriver = 0 }
, testOperation "to specific position several slots away"
{ empty | mobsters = [ "a", "b", "c", "d", "e", "f", "g" ] |> toMobsters, nextDriver = 0 }
(Move 6 0)
{ empty | mobsters = [ "g", "a", "b", "c", "d", "e", "f" ] |> toMobsters, nextDriver = 0 }
]
addCases : Test
addCases =
describe "add"
[ testOperation "add to empty"
Mobster.empty
(Add "<NAME>")
{ empty | mobsters = [ "<NAME>" ] |> toMobsters }
, testOperations "add two things"
Mobster.empty
[ (Add "<NAME>"), (Add "<NAME>") ]
{ empty | mobsters = [ "<NAME>", "<NAME>" ] |> toMobsters, nextDriver = 0 }
]
testOperation : String -> RosterData -> MobsterOperation -> RosterData -> Test
testOperation description startList operation expectedResult =
test description <|
\() ->
startList
|> updateMoblist operation
|> Expect.equal expectedResult
testOperations : String -> RosterData -> List MobsterOperation -> RosterData -> Test
testOperations description startList operations expectedResult =
test description <|
\() ->
List.foldl updateMoblist startList operations
|> Expect.equal expectedResult
| true | module MobsterOperationTests exposing (all)
import Test exposing (..)
import Expect
import Roster.Data as Mobster exposing (RosterData, empty)
import Roster.Operation exposing (MobsterOperation(..), updateMoblist)
import TestHelpers exposing (toMobsters)
import Roster.RpgRole exposing (..)
fakeExperience =
{ driver = [ { complete = False, description = "driver goal" } ]
, navigator = [ { complete = False, description = "navigator goal" } ]
, mobber = [ { complete = False, description = "mobber goal" } ]
, researcher = [ { complete = False, description = "researcher goal" } ]
, sponsor = [ { complete = False, description = "sponsor goal" } ]
}
fakeExperience2 =
{ driver = [ { complete = True, description = "driver goal" } ]
, navigator = [ { complete = False, description = "navigator goal" } ]
, mobber = [ { complete = False, description = "mobber goal" } ]
, researcher = [ { complete = False, description = "researcher goal" } ]
, sponsor = [ { complete = False, description = "sponsor goal" } ]
}
createMobster : String -> Mobster.Mobster
createMobster name =
Mobster.Mobster name fakeExperience
all : Test
all =
describe "mobster operation" [ benchCases, rotateInCases, removeCases, rotateCases, moveCases, addCases, completeGoalCases ]
completeGoalCases : Test
completeGoalCases =
describe "complete goal"
[ testOperation "driver doesn't change when navigator is removed"
{ empty
| mobsters = [ createMobster "PI:NAME:<NAME>END_PI", createMobster "PI:NAME:<NAME>END_PI", createMobster "PI:NAME:<NAME>END_PI", createMobster "PI:NAME:<NAME>END_PI" ]
}
(CompleteGoal 0 Driver 0)
{ empty
| mobsters =
[ Mobster.Mobster "PI:NAME:<NAME>END_PI" fakeExperience2
, createMobster "PI:NAME:<NAME>END_PI"
, createMobster "PI:NAME:<NAME>END_PI"
, createMobster "PI:NAME:<NAME>END_PI"
]
}
]
benchCases : Test
benchCases =
describe "bench"
[ testOperation "driver doesn't change when navigator is removed"
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters }
(Bench 1)
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters, inactiveMobsters = [ "PI:NAME:<NAME>END_PI" ] |> toMobsters, nextDriver = 0 }
, testOperation "wraps around list for next driver when nextDriver is removed and was at end of list"
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters, nextDriver = 2 }
(Bench 2)
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters, inactiveMobsters = [ "PI:NAME:<NAME>END_PICoPI:NAME:<NAME>END_PI" ] |> toMobsters, nextDriver = 0 }
, testOperation "moves a single mobster to an empty bench"
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI" ] |> toMobsters }
(Bench 0)
{ empty | inactiveMobsters = [ "PI:NAME:<NAME>END_PI" ] |> toMobsters }
, testOperation "moves the mobster with the correct index"
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters }
(Bench 0)
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI" ] |> toMobsters, inactiveMobsters = [ "PI:NAME:<NAME>END_PI" ] |> toMobsters }
, testOperations "puts mobsters on bench in order they are added"
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters }
[ (Bench 1), (Bench 1) ]
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI" ] |> toMobsters, inactiveMobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters }
]
rotateInCases : Test
rotateInCases =
describe "rotate in"
[ testOperation "puts mobster back in rotation"
{ empty | inactiveMobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters }
(RotateIn 2)
{ empty | inactiveMobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters, mobsters = [ "PI:NAME:<NAME>END_PICoy" ] |> toMobsters }
, testOperation "adds mobsters back in rotation below the next driver"
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters, inactiveMobsters = [ "SPI:NAME:<NAME>END_PI" ] |> toMobsters, nextDriver = 1 }
(RotateIn 0)
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "SPI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters, nextDriver = 1 }
]
removeCases : Test
removeCases =
describe "remove"
[ testOperation "removes an item from bench with no active mobsters"
{ empty | inactiveMobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters }
(Remove 1)
{ empty | inactiveMobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters }
]
rotateCase1 : Test
rotateCase1 =
let
startList =
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters, nextDriver = 0 }
in
testOperation "without wrapping"
startList
NextTurn
{ startList | nextDriver = 1 }
rotateCase2 : Test
rotateCase2 =
let
startList =
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters, nextDriver = 1 }
in
testOperation "with wrapping"
startList
NextTurn
{ startList | nextDriver = 0 }
rotateCase3 : Test
rotateCase3 =
let
startList =
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters, nextDriver = 1 }
in
testOperation "rewind"
startList
RewindTurn
{ startList | nextDriver = 0 }
rotateCases : Test
rotateCases =
describe "rotate" [ rotateCase1, rotateCase2, rotateCase3 ]
moveCases : Test
moveCases =
describe "move"
[ testOperation "single item list"
{ empty | mobsters = [ "only item" ] |> toMobsters, nextDriver = 0 }
(Move 0 0)
{ empty | mobsters = [ "only item" ] |> toMobsters, nextDriver = 0 }
, testOperation "index not in list"
{ empty | mobsters = [ "a", "b", "d", "c" ] |> toMobsters, nextDriver = 0 }
(Move 4 3)
{ empty | mobsters = [ "a", "b", "d", "c" ] |> toMobsters, nextDriver = 0 }
, testOperation "multiple items without wrapping"
{ empty | mobsters = [ "a", "b", "d", "c" ] |> toMobsters, nextDriver = 0 }
(Move 3 2)
{ empty | mobsters = [ "a", "b", "c", "d" ] |> toMobsters, nextDriver = 0 }
, testOperation "placing it below hovered slot when moving from higher to lower"
{ empty | mobsters = [ "a", "b", "c" ] |> toMobsters, nextDriver = 0 }
(Move 0 1)
{ empty | mobsters = [ "b", "a", "c" ] |> toMobsters, nextDriver = 0 }
, testOperation "to specific position one up"
{ empty | mobsters = [ "a", "b", "c", "d" ] |> toMobsters, nextDriver = 0 }
(Move 3 2)
{ empty | mobsters = [ "a", "b", "d", "c" ] |> toMobsters, nextDriver = 0 }
, testOperation "to specific position two up"
{ empty | mobsters = [ "a", "b", "c", "d" ] |> toMobsters, nextDriver = 0 }
(Move 3 1)
{ empty | mobsters = [ "a", "d", "b", "c" ] |> toMobsters, nextDriver = 0 }
, testOperation "down below the last item in list"
{ empty | mobsters = [ "a", "b", "c", "d" ] |> toMobsters, nextDriver = 0 }
(Move 0 3)
{ empty | mobsters = [ "b", "c", "d", "a" ] |> toMobsters, nextDriver = 0 }
, testOperation "to specific position several slots away"
{ empty | mobsters = [ "a", "b", "c", "d", "e", "f", "g" ] |> toMobsters, nextDriver = 0 }
(Move 6 0)
{ empty | mobsters = [ "g", "a", "b", "c", "d", "e", "f" ] |> toMobsters, nextDriver = 0 }
]
addCases : Test
addCases =
describe "add"
[ testOperation "add to empty"
Mobster.empty
(Add "PI:NAME:<NAME>END_PI")
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI" ] |> toMobsters }
, testOperations "add two things"
Mobster.empty
[ (Add "PI:NAME:<NAME>END_PI"), (Add "PI:NAME:<NAME>END_PI") ]
{ empty | mobsters = [ "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ] |> toMobsters, nextDriver = 0 }
]
testOperation : String -> RosterData -> MobsterOperation -> RosterData -> Test
testOperation description startList operation expectedResult =
test description <|
\() ->
startList
|> updateMoblist operation
|> Expect.equal expectedResult
testOperations : String -> RosterData -> List MobsterOperation -> RosterData -> Test
testOperations description startList operations expectedResult =
test description <|
\() ->
List.foldl updateMoblist startList operations
|> Expect.equal expectedResult
| elm |
[
{
"context": "ädteverzeichnis\\\"},{\\\"eintrag\\\":[{\\\"stichwort\\\":\\\"Genf\\\"},{\\\"eintragstext\\\":\\\"Genf ist der Sitz von ...\\",
"end": 1941,
"score": 0.680801034,
"start": 1937,
"tag": "NAME",
"value": "Genf"
},
{
"context": " Sitz von ...\\\"}]},{\\\"eintrag\\\":[{\\\"stichwort\\\":\\\"Köln\\\"},{\\\"eintragstext\\\":\\\"Köln ist eine Stadt, die .",
"end": 2031,
"score": 0.9563560486,
"start": 2027,
"tag": "NAME",
"value": "Köln"
},
{
"context": "\\\":[{\\\"stichwort\\\":\\\"Köln\\\"},{\\\"eintragstext\\\":\\\"Köln ist eine Stadt, die ...\\\"}]}]}]\"\n\n-}\ndecode : S",
"end": 2057,
"score": 0.6777476668,
"start": 2056,
"tag": "NAME",
"value": "ö"
}
] | src/Generic/Decoder.elm | andre-dietrich/elm-generic | 7 | module Generic.Decoder exposing (decode)
{-|
@docs decode
-}
import Generic
import Generic.Json as Json
import Generic.Xml as Xml
import Generic.Yaml as Yaml
{-| Use this general type of decoder, it will try out at first to parse a JSON format, then XML, and finally YAML
import Generic
"""
<verzeichnis>
<titel>Wikipedia Städteverzeichnis</titel>
<eintrag>
<stichwort>Genf</stichwort>
<eintragstext>Genf ist der Sitz von ...</eintragstext>
</eintrag>
<eintrag>
<stichwort>Köln</stichwort>
<eintragstext>Köln ist eine Stadt, die ...</eintragstext>
</eintrag>
</verzeichnis>
"""
|> decode
|> Result.withDefault Generic.Null
|> Generic.toString
--> Just "[{\"verzeichnis\":[{\"titel\":\"Wikipedia Städteverzeichnis\"},{\"eintrag\":[{\"stichwort\":\"Genf\"},{\"eintragstext\":\"Genf ist der Sitz von ...\"}]},{\"eintrag\":[{\"stichwort\":\"Köln\"},{\"eintragstext\":\"Köln ist eine Stadt, die ...\"}]}]}]"
"""
[
{
"verzeichnis": [
{
"titel": "Wikipedia Städteverzeichnis"
},
{
"eintrag": [
{
"stichwort": "Genf"
},
{
"eintragstext": "Genf ist der Sitz von ..."
}
]
},
{
"eintrag": [
{
"stichwort": "Köln"
},
{
"eintragstext": "Köln ist eine Stadt, die ..."
}
]
}
]
}
]
"""
|> decode
|> Result.withDefault Generic.Null
|> Generic.toString
--> Just "[{\"verzeichnis\":[{\"titel\":\"Wikipedia Städteverzeichnis\"},{\"eintrag\":[{\"stichwort\":\"Genf\"},{\"eintragstext\":\"Genf ist der Sitz von ...\"}]},{\"eintrag\":[{\"stichwort\":\"Köln\"},{\"eintragstext\":\"Köln ist eine Stadt, die ...\"}]}]}]"
-}
decode : String -> Result String Generic.Value
decode str =
case Json.decode str of
Ok gen ->
Ok gen
Err _ ->
case Xml.decode str of
Ok gen ->
Ok gen
Err _ ->
case Yaml.decode str of
Ok gen ->
Ok gen
Err _ ->
Err "Unable to decode as JSON, XML, and YAML"
| 6424 | module Generic.Decoder exposing (decode)
{-|
@docs decode
-}
import Generic
import Generic.Json as Json
import Generic.Xml as Xml
import Generic.Yaml as Yaml
{-| Use this general type of decoder, it will try out at first to parse a JSON format, then XML, and finally YAML
import Generic
"""
<verzeichnis>
<titel>Wikipedia Städteverzeichnis</titel>
<eintrag>
<stichwort>Genf</stichwort>
<eintragstext>Genf ist der Sitz von ...</eintragstext>
</eintrag>
<eintrag>
<stichwort>Köln</stichwort>
<eintragstext>Köln ist eine Stadt, die ...</eintragstext>
</eintrag>
</verzeichnis>
"""
|> decode
|> Result.withDefault Generic.Null
|> Generic.toString
--> Just "[{\"verzeichnis\":[{\"titel\":\"Wikipedia Städteverzeichnis\"},{\"eintrag\":[{\"stichwort\":\"Genf\"},{\"eintragstext\":\"Genf ist der Sitz von ...\"}]},{\"eintrag\":[{\"stichwort\":\"Köln\"},{\"eintragstext\":\"Köln ist eine Stadt, die ...\"}]}]}]"
"""
[
{
"verzeichnis": [
{
"titel": "Wikipedia Städteverzeichnis"
},
{
"eintrag": [
{
"stichwort": "Genf"
},
{
"eintragstext": "Genf ist der Sitz von ..."
}
]
},
{
"eintrag": [
{
"stichwort": "Köln"
},
{
"eintragstext": "Köln ist eine Stadt, die ..."
}
]
}
]
}
]
"""
|> decode
|> Result.withDefault Generic.Null
|> Generic.toString
--> Just "[{\"verzeichnis\":[{\"titel\":\"Wikipedia Städteverzeichnis\"},{\"eintrag\":[{\"stichwort\":\"<NAME>\"},{\"eintragstext\":\"Genf ist der Sitz von ...\"}]},{\"eintrag\":[{\"stichwort\":\"<NAME>\"},{\"eintragstext\":\"K<NAME>ln ist eine Stadt, die ...\"}]}]}]"
-}
decode : String -> Result String Generic.Value
decode str =
case Json.decode str of
Ok gen ->
Ok gen
Err _ ->
case Xml.decode str of
Ok gen ->
Ok gen
Err _ ->
case Yaml.decode str of
Ok gen ->
Ok gen
Err _ ->
Err "Unable to decode as JSON, XML, and YAML"
| true | module Generic.Decoder exposing (decode)
{-|
@docs decode
-}
import Generic
import Generic.Json as Json
import Generic.Xml as Xml
import Generic.Yaml as Yaml
{-| Use this general type of decoder, it will try out at first to parse a JSON format, then XML, and finally YAML
import Generic
"""
<verzeichnis>
<titel>Wikipedia Städteverzeichnis</titel>
<eintrag>
<stichwort>Genf</stichwort>
<eintragstext>Genf ist der Sitz von ...</eintragstext>
</eintrag>
<eintrag>
<stichwort>Köln</stichwort>
<eintragstext>Köln ist eine Stadt, die ...</eintragstext>
</eintrag>
</verzeichnis>
"""
|> decode
|> Result.withDefault Generic.Null
|> Generic.toString
--> Just "[{\"verzeichnis\":[{\"titel\":\"Wikipedia Städteverzeichnis\"},{\"eintrag\":[{\"stichwort\":\"Genf\"},{\"eintragstext\":\"Genf ist der Sitz von ...\"}]},{\"eintrag\":[{\"stichwort\":\"Köln\"},{\"eintragstext\":\"Köln ist eine Stadt, die ...\"}]}]}]"
"""
[
{
"verzeichnis": [
{
"titel": "Wikipedia Städteverzeichnis"
},
{
"eintrag": [
{
"stichwort": "Genf"
},
{
"eintragstext": "Genf ist der Sitz von ..."
}
]
},
{
"eintrag": [
{
"stichwort": "Köln"
},
{
"eintragstext": "Köln ist eine Stadt, die ..."
}
]
}
]
}
]
"""
|> decode
|> Result.withDefault Generic.Null
|> Generic.toString
--> Just "[{\"verzeichnis\":[{\"titel\":\"Wikipedia Städteverzeichnis\"},{\"eintrag\":[{\"stichwort\":\"PI:NAME:<NAME>END_PI\"},{\"eintragstext\":\"Genf ist der Sitz von ...\"}]},{\"eintrag\":[{\"stichwort\":\"PI:NAME:<NAME>END_PI\"},{\"eintragstext\":\"KPI:NAME:<NAME>END_PIln ist eine Stadt, die ...\"}]}]}]"
-}
decode : String -> Result String Generic.Value
decode str =
case Json.decode str of
Ok gen ->
Ok gen
Err _ ->
case Xml.decode str of
Ok gen ->
Ok gen
Err _ ->
case Yaml.decode str of
Ok gen ->
Ok gen
Err _ ->
Err "Unable to decode as JSON, XML, and YAML"
| elm |
[
{
"context": "docs dayOfMonthWithSuffix\n\nCopyright (c) 2016-2018 Robin Luiten\n\n-}\n\nimport Date exposing (Day(..), Month(..))\nim",
"end": 218,
"score": 0.9998647571,
"start": 206,
"tag": "NAME",
"value": "Robin Luiten"
}
] | src/Date/Extra/I18n/I_et_ee.elm | AdrianRibao/elm-date-extra | 81 | module Date.Extra.I18n.I_et_ee exposing (..)
{-| Estonian values for day and month names.
@docs dayShort
@docs dayName
@docs monthShort
@docs monthName
@docs dayOfMonthWithSuffix
Copyright (c) 2016-2018 Robin Luiten
-}
import Date exposing (Day(..), Month(..))
import String exposing (padLeft)
{-| Day short name.
-}
dayShort : Day -> String
dayShort day =
case day of
Mon ->
"E"
Tue ->
"T"
Wed ->
"K"
Thu ->
"N"
Fri ->
"R"
Sat ->
"L"
Sun ->
"P"
{-| Day full name.
-}
dayName : Day -> String
dayName day =
case day of
Mon ->
"esmaspäev"
Tue ->
"teisipäev"
Wed ->
"kolmapäev"
Thu ->
"neljapäev"
Fri ->
"reede"
Sat ->
"laupäev"
Sun ->
"pühapäev"
{-| Month short name.
-}
monthShort : Month -> String
monthShort month =
case month of
Jan ->
"jaan"
Feb ->
"veebr"
Mar ->
"märts"
Apr ->
"apr"
May ->
"mai"
Jun ->
"juuni"
Jul ->
"juuli"
Aug ->
"aug"
Sep ->
"sept"
Oct ->
"okt"
Nov ->
"nov"
Dec ->
"dets"
{-| Month full name.
-}
monthName : Month -> String
monthName month =
case month of
Jan ->
"jaanuar"
Feb ->
"veebruar"
Mar ->
"märts"
Apr ->
"aprill"
May ->
"mai"
Jun ->
"juuni"
Jul ->
"juuli"
Aug ->
"august"
Sep ->
"september"
Oct ->
"oktoober"
Nov ->
"november"
Dec ->
"detsember"
{-| Nothing to do here for Estonian.
-}
dayOfMonthWithSuffix : Bool -> Int -> String
dayOfMonthWithSuffix pad day =
(toString day) ++ "."
| 55112 | module Date.Extra.I18n.I_et_ee exposing (..)
{-| Estonian values for day and month names.
@docs dayShort
@docs dayName
@docs monthShort
@docs monthName
@docs dayOfMonthWithSuffix
Copyright (c) 2016-2018 <NAME>
-}
import Date exposing (Day(..), Month(..))
import String exposing (padLeft)
{-| Day short name.
-}
dayShort : Day -> String
dayShort day =
case day of
Mon ->
"E"
Tue ->
"T"
Wed ->
"K"
Thu ->
"N"
Fri ->
"R"
Sat ->
"L"
Sun ->
"P"
{-| Day full name.
-}
dayName : Day -> String
dayName day =
case day of
Mon ->
"esmaspäev"
Tue ->
"teisipäev"
Wed ->
"kolmapäev"
Thu ->
"neljapäev"
Fri ->
"reede"
Sat ->
"laupäev"
Sun ->
"pühapäev"
{-| Month short name.
-}
monthShort : Month -> String
monthShort month =
case month of
Jan ->
"jaan"
Feb ->
"veebr"
Mar ->
"märts"
Apr ->
"apr"
May ->
"mai"
Jun ->
"juuni"
Jul ->
"juuli"
Aug ->
"aug"
Sep ->
"sept"
Oct ->
"okt"
Nov ->
"nov"
Dec ->
"dets"
{-| Month full name.
-}
monthName : Month -> String
monthName month =
case month of
Jan ->
"jaanuar"
Feb ->
"veebruar"
Mar ->
"märts"
Apr ->
"aprill"
May ->
"mai"
Jun ->
"juuni"
Jul ->
"juuli"
Aug ->
"august"
Sep ->
"september"
Oct ->
"oktoober"
Nov ->
"november"
Dec ->
"detsember"
{-| Nothing to do here for Estonian.
-}
dayOfMonthWithSuffix : Bool -> Int -> String
dayOfMonthWithSuffix pad day =
(toString day) ++ "."
| true | module Date.Extra.I18n.I_et_ee exposing (..)
{-| Estonian values for day and month names.
@docs dayShort
@docs dayName
@docs monthShort
@docs monthName
@docs dayOfMonthWithSuffix
Copyright (c) 2016-2018 PI:NAME:<NAME>END_PI
-}
import Date exposing (Day(..), Month(..))
import String exposing (padLeft)
{-| Day short name.
-}
dayShort : Day -> String
dayShort day =
case day of
Mon ->
"E"
Tue ->
"T"
Wed ->
"K"
Thu ->
"N"
Fri ->
"R"
Sat ->
"L"
Sun ->
"P"
{-| Day full name.
-}
dayName : Day -> String
dayName day =
case day of
Mon ->
"esmaspäev"
Tue ->
"teisipäev"
Wed ->
"kolmapäev"
Thu ->
"neljapäev"
Fri ->
"reede"
Sat ->
"laupäev"
Sun ->
"pühapäev"
{-| Month short name.
-}
monthShort : Month -> String
monthShort month =
case month of
Jan ->
"jaan"
Feb ->
"veebr"
Mar ->
"märts"
Apr ->
"apr"
May ->
"mai"
Jun ->
"juuni"
Jul ->
"juuli"
Aug ->
"aug"
Sep ->
"sept"
Oct ->
"okt"
Nov ->
"nov"
Dec ->
"dets"
{-| Month full name.
-}
monthName : Month -> String
monthName month =
case month of
Jan ->
"jaanuar"
Feb ->
"veebruar"
Mar ->
"märts"
Apr ->
"aprill"
May ->
"mai"
Jun ->
"juuni"
Jul ->
"juuli"
Aug ->
"august"
Sep ->
"september"
Oct ->
"oktoober"
Nov ->
"november"
Dec ->
"detsember"
{-| Nothing to do here for Estonian.
-}
dayOfMonthWithSuffix : Bool -> Int -> String
dayOfMonthWithSuffix pad day =
(toString day) ++ "."
| elm |
[
{
"context": " span\n []\n [ text \"@ Simon Olander Sahlén\" ]\n , br [] []\n , a\n ",
"end": 2358,
"score": 0.9998801947,
"start": 2338,
"tag": "NAME",
"value": "Simon Olander Sahlén"
},
{
"context": "l.Styled.Attributes.href \"https://github.com/simonolander/elm-nick\"\n , Html.Styled.Attribute",
"end": 2479,
"score": 0.5912438631,
"start": 2472,
"tag": "USERNAME",
"value": "olander"
}
] | src/Menu/View.elm | simonolander/elm-nick | 0 | module Menu.View exposing (renderMenu)
import Array
import Css exposing (..)
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (type_, value, selected, title)
import Html.Styled.Events exposing (onClick, onInput)
import Model exposing (..)
import RemoteData exposing (..)
import UI
import Util exposing (gameModeToString)
renderMenu : Settings -> Menu -> Html Msg
renderMenu settings menu =
case menu of
MainMenu ->
renderMainMenu
SinglePlayerMenu ->
renderSinglePlayerMenu settings
MultiplayerMenu ->
renderMultiplayerMenu settings
SelectHighscoreMenu ->
renderSelectHighscoresMenu
HighscoreMenu gameMode webData ->
renderHighscoresMenu gameMode webData
renderHighscoresMenu : GameMode -> WebData (List Score) -> Html Msg
renderHighscoresMenu gameMode webData =
UI.menu
[ UI.menuTitle (gameModeToString gameMode)
, UI.scoreboard webData
, UI.space
, UI.btn [ onClick (MenuNavigation SelectHighscoreMenu)] "Back to Highscores"
]
renderSelectHighscoresMenu : Html Msg
renderSelectHighscoresMenu =
UI.menu
[ UI.menuTitle "Highscores"
, UI.btn [ onClick (MenuNavigation (HighscoreMenu SinglePlayerSurvival NotAsked)) ] (gameModeToString SinglePlayerSurvival)
, UI.btn [ onClick (MenuNavigation (HighscoreMenu MultiplayerCooperation NotAsked)) ] (gameModeToString MultiplayerCooperation)
, UI.space
, UI.btn [ onClick (MenuNavigation MainMenu)] "Back to Main Menu"
]
renderMainMenu : Html Msg
renderMainMenu =
UI.menu
[ styled img
[ width (pct 100)
, height auto
]
[ Html.Styled.Attributes.src "/assets/title.png" ]
[]
, UI.btn [ onClick (MenuNavigation SinglePlayerMenu)] "Single Player"
, UI.btn [ onClick (MenuNavigation MultiplayerMenu)] "Multiplayer"
, UI.space
, UI.btn [ onClick (MenuNavigation SelectHighscoreMenu)] "Highscores"
, UI.space
, styled div
[ width (pct 100)
, textAlign right
, fontFamily monospace
, color (rgb 220 220 220)
]
[]
[ span
[]
[ text "@ Simon Olander Sahlén" ]
, br [] []
, a
[ Html.Styled.Attributes.href "https://github.com/simonolander/elm-nick"
, Html.Styled.Attributes.target "_blank"
]
[ text "Source code" ]
]
]
renderSinglePlayerMenu : Settings -> Html Msg
renderSinglePlayerMenu settings =
UI.menu
[ UI.menuTitle "Single Player"
, UI.label "Left and right controls"
, settings.characterSettings
|> Array.toList
|> List.take 1
|> UI.leftRightControls
, UI.space
, UI.btn [ onClick (InitializeGame SinglePlayerSurvival)] "Survival"
, UI.btn [ onClick (InitializeGame SinglePlayerFree)] "Free Mode"
, UI.space
, UI.btn [ onClick (MenuNavigation MainMenu)] "Back to Main Menu"
]
renderMultiplayerMenu : Settings -> Html Msg
renderMultiplayerMenu settings =
UI.menu
[ UI.menuTitle "Multiplayer"
, UI.label "Number of players"
, styled div
[ displayFlex
, flexDirection row
, justifyContent spaceBetween
, flexShrink (int 0)
, width (pct 100)
]
[]
[ styled select
[ fontSize (px 18)
, color (rgb 51 51 51)
, border3 (px 1) solid (rgb 191 191 191)
, borderRadius (px 8)
, padding2 (px 5) (px 10)
, height (px 48)
, backgroundColor (rgb 255 255 255)
, boxShadow6 inset (px 0) (px 3) (px 0) (px 0) (rgb 235 235 235)
, marginBottom (px 4)
, flex (int 1)
]
[ onInput (\ intString -> UpdateNumberOfPlayers (Result.withDefault 2 (String.toInt intString)))
, title "Number of players"
]
( [ (2, "Two Players")
, (3, "Three Players")
, (4, "Four Players")
, (5, "Five Players")
, (6, "Six Players")
]
|> List.map
(\(num, label) ->
option
[ value (toString num)
, selected (num == settings.numberOfPlayers)
]
[ text label ]
)
)
]
, UI.label "Left and right controls"
, settings.characterSettings
|> Array.toList
|> List.take settings.numberOfPlayers
|> UI.leftRightControls
, UI.space
, UI.btn [ onClick (InitializeGame MultiplayerCooperation)] "Cooperation"
, UI.btn [ onClick (InitializeGame LastManStanding)] "Last Man Standing"
, UI.btn [ onClick (InitializeGame MultiplayerFree)] "Free Mode"
, UI.space
, UI.btn [ onClick (MenuNavigation MainMenu)] "Back to Main Menu"
]
| 3844 | module Menu.View exposing (renderMenu)
import Array
import Css exposing (..)
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (type_, value, selected, title)
import Html.Styled.Events exposing (onClick, onInput)
import Model exposing (..)
import RemoteData exposing (..)
import UI
import Util exposing (gameModeToString)
renderMenu : Settings -> Menu -> Html Msg
renderMenu settings menu =
case menu of
MainMenu ->
renderMainMenu
SinglePlayerMenu ->
renderSinglePlayerMenu settings
MultiplayerMenu ->
renderMultiplayerMenu settings
SelectHighscoreMenu ->
renderSelectHighscoresMenu
HighscoreMenu gameMode webData ->
renderHighscoresMenu gameMode webData
renderHighscoresMenu : GameMode -> WebData (List Score) -> Html Msg
renderHighscoresMenu gameMode webData =
UI.menu
[ UI.menuTitle (gameModeToString gameMode)
, UI.scoreboard webData
, UI.space
, UI.btn [ onClick (MenuNavigation SelectHighscoreMenu)] "Back to Highscores"
]
renderSelectHighscoresMenu : Html Msg
renderSelectHighscoresMenu =
UI.menu
[ UI.menuTitle "Highscores"
, UI.btn [ onClick (MenuNavigation (HighscoreMenu SinglePlayerSurvival NotAsked)) ] (gameModeToString SinglePlayerSurvival)
, UI.btn [ onClick (MenuNavigation (HighscoreMenu MultiplayerCooperation NotAsked)) ] (gameModeToString MultiplayerCooperation)
, UI.space
, UI.btn [ onClick (MenuNavigation MainMenu)] "Back to Main Menu"
]
renderMainMenu : Html Msg
renderMainMenu =
UI.menu
[ styled img
[ width (pct 100)
, height auto
]
[ Html.Styled.Attributes.src "/assets/title.png" ]
[]
, UI.btn [ onClick (MenuNavigation SinglePlayerMenu)] "Single Player"
, UI.btn [ onClick (MenuNavigation MultiplayerMenu)] "Multiplayer"
, UI.space
, UI.btn [ onClick (MenuNavigation SelectHighscoreMenu)] "Highscores"
, UI.space
, styled div
[ width (pct 100)
, textAlign right
, fontFamily monospace
, color (rgb 220 220 220)
]
[]
[ span
[]
[ text "@ <NAME>" ]
, br [] []
, a
[ Html.Styled.Attributes.href "https://github.com/simonolander/elm-nick"
, Html.Styled.Attributes.target "_blank"
]
[ text "Source code" ]
]
]
renderSinglePlayerMenu : Settings -> Html Msg
renderSinglePlayerMenu settings =
UI.menu
[ UI.menuTitle "Single Player"
, UI.label "Left and right controls"
, settings.characterSettings
|> Array.toList
|> List.take 1
|> UI.leftRightControls
, UI.space
, UI.btn [ onClick (InitializeGame SinglePlayerSurvival)] "Survival"
, UI.btn [ onClick (InitializeGame SinglePlayerFree)] "Free Mode"
, UI.space
, UI.btn [ onClick (MenuNavigation MainMenu)] "Back to Main Menu"
]
renderMultiplayerMenu : Settings -> Html Msg
renderMultiplayerMenu settings =
UI.menu
[ UI.menuTitle "Multiplayer"
, UI.label "Number of players"
, styled div
[ displayFlex
, flexDirection row
, justifyContent spaceBetween
, flexShrink (int 0)
, width (pct 100)
]
[]
[ styled select
[ fontSize (px 18)
, color (rgb 51 51 51)
, border3 (px 1) solid (rgb 191 191 191)
, borderRadius (px 8)
, padding2 (px 5) (px 10)
, height (px 48)
, backgroundColor (rgb 255 255 255)
, boxShadow6 inset (px 0) (px 3) (px 0) (px 0) (rgb 235 235 235)
, marginBottom (px 4)
, flex (int 1)
]
[ onInput (\ intString -> UpdateNumberOfPlayers (Result.withDefault 2 (String.toInt intString)))
, title "Number of players"
]
( [ (2, "Two Players")
, (3, "Three Players")
, (4, "Four Players")
, (5, "Five Players")
, (6, "Six Players")
]
|> List.map
(\(num, label) ->
option
[ value (toString num)
, selected (num == settings.numberOfPlayers)
]
[ text label ]
)
)
]
, UI.label "Left and right controls"
, settings.characterSettings
|> Array.toList
|> List.take settings.numberOfPlayers
|> UI.leftRightControls
, UI.space
, UI.btn [ onClick (InitializeGame MultiplayerCooperation)] "Cooperation"
, UI.btn [ onClick (InitializeGame LastManStanding)] "Last Man Standing"
, UI.btn [ onClick (InitializeGame MultiplayerFree)] "Free Mode"
, UI.space
, UI.btn [ onClick (MenuNavigation MainMenu)] "Back to Main Menu"
]
| true | module Menu.View exposing (renderMenu)
import Array
import Css exposing (..)
import Html.Styled exposing (..)
import Html.Styled.Attributes exposing (type_, value, selected, title)
import Html.Styled.Events exposing (onClick, onInput)
import Model exposing (..)
import RemoteData exposing (..)
import UI
import Util exposing (gameModeToString)
renderMenu : Settings -> Menu -> Html Msg
renderMenu settings menu =
case menu of
MainMenu ->
renderMainMenu
SinglePlayerMenu ->
renderSinglePlayerMenu settings
MultiplayerMenu ->
renderMultiplayerMenu settings
SelectHighscoreMenu ->
renderSelectHighscoresMenu
HighscoreMenu gameMode webData ->
renderHighscoresMenu gameMode webData
renderHighscoresMenu : GameMode -> WebData (List Score) -> Html Msg
renderHighscoresMenu gameMode webData =
UI.menu
[ UI.menuTitle (gameModeToString gameMode)
, UI.scoreboard webData
, UI.space
, UI.btn [ onClick (MenuNavigation SelectHighscoreMenu)] "Back to Highscores"
]
renderSelectHighscoresMenu : Html Msg
renderSelectHighscoresMenu =
UI.menu
[ UI.menuTitle "Highscores"
, UI.btn [ onClick (MenuNavigation (HighscoreMenu SinglePlayerSurvival NotAsked)) ] (gameModeToString SinglePlayerSurvival)
, UI.btn [ onClick (MenuNavigation (HighscoreMenu MultiplayerCooperation NotAsked)) ] (gameModeToString MultiplayerCooperation)
, UI.space
, UI.btn [ onClick (MenuNavigation MainMenu)] "Back to Main Menu"
]
renderMainMenu : Html Msg
renderMainMenu =
UI.menu
[ styled img
[ width (pct 100)
, height auto
]
[ Html.Styled.Attributes.src "/assets/title.png" ]
[]
, UI.btn [ onClick (MenuNavigation SinglePlayerMenu)] "Single Player"
, UI.btn [ onClick (MenuNavigation MultiplayerMenu)] "Multiplayer"
, UI.space
, UI.btn [ onClick (MenuNavigation SelectHighscoreMenu)] "Highscores"
, UI.space
, styled div
[ width (pct 100)
, textAlign right
, fontFamily monospace
, color (rgb 220 220 220)
]
[]
[ span
[]
[ text "@ PI:NAME:<NAME>END_PI" ]
, br [] []
, a
[ Html.Styled.Attributes.href "https://github.com/simonolander/elm-nick"
, Html.Styled.Attributes.target "_blank"
]
[ text "Source code" ]
]
]
renderSinglePlayerMenu : Settings -> Html Msg
renderSinglePlayerMenu settings =
UI.menu
[ UI.menuTitle "Single Player"
, UI.label "Left and right controls"
, settings.characterSettings
|> Array.toList
|> List.take 1
|> UI.leftRightControls
, UI.space
, UI.btn [ onClick (InitializeGame SinglePlayerSurvival)] "Survival"
, UI.btn [ onClick (InitializeGame SinglePlayerFree)] "Free Mode"
, UI.space
, UI.btn [ onClick (MenuNavigation MainMenu)] "Back to Main Menu"
]
renderMultiplayerMenu : Settings -> Html Msg
renderMultiplayerMenu settings =
UI.menu
[ UI.menuTitle "Multiplayer"
, UI.label "Number of players"
, styled div
[ displayFlex
, flexDirection row
, justifyContent spaceBetween
, flexShrink (int 0)
, width (pct 100)
]
[]
[ styled select
[ fontSize (px 18)
, color (rgb 51 51 51)
, border3 (px 1) solid (rgb 191 191 191)
, borderRadius (px 8)
, padding2 (px 5) (px 10)
, height (px 48)
, backgroundColor (rgb 255 255 255)
, boxShadow6 inset (px 0) (px 3) (px 0) (px 0) (rgb 235 235 235)
, marginBottom (px 4)
, flex (int 1)
]
[ onInput (\ intString -> UpdateNumberOfPlayers (Result.withDefault 2 (String.toInt intString)))
, title "Number of players"
]
( [ (2, "Two Players")
, (3, "Three Players")
, (4, "Four Players")
, (5, "Five Players")
, (6, "Six Players")
]
|> List.map
(\(num, label) ->
option
[ value (toString num)
, selected (num == settings.numberOfPlayers)
]
[ text label ]
)
)
]
, UI.label "Left and right controls"
, settings.characterSettings
|> Array.toList
|> List.take settings.numberOfPlayers
|> UI.leftRightControls
, UI.space
, UI.btn [ onClick (InitializeGame MultiplayerCooperation)] "Cooperation"
, UI.btn [ onClick (InitializeGame LastManStanding)] "Last Man Standing"
, UI.btn [ onClick (InitializeGame MultiplayerFree)] "Free Mode"
, UI.space
, UI.btn [ onClick (MenuNavigation MainMenu)] "Back to Main Menu"
]
| elm |
[
{
"context": "lroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJv",
"end": 1244,
"score": 0.6573061943,
"start": 1242,
"tag": "KEY",
"value": "L3"
},
{
"context": ".imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa",
"end": 1454,
"score": 0.9337339997,
"start": 1246,
"tag": "KEY",
"value": "LmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d"
},
{
"context": "}**\n\n![duotone](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZ",
"end": 1677,
"score": 0.5814574957,
"start": 1671,
"tag": "KEY",
"value": "assets"
},
{
"context": "duotone](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d739444",
"end": 1927,
"score": 0.9789845347,
"start": 1678,
"tag": "KEY",
"value": "W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507"
},
{
"context": "original**\n\n![original](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZH",
"end": 2452,
"score": 0.8496062756,
"start": 2437,
"tag": "KEY",
"value": "dynamic-assets/"
},
{
"context": "riginal](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)\n\n**gaussianBlur 10**\n\n!",
"end": 2766,
"score": 0.9689578414,
"start": 2452,
"tag": "KEY",
"value": "W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95"
},
{
"context": "r 10**\n\n![gaussianBlur](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZH",
"end": 2872,
"score": 0.8736076355,
"start": 2857,
"tag": "KEY",
"value": "dynamic-assets/"
},
{
"context": "ianBlur](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&blur=10)\n\n-}\ngaussianB",
"end": 3184,
"score": 0.9914302826,
"start": 2872,
"tag": "KEY",
"value": "W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f"
},
{
"context": "9aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&blur=10)\n\n-}\ngaussianBlu",
"end": 3186,
"score": 0.807280004,
"start": 3185,
"tag": "KEY",
"value": "5"
},
{
"context": "riginal](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa",
"end": 3934,
"score": 0.9901691079,
"start": 3702,
"tag": "KEY",
"value": "W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d"
},
{
"context": "kN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28",
"end": 3941,
"score": 0.8565610647,
"start": 3935,
"tag": "KEY",
"value": "5460fe"
},
{
"context": "alftone](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d739444",
"end": 4363,
"score": 0.9921628237,
"start": 4114,
"tag": "KEY",
"value": "W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507"
},
{
"context": "TMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf",
"end": 4370,
"score": 0.7047097087,
"start": 4369,
"tag": "KEY",
"value": "0"
},
{
"context": "riginal](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d739444",
"end": 5010,
"score": 0.9887583852,
"start": 4761,
"tag": "KEY",
"value": "W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507"
},
{
"context": "YTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf",
"end": 5017,
"score": 0.693508029,
"start": 5015,
"tag": "KEY",
"value": "60"
},
{
"context": "mRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95",
"end": 5025,
"score": 0.670037508,
"start": 5020,
"tag": "KEY",
"value": "cd239"
},
{
"context": "UuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop",
"end": 5038,
"score": 0.6940993071,
"start": 5033,
"tag": "KEY",
"value": "8a769"
},
{
"context": "/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150",
"end": 5044,
"score": 0.5918462276,
"start": 5043,
"tag": "KEY",
"value": "9"
},
{
"context": "60fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=1",
"end": 5048,
"score": 0.6848695278,
"start": 5046,
"tag": "KEY",
"value": "7c"
},
{
"context": "e0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150",
"end": 5050,
"score": 0.7919856906,
"start": 5049,
"tag": "KEY",
"value": "8"
},
{
"context": "ochrome](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441",
"end": 5434,
"score": 0.9981398582,
"start": 5184,
"tag": "KEY",
"value": "W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/"
},
{
"context": "YTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bd",
"end": 5439,
"score": 0.538348794,
"start": 5438,
"tag": "KEY",
"value": "6"
},
{
"context": "riginal](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28",
"end": 6068,
"score": 0.9981700182,
"start": 5829,
"tag": "KEY",
"value": "W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe"
},
{
"context": "3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394",
"end": 6076,
"score": 0.8562154174,
"start": 6070,
"tag": "KEY",
"value": "4301a5"
},
{
"context": "ixelate](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC",
"end": 6245,
"score": 0.6100698113,
"start": 6241,
"tag": "KEY",
"value": "W1si"
},
{
"context": "(https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuY",
"end": 6256,
"score": 0.7984026074,
"start": 6249,
"tag": "KEY",
"value": "LCJodHR"
},
{
"context": "ellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa",
"end": 6473,
"score": 0.9461058378,
"start": 6259,
"tag": "KEY",
"value": "ovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d"
},
{
"context": "kN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d739444",
"end": 6490,
"score": 0.8827187419,
"start": 6474,
"tag": "KEY",
"value": "5460fe0f4301a507"
},
{
"context": "riginal](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441",
"end": 7138,
"score": 0.955786407,
"start": 6888,
"tag": "KEY",
"value": "W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/"
},
{
"context": "DQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf",
"end": 7144,
"score": 0.6384066939,
"start": 7139,
"tag": "KEY",
"value": "9fc60"
},
{
"context": "mRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?",
"end": 7157,
"score": 0.6206462979,
"start": 7147,
"tag": "KEY",
"value": "cd239aacde"
},
{
"context": "OTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fi",
"end": 7159,
"score": 0.5383773446,
"start": 7158,
"tag": "KEY",
"value": "9"
},
{
"context": "UuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=",
"end": 7161,
"score": 0.5306329727,
"start": 7160,
"tag": "KEY",
"value": "8"
},
{
"context": "nIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w",
"end": 7167,
"score": 0.572917819,
"start": 7165,
"tag": "KEY",
"value": "45"
},
{
"context": "e0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)",
"end": 7178,
"score": 0.6031928062,
"start": 7176,
"tag": "KEY",
"value": "85"
},
{
"context": "4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)\n\n",
"end": 7180,
"score": 0.6290433407,
"start": 7179,
"tag": "KEY",
"value": "4"
},
{
"context": "1a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)\n\n**s",
"end": 7183,
"score": 0.7050461173,
"start": 7182,
"tag": "KEY",
"value": "3"
},
{
"context": "79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)\n\n**sepia 8",
"end": 7189,
"score": 0.5994645357,
"start": 7188,
"tag": "KEY",
"value": "a"
},
{
"context": "fcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)\n\n**sepia 80**\n\n![s",
"end": 7197,
"score": 0.6291464567,
"start": 7196,
"tag": "KEY",
"value": "8"
},
{
"context": " 80**\n\n![sepia](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZ",
"end": 7293,
"score": 0.5268452168,
"start": 7287,
"tag": "KEY",
"value": "assets"
},
{
"context": "![sepia](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441",
"end": 7544,
"score": 0.9959002137,
"start": 7294,
"tag": "KEY",
"value": "W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/"
},
{
"context": "DQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a3",
"end": 7546,
"score": 0.7969169021,
"start": 7545,
"tag": "KEY",
"value": "9"
},
{
"context": "YTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf",
"end": 7550,
"score": 0.5458165407,
"start": 7548,
"tag": "KEY",
"value": "60"
},
{
"context": "e0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&",
"end": 7584,
"score": 0.5764124393,
"start": 7582,
"tag": "KEY",
"value": "85"
},
{
"context": "1a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&sepia=8",
"end": 7591,
"score": 0.640570879,
"start": 7588,
"tag": "KEY",
"value": "394"
},
{
"context": "7/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&sepia=80)\n",
"end": 7594,
"score": 0.6911640167,
"start": 7592,
"tag": "KEY",
"value": "41"
}
] | src/ImgIX/Stylize.elm | samuelgiles/elm-imgix | 3 | module ImgIX.Stylize exposing
( Stylize
, duotone, gaussianBlur, blur, halftone, monochrome, pixelate, sepia
, toQueryParameters
)
{-| The stylize parameters allow you to apply basic artistic effects to your images.
@docs Stylize
# Stylize
@docs duotone, gaussianBlur, blur, halftone, monochrome, pixelate, sepia
# Applying
@docs toQueryParameters
-}
import ImgIX.Internals.Color as Color exposing (Alpha, Color)
import Url.Builder as UrlBuilder exposing (QueryParameter, int, string)
{-| The Stylize type
-}
type Stylize
= Duotone Color.Color Color.Color Color.Alpha
| GaussianBlur Int
| Halftone Int
| Monochrome Color.Color
| Pixelate Int
| Sepia Int
{-| Applies a duotone effect—a gradient with two different colors as its endpoints—to the image.
To achieve this effect, the image is first converted to greyscale. Two colors, usually contrasting, are then mapped to that gradient.
ColorA is mapped to the darker parts of the image, and colorB to the lighter parts.
If you were to set a light color as colorA and a dark color as colorB, you would create a duotone with a photo negative effect.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**duotone { colorA: #ff0000, colorB: #00ff00, alpha: 0.2 }**
![duotone](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&duotone=ff0000,00ff00&duotone-alpha=20)
-}
duotone : { colorA : Color.Color, colorB : Color.Color, alpha : Float } -> Stylize
duotone { colorA, colorB, alpha } =
Duotone colorA colorB alpha
{-| Applies a [Gaussian style](https://en.wikipedia.org/wiki/Gaussian_blur) blur to your image, smoothing out image noise.
Valid values are in the range from 0 – 2000.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**gaussianBlur 10**
![gaussianBlur](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&blur=10)
-}
gaussianBlur : Int -> Stylize
gaussianBlur =
GaussianBlur << betweenZeroAndTwoThousand
{-| Same as gaussianBlur
-}
blur : Int -> Stylize
blur =
gaussianBlur
{-| Applies a [half-toning](https://en.wikipedia.org/wiki/Halftone) effect to the image.
Valid values are in the range 0 – 100. The default value is 0, which leaves the image unchanged. The value represents the width of the halftone dots.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**halftone 10**
![halftone](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&htn=10)
-}
halftone : Int -> Stylize
halftone =
Halftone << betweenZeroAndHundred
{-| Applies an overall monochromatic hue change.
The higher the intensity defined by the alpha channel, the closer you will get to a duotone effect.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**monochrome #33ff0000**
![monochrome](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&mono=33ff0000)
-}
monochrome : Color.Color -> Stylize
monochrome =
Monochrome
{-| Applies a square pixellation effect to the image.
Valid values are in the range 0 – 100. The default value is 0, which leaves the image unchanged.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**pixelate 10**
![pixelate](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&px=10)
-}
pixelate : Int -> Stylize
pixelate =
Pixelate << betweenZeroAndHundred
{-| Applies a sepia-toning effect to the image.
Valid values are in the range from 0 – 100. The default value is 0, which leaves the image unchanged.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**sepia 80**
![sepia](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovL3MzLmFtYXpvbmF3cy5jb20vcHJvZHVjdC5pbWFnZXMuYmVsbHJveS5jb20vcHJvZHVjdF9pbWFnZXMvaW1hZ2VzLzAwMC8wMDMvODMzL29yaWdpbmFsLzc5ZmM2MGNkZmNkMjM5YWFjZGU3OWU4YTc2OTQ1NWZhOWJkN2MyODU3NGQ3Mzk0NDQxYTMyYmRmOGU4ZTdmOTUuanBnIl1d/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&sepia=80)
-}
sepia : Int -> Stylize
sepia =
Sepia << betweenZeroAndHundred
-- Applying
{-| -}
toQueryParameters : List Stylize -> List UrlBuilder.QueryParameter
toQueryParameters =
List.foldl
(\stylize list -> toQueryParameters_ stylize ++ list)
[]
-- Helpers
toQueryParameters_ : Stylize -> List UrlBuilder.QueryParameter
toQueryParameters_ stylize =
case stylize of
Duotone colorA colorB alpha ->
[ String.join ","
[ Color.toHex colorA
, Color.toHex colorB
]
|> UrlBuilder.string "duotone"
, round (alpha * 100)
|> String.fromInt
|> UrlBuilder.string "duotone-alpha"
]
GaussianBlur int ->
[ UrlBuilder.int "blur" int ]
Halftone int ->
[ UrlBuilder.int "htn" int ]
Monochrome color ->
[ UrlBuilder.string "mono" <| Color.toHexAlpha color ]
Pixelate int ->
[ UrlBuilder.int "px" int ]
Sepia int ->
[ UrlBuilder.int "sepia" int ]
betweenZeroAndHundred : Int -> Int
betweenZeroAndHundred =
between 0 100
betweenZeroAndTwoThousand : Int -> Int
betweenZeroAndTwoThousand =
between 0 2000
between : Int -> Int -> Int -> Int
between a z value =
if value < a then
a
else if value > z then
z
else
value
| 56405 | module ImgIX.Stylize exposing
( Stylize
, duotone, gaussianBlur, blur, halftone, monochrome, pixelate, sepia
, toQueryParameters
)
{-| The stylize parameters allow you to apply basic artistic effects to your images.
@docs Stylize
# Stylize
@docs duotone, gaussianBlur, blur, halftone, monochrome, pixelate, sepia
# Applying
@docs toQueryParameters
-}
import ImgIX.Internals.Color as Color exposing (Alpha, Color)
import Url.Builder as UrlBuilder exposing (QueryParameter, int, string)
{-| The Stylize type
-}
type Stylize
= Duotone Color.Color Color.Color Color.Alpha
| GaussianBlur Int
| Halftone Int
| Monochrome Color.Color
| Pixelate Int
| Sepia Int
{-| Applies a duotone effect—a gradient with two different colors as its endpoints—to the image.
To achieve this effect, the image is first converted to greyscale. Two colors, usually contrasting, are then mapped to that gradient.
ColorA is mapped to the darker parts of the image, and colorB to the lighter parts.
If you were to set a light color as colorA and a dark color as colorB, you would create a duotone with a photo negative effect.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczov<KEY>Mz<KEY>/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**duotone { colorA: #ff0000, colorB: #00ff00, alpha: 0.2 }**
![duotone](https://bellroy.imgix.net/dynamic-<KEY>/<KEY>/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&duotone=ff0000,00ff00&duotone-alpha=20)
-}
duotone : { colorA : Color.Color, colorB : Color.Color, alpha : Float } -> Stylize
duotone { colorA, colorB, alpha } =
Duotone colorA colorB alpha
{-| Applies a [Gaussian style](https://en.wikipedia.org/wiki/Gaussian_blur) blur to your image, smoothing out image noise.
Valid values are in the range from 0 – 2000.
**original**
![original](https://bellroy.imgix.net/<KEY> <KEY>.jpg?fit=crop&w=150&h=150)
**gaussianBlur 10**
![gaussianBlur](https://bellroy.imgix.net/<KEY> <KEY>9<KEY>.jpg?fit=crop&w=150&h=150&blur=10)
-}
gaussianBlur : Int -> Stylize
gaussianBlur =
GaussianBlur << betweenZeroAndTwoThousand
{-| Same as gaussianBlur
-}
blur : Int -> Stylize
blur =
gaussianBlur
{-| Applies a [half-toning](https://en.wikipedia.org/wiki/Halftone) effect to the image.
Valid values are in the range 0 – 100. The default value is 0, which leaves the image unchanged. The value represents the width of the halftone dots.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/<KEY>/<KEY>0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**halftone 10**
![halftone](https://bellroy.imgix.net/dynamic-assets/<KEY>/79fc6<KEY>cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&htn=10)
-}
halftone : Int -> Stylize
halftone =
Halftone << betweenZeroAndHundred
{-| Applies an overall monochromatic hue change.
The higher the intensity defined by the alpha channel, the closer you will get to a duotone effect.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/<KEY>/79fc<KEY>cdf<KEY>aacde79e<KEY>455fa<KEY>bd<KEY>2<KEY>574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**monochrome #33ff0000**
![monochrome](https://bellroy.imgix.net/dynamic-assets/<KEY>79fc<KEY>0cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&mono=33ff0000)
-}
monochrome : Color.Color -> Stylize
monochrome =
Monochrome
{-| Applies a square pixellation effect to the image.
Valid values are in the range 0 – 100. The default value is 0, which leaves the image unchanged.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/<KEY>0f<KEY>07/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**pixelate 10**
![pixelate](https://bellroy.imgix.net/dynamic-assets/<KEY>ZnUi<KEY>wcz<KEY>/<KEY>/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&px=10)
-}
pixelate : Int -> Stylize
pixelate =
Pixelate << betweenZeroAndHundred
{-| Applies a sepia-toning effect to the image.
Valid values are in the range from 0 – 100. The default value is 0, which leaves the image unchanged.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/<KEY>7<KEY>cdf<KEY>7<KEY>e<KEY>a769<KEY>5fa9bd7c2<KEY>7<KEY>d7<KEY>94441<KEY>32bdf8e<KEY>e7f95.jpg?fit=crop&w=150&h=150)
**sepia 80**
![sepia](https://bellroy.imgix.net/dynamic-<KEY>/<KEY>7<KEY>fc<KEY>cdfcd239aacde79e8a769455fa9bd7c2<KEY>74d7<KEY>4<KEY>a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&sepia=80)
-}
sepia : Int -> Stylize
sepia =
Sepia << betweenZeroAndHundred
-- Applying
{-| -}
toQueryParameters : List Stylize -> List UrlBuilder.QueryParameter
toQueryParameters =
List.foldl
(\stylize list -> toQueryParameters_ stylize ++ list)
[]
-- Helpers
toQueryParameters_ : Stylize -> List UrlBuilder.QueryParameter
toQueryParameters_ stylize =
case stylize of
Duotone colorA colorB alpha ->
[ String.join ","
[ Color.toHex colorA
, Color.toHex colorB
]
|> UrlBuilder.string "duotone"
, round (alpha * 100)
|> String.fromInt
|> UrlBuilder.string "duotone-alpha"
]
GaussianBlur int ->
[ UrlBuilder.int "blur" int ]
Halftone int ->
[ UrlBuilder.int "htn" int ]
Monochrome color ->
[ UrlBuilder.string "mono" <| Color.toHexAlpha color ]
Pixelate int ->
[ UrlBuilder.int "px" int ]
Sepia int ->
[ UrlBuilder.int "sepia" int ]
betweenZeroAndHundred : Int -> Int
betweenZeroAndHundred =
between 0 100
betweenZeroAndTwoThousand : Int -> Int
betweenZeroAndTwoThousand =
between 0 2000
between : Int -> Int -> Int -> Int
between a z value =
if value < a then
a
else if value > z then
z
else
value
| true | module ImgIX.Stylize exposing
( Stylize
, duotone, gaussianBlur, blur, halftone, monochrome, pixelate, sepia
, toQueryParameters
)
{-| The stylize parameters allow you to apply basic artistic effects to your images.
@docs Stylize
# Stylize
@docs duotone, gaussianBlur, blur, halftone, monochrome, pixelate, sepia
# Applying
@docs toQueryParameters
-}
import ImgIX.Internals.Color as Color exposing (Alpha, Color)
import Url.Builder as UrlBuilder exposing (QueryParameter, int, string)
{-| The Stylize type
-}
type Stylize
= Duotone Color.Color Color.Color Color.Alpha
| GaussianBlur Int
| Halftone Int
| Monochrome Color.Color
| Pixelate Int
| Sepia Int
{-| Applies a duotone effect—a gradient with two different colors as its endpoints—to the image.
To achieve this effect, the image is first converted to greyscale. Two colors, usually contrasting, are then mapped to that gradient.
ColorA is mapped to the darker parts of the image, and colorB to the lighter parts.
If you were to set a light color as colorA and a dark color as colorB, you would create a duotone with a photo negative effect.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/W1siZnUiLCJodHRwczovPI:KEY:<KEY>END_PIMzPI:KEY:<KEY>END_PI/5460fe0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**duotone { colorA: #ff0000, colorB: #00ff00, alpha: 0.2 }**
![duotone](https://bellroy.imgix.net/dynamic-PI:KEY:<KEY>END_PI/PI:KEY:<KEY>END_PI/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&duotone=ff0000,00ff00&duotone-alpha=20)
-}
duotone : { colorA : Color.Color, colorB : Color.Color, alpha : Float } -> Stylize
duotone { colorA, colorB, alpha } =
Duotone colorA colorB alpha
{-| Applies a [Gaussian style](https://en.wikipedia.org/wiki/Gaussian_blur) blur to your image, smoothing out image noise.
Valid values are in the range from 0 – 2000.
**original**
![original](https://bellroy.imgix.net/PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI.jpg?fit=crop&w=150&h=150)
**gaussianBlur 10**
![gaussianBlur](https://bellroy.imgix.net/PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI9PI:KEY:<KEY>END_PI.jpg?fit=crop&w=150&h=150&blur=10)
-}
gaussianBlur : Int -> Stylize
gaussianBlur =
GaussianBlur << betweenZeroAndTwoThousand
{-| Same as gaussianBlur
-}
blur : Int -> Stylize
blur =
gaussianBlur
{-| Applies a [half-toning](https://en.wikipedia.org/wiki/Halftone) effect to the image.
Valid values are in the range 0 – 100. The default value is 0, which leaves the image unchanged. The value represents the width of the halftone dots.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/PI:KEY:<KEY>END_PI/PI:KEY:<KEY>END_PI0f4301a507/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**halftone 10**
![halftone](https://bellroy.imgix.net/dynamic-assets/PI:KEY:<KEY>END_PI/79fc6PI:KEY:<KEY>END_PIcdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&htn=10)
-}
halftone : Int -> Stylize
halftone =
Halftone << betweenZeroAndHundred
{-| Applies an overall monochromatic hue change.
The higher the intensity defined by the alpha channel, the closer you will get to a duotone effect.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/PI:KEY:<KEY>END_PI/79fcPI:KEY:<KEY>END_PIcdfPI:KEY:<KEY>END_PIaacde79ePI:KEY:<KEY>END_PI455faPI:KEY:<KEY>END_PIbdPI:KEY:<KEY>END_PI2PI:KEY:<KEY>END_PI574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**monochrome #33ff0000**
![monochrome](https://bellroy.imgix.net/dynamic-assets/PI:KEY:<KEY>END_PI79fcPI:KEY:<KEY>END_PI0cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&mono=33ff0000)
-}
monochrome : Color.Color -> Stylize
monochrome =
Monochrome
{-| Applies a square pixellation effect to the image.
Valid values are in the range 0 – 100. The default value is 0, which leaves the image unchanged.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/PI:KEY:<KEY>END_PI0fPI:KEY:<KEY>END_PI07/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150)
**pixelate 10**
![pixelate](https://bellroy.imgix.net/dynamic-assets/PI:KEY:<KEY>END_PIZnUiPI:KEY:<KEY>END_PIwczPI:KEY:<KEY>END_PI/PI:KEY:<KEY>END_PI/79fc60cdfcd239aacde79e8a769455fa9bd7c28574d7394441a32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&px=10)
-}
pixelate : Int -> Stylize
pixelate =
Pixelate << betweenZeroAndHundred
{-| Applies a sepia-toning effect to the image.
Valid values are in the range from 0 – 100. The default value is 0, which leaves the image unchanged.
**original**
![original](https://bellroy.imgix.net/dynamic-assets/PI:KEY:<KEY>END_PI7PI:KEY:<KEY>END_PIcdfPI:KEY:<KEY>END_PI7PI:KEY:<KEY>END_PIePI:KEY:<KEY>END_PIa769PI:KEY:<KEY>END_PI5fa9bd7c2PI:KEY:<KEY>END_PI7PI:KEY:<KEY>END_PId7PI:KEY:<KEY>END_PI94441PI:KEY:<KEY>END_PI32bdf8ePI:KEY:<KEY>END_PIe7f95.jpg?fit=crop&w=150&h=150)
**sepia 80**
![sepia](https://bellroy.imgix.net/dynamic-PI:KEY:<KEY>END_PI/PI:KEY:<KEY>END_PI7PI:KEY:<KEY>END_PIfcPI:KEY:<KEY>END_PIcdfcd239aacde79e8a769455fa9bd7c2PI:KEY:<KEY>END_PI74d7PI:KEY:<KEY>END_PI4PI:KEY:<KEY>END_PIa32bdf8e8e7f95.jpg?fit=crop&w=150&h=150&sepia=80)
-}
sepia : Int -> Stylize
sepia =
Sepia << betweenZeroAndHundred
-- Applying
{-| -}
toQueryParameters : List Stylize -> List UrlBuilder.QueryParameter
toQueryParameters =
List.foldl
(\stylize list -> toQueryParameters_ stylize ++ list)
[]
-- Helpers
toQueryParameters_ : Stylize -> List UrlBuilder.QueryParameter
toQueryParameters_ stylize =
case stylize of
Duotone colorA colorB alpha ->
[ String.join ","
[ Color.toHex colorA
, Color.toHex colorB
]
|> UrlBuilder.string "duotone"
, round (alpha * 100)
|> String.fromInt
|> UrlBuilder.string "duotone-alpha"
]
GaussianBlur int ->
[ UrlBuilder.int "blur" int ]
Halftone int ->
[ UrlBuilder.int "htn" int ]
Monochrome color ->
[ UrlBuilder.string "mono" <| Color.toHexAlpha color ]
Pixelate int ->
[ UrlBuilder.int "px" int ]
Sepia int ->
[ UrlBuilder.int "sepia" int ]
betweenZeroAndHundred : Int -> Int
betweenZeroAndHundred =
between 0 100
betweenZeroAndTwoThousand : Int -> Int
betweenZeroAndTwoThousand =
between 0 2000
between : Int -> Int -> Int -> Int
between a z value =
if value < a then
a
else if value > z then
z
else
value
| elm |
[
{
"context": "ide column\"] [ span [ class \"pull-right\"] [ text \"Mark Stevens\"] ]\n ]\n ]\n\n ",
"end": 3380,
"score": 0.9971749783,
"start": 3368,
"tag": "NAME",
"value": "Mark Stevens"
}
] | client/app1/Main.elm | haishengwu-okta/authz-demo-2017 | 0 | {-
/*!
* Copyright (c) 2015-2016, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/
-}
port module Main exposing (..)
import Dict exposing (..)
import Html exposing (..)
import Html as Html
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Http
import String
import Navigation
import Date
import Json.Encode as Encode
import Json.Decode as Decode
import Json.Decode.Pipeline as DP
main : Program ProgramOptions Model Msg
main =
Html.programWithFlags
{ init = init
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
--------------------------------------------------
-- MODEL
--------------------------------------------------
type alias ProgramOptions =
{ accessTokenResp : Maybe AccessTokenResp
, userInfo : Maybe UserInfo
}
type alias Model =
{ accessTokenResp : Maybe AccessTokenResp
, userInfo : Maybe UserInfo
, usage : List Usage
}
type alias Usage =
{ solar : Int
, pge : Int
, net : Int
, perc : Float
}
type alias AccessTokenResp =
{ accessToken : String
, scopes : List String
}
type alias UserInfo =
{ sub : String
, name : String
}
type Msg
= LoginRedirect
--------------------------------------------------
-- INIT
--------------------------------------------------
init : ProgramOptions -> (Model, Cmd Msg)
init opt = let us = case opt.userInfo of
Just ui -> usage2
Nothing -> usage1
in
( Model opt.accessTokenResp opt.userInfo us, Cmd.none )
usage1 : List Usage
usage1 =
[ makeUsage 0 428 0.201
, makeUsage 0 432 0.205
, makeUsage 0 544 0.211
, makeUsage 0 368 0.200
]
usage2 : List Usage
usage2 = [ makeUsage 105 428 0.201
, makeUsage 122 432 0.205
, makeUsage 145 544 0.211
, makeUsage 116 368 0.200
]
makeUsage : Int -> Int -> Float -> Usage
makeUsage s p perc = Usage s p (p - s) perc
--------------------------------------------------
-- UPDATE
--------------------------------------------------
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
LoginRedirect -> ( model, loginRedirect () )
--------------------------------------------------
-- VIEW
--------------------------------------------------
view : Model -> Html Msg
view m =
div []
[ div [ class "ui container"]
[ div [ class "ui grid"]
[ div [class "two wide column"] [ img [ class "ui image", src "/assets/images/pge-spot-full-rgb-pos-lg.png"] [] ]
, div [class "four wide column"] [ h2 [ class "ui huge header company-title"] [ text "Pacific Gas and Electric Company" ] ]
, div [class "ten wide column"] [ span [ class "pull-right"] [ text "Mark Stevens"] ]
]
]
, div [ class "ui container"]
[ h1 [] [ text "Energy Production & Usage" ]
, h5 [] [ text "123 Kent Ave, Kentfield, CA" ]
, table [ class "ui celled striped table" ]
[ thead []
[ tr []
(List.map (\t -> th [] [ text t] ) [ "", "Jul", "Aug", "Sep", "Oct"])
]
, tbody []
[ solarRow m
, tr [] (td [] [text "Usage PG & E"] :: (List.map (\u -> td [] [text <| toString u.pge]) m.usage))
, tr [] (td [] [text "net"] :: (List.map (\u -> td [] [text <| toString u.net]) m.usage))
, tr [] (td [] [text "$/KwH"] :: (List.map (\u -> td [] [text <| toString u.perc]) m.usage))
]
]
]
, additionalData m
]
solarRow : Model -> Html Msg
solarRow m =
case m.userInfo of
Nothing -> tr []
[ td [] [ text "Solar Production"]
, td [colspan 4, class "link-solar-row"]
[ button
[ id "login"
, class "ui icon button blue"
, onClick LoginRedirect
]
[ text "Link Solar Account" ]
]
]
Just _ -> tr []
(td [] [ text "Solar Production (Vivint)"] :: (List.map (\u -> td [] [text <| toString u.solar]) m.usage))
additionalData : Model -> Html Msg
additionalData m =
div [ class "ui container" ]
[ h5 [ class "ui header" ] [ text "Additional Data" ],
(case m.userInfo of
Just ui -> displayUserInfo ui m.accessTokenResp
Nothing -> p [] [ ]
)
]
displayUserInfo : UserInfo -> Maybe AccessTokenResp -> Html Msg
displayUserInfo ui aresp =
div [ class "ui grid" ]
[ div [ class "four wide column" ]
[ img [ class "ui image", src "/assets/images/vivint-solar.png" ] [] ]
, div [ class "twelve wide column" ]
[ h5 [ class "ui header" ] [ text ("Account Name: " ++ ui.name) ]
, p [] [ text "This application can do following with Vivint Solar on your behalf: " ]
, displayScopes aresp
]
]
displayScopes : Maybe AccessTokenResp -> Html Msg
displayScopes aresp =
let scopes = case aresp of
Just ar -> List.filter (\s -> s /= "openid" && s /= "profile") ar.scopes
Nothing -> []
in
ul [] (List.map (\s -> li [] [ text s ]) scopes)
--------------------------------------------------
-- PORTs
--------------------------------------------------
port loginRedirect : () -> Cmd msg
| 37203 | {-
/*!
* Copyright (c) 2015-2016, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/
-}
port module Main exposing (..)
import Dict exposing (..)
import Html exposing (..)
import Html as Html
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Http
import String
import Navigation
import Date
import Json.Encode as Encode
import Json.Decode as Decode
import Json.Decode.Pipeline as DP
main : Program ProgramOptions Model Msg
main =
Html.programWithFlags
{ init = init
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
--------------------------------------------------
-- MODEL
--------------------------------------------------
type alias ProgramOptions =
{ accessTokenResp : Maybe AccessTokenResp
, userInfo : Maybe UserInfo
}
type alias Model =
{ accessTokenResp : Maybe AccessTokenResp
, userInfo : Maybe UserInfo
, usage : List Usage
}
type alias Usage =
{ solar : Int
, pge : Int
, net : Int
, perc : Float
}
type alias AccessTokenResp =
{ accessToken : String
, scopes : List String
}
type alias UserInfo =
{ sub : String
, name : String
}
type Msg
= LoginRedirect
--------------------------------------------------
-- INIT
--------------------------------------------------
init : ProgramOptions -> (Model, Cmd Msg)
init opt = let us = case opt.userInfo of
Just ui -> usage2
Nothing -> usage1
in
( Model opt.accessTokenResp opt.userInfo us, Cmd.none )
usage1 : List Usage
usage1 =
[ makeUsage 0 428 0.201
, makeUsage 0 432 0.205
, makeUsage 0 544 0.211
, makeUsage 0 368 0.200
]
usage2 : List Usage
usage2 = [ makeUsage 105 428 0.201
, makeUsage 122 432 0.205
, makeUsage 145 544 0.211
, makeUsage 116 368 0.200
]
makeUsage : Int -> Int -> Float -> Usage
makeUsage s p perc = Usage s p (p - s) perc
--------------------------------------------------
-- UPDATE
--------------------------------------------------
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
LoginRedirect -> ( model, loginRedirect () )
--------------------------------------------------
-- VIEW
--------------------------------------------------
view : Model -> Html Msg
view m =
div []
[ div [ class "ui container"]
[ div [ class "ui grid"]
[ div [class "two wide column"] [ img [ class "ui image", src "/assets/images/pge-spot-full-rgb-pos-lg.png"] [] ]
, div [class "four wide column"] [ h2 [ class "ui huge header company-title"] [ text "Pacific Gas and Electric Company" ] ]
, div [class "ten wide column"] [ span [ class "pull-right"] [ text "<NAME>"] ]
]
]
, div [ class "ui container"]
[ h1 [] [ text "Energy Production & Usage" ]
, h5 [] [ text "123 Kent Ave, Kentfield, CA" ]
, table [ class "ui celled striped table" ]
[ thead []
[ tr []
(List.map (\t -> th [] [ text t] ) [ "", "Jul", "Aug", "Sep", "Oct"])
]
, tbody []
[ solarRow m
, tr [] (td [] [text "Usage PG & E"] :: (List.map (\u -> td [] [text <| toString u.pge]) m.usage))
, tr [] (td [] [text "net"] :: (List.map (\u -> td [] [text <| toString u.net]) m.usage))
, tr [] (td [] [text "$/KwH"] :: (List.map (\u -> td [] [text <| toString u.perc]) m.usage))
]
]
]
, additionalData m
]
solarRow : Model -> Html Msg
solarRow m =
case m.userInfo of
Nothing -> tr []
[ td [] [ text "Solar Production"]
, td [colspan 4, class "link-solar-row"]
[ button
[ id "login"
, class "ui icon button blue"
, onClick LoginRedirect
]
[ text "Link Solar Account" ]
]
]
Just _ -> tr []
(td [] [ text "Solar Production (Vivint)"] :: (List.map (\u -> td [] [text <| toString u.solar]) m.usage))
additionalData : Model -> Html Msg
additionalData m =
div [ class "ui container" ]
[ h5 [ class "ui header" ] [ text "Additional Data" ],
(case m.userInfo of
Just ui -> displayUserInfo ui m.accessTokenResp
Nothing -> p [] [ ]
)
]
displayUserInfo : UserInfo -> Maybe AccessTokenResp -> Html Msg
displayUserInfo ui aresp =
div [ class "ui grid" ]
[ div [ class "four wide column" ]
[ img [ class "ui image", src "/assets/images/vivint-solar.png" ] [] ]
, div [ class "twelve wide column" ]
[ h5 [ class "ui header" ] [ text ("Account Name: " ++ ui.name) ]
, p [] [ text "This application can do following with Vivint Solar on your behalf: " ]
, displayScopes aresp
]
]
displayScopes : Maybe AccessTokenResp -> Html Msg
displayScopes aresp =
let scopes = case aresp of
Just ar -> List.filter (\s -> s /= "openid" && s /= "profile") ar.scopes
Nothing -> []
in
ul [] (List.map (\s -> li [] [ text s ]) scopes)
--------------------------------------------------
-- PORTs
--------------------------------------------------
port loginRedirect : () -> Cmd msg
| true | {-
/*!
* Copyright (c) 2015-2016, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/
-}
port module Main exposing (..)
import Dict exposing (..)
import Html exposing (..)
import Html as Html
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Http
import String
import Navigation
import Date
import Json.Encode as Encode
import Json.Decode as Decode
import Json.Decode.Pipeline as DP
main : Program ProgramOptions Model Msg
main =
Html.programWithFlags
{ init = init
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
--------------------------------------------------
-- MODEL
--------------------------------------------------
type alias ProgramOptions =
{ accessTokenResp : Maybe AccessTokenResp
, userInfo : Maybe UserInfo
}
type alias Model =
{ accessTokenResp : Maybe AccessTokenResp
, userInfo : Maybe UserInfo
, usage : List Usage
}
type alias Usage =
{ solar : Int
, pge : Int
, net : Int
, perc : Float
}
type alias AccessTokenResp =
{ accessToken : String
, scopes : List String
}
type alias UserInfo =
{ sub : String
, name : String
}
type Msg
= LoginRedirect
--------------------------------------------------
-- INIT
--------------------------------------------------
init : ProgramOptions -> (Model, Cmd Msg)
init opt = let us = case opt.userInfo of
Just ui -> usage2
Nothing -> usage1
in
( Model opt.accessTokenResp opt.userInfo us, Cmd.none )
usage1 : List Usage
usage1 =
[ makeUsage 0 428 0.201
, makeUsage 0 432 0.205
, makeUsage 0 544 0.211
, makeUsage 0 368 0.200
]
usage2 : List Usage
usage2 = [ makeUsage 105 428 0.201
, makeUsage 122 432 0.205
, makeUsage 145 544 0.211
, makeUsage 116 368 0.200
]
makeUsage : Int -> Int -> Float -> Usage
makeUsage s p perc = Usage s p (p - s) perc
--------------------------------------------------
-- UPDATE
--------------------------------------------------
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
LoginRedirect -> ( model, loginRedirect () )
--------------------------------------------------
-- VIEW
--------------------------------------------------
view : Model -> Html Msg
view m =
div []
[ div [ class "ui container"]
[ div [ class "ui grid"]
[ div [class "two wide column"] [ img [ class "ui image", src "/assets/images/pge-spot-full-rgb-pos-lg.png"] [] ]
, div [class "four wide column"] [ h2 [ class "ui huge header company-title"] [ text "Pacific Gas and Electric Company" ] ]
, div [class "ten wide column"] [ span [ class "pull-right"] [ text "PI:NAME:<NAME>END_PI"] ]
]
]
, div [ class "ui container"]
[ h1 [] [ text "Energy Production & Usage" ]
, h5 [] [ text "123 Kent Ave, Kentfield, CA" ]
, table [ class "ui celled striped table" ]
[ thead []
[ tr []
(List.map (\t -> th [] [ text t] ) [ "", "Jul", "Aug", "Sep", "Oct"])
]
, tbody []
[ solarRow m
, tr [] (td [] [text "Usage PG & E"] :: (List.map (\u -> td [] [text <| toString u.pge]) m.usage))
, tr [] (td [] [text "net"] :: (List.map (\u -> td [] [text <| toString u.net]) m.usage))
, tr [] (td [] [text "$/KwH"] :: (List.map (\u -> td [] [text <| toString u.perc]) m.usage))
]
]
]
, additionalData m
]
solarRow : Model -> Html Msg
solarRow m =
case m.userInfo of
Nothing -> tr []
[ td [] [ text "Solar Production"]
, td [colspan 4, class "link-solar-row"]
[ button
[ id "login"
, class "ui icon button blue"
, onClick LoginRedirect
]
[ text "Link Solar Account" ]
]
]
Just _ -> tr []
(td [] [ text "Solar Production (Vivint)"] :: (List.map (\u -> td [] [text <| toString u.solar]) m.usage))
additionalData : Model -> Html Msg
additionalData m =
div [ class "ui container" ]
[ h5 [ class "ui header" ] [ text "Additional Data" ],
(case m.userInfo of
Just ui -> displayUserInfo ui m.accessTokenResp
Nothing -> p [] [ ]
)
]
displayUserInfo : UserInfo -> Maybe AccessTokenResp -> Html Msg
displayUserInfo ui aresp =
div [ class "ui grid" ]
[ div [ class "four wide column" ]
[ img [ class "ui image", src "/assets/images/vivint-solar.png" ] [] ]
, div [ class "twelve wide column" ]
[ h5 [ class "ui header" ] [ text ("Account Name: " ++ ui.name) ]
, p [] [ text "This application can do following with Vivint Solar on your behalf: " ]
, displayScopes aresp
]
]
displayScopes : Maybe AccessTokenResp -> Html Msg
displayScopes aresp =
let scopes = case aresp of
Just ar -> List.filter (\s -> s /= "openid" && s /= "profile") ar.scopes
Nothing -> []
in
ul [] (List.map (\s -> li [] [ text s ]) scopes)
--------------------------------------------------
-- PORTs
--------------------------------------------------
port loginRedirect : () -> Cmd msg
| elm |
[
{
"context": "style}\n\\\\end{mathmacro}\n\n\\\\title{Test}\n% \\\\author{James Carlson}\n% \\\\email{jxxcarlson@gmail.com}\n% \\\\date{August ",
"end": 1949,
"score": 0.9998720288,
"start": 1936,
"tag": "NAME",
"value": "James Carlson"
},
{
"context": "\\\\title{Test}\n% \\\\author{James Carlson}\n% \\\\email{jxxcarlson@gmail.com}\n% \\\\date{August 5, 2018}s\n\n\\\\maketitle\n\n% EXAMPL",
"end": 1981,
"score": 0.9999320507,
"start": 1961,
"tag": "EMAIL",
"value": "jxxcarlson@gmail.com"
}
] | Demo/src/TestData.elm | elm-review-bot/meenylatex | 0 | module TestData exposing (..)
text: String
text =
"""
\\begin{mathmacro}
\\newcommand{\\A}[0]{\\mathbb{A}}
\\newcommand{\\B}[0]{\\text{B}}
\\newcommand{\\C}[0]{\\mathbb{C}}
\\newcommand{\\Dcal}[0]{\\mathcal{D}}
\\newcommand{\\Ecal}[0]{\\mathcal{E}}
\\newcommand{\\Fcal}[0]{\\mathcal{F}}
\\newcommand{\\G}[0]{\\mathbb{G}}
\\newcommand{\\g}[0]{\\mathfrak{g}}
\\newcommand{\\Hcal}[0]{\\mathcal{H}}
\\newcommand{\\Ical}[0]{\\mathcal{I}}
\\newcommand{\\K}[0]{\\mathbb{K}}
\\newcommand{\\Kcal}[0]{\\mathcal{K}}
\\newcommand{\\Lcal}[0]{\\mathcal{L}}
\\newcommand{\\Mcal}[0]{\\mathcal{M}}
\\newcommand{\\N}[0]{\\mathbb{N}}
\\newcommand{\\Ncal}[0]{\\mathcal{N}}
\\newcommand{\\Ocal}[0]{\\mathcal{O}}
\\newcommand{\\Pro}[0]{\\mathbb{P}}
\\newcommand{\\Pcal}[0]{\\mathcal{P}}
\\newcommand{\\Q}[0]{\\mathbb{Q}}
\\newcommand{\\Qcal}[0]{\\mathcal{Q}}
\\newcommand{\\R}[0]{\\mathbb{R}}
\\newcommand{\\Scal}[0]{\\mathcal{S}}
\\newcommand{\\Tcal}[0]{\\mathcal{T}}
\\newcommand{\\Ucal}[0]{\\mathcal{U}}
\\newcommand{\\Xcal}[0]{\\mathcal{X}}
\\newcommand{\\Ycal}[0]{\\mathcal{Y}}
\\newcommand{\\Z}[0]{\\mathbb{Z}}
\\newcommand{\\Zcal}[0]{\\mathcal{Z}}
\\newcommand{\\cart}[0]{\\ar @{} [dr] |{\\Box}}
\\newcommand{\\Hom}[0]{\\text{Hom}}
\\newcommand{\\Isom}[0]{\\text{Isom}}
\\newcommand{\\Pic}[0]{\\text{Pic}}
\\newcommand{\\GL}[0]{\\text{GL}}
\\newcommand{\\PGL}[0]{\\text{PGL}}
\\newcommand{\\SL}[0]{\\text{SL}}
\\newcommand{\\Sym}[0]{\\text{Sym}}
\\newcommand{\\Spec}[0]{\\text{Spec}}
\\newcommand{\\un}[0]{\\underline}
\\newcommand{\\pr}[0]{\\text{pr}}
\\newcommand{\\ov}[0]{\\overline}
\\newcommand{\\im}[0]{\\text{Im}}
\\newcommand{\\wh}[0]{\\widehat}
\\newcommand{\\wt}[1]{\\widetilde}
\\newcommand{\\ev}[0]{\\text{ev}}
\\newcommand{\\Char}[0]{\\text{char}}
\\newcommand{\\Bl}[0]{\\text{Bl}}
\\newcommand{\\M}[0]{\\text{M}}
\\newcommand{\\Sch}[0]{\\text{Sch}}
\\newcommand{\\di}[1]{\\displaystyle}
\\end{mathmacro}
\\title{Test}
% \\author{James Carlson}
% \\email{jxxcarlson@gmail.com}
% \\date{August 5, 2018}s
\\maketitle
% EXAMPLE 1
\\begin{comment}
This multi-line comment
should also not
be visible in the
rendered text.
\\end{comment}
\\section{Test A: $a^2 + b^2 = c^2$}
\\section{Test B: $\\Mcal$}
""" | 17456 | module TestData exposing (..)
text: String
text =
"""
\\begin{mathmacro}
\\newcommand{\\A}[0]{\\mathbb{A}}
\\newcommand{\\B}[0]{\\text{B}}
\\newcommand{\\C}[0]{\\mathbb{C}}
\\newcommand{\\Dcal}[0]{\\mathcal{D}}
\\newcommand{\\Ecal}[0]{\\mathcal{E}}
\\newcommand{\\Fcal}[0]{\\mathcal{F}}
\\newcommand{\\G}[0]{\\mathbb{G}}
\\newcommand{\\g}[0]{\\mathfrak{g}}
\\newcommand{\\Hcal}[0]{\\mathcal{H}}
\\newcommand{\\Ical}[0]{\\mathcal{I}}
\\newcommand{\\K}[0]{\\mathbb{K}}
\\newcommand{\\Kcal}[0]{\\mathcal{K}}
\\newcommand{\\Lcal}[0]{\\mathcal{L}}
\\newcommand{\\Mcal}[0]{\\mathcal{M}}
\\newcommand{\\N}[0]{\\mathbb{N}}
\\newcommand{\\Ncal}[0]{\\mathcal{N}}
\\newcommand{\\Ocal}[0]{\\mathcal{O}}
\\newcommand{\\Pro}[0]{\\mathbb{P}}
\\newcommand{\\Pcal}[0]{\\mathcal{P}}
\\newcommand{\\Q}[0]{\\mathbb{Q}}
\\newcommand{\\Qcal}[0]{\\mathcal{Q}}
\\newcommand{\\R}[0]{\\mathbb{R}}
\\newcommand{\\Scal}[0]{\\mathcal{S}}
\\newcommand{\\Tcal}[0]{\\mathcal{T}}
\\newcommand{\\Ucal}[0]{\\mathcal{U}}
\\newcommand{\\Xcal}[0]{\\mathcal{X}}
\\newcommand{\\Ycal}[0]{\\mathcal{Y}}
\\newcommand{\\Z}[0]{\\mathbb{Z}}
\\newcommand{\\Zcal}[0]{\\mathcal{Z}}
\\newcommand{\\cart}[0]{\\ar @{} [dr] |{\\Box}}
\\newcommand{\\Hom}[0]{\\text{Hom}}
\\newcommand{\\Isom}[0]{\\text{Isom}}
\\newcommand{\\Pic}[0]{\\text{Pic}}
\\newcommand{\\GL}[0]{\\text{GL}}
\\newcommand{\\PGL}[0]{\\text{PGL}}
\\newcommand{\\SL}[0]{\\text{SL}}
\\newcommand{\\Sym}[0]{\\text{Sym}}
\\newcommand{\\Spec}[0]{\\text{Spec}}
\\newcommand{\\un}[0]{\\underline}
\\newcommand{\\pr}[0]{\\text{pr}}
\\newcommand{\\ov}[0]{\\overline}
\\newcommand{\\im}[0]{\\text{Im}}
\\newcommand{\\wh}[0]{\\widehat}
\\newcommand{\\wt}[1]{\\widetilde}
\\newcommand{\\ev}[0]{\\text{ev}}
\\newcommand{\\Char}[0]{\\text{char}}
\\newcommand{\\Bl}[0]{\\text{Bl}}
\\newcommand{\\M}[0]{\\text{M}}
\\newcommand{\\Sch}[0]{\\text{Sch}}
\\newcommand{\\di}[1]{\\displaystyle}
\\end{mathmacro}
\\title{Test}
% \\author{<NAME>}
% \\email{<EMAIL>}
% \\date{August 5, 2018}s
\\maketitle
% EXAMPLE 1
\\begin{comment}
This multi-line comment
should also not
be visible in the
rendered text.
\\end{comment}
\\section{Test A: $a^2 + b^2 = c^2$}
\\section{Test B: $\\Mcal$}
""" | true | module TestData exposing (..)
text: String
text =
"""
\\begin{mathmacro}
\\newcommand{\\A}[0]{\\mathbb{A}}
\\newcommand{\\B}[0]{\\text{B}}
\\newcommand{\\C}[0]{\\mathbb{C}}
\\newcommand{\\Dcal}[0]{\\mathcal{D}}
\\newcommand{\\Ecal}[0]{\\mathcal{E}}
\\newcommand{\\Fcal}[0]{\\mathcal{F}}
\\newcommand{\\G}[0]{\\mathbb{G}}
\\newcommand{\\g}[0]{\\mathfrak{g}}
\\newcommand{\\Hcal}[0]{\\mathcal{H}}
\\newcommand{\\Ical}[0]{\\mathcal{I}}
\\newcommand{\\K}[0]{\\mathbb{K}}
\\newcommand{\\Kcal}[0]{\\mathcal{K}}
\\newcommand{\\Lcal}[0]{\\mathcal{L}}
\\newcommand{\\Mcal}[0]{\\mathcal{M}}
\\newcommand{\\N}[0]{\\mathbb{N}}
\\newcommand{\\Ncal}[0]{\\mathcal{N}}
\\newcommand{\\Ocal}[0]{\\mathcal{O}}
\\newcommand{\\Pro}[0]{\\mathbb{P}}
\\newcommand{\\Pcal}[0]{\\mathcal{P}}
\\newcommand{\\Q}[0]{\\mathbb{Q}}
\\newcommand{\\Qcal}[0]{\\mathcal{Q}}
\\newcommand{\\R}[0]{\\mathbb{R}}
\\newcommand{\\Scal}[0]{\\mathcal{S}}
\\newcommand{\\Tcal}[0]{\\mathcal{T}}
\\newcommand{\\Ucal}[0]{\\mathcal{U}}
\\newcommand{\\Xcal}[0]{\\mathcal{X}}
\\newcommand{\\Ycal}[0]{\\mathcal{Y}}
\\newcommand{\\Z}[0]{\\mathbb{Z}}
\\newcommand{\\Zcal}[0]{\\mathcal{Z}}
\\newcommand{\\cart}[0]{\\ar @{} [dr] |{\\Box}}
\\newcommand{\\Hom}[0]{\\text{Hom}}
\\newcommand{\\Isom}[0]{\\text{Isom}}
\\newcommand{\\Pic}[0]{\\text{Pic}}
\\newcommand{\\GL}[0]{\\text{GL}}
\\newcommand{\\PGL}[0]{\\text{PGL}}
\\newcommand{\\SL}[0]{\\text{SL}}
\\newcommand{\\Sym}[0]{\\text{Sym}}
\\newcommand{\\Spec}[0]{\\text{Spec}}
\\newcommand{\\un}[0]{\\underline}
\\newcommand{\\pr}[0]{\\text{pr}}
\\newcommand{\\ov}[0]{\\overline}
\\newcommand{\\im}[0]{\\text{Im}}
\\newcommand{\\wh}[0]{\\widehat}
\\newcommand{\\wt}[1]{\\widetilde}
\\newcommand{\\ev}[0]{\\text{ev}}
\\newcommand{\\Char}[0]{\\text{char}}
\\newcommand{\\Bl}[0]{\\text{Bl}}
\\newcommand{\\M}[0]{\\text{M}}
\\newcommand{\\Sch}[0]{\\text{Sch}}
\\newcommand{\\di}[1]{\\displaystyle}
\\end{mathmacro}
\\title{Test}
% \\author{PI:NAME:<NAME>END_PI}
% \\email{PI:EMAIL:<EMAIL>END_PI}
% \\date{August 5, 2018}s
\\maketitle
% EXAMPLE 1
\\begin{comment}
This multi-line comment
should also not
be visible in the
rendered text.
\\end{comment}
\\section{Test A: $a^2 + b^2 = c^2$}
\\section{Test B: $\\Mcal$}
""" | elm |
[
{
"context": ": GoogleSignIn.ClientId\nid =\n GoogleSignIn.Id \"421355382458-d5e1j581a9atnin2t9vfsbd62fkqkmie\"\n\n\nport googleSignOut : E.Value -> Cmd msg\n\n\nport",
"end": 436,
"score": 0.969288826,
"start": 391,
"tag": "KEY",
"value": "421355382458-d5e1j581a9atnin2t9vfsbd62fkqkmie"
}
] | example/src/Main.elm | cedric-h/elm-google-sign-in | 10 | port module Main exposing (..)
import Browser
import GoogleSignIn
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
import Json.Encode as E
-- MAIN
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
id : GoogleSignIn.ClientId
id =
GoogleSignIn.Id "421355382458-d5e1j581a9atnin2t9vfsbd62fkqkmie"
port googleSignOut : E.Value -> Cmd msg
port googleSignOutComplete : (E.Value -> msg) -> Sub msg
-- MODEL
type alias Model =
Maybe String
init : () -> ( Model, Cmd msg )
init () =
( Nothing, Cmd.none )
-- UPDATE
type Msg
= SignIn GoogleSignIn.Profile
| BeginSignOut
| SignOutComplete
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
SignIn profile ->
( Just profile.name, Cmd.none )
BeginSignOut ->
( model, googleSignOut <| GoogleSignIn.encodeId id )
SignOutComplete ->
( Nothing, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
googleSignOutComplete (\a -> SignOutComplete)
-- VIEW
view : Model -> Html Msg
view model =
div []
[ case model of
Just name ->
div []
[ div [] [ text ("Welcome, " ++ name) ]
, div [] [ button [ onClick BeginSignOut ] [ text "Sign Out" ] ]
]
Nothing ->
GoogleSignIn.view
[ GoogleSignIn.onSignIn SignIn
, GoogleSignIn.idAttr id
]
]
| 59052 | port module Main exposing (..)
import Browser
import GoogleSignIn
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
import Json.Encode as E
-- MAIN
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
id : GoogleSignIn.ClientId
id =
GoogleSignIn.Id "<KEY>"
port googleSignOut : E.Value -> Cmd msg
port googleSignOutComplete : (E.Value -> msg) -> Sub msg
-- MODEL
type alias Model =
Maybe String
init : () -> ( Model, Cmd msg )
init () =
( Nothing, Cmd.none )
-- UPDATE
type Msg
= SignIn GoogleSignIn.Profile
| BeginSignOut
| SignOutComplete
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
SignIn profile ->
( Just profile.name, Cmd.none )
BeginSignOut ->
( model, googleSignOut <| GoogleSignIn.encodeId id )
SignOutComplete ->
( Nothing, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
googleSignOutComplete (\a -> SignOutComplete)
-- VIEW
view : Model -> Html Msg
view model =
div []
[ case model of
Just name ->
div []
[ div [] [ text ("Welcome, " ++ name) ]
, div [] [ button [ onClick BeginSignOut ] [ text "Sign Out" ] ]
]
Nothing ->
GoogleSignIn.view
[ GoogleSignIn.onSignIn SignIn
, GoogleSignIn.idAttr id
]
]
| true | port module Main exposing (..)
import Browser
import GoogleSignIn
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
import Json.Encode as E
-- MAIN
main =
Browser.element
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
id : GoogleSignIn.ClientId
id =
GoogleSignIn.Id "PI:KEY:<KEY>END_PI"
port googleSignOut : E.Value -> Cmd msg
port googleSignOutComplete : (E.Value -> msg) -> Sub msg
-- MODEL
type alias Model =
Maybe String
init : () -> ( Model, Cmd msg )
init () =
( Nothing, Cmd.none )
-- UPDATE
type Msg
= SignIn GoogleSignIn.Profile
| BeginSignOut
| SignOutComplete
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
SignIn profile ->
( Just profile.name, Cmd.none )
BeginSignOut ->
( model, googleSignOut <| GoogleSignIn.encodeId id )
SignOutComplete ->
( Nothing, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
googleSignOutComplete (\a -> SignOutComplete)
-- VIEW
view : Model -> Html Msg
view model =
div []
[ case model of
Just name ->
div []
[ div [] [ text ("Welcome, " ++ name) ]
, div [] [ button [ onClick BeginSignOut ] [ text "Sign Out" ] ]
]
Nothing ->
GoogleSignIn.view
[ GoogleSignIn.onSignIn SignIn
, GoogleSignIn.idAttr id
]
]
| elm |
[
{
"context": "]\n [ text \"Créé par Olivier Adam. Code source sur \"\n ",
"end": 4558,
"score": 0.9998810291,
"start": 4546,
"tag": "NAME",
"value": "Olivier Adam"
},
{
"context": " , a [ href \"https://www.github.com/oadam/secret-wishlist\" ]\n ",
"end": 4650,
"score": 0.9996811748,
"start": 4645,
"tag": "USERNAME",
"value": "oadam"
}
] | elm/Main.elm | oadam/secret-whishlist | 0 | module Main exposing (main)
import Api exposing (Present, PresentId, Token, User, UserId)
import Browser
import Help
import Html exposing (Html, a, br, button, div, footer, h1, h3, header, main_, nav, p, span, text, u)
import Html.Attributes exposing (attribute, class, classList, hidden, href)
import Html.Events exposing (onClick)
import Pages.Login as Login exposing (Msg)
import Pages.WishList as WishList
import Session exposing (Session)
import String.Interpolate exposing (interpolate)
type Page
= Login Login.Model
| WishList WishList.Model
type alias Model =
{ page : Page, help : Bool }
type Msg
= ToggleHelp
| LoginMsg Login.Msg
| WishListMsg WishList.Msg
| EditPresentMsg Present
| Logout
init : () -> ( Model, Cmd Msg )
init flags =
( { page =
Login <| Login.init
, help = False
}
, Cmd.none
)
update : Msg -> Model -> ( Model, Cmd Msg )
update message model =
case ( message, model.page ) of
( ToggleHelp, _ ) ->
( { model | help = not model.help }, Cmd.none )
( LoginMsg msg, Login login ) ->
let
newSession =
Login.isMsgStartSession msg
( loginModel, cmd ) =
Login.update msg login
in
case newSession of
Nothing ->
( { model | page = Login loginModel }, Cmd.map LoginMsg cmd )
Just session ->
let
( wiModel, wiCmd ) =
WishList.init session session.logged_user []
in
( { model | page = WishList wiModel }
, Cmd.map WishListMsg wiCmd
)
( WishListMsg msg, WishList wishList ) ->
let
( wishListModel, cmd ) =
WishList.update msg wishList
in
( { model | page = WishList wishListModel }, Cmd.map WishListMsg cmd )
( Logout, _ ) ->
init ()
_ ->
( model, Cmd.none )
windowTitle : Page -> String
windowTitle page =
case page of
_ ->
"Secret Wishlist"
viewMain : Page -> List (Html Msg)
viewMain page =
case page of
Login login ->
List.map (Html.map LoginMsg) (Login.view login)
++ [ p [ class "lead text-center" ]
[ button [ class "btn btn-link", onClick ToggleHelp ]
[ text "Comment ça marche ?" ]
]
]
WishList wishList ->
List.map (Html.map WishListMsg) (WishList.view wishList)
viewLogout : Page -> List (Html Msg)
viewLogout page =
let
session =
getSession page
in
case session of
Nothing ->
[]
Just s ->
[ nav [ class "nav nav-masthead justify-content-center" ]
[ span [] [ span [ class "text-muted" ] [ text "connecté en tant que " ], span [] [ text s.logged_user.name ] ]
, button [ class "btn", onClick Logout ]
[ text "Déconnexion" ]
]
]
centerMain : Page -> Bool
centerMain page =
case page of
Login _ ->
True
_ ->
False
getSession : Page -> Maybe Session
getSession page =
case page of
Login _ ->
Nothing
WishList wishlist ->
Just <| WishList.getSession wishlist
view : Model -> Browser.Document Msg
view { page, help } =
{ title = windowTitle page
, body =
(if help then
Help.modal ToggleHelp
else
[]
)
++ [ div [ class "cover-container d-flex w-100 h-100 p-3 mx-auto flex-column" ]
[ header [ class "masthead", classList [ ( "mb-auto", centerMain page ) ] ]
[ div [ class "inner" ]
(h3 [ class "masthead-brand" ]
[ text "Secret Wishlist" ]
:: viewLogout page
)
]
, main_ [ class "inner", classList [ ( "cover", centerMain page ) ], attribute "role" "main" ] (viewMain page)
, footer [ class "mastfoot mt-auto" ]
[ div [ class "inner" ]
[ p []
[ text "Créé par Olivier Adam. Code source sur "
, a [ href "https://www.github.com/oadam/secret-wishlist" ]
[ text "Github" ]
]
]
]
]
]
}
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
main =
Browser.document { init = init, update = update, view = view, subscriptions = subscriptions }
| 55639 | module Main exposing (main)
import Api exposing (Present, PresentId, Token, User, UserId)
import Browser
import Help
import Html exposing (Html, a, br, button, div, footer, h1, h3, header, main_, nav, p, span, text, u)
import Html.Attributes exposing (attribute, class, classList, hidden, href)
import Html.Events exposing (onClick)
import Pages.Login as Login exposing (Msg)
import Pages.WishList as WishList
import Session exposing (Session)
import String.Interpolate exposing (interpolate)
type Page
= Login Login.Model
| WishList WishList.Model
type alias Model =
{ page : Page, help : Bool }
type Msg
= ToggleHelp
| LoginMsg Login.Msg
| WishListMsg WishList.Msg
| EditPresentMsg Present
| Logout
init : () -> ( Model, Cmd Msg )
init flags =
( { page =
Login <| Login.init
, help = False
}
, Cmd.none
)
update : Msg -> Model -> ( Model, Cmd Msg )
update message model =
case ( message, model.page ) of
( ToggleHelp, _ ) ->
( { model | help = not model.help }, Cmd.none )
( LoginMsg msg, Login login ) ->
let
newSession =
Login.isMsgStartSession msg
( loginModel, cmd ) =
Login.update msg login
in
case newSession of
Nothing ->
( { model | page = Login loginModel }, Cmd.map LoginMsg cmd )
Just session ->
let
( wiModel, wiCmd ) =
WishList.init session session.logged_user []
in
( { model | page = WishList wiModel }
, Cmd.map WishListMsg wiCmd
)
( WishListMsg msg, WishList wishList ) ->
let
( wishListModel, cmd ) =
WishList.update msg wishList
in
( { model | page = WishList wishListModel }, Cmd.map WishListMsg cmd )
( Logout, _ ) ->
init ()
_ ->
( model, Cmd.none )
windowTitle : Page -> String
windowTitle page =
case page of
_ ->
"Secret Wishlist"
viewMain : Page -> List (Html Msg)
viewMain page =
case page of
Login login ->
List.map (Html.map LoginMsg) (Login.view login)
++ [ p [ class "lead text-center" ]
[ button [ class "btn btn-link", onClick ToggleHelp ]
[ text "Comment ça marche ?" ]
]
]
WishList wishList ->
List.map (Html.map WishListMsg) (WishList.view wishList)
viewLogout : Page -> List (Html Msg)
viewLogout page =
let
session =
getSession page
in
case session of
Nothing ->
[]
Just s ->
[ nav [ class "nav nav-masthead justify-content-center" ]
[ span [] [ span [ class "text-muted" ] [ text "connecté en tant que " ], span [] [ text s.logged_user.name ] ]
, button [ class "btn", onClick Logout ]
[ text "Déconnexion" ]
]
]
centerMain : Page -> Bool
centerMain page =
case page of
Login _ ->
True
_ ->
False
getSession : Page -> Maybe Session
getSession page =
case page of
Login _ ->
Nothing
WishList wishlist ->
Just <| WishList.getSession wishlist
view : Model -> Browser.Document Msg
view { page, help } =
{ title = windowTitle page
, body =
(if help then
Help.modal ToggleHelp
else
[]
)
++ [ div [ class "cover-container d-flex w-100 h-100 p-3 mx-auto flex-column" ]
[ header [ class "masthead", classList [ ( "mb-auto", centerMain page ) ] ]
[ div [ class "inner" ]
(h3 [ class "masthead-brand" ]
[ text "Secret Wishlist" ]
:: viewLogout page
)
]
, main_ [ class "inner", classList [ ( "cover", centerMain page ) ], attribute "role" "main" ] (viewMain page)
, footer [ class "mastfoot mt-auto" ]
[ div [ class "inner" ]
[ p []
[ text "Créé par <NAME>. Code source sur "
, a [ href "https://www.github.com/oadam/secret-wishlist" ]
[ text "Github" ]
]
]
]
]
]
}
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
main =
Browser.document { init = init, update = update, view = view, subscriptions = subscriptions }
| true | module Main exposing (main)
import Api exposing (Present, PresentId, Token, User, UserId)
import Browser
import Help
import Html exposing (Html, a, br, button, div, footer, h1, h3, header, main_, nav, p, span, text, u)
import Html.Attributes exposing (attribute, class, classList, hidden, href)
import Html.Events exposing (onClick)
import Pages.Login as Login exposing (Msg)
import Pages.WishList as WishList
import Session exposing (Session)
import String.Interpolate exposing (interpolate)
type Page
= Login Login.Model
| WishList WishList.Model
type alias Model =
{ page : Page, help : Bool }
type Msg
= ToggleHelp
| LoginMsg Login.Msg
| WishListMsg WishList.Msg
| EditPresentMsg Present
| Logout
init : () -> ( Model, Cmd Msg )
init flags =
( { page =
Login <| Login.init
, help = False
}
, Cmd.none
)
update : Msg -> Model -> ( Model, Cmd Msg )
update message model =
case ( message, model.page ) of
( ToggleHelp, _ ) ->
( { model | help = not model.help }, Cmd.none )
( LoginMsg msg, Login login ) ->
let
newSession =
Login.isMsgStartSession msg
( loginModel, cmd ) =
Login.update msg login
in
case newSession of
Nothing ->
( { model | page = Login loginModel }, Cmd.map LoginMsg cmd )
Just session ->
let
( wiModel, wiCmd ) =
WishList.init session session.logged_user []
in
( { model | page = WishList wiModel }
, Cmd.map WishListMsg wiCmd
)
( WishListMsg msg, WishList wishList ) ->
let
( wishListModel, cmd ) =
WishList.update msg wishList
in
( { model | page = WishList wishListModel }, Cmd.map WishListMsg cmd )
( Logout, _ ) ->
init ()
_ ->
( model, Cmd.none )
windowTitle : Page -> String
windowTitle page =
case page of
_ ->
"Secret Wishlist"
viewMain : Page -> List (Html Msg)
viewMain page =
case page of
Login login ->
List.map (Html.map LoginMsg) (Login.view login)
++ [ p [ class "lead text-center" ]
[ button [ class "btn btn-link", onClick ToggleHelp ]
[ text "Comment ça marche ?" ]
]
]
WishList wishList ->
List.map (Html.map WishListMsg) (WishList.view wishList)
viewLogout : Page -> List (Html Msg)
viewLogout page =
let
session =
getSession page
in
case session of
Nothing ->
[]
Just s ->
[ nav [ class "nav nav-masthead justify-content-center" ]
[ span [] [ span [ class "text-muted" ] [ text "connecté en tant que " ], span [] [ text s.logged_user.name ] ]
, button [ class "btn", onClick Logout ]
[ text "Déconnexion" ]
]
]
centerMain : Page -> Bool
centerMain page =
case page of
Login _ ->
True
_ ->
False
getSession : Page -> Maybe Session
getSession page =
case page of
Login _ ->
Nothing
WishList wishlist ->
Just <| WishList.getSession wishlist
view : Model -> Browser.Document Msg
view { page, help } =
{ title = windowTitle page
, body =
(if help then
Help.modal ToggleHelp
else
[]
)
++ [ div [ class "cover-container d-flex w-100 h-100 p-3 mx-auto flex-column" ]
[ header [ class "masthead", classList [ ( "mb-auto", centerMain page ) ] ]
[ div [ class "inner" ]
(h3 [ class "masthead-brand" ]
[ text "Secret Wishlist" ]
:: viewLogout page
)
]
, main_ [ class "inner", classList [ ( "cover", centerMain page ) ], attribute "role" "main" ] (viewMain page)
, footer [ class "mastfoot mt-auto" ]
[ div [ class "inner" ]
[ p []
[ text "Créé par PI:NAME:<NAME>END_PI. Code source sur "
, a [ href "https://www.github.com/oadam/secret-wishlist" ]
[ text "Github" ]
]
]
]
]
]
}
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
main =
Browser.document { init = init, update = update, view = view, subscriptions = subscriptions }
| elm |
[
{
"context": ", a [ class \"grey-link\", href \"https://github.com/mhoare/elm-stack-demo\" ] [ text \"View the code!\" ]\n ",
"end": 1486,
"score": 0.9582905769,
"start": 1480,
"tag": "USERNAME",
"value": "mhoare"
},
{
"context": "text \"View the code!\" ]\n , text \"! — © 2017 Matthew Hoare\"\n ]\n\n\nstackOperationsPara =\n \"\"\"\n## Sta",
"end": 1571,
"score": 0.9998896122,
"start": 1558,
"tag": "NAME",
"value": "Matthew Hoare"
}
] | src/ViewHelpers.elm | mhoare/elm-stack-demo | 1 | module ViewHelpers exposing (..)
import Array
import Types exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Markdown
stackViewHelp : Int -> String -> Html Types.Msg
stackViewHelp i l =
div [ class "stackitem" ]
[ span [ class "stackindex" ] [ i |> toString |> text ]
, div [ class "stackdata" ] [ text l ]
]
stackView : List String -> Html Types.Msg
stackView data =
let
newlist =
if List.length data < 10 then
List.append data (Array.initialize (10 - List.length data) (always "") |> Array.toList)
else
data
in
div [ class "row" ]
[ div [ class "stackview col-sm-12 col-md-10 col-md-offset-1" ]
(List.reverse
(List.indexedMap
stackViewHelp
newlist
)
)
]
introView : Html Types.Msg
introView =
div []
[ div [ class "jumbotron" ]
[ div [ class "container" ] [ h1 [] [ text "Abstract Data Structures: Stacks" ], p [] [ text """
Stacks are great! They allow us to store data in a way where the last data item we add is the first
item which is returned.
""" ] ] ]
]
footer =
div [ class "footer" ]
[ text "All code for this site is written in Elm and open-sourced on Github."
, a [ class "grey-link", href "https://github.com/mhoare/elm-stack-demo" ] [ text "View the code!" ]
, text "! — © 2017 Matthew Hoare"
]
stackOperationsPara =
"""
## Stack operations
There are only two legal operations which can be carried out on a stack.
1. **Push**
1. **Pop**
What does it mean to push and pop? Well, keep reading and you'll find out.
### Push
When we talk about *pushing* onto the stack, what we really mean is adding a new item onto the top of the stack. Once we have *pushed* items onto the stack we can access the top element. Use the [interactive stack](#interactivestack) at the top of the page to see what I mean.
### Pop
Okay, so we have worked out how to add items to the stack, but what happens when we want to access them?
When we want to access items on the stack, we can only access and remove the top element.
This is called *popping*, you will *pop* the top element off of the stack.
You don't understand? Don't worry, lets give and example.
You have pushed the calculation shown above onto the stack. The stack now looks like this:
See, the top element is `1 + 2` and the second is `+ 3` and so on.
Now we are going to *pop* `1 + 2` off of the stack and evaluate it. Now the stack looks like this:
Did you notice that `1 + 2` is no longer on the top of the stack? It is now `+ 3`. So we *pop* that from the stack as well and evaluate that operation applied to our previous value. Our total is now 6.
We will continue this process until the stack is empty.
You may be thinking, "Why do you remove the item when popping it off?" The reason we do that is so that we can access the next item. Remember we can only access the top item in the stack.
"""
secondPara =
"""
## Stacks... Why?
You may be thinking - why would we want only want to access the last item we added?
Well, think about what happens when you use brackets in this calculation:
```( ( ( 1 + 2 ) + 3 ) + 4 )```
You first evalute the deepest brackets and then use that value when evaluating the brackets in which it was nested in and so on. Here you need to know calculate a value and then use that value in the next calculation.
**This is exactly where a stack would be used in computing.** Each operation would be pushed onto the stack, meaning that the `( 1 + 2 )` operation would be on the top of the stack. Then each item is popped off of the stack, evaluated and then the next item is popped off.
Stacks are also used when *calling procedures in programs* and *when reversing array items*.
"""
substituteNothing l =
case l of
Just l ->
l
Nothing ->
""
| 43917 | module ViewHelpers exposing (..)
import Array
import Types exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Markdown
stackViewHelp : Int -> String -> Html Types.Msg
stackViewHelp i l =
div [ class "stackitem" ]
[ span [ class "stackindex" ] [ i |> toString |> text ]
, div [ class "stackdata" ] [ text l ]
]
stackView : List String -> Html Types.Msg
stackView data =
let
newlist =
if List.length data < 10 then
List.append data (Array.initialize (10 - List.length data) (always "") |> Array.toList)
else
data
in
div [ class "row" ]
[ div [ class "stackview col-sm-12 col-md-10 col-md-offset-1" ]
(List.reverse
(List.indexedMap
stackViewHelp
newlist
)
)
]
introView : Html Types.Msg
introView =
div []
[ div [ class "jumbotron" ]
[ div [ class "container" ] [ h1 [] [ text "Abstract Data Structures: Stacks" ], p [] [ text """
Stacks are great! They allow us to store data in a way where the last data item we add is the first
item which is returned.
""" ] ] ]
]
footer =
div [ class "footer" ]
[ text "All code for this site is written in Elm and open-sourced on Github."
, a [ class "grey-link", href "https://github.com/mhoare/elm-stack-demo" ] [ text "View the code!" ]
, text "! — © 2017 <NAME>"
]
stackOperationsPara =
"""
## Stack operations
There are only two legal operations which can be carried out on a stack.
1. **Push**
1. **Pop**
What does it mean to push and pop? Well, keep reading and you'll find out.
### Push
When we talk about *pushing* onto the stack, what we really mean is adding a new item onto the top of the stack. Once we have *pushed* items onto the stack we can access the top element. Use the [interactive stack](#interactivestack) at the top of the page to see what I mean.
### Pop
Okay, so we have worked out how to add items to the stack, but what happens when we want to access them?
When we want to access items on the stack, we can only access and remove the top element.
This is called *popping*, you will *pop* the top element off of the stack.
You don't understand? Don't worry, lets give and example.
You have pushed the calculation shown above onto the stack. The stack now looks like this:
See, the top element is `1 + 2` and the second is `+ 3` and so on.
Now we are going to *pop* `1 + 2` off of the stack and evaluate it. Now the stack looks like this:
Did you notice that `1 + 2` is no longer on the top of the stack? It is now `+ 3`. So we *pop* that from the stack as well and evaluate that operation applied to our previous value. Our total is now 6.
We will continue this process until the stack is empty.
You may be thinking, "Why do you remove the item when popping it off?" The reason we do that is so that we can access the next item. Remember we can only access the top item in the stack.
"""
secondPara =
"""
## Stacks... Why?
You may be thinking - why would we want only want to access the last item we added?
Well, think about what happens when you use brackets in this calculation:
```( ( ( 1 + 2 ) + 3 ) + 4 )```
You first evalute the deepest brackets and then use that value when evaluating the brackets in which it was nested in and so on. Here you need to know calculate a value and then use that value in the next calculation.
**This is exactly where a stack would be used in computing.** Each operation would be pushed onto the stack, meaning that the `( 1 + 2 )` operation would be on the top of the stack. Then each item is popped off of the stack, evaluated and then the next item is popped off.
Stacks are also used when *calling procedures in programs* and *when reversing array items*.
"""
substituteNothing l =
case l of
Just l ->
l
Nothing ->
""
| true | module ViewHelpers exposing (..)
import Array
import Types exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Markdown
stackViewHelp : Int -> String -> Html Types.Msg
stackViewHelp i l =
div [ class "stackitem" ]
[ span [ class "stackindex" ] [ i |> toString |> text ]
, div [ class "stackdata" ] [ text l ]
]
stackView : List String -> Html Types.Msg
stackView data =
let
newlist =
if List.length data < 10 then
List.append data (Array.initialize (10 - List.length data) (always "") |> Array.toList)
else
data
in
div [ class "row" ]
[ div [ class "stackview col-sm-12 col-md-10 col-md-offset-1" ]
(List.reverse
(List.indexedMap
stackViewHelp
newlist
)
)
]
introView : Html Types.Msg
introView =
div []
[ div [ class "jumbotron" ]
[ div [ class "container" ] [ h1 [] [ text "Abstract Data Structures: Stacks" ], p [] [ text """
Stacks are great! They allow us to store data in a way where the last data item we add is the first
item which is returned.
""" ] ] ]
]
footer =
div [ class "footer" ]
[ text "All code for this site is written in Elm and open-sourced on Github."
, a [ class "grey-link", href "https://github.com/mhoare/elm-stack-demo" ] [ text "View the code!" ]
, text "! — © 2017 PI:NAME:<NAME>END_PI"
]
stackOperationsPara =
"""
## Stack operations
There are only two legal operations which can be carried out on a stack.
1. **Push**
1. **Pop**
What does it mean to push and pop? Well, keep reading and you'll find out.
### Push
When we talk about *pushing* onto the stack, what we really mean is adding a new item onto the top of the stack. Once we have *pushed* items onto the stack we can access the top element. Use the [interactive stack](#interactivestack) at the top of the page to see what I mean.
### Pop
Okay, so we have worked out how to add items to the stack, but what happens when we want to access them?
When we want to access items on the stack, we can only access and remove the top element.
This is called *popping*, you will *pop* the top element off of the stack.
You don't understand? Don't worry, lets give and example.
You have pushed the calculation shown above onto the stack. The stack now looks like this:
See, the top element is `1 + 2` and the second is `+ 3` and so on.
Now we are going to *pop* `1 + 2` off of the stack and evaluate it. Now the stack looks like this:
Did you notice that `1 + 2` is no longer on the top of the stack? It is now `+ 3`. So we *pop* that from the stack as well and evaluate that operation applied to our previous value. Our total is now 6.
We will continue this process until the stack is empty.
You may be thinking, "Why do you remove the item when popping it off?" The reason we do that is so that we can access the next item. Remember we can only access the top item in the stack.
"""
secondPara =
"""
## Stacks... Why?
You may be thinking - why would we want only want to access the last item we added?
Well, think about what happens when you use brackets in this calculation:
```( ( ( 1 + 2 ) + 3 ) + 4 )```
You first evalute the deepest brackets and then use that value when evaluating the brackets in which it was nested in and so on. Here you need to know calculate a value and then use that value in the next calculation.
**This is exactly where a stack would be used in computing.** Each operation would be pushed onto the stack, meaning that the `( 1 + 2 )` operation would be on the top of the stack. Then each item is popped off of the stack, evaluated and then the next item is popped off.
Stacks are also used when *calling procedures in programs* and *when reversing array items*.
"""
substituteNothing l =
case l of
Just l ->
l
Nothing ->
""
| elm |
[
{
"context": "\n , \"lapel\"\n , \"start\"\n , \"greet\"\n , \"goner\"\n , \"golem\"\n , \"lusty\"\n , \"loopy\"\n , ",
"end": 1287,
"score": 0.8838607073,
"start": 1282,
"tag": "NAME",
"value": "goner"
},
{
"context": "\n , \"start\"\n , \"greet\"\n , \"goner\"\n , \"golem\"\n , \"lusty\"\n , \"loopy\"\n , \"round\"\n , ",
"end": 1301,
"score": 0.9364655614,
"start": 1296,
"tag": "NAME",
"value": "golem"
},
{
"context": "\n , \"greet\"\n , \"goner\"\n , \"golem\"\n , \"lusty\"\n , \"loopy\"\n , \"round\"\n , \"audit\"\n ,",
"end": 1314,
"score": 0.7809064388,
"start": 1310,
"tag": "NAME",
"value": "lust"
},
{
"context": "\n , \"islet\"\n , \"civic\"\n , \"forge\"\n , \"corny\"\n , \"moult\"\n , \"basic\"\n , \"salad\"\n , ",
"end": 1455,
"score": 0.9376015663,
"start": 1450,
"tag": "NAME",
"value": "corny"
},
{
"context": "\n , \"badly\"\n , \"smart\"\n , \"pithy\"\n , \"gaudy\"\n , \"chill\"\n , \"heron\"\n , \"vodka\"\n , ",
"end": 2169,
"score": 0.7416349649,
"start": 2164,
"tag": "NAME",
"value": "gaudy"
},
{
"context": "\n , \"smart\"\n , \"pithy\"\n , \"gaudy\"\n , \"chill\"\n , \"heron\"\n , \"vodka\"\n , \"finer\"\n , ",
"end": 2183,
"score": 0.7506069541,
"start": 2178,
"tag": "NAME",
"value": "chill"
},
{
"context": "\n , \"pithy\"\n , \"gaudy\"\n , \"chill\"\n , \"heron\"\n , \"vodka\"\n , \"finer\"\n , \"surer\"\n , ",
"end": 2197,
"score": 0.8656498194,
"start": 2192,
"tag": "NAME",
"value": "heron"
},
{
"context": "\n , \"gaudy\"\n , \"chill\"\n , \"heron\"\n , \"vodka\"\n , \"finer\"\n , \"surer\"\n , \"radio\"\n , ",
"end": 2211,
"score": 0.9544847012,
"start": 2206,
"tag": "NAME",
"value": "vodka"
},
{
"context": "\n , \"chill\"\n , \"heron\"\n , \"vodka\"\n , \"finer\"\n , \"surer\"\n , \"radio\"\n , \"rouge\"\n , ",
"end": 2225,
"score": 0.8289997578,
"start": 2220,
"tag": "NAME",
"value": "finer"
},
{
"context": "\n , \"heron\"\n , \"vodka\"\n , \"finer\"\n , \"surer\"\n , \"radio\"\n , \"rouge\"\n , \"perch\"\n , ",
"end": 2239,
"score": 0.848412931,
"start": 2234,
"tag": "NAME",
"value": "surer"
},
{
"context": "\n , \"finer\"\n , \"surer\"\n , \"radio\"\n , \"rouge\"\n , \"perch\"\n , \"retch\"\n , \"wrote\"\n , ",
"end": 2267,
"score": 0.6037120819,
"start": 2262,
"tag": "NAME",
"value": "rouge"
},
{
"context": "\n , \"surer\"\n , \"radio\"\n , \"rouge\"\n , \"perch\"\n , \"retch\"\n , \"wrote\"\n , \"clock\"\n , ",
"end": 2281,
"score": 0.6103055477,
"start": 2276,
"tag": "NAME",
"value": "perch"
},
{
"context": "\n , \"break\"\n , \"rhino\"\n , \"viral\"\n , \"conic\"\n , \"masse\"\n , \"sonic\"\n , \"vital\"\n , ",
"end": 2533,
"score": 0.6393893361,
"start": 2528,
"tag": "NAME",
"value": "conic"
},
{
"context": "\n , \"rhino\"\n , \"viral\"\n , \"conic\"\n , \"masse\"\n , \"sonic\"\n , \"vital\"\n , \"trace\"\n , ",
"end": 2547,
"score": 0.7248339057,
"start": 2542,
"tag": "NAME",
"value": "masse"
},
{
"context": "\n , \"trace\"\n , \"using\"\n , \"peach\"\n , \"champ\"\n , \"baton\"\n , \"brake\"\n , \"pluck\"\n , ",
"end": 2631,
"score": 0.6685496569,
"start": 2626,
"tag": "NAME",
"value": "champ"
},
{
"context": "\n , \"using\"\n , \"peach\"\n , \"champ\"\n , \"baton\"\n , \"brake\"\n , \"pluck\"\n , \"craze\"\n , ",
"end": 2645,
"score": 0.5854182243,
"start": 2640,
"tag": "NAME",
"value": "baton"
},
{
"context": "\n , \"brake\"\n , \"pluck\"\n , \"craze\"\n , \"gripe\"\n , \"weary\"\n , \"picky\"\n , \"acute\"\n , ",
"end": 2701,
"score": 0.6314152479,
"start": 2696,
"tag": "NAME",
"value": "gripe"
},
{
"context": "\n , \"weary\"\n , \"picky\"\n , \"acute\"\n , \"ferry\"\n , \"aside\"\n , \"tapir\"\n , \"troll\"\n , ",
"end": 2757,
"score": 0.5588638783,
"start": 2752,
"tag": "NAME",
"value": "ferry"
},
{
"context": "\n , \"proxy\"\n , \"point\"\n , \"robot\"\n , \"prick\"\n , \"wince\"\n , \"crimp\"\n , \"knoll\"\n ",
"end": 3104,
"score": 0.6903079152,
"start": 3102,
"tag": "NAME",
"value": "pr"
},
{
"context": "\n , \"point\"\n , \"robot\"\n , \"prick\"\n , \"wince\"\n , \"crimp\"\n , \"knoll\"\n , \"sugar\"\n ",
"end": 3117,
"score": 0.5134197474,
"start": 3116,
"tag": "NAME",
"value": "w"
},
{
"context": "\n , \"robot\"\n , \"prick\"\n , \"wince\"\n , \"crimp\"\n , \"knoll\"\n , \"sugar\"\n , \"whack\"\n , ",
"end": 3135,
"score": 0.7718532085,
"start": 3130,
"tag": "NAME",
"value": "crimp"
},
{
"context": "\n , \"prick\"\n , \"wince\"\n , \"crimp\"\n , \"knoll\"\n , \"sugar\"\n , \"whack\"\n , \"mount\"\n , ",
"end": 3149,
"score": 0.6417549253,
"start": 3144,
"tag": "NAME",
"value": "knoll"
},
{
"context": "\n , \"pause\"\n , \"ulcer\"\n , \"ultra\"\n , \"robin\"\n , \"cynic\"\n , \"agora\"\n , \"aroma\"\n , ",
"end": 3429,
"score": 0.9014858007,
"start": 3424,
"tag": "NAME",
"value": "robin"
},
{
"context": "\n , \"ulcer\"\n , \"ultra\"\n , \"robin\"\n , \"cynic\"\n , \"agora\"\n , \"aroma\"\n , \"caulk\"\n , ",
"end": 3443,
"score": 0.5478473306,
"start": 3438,
"tag": "NAME",
"value": "cynic"
},
{
"context": "\n , \"ultra\"\n , \"robin\"\n , \"cynic\"\n , \"agora\"\n , \"aroma\"\n , \"caulk\"\n , \"shake\"\n , ",
"end": 3457,
"score": 0.5926859379,
"start": 3452,
"tag": "NAME",
"value": "agora"
},
{
"context": "\n , \"cynic\"\n , \"agora\"\n , \"aroma\"\n , \"caulk\"\n , \"shake\"\n , \"pupal\"\n , \"dodge\"\n , ",
"end": 3485,
"score": 0.6183431149,
"start": 3480,
"tag": "NAME",
"value": "caulk"
},
{
"context": "\n , \"nymph\"\n , \"found\"\n , \"shall\"\n , \"harry\"\n , \"stove\"\n , \"lowly\"\n , \"snout\"\n ",
"end": 4097,
"score": 0.6173700094,
"start": 4096,
"tag": "NAME",
"value": "h"
},
{
"context": "\n , \"cheek\"\n , \"ample\"\n , \"flair\"\n , \"foyer\"\n , \"cargo\"\n , \"oxide\"\n , \"plant\"\n ",
"end": 4420,
"score": 0.7571387887,
"start": 4418,
"tag": "NAME",
"value": "fo"
},
{
"context": "\n , \"plant\"\n , \"olive\"\n , \"inert\"\n , \"askew\"\n , \"heist\"\n , \"shown\"\n , \"zesty\"\n ",
"end": 4505,
"score": 0.5963119268,
"start": 4502,
"tag": "NAME",
"value": "ask"
},
{
"context": "\n , \"hasty\"\n , \"trash\"\n , \"fella\"\n , \"larva\"\n , \"forgo\"\n , \"story\"\n , \"hairy\"\n , ",
"end": 4605,
"score": 0.9072220325,
"start": 4600,
"tag": "NAME",
"value": "larva"
},
{
"context": "\n , \"trash\"\n , \"fella\"\n , \"larva\"\n , \"forgo\"\n , \"story\"\n , \"hairy\"\n , \"train\"\n , ",
"end": 4619,
"score": 0.8060035706,
"start": 4614,
"tag": "NAME",
"value": "forgo"
},
{
"context": "\n , \"homer\"\n , \"badge\"\n , \"midst\"\n , \"canny\"\n , \"fetus\"\n , \"butch\"\n , \"farce\"\n , ",
"end": 4717,
"score": 0.8284919262,
"start": 4712,
"tag": "NAME",
"value": "canny"
},
{
"context": "\n , \"badge\"\n , \"midst\"\n , \"canny\"\n , \"fetus\"\n , \"butch\"\n , \"farce\"\n , \"slung\"\n , ",
"end": 4731,
"score": 0.6896085143,
"start": 4726,
"tag": "NAME",
"value": "fetus"
},
{
"context": "\n , \"crept\"\n , \"bayou\"\n , \"atoll\"\n , \"manor\"\n , \"creak\"\n , \"showy\"\n , \"phase\"\n , ",
"end": 5039,
"score": 0.9698956013,
"start": 5034,
"tag": "NAME",
"value": "manor"
},
{
"context": "\n , \"bayou\"\n , \"atoll\"\n , \"manor\"\n , \"creak\"\n , \"showy\"\n , \"phase\"\n , \"froth\"\n , ",
"end": 5053,
"score": 0.714685142,
"start": 5048,
"tag": "NAME",
"value": "creak"
},
{
"context": "\n , \"payer\"\n , \"goose\"\n , \"float\"\n , \"donor\"\n , \"atone\"\n , \"primo\"\n , \"apron\"\n , ",
"end": 5235,
"score": 0.5951023102,
"start": 5230,
"tag": "NAME",
"value": "donor"
},
{
"context": "\n , \"donor\"\n , \"atone\"\n , \"primo\"\n , \"apron\"\n , \"blown\"\n , \"cacao\"\n , \"loser\"\n , ",
"end": 5277,
"score": 0.7431650162,
"start": 5272,
"tag": "NAME",
"value": "apron"
},
{
"context": " , \"beady\"\n , \"rusty\"\n , \"retro\"\n , \"droll\"\n , \"gawky\"\n , \"hutch\"\n , \"pinto\"\n , ",
"end": 5445,
"score": 0.5330398679,
"start": 5441,
"tag": "NAME",
"value": "roll"
},
{
"context": " , \"rusty\"\n , \"retro\"\n , \"droll\"\n , \"gawky\"\n , \"hutch\"\n , \"pinto\"\n , \"gaily\"\n , ",
"end": 5459,
"score": 0.5317469239,
"start": 5457,
"tag": "NAME",
"value": "ky"
},
{
"context": "\n , \"retro\"\n , \"droll\"\n , \"gawky\"\n , \"hutch\"\n , \"pinto\"\n , \"gaily\"\n , \"egret\"\n , ",
"end": 5473,
"score": 0.5247965455,
"start": 5468,
"tag": "NAME",
"value": "hutch"
},
{
"context": "\n , \"gawky\"\n , \"hutch\"\n , \"pinto\"\n , \"gaily\"\n , \"egret\"\n , \"lilac\"\n , \"sever\"\n ",
"end": 5497,
"score": 0.7305220962,
"start": 5496,
"tag": "NAME",
"value": "g"
},
{
"context": "\n , \"hutch\"\n , \"pinto\"\n , \"gaily\"\n , \"egret\"\n , \"lilac\"\n , \"sever\"\n , \"field\"\n , ",
"end": 5515,
"score": 0.5699307919,
"start": 5510,
"tag": "NAME",
"value": "egret"
},
{
"context": "\n , \"pinto\"\n , \"gaily\"\n , \"egret\"\n , \"lilac\"\n , \"sever\"\n , \"field\"\n , \"fluff\"\n , ",
"end": 5529,
"score": 0.9311846495,
"start": 5524,
"tag": "NAME",
"value": "lilac"
},
{
"context": "\n , \"gaily\"\n , \"egret\"\n , \"lilac\"\n , \"sever\"\n , \"field\"\n , \"fluff\"\n , \"hydro\"\n , ",
"end": 5543,
"score": 0.6181584597,
"start": 5538,
"tag": "NAME",
"value": "sever"
},
{
"context": "\n , \"fluff\"\n , \"hydro\"\n , \"flack\"\n , \"agape\"\n , \"wench\"\n , \"voice\"\n , \"stead\"\n , ",
"end": 5613,
"score": 0.7244880795,
"start": 5608,
"tag": "NAME",
"value": "agape"
},
{
"context": "\n , \"voice\"\n , \"stead\"\n , \"stalk\"\n , \"berth\"\n , \"madam\"\n , \"night\"\n , \"bland\"\n , ",
"end": 5683,
"score": 0.8465611935,
"start": 5678,
"tag": "NAME",
"value": "berth"
},
{
"context": "\n , \"stead\"\n , \"stalk\"\n , \"berth\"\n , \"madam\"\n , \"night\"\n , \"bland\"\n , \"liver\"\n , ",
"end": 5697,
"score": 0.9359747171,
"start": 5692,
"tag": "NAME",
"value": "madam"
},
{
"context": "\n , \"bland\"\n , \"liver\"\n , \"wedge\"\n , \"augur\"\n , \"roomy\"\n , \"wacky\"\n , \"flock\"\n , ",
"end": 5767,
"score": 0.7919954658,
"start": 5762,
"tag": "NAME",
"value": "augur"
},
{
"context": "\n , \"wacky\"\n , \"flock\"\n , \"angry\"\n , \"bobby\"\n , \"trite\"\n , \"aphid\"\n , \"tryst\"\n , ",
"end": 5837,
"score": 0.8081068993,
"start": 5832,
"tag": "NAME",
"value": "bobby"
},
{
"context": " , \"flock\"\n , \"angry\"\n , \"bobby\"\n , \"trite\"\n , \"aphid\"\n , \"tryst\"\n , \"midge\"\n , ",
"end": 5851,
"score": 0.5698434711,
"start": 5848,
"tag": "NAME",
"value": "ite"
},
{
"context": "\n , \"angry\"\n , \"bobby\"\n , \"trite\"\n , \"aphid\"\n , \"tryst\"\n , \"midge\"\n , \"power\"\n , ",
"end": 5865,
"score": 0.848315537,
"start": 5860,
"tag": "NAME",
"value": "aphid"
},
{
"context": "\n , \"alien\"\n , \"smear\"\n , \"unfit\"\n , \"patty\"\n , \"cling\"\n , \"glean\"\n , \"label\"\n ",
"end": 6129,
"score": 0.7018748522,
"start": 6126,
"tag": "NAME",
"value": "pat"
},
{
"context": "\n , \"cling\"\n , \"glean\"\n , \"label\"\n , \"hunky\"\n , \"khaki\"\n , \"poker\"\n , \"gruel\"\n , ",
"end": 6187,
"score": 0.7919757962,
"start": 6182,
"tag": "NAME",
"value": "hunky"
},
{
"context": "\n , \"glean\"\n , \"label\"\n , \"hunky\"\n , \"khaki\"\n , \"poker\"\n , \"gruel\"\n , \"twice\"\n , ",
"end": 6201,
"score": 0.6881097555,
"start": 6196,
"tag": "NAME",
"value": "khaki"
},
{
"context": "\n , \"hunky\"\n , \"khaki\"\n , \"poker\"\n , \"gruel\"\n , \"twice\"\n , \"twang\"\n , \"shrug\"\n , ",
"end": 6229,
"score": 0.8197034597,
"start": 6224,
"tag": "NAME",
"value": "gruel"
},
{
"context": "\n , \"spilt\"\n , \"apple\"\n , \"slack\"\n , \"honey\"\n , \"final\"\n , \"sheen\"\n , \"eerie\"\n , ",
"end": 8721,
"score": 0.8673717976,
"start": 8716,
"tag": "NAME",
"value": "honey"
},
{
"context": "\n , \"slack\"\n , \"honey\"\n , \"final\"\n , \"sheen\"\n , \"eerie\"\n , \"minty\"\n , \"slick\"\n , ",
"end": 8749,
"score": 0.6960589886,
"start": 8744,
"tag": "NAME",
"value": "sheen"
},
{
"context": "\n , \"honey\"\n , \"final\"\n , \"sheen\"\n , \"eerie\"\n , \"minty\"\n , \"slick\"\n , \"derby\"\n , ",
"end": 8763,
"score": 0.9234853387,
"start": 8758,
"tag": "NAME",
"value": "eerie"
},
{
"context": "\n , \"final\"\n , \"sheen\"\n , \"eerie\"\n , \"minty\"\n , \"slick\"\n , \"derby\"\n , \"wharf\"\n , ",
"end": 8777,
"score": 0.7078262568,
"start": 8772,
"tag": "NAME",
"value": "minty"
},
{
"context": "\n , \"sheen\"\n , \"eerie\"\n , \"minty\"\n , \"slick\"\n , \"derby\"\n , \"wharf\"\n , \"spelt\"\n , ",
"end": 8791,
"score": 0.6534386873,
"start": 8786,
"tag": "NAME",
"value": "slick"
},
{
"context": "\n , \"eerie\"\n , \"minty\"\n , \"slick\"\n , \"derby\"\n , \"wharf\"\n , \"spelt\"\n , \"coach\"\n , ",
"end": 8805,
"score": 0.9086797237,
"start": 8800,
"tag": "NAME",
"value": "derby"
},
{
"context": "\n , \"minty\"\n , \"slick\"\n , \"derby\"\n , \"wharf\"\n , \"spelt\"\n , \"coach\"\n , \"erupt\"\n ",
"end": 8816,
"score": 0.5775403976,
"start": 8814,
"tag": "NAME",
"value": "wh"
},
{
"context": "\n , \"spelt\"\n , \"coach\"\n , \"erupt\"\n , \"singe\"\n , \"price\"\n , \"spawn\"\n , \"fairy\"\n , ",
"end": 8875,
"score": 0.8143404722,
"start": 8870,
"tag": "NAME",
"value": "singe"
},
{
"context": "\n , \"price\"\n , \"spawn\"\n , \"fairy\"\n , \"jiffy\"\n , \"filmy\"\n , \"stack\"\n , \"chose\"\n , ",
"end": 8931,
"score": 0.8925789595,
"start": 8926,
"tag": "NAME",
"value": "jiffy"
},
{
"context": "\n , \"spawn\"\n , \"fairy\"\n , \"jiffy\"\n , \"filmy\"\n , \"stack\"\n , \"chose\"\n , \"sleep\"\n , ",
"end": 8945,
"score": 0.9664675593,
"start": 8940,
"tag": "NAME",
"value": "filmy"
},
{
"context": "\n , \"stack\"\n , \"chose\"\n , \"sleep\"\n , \"ardor\"\n , \"nanny\"\n , \"niece\"\n , \"woozy\"\n , ",
"end": 9001,
"score": 0.8947924972,
"start": 8996,
"tag": "NAME",
"value": "ardor"
},
{
"context": "\n , \"chose\"\n , \"sleep\"\n , \"ardor\"\n , \"nanny\"\n , \"niece\"\n , \"woozy\"\n , \"handy\"\n , ",
"end": 9015,
"score": 0.9702222943,
"start": 9010,
"tag": "NAME",
"value": "nanny"
},
{
"context": "\n , \"woozy\"\n , \"handy\"\n , \"grace\"\n , \"ditto\"\n , \"stank\"\n , \"cream\"\n , \"usual\"\n ",
"end": 9083,
"score": 0.502066493,
"start": 9080,
"tag": "NAME",
"value": "dit"
},
{
"context": "\n , \"valor\"\n , \"angle\"\n , \"ninja\"\n , \"muddy\"\n , \"chase\"\n , \"reply\"\n , \"prone\"\n , ",
"end": 9197,
"score": 0.9040486813,
"start": 9192,
"tag": "NAME",
"value": "muddy"
},
{
"context": "\n , \"heart\"\n , \"shade\"\n , \"diner\"\n , \"arson\"\n , \"onion\"\n , \"sleet\"\n , \"dowel\"\n , ",
"end": 9309,
"score": 0.9376637936,
"start": 9304,
"tag": "NAME",
"value": "arson"
},
{
"context": "\n , \"shade\"\n , \"diner\"\n , \"arson\"\n , \"onion\"\n , \"sleet\"\n , \"dowel\"\n , \"couch\"\n , ",
"end": 9323,
"score": 0.7241462469,
"start": 9318,
"tag": "NAME",
"value": "onion"
},
{
"context": "\n , \"diner\"\n , \"arson\"\n , \"onion\"\n , \"sleet\"\n , \"dowel\"\n , \"couch\"\n , \"palsy\"\n , ",
"end": 9337,
"score": 0.6332947016,
"start": 9332,
"tag": "NAME",
"value": "sleet"
},
{
"context": " , \"sleet\"\n , \"dowel\"\n , \"couch\"\n , \"palsy\"\n , \"bowel\"\n , \"smile\"\n , \"evoke\"\n , ",
"end": 9379,
"score": 0.5823989511,
"start": 9375,
"tag": "NAME",
"value": "alsy"
},
{
"context": " , \"built\"\n , \"embed\"\n , \"award\"\n , \"dross\"\n , \"annul\"\n , \"goody\"\n , \"frown\"\n , ",
"end": 9547,
"score": 0.5849559903,
"start": 9543,
"tag": "NAME",
"value": "ross"
},
{
"context": "\n , \"embed\"\n , \"award\"\n , \"dross\"\n , \"annul\"\n , \"goody\"\n , \"frown\"\n , \"patio\"\n , ",
"end": 9561,
"score": 0.7201468349,
"start": 9556,
"tag": "NAME",
"value": "annul"
},
{
"context": "\n , \"award\"\n , \"dross\"\n , \"annul\"\n , \"goody\"\n , \"frown\"\n , \"patio\"\n , \"laden\"\n , ",
"end": 9575,
"score": 0.7679315805,
"start": 9570,
"tag": "NAME",
"value": "goody"
},
{
"context": "\n , \"acorn\"\n , \"aping\"\n , \"pushy\"\n , \"tamer\"\n , \"hater\"\n , \"mania\"\n , \"awoke\"\n , ",
"end": 9967,
"score": 0.7601409554,
"start": 9962,
"tag": "NAME",
"value": "tamer"
},
{
"context": "\n , \"aping\"\n , \"pushy\"\n , \"tamer\"\n , \"hater\"\n , \"mania\"\n , \"awoke\"\n , \"brawn\"\n , ",
"end": 9981,
"score": 0.9947989583,
"start": 9976,
"tag": "NAME",
"value": "hater"
},
{
"context": "\n , \"pushy\"\n , \"tamer\"\n , \"hater\"\n , \"mania\"\n , \"awoke\"\n , \"brawn\"\n , \"swift\"\n , ",
"end": 9995,
"score": 0.9984608889,
"start": 9990,
"tag": "NAME",
"value": "mania"
},
{
"context": "\n , \"tamer\"\n , \"hater\"\n , \"mania\"\n , \"awoke\"\n , \"brawn\"\n , \"swift\"\n , \"exile\"\n , ",
"end": 10009,
"score": 0.9956775308,
"start": 10004,
"tag": "NAME",
"value": "awoke"
},
{
"context": "\n , \"hater\"\n , \"mania\"\n , \"awoke\"\n , \"brawn\"\n , \"swift\"\n , \"exile\"\n , \"birch\"\n , ",
"end": 10023,
"score": 0.9966160655,
"start": 10018,
"tag": "NAME",
"value": "brawn"
},
{
"context": "\n , \"mania\"\n , \"awoke\"\n , \"brawn\"\n , \"swift\"\n , \"exile\"\n , \"birch\"\n , \"lucky\"\n , ",
"end": 10037,
"score": 0.9862889051,
"start": 10032,
"tag": "NAME",
"value": "swift"
},
{
"context": "\n , \"awoke\"\n , \"brawn\"\n , \"swift\"\n , \"exile\"\n , \"birch\"\n , \"lucky\"\n , \"freer\"\n ",
"end": 10048,
"score": 0.5251361132,
"start": 10046,
"tag": "NAME",
"value": "ex"
},
{
"context": "\n , \"brawn\"\n , \"swift\"\n , \"exile\"\n , \"birch\"\n , \"lucky\"\n , \"freer\"\n , \"risky\"\n , ",
"end": 10065,
"score": 0.9835987687,
"start": 10060,
"tag": "NAME",
"value": "birch"
},
{
"context": "\n , \"swift\"\n , \"exile\"\n , \"birch\"\n , \"lucky\"\n , \"freer\"\n , \"risky\"\n , \"ghost\"\n , ",
"end": 10079,
"score": 0.9722685814,
"start": 10074,
"tag": "NAME",
"value": "lucky"
},
{
"context": "\n , \"exile\"\n , \"birch\"\n , \"lucky\"\n , \"freer\"\n , \"risky\"\n , \"ghost\"\n , \"plier\"\n , ",
"end": 10093,
"score": 0.9968717098,
"start": 10088,
"tag": "NAME",
"value": "freer"
},
{
"context": "\n , \"birch\"\n , \"lucky\"\n , \"freer\"\n , \"risky\"\n , \"ghost\"\n , \"plier\"\n , \"lunar\"\n , ",
"end": 10107,
"score": 0.9949210882,
"start": 10102,
"tag": "NAME",
"value": "risky"
},
{
"context": "\n , \"lucky\"\n , \"freer\"\n , \"risky\"\n , \"ghost\"\n , \"plier\"\n , \"lunar\"\n , \"winch\"\n , ",
"end": 10121,
"score": 0.9934099317,
"start": 10116,
"tag": "NAME",
"value": "ghost"
},
{
"context": "\n , \"freer\"\n , \"risky\"\n , \"ghost\"\n , \"plier\"\n , \"lunar\"\n , \"winch\"\n , \"snare\"\n , ",
"end": 10135,
"score": 0.996860981,
"start": 10130,
"tag": "NAME",
"value": "plier"
},
{
"context": "\n , \"risky\"\n , \"ghost\"\n , \"plier\"\n , \"lunar\"\n , \"winch\"\n , \"snare\"\n , \"nurse\"\n , ",
"end": 10149,
"score": 0.9952195883,
"start": 10144,
"tag": "NAME",
"value": "lunar"
},
{
"context": "\n , \"ghost\"\n , \"plier\"\n , \"lunar\"\n , \"winch\"\n , \"snare\"\n , \"nurse\"\n , \"house\"\n , ",
"end": 10163,
"score": 0.9943158031,
"start": 10158,
"tag": "NAME",
"value": "winch"
},
{
"context": "\n , \"plier\"\n , \"lunar\"\n , \"winch\"\n , \"snare\"\n , \"nurse\"\n , \"house\"\n , \"borax\"\n , ",
"end": 10177,
"score": 0.9931319952,
"start": 10172,
"tag": "NAME",
"value": "snare"
},
{
"context": "\n , \"lunar\"\n , \"winch\"\n , \"snare\"\n , \"nurse\"\n , \"house\"\n , \"borax\"\n , \"nicer\"\n , ",
"end": 10191,
"score": 0.9885786772,
"start": 10186,
"tag": "NAME",
"value": "nurse"
},
{
"context": "\n , \"snare\"\n , \"nurse\"\n , \"house\"\n , \"borax\"\n , \"nicer\"\n , \"lurch\"\n , \"exalt\"\n , ",
"end": 10219,
"score": 0.994985342,
"start": 10214,
"tag": "NAME",
"value": "borax"
},
{
"context": "\n , \"nurse\"\n , \"house\"\n , \"borax\"\n , \"nicer\"\n , \"lurch\"\n , \"exalt\"\n , \"about\"\n , ",
"end": 10233,
"score": 0.9798840284,
"start": 10228,
"tag": "NAME",
"value": "nicer"
},
{
"context": "\n , \"house\"\n , \"borax\"\n , \"nicer\"\n , \"lurch\"\n , \"exalt\"\n , \"about\"\n , \"savvy\"\n , ",
"end": 10247,
"score": 0.817950964,
"start": 10242,
"tag": "NAME",
"value": "lurch"
},
{
"context": " , \"borax\"\n , \"nicer\"\n , \"lurch\"\n , \"exalt\"\n , \"about\"\n , \"savvy\"\n , \"toxin\"\n , ",
"end": 10261,
"score": 0.602055788,
"start": 10258,
"tag": "NAME",
"value": "alt"
},
{
"context": "\n , \"lurch\"\n , \"exalt\"\n , \"about\"\n , \"savvy\"\n , \"toxin\"\n , \"tunic\"\n , \"pried\"\n , ",
"end": 10289,
"score": 0.7997847795,
"start": 10284,
"tag": "NAME",
"value": "savvy"
},
{
"context": "\n , \"exalt\"\n , \"about\"\n , \"savvy\"\n , \"toxin\"\n , \"tunic\"\n , \"pried\"\n , \"inlay\"\n , ",
"end": 10303,
"score": 0.9326374531,
"start": 10298,
"tag": "NAME",
"value": "toxin"
},
{
"context": "\n , \"about\"\n , \"savvy\"\n , \"toxin\"\n , \"tunic\"\n , \"pried\"\n , \"inlay\"\n , \"chump\"\n , ",
"end": 10317,
"score": 0.9895863533,
"start": 10312,
"tag": "NAME",
"value": "tunic"
},
{
"context": "\n , \"savvy\"\n , \"toxin\"\n , \"tunic\"\n , \"pried\"\n , \"inlay\"\n , \"chump\"\n , \"lanky\"\n , ",
"end": 10331,
"score": 0.9604920149,
"start": 10326,
"tag": "NAME",
"value": "pried"
},
{
"context": "\n , \"toxin\"\n , \"tunic\"\n , \"pried\"\n , \"inlay\"\n , \"chump\"\n , \"lanky\"\n , \"cress\"\n , ",
"end": 10345,
"score": 0.9841718674,
"start": 10340,
"tag": "NAME",
"value": "inlay"
},
{
"context": "\n , \"tunic\"\n , \"pried\"\n , \"inlay\"\n , \"chump\"\n , \"lanky\"\n , \"cress\"\n , \"eater\"\n , ",
"end": 10359,
"score": 0.992744267,
"start": 10354,
"tag": "NAME",
"value": "chump"
},
{
"context": "\n , \"pried\"\n , \"inlay\"\n , \"chump\"\n , \"lanky\"\n , \"cress\"\n , \"eater\"\n , \"elude\"\n , ",
"end": 10373,
"score": 0.9674041867,
"start": 10368,
"tag": "NAME",
"value": "lanky"
},
{
"context": "\n , \"inlay\"\n , \"chump\"\n , \"lanky\"\n , \"cress\"\n , \"eater\"\n , \"elude\"\n , \"cycle\"\n , ",
"end": 10387,
"score": 0.9721864462,
"start": 10382,
"tag": "NAME",
"value": "cress"
},
{
"context": "\n , \"chump\"\n , \"lanky\"\n , \"cress\"\n , \"eater\"\n , \"elude\"\n , \"cycle\"\n , \"kitty\"\n , ",
"end": 10401,
"score": 0.9718191624,
"start": 10396,
"tag": "NAME",
"value": "eater"
},
{
"context": "\n , \"lanky\"\n , \"cress\"\n , \"eater\"\n , \"elude\"\n , \"cycle\"\n , \"kitty\"\n , \"boule\"\n , ",
"end": 10415,
"score": 0.9569865465,
"start": 10410,
"tag": "NAME",
"value": "elude"
},
{
"context": "\n , \"eater\"\n , \"elude\"\n , \"cycle\"\n , \"kitty\"\n , \"boule\"\n , \"moron\"\n , \"tenet\"\n , ",
"end": 10443,
"score": 0.9611557722,
"start": 10438,
"tag": "NAME",
"value": "kitty"
},
{
"context": "\n , \"elude\"\n , \"cycle\"\n , \"kitty\"\n , \"boule\"\n , \"moron\"\n , \"tenet\"\n , \"place\"\n , ",
"end": 10457,
"score": 0.9684672356,
"start": 10452,
"tag": "NAME",
"value": "boule"
},
{
"context": "\n , \"cycle\"\n , \"kitty\"\n , \"boule\"\n , \"moron\"\n , \"tenet\"\n , \"place\"\n , \"lobby\"\n , ",
"end": 10471,
"score": 0.994061172,
"start": 10466,
"tag": "NAME",
"value": "moron"
},
{
"context": "\n , \"kitty\"\n , \"boule\"\n , \"moron\"\n , \"tenet\"\n , \"place\"\n , \"lobby\"\n , \"plush\"\n , ",
"end": 10485,
"score": 0.9649595022,
"start": 10480,
"tag": "NAME",
"value": "tenet"
},
{
"context": "\n , \"moron\"\n , \"tenet\"\n , \"place\"\n , \"lobby\"\n , \"plush\"\n , \"vigil\"\n , \"index\"\n , ",
"end": 10513,
"score": 0.6818411946,
"start": 10508,
"tag": "NAME",
"value": "lobby"
},
{
"context": "\n , \"tenet\"\n , \"place\"\n , \"lobby\"\n , \"plush\"\n , \"vigil\"\n , \"index\"\n , \"blink\"\n , ",
"end": 10527,
"score": 0.8531125784,
"start": 10522,
"tag": "NAME",
"value": "plush"
},
{
"context": "\n , \"place\"\n , \"lobby\"\n , \"plush\"\n , \"vigil\"\n , \"index\"\n , \"blink\"\n , \"clung\"\n , ",
"end": 10541,
"score": 0.9679055214,
"start": 10536,
"tag": "NAME",
"value": "vigil"
},
{
"context": "\n , \"lobby\"\n , \"plush\"\n , \"vigil\"\n , \"index\"\n , \"blink\"\n , \"clung\"\n , \"qualm\"\n , ",
"end": 10555,
"score": 0.6324920654,
"start": 10550,
"tag": "NAME",
"value": "index"
},
{
"context": "\n , \"plush\"\n , \"vigil\"\n , \"index\"\n , \"blink\"\n , \"clung\"\n , \"qualm\"\n , \"croup\"\n , ",
"end": 10569,
"score": 0.9526145458,
"start": 10564,
"tag": "NAME",
"value": "blink"
},
{
"context": "\n , \"vigil\"\n , \"index\"\n , \"blink\"\n , \"clung\"\n , \"qualm\"\n , \"croup\"\n , \"clink\"\n , ",
"end": 10583,
"score": 0.9442088604,
"start": 10578,
"tag": "NAME",
"value": "clung"
},
{
"context": "\n , \"index\"\n , \"blink\"\n , \"clung\"\n , \"qualm\"\n , \"croup\"\n , \"clink\"\n , \"juicy\"\n , ",
"end": 10597,
"score": 0.9391067624,
"start": 10592,
"tag": "NAME",
"value": "qualm"
},
{
"context": "\n , \"blink\"\n , \"clung\"\n , \"qualm\"\n , \"croup\"\n , \"clink\"\n , \"juicy\"\n , \"stage\"\n , ",
"end": 10611,
"score": 0.9101681709,
"start": 10606,
"tag": "NAME",
"value": "croup"
},
{
"context": "\n , \"clung\"\n , \"qualm\"\n , \"croup\"\n , \"clink\"\n , \"juicy\"\n , \"stage\"\n , \"decay\"\n , ",
"end": 10625,
"score": 0.6423831582,
"start": 10620,
"tag": "NAME",
"value": "clink"
},
{
"context": "\n , \"qualm\"\n , \"croup\"\n , \"clink\"\n , \"juicy\"\n , \"stage\"\n , \"decay\"\n , \"nerve\"\n , ",
"end": 10639,
"score": 0.7830428481,
"start": 10634,
"tag": "NAME",
"value": "juicy"
},
{
"context": "\n , \"juicy\"\n , \"stage\"\n , \"decay\"\n , \"nerve\"\n , \"flier\"\n , \"shaft\"\n , \"crook\"\n , ",
"end": 10681,
"score": 0.8826020956,
"start": 10676,
"tag": "NAME",
"value": "nerve"
},
{
"context": "\n , \"stage\"\n , \"decay\"\n , \"nerve\"\n , \"flier\"\n , \"shaft\"\n , \"crook\"\n , \"clean\"\n , ",
"end": 10695,
"score": 0.9937188625,
"start": 10690,
"tag": "NAME",
"value": "flier"
},
{
"context": "\n , \"decay\"\n , \"nerve\"\n , \"flier\"\n , \"shaft\"\n , \"crook\"\n , \"clean\"\n , \"china\"\n , ",
"end": 10709,
"score": 0.9853570461,
"start": 10704,
"tag": "NAME",
"value": "shaft"
},
{
"context": "\n , \"nerve\"\n , \"flier\"\n , \"shaft\"\n , \"crook\"\n , \"clean\"\n , \"china\"\n , \"ridge\"\n , ",
"end": 10723,
"score": 0.8813524842,
"start": 10718,
"tag": "NAME",
"value": "crook"
},
{
"context": " , \"ridge\"\n , \"vowel\"\n , \"gnome\"\n , \"snuck\"\n , \"icing\"\n , \"spiny\"\n , \"rigor\"\n , ",
"end": 10807,
"score": 0.6908695698,
"start": 10804,
"tag": "NAME",
"value": "uck"
},
{
"context": " , \"gnome\"\n , \"snuck\"\n , \"icing\"\n , \"spiny\"\n , \"rigor\"\n , \"snail\"\n , \"flown\"\n , ",
"end": 10835,
"score": 0.5742298365,
"start": 10832,
"tag": "NAME",
"value": "iny"
},
{
"context": "\n , \"snuck\"\n , \"icing\"\n , \"spiny\"\n , \"rigor\"\n , \"snail\"\n , \"flown\"\n , \"rabid\"\n , ",
"end": 10849,
"score": 0.9607976675,
"start": 10844,
"tag": "NAME",
"value": "rigor"
},
{
"context": " , \"icing\"\n , \"spiny\"\n , \"rigor\"\n , \"snail\"\n , \"flown\"\n , \"rabid\"\n , \"prose\"\n , ",
"end": 10863,
"score": 0.6200296879,
"start": 10860,
"tag": "NAME",
"value": "ail"
},
{
"context": " , \"spiny\"\n , \"rigor\"\n , \"snail\"\n , \"flown\"\n , \"rabid\"\n , \"prose\"\n , \"thank\"\n , ",
"end": 10877,
"score": 0.6489269733,
"start": 10876,
"tag": "NAME",
"value": "n"
},
{
"context": "\n , \"rigor\"\n , \"snail\"\n , \"flown\"\n , \"rabid\"\n , \"prose\"\n , \"thank\"\n , \"poppy\"\n , ",
"end": 10891,
"score": 0.9501344562,
"start": 10886,
"tag": "NAME",
"value": "rabid"
},
{
"context": "\n , \"snail\"\n , \"flown\"\n , \"rabid\"\n , \"prose\"\n , \"thank\"\n , \"poppy\"\n , \"budge\"\n , ",
"end": 10905,
"score": 0.8938696384,
"start": 10900,
"tag": "NAME",
"value": "prose"
},
{
"context": "\n , \"flown\"\n , \"rabid\"\n , \"prose\"\n , \"thank\"\n , \"poppy\"\n , \"budge\"\n , \"fiber\"\n , ",
"end": 10919,
"score": 0.8252342939,
"start": 10914,
"tag": "NAME",
"value": "thank"
},
{
"context": "\n , \"rabid\"\n , \"prose\"\n , \"thank\"\n , \"poppy\"\n , \"budge\"\n , \"fiber\"\n , \"moldy\"\n , ",
"end": 10933,
"score": 0.9250844717,
"start": 10928,
"tag": "NAME",
"value": "poppy"
},
{
"context": "\n , \"prose\"\n , \"thank\"\n , \"poppy\"\n , \"budge\"\n , \"fiber\"\n , \"moldy\"\n , \"dowdy\"\n , ",
"end": 10947,
"score": 0.8383900523,
"start": 10942,
"tag": "NAME",
"value": "budge"
},
{
"context": "\n , \"thank\"\n , \"poppy\"\n , \"budge\"\n , \"fiber\"\n , \"moldy\"\n , \"dowdy\"\n , \"kneel\"\n , ",
"end": 10961,
"score": 0.6878246069,
"start": 10956,
"tag": "NAME",
"value": "fiber"
},
{
"context": "\n , \"poppy\"\n , \"budge\"\n , \"fiber\"\n , \"moldy\"\n , \"dowdy\"\n , \"kneel\"\n , \"track\"\n , ",
"end": 10975,
"score": 0.9918069243,
"start": 10970,
"tag": "NAME",
"value": "moldy"
},
{
"context": "\n , \"budge\"\n , \"fiber\"\n , \"moldy\"\n , \"dowdy\"\n , \"kneel\"\n , \"track\"\n , \"caddy\"\n , ",
"end": 10989,
"score": 0.9845526218,
"start": 10984,
"tag": "NAME",
"value": "dowdy"
},
{
"context": "\n , \"fiber\"\n , \"moldy\"\n , \"dowdy\"\n , \"kneel\"\n , \"track\"\n , \"caddy\"\n , \"quell\"\n , ",
"end": 11003,
"score": 0.9897941947,
"start": 10998,
"tag": "NAME",
"value": "kneel"
},
{
"context": "\n , \"dowdy\"\n , \"kneel\"\n , \"track\"\n , \"caddy\"\n , \"quell\"\n , \"dumpy\"\n , \"paler\"\n , ",
"end": 11031,
"score": 0.995518446,
"start": 11026,
"tag": "NAME",
"value": "caddy"
},
{
"context": "\n , \"kneel\"\n , \"track\"\n , \"caddy\"\n , \"quell\"\n , \"dumpy\"\n , \"paler\"\n , \"swore\"\n , ",
"end": 11045,
"score": 0.9872757196,
"start": 11040,
"tag": "NAME",
"value": "quell"
},
{
"context": "\n , \"track\"\n , \"caddy\"\n , \"quell\"\n , \"dumpy\"\n , \"paler\"\n , \"swore\"\n , \"rebar\"\n , ",
"end": 11059,
"score": 0.9798514843,
"start": 11054,
"tag": "NAME",
"value": "dumpy"
},
{
"context": "\n , \"caddy\"\n , \"quell\"\n , \"dumpy\"\n , \"paler\"\n , \"swore\"\n , \"rebar\"\n , \"scuba\"\n , ",
"end": 11073,
"score": 0.9495699406,
"start": 11068,
"tag": "NAME",
"value": "paler"
},
{
"context": "\n , \"quell\"\n , \"dumpy\"\n , \"paler\"\n , \"swore\"\n , \"rebar\"\n , \"scuba\"\n , \"splat\"\n , ",
"end": 11087,
"score": 0.6252329946,
"start": 11082,
"tag": "NAME",
"value": "swore"
},
{
"context": "\n , \"dumpy\"\n , \"paler\"\n , \"swore\"\n , \"rebar\"\n , \"scuba\"\n , \"splat\"\n , \"flyer\"\n , ",
"end": 11101,
"score": 0.6547266841,
"start": 11096,
"tag": "NAME",
"value": "rebar"
},
{
"context": "\n , \"paler\"\n , \"swore\"\n , \"rebar\"\n , \"scuba\"\n , \"splat\"\n , \"flyer\"\n , \"horny\"\n , ",
"end": 11115,
"score": 0.6991655827,
"start": 11110,
"tag": "NAME",
"value": "scuba"
},
{
"context": "\n , \"swore\"\n , \"rebar\"\n , \"scuba\"\n , \"splat\"\n , \"flyer\"\n , \"horny\"\n , \"mason\"\n , ",
"end": 11129,
"score": 0.8240453005,
"start": 11124,
"tag": "NAME",
"value": "splat"
},
{
"context": "\n , \"rebar\"\n , \"scuba\"\n , \"splat\"\n , \"flyer\"\n , \"horny\"\n , \"mason\"\n , \"doing\"\n , ",
"end": 11143,
"score": 0.9850537777,
"start": 11138,
"tag": "NAME",
"value": "flyer"
},
{
"context": "\n , \"scuba\"\n , \"splat\"\n , \"flyer\"\n , \"horny\"\n , \"mason\"\n , \"doing\"\n , \"ozone\"\n , ",
"end": 11157,
"score": 0.9851355553,
"start": 11152,
"tag": "NAME",
"value": "horny"
},
{
"context": "\n , \"splat\"\n , \"flyer\"\n , \"horny\"\n , \"mason\"\n , \"doing\"\n , \"ozone\"\n , \"amply\"\n , ",
"end": 11171,
"score": 0.9761688709,
"start": 11166,
"tag": "NAME",
"value": "mason"
},
{
"context": "\n , \"magic\"\n , \"truce\"\n , \"sport\"\n , \"fritz\"\n , \"edict\"\n , \"twirl\"\n , \"verse\"\n , ",
"end": 11339,
"score": 0.7389244437,
"start": 11334,
"tag": "NAME",
"value": "fritz"
},
{
"context": "\n , \"buddy\"\n , \"thump\"\n , \"scion\"\n , \"candy\"\n , \"chord\"\n , \"basin\"\n , \"march\"\n ",
"end": 11629,
"score": 0.5345845222,
"start": 11628,
"tag": "NAME",
"value": "c"
},
{
"context": "\n , \"gayly\"\n , \"musky\"\n , \"stain\"\n , \"dally\"\n , \"bless\"\n , \"bravo\"\n , \"stung\"\n , ",
"end": 11759,
"score": 0.7527394891,
"start": 11754,
"tag": "NAME",
"value": "dally"
},
{
"context": "\n , \"stain\"\n , \"dally\"\n , \"bless\"\n , \"bravo\"\n , \"stung\"\n , \"title\"\n , \"ruler\"\n , ",
"end": 11787,
"score": 0.808853507,
"start": 11782,
"tag": "NAME",
"value": "bravo"
},
{
"context": "\n , \"ruler\"\n , \"kiosk\"\n , \"blond\"\n , \"ennui\"\n , \"layer\"\n , \"fluid\"\n , \"tatty\"\n ",
"end": 11869,
"score": 0.631762743,
"start": 11866,
"tag": "NAME",
"value": "enn"
},
{
"context": "\n , \"score\"\n , \"cutie\"\n , \"zebra\"\n , \"barge\"\n , \"matey\"\n , \"bluer\"\n , \"aider\"\n , ",
"end": 11969,
"score": 0.5397986174,
"start": 11964,
"tag": "NAME",
"value": "barge"
},
{
"context": "\n , \"cutie\"\n , \"zebra\"\n , \"barge\"\n , \"matey\"\n , \"bluer\"\n , \"aider\"\n , \"shook\"\n ,",
"end": 11982,
"score": 0.6944893599,
"start": 11978,
"tag": "NAME",
"value": "mate"
},
{
"context": "\n , \"zebra\"\n , \"barge\"\n , \"matey\"\n , \"bluer\"\n , \"aider\"\n , \"shook\"\n , \"river\"\n , ",
"end": 11997,
"score": 0.6289968491,
"start": 11992,
"tag": "NAME",
"value": "bluer"
},
{
"context": "\n , \"river\"\n , \"privy\"\n , \"betel\"\n , \"frisk\"\n , \"bongo\"\n , \"begun\"\n , \"azure\"\n ",
"end": 12078,
"score": 0.6817899942,
"start": 12076,
"tag": "NAME",
"value": "fr"
},
{
"context": "\n , \"begun\"\n , \"azure\"\n , \"weave\"\n , \"genie\"\n , \"sound\"\n , \"glove\"\n , \"braid\"\n ",
"end": 12149,
"score": 0.7210183144,
"start": 12146,
"tag": "NAME",
"value": "gen"
},
{
"context": "\n , \"strut\"\n , \"burnt\"\n , \"tulip\"\n , \"crick\"\n , \"idyll\"\n , \"vixen\"\n , \"furor\"\n ",
"end": 13268,
"score": 0.5135422349,
"start": 13266,
"tag": "NAME",
"value": "cr"
},
{
"context": " , \"wagon\"\n , \"salon\"\n , \"nudge\"\n , \"harem\"\n , \"pitch\"\n , \"sworn\"\n , \"pupil\"\n , ",
"end": 13705,
"score": 0.7102998495,
"start": 13701,
"tag": "NAME",
"value": "arem"
},
{
"context": "\n , \"swoon\"\n , \"knife\"\n , \"pouch\"\n , \"ascot\"\n , \"plane\"\n , \"crown\"\n , \"urban\"\n , ",
"end": 14881,
"score": 0.9903120995,
"start": 14876,
"tag": "NAME",
"value": "ascot"
},
{
"context": "\n , \"snide\"\n , \"relay\"\n , \"abide\"\n , \"viola\"\n , \"rajah\"\n , \"straw\"\n , \"dilly\"\n , ",
"end": 14979,
"score": 0.5935418606,
"start": 14974,
"tag": "NAME",
"value": "viola"
},
{
"context": "\n , \"relay\"\n , \"abide\"\n , \"viola\"\n , \"rajah\"\n , \"straw\"\n , \"dilly\"\n , \"crash\"\n , ",
"end": 14993,
"score": 0.9304494858,
"start": 14988,
"tag": "NAME",
"value": "rajah"
},
{
"context": "\n , \"viola\"\n , \"rajah\"\n , \"straw\"\n , \"dilly\"\n , \"crash\"\n , \"amass\"\n , \"third\"\n , ",
"end": 15021,
"score": 0.5591524839,
"start": 15016,
"tag": "NAME",
"value": "dilly"
},
{
"context": "\n , \"straw\"\n , \"dilly\"\n , \"crash\"\n , \"amass\"\n , \"third\"\n , \"trick\"\n , \"tutor\"\n ",
"end": 15046,
"score": 0.5504271388,
"start": 15044,
"tag": "NAME",
"value": "am"
},
{
"context": "\n , \"crash\"\n , \"amass\"\n , \"third\"\n , \"trick\"\n , \"tutor\"\n , \"woody\"\n , \"blurb\"\n ",
"end": 15074,
"score": 0.5119878054,
"start": 15072,
"tag": "NAME",
"value": "tr"
},
{
"context": "\n , \"third\"\n , \"trick\"\n , \"tutor\"\n , \"woody\"\n , \"blurb\"\n , \"grief\"\n , \"disco\"\n , ",
"end": 15105,
"score": 0.61885041,
"start": 15100,
"tag": "NAME",
"value": "woody"
},
{
"context": "\n , \"comic\"\n , \"clued\"\n , \"creep\"\n , \"caste\"\n , \"graze\"\n , \"snuff\"\n , \"frock\"\n , ",
"end": 15259,
"score": 0.6804367304,
"start": 15254,
"tag": "NAME",
"value": "caste"
},
{
"context": "\n , \"graze\"\n , \"snuff\"\n , \"frock\"\n , \"gonad\"\n , \"drunk\"\n , \"prong\"\n , \"lurid\"\n , ",
"end": 15315,
"score": 0.5778520107,
"start": 15310,
"tag": "NAME",
"value": "gonad"
},
{
"context": "\n , \"snuff\"\n , \"frock\"\n , \"gonad\"\n , \"drunk\"\n , \"prong\"\n , \"lurid\"\n , \"steel\"\n , ",
"end": 15329,
"score": 0.8271309733,
"start": 15324,
"tag": "NAME",
"value": "drunk"
},
{
"context": "\n , \"frock\"\n , \"gonad\"\n , \"drunk\"\n , \"prong\"\n , \"lurid\"\n , \"steel\"\n , \"halve\"\n , ",
"end": 15343,
"score": 0.6577506065,
"start": 15338,
"tag": "NAME",
"value": "prong"
},
{
"context": "\n , \"gonad\"\n , \"drunk\"\n , \"prong\"\n , \"lurid\"\n , \"steel\"\n , \"halve\"\n , \"buyer\"\n , ",
"end": 15357,
"score": 0.8075580597,
"start": 15352,
"tag": "NAME",
"value": "lurid"
},
{
"context": "\n , \"local\"\n , \"trade\"\n , \"finch\"\n , \"ashen\"\n , \"modal\"\n , \"gaunt\"\n , \"clove\"\n , ",
"end": 15539,
"score": 0.7044018507,
"start": 15534,
"tag": "NAME",
"value": "ashen"
},
{
"context": "\n , \"speck\"\n , \"sheik\"\n , \"missy\"\n , \"grunt\"\n , \"snoop\"\n , \"party\"\n , \"touch\"\n , ",
"end": 15679,
"score": 0.6871256828,
"start": 15674,
"tag": "NAME",
"value": "grunt"
},
{
"context": "\n , \"snoop\"\n , \"party\"\n , \"touch\"\n , \"mafia\"\n , \"emcee\"\n , \"array\"\n , \"south\"\n , ",
"end": 15735,
"score": 0.6153786778,
"start": 15730,
"tag": "NAME",
"value": "mafia"
},
{
"context": "\n , \"party\"\n , \"touch\"\n , \"mafia\"\n , \"emcee\"\n , \"array\"\n , \"south\"\n , \"vapid\"\n , ",
"end": 15749,
"score": 0.685077548,
"start": 15744,
"tag": "NAME",
"value": "emcee"
},
{
"context": "\n , \"array\"\n , \"south\"\n , \"vapid\"\n , \"jelly\"\n , \"skulk\"\n , \"angst\"\n , \"tubal\"\n , ",
"end": 15805,
"score": 0.6861148477,
"start": 15800,
"tag": "NAME",
"value": "jelly"
},
{
"context": "\n , \"south\"\n , \"vapid\"\n , \"jelly\"\n , \"skulk\"\n , \"angst\"\n , \"tubal\"\n , \"lower\"\n , ",
"end": 15819,
"score": 0.8234232068,
"start": 15814,
"tag": "NAME",
"value": "skulk"
},
{
"context": "\n , \"offer\"\n , \"seven\"\n , \"dryer\"\n , \"diary\"\n , \"dryly\"\n , \"drank\"\n , \"acrid\"\n ",
"end": 16180,
"score": 0.550557673,
"start": 16178,
"tag": "NAME",
"value": "di"
},
{
"context": "\n , \"dryer\"\n , \"diary\"\n , \"dryly\"\n , \"drank\"\n , \"acrid\"\n , \"heady\"\n , \"theta\"\n , ",
"end": 16211,
"score": 0.5206983685,
"start": 16206,
"tag": "NAME",
"value": "drank"
},
{
"context": "\n , \"diary\"\n , \"dryly\"\n , \"drank\"\n , \"acrid\"\n , \"heady\"\n , \"theta\"\n , \"junto\"\n , ",
"end": 16225,
"score": 0.6674683094,
"start": 16220,
"tag": "NAME",
"value": "acrid"
},
{
"context": "\n , \"acrid\"\n , \"heady\"\n , \"theta\"\n , \"junto\"\n , \"pixie\"\n , \"quoth\"\n , \"bonus\"\n ",
"end": 16263,
"score": 0.5880416632,
"start": 16262,
"tag": "NAME",
"value": "j"
},
{
"context": "\n , \"heady\"\n , \"theta\"\n , \"junto\"\n , \"pixie\"\n , \"quoth\"\n , \"bonus\"\n , \"shalt\"\n , ",
"end": 16281,
"score": 0.8946677446,
"start": 16276,
"tag": "NAME",
"value": "pixie"
},
{
"context": "\n , \"theta\"\n , \"junto\"\n , \"pixie\"\n , \"quoth\"\n , \"bonus\"\n , \"shalt\"\n , \"penne\"\n ",
"end": 16292,
"score": 0.7827430367,
"start": 16290,
"tag": "NAME",
"value": "qu"
},
{
"context": "\n , \"quoth\"\n , \"bonus\"\n , \"shalt\"\n , \"penne\"\n , \"amend\"\n , \"datum\"\n , \"build\"\n , ",
"end": 16337,
"score": 0.7061077356,
"start": 16332,
"tag": "NAME",
"value": "penne"
},
{
"context": "\n , \"bonus\"\n , \"shalt\"\n , \"penne\"\n , \"amend\"\n , \"datum\"\n , \"build\"\n , \"piano\"\n , ",
"end": 16351,
"score": 0.6678153872,
"start": 16346,
"tag": "NAME",
"value": "amend"
},
{
"context": "\n , \"suing\"\n , \"rearm\"\n , \"coral\"\n , \"ramen\"\n , \"worth\"\n , \"psalm\"\n , \"infer\"\n , ",
"end": 16477,
"score": 0.6739382744,
"start": 16472,
"tag": "NAME",
"value": "ramen"
},
{
"context": "\n , \"glide\"\n , \"usage\"\n , \"poise\"\n , \"randy\"\n , \"chuck\"\n , \"prank\"\n , \"fishy\"\n ,",
"end": 16616,
"score": 0.543915689,
"start": 16612,
"tag": "NAME",
"value": "rand"
},
{
"context": "\n , \"poise\"\n , \"randy\"\n , \"chuck\"\n , \"prank\"\n , \"fishy\"\n , \"tooth\"\n , \"ether\"\n , ",
"end": 16645,
"score": 0.7237078547,
"start": 16640,
"tag": "NAME",
"value": "prank"
},
{
"context": "\n , \"tooth\"\n , \"ether\"\n , \"drove\"\n , \"idler\"\n , \"swath\"\n , \"stint\"\n , \"while\"\n ",
"end": 16712,
"score": 0.7455524802,
"start": 16710,
"tag": "NAME",
"value": "id"
},
{
"context": "\n , \"ether\"\n , \"drove\"\n , \"idler\"\n , \"swath\"\n , \"stint\"\n , \"while\"\n , \"begat\"\n ",
"end": 16726,
"score": 0.5730872154,
"start": 16724,
"tag": "NAME",
"value": "sw"
},
{
"context": "\n , \"slang\"\n , \"tarot\"\n , \"radar\"\n , \"credo\"\n , \"aware\"\n , \"canon\"\n , \"shift\"\n , ",
"end": 16841,
"score": 0.8268380165,
"start": 16836,
"tag": "NAME",
"value": "credo"
},
{
"context": "\n , \"shift\"\n , \"timer\"\n , \"bylaw\"\n , \"serum\"\n , \"three\"\n , \"steak\"\n , \"iliac\"\n ",
"end": 16923,
"score": 0.6334840655,
"start": 16920,
"tag": "NAME",
"value": "ser"
},
{
"context": "\n , \"serum\"\n , \"three\"\n , \"steak\"\n , \"iliac\"\n , \"shirk\"\n , \"blunt\"\n , \"puppy\"\n , ",
"end": 16967,
"score": 0.7867796421,
"start": 16962,
"tag": "NAME",
"value": "iliac"
},
{
"context": "\n , \"three\"\n , \"steak\"\n , \"iliac\"\n , \"shirk\"\n , \"blunt\"\n , \"puppy\"\n , \"penal\"\n , ",
"end": 16981,
"score": 0.8048232198,
"start": 16976,
"tag": "NAME",
"value": "shirk"
},
{
"context": "\n , \"puppy\"\n , \"penal\"\n , \"joist\"\n , \"bunny\"\n , \"shape\"\n , \"beget\"\n , \"wheel\"\n , ",
"end": 17051,
"score": 0.552051723,
"start": 17046,
"tag": "NAME",
"value": "bunny"
},
{
"context": "\n , \"rebel\"\n , \"flank\"\n , \"learn\"\n , \"nadir\"\n , \"maple\"\n , \"comfy\"\n , \"remit\"\n , ",
"end": 17989,
"score": 0.6595995426,
"start": 17984,
"tag": "NAME",
"value": "nadir"
},
{
"context": "\n , \"maple\"\n , \"comfy\"\n , \"remit\"\n , \"gruff\"\n , \"ester\"\n , \"least\"\n , \"mogul\"\n ",
"end": 18042,
"score": 0.51929456,
"start": 18040,
"tag": "NAME",
"value": "gr"
},
{
"context": "\n , \"meaty\"\n , \"gaffe\"\n , \"shyly\"\n , \"racer\"\n , \"prowl\"\n , \"thief\"\n , \"stern\"\n ",
"end": 18195,
"score": 0.513034761,
"start": 18194,
"tag": "NAME",
"value": "r"
},
{
"context": "\n , \"novel\"\n , \"waxen\"\n , \"stoic\"\n , \"jerky\"\n , \"blitz\"\n , \"beefy\"\n , \"lyric\"\n ",
"end": 19779,
"score": 0.6351303458,
"start": 19776,
"tag": "NAME",
"value": "jer"
},
{
"context": "\n , \"jerky\"\n , \"blitz\"\n , \"beefy\"\n , \"lyric\"\n , \"hussy\"\n , \"towel\"\n , \"quilt\"\n , ",
"end": 19823,
"score": 0.9751689434,
"start": 19818,
"tag": "NAME",
"value": "lyric"
},
{
"context": "\n , \"again\"\n , \"tying\"\n , \"pesky\"\n , \"alter\"\n , \"gazer\"\n , \"noble\"\n , \"ethos\"\n , ",
"end": 21195,
"score": 0.5511103272,
"start": 21190,
"tag": "NAME",
"value": "alter"
},
{
"context": " , \"tying\"\n , \"pesky\"\n , \"alter\"\n , \"gazer\"\n , \"noble\"\n , \"ethos\"\n , \"bride\"\n , ",
"end": 21209,
"score": 0.5176564455,
"start": 21205,
"tag": "NAME",
"value": "azer"
},
{
"context": "\n , \"erase\"\n , \"elegy\"\n , \"spunk\"\n , \"piper\"\n , \"scaly\"\n , \"scold\"\n , \"hefty\"\n , ",
"end": 21433,
"score": 0.7648209929,
"start": 21428,
"tag": "NAME",
"value": "piper"
},
{
"context": "\n , \"spent\"\n , \"prism\"\n , \"stoke\"\n , \"riper\"\n , \"orbit\"\n , \"cocoa\"\n , \"guilt\"\n , ",
"end": 21825,
"score": 0.8214749098,
"start": 21820,
"tag": "NAME",
"value": "riper"
},
{
"context": "\n , \"scoff\"\n , \"torus\"\n , \"ninny\"\n , \"covey\"\n , \"viper\"\n , \"taken\"\n , \"moral\"\n , ",
"end": 24639,
"score": 0.5971338749,
"start": 24634,
"tag": "NAME",
"value": "covey"
},
{
"context": "\n , \"booth\"\n , \"voter\"\n , \"chide\"\n , \"elfin\"\n , \"ebony\"\n , \"neigh\"\n , \"minim\"\n ",
"end": 24790,
"score": 0.5198642015,
"start": 24788,
"tag": "NAME",
"value": "el"
},
{
"context": "\n , \"fetal\"\n , \"sprig\"\n , \"spine\"\n , \"shout\"\n , \"cadet\"\n , \"macro\"\n , \"dodgy\"\n , ",
"end": 26011,
"score": 0.5575300455,
"start": 26006,
"tag": "NAME",
"value": "shout"
},
{
"context": "\n , \"sprig\"\n , \"spine\"\n , \"shout\"\n , \"cadet\"\n , \"macro\"\n , \"dodgy\"\n , \"satyr\"\n , ",
"end": 26025,
"score": 0.6060979962,
"start": 26020,
"tag": "NAME",
"value": "cadet"
},
{
"context": "\n , \"macro\"\n , \"dodgy\"\n , \"satyr\"\n , \"rarer\"\n , \"binge\"\n , \"trend\"\n , \"nutty\"\n ",
"end": 26077,
"score": 0.6109469533,
"start": 26076,
"tag": "NAME",
"value": "r"
},
{
"context": "\n , \"trend\"\n , \"nutty\"\n , \"leapt\"\n , \"amiss\"\n , \"split\"\n , \"myrrh\"\n , \"width\"\n , ",
"end": 26151,
"score": 0.6947219372,
"start": 26146,
"tag": "NAME",
"value": "amiss"
},
{
"context": "\n , \"north\"\n , \"wafer\"\n , \"scant\"\n , \"frill\"\n , \"awash\"\n , \"snack\"\n , \"scowl\"\n , ",
"end": 26417,
"score": 0.5653027296,
"start": 26412,
"tag": "NAME",
"value": "frill"
},
{
"context": "\n , \"ounce\"\n , \"wreak\"\n , \"revel\"\n , \"talon\"\n , \"prior\"\n , \"knelt\"\n , \"cello\"\n , ",
"end": 26585,
"score": 0.7001601458,
"start": 26580,
"tag": "NAME",
"value": "talon"
},
{
"context": "\n , \"revel\"\n , \"talon\"\n , \"prior\"\n , \"knelt\"\n , \"cello\"\n , \"flake\"\n , \"debug\"\n , ",
"end": 26613,
"score": 0.9183220863,
"start": 26608,
"tag": "NAME",
"value": "knelt"
},
{
"context": "\n , \"talon\"\n , \"prior\"\n , \"knelt\"\n , \"cello\"\n , \"flake\"\n , \"debug\"\n , \"anode\"\n , ",
"end": 26627,
"score": 0.8172565699,
"start": 26622,
"tag": "NAME",
"value": "cello"
},
{
"context": "\n , \"flake\"\n , \"debug\"\n , \"anode\"\n , \"crime\"\n , \"salve\"\n , \"scout\"\n , \"imbue\"\n ",
"end": 26681,
"score": 0.5511440635,
"start": 26678,
"tag": "NAME",
"value": "cri"
},
{
"context": "\n , \"teach\"\n , \"cleft\"\n , \"frost\"\n , \"prawn\"\n , \"booty\"\n , \"twist\"\n , \"apnea\"\n ",
"end": 26876,
"score": 0.5052929521,
"start": 26874,
"tag": "NAME",
"value": "pr"
},
{
"context": "\n , \"prawn\"\n , \"booty\"\n , \"twist\"\n , \"apnea\"\n , \"stiff\"\n , \"plaza\"\n , \"ledge\"\n ",
"end": 26918,
"score": 0.5363233089,
"start": 26916,
"tag": "NAME",
"value": "ap"
},
{
"context": "\n , \"board\"\n , \"grant\"\n , \"medic\"\n , \"bacon\"\n , \"cable\"\n , \"brawl\"\n , \"slunk\"\n ",
"end": 27029,
"score": 0.6411381364,
"start": 27028,
"tag": "NAME",
"value": "b"
},
{
"context": "\n , \"forum\"\n , \"drone\"\n , \"women\"\n , \"mucus\"\n , \"boast\"\n , \"toddy\"\n , \"coven\"\n ",
"end": 27141,
"score": 0.7103350163,
"start": 27140,
"tag": "NAME",
"value": "m"
},
{
"context": "\n , \"women\"\n , \"mucus\"\n , \"boast\"\n , \"toddy\"\n , \"coven\"\n , \"tumor\"\n , \"truer\"\n ",
"end": 27171,
"score": 0.7460895181,
"start": 27168,
"tag": "NAME",
"value": "tod"
},
{
"context": "\n , \"mucus\"\n , \"boast\"\n , \"toddy\"\n , \"coven\"\n , \"tumor\"\n , \"truer\"\n , \"wrath\"\n ",
"end": 27184,
"score": 0.6550880075,
"start": 27182,
"tag": "NAME",
"value": "co"
},
{
"context": "\n , \"toddy\"\n , \"coven\"\n , \"tumor\"\n , \"truer\"\n , \"wrath\"\n , \"stall\"\n , \"steam\"\n ",
"end": 27212,
"score": 0.5593916178,
"start": 27210,
"tag": "NAME",
"value": "tr"
},
{
"context": "\n , \"truer\"\n , \"wrath\"\n , \"stall\"\n , \"steam\"\n , \"axial\"\n , \"purer\"\n , \"daily\"\n , ",
"end": 27257,
"score": 0.9570832849,
"start": 27252,
"tag": "NAME",
"value": "steam"
},
{
"context": "\n , \"wrath\"\n , \"stall\"\n , \"steam\"\n , \"axial\"\n , \"purer\"\n , \"daily\"\n , \"trail\"\n , ",
"end": 27271,
"score": 0.9683489799,
"start": 27266,
"tag": "NAME",
"value": "axial"
},
{
"context": "\n , \"stall\"\n , \"steam\"\n , \"axial\"\n , \"purer\"\n , \"daily\"\n , \"trail\"\n , \"niche\"\n , ",
"end": 27285,
"score": 0.9685082436,
"start": 27280,
"tag": "NAME",
"value": "purer"
},
{
"context": "\n , \"steam\"\n , \"axial\"\n , \"purer\"\n , \"daily\"\n , \"trail\"\n , \"niche\"\n , \"mealy\"\n , ",
"end": 27299,
"score": 0.7731763124,
"start": 27294,
"tag": "NAME",
"value": "daily"
},
{
"context": "\n , \"axial\"\n , \"purer\"\n , \"daily\"\n , \"trail\"\n , \"niche\"\n , \"mealy\"\n , \"juice\"\n , ",
"end": 27313,
"score": 0.6000857353,
"start": 27308,
"tag": "NAME",
"value": "trail"
},
{
"context": "\n , \"purer\"\n , \"daily\"\n , \"trail\"\n , \"niche\"\n , \"mealy\"\n , \"juice\"\n , \"nylon\"\n , ",
"end": 27327,
"score": 0.9790803194,
"start": 27322,
"tag": "NAME",
"value": "niche"
},
{
"context": "\n , \"daily\"\n , \"trail\"\n , \"niche\"\n , \"mealy\"\n , \"juice\"\n , \"nylon\"\n , \"plump\"\n , ",
"end": 27341,
"score": 0.9017681479,
"start": 27336,
"tag": "NAME",
"value": "mealy"
},
{
"context": "\n , \"trail\"\n , \"niche\"\n , \"mealy\"\n , \"juice\"\n , \"nylon\"\n , \"plump\"\n , \"merry\"\n , ",
"end": 27355,
"score": 0.8720850348,
"start": 27350,
"tag": "NAME",
"value": "juice"
},
{
"context": "\n , \"niche\"\n , \"mealy\"\n , \"juice\"\n , \"nylon\"\n , \"plump\"\n , \"merry\"\n , \"flail\"\n , ",
"end": 27369,
"score": 0.9719693661,
"start": 27364,
"tag": "NAME",
"value": "nylon"
},
{
"context": "\n , \"mealy\"\n , \"juice\"\n , \"nylon\"\n , \"plump\"\n , \"merry\"\n , \"flail\"\n , \"papal\"\n , ",
"end": 27383,
"score": 0.9368627071,
"start": 27378,
"tag": "NAME",
"value": "plump"
},
{
"context": "\n , \"juice\"\n , \"nylon\"\n , \"plump\"\n , \"merry\"\n , \"flail\"\n , \"papal\"\n , \"wheat\"\n , ",
"end": 27397,
"score": 0.9738535881,
"start": 27392,
"tag": "NAME",
"value": "merry"
},
{
"context": "\n , \"nylon\"\n , \"plump\"\n , \"merry\"\n , \"flail\"\n , \"papal\"\n , \"wheat\"\n , \"berry\"\n , ",
"end": 27411,
"score": 0.9241543412,
"start": 27406,
"tag": "NAME",
"value": "flail"
},
{
"context": "\n , \"plump\"\n , \"merry\"\n , \"flail\"\n , \"papal\"\n , \"wheat\"\n , \"berry\"\n , \"cower\"\n , ",
"end": 27425,
"score": 0.9157933593,
"start": 27420,
"tag": "NAME",
"value": "papal"
},
{
"context": "\n , \"merry\"\n , \"flail\"\n , \"papal\"\n , \"wheat\"\n , \"berry\"\n , \"cower\"\n , \"erect\"\n , ",
"end": 27439,
"score": 0.6911057234,
"start": 27434,
"tag": "NAME",
"value": "wheat"
},
{
"context": " , \"papal\"\n , \"wheat\"\n , \"berry\"\n , \"cower\"\n , \"erect\"\n , \"brute\"\n , \"leggy\"\n , ",
"end": 27467,
"score": 0.5046653152,
"start": 27464,
"tag": "NAME",
"value": "wer"
},
{
"context": "\n , \"wheat\"\n , \"berry\"\n , \"cower\"\n , \"erect\"\n , \"brute\"\n , \"leggy\"\n , \"snipe\"\n , ",
"end": 27481,
"score": 0.7353219986,
"start": 27476,
"tag": "NAME",
"value": "erect"
},
{
"context": " , \"berry\"\n , \"cower\"\n , \"erect\"\n , \"brute\"\n , \"leggy\"\n , \"snipe\"\n , \"sinew\"\n , ",
"end": 27495,
"score": 0.551096499,
"start": 27492,
"tag": "NAME",
"value": "ute"
},
{
"context": " , \"cower\"\n , \"erect\"\n , \"brute\"\n , \"leggy\"\n , \"snipe\"\n , \"sinew\"\n , \"skier\"\n , ",
"end": 27509,
"score": 0.5035850406,
"start": 27507,
"tag": "NAME",
"value": "gy"
},
{
"context": "\n , \"erect\"\n , \"brute\"\n , \"leggy\"\n , \"snipe\"\n , \"sinew\"\n , \"skier\"\n , \"penny\"\n , ",
"end": 27523,
"score": 0.8664411306,
"start": 27518,
"tag": "NAME",
"value": "snipe"
},
{
"context": "\n , \"brute\"\n , \"leggy\"\n , \"snipe\"\n , \"sinew\"\n , \"skier\"\n , \"penny\"\n , \"jumpy\"\n , ",
"end": 27537,
"score": 0.9138206244,
"start": 27532,
"tag": "NAME",
"value": "sinew"
},
{
"context": "\n , \"leggy\"\n , \"snipe\"\n , \"sinew\"\n , \"skier\"\n , \"penny\"\n , \"jumpy\"\n , \"rally\"\n , ",
"end": 27551,
"score": 0.8302571774,
"start": 27546,
"tag": "NAME",
"value": "skier"
},
{
"context": "\n , \"snipe\"\n , \"sinew\"\n , \"skier\"\n , \"penny\"\n , \"jumpy\"\n , \"rally\"\n , \"umbra\"\n , ",
"end": 27565,
"score": 0.9668347836,
"start": 27560,
"tag": "NAME",
"value": "penny"
},
{
"context": "\n , \"sinew\"\n , \"skier\"\n , \"penny\"\n , \"jumpy\"\n , \"rally\"\n , \"umbra\"\n , \"scary\"\n , ",
"end": 27579,
"score": 0.75173527,
"start": 27574,
"tag": "NAME",
"value": "jumpy"
},
{
"context": "\n , \"skier\"\n , \"penny\"\n , \"jumpy\"\n , \"rally\"\n , \"umbra\"\n , \"scary\"\n , \"modem\"\n , ",
"end": 27593,
"score": 0.925940752,
"start": 27588,
"tag": "NAME",
"value": "rally"
},
{
"context": "\n , \"penny\"\n , \"jumpy\"\n , \"rally\"\n , \"umbra\"\n , \"scary\"\n , \"modem\"\n , \"gross\"\n , ",
"end": 27607,
"score": 0.8476780057,
"start": 27602,
"tag": "NAME",
"value": "umbra"
},
{
"context": " , \"jumpy\"\n , \"rally\"\n , \"umbra\"\n , \"scary\"\n , \"modem\"\n , \"gross\"\n , \"avian\"\n , ",
"end": 27621,
"score": 0.7928575873,
"start": 27618,
"tag": "NAME",
"value": "ary"
},
{
"context": "\n , \"rally\"\n , \"umbra\"\n , \"scary\"\n , \"modem\"\n , \"gross\"\n , \"avian\"\n , \"greed\"\n , ",
"end": 27635,
"score": 0.854052484,
"start": 27630,
"tag": "NAME",
"value": "modem"
},
{
"context": "\n , \"umbra\"\n , \"scary\"\n , \"modem\"\n , \"gross\"\n , \"avian\"\n , \"greed\"\n , \"satin\"\n , ",
"end": 27649,
"score": 0.7922791243,
"start": 27644,
"tag": "NAME",
"value": "gross"
},
{
"context": "\n , \"scary\"\n , \"modem\"\n , \"gross\"\n , \"avian\"\n , \"greed\"\n , \"satin\"\n , \"tonic\"\n , ",
"end": 27663,
"score": 0.822583437,
"start": 27658,
"tag": "NAME",
"value": "avian"
},
{
"context": "\n , \"modem\"\n , \"gross\"\n , \"avian\"\n , \"greed\"\n , \"satin\"\n , \"tonic\"\n , \"parka\"\n , ",
"end": 27677,
"score": 0.703436017,
"start": 27672,
"tag": "NAME",
"value": "greed"
},
{
"context": "\n , \"gross\"\n , \"avian\"\n , \"greed\"\n , \"satin\"\n , \"tonic\"\n , \"parka\"\n , \"sniff\"\n , ",
"end": 27691,
"score": 0.8421227932,
"start": 27686,
"tag": "NAME",
"value": "satin"
},
{
"context": "\n , \"avian\"\n , \"greed\"\n , \"satin\"\n , \"tonic\"\n , \"parka\"\n , \"sniff\"\n , \"livid\"\n , ",
"end": 27705,
"score": 0.929084301,
"start": 27700,
"tag": "NAME",
"value": "tonic"
},
{
"context": "\n , \"greed\"\n , \"satin\"\n , \"tonic\"\n , \"parka\"\n , \"sniff\"\n , \"livid\"\n , \"stark\"\n , ",
"end": 27719,
"score": 0.9837717414,
"start": 27714,
"tag": "NAME",
"value": "parka"
},
{
"context": "\n , \"satin\"\n , \"tonic\"\n , \"parka\"\n , \"sniff\"\n , \"livid\"\n , \"stark\"\n , \"trump\"\n , ",
"end": 27733,
"score": 0.9201829433,
"start": 27728,
"tag": "NAME",
"value": "sniff"
},
{
"context": "\n , \"tonic\"\n , \"parka\"\n , \"sniff\"\n , \"livid\"\n , \"stark\"\n , \"trump\"\n , \"giddy\"\n , ",
"end": 27747,
"score": 0.9602688551,
"start": 27742,
"tag": "NAME",
"value": "livid"
},
{
"context": "\n , \"parka\"\n , \"sniff\"\n , \"livid\"\n , \"stark\"\n , \"trump\"\n , \"giddy\"\n , \"reuse\"\n , ",
"end": 27761,
"score": 0.9238182306,
"start": 27756,
"tag": "NAME",
"value": "stark"
},
{
"context": "\n , \"sniff\"\n , \"livid\"\n , \"stark\"\n , \"trump\"\n , \"giddy\"\n , \"reuse\"\n , \"taboo\"\n , ",
"end": 27775,
"score": 0.8998373151,
"start": 27770,
"tag": "NAME",
"value": "trump"
},
{
"context": "\n , \"livid\"\n , \"stark\"\n , \"trump\"\n , \"giddy\"\n , \"reuse\"\n , \"taboo\"\n , \"avoid\"\n , ",
"end": 27789,
"score": 0.818839848,
"start": 27784,
"tag": "NAME",
"value": "giddy"
},
{
"context": "\n , \"stark\"\n , \"trump\"\n , \"giddy\"\n , \"reuse\"\n , \"taboo\"\n , \"avoid\"\n , \"quote\"\n , ",
"end": 27803,
"score": 0.5628293157,
"start": 27798,
"tag": "NAME",
"value": "reuse"
},
{
"context": "\n , \"trump\"\n , \"giddy\"\n , \"reuse\"\n , \"taboo\"\n , \"avoid\"\n , \"quote\"\n , \"devil\"\n , ",
"end": 27817,
"score": 0.6522163153,
"start": 27812,
"tag": "NAME",
"value": "taboo"
},
{
"context": "\n , \"taboo\"\n , \"avoid\"\n , \"quote\"\n , \"devil\"\n , \"liken\"\n , \"gloss\"\n , \"gayer\"\n , ",
"end": 27859,
"score": 0.8875223398,
"start": 27854,
"tag": "NAME",
"value": "devil"
},
{
"context": "\n , \"avoid\"\n , \"quote\"\n , \"devil\"\n , \"liken\"\n , \"gloss\"\n , \"gayer\"\n , \"beret\"\n , ",
"end": 27873,
"score": 0.8883193731,
"start": 27868,
"tag": "NAME",
"value": "liken"
},
{
"context": " , \"devil\"\n , \"liken\"\n , \"gloss\"\n , \"gayer\"\n , \"beret\"\n , \"noise\"\n , \"gland\"\n , ",
"end": 27901,
"score": 0.5085795522,
"start": 27897,
"tag": "NAME",
"value": "ayer"
},
{
"context": "\n , \"liken\"\n , \"gloss\"\n , \"gayer\"\n , \"beret\"\n , \"noise\"\n , \"gland\"\n , \"dealt\"\n , ",
"end": 27915,
"score": 0.7831937075,
"start": 27910,
"tag": "NAME",
"value": "beret"
},
{
"context": "\n , \"gland\"\n , \"dealt\"\n , \"sling\"\n , \"rumor\"\n , \"opera\"\n , \"thigh\"\n , \"tonga\"\n , ",
"end": 27985,
"score": 0.6469604969,
"start": 27980,
"tag": "NAME",
"value": "rumor"
},
{
"context": "\n , \"dealt\"\n , \"sling\"\n , \"rumor\"\n , \"opera\"\n , \"thigh\"\n , \"tonga\"\n , \"flare\"\n , ",
"end": 27999,
"score": 0.61488837,
"start": 27994,
"tag": "NAME",
"value": "opera"
},
{
"context": "\n , \"sling\"\n , \"rumor\"\n , \"opera\"\n , \"thigh\"\n , \"tonga\"\n , \"flare\"\n , \"wound\"\n , ",
"end": 28013,
"score": 0.7059466839,
"start": 28008,
"tag": "NAME",
"value": "thigh"
},
{
"context": "\n , \"opera\"\n , \"thigh\"\n , \"tonga\"\n , \"flare\"\n , \"wound\"\n , \"white\"\n , \"bulky\"\n , ",
"end": 28041,
"score": 0.6727093458,
"start": 28036,
"tag": "NAME",
"value": "flare"
},
{
"context": "\n , \"tonga\"\n , \"flare\"\n , \"wound\"\n , \"white\"\n , \"bulky\"\n , \"etude\"\n , \"horse\"\n , ",
"end": 28069,
"score": 0.7181556821,
"start": 28064,
"tag": "NAME",
"value": "white"
},
{
"context": "\n , \"flare\"\n , \"wound\"\n , \"white\"\n , \"bulky\"\n , \"etude\"\n , \"horse\"\n , \"circa\"\n , ",
"end": 28083,
"score": 0.7513449192,
"start": 28078,
"tag": "NAME",
"value": "bulky"
},
{
"context": "\n , \"bulky\"\n , \"etude\"\n , \"horse\"\n , \"circa\"\n , \"paddy\"\n , \"inbox\"\n , \"fizzy\"\n , ",
"end": 28125,
"score": 0.8851572275,
"start": 28120,
"tag": "NAME",
"value": "circa"
},
{
"context": "\n , \"etude\"\n , \"horse\"\n , \"circa\"\n , \"paddy\"\n , \"inbox\"\n , \"fizzy\"\n , \"grain\"\n , ",
"end": 28139,
"score": 0.9805368781,
"start": 28134,
"tag": "NAME",
"value": "paddy"
},
{
"context": "\n , \"paddy\"\n , \"inbox\"\n , \"fizzy\"\n , \"grain\"\n , \"exert\"\n , \"surge\"\n , \"gleam\"\n ",
"end": 28178,
"score": 0.5426246524,
"start": 28176,
"tag": "NAME",
"value": "gr"
},
{
"context": "\n , \"inbox\"\n , \"fizzy\"\n , \"grain\"\n , \"exert\"\n , \"surge\"\n , \"gleam\"\n , \"belle\"\n , ",
"end": 28195,
"score": 0.5128134489,
"start": 28190,
"tag": "NAME",
"value": "exert"
},
{
"context": "\n , \"grain\"\n , \"exert\"\n , \"surge\"\n , \"gleam\"\n , \"belle\"\n , \"salvo\"\n , \"crush\"\n , ",
"end": 28223,
"score": 0.5879157186,
"start": 28218,
"tag": "NAME",
"value": "gleam"
},
{
"context": "\n , \"surge\"\n , \"gleam\"\n , \"belle\"\n , \"salvo\"\n , \"crush\"\n , \"fruit\"\n , \"sappy\"\n , ",
"end": 28251,
"score": 0.6934666038,
"start": 28246,
"tag": "NAME",
"value": "salvo"
},
{
"context": "\n , \"sappy\"\n , \"taker\"\n , \"tract\"\n , \"ovine\"\n , \"spiky\"\n , \"frank\"\n , \"reedy\"\n ",
"end": 28332,
"score": 0.5515196919,
"start": 28330,
"tag": "NAME",
"value": "ov"
},
{
"context": "\n , \"tract\"\n , \"ovine\"\n , \"spiky\"\n , \"frank\"\n , \"reedy\"\n , \"filth\"\n , \"spasm\"\n , ",
"end": 28363,
"score": 0.6848069429,
"start": 28358,
"tag": "NAME",
"value": "frank"
},
{
"context": "\n , \"spiky\"\n , \"frank\"\n , \"reedy\"\n , \"filth\"\n , \"spasm\"\n , \"heave\"\n , \"mambo\"\n ",
"end": 28389,
"score": 0.6273310781,
"start": 28386,
"tag": "NAME",
"value": "fil"
},
{
"context": "\n , \"reedy\"\n , \"filth\"\n , \"spasm\"\n , \"heave\"\n , \"mambo\"\n , \"right\"\n , \"clank\"\n ",
"end": 28416,
"score": 0.5285590887,
"start": 28414,
"tag": "NAME",
"value": "he"
},
{
"context": "\n , \"filth\"\n , \"spasm\"\n , \"heave\"\n , \"mambo\"\n , \"right\"\n , \"clank\"\n , \"trust\"\n , ",
"end": 28433,
"score": 0.6088688374,
"start": 28428,
"tag": "NAME",
"value": "mambo"
},
{
"context": "\n , \"heave\"\n , \"mambo\"\n , \"right\"\n , \"clank\"\n , \"trust\"\n , \"lumen\"\n , \"borne\"\n ",
"end": 28458,
"score": 0.5606084466,
"start": 28456,
"tag": "NAME",
"value": "cl"
},
{
"context": "\n , \"mambo\"\n , \"right\"\n , \"clank\"\n , \"trust\"\n , \"lumen\"\n , \"borne\"\n , \"spook\"\n , ",
"end": 28475,
"score": 0.8846704364,
"start": 28470,
"tag": "NAME",
"value": "trust"
},
{
"context": "\n , \"right\"\n , \"clank\"\n , \"trust\"\n , \"lumen\"\n , \"borne\"\n , \"spook\"\n , \"sauce\"\n , ",
"end": 28489,
"score": 0.9137064815,
"start": 28484,
"tag": "NAME",
"value": "lumen"
},
{
"context": "\n , \"clank\"\n , \"trust\"\n , \"lumen\"\n , \"borne\"\n , \"spook\"\n , \"sauce\"\n , \"amber\"\n , ",
"end": 28503,
"score": 0.9906178713,
"start": 28498,
"tag": "NAME",
"value": "borne"
},
{
"context": "\n , \"trust\"\n , \"lumen\"\n , \"borne\"\n , \"spook\"\n , \"sauce\"\n , \"amber\"\n , \"lathe\"\n , ",
"end": 28517,
"score": 0.7402284145,
"start": 28512,
"tag": "NAME",
"value": "spook"
},
{
"context": "\n , \"lumen\"\n , \"borne\"\n , \"spook\"\n , \"sauce\"\n , \"amber\"\n , \"lathe\"\n , \"carat\"\n , ",
"end": 28531,
"score": 0.6297202706,
"start": 28526,
"tag": "NAME",
"value": "sauce"
},
{
"context": "\n , \"borne\"\n , \"spook\"\n , \"sauce\"\n , \"amber\"\n , \"lathe\"\n , \"carat\"\n , \"corer\"\n , ",
"end": 28545,
"score": 0.8813640475,
"start": 28540,
"tag": "NAME",
"value": "amber"
},
{
"context": "\n , \"spook\"\n , \"sauce\"\n , \"amber\"\n , \"lathe\"\n , \"carat\"\n , \"corer\"\n , \"dirty\"\n , ",
"end": 28559,
"score": 0.9709669352,
"start": 28554,
"tag": "NAME",
"value": "lathe"
},
{
"context": "\n , \"sauce\"\n , \"amber\"\n , \"lathe\"\n , \"carat\"\n , \"corer\"\n , \"dirty\"\n , \"slyly\"\n , ",
"end": 28573,
"score": 0.9911896586,
"start": 28568,
"tag": "NAME",
"value": "carat"
},
{
"context": "\n , \"amber\"\n , \"lathe\"\n , \"carat\"\n , \"corer\"\n , \"dirty\"\n , \"slyly\"\n , \"affix\"\n , ",
"end": 28587,
"score": 0.987383604,
"start": 28582,
"tag": "NAME",
"value": "corer"
},
{
"context": "\n , \"lathe\"\n , \"carat\"\n , \"corer\"\n , \"dirty\"\n , \"slyly\"\n , \"affix\"\n , \"alloy\"\n , ",
"end": 28601,
"score": 0.7841975093,
"start": 28596,
"tag": "NAME",
"value": "dirty"
},
{
"context": "\n , \"carat\"\n , \"corer\"\n , \"dirty\"\n , \"slyly\"\n , \"affix\"\n , \"alloy\"\n , \"taint\"\n , ",
"end": 28615,
"score": 0.9546890855,
"start": 28610,
"tag": "NAME",
"value": "slyly"
},
{
"context": "\n , \"corer\"\n , \"dirty\"\n , \"slyly\"\n , \"affix\"\n , \"alloy\"\n , \"taint\"\n , \"sheep\"\n , ",
"end": 28629,
"score": 0.96995157,
"start": 28624,
"tag": "NAME",
"value": "affix"
},
{
"context": "\n , \"dirty\"\n , \"slyly\"\n , \"affix\"\n , \"alloy\"\n , \"taint\"\n , \"sheep\"\n , \"kinky\"\n , ",
"end": 28643,
"score": 0.9894286394,
"start": 28638,
"tag": "NAME",
"value": "alloy"
},
{
"context": "\n , \"slyly\"\n , \"affix\"\n , \"alloy\"\n , \"taint\"\n , \"sheep\"\n , \"kinky\"\n , \"wooly\"\n , ",
"end": 28657,
"score": 0.9410257339,
"start": 28652,
"tag": "NAME",
"value": "taint"
},
{
"context": "\n , \"affix\"\n , \"alloy\"\n , \"taint\"\n , \"sheep\"\n , \"kinky\"\n , \"wooly\"\n , \"mauve\"\n , ",
"end": 28671,
"score": 0.5821341276,
"start": 28666,
"tag": "NAME",
"value": "sheep"
},
{
"context": "\n , \"alloy\"\n , \"taint\"\n , \"sheep\"\n , \"kinky\"\n , \"wooly\"\n , \"mauve\"\n , \"flung\"\n , ",
"end": 28685,
"score": 0.6657504439,
"start": 28680,
"tag": "NAME",
"value": "kinky"
},
{
"context": "\n , \"taint\"\n , \"sheep\"\n , \"kinky\"\n , \"wooly\"\n , \"mauve\"\n , \"flung\"\n , \"yacht\"\n , ",
"end": 28699,
"score": 0.7868651748,
"start": 28694,
"tag": "NAME",
"value": "wooly"
},
{
"context": "\n , \"sheep\"\n , \"kinky\"\n , \"wooly\"\n , \"mauve\"\n , \"flung\"\n , \"yacht\"\n , \"fried\"\n , ",
"end": 28713,
"score": 0.7120172977,
"start": 28708,
"tag": "NAME",
"value": "mauve"
},
{
"context": "\n , \"kinky\"\n , \"wooly\"\n , \"mauve\"\n , \"flung\"\n , \"yacht\"\n , \"fried\"\n , \"quail\"\n , ",
"end": 28727,
"score": 0.7546830177,
"start": 28722,
"tag": "NAME",
"value": "flung"
},
{
"context": "\n , \"wooly\"\n , \"mauve\"\n , \"flung\"\n , \"yacht\"\n , \"fried\"\n , \"quail\"\n , \"brunt\"\n ",
"end": 28737,
"score": 0.4997920692,
"start": 28736,
"tag": "NAME",
"value": "y"
},
{
"context": "\n , \"mauve\"\n , \"flung\"\n , \"yacht\"\n , \"fried\"\n , \"quail\"\n , \"brunt\"\n , \"grimy\"\n , ",
"end": 28755,
"score": 0.535566926,
"start": 28750,
"tag": "NAME",
"value": "fried"
},
{
"context": "\n , \"flung\"\n , \"yacht\"\n , \"fried\"\n , \"quail\"\n , \"brunt\"\n , \"grimy\"\n , \"curvy\"\n , ",
"end": 28769,
"score": 0.6112939119,
"start": 28764,
"tag": "NAME",
"value": "quail"
},
{
"context": "\n , \"yacht\"\n , \"fried\"\n , \"quail\"\n , \"brunt\"\n , \"grimy\"\n , \"curvy\"\n , \"cagey\"\n , ",
"end": 28783,
"score": 0.7393249273,
"start": 28778,
"tag": "NAME",
"value": "brunt"
},
{
"context": "\n , \"fried\"\n , \"quail\"\n , \"brunt\"\n , \"grimy\"\n , \"curvy\"\n , \"cagey\"\n , \"rinse\"\n , ",
"end": 28797,
"score": 0.9758188725,
"start": 28792,
"tag": "NAME",
"value": "grimy"
},
{
"context": "\n , \"quail\"\n , \"brunt\"\n , \"grimy\"\n , \"curvy\"\n , \"cagey\"\n , \"rinse\"\n , \"deuce\"\n , ",
"end": 28811,
"score": 0.9423952103,
"start": 28806,
"tag": "NAME",
"value": "curvy"
},
{
"context": "\n , \"brunt\"\n , \"grimy\"\n , \"curvy\"\n , \"cagey\"\n , \"rinse\"\n , \"deuce\"\n , \"state\"\n , ",
"end": 28825,
"score": 0.9600000381,
"start": 28820,
"tag": "NAME",
"value": "cagey"
},
{
"context": "\n , \"grimy\"\n , \"curvy\"\n , \"cagey\"\n , \"rinse\"\n , \"deuce\"\n , \"state\"\n , \"grasp\"\n , ",
"end": 28839,
"score": 0.9703658819,
"start": 28834,
"tag": "NAME",
"value": "rinse"
},
{
"context": "\n , \"curvy\"\n , \"cagey\"\n , \"rinse\"\n , \"deuce\"\n , \"state\"\n , \"grasp\"\n , \"milky\"\n , ",
"end": 28853,
"score": 0.8555675149,
"start": 28848,
"tag": "NAME",
"value": "deuce"
},
{
"context": "\n , \"state\"\n , \"grasp\"\n , \"milky\"\n , \"bison\"\n , \"graft\"\n , \"sandy\"\n , \"baste\"\n , ",
"end": 28909,
"score": 0.860923171,
"start": 28904,
"tag": "NAME",
"value": "bison"
},
{
"context": "\n , \"grasp\"\n , \"milky\"\n , \"bison\"\n , \"graft\"\n , \"sandy\"\n , \"baste\"\n , \"flask\"\n , ",
"end": 28923,
"score": 0.7372642159,
"start": 28918,
"tag": "NAME",
"value": "graft"
},
{
"context": "\n , \"graft\"\n , \"sandy\"\n , \"baste\"\n , \"flask\"\n , \"hedge\"\n , \"girly\"\n , \"swash\"\n , ",
"end": 28965,
"score": 0.7723966837,
"start": 28960,
"tag": "NAME",
"value": "flask"
},
{
"context": "\n , \"sandy\"\n , \"baste\"\n , \"flask\"\n , \"hedge\"\n , \"girly\"\n , \"swash\"\n , \"boney\"\n , ",
"end": 28979,
"score": 0.9217107296,
"start": 28974,
"tag": "NAME",
"value": "hedge"
},
{
"context": "\n , \"baste\"\n , \"flask\"\n , \"hedge\"\n , \"girly\"\n , \"swash\"\n , \"boney\"\n , \"coupe\"\n , ",
"end": 28993,
"score": 0.9727563858,
"start": 28988,
"tag": "NAME",
"value": "girly"
},
{
"context": "\n , \"flask\"\n , \"hedge\"\n , \"girly\"\n , \"swash\"\n , \"boney\"\n , \"coupe\"\n , \"endow\"\n , ",
"end": 29007,
"score": 0.9321784973,
"start": 29002,
"tag": "NAME",
"value": "swash"
},
{
"context": "\n , \"hedge\"\n , \"girly\"\n , \"swash\"\n , \"boney\"\n , \"coupe\"\n , \"endow\"\n , \"abhor\"\n , ",
"end": 29021,
"score": 0.8261144161,
"start": 29016,
"tag": "NAME",
"value": "boney"
},
{
"context": "\n , \"girly\"\n , \"swash\"\n , \"boney\"\n , \"coupe\"\n , \"endow\"\n , \"abhor\"\n , \"welch\"\n , ",
"end": 29035,
"score": 0.804164052,
"start": 29030,
"tag": "NAME",
"value": "coupe"
},
{
"context": "\n , \"swash\"\n , \"boney\"\n , \"coupe\"\n , \"endow\"\n , \"abhor\"\n , \"welch\"\n , \"blade\"\n , ",
"end": 29049,
"score": 0.8443319201,
"start": 29044,
"tag": "NAME",
"value": "endow"
},
{
"context": "\n , \"boney\"\n , \"coupe\"\n , \"endow\"\n , \"abhor\"\n , \"welch\"\n , \"blade\"\n , \"tight\"\n , ",
"end": 29063,
"score": 0.9855731726,
"start": 29058,
"tag": "NAME",
"value": "abhor"
},
{
"context": "\n , \"coupe\"\n , \"endow\"\n , \"abhor\"\n , \"welch\"\n , \"blade\"\n , \"tight\"\n , \"geese\"\n , ",
"end": 29077,
"score": 0.7101022601,
"start": 29072,
"tag": "NAME",
"value": "welch"
},
{
"context": "\n , \"abhor\"\n , \"welch\"\n , \"blade\"\n , \"tight\"\n , \"geese\"\n , \"miser\"\n , \"mirth\"\n , ",
"end": 29105,
"score": 0.5566421747,
"start": 29100,
"tag": "NAME",
"value": "tight"
},
{
"context": "\n , \"welch\"\n , \"blade\"\n , \"tight\"\n , \"geese\"\n , \"miser\"\n , \"mirth\"\n , \"cloud\"\n , ",
"end": 29119,
"score": 0.8916215897,
"start": 29114,
"tag": "NAME",
"value": "geese"
},
{
"context": "\n , \"blade\"\n , \"tight\"\n , \"geese\"\n , \"miser\"\n , \"mirth\"\n , \"cloud\"\n , \"cabal\"\n , ",
"end": 29133,
"score": 0.9664727449,
"start": 29128,
"tag": "NAME",
"value": "miser"
},
{
"context": "\n , \"tight\"\n , \"geese\"\n , \"miser\"\n , \"mirth\"\n , \"cloud\"\n , \"cabal\"\n , \"leech\"\n , ",
"end": 29147,
"score": 0.9314109087,
"start": 29142,
"tag": "NAME",
"value": "mirth"
},
{
"context": " , \"mirth\"\n , \"cloud\"\n , \"cabal\"\n , \"leech\"\n , \"close\"\n , \"tenth\"\n , \"pecan\"\n , ",
"end": 29189,
"score": 0.5400891304,
"start": 29186,
"tag": "NAME",
"value": "ech"
},
{
"context": "\n , \"leech\"\n , \"close\"\n , \"tenth\"\n , \"pecan\"\n , \"droit\"\n , \"grail\"\n , \"clone\"\n , ",
"end": 29231,
"score": 0.8059729338,
"start": 29226,
"tag": "NAME",
"value": "pecan"
},
{
"context": "\n , \"close\"\n , \"tenth\"\n , \"pecan\"\n , \"droit\"\n , \"grail\"\n , \"clone\"\n , \"guise\"\n , ",
"end": 29245,
"score": 0.7073656321,
"start": 29240,
"tag": "NAME",
"value": "droit"
},
{
"context": "\n , \"tenth\"\n , \"pecan\"\n , \"droit\"\n , \"grail\"\n , \"clone\"\n , \"guise\"\n , \"ralph\"\n ",
"end": 29256,
"score": 0.5376480818,
"start": 29254,
"tag": "NAME",
"value": "gr"
},
{
"context": "\n , \"pecan\"\n , \"droit\"\n , \"grail\"\n , \"clone\"\n , \"guise\"\n , \"ralph\"\n , \"tango\"\n , ",
"end": 29273,
"score": 0.5028273463,
"start": 29268,
"tag": "NAME",
"value": "clone"
},
{
"context": "\n , \"droit\"\n , \"grail\"\n , \"clone\"\n , \"guise\"\n , \"ralph\"\n , \"tango\"\n , \"biddy\"\n , ",
"end": 29287,
"score": 0.9205055237,
"start": 29282,
"tag": "NAME",
"value": "guise"
},
{
"context": "\n , \"grail\"\n , \"clone\"\n , \"guise\"\n , \"ralph\"\n , \"tango\"\n , \"biddy\"\n , \"smith\"\n , ",
"end": 29301,
"score": 0.9859150648,
"start": 29296,
"tag": "NAME",
"value": "ralph"
},
{
"context": "\n , \"clone\"\n , \"guise\"\n , \"ralph\"\n , \"tango\"\n , \"biddy\"\n , \"smith\"\n , \"mower\"\n , ",
"end": 29315,
"score": 0.6650565863,
"start": 29310,
"tag": "NAME",
"value": "tango"
},
{
"context": "\n , \"guise\"\n , \"ralph\"\n , \"tango\"\n , \"biddy\"\n , \"smith\"\n , \"mower\"\n , \"payee\"\n , ",
"end": 29329,
"score": 0.9223760962,
"start": 29324,
"tag": "NAME",
"value": "biddy"
},
{
"context": "\n , \"ralph\"\n , \"tango\"\n , \"biddy\"\n , \"smith\"\n , \"mower\"\n , \"payee\"\n , \"serif\"\n , ",
"end": 29343,
"score": 0.981349647,
"start": 29338,
"tag": "NAME",
"value": "smith"
},
{
"context": "\n , \"tango\"\n , \"biddy\"\n , \"smith\"\n , \"mower\"\n , \"payee\"\n , \"serif\"\n , \"drape\"\n , ",
"end": 29357,
"score": 0.9296617508,
"start": 29352,
"tag": "NAME",
"value": "mower"
},
{
"context": "\n , \"biddy\"\n , \"smith\"\n , \"mower\"\n , \"payee\"\n , \"serif\"\n , \"drape\"\n , \"fifth\"\n ",
"end": 29369,
"score": 0.7437238693,
"start": 29366,
"tag": "NAME",
"value": "pay"
},
{
"context": "\n , \"smith\"\n , \"mower\"\n , \"payee\"\n , \"serif\"\n , \"drape\"\n , \"fifth\"\n , \"spank\"\n , ",
"end": 29385,
"score": 0.6158893108,
"start": 29380,
"tag": "NAME",
"value": "serif"
},
{
"context": "\n , \"mower\"\n , \"payee\"\n , \"serif\"\n , \"drape\"\n , \"fifth\"\n , \"spank\"\n , \"glaze\"\n , ",
"end": 29399,
"score": 0.9348795414,
"start": 29394,
"tag": "NAME",
"value": "drape"
},
{
"context": " , \"payee\"\n , \"serif\"\n , \"drape\"\n , \"fifth\"\n , \"spank\"\n , \"glaze\"\n , \"allot\"\n , ",
"end": 29413,
"score": 0.4986438751,
"start": 29409,
"tag": "NAME",
"value": "ifth"
},
{
"context": "\n , \"serif\"\n , \"drape\"\n , \"fifth\"\n , \"spank\"\n , \"glaze\"\n , \"allot\"\n , \"truck\"\n , ",
"end": 29427,
"score": 0.6801348925,
"start": 29422,
"tag": "NAME",
"value": "spank"
},
{
"context": "\n , \"drape\"\n , \"fifth\"\n , \"spank\"\n , \"glaze\"\n , \"allot\"\n , \"truck\"\n , \"kayak\"\n , ",
"end": 29441,
"score": 0.7221796513,
"start": 29436,
"tag": "NAME",
"value": "glaze"
},
{
"context": "\n , \"fifth\"\n , \"spank\"\n , \"glaze\"\n , \"allot\"\n , \"truck\"\n , \"kayak\"\n , \"virus\"\n , ",
"end": 29455,
"score": 0.9312268496,
"start": 29450,
"tag": "NAME",
"value": "allot"
},
{
"context": "\n , \"spank\"\n , \"glaze\"\n , \"allot\"\n , \"truck\"\n , \"kayak\"\n , \"virus\"\n , \"testy\"\n , ",
"end": 29469,
"score": 0.8621814847,
"start": 29464,
"tag": "NAME",
"value": "truck"
},
{
"context": "\n , \"glaze\"\n , \"allot\"\n , \"truck\"\n , \"kayak\"\n , \"virus\"\n , \"testy\"\n , \"tepee\"\n , ",
"end": 29483,
"score": 0.7615542412,
"start": 29478,
"tag": "NAME",
"value": "kayak"
},
{
"context": "\n , \"allot\"\n , \"truck\"\n , \"kayak\"\n , \"virus\"\n , \"testy\"\n , \"tepee\"\n , \"fully\"\n , ",
"end": 29497,
"score": 0.949870944,
"start": 29492,
"tag": "NAME",
"value": "virus"
},
{
"context": "\n , \"truck\"\n , \"kayak\"\n , \"virus\"\n , \"testy\"\n , \"tepee\"\n , \"fully\"\n , \"zonal\"\n , ",
"end": 29511,
"score": 0.6688158512,
"start": 29506,
"tag": "NAME",
"value": "testy"
},
{
"context": "\n , \"kayak\"\n , \"virus\"\n , \"testy\"\n , \"tepee\"\n , \"fully\"\n , \"zonal\"\n , \"metro\"\n , ",
"end": 29525,
"score": 0.5999829769,
"start": 29520,
"tag": "NAME",
"value": "tepee"
},
{
"context": "\n , \"fully\"\n , \"zonal\"\n , \"metro\"\n , \"curry\"\n , \"grand\"\n , \"banjo\"\n , \"axion\"\n , ",
"end": 29581,
"score": 0.7010211945,
"start": 29576,
"tag": "NAME",
"value": "curry"
},
{
"context": "\n , \"zonal\"\n , \"metro\"\n , \"curry\"\n , \"grand\"\n , \"banjo\"\n , \"axion\"\n , \"bezel\"\n , ",
"end": 29595,
"score": 0.5816042423,
"start": 29590,
"tag": "NAME",
"value": "grand"
},
{
"context": "\n , \"metro\"\n , \"curry\"\n , \"grand\"\n , \"banjo\"\n , \"axion\"\n , \"bezel\"\n , \"occur\"\n , ",
"end": 29609,
"score": 0.8215458393,
"start": 29604,
"tag": "NAME",
"value": "banjo"
},
{
"context": "\n , \"curry\"\n , \"grand\"\n , \"banjo\"\n , \"axion\"\n , \"bezel\"\n , \"occur\"\n , \"chain\"\n , ",
"end": 29623,
"score": 0.8805854321,
"start": 29618,
"tag": "NAME",
"value": "axion"
},
{
"context": "\n , \"grand\"\n , \"banjo\"\n , \"axion\"\n , \"bezel\"\n , \"occur\"\n , \"chain\"\n , \"nasal\"\n , ",
"end": 29637,
"score": 0.8812055588,
"start": 29632,
"tag": "NAME",
"value": "bezel"
},
{
"context": "\n , \"verso\"\n , \"quash\"\n , \"fauna\"\n , \"gummy\"\n , \"happy\"\n , \"newly\"\n , \"fussy\"\n , ",
"end": 30939,
"score": 0.9842461944,
"start": 30934,
"tag": "NAME",
"value": "gummy"
},
{
"context": "\n , \"quash\"\n , \"fauna\"\n , \"gummy\"\n , \"happy\"\n , \"newly\"\n , \"fussy\"\n , \"relic\"\n , ",
"end": 30953,
"score": 0.764781177,
"start": 30948,
"tag": "NAME",
"value": "happy"
},
{
"context": "\n , \"fauna\"\n , \"gummy\"\n , \"happy\"\n , \"newly\"\n , \"fussy\"\n , \"relic\"\n , \"guava\"\n , ",
"end": 30967,
"score": 0.9614762068,
"start": 30962,
"tag": "NAME",
"value": "newly"
},
{
"context": "\n , \"gummy\"\n , \"happy\"\n , \"newly\"\n , \"fussy\"\n , \"relic\"\n , \"guava\"\n , \"ratty\"\n , ",
"end": 30981,
"score": 0.9861879945,
"start": 30976,
"tag": "NAME",
"value": "fussy"
},
{
"context": "\n , \"happy\"\n , \"newly\"\n , \"fussy\"\n , \"relic\"\n , \"guava\"\n , \"ratty\"\n , \"fudge\"\n , ",
"end": 30995,
"score": 0.9823692441,
"start": 30990,
"tag": "NAME",
"value": "relic"
},
{
"context": "\n , \"newly\"\n , \"fussy\"\n , \"relic\"\n , \"guava\"\n , \"ratty\"\n , \"fudge\"\n , \"femur\"\n , ",
"end": 31009,
"score": 0.9922235012,
"start": 31004,
"tag": "NAME",
"value": "guava"
},
{
"context": "\n , \"fussy\"\n , \"relic\"\n , \"guava\"\n , \"ratty\"\n , \"fudge\"\n , \"femur\"\n , \"chirp\"\n , ",
"end": 31023,
"score": 0.9925578237,
"start": 31018,
"tag": "NAME",
"value": "ratty"
},
{
"context": "\n , \"relic\"\n , \"guava\"\n , \"ratty\"\n , \"fudge\"\n , \"femur\"\n , \"chirp\"\n , \"forte\"\n , ",
"end": 31037,
"score": 0.992934823,
"start": 31032,
"tag": "NAME",
"value": "fudge"
},
{
"context": "\n , \"guava\"\n , \"ratty\"\n , \"fudge\"\n , \"femur\"\n , \"chirp\"\n , \"forte\"\n , \"alibi\"\n , ",
"end": 31051,
"score": 0.9950796962,
"start": 31046,
"tag": "NAME",
"value": "femur"
},
{
"context": "\n , \"ratty\"\n , \"fudge\"\n , \"femur\"\n , \"chirp\"\n , \"forte\"\n , \"alibi\"\n , \"whine\"\n , ",
"end": 31065,
"score": 0.9930799007,
"start": 31060,
"tag": "NAME",
"value": "chirp"
},
{
"context": "\n , \"fudge\"\n , \"femur\"\n , \"chirp\"\n , \"forte\"\n , \"alibi\"\n , \"whine\"\n , \"petty\"\n , ",
"end": 31079,
"score": 0.9939483404,
"start": 31074,
"tag": "NAME",
"value": "forte"
},
{
"context": "\n , \"femur\"\n , \"chirp\"\n , \"forte\"\n , \"alibi\"\n , \"whine\"\n , \"petty\"\n , \"golly\"\n , ",
"end": 31093,
"score": 0.9946466684,
"start": 31088,
"tag": "NAME",
"value": "alibi"
},
{
"context": "\n , \"chirp\"\n , \"forte\"\n , \"alibi\"\n , \"whine\"\n , \"petty\"\n , \"golly\"\n , \"plait\"\n , ",
"end": 31107,
"score": 0.9895873666,
"start": 31102,
"tag": "NAME",
"value": "whine"
},
{
"context": "\n , \"forte\"\n , \"alibi\"\n , \"whine\"\n , \"petty\"\n , \"golly\"\n , \"plait\"\n , \"fleck\"\n , ",
"end": 31121,
"score": 0.9928566217,
"start": 31116,
"tag": "NAME",
"value": "petty"
},
{
"context": "\n , \"alibi\"\n , \"whine\"\n , \"petty\"\n , \"golly\"\n , \"plait\"\n , \"fleck\"\n , \"felon\"\n , ",
"end": 31135,
"score": 0.9966978431,
"start": 31130,
"tag": "NAME",
"value": "golly"
},
{
"context": "\n , \"whine\"\n , \"petty\"\n , \"golly\"\n , \"plait\"\n , \"fleck\"\n , \"felon\"\n , \"gourd\"\n , ",
"end": 31149,
"score": 0.9906935096,
"start": 31144,
"tag": "NAME",
"value": "plait"
},
{
"context": "\n , \"petty\"\n , \"golly\"\n , \"plait\"\n , \"fleck\"\n , \"felon\"\n , \"gourd\"\n , \"brown\"\n , ",
"end": 31163,
"score": 0.9964495301,
"start": 31158,
"tag": "NAME",
"value": "fleck"
},
{
"context": "\n , \"golly\"\n , \"plait\"\n , \"fleck\"\n , \"felon\"\n , \"gourd\"\n , \"brown\"\n , \"thrum\"\n , ",
"end": 31177,
"score": 0.9980117679,
"start": 31172,
"tag": "NAME",
"value": "felon"
},
{
"context": "\n , \"plait\"\n , \"fleck\"\n , \"felon\"\n , \"gourd\"\n , \"brown\"\n , \"thrum\"\n , \"ficus\"\n , ",
"end": 31191,
"score": 0.993566215,
"start": 31186,
"tag": "NAME",
"value": "gourd"
},
{
"context": "\n , \"fleck\"\n , \"felon\"\n , \"gourd\"\n , \"brown\"\n , \"thrum\"\n , \"ficus\"\n , \"stash\"\n , ",
"end": 31205,
"score": 0.9941172004,
"start": 31200,
"tag": "NAME",
"value": "brown"
},
{
"context": "\n , \"felon\"\n , \"gourd\"\n , \"brown\"\n , \"thrum\"\n , \"ficus\"\n , \"stash\"\n , \"decry\"\n , ",
"end": 31219,
"score": 0.9920539856,
"start": 31214,
"tag": "NAME",
"value": "thrum"
},
{
"context": "\n , \"gourd\"\n , \"brown\"\n , \"thrum\"\n , \"ficus\"\n , \"stash\"\n , \"decry\"\n , \"wiser\"\n , ",
"end": 31233,
"score": 0.9933438897,
"start": 31228,
"tag": "NAME",
"value": "ficus"
},
{
"context": "\n , \"brown\"\n , \"thrum\"\n , \"ficus\"\n , \"stash\"\n , \"decry\"\n , \"wiser\"\n , \"junta\"\n , ",
"end": 31247,
"score": 0.9452915788,
"start": 31242,
"tag": "NAME",
"value": "stash"
},
{
"context": "\n , \"thrum\"\n , \"ficus\"\n , \"stash\"\n , \"decry\"\n , \"wiser\"\n , \"junta\"\n , \"visor\"\n , ",
"end": 31261,
"score": 0.9535508156,
"start": 31256,
"tag": "NAME",
"value": "decry"
},
{
"context": "\n , \"ficus\"\n , \"stash\"\n , \"decry\"\n , \"wiser\"\n , \"junta\"\n , \"visor\"\n , \"daunt\"\n , ",
"end": 31275,
"score": 0.9687646627,
"start": 31270,
"tag": "NAME",
"value": "wiser"
},
{
"context": "\n , \"stash\"\n , \"decry\"\n , \"wiser\"\n , \"junta\"\n , \"visor\"\n , \"daunt\"\n , \"scree\"\n , ",
"end": 31289,
"score": 0.9880385399,
"start": 31284,
"tag": "NAME",
"value": "junta"
},
{
"context": "\n , \"decry\"\n , \"wiser\"\n , \"junta\"\n , \"visor\"\n , \"daunt\"\n , \"scree\"\n , \"impel\"\n , ",
"end": 31303,
"score": 0.9836717248,
"start": 31298,
"tag": "NAME",
"value": "visor"
},
{
"context": "\n , \"wiser\"\n , \"junta\"\n , \"visor\"\n , \"daunt\"\n , \"scree\"\n , \"impel\"\n , \"await\"\n , ",
"end": 31317,
"score": 0.9888989925,
"start": 31312,
"tag": "NAME",
"value": "daunt"
},
{
"context": "\n , \"junta\"\n , \"visor\"\n , \"daunt\"\n , \"scree\"\n , \"impel\"\n , \"await\"\n , \"press\"\n , ",
"end": 31331,
"score": 0.9699237347,
"start": 31326,
"tag": "NAME",
"value": "scree"
},
{
"context": "\n , \"visor\"\n , \"daunt\"\n , \"scree\"\n , \"impel\"\n , \"await\"\n , \"press\"\n , \"whose\"\n , ",
"end": 31345,
"score": 0.9007207155,
"start": 31340,
"tag": "NAME",
"value": "impel"
},
{
"context": "\n , \"daunt\"\n , \"scree\"\n , \"impel\"\n , \"await\"\n , \"press\"\n , \"whose\"\n , \"turbo\"\n , ",
"end": 31359,
"score": 0.6038564444,
"start": 31354,
"tag": "NAME",
"value": "await"
},
{
"context": "\n , \"impel\"\n , \"await\"\n , \"press\"\n , \"whose\"\n , \"turbo\"\n , \"stoop\"\n , \"speak\"\n ",
"end": 31384,
"score": 0.4989857376,
"start": 31382,
"tag": "NAME",
"value": "wh"
},
{
"context": "\n , \"await\"\n , \"press\"\n , \"whose\"\n , \"turbo\"\n , \"stoop\"\n , \"speak\"\n , \"mangy\"\n , ",
"end": 31401,
"score": 0.9348088503,
"start": 31396,
"tag": "NAME",
"value": "turbo"
},
{
"context": "\n , \"press\"\n , \"whose\"\n , \"turbo\"\n , \"stoop\"\n , \"speak\"\n , \"mangy\"\n , \"eying\"\n , ",
"end": 31415,
"score": 0.8863230944,
"start": 31410,
"tag": "NAME",
"value": "stoop"
},
{
"context": "\n , \"turbo\"\n , \"stoop\"\n , \"speak\"\n , \"mangy\"\n , \"eying\"\n , \"inlet\"\n , \"crone\"\n , ",
"end": 31443,
"score": 0.9238989949,
"start": 31438,
"tag": "NAME",
"value": "mangy"
},
{
"context": "\n , \"stoop\"\n , \"speak\"\n , \"mangy\"\n , \"eying\"\n , \"inlet\"\n , \"crone\"\n , \"pulse\"\n , ",
"end": 31457,
"score": 0.8691933155,
"start": 31452,
"tag": "NAME",
"value": "eying"
},
{
"context": "\n , \"speak\"\n , \"mangy\"\n , \"eying\"\n , \"inlet\"\n , \"crone\"\n , \"pulse\"\n , \"mossy\"\n , ",
"end": 31471,
"score": 0.625726819,
"start": 31466,
"tag": "NAME",
"value": "inlet"
},
{
"context": "\n , \"mangy\"\n , \"eying\"\n , \"inlet\"\n , \"crone\"\n , \"pulse\"\n , \"mossy\"\n , \"staid\"\n , ",
"end": 31485,
"score": 0.9243886471,
"start": 31480,
"tag": "NAME",
"value": "crone"
},
{
"context": "\n , \"eying\"\n , \"inlet\"\n , \"crone\"\n , \"pulse\"\n , \"mossy\"\n , \"staid\"\n , \"hence\"\n , ",
"end": 31499,
"score": 0.7537941933,
"start": 31494,
"tag": "NAME",
"value": "pulse"
},
{
"context": "\n , \"inlet\"\n , \"crone\"\n , \"pulse\"\n , \"mossy\"\n , \"staid\"\n , \"hence\"\n , \"pinch\"\n , ",
"end": 31513,
"score": 0.8425084949,
"start": 31508,
"tag": "NAME",
"value": "mossy"
},
{
"context": "\n , \"crone\"\n , \"pulse\"\n , \"mossy\"\n , \"staid\"\n , \"hence\"\n , \"pinch\"\n , \"teddy\"\n , ",
"end": 31527,
"score": 0.7614961267,
"start": 31522,
"tag": "NAME",
"value": "staid"
},
{
"context": "\n , \"pulse\"\n , \"mossy\"\n , \"staid\"\n , \"hence\"\n , \"pinch\"\n , \"teddy\"\n , \"sully\"\n , ",
"end": 31541,
"score": 0.7667169571,
"start": 31536,
"tag": "NAME",
"value": "hence"
},
{
"context": "\n , \"mossy\"\n , \"staid\"\n , \"hence\"\n , \"pinch\"\n , \"teddy\"\n , \"sully\"\n , \"snore\"\n , ",
"end": 31555,
"score": 0.8654849529,
"start": 31550,
"tag": "NAME",
"value": "pinch"
},
{
"context": "\n , \"staid\"\n , \"hence\"\n , \"pinch\"\n , \"teddy\"\n , \"sully\"\n , \"snore\"\n , \"ripen\"\n , ",
"end": 31569,
"score": 0.9189480543,
"start": 31564,
"tag": "NAME",
"value": "teddy"
},
{
"context": "\n , \"hence\"\n , \"pinch\"\n , \"teddy\"\n , \"sully\"\n , \"snore\"\n , \"ripen\"\n , \"snowy\"\n , ",
"end": 31583,
"score": 0.920024395,
"start": 31578,
"tag": "NAME",
"value": "sully"
},
{
"context": " , \"pinch\"\n , \"teddy\"\n , \"sully\"\n , \"snore\"\n , \"ripen\"\n , \"snowy\"\n , \"attic\"\n , ",
"end": 31597,
"score": 0.5929480195,
"start": 31594,
"tag": "NAME",
"value": "ore"
},
{
"context": "\n , \"teddy\"\n , \"sully\"\n , \"snore\"\n , \"ripen\"\n , \"snowy\"\n , \"attic\"\n , \"going\"\n , ",
"end": 31611,
"score": 0.9772776961,
"start": 31606,
"tag": "NAME",
"value": "ripen"
},
{
"context": "\n , \"sully\"\n , \"snore\"\n , \"ripen\"\n , \"snowy\"\n , \"attic\"\n , \"going\"\n , \"leach\"\n ,",
"end": 31624,
"score": 0.5154798031,
"start": 31620,
"tag": "NAME",
"value": "snow"
},
{
"context": "\n , \"snore\"\n , \"ripen\"\n , \"snowy\"\n , \"attic\"\n , \"going\"\n , \"leach\"\n , \"mouth\"\n , ",
"end": 31639,
"score": 0.7618014216,
"start": 31634,
"tag": "NAME",
"value": "attic"
},
{
"context": "\n , \"going\"\n , \"leach\"\n , \"mouth\"\n , \"hound\"\n , \"clump\"\n , \"tonal\"\n , \"bigot\"\n , ",
"end": 31695,
"score": 0.7259322405,
"start": 31690,
"tag": "NAME",
"value": "hound"
},
{
"context": "\n , \"leach\"\n , \"mouth\"\n , \"hound\"\n , \"clump\"\n , \"tonal\"\n , \"bigot\"\n , \"peril\"\n , ",
"end": 31709,
"score": 0.9647170305,
"start": 31704,
"tag": "NAME",
"value": "clump"
},
{
"context": "\n , \"mouth\"\n , \"hound\"\n , \"clump\"\n , \"tonal\"\n , \"bigot\"\n , \"peril\"\n , \"piece\"\n , ",
"end": 31723,
"score": 0.7059000731,
"start": 31718,
"tag": "NAME",
"value": "tonal"
},
{
"context": "\n , \"hound\"\n , \"clump\"\n , \"tonal\"\n , \"bigot\"\n , \"peril\"\n , \"piece\"\n , \"blame\"\n , ",
"end": 31737,
"score": 0.9040019512,
"start": 31732,
"tag": "NAME",
"value": "bigot"
},
{
"context": "\n , \"clump\"\n , \"tonal\"\n , \"bigot\"\n , \"peril\"\n , \"piece\"\n , \"blame\"\n , \"haute\"\n , ",
"end": 31751,
"score": 0.9635663629,
"start": 31746,
"tag": "NAME",
"value": "peril"
},
{
"context": " , \"bigot\"\n , \"peril\"\n , \"piece\"\n , \"blame\"\n , \"haute\"\n , \"spied\"\n , \"undid\"\n , ",
"end": 31779,
"score": 0.6088770032,
"start": 31776,
"tag": "NAME",
"value": "ame"
},
{
"context": "\n , \"peril\"\n , \"piece\"\n , \"blame\"\n , \"haute\"\n , \"spied\"\n , \"undid\"\n , \"intro\"\n , ",
"end": 31793,
"score": 0.630425334,
"start": 31788,
"tag": "NAME",
"value": "haute"
},
{
"context": " , \"piece\"\n , \"blame\"\n , \"haute\"\n , \"spied\"\n , \"undid\"\n , \"intro\"\n , \"basal\"\n , ",
"end": 31807,
"score": 0.606171608,
"start": 31804,
"tag": "NAME",
"value": "ied"
},
{
"context": "\n , \"blame\"\n , \"haute\"\n , \"spied\"\n , \"undid\"\n , \"intro\"\n , \"basal\"\n , \"shine\"\n ",
"end": 31819,
"score": 0.7470024824,
"start": 31816,
"tag": "NAME",
"value": "und"
},
{
"context": "\n , \"spied\"\n , \"undid\"\n , \"intro\"\n , \"basal\"\n , \"shine\"\n , \"gecko\"\n , \"rodeo\"\n , ",
"end": 31849,
"score": 0.690359354,
"start": 31844,
"tag": "NAME",
"value": "basal"
},
{
"context": "\n , \"undid\"\n , \"intro\"\n , \"basal\"\n , \"shine\"\n , \"gecko\"\n , \"rodeo\"\n , \"guard\"\n , ",
"end": 31863,
"score": 0.6332029104,
"start": 31858,
"tag": "NAME",
"value": "shine"
},
{
"context": "\n , \"intro\"\n , \"basal\"\n , \"shine\"\n , \"gecko\"\n , \"rodeo\"\n , \"guard\"\n , \"steer\"\n , ",
"end": 31877,
"score": 0.9935046434,
"start": 31872,
"tag": "NAME",
"value": "gecko"
},
{
"context": "\n , \"basal\"\n , \"shine\"\n , \"gecko\"\n , \"rodeo\"\n , \"guard\"\n , \"steer\"\n , \"loamy\"\n , ",
"end": 31891,
"score": 0.9957483411,
"start": 31886,
"tag": "NAME",
"value": "rodeo"
},
{
"context": "\n , \"shine\"\n , \"gecko\"\n , \"rodeo\"\n , \"guard\"\n , \"steer\"\n , \"loamy\"\n , \"scamp\"\n , ",
"end": 31905,
"score": 0.6478586197,
"start": 31900,
"tag": "NAME",
"value": "guard"
},
{
"context": "\n , \"gecko\"\n , \"rodeo\"\n , \"guard\"\n , \"steer\"\n , \"loamy\"\n , \"scamp\"\n , \"scram\"\n , ",
"end": 31919,
"score": 0.9931600094,
"start": 31914,
"tag": "NAME",
"value": "steer"
},
{
"context": "\n , \"rodeo\"\n , \"guard\"\n , \"steer\"\n , \"loamy\"\n , \"scamp\"\n , \"scram\"\n , \"manly\"\n , ",
"end": 31933,
"score": 0.9953224063,
"start": 31928,
"tag": "NAME",
"value": "loamy"
},
{
"context": "\n , \"guard\"\n , \"steer\"\n , \"loamy\"\n , \"scamp\"\n , \"scram\"\n , \"manly\"\n , \"hello\"\n , ",
"end": 31947,
"score": 0.9677513242,
"start": 31942,
"tag": "NAME",
"value": "scamp"
},
{
"context": "\n , \"steer\"\n , \"loamy\"\n , \"scamp\"\n , \"scram\"\n , \"manly\"\n , \"hello\"\n , \"vaunt\"\n , ",
"end": 31961,
"score": 0.981610775,
"start": 31956,
"tag": "NAME",
"value": "scram"
},
{
"context": "\n , \"loamy\"\n , \"scamp\"\n , \"scram\"\n , \"manly\"\n , \"hello\"\n , \"vaunt\"\n , \"organ\"\n , ",
"end": 31975,
"score": 0.99655056,
"start": 31970,
"tag": "NAME",
"value": "manly"
},
{
"context": "\n , \"scram\"\n , \"manly\"\n , \"hello\"\n , \"vaunt\"\n , \"organ\"\n , \"feral\"\n , \"knock\"\n , ",
"end": 32003,
"score": 0.9931761026,
"start": 31998,
"tag": "NAME",
"value": "vaunt"
},
{
"context": "\n , \"manly\"\n , \"hello\"\n , \"vaunt\"\n , \"organ\"\n , \"feral\"\n , \"knock\"\n , \"extra\"\n , ",
"end": 32017,
"score": 0.9961737394,
"start": 32012,
"tag": "NAME",
"value": "organ"
},
{
"context": "\n , \"hello\"\n , \"vaunt\"\n , \"organ\"\n , \"feral\"\n , \"knock\"\n , \"extra\"\n , \"condo\"\n , ",
"end": 32031,
"score": 0.9964501262,
"start": 32026,
"tag": "NAME",
"value": "feral"
},
{
"context": "\n , \"vaunt\"\n , \"organ\"\n , \"feral\"\n , \"knock\"\n , \"extra\"\n , \"condo\"\n , \"adapt\"\n , ",
"end": 32045,
"score": 0.8991547227,
"start": 32040,
"tag": "NAME",
"value": "knock"
},
{
"context": "\n , \"feral\"\n , \"knock\"\n , \"extra\"\n , \"condo\"\n , \"adapt\"\n , \"willy\"\n , \"polka\"\n , ",
"end": 32073,
"score": 0.9445792437,
"start": 32068,
"tag": "NAME",
"value": "condo"
},
{
"context": "\n , \"knock\"\n , \"extra\"\n , \"condo\"\n , \"adapt\"\n , \"willy\"\n , \"polka\"\n , \"rayon\"\n , ",
"end": 32087,
"score": 0.8170577288,
"start": 32082,
"tag": "NAME",
"value": "adapt"
},
{
"context": "\n , \"extra\"\n , \"condo\"\n , \"adapt\"\n , \"willy\"\n , \"polka\"\n , \"rayon\"\n , \"skirt\"\n , ",
"end": 32101,
"score": 0.994573772,
"start": 32096,
"tag": "NAME",
"value": "willy"
},
{
"context": "\n , \"condo\"\n , \"adapt\"\n , \"willy\"\n , \"polka\"\n , \"rayon\"\n , \"skirt\"\n , \"faith\"\n , ",
"end": 32115,
"score": 0.9962491989,
"start": 32110,
"tag": "NAME",
"value": "polka"
},
{
"context": "\n , \"adapt\"\n , \"willy\"\n , \"polka\"\n , \"rayon\"\n , \"skirt\"\n , \"faith\"\n , \"torso\"\n , ",
"end": 32129,
"score": 0.9969722033,
"start": 32124,
"tag": "NAME",
"value": "rayon"
},
{
"context": "\n , \"willy\"\n , \"polka\"\n , \"rayon\"\n , \"skirt\"\n , \"faith\"\n , \"torso\"\n , \"match\"\n , ",
"end": 32143,
"score": 0.9817779064,
"start": 32138,
"tag": "NAME",
"value": "skirt"
},
{
"context": "\n , \"polka\"\n , \"rayon\"\n , \"skirt\"\n , \"faith\"\n , \"torso\"\n , \"match\"\n , \"mercy\"\n , ",
"end": 32157,
"score": 0.9989590645,
"start": 32152,
"tag": "NAME",
"value": "faith"
},
{
"context": "\n , \"rayon\"\n , \"skirt\"\n , \"faith\"\n , \"torso\"\n , \"match\"\n , \"mercy\"\n , \"tepid\"\n , ",
"end": 32171,
"score": 0.9991116524,
"start": 32166,
"tag": "NAME",
"value": "torso"
},
{
"context": "\n , \"skirt\"\n , \"faith\"\n , \"torso\"\n , \"match\"\n , \"mercy\"\n , \"tepid\"\n , \"sleek\"\n , ",
"end": 32185,
"score": 0.9209823012,
"start": 32180,
"tag": "NAME",
"value": "match"
},
{
"context": "\n , \"faith\"\n , \"torso\"\n , \"match\"\n , \"mercy\"\n , \"tepid\"\n , \"sleek\"\n , \"riser\"\n , ",
"end": 32199,
"score": 0.9992842674,
"start": 32194,
"tag": "NAME",
"value": "mercy"
},
{
"context": "\n , \"torso\"\n , \"match\"\n , \"mercy\"\n , \"tepid\"\n , \"sleek\"\n , \"riser\"\n , \"twixt\"\n , ",
"end": 32213,
"score": 0.9967471361,
"start": 32208,
"tag": "NAME",
"value": "tepid"
},
{
"context": "\n , \"match\"\n , \"mercy\"\n , \"tepid\"\n , \"sleek\"\n , \"riser\"\n , \"twixt\"\n , \"peace\"\n , ",
"end": 32227,
"score": 0.9928367734,
"start": 32222,
"tag": "NAME",
"value": "sleek"
},
{
"context": "\n , \"mercy\"\n , \"tepid\"\n , \"sleek\"\n , \"riser\"\n , \"twixt\"\n , \"peace\"\n , \"flush\"\n , ",
"end": 32241,
"score": 0.9992610812,
"start": 32236,
"tag": "NAME",
"value": "riser"
},
{
"context": "\n , \"tepid\"\n , \"sleek\"\n , \"riser\"\n , \"twixt\"\n , \"peace\"\n , \"flush\"\n , \"catty\"\n , ",
"end": 32255,
"score": 0.9988408685,
"start": 32250,
"tag": "NAME",
"value": "twixt"
},
{
"context": "\n , \"sleek\"\n , \"riser\"\n , \"twixt\"\n , \"peace\"\n , \"flush\"\n , \"catty\"\n , \"login\"\n , ",
"end": 32269,
"score": 0.9491337538,
"start": 32264,
"tag": "NAME",
"value": "peace"
},
{
"context": "\n , \"riser\"\n , \"twixt\"\n , \"peace\"\n , \"flush\"\n , \"catty\"\n , \"login\"\n , \"eject\"\n , ",
"end": 32283,
"score": 0.982617259,
"start": 32278,
"tag": "NAME",
"value": "flush"
},
{
"context": "\n , \"twixt\"\n , \"peace\"\n , \"flush\"\n , \"catty\"\n , \"login\"\n , \"eject\"\n , \"roger\"\n , ",
"end": 32297,
"score": 0.9987478256,
"start": 32292,
"tag": "NAME",
"value": "catty"
},
{
"context": "\n , \"peace\"\n , \"flush\"\n , \"catty\"\n , \"login\"\n , \"eject\"\n , \"roger\"\n , \"rival\"\n , ",
"end": 32311,
"score": 0.9900242686,
"start": 32306,
"tag": "NAME",
"value": "login"
},
{
"context": "\n , \"flush\"\n , \"catty\"\n , \"login\"\n , \"eject\"\n , \"roger\"\n , \"rival\"\n , \"untie\"\n , ",
"end": 32325,
"score": 0.9886541367,
"start": 32320,
"tag": "NAME",
"value": "eject"
},
{
"context": "\n , \"catty\"\n , \"login\"\n , \"eject\"\n , \"roger\"\n , \"rival\"\n , \"untie\"\n , \"refit\"\n , ",
"end": 32339,
"score": 0.9993014932,
"start": 32334,
"tag": "NAME",
"value": "roger"
},
{
"context": "\n , \"login\"\n , \"eject\"\n , \"roger\"\n , \"rival\"\n , \"untie\"\n , \"refit\"\n , \"aorta\"\n , ",
"end": 32353,
"score": 0.9331985712,
"start": 32348,
"tag": "NAME",
"value": "rival"
},
{
"context": "\n , \"eject\"\n , \"roger\"\n , \"rival\"\n , \"untie\"\n , \"refit\"\n , \"aorta\"\n , \"adult\"\n , ",
"end": 32367,
"score": 0.9863573909,
"start": 32362,
"tag": "NAME",
"value": "untie"
},
{
"context": "\n , \"roger\"\n , \"rival\"\n , \"untie\"\n , \"refit\"\n , \"aorta\"\n , \"adult\"\n , \"judge\"\n , ",
"end": 32381,
"score": 0.9764399529,
"start": 32376,
"tag": "NAME",
"value": "refit"
},
{
"context": "\n , \"rival\"\n , \"untie\"\n , \"refit\"\n , \"aorta\"\n , \"adult\"\n , \"judge\"\n , \"rower\"\n , ",
"end": 32395,
"score": 0.994799912,
"start": 32390,
"tag": "NAME",
"value": "aorta"
},
{
"context": "\n , \"aorta\"\n , \"adult\"\n , \"judge\"\n , \"rower\"\n , \"artsy\"\n , \"rural\"\n , \"shave\"\n ]\n",
"end": 32437,
"score": 0.9992843866,
"start": 32432,
"tag": "NAME",
"value": "rower"
},
{
"context": "\n , \"adult\"\n , \"judge\"\n , \"rower\"\n , \"artsy\"\n , \"rural\"\n , \"shave\"\n ]\n\n\nlength : Int",
"end": 32451,
"score": 0.9969661236,
"start": 32446,
"tag": "NAME",
"value": "artsy"
},
{
"context": "\n , \"judge\"\n , \"rower\"\n , \"artsy\"\n , \"rural\"\n , \"shave\"\n ]\n\n\nlength : Int\nlength =\n ",
"end": 32465,
"score": 0.8323135376,
"start": 32460,
"tag": "NAME",
"value": "rural"
},
{
"context": "\n , \"rower\"\n , \"artsy\"\n , \"rural\"\n , \"shave\"\n ]\n\n\nlength : Int\nlength =\n List.length as",
"end": 32479,
"score": 0.9669190645,
"start": 32474,
"tag": "NAME",
"value": "shave"
}
] | src/Words.elm | ericqweinstein/worsle | 0 | module Words exposing (asList, length)
asList : List String
asList =
[ "cigar"
, "rebut"
, "sissy"
, "humph"
, "awake"
, "blush"
, "focal"
, "evade"
, "naval"
, "serve"
, "heath"
, "dwarf"
, "model"
, "karma"
, "stink"
, "grade"
, "quiet"
, "bench"
, "abate"
, "feign"
, "major"
, "death"
, "fresh"
, "crust"
, "stool"
, "colon"
, "abase"
, "marry"
, "react"
, "batty"
, "pride"
, "floss"
, "helix"
, "croak"
, "staff"
, "paper"
, "unfed"
, "whelp"
, "trawl"
, "outdo"
, "adobe"
, "crazy"
, "sower"
, "repay"
, "digit"
, "crate"
, "cluck"
, "spike"
, "mimic"
, "pound"
, "maxim"
, "linen"
, "unmet"
, "flesh"
, "booby"
, "forth"
, "first"
, "stand"
, "belly"
, "ivory"
, "seedy"
, "print"
, "yearn"
, "drain"
, "bribe"
, "stout"
, "panel"
, "crass"
, "flume"
, "offal"
, "agree"
, "error"
, "swirl"
, "argue"
, "bleed"
, "delta"
, "flick"
, "totem"
, "wooer"
, "front"
, "shrub"
, "parry"
, "biome"
, "lapel"
, "start"
, "greet"
, "goner"
, "golem"
, "lusty"
, "loopy"
, "round"
, "audit"
, "lying"
, "gamma"
, "labor"
, "islet"
, "civic"
, "forge"
, "corny"
, "moult"
, "basic"
, "salad"
, "agate"
, "spicy"
, "spray"
, "essay"
, "fjord"
, "spend"
, "kebab"
, "guild"
, "aback"
, "motor"
, "alone"
, "hatch"
, "hyper"
, "thumb"
, "dowry"
, "ought"
, "belch"
, "dutch"
, "pilot"
, "tweed"
, "comet"
, "jaunt"
, "enema"
, "steed"
, "abyss"
, "growl"
, "fling"
, "dozen"
, "boozy"
, "erode"
, "world"
, "gouge"
, "click"
, "briar"
, "great"
, "altar"
, "pulpy"
, "blurt"
, "coast"
, "duchy"
, "groin"
, "fixer"
, "group"
, "rogue"
, "badly"
, "smart"
, "pithy"
, "gaudy"
, "chill"
, "heron"
, "vodka"
, "finer"
, "surer"
, "radio"
, "rouge"
, "perch"
, "retch"
, "wrote"
, "clock"
, "tilde"
, "store"
, "prove"
, "bring"
, "solve"
, "cheat"
, "grime"
, "exult"
, "usher"
, "epoch"
, "triad"
, "break"
, "rhino"
, "viral"
, "conic"
, "masse"
, "sonic"
, "vital"
, "trace"
, "using"
, "peach"
, "champ"
, "baton"
, "brake"
, "pluck"
, "craze"
, "gripe"
, "weary"
, "picky"
, "acute"
, "ferry"
, "aside"
, "tapir"
, "troll"
, "unify"
, "rebus"
, "boost"
, "truss"
, "siege"
, "tiger"
, "banal"
, "slump"
, "crank"
, "gorge"
, "query"
, "drink"
, "favor"
, "abbey"
, "tangy"
, "panic"
, "solar"
, "shire"
, "proxy"
, "point"
, "robot"
, "prick"
, "wince"
, "crimp"
, "knoll"
, "sugar"
, "whack"
, "mount"
, "perky"
, "could"
, "wrung"
, "light"
, "those"
, "moist"
, "shard"
, "pleat"
, "aloft"
, "skill"
, "elder"
, "frame"
, "humor"
, "pause"
, "ulcer"
, "ultra"
, "robin"
, "cynic"
, "agora"
, "aroma"
, "caulk"
, "shake"
, "pupal"
, "dodge"
, "swill"
, "tacit"
, "other"
, "thorn"
, "trove"
, "bloke"
, "vivid"
, "spill"
, "chant"
, "choke"
, "rupee"
, "nasty"
, "mourn"
, "ahead"
, "brine"
, "cloth"
, "hoard"
, "sweet"
, "month"
, "lapse"
, "watch"
, "today"
, "focus"
, "smelt"
, "tease"
, "cater"
, "movie"
, "lynch"
, "saute"
, "allow"
, "renew"
, "their"
, "slosh"
, "purge"
, "chest"
, "depot"
, "epoxy"
, "nymph"
, "found"
, "shall"
, "harry"
, "stove"
, "lowly"
, "snout"
, "trope"
, "fewer"
, "shawl"
, "natal"
, "fibre"
, "comma"
, "foray"
, "scare"
, "stair"
, "black"
, "squad"
, "royal"
, "chunk"
, "mince"
, "slave"
, "shame"
, "cheek"
, "ample"
, "flair"
, "foyer"
, "cargo"
, "oxide"
, "plant"
, "olive"
, "inert"
, "askew"
, "heist"
, "shown"
, "zesty"
, "hasty"
, "trash"
, "fella"
, "larva"
, "forgo"
, "story"
, "hairy"
, "train"
, "homer"
, "badge"
, "midst"
, "canny"
, "fetus"
, "butch"
, "farce"
, "slung"
, "tipsy"
, "metal"
, "yield"
, "delve"
, "being"
, "scour"
, "glass"
, "gamer"
, "scrap"
, "money"
, "hinge"
, "album"
, "vouch"
, "asset"
, "tiara"
, "crept"
, "bayou"
, "atoll"
, "manor"
, "creak"
, "showy"
, "phase"
, "froth"
, "depth"
, "gloom"
, "flood"
, "trait"
, "girth"
, "piety"
, "payer"
, "goose"
, "float"
, "donor"
, "atone"
, "primo"
, "apron"
, "blown"
, "cacao"
, "loser"
, "input"
, "gloat"
, "awful"
, "brink"
, "smite"
, "beady"
, "rusty"
, "retro"
, "droll"
, "gawky"
, "hutch"
, "pinto"
, "gaily"
, "egret"
, "lilac"
, "sever"
, "field"
, "fluff"
, "hydro"
, "flack"
, "agape"
, "wench"
, "voice"
, "stead"
, "stalk"
, "berth"
, "madam"
, "night"
, "bland"
, "liver"
, "wedge"
, "augur"
, "roomy"
, "wacky"
, "flock"
, "angry"
, "bobby"
, "trite"
, "aphid"
, "tryst"
, "midge"
, "power"
, "elope"
, "cinch"
, "motto"
, "stomp"
, "upset"
, "bluff"
, "cramp"
, "quart"
, "coyly"
, "youth"
, "rhyme"
, "buggy"
, "alien"
, "smear"
, "unfit"
, "patty"
, "cling"
, "glean"
, "label"
, "hunky"
, "khaki"
, "poker"
, "gruel"
, "twice"
, "twang"
, "shrug"
, "treat"
, "unlit"
, "waste"
, "merit"
, "woven"
, "octal"
, "needy"
, "clown"
, "widow"
, "irony"
, "ruder"
, "gauze"
, "chief"
, "onset"
, "prize"
, "fungi"
, "charm"
, "gully"
, "inter"
, "whoop"
, "taunt"
, "leery"
, "class"
, "theme"
, "lofty"
, "tibia"
, "booze"
, "alpha"
, "thyme"
, "eclat"
, "doubt"
, "parer"
, "chute"
, "stick"
, "trice"
, "alike"
, "sooth"
, "recap"
, "saint"
, "liege"
, "glory"
, "grate"
, "admit"
, "brisk"
, "soggy"
, "usurp"
, "scald"
, "scorn"
, "leave"
, "twine"
, "sting"
, "bough"
, "marsh"
, "sloth"
, "dandy"
, "vigor"
, "howdy"
, "enjoy"
, "valid"
, "ionic"
, "equal"
, "unset"
, "floor"
, "catch"
, "spade"
, "stein"
, "exist"
, "quirk"
, "denim"
, "grove"
, "spiel"
, "mummy"
, "fault"
, "foggy"
, "flout"
, "carry"
, "sneak"
, "libel"
, "waltz"
, "aptly"
, "piney"
, "inept"
, "aloud"
, "photo"
, "dream"
, "stale"
, "vomit"
, "ombre"
, "fanny"
, "unite"
, "snarl"
, "baker"
, "there"
, "glyph"
, "pooch"
, "hippy"
, "spell"
, "folly"
, "louse"
, "gulch"
, "vault"
, "godly"
, "threw"
, "fleet"
, "grave"
, "inane"
, "shock"
, "crave"
, "spite"
, "valve"
, "skimp"
, "claim"
, "rainy"
, "musty"
, "pique"
, "daddy"
, "quasi"
, "arise"
, "aging"
, "valet"
, "opium"
, "avert"
, "stuck"
, "recut"
, "mulch"
, "genre"
, "plume"
, "rifle"
, "count"
, "incur"
, "total"
, "wrest"
, "mocha"
, "deter"
, "study"
, "lover"
, "safer"
, "rivet"
, "funny"
, "smoke"
, "mound"
, "undue"
, "sedan"
, "pagan"
, "swine"
, "guile"
, "gusty"
, "equip"
, "tough"
, "canoe"
, "chaos"
, "covet"
, "human"
, "udder"
, "lunch"
, "blast"
, "stray"
, "manga"
, "melee"
, "lefty"
, "quick"
, "paste"
, "given"
, "octet"
, "risen"
, "groan"
, "leaky"
, "grind"
, "carve"
, "loose"
, "sadly"
, "spilt"
, "apple"
, "slack"
, "honey"
, "final"
, "sheen"
, "eerie"
, "minty"
, "slick"
, "derby"
, "wharf"
, "spelt"
, "coach"
, "erupt"
, "singe"
, "price"
, "spawn"
, "fairy"
, "jiffy"
, "filmy"
, "stack"
, "chose"
, "sleep"
, "ardor"
, "nanny"
, "niece"
, "woozy"
, "handy"
, "grace"
, "ditto"
, "stank"
, "cream"
, "usual"
, "diode"
, "valor"
, "angle"
, "ninja"
, "muddy"
, "chase"
, "reply"
, "prone"
, "spoil"
, "heart"
, "shade"
, "diner"
, "arson"
, "onion"
, "sleet"
, "dowel"
, "couch"
, "palsy"
, "bowel"
, "smile"
, "evoke"
, "creek"
, "lance"
, "eagle"
, "idiot"
, "siren"
, "built"
, "embed"
, "award"
, "dross"
, "annul"
, "goody"
, "frown"
, "patio"
, "laden"
, "humid"
, "elite"
, "lymph"
, "edify"
, "might"
, "reset"
, "visit"
, "gusto"
, "purse"
, "vapor"
, "crock"
, "write"
, "sunny"
, "loath"
, "chaff"
, "slide"
, "queer"
, "venom"
, "stamp"
, "sorry"
, "still"
, "acorn"
, "aping"
, "pushy"
, "tamer"
, "hater"
, "mania"
, "awoke"
, "brawn"
, "swift"
, "exile"
, "birch"
, "lucky"
, "freer"
, "risky"
, "ghost"
, "plier"
, "lunar"
, "winch"
, "snare"
, "nurse"
, "house"
, "borax"
, "nicer"
, "lurch"
, "exalt"
, "about"
, "savvy"
, "toxin"
, "tunic"
, "pried"
, "inlay"
, "chump"
, "lanky"
, "cress"
, "eater"
, "elude"
, "cycle"
, "kitty"
, "boule"
, "moron"
, "tenet"
, "place"
, "lobby"
, "plush"
, "vigil"
, "index"
, "blink"
, "clung"
, "qualm"
, "croup"
, "clink"
, "juicy"
, "stage"
, "decay"
, "nerve"
, "flier"
, "shaft"
, "crook"
, "clean"
, "china"
, "ridge"
, "vowel"
, "gnome"
, "snuck"
, "icing"
, "spiny"
, "rigor"
, "snail"
, "flown"
, "rabid"
, "prose"
, "thank"
, "poppy"
, "budge"
, "fiber"
, "moldy"
, "dowdy"
, "kneel"
, "track"
, "caddy"
, "quell"
, "dumpy"
, "paler"
, "swore"
, "rebar"
, "scuba"
, "splat"
, "flyer"
, "horny"
, "mason"
, "doing"
, "ozone"
, "amply"
, "molar"
, "ovary"
, "beset"
, "queue"
, "cliff"
, "magic"
, "truce"
, "sport"
, "fritz"
, "edict"
, "twirl"
, "verse"
, "llama"
, "eaten"
, "range"
, "whisk"
, "hovel"
, "rehab"
, "macaw"
, "sigma"
, "spout"
, "verve"
, "sushi"
, "dying"
, "fetid"
, "brain"
, "buddy"
, "thump"
, "scion"
, "candy"
, "chord"
, "basin"
, "march"
, "crowd"
, "arbor"
, "gayly"
, "musky"
, "stain"
, "dally"
, "bless"
, "bravo"
, "stung"
, "title"
, "ruler"
, "kiosk"
, "blond"
, "ennui"
, "layer"
, "fluid"
, "tatty"
, "score"
, "cutie"
, "zebra"
, "barge"
, "matey"
, "bluer"
, "aider"
, "shook"
, "river"
, "privy"
, "betel"
, "frisk"
, "bongo"
, "begun"
, "azure"
, "weave"
, "genie"
, "sound"
, "glove"
, "braid"
, "scope"
, "wryly"
, "rover"
, "assay"
, "ocean"
, "bloom"
, "irate"
, "later"
, "woken"
, "silky"
, "wreck"
, "dwelt"
, "slate"
, "smack"
, "solid"
, "amaze"
, "hazel"
, "wrist"
, "jolly"
, "globe"
, "flint"
, "rouse"
, "civil"
, "vista"
, "relax"
, "cover"
, "alive"
, "beech"
, "jetty"
, "bliss"
, "vocal"
, "often"
, "dolly"
, "eight"
, "joker"
, "since"
, "event"
, "ensue"
, "shunt"
, "diver"
, "poser"
, "worst"
, "sweep"
, "alley"
, "creed"
, "anime"
, "leafy"
, "bosom"
, "dunce"
, "stare"
, "pudgy"
, "waive"
, "choir"
, "stood"
, "spoke"
, "outgo"
, "delay"
, "bilge"
, "ideal"
, "clasp"
, "seize"
, "hotly"
, "laugh"
, "sieve"
, "block"
, "meant"
, "grape"
, "noose"
, "hardy"
, "shied"
, "drawl"
, "daisy"
, "putty"
, "strut"
, "burnt"
, "tulip"
, "crick"
, "idyll"
, "vixen"
, "furor"
, "geeky"
, "cough"
, "naive"
, "shoal"
, "stork"
, "bathe"
, "aunty"
, "check"
, "prime"
, "brass"
, "outer"
, "furry"
, "razor"
, "elect"
, "evict"
, "imply"
, "demur"
, "quota"
, "haven"
, "cavil"
, "swear"
, "crump"
, "dough"
, "gavel"
, "wagon"
, "salon"
, "nudge"
, "harem"
, "pitch"
, "sworn"
, "pupil"
, "excel"
, "stony"
, "cabin"
, "unzip"
, "queen"
, "trout"
, "polyp"
, "earth"
, "storm"
, "until"
, "taper"
, "enter"
, "child"
, "adopt"
, "minor"
, "fatty"
, "husky"
, "brave"
, "filet"
, "slime"
, "glint"
, "tread"
, "steal"
, "regal"
, "guest"
, "every"
, "murky"
, "share"
, "spore"
, "hoist"
, "buxom"
, "inner"
, "otter"
, "dimly"
, "level"
, "sumac"
, "donut"
, "stilt"
, "arena"
, "sheet"
, "scrub"
, "fancy"
, "slimy"
, "pearl"
, "silly"
, "porch"
, "dingo"
, "sepia"
, "amble"
, "shady"
, "bread"
, "friar"
, "reign"
, "dairy"
, "quill"
, "cross"
, "brood"
, "tuber"
, "shear"
, "posit"
, "blank"
, "villa"
, "shank"
, "piggy"
, "freak"
, "which"
, "among"
, "fecal"
, "shell"
, "would"
, "algae"
, "large"
, "rabbi"
, "agony"
, "amuse"
, "bushy"
, "copse"
, "swoon"
, "knife"
, "pouch"
, "ascot"
, "plane"
, "crown"
, "urban"
, "snide"
, "relay"
, "abide"
, "viola"
, "rajah"
, "straw"
, "dilly"
, "crash"
, "amass"
, "third"
, "trick"
, "tutor"
, "woody"
, "blurb"
, "grief"
, "disco"
, "where"
, "sassy"
, "beach"
, "sauna"
, "comic"
, "clued"
, "creep"
, "caste"
, "graze"
, "snuff"
, "frock"
, "gonad"
, "drunk"
, "prong"
, "lurid"
, "steel"
, "halve"
, "buyer"
, "vinyl"
, "utile"
, "smell"
, "adage"
, "worry"
, "tasty"
, "local"
, "trade"
, "finch"
, "ashen"
, "modal"
, "gaunt"
, "clove"
, "enact"
, "adorn"
, "roast"
, "speck"
, "sheik"
, "missy"
, "grunt"
, "snoop"
, "party"
, "touch"
, "mafia"
, "emcee"
, "array"
, "south"
, "vapid"
, "jelly"
, "skulk"
, "angst"
, "tubal"
, "lower"
, "crest"
, "sweat"
, "cyber"
, "adore"
, "tardy"
, "swami"
, "notch"
, "groom"
, "roach"
, "hitch"
, "young"
, "align"
, "ready"
, "frond"
, "strap"
, "puree"
, "realm"
, "venue"
, "swarm"
, "offer"
, "seven"
, "dryer"
, "diary"
, "dryly"
, "drank"
, "acrid"
, "heady"
, "theta"
, "junto"
, "pixie"
, "quoth"
, "bonus"
, "shalt"
, "penne"
, "amend"
, "datum"
, "build"
, "piano"
, "shelf"
, "lodge"
, "suing"
, "rearm"
, "coral"
, "ramen"
, "worth"
, "psalm"
, "infer"
, "overt"
, "mayor"
, "ovoid"
, "glide"
, "usage"
, "poise"
, "randy"
, "chuck"
, "prank"
, "fishy"
, "tooth"
, "ether"
, "drove"
, "idler"
, "swath"
, "stint"
, "while"
, "begat"
, "apply"
, "slang"
, "tarot"
, "radar"
, "credo"
, "aware"
, "canon"
, "shift"
, "timer"
, "bylaw"
, "serum"
, "three"
, "steak"
, "iliac"
, "shirk"
, "blunt"
, "puppy"
, "penal"
, "joist"
, "bunny"
, "shape"
, "beget"
, "wheel"
, "adept"
, "stunt"
, "stole"
, "topaz"
, "chore"
, "fluke"
, "afoot"
, "bloat"
, "bully"
, "dense"
, "caper"
, "sneer"
, "boxer"
, "jumbo"
, "lunge"
, "space"
, "avail"
, "short"
, "slurp"
, "loyal"
, "flirt"
, "pizza"
, "conch"
, "tempo"
, "droop"
, "plate"
, "bible"
, "plunk"
, "afoul"
, "savoy"
, "steep"
, "agile"
, "stake"
, "dwell"
, "knave"
, "beard"
, "arose"
, "motif"
, "smash"
, "broil"
, "glare"
, "shove"
, "baggy"
, "mammy"
, "swamp"
, "along"
, "rugby"
, "wager"
, "quack"
, "squat"
, "snaky"
, "debit"
, "mange"
, "skate"
, "ninth"
, "joust"
, "tramp"
, "spurn"
, "medal"
, "micro"
, "rebel"
, "flank"
, "learn"
, "nadir"
, "maple"
, "comfy"
, "remit"
, "gruff"
, "ester"
, "least"
, "mogul"
, "fetch"
, "cause"
, "oaken"
, "aglow"
, "meaty"
, "gaffe"
, "shyly"
, "racer"
, "prowl"
, "thief"
, "stern"
, "poesy"
, "rocky"
, "tweet"
, "waist"
, "spire"
, "grope"
, "havoc"
, "patsy"
, "truly"
, "forty"
, "deity"
, "uncle"
, "swish"
, "giver"
, "preen"
, "bevel"
, "lemur"
, "draft"
, "slope"
, "annoy"
, "lingo"
, "bleak"
, "ditty"
, "curly"
, "cedar"
, "dirge"
, "grown"
, "horde"
, "drool"
, "shuck"
, "crypt"
, "cumin"
, "stock"
, "gravy"
, "locus"
, "wider"
, "breed"
, "quite"
, "chafe"
, "cache"
, "blimp"
, "deign"
, "fiend"
, "logic"
, "cheap"
, "elide"
, "rigid"
, "false"
, "renal"
, "pence"
, "rowdy"
, "shoot"
, "blaze"
, "envoy"
, "posse"
, "brief"
, "never"
, "abort"
, "mouse"
, "mucky"
, "sulky"
, "fiery"
, "media"
, "trunk"
, "yeast"
, "clear"
, "skunk"
, "scalp"
, "bitty"
, "cider"
, "koala"
, "duvet"
, "segue"
, "creme"
, "super"
, "grill"
, "after"
, "owner"
, "ember"
, "reach"
, "nobly"
, "empty"
, "speed"
, "gipsy"
, "recur"
, "smock"
, "dread"
, "merge"
, "burst"
, "kappa"
, "amity"
, "shaky"
, "hover"
, "carol"
, "snort"
, "synod"
, "faint"
, "haunt"
, "flour"
, "chair"
, "detox"
, "shrew"
, "tense"
, "plied"
, "quark"
, "burly"
, "novel"
, "waxen"
, "stoic"
, "jerky"
, "blitz"
, "beefy"
, "lyric"
, "hussy"
, "towel"
, "quilt"
, "below"
, "bingo"
, "wispy"
, "brash"
, "scone"
, "toast"
, "easel"
, "saucy"
, "value"
, "spice"
, "honor"
, "route"
, "sharp"
, "bawdy"
, "radii"
, "skull"
, "phony"
, "issue"
, "lager"
, "swell"
, "urine"
, "gassy"
, "trial"
, "flora"
, "upper"
, "latch"
, "wight"
, "brick"
, "retry"
, "holly"
, "decal"
, "grass"
, "shack"
, "dogma"
, "mover"
, "defer"
, "sober"
, "optic"
, "crier"
, "vying"
, "nomad"
, "flute"
, "hippo"
, "shark"
, "drier"
, "obese"
, "bugle"
, "tawny"
, "chalk"
, "feast"
, "ruddy"
, "pedal"
, "scarf"
, "cruel"
, "bleat"
, "tidal"
, "slush"
, "semen"
, "windy"
, "dusty"
, "sally"
, "igloo"
, "nerdy"
, "jewel"
, "shone"
, "whale"
, "hymen"
, "abuse"
, "fugue"
, "elbow"
, "crumb"
, "pansy"
, "welsh"
, "syrup"
, "terse"
, "suave"
, "gamut"
, "swung"
, "drake"
, "freed"
, "afire"
, "shirt"
, "grout"
, "oddly"
, "tithe"
, "plaid"
, "dummy"
, "broom"
, "blind"
, "torch"
, "enemy"
, "again"
, "tying"
, "pesky"
, "alter"
, "gazer"
, "noble"
, "ethos"
, "bride"
, "extol"
, "decor"
, "hobby"
, "beast"
, "idiom"
, "utter"
, "these"
, "sixth"
, "alarm"
, "erase"
, "elegy"
, "spunk"
, "piper"
, "scaly"
, "scold"
, "hefty"
, "chick"
, "sooty"
, "canal"
, "whiny"
, "slash"
, "quake"
, "joint"
, "swept"
, "prude"
, "heavy"
, "wield"
, "femme"
, "lasso"
, "maize"
, "shale"
, "screw"
, "spree"
, "smoky"
, "whiff"
, "scent"
, "glade"
, "spent"
, "prism"
, "stoke"
, "riper"
, "orbit"
, "cocoa"
, "guilt"
, "humus"
, "shush"
, "table"
, "smirk"
, "wrong"
, "noisy"
, "alert"
, "shiny"
, "elate"
, "resin"
, "whole"
, "hunch"
, "pixel"
, "polar"
, "hotel"
, "sword"
, "cleat"
, "mango"
, "rumba"
, "puffy"
, "filly"
, "billy"
, "leash"
, "clout"
, "dance"
, "ovate"
, "facet"
, "chili"
, "paint"
, "liner"
, "curio"
, "salty"
, "audio"
, "snake"
, "fable"
, "cloak"
, "navel"
, "spurt"
, "pesto"
, "balmy"
, "flash"
, "unwed"
, "early"
, "churn"
, "weedy"
, "stump"
, "lease"
, "witty"
, "wimpy"
, "spoof"
, "saner"
, "blend"
, "salsa"
, "thick"
, "warty"
, "manic"
, "blare"
, "squib"
, "spoon"
, "probe"
, "crepe"
, "knack"
, "force"
, "debut"
, "order"
, "haste"
, "teeth"
, "agent"
, "widen"
, "icily"
, "slice"
, "ingot"
, "clash"
, "juror"
, "blood"
, "abode"
, "throw"
, "unity"
, "pivot"
, "slept"
, "troop"
, "spare"
, "sewer"
, "parse"
, "morph"
, "cacti"
, "tacky"
, "spool"
, "demon"
, "moody"
, "annex"
, "begin"
, "fuzzy"
, "patch"
, "water"
, "lumpy"
, "admin"
, "omega"
, "limit"
, "tabby"
, "macho"
, "aisle"
, "skiff"
, "basis"
, "plank"
, "verge"
, "botch"
, "crawl"
, "lousy"
, "slain"
, "cubic"
, "raise"
, "wrack"
, "guide"
, "foist"
, "cameo"
, "under"
, "actor"
, "revue"
, "fraud"
, "harpy"
, "scoop"
, "climb"
, "refer"
, "olden"
, "clerk"
, "debar"
, "tally"
, "ethic"
, "cairn"
, "tulle"
, "ghoul"
, "hilly"
, "crude"
, "apart"
, "scale"
, "older"
, "plain"
, "sperm"
, "briny"
, "abbot"
, "rerun"
, "quest"
, "crisp"
, "bound"
, "befit"
, "drawn"
, "suite"
, "itchy"
, "cheer"
, "bagel"
, "guess"
, "broad"
, "axiom"
, "chard"
, "caput"
, "leant"
, "harsh"
, "curse"
, "proud"
, "swing"
, "opine"
, "taste"
, "lupus"
, "gumbo"
, "miner"
, "green"
, "chasm"
, "lipid"
, "topic"
, "armor"
, "brush"
, "crane"
, "mural"
, "abled"
, "habit"
, "bossy"
, "maker"
, "dusky"
, "dizzy"
, "lithe"
, "brook"
, "jazzy"
, "fifty"
, "sense"
, "giant"
, "surly"
, "legal"
, "fatal"
, "flunk"
, "began"
, "prune"
, "small"
, "slant"
, "scoff"
, "torus"
, "ninny"
, "covey"
, "viper"
, "taken"
, "moral"
, "vogue"
, "owing"
, "token"
, "entry"
, "booth"
, "voter"
, "chide"
, "elfin"
, "ebony"
, "neigh"
, "minim"
, "melon"
, "kneed"
, "decoy"
, "voila"
, "ankle"
, "arrow"
, "mushy"
, "tribe"
, "cease"
, "eager"
, "birth"
, "graph"
, "odder"
, "terra"
, "weird"
, "tried"
, "clack"
, "color"
, "rough"
, "weigh"
, "uncut"
, "ladle"
, "strip"
, "craft"
, "minus"
, "dicey"
, "titan"
, "lucid"
, "vicar"
, "dress"
, "ditch"
, "gypsy"
, "pasta"
, "taffy"
, "flame"
, "swoop"
, "aloof"
, "sight"
, "broke"
, "teary"
, "chart"
, "sixty"
, "wordy"
, "sheer"
, "leper"
, "nosey"
, "bulge"
, "savor"
, "clamp"
, "funky"
, "foamy"
, "toxic"
, "brand"
, "plumb"
, "dingy"
, "butte"
, "drill"
, "tripe"
, "bicep"
, "tenor"
, "krill"
, "worse"
, "drama"
, "hyena"
, "think"
, "ratio"
, "cobra"
, "basil"
, "scrum"
, "bused"
, "phone"
, "court"
, "camel"
, "proof"
, "heard"
, "angel"
, "petal"
, "pouty"
, "throb"
, "maybe"
, "fetal"
, "sprig"
, "spine"
, "shout"
, "cadet"
, "macro"
, "dodgy"
, "satyr"
, "rarer"
, "binge"
, "trend"
, "nutty"
, "leapt"
, "amiss"
, "split"
, "myrrh"
, "width"
, "sonar"
, "tower"
, "baron"
, "fever"
, "waver"
, "spark"
, "belie"
, "sloop"
, "expel"
, "smote"
, "baler"
, "above"
, "north"
, "wafer"
, "scant"
, "frill"
, "awash"
, "snack"
, "scowl"
, "frail"
, "drift"
, "limbo"
, "fence"
, "motel"
, "ounce"
, "wreak"
, "revel"
, "talon"
, "prior"
, "knelt"
, "cello"
, "flake"
, "debug"
, "anode"
, "crime"
, "salve"
, "scout"
, "imbue"
, "pinky"
, "stave"
, "vague"
, "chock"
, "fight"
, "video"
, "stone"
, "teach"
, "cleft"
, "frost"
, "prawn"
, "booty"
, "twist"
, "apnea"
, "stiff"
, "plaza"
, "ledge"
, "tweak"
, "board"
, "grant"
, "medic"
, "bacon"
, "cable"
, "brawl"
, "slunk"
, "raspy"
, "forum"
, "drone"
, "women"
, "mucus"
, "boast"
, "toddy"
, "coven"
, "tumor"
, "truer"
, "wrath"
, "stall"
, "steam"
, "axial"
, "purer"
, "daily"
, "trail"
, "niche"
, "mealy"
, "juice"
, "nylon"
, "plump"
, "merry"
, "flail"
, "papal"
, "wheat"
, "berry"
, "cower"
, "erect"
, "brute"
, "leggy"
, "snipe"
, "sinew"
, "skier"
, "penny"
, "jumpy"
, "rally"
, "umbra"
, "scary"
, "modem"
, "gross"
, "avian"
, "greed"
, "satin"
, "tonic"
, "parka"
, "sniff"
, "livid"
, "stark"
, "trump"
, "giddy"
, "reuse"
, "taboo"
, "avoid"
, "quote"
, "devil"
, "liken"
, "gloss"
, "gayer"
, "beret"
, "noise"
, "gland"
, "dealt"
, "sling"
, "rumor"
, "opera"
, "thigh"
, "tonga"
, "flare"
, "wound"
, "white"
, "bulky"
, "etude"
, "horse"
, "circa"
, "paddy"
, "inbox"
, "fizzy"
, "grain"
, "exert"
, "surge"
, "gleam"
, "belle"
, "salvo"
, "crush"
, "fruit"
, "sappy"
, "taker"
, "tract"
, "ovine"
, "spiky"
, "frank"
, "reedy"
, "filth"
, "spasm"
, "heave"
, "mambo"
, "right"
, "clank"
, "trust"
, "lumen"
, "borne"
, "spook"
, "sauce"
, "amber"
, "lathe"
, "carat"
, "corer"
, "dirty"
, "slyly"
, "affix"
, "alloy"
, "taint"
, "sheep"
, "kinky"
, "wooly"
, "mauve"
, "flung"
, "yacht"
, "fried"
, "quail"
, "brunt"
, "grimy"
, "curvy"
, "cagey"
, "rinse"
, "deuce"
, "state"
, "grasp"
, "milky"
, "bison"
, "graft"
, "sandy"
, "baste"
, "flask"
, "hedge"
, "girly"
, "swash"
, "boney"
, "coupe"
, "endow"
, "abhor"
, "welch"
, "blade"
, "tight"
, "geese"
, "miser"
, "mirth"
, "cloud"
, "cabal"
, "leech"
, "close"
, "tenth"
, "pecan"
, "droit"
, "grail"
, "clone"
, "guise"
, "ralph"
, "tango"
, "biddy"
, "smith"
, "mower"
, "payee"
, "serif"
, "drape"
, "fifth"
, "spank"
, "glaze"
, "allot"
, "truck"
, "kayak"
, "virus"
, "testy"
, "tepee"
, "fully"
, "zonal"
, "metro"
, "curry"
, "grand"
, "banjo"
, "axion"
, "bezel"
, "occur"
, "chain"
, "nasal"
, "gooey"
, "filer"
, "brace"
, "allay"
, "pubic"
, "raven"
, "plead"
, "gnash"
, "flaky"
, "munch"
, "dully"
, "eking"
, "thing"
, "slink"
, "hurry"
, "theft"
, "shorn"
, "pygmy"
, "ranch"
, "wring"
, "lemon"
, "shore"
, "mamma"
, "froze"
, "newer"
, "style"
, "moose"
, "antic"
, "drown"
, "vegan"
, "chess"
, "guppy"
, "union"
, "lever"
, "lorry"
, "image"
, "cabby"
, "druid"
, "exact"
, "truth"
, "dopey"
, "spear"
, "cried"
, "chime"
, "crony"
, "stunk"
, "timid"
, "batch"
, "gauge"
, "rotor"
, "crack"
, "curve"
, "latte"
, "witch"
, "bunch"
, "repel"
, "anvil"
, "soapy"
, "meter"
, "broth"
, "madly"
, "dried"
, "scene"
, "known"
, "magma"
, "roost"
, "woman"
, "thong"
, "punch"
, "pasty"
, "downy"
, "knead"
, "whirl"
, "rapid"
, "clang"
, "anger"
, "drive"
, "goofy"
, "email"
, "music"
, "stuff"
, "bleep"
, "rider"
, "mecca"
, "folio"
, "setup"
, "verso"
, "quash"
, "fauna"
, "gummy"
, "happy"
, "newly"
, "fussy"
, "relic"
, "guava"
, "ratty"
, "fudge"
, "femur"
, "chirp"
, "forte"
, "alibi"
, "whine"
, "petty"
, "golly"
, "plait"
, "fleck"
, "felon"
, "gourd"
, "brown"
, "thrum"
, "ficus"
, "stash"
, "decry"
, "wiser"
, "junta"
, "visor"
, "daunt"
, "scree"
, "impel"
, "await"
, "press"
, "whose"
, "turbo"
, "stoop"
, "speak"
, "mangy"
, "eying"
, "inlet"
, "crone"
, "pulse"
, "mossy"
, "staid"
, "hence"
, "pinch"
, "teddy"
, "sully"
, "snore"
, "ripen"
, "snowy"
, "attic"
, "going"
, "leach"
, "mouth"
, "hound"
, "clump"
, "tonal"
, "bigot"
, "peril"
, "piece"
, "blame"
, "haute"
, "spied"
, "undid"
, "intro"
, "basal"
, "shine"
, "gecko"
, "rodeo"
, "guard"
, "steer"
, "loamy"
, "scamp"
, "scram"
, "manly"
, "hello"
, "vaunt"
, "organ"
, "feral"
, "knock"
, "extra"
, "condo"
, "adapt"
, "willy"
, "polka"
, "rayon"
, "skirt"
, "faith"
, "torso"
, "match"
, "mercy"
, "tepid"
, "sleek"
, "riser"
, "twixt"
, "peace"
, "flush"
, "catty"
, "login"
, "eject"
, "roger"
, "rival"
, "untie"
, "refit"
, "aorta"
, "adult"
, "judge"
, "rower"
, "artsy"
, "rural"
, "shave"
]
length : Int
length =
List.length asList
| 41387 | module Words exposing (asList, length)
asList : List String
asList =
[ "cigar"
, "rebut"
, "sissy"
, "humph"
, "awake"
, "blush"
, "focal"
, "evade"
, "naval"
, "serve"
, "heath"
, "dwarf"
, "model"
, "karma"
, "stink"
, "grade"
, "quiet"
, "bench"
, "abate"
, "feign"
, "major"
, "death"
, "fresh"
, "crust"
, "stool"
, "colon"
, "abase"
, "marry"
, "react"
, "batty"
, "pride"
, "floss"
, "helix"
, "croak"
, "staff"
, "paper"
, "unfed"
, "whelp"
, "trawl"
, "outdo"
, "adobe"
, "crazy"
, "sower"
, "repay"
, "digit"
, "crate"
, "cluck"
, "spike"
, "mimic"
, "pound"
, "maxim"
, "linen"
, "unmet"
, "flesh"
, "booby"
, "forth"
, "first"
, "stand"
, "belly"
, "ivory"
, "seedy"
, "print"
, "yearn"
, "drain"
, "bribe"
, "stout"
, "panel"
, "crass"
, "flume"
, "offal"
, "agree"
, "error"
, "swirl"
, "argue"
, "bleed"
, "delta"
, "flick"
, "totem"
, "wooer"
, "front"
, "shrub"
, "parry"
, "biome"
, "lapel"
, "start"
, "greet"
, "<NAME>"
, "<NAME>"
, "<NAME>y"
, "loopy"
, "round"
, "audit"
, "lying"
, "gamma"
, "labor"
, "islet"
, "civic"
, "forge"
, "<NAME>"
, "moult"
, "basic"
, "salad"
, "agate"
, "spicy"
, "spray"
, "essay"
, "fjord"
, "spend"
, "kebab"
, "guild"
, "aback"
, "motor"
, "alone"
, "hatch"
, "hyper"
, "thumb"
, "dowry"
, "ought"
, "belch"
, "dutch"
, "pilot"
, "tweed"
, "comet"
, "jaunt"
, "enema"
, "steed"
, "abyss"
, "growl"
, "fling"
, "dozen"
, "boozy"
, "erode"
, "world"
, "gouge"
, "click"
, "briar"
, "great"
, "altar"
, "pulpy"
, "blurt"
, "coast"
, "duchy"
, "groin"
, "fixer"
, "group"
, "rogue"
, "badly"
, "smart"
, "pithy"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "radio"
, "<NAME>"
, "<NAME>"
, "retch"
, "wrote"
, "clock"
, "tilde"
, "store"
, "prove"
, "bring"
, "solve"
, "cheat"
, "grime"
, "exult"
, "usher"
, "epoch"
, "triad"
, "break"
, "rhino"
, "viral"
, "<NAME>"
, "<NAME>"
, "sonic"
, "vital"
, "trace"
, "using"
, "peach"
, "<NAME>"
, "<NAME>"
, "brake"
, "pluck"
, "craze"
, "<NAME>"
, "weary"
, "picky"
, "acute"
, "<NAME>"
, "aside"
, "tapir"
, "troll"
, "unify"
, "rebus"
, "boost"
, "truss"
, "siege"
, "tiger"
, "banal"
, "slump"
, "crank"
, "gorge"
, "query"
, "drink"
, "favor"
, "abbey"
, "tangy"
, "panic"
, "solar"
, "shire"
, "proxy"
, "point"
, "robot"
, "<NAME>ick"
, "<NAME>ince"
, "<NAME>"
, "<NAME>"
, "sugar"
, "whack"
, "mount"
, "perky"
, "could"
, "wrung"
, "light"
, "those"
, "moist"
, "shard"
, "pleat"
, "aloft"
, "skill"
, "elder"
, "frame"
, "humor"
, "pause"
, "ulcer"
, "ultra"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "aroma"
, "<NAME>"
, "shake"
, "pupal"
, "dodge"
, "swill"
, "tacit"
, "other"
, "thorn"
, "trove"
, "bloke"
, "vivid"
, "spill"
, "chant"
, "choke"
, "rupee"
, "nasty"
, "mourn"
, "ahead"
, "brine"
, "cloth"
, "hoard"
, "sweet"
, "month"
, "lapse"
, "watch"
, "today"
, "focus"
, "smelt"
, "tease"
, "cater"
, "movie"
, "lynch"
, "saute"
, "allow"
, "renew"
, "their"
, "slosh"
, "purge"
, "chest"
, "depot"
, "epoxy"
, "nymph"
, "found"
, "shall"
, "<NAME>arry"
, "stove"
, "lowly"
, "snout"
, "trope"
, "fewer"
, "shawl"
, "natal"
, "fibre"
, "comma"
, "foray"
, "scare"
, "stair"
, "black"
, "squad"
, "royal"
, "chunk"
, "mince"
, "slave"
, "shame"
, "cheek"
, "ample"
, "flair"
, "<NAME>yer"
, "cargo"
, "oxide"
, "plant"
, "olive"
, "inert"
, "<NAME>ew"
, "heist"
, "shown"
, "zesty"
, "hasty"
, "trash"
, "fella"
, "<NAME>"
, "<NAME>"
, "story"
, "hairy"
, "train"
, "homer"
, "badge"
, "midst"
, "<NAME>"
, "<NAME>"
, "butch"
, "farce"
, "slung"
, "tipsy"
, "metal"
, "yield"
, "delve"
, "being"
, "scour"
, "glass"
, "gamer"
, "scrap"
, "money"
, "hinge"
, "album"
, "vouch"
, "asset"
, "tiara"
, "crept"
, "bayou"
, "atoll"
, "<NAME>"
, "<NAME>"
, "showy"
, "phase"
, "froth"
, "depth"
, "gloom"
, "flood"
, "trait"
, "girth"
, "piety"
, "payer"
, "goose"
, "float"
, "<NAME>"
, "atone"
, "primo"
, "<NAME>"
, "blown"
, "cacao"
, "loser"
, "input"
, "gloat"
, "awful"
, "brink"
, "smite"
, "beady"
, "rusty"
, "retro"
, "d<NAME>"
, "gaw<NAME>"
, "<NAME>"
, "pinto"
, "<NAME>aily"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "field"
, "fluff"
, "hydro"
, "flack"
, "<NAME>"
, "wench"
, "voice"
, "stead"
, "stalk"
, "<NAME>"
, "<NAME>"
, "night"
, "bland"
, "liver"
, "wedge"
, "<NAME>"
, "roomy"
, "wacky"
, "flock"
, "angry"
, "<NAME>"
, "tr<NAME>"
, "<NAME>"
, "tryst"
, "midge"
, "power"
, "elope"
, "cinch"
, "motto"
, "stomp"
, "upset"
, "bluff"
, "cramp"
, "quart"
, "coyly"
, "youth"
, "rhyme"
, "buggy"
, "alien"
, "smear"
, "unfit"
, "<NAME>ty"
, "cling"
, "glean"
, "label"
, "<NAME>"
, "<NAME>"
, "poker"
, "<NAME>"
, "twice"
, "twang"
, "shrug"
, "treat"
, "unlit"
, "waste"
, "merit"
, "woven"
, "octal"
, "needy"
, "clown"
, "widow"
, "irony"
, "ruder"
, "gauze"
, "chief"
, "onset"
, "prize"
, "fungi"
, "charm"
, "gully"
, "inter"
, "whoop"
, "taunt"
, "leery"
, "class"
, "theme"
, "lofty"
, "tibia"
, "booze"
, "alpha"
, "thyme"
, "eclat"
, "doubt"
, "parer"
, "chute"
, "stick"
, "trice"
, "alike"
, "sooth"
, "recap"
, "saint"
, "liege"
, "glory"
, "grate"
, "admit"
, "brisk"
, "soggy"
, "usurp"
, "scald"
, "scorn"
, "leave"
, "twine"
, "sting"
, "bough"
, "marsh"
, "sloth"
, "dandy"
, "vigor"
, "howdy"
, "enjoy"
, "valid"
, "ionic"
, "equal"
, "unset"
, "floor"
, "catch"
, "spade"
, "stein"
, "exist"
, "quirk"
, "denim"
, "grove"
, "spiel"
, "mummy"
, "fault"
, "foggy"
, "flout"
, "carry"
, "sneak"
, "libel"
, "waltz"
, "aptly"
, "piney"
, "inept"
, "aloud"
, "photo"
, "dream"
, "stale"
, "vomit"
, "ombre"
, "fanny"
, "unite"
, "snarl"
, "baker"
, "there"
, "glyph"
, "pooch"
, "hippy"
, "spell"
, "folly"
, "louse"
, "gulch"
, "vault"
, "godly"
, "threw"
, "fleet"
, "grave"
, "inane"
, "shock"
, "crave"
, "spite"
, "valve"
, "skimp"
, "claim"
, "rainy"
, "musty"
, "pique"
, "daddy"
, "quasi"
, "arise"
, "aging"
, "valet"
, "opium"
, "avert"
, "stuck"
, "recut"
, "mulch"
, "genre"
, "plume"
, "rifle"
, "count"
, "incur"
, "total"
, "wrest"
, "mocha"
, "deter"
, "study"
, "lover"
, "safer"
, "rivet"
, "funny"
, "smoke"
, "mound"
, "undue"
, "sedan"
, "pagan"
, "swine"
, "guile"
, "gusty"
, "equip"
, "tough"
, "canoe"
, "chaos"
, "covet"
, "human"
, "udder"
, "lunch"
, "blast"
, "stray"
, "manga"
, "melee"
, "lefty"
, "quick"
, "paste"
, "given"
, "octet"
, "risen"
, "groan"
, "leaky"
, "grind"
, "carve"
, "loose"
, "sadly"
, "spilt"
, "apple"
, "slack"
, "<NAME>"
, "final"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>arf"
, "spelt"
, "coach"
, "erupt"
, "<NAME>"
, "price"
, "spawn"
, "fairy"
, "<NAME>"
, "<NAME>"
, "stack"
, "chose"
, "sleep"
, "<NAME>"
, "<NAME>"
, "niece"
, "woozy"
, "handy"
, "grace"
, "<NAME>to"
, "stank"
, "cream"
, "usual"
, "diode"
, "valor"
, "angle"
, "ninja"
, "<NAME>"
, "chase"
, "reply"
, "prone"
, "spoil"
, "heart"
, "shade"
, "diner"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "dowel"
, "couch"
, "p<NAME>"
, "bowel"
, "smile"
, "evoke"
, "creek"
, "lance"
, "eagle"
, "idiot"
, "siren"
, "built"
, "embed"
, "award"
, "d<NAME>"
, "<NAME>"
, "<NAME>"
, "frown"
, "patio"
, "laden"
, "humid"
, "elite"
, "lymph"
, "edify"
, "might"
, "reset"
, "visit"
, "gusto"
, "purse"
, "vapor"
, "crock"
, "write"
, "sunny"
, "loath"
, "chaff"
, "slide"
, "queer"
, "venom"
, "stamp"
, "sorry"
, "still"
, "acorn"
, "aping"
, "pushy"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>ile"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "house"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "ex<NAME>"
, "about"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "cycle"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "place"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "stage"
, "decay"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "clean"
, "china"
, "ridge"
, "vowel"
, "gnome"
, "sn<NAME>"
, "icing"
, "sp<NAME>"
, "<NAME>"
, "sn<NAME>"
, "flow<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "track"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "doing"
, "ozone"
, "amply"
, "molar"
, "ovary"
, "beset"
, "queue"
, "cliff"
, "magic"
, "truce"
, "sport"
, "<NAME>"
, "edict"
, "twirl"
, "verse"
, "llama"
, "eaten"
, "range"
, "whisk"
, "hovel"
, "rehab"
, "macaw"
, "sigma"
, "spout"
, "verve"
, "sushi"
, "dying"
, "fetid"
, "brain"
, "buddy"
, "thump"
, "scion"
, "<NAME>andy"
, "chord"
, "basin"
, "march"
, "crowd"
, "arbor"
, "gayly"
, "musky"
, "stain"
, "<NAME>"
, "bless"
, "<NAME>"
, "stung"
, "title"
, "ruler"
, "kiosk"
, "blond"
, "<NAME>ui"
, "layer"
, "fluid"
, "tatty"
, "score"
, "cutie"
, "zebra"
, "<NAME>"
, "<NAME>y"
, "<NAME>"
, "aider"
, "shook"
, "river"
, "privy"
, "betel"
, "<NAME>isk"
, "bongo"
, "begun"
, "azure"
, "weave"
, "<NAME>ie"
, "sound"
, "glove"
, "braid"
, "scope"
, "wryly"
, "rover"
, "assay"
, "ocean"
, "bloom"
, "irate"
, "later"
, "woken"
, "silky"
, "wreck"
, "dwelt"
, "slate"
, "smack"
, "solid"
, "amaze"
, "hazel"
, "wrist"
, "jolly"
, "globe"
, "flint"
, "rouse"
, "civil"
, "vista"
, "relax"
, "cover"
, "alive"
, "beech"
, "jetty"
, "bliss"
, "vocal"
, "often"
, "dolly"
, "eight"
, "joker"
, "since"
, "event"
, "ensue"
, "shunt"
, "diver"
, "poser"
, "worst"
, "sweep"
, "alley"
, "creed"
, "anime"
, "leafy"
, "bosom"
, "dunce"
, "stare"
, "pudgy"
, "waive"
, "choir"
, "stood"
, "spoke"
, "outgo"
, "delay"
, "bilge"
, "ideal"
, "clasp"
, "seize"
, "hotly"
, "laugh"
, "sieve"
, "block"
, "meant"
, "grape"
, "noose"
, "hardy"
, "shied"
, "drawl"
, "daisy"
, "putty"
, "strut"
, "burnt"
, "tulip"
, "<NAME>ick"
, "idyll"
, "vixen"
, "furor"
, "geeky"
, "cough"
, "naive"
, "shoal"
, "stork"
, "bathe"
, "aunty"
, "check"
, "prime"
, "brass"
, "outer"
, "furry"
, "razor"
, "elect"
, "evict"
, "imply"
, "demur"
, "quota"
, "haven"
, "cavil"
, "swear"
, "crump"
, "dough"
, "gavel"
, "wagon"
, "salon"
, "nudge"
, "h<NAME>"
, "pitch"
, "sworn"
, "pupil"
, "excel"
, "stony"
, "cabin"
, "unzip"
, "queen"
, "trout"
, "polyp"
, "earth"
, "storm"
, "until"
, "taper"
, "enter"
, "child"
, "adopt"
, "minor"
, "fatty"
, "husky"
, "brave"
, "filet"
, "slime"
, "glint"
, "tread"
, "steal"
, "regal"
, "guest"
, "every"
, "murky"
, "share"
, "spore"
, "hoist"
, "buxom"
, "inner"
, "otter"
, "dimly"
, "level"
, "sumac"
, "donut"
, "stilt"
, "arena"
, "sheet"
, "scrub"
, "fancy"
, "slimy"
, "pearl"
, "silly"
, "porch"
, "dingo"
, "sepia"
, "amble"
, "shady"
, "bread"
, "friar"
, "reign"
, "dairy"
, "quill"
, "cross"
, "brood"
, "tuber"
, "shear"
, "posit"
, "blank"
, "villa"
, "shank"
, "piggy"
, "freak"
, "which"
, "among"
, "fecal"
, "shell"
, "would"
, "algae"
, "large"
, "rabbi"
, "agony"
, "amuse"
, "bushy"
, "copse"
, "swoon"
, "knife"
, "pouch"
, "<NAME>"
, "plane"
, "crown"
, "urban"
, "snide"
, "relay"
, "abide"
, "<NAME>"
, "<NAME>"
, "straw"
, "<NAME>"
, "crash"
, "<NAME>ass"
, "third"
, "<NAME>ick"
, "tutor"
, "<NAME>"
, "blurb"
, "grief"
, "disco"
, "where"
, "sassy"
, "beach"
, "sauna"
, "comic"
, "clued"
, "creep"
, "<NAME>"
, "graze"
, "snuff"
, "frock"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "steel"
, "halve"
, "buyer"
, "vinyl"
, "utile"
, "smell"
, "adage"
, "worry"
, "tasty"
, "local"
, "trade"
, "finch"
, "<NAME>"
, "modal"
, "gaunt"
, "clove"
, "enact"
, "adorn"
, "roast"
, "speck"
, "sheik"
, "missy"
, "<NAME>"
, "snoop"
, "party"
, "touch"
, "<NAME>"
, "<NAME>"
, "array"
, "south"
, "vapid"
, "<NAME>"
, "<NAME>"
, "angst"
, "tubal"
, "lower"
, "crest"
, "sweat"
, "cyber"
, "adore"
, "tardy"
, "swami"
, "notch"
, "groom"
, "roach"
, "hitch"
, "young"
, "align"
, "ready"
, "frond"
, "strap"
, "puree"
, "realm"
, "venue"
, "swarm"
, "offer"
, "seven"
, "dryer"
, "<NAME>ary"
, "dryly"
, "<NAME>"
, "<NAME>"
, "heady"
, "theta"
, "<NAME>unto"
, "<NAME>"
, "<NAME>oth"
, "bonus"
, "shalt"
, "<NAME>"
, "<NAME>"
, "datum"
, "build"
, "piano"
, "shelf"
, "lodge"
, "suing"
, "rearm"
, "coral"
, "<NAME>"
, "worth"
, "psalm"
, "infer"
, "overt"
, "mayor"
, "ovoid"
, "glide"
, "usage"
, "poise"
, "<NAME>y"
, "chuck"
, "<NAME>"
, "fishy"
, "tooth"
, "ether"
, "drove"
, "<NAME>ler"
, "<NAME>ath"
, "stint"
, "while"
, "begat"
, "apply"
, "slang"
, "tarot"
, "radar"
, "<NAME>"
, "aware"
, "canon"
, "shift"
, "timer"
, "bylaw"
, "<NAME>um"
, "three"
, "steak"
, "<NAME>"
, "<NAME>"
, "blunt"
, "puppy"
, "penal"
, "joist"
, "<NAME>"
, "shape"
, "beget"
, "wheel"
, "adept"
, "stunt"
, "stole"
, "topaz"
, "chore"
, "fluke"
, "afoot"
, "bloat"
, "bully"
, "dense"
, "caper"
, "sneer"
, "boxer"
, "jumbo"
, "lunge"
, "space"
, "avail"
, "short"
, "slurp"
, "loyal"
, "flirt"
, "pizza"
, "conch"
, "tempo"
, "droop"
, "plate"
, "bible"
, "plunk"
, "afoul"
, "savoy"
, "steep"
, "agile"
, "stake"
, "dwell"
, "knave"
, "beard"
, "arose"
, "motif"
, "smash"
, "broil"
, "glare"
, "shove"
, "baggy"
, "mammy"
, "swamp"
, "along"
, "rugby"
, "wager"
, "quack"
, "squat"
, "snaky"
, "debit"
, "mange"
, "skate"
, "ninth"
, "joust"
, "tramp"
, "spurn"
, "medal"
, "micro"
, "rebel"
, "flank"
, "learn"
, "<NAME>"
, "maple"
, "comfy"
, "remit"
, "<NAME>uff"
, "ester"
, "least"
, "mogul"
, "fetch"
, "cause"
, "oaken"
, "aglow"
, "meaty"
, "gaffe"
, "shyly"
, "<NAME>acer"
, "prowl"
, "thief"
, "stern"
, "poesy"
, "rocky"
, "tweet"
, "waist"
, "spire"
, "grope"
, "havoc"
, "patsy"
, "truly"
, "forty"
, "deity"
, "uncle"
, "swish"
, "giver"
, "preen"
, "bevel"
, "lemur"
, "draft"
, "slope"
, "annoy"
, "lingo"
, "bleak"
, "ditty"
, "curly"
, "cedar"
, "dirge"
, "grown"
, "horde"
, "drool"
, "shuck"
, "crypt"
, "cumin"
, "stock"
, "gravy"
, "locus"
, "wider"
, "breed"
, "quite"
, "chafe"
, "cache"
, "blimp"
, "deign"
, "fiend"
, "logic"
, "cheap"
, "elide"
, "rigid"
, "false"
, "renal"
, "pence"
, "rowdy"
, "shoot"
, "blaze"
, "envoy"
, "posse"
, "brief"
, "never"
, "abort"
, "mouse"
, "mucky"
, "sulky"
, "fiery"
, "media"
, "trunk"
, "yeast"
, "clear"
, "skunk"
, "scalp"
, "bitty"
, "cider"
, "koala"
, "duvet"
, "segue"
, "creme"
, "super"
, "grill"
, "after"
, "owner"
, "ember"
, "reach"
, "nobly"
, "empty"
, "speed"
, "gipsy"
, "recur"
, "smock"
, "dread"
, "merge"
, "burst"
, "kappa"
, "amity"
, "shaky"
, "hover"
, "carol"
, "snort"
, "synod"
, "faint"
, "haunt"
, "flour"
, "chair"
, "detox"
, "shrew"
, "tense"
, "plied"
, "quark"
, "burly"
, "novel"
, "waxen"
, "stoic"
, "<NAME>ky"
, "blitz"
, "beefy"
, "<NAME>"
, "hussy"
, "towel"
, "quilt"
, "below"
, "bingo"
, "wispy"
, "brash"
, "scone"
, "toast"
, "easel"
, "saucy"
, "value"
, "spice"
, "honor"
, "route"
, "sharp"
, "bawdy"
, "radii"
, "skull"
, "phony"
, "issue"
, "lager"
, "swell"
, "urine"
, "gassy"
, "trial"
, "flora"
, "upper"
, "latch"
, "wight"
, "brick"
, "retry"
, "holly"
, "decal"
, "grass"
, "shack"
, "dogma"
, "mover"
, "defer"
, "sober"
, "optic"
, "crier"
, "vying"
, "nomad"
, "flute"
, "hippo"
, "shark"
, "drier"
, "obese"
, "bugle"
, "tawny"
, "chalk"
, "feast"
, "ruddy"
, "pedal"
, "scarf"
, "cruel"
, "bleat"
, "tidal"
, "slush"
, "semen"
, "windy"
, "dusty"
, "sally"
, "igloo"
, "nerdy"
, "jewel"
, "shone"
, "whale"
, "hymen"
, "abuse"
, "fugue"
, "elbow"
, "crumb"
, "pansy"
, "welsh"
, "syrup"
, "terse"
, "suave"
, "gamut"
, "swung"
, "drake"
, "freed"
, "afire"
, "shirt"
, "grout"
, "oddly"
, "tithe"
, "plaid"
, "dummy"
, "broom"
, "blind"
, "torch"
, "enemy"
, "again"
, "tying"
, "pesky"
, "<NAME>"
, "g<NAME>"
, "noble"
, "ethos"
, "bride"
, "extol"
, "decor"
, "hobby"
, "beast"
, "idiom"
, "utter"
, "these"
, "sixth"
, "alarm"
, "erase"
, "elegy"
, "spunk"
, "<NAME>"
, "scaly"
, "scold"
, "hefty"
, "chick"
, "sooty"
, "canal"
, "whiny"
, "slash"
, "quake"
, "joint"
, "swept"
, "prude"
, "heavy"
, "wield"
, "femme"
, "lasso"
, "maize"
, "shale"
, "screw"
, "spree"
, "smoky"
, "whiff"
, "scent"
, "glade"
, "spent"
, "prism"
, "stoke"
, "<NAME>"
, "orbit"
, "cocoa"
, "guilt"
, "humus"
, "shush"
, "table"
, "smirk"
, "wrong"
, "noisy"
, "alert"
, "shiny"
, "elate"
, "resin"
, "whole"
, "hunch"
, "pixel"
, "polar"
, "hotel"
, "sword"
, "cleat"
, "mango"
, "rumba"
, "puffy"
, "filly"
, "billy"
, "leash"
, "clout"
, "dance"
, "ovate"
, "facet"
, "chili"
, "paint"
, "liner"
, "curio"
, "salty"
, "audio"
, "snake"
, "fable"
, "cloak"
, "navel"
, "spurt"
, "pesto"
, "balmy"
, "flash"
, "unwed"
, "early"
, "churn"
, "weedy"
, "stump"
, "lease"
, "witty"
, "wimpy"
, "spoof"
, "saner"
, "blend"
, "salsa"
, "thick"
, "warty"
, "manic"
, "blare"
, "squib"
, "spoon"
, "probe"
, "crepe"
, "knack"
, "force"
, "debut"
, "order"
, "haste"
, "teeth"
, "agent"
, "widen"
, "icily"
, "slice"
, "ingot"
, "clash"
, "juror"
, "blood"
, "abode"
, "throw"
, "unity"
, "pivot"
, "slept"
, "troop"
, "spare"
, "sewer"
, "parse"
, "morph"
, "cacti"
, "tacky"
, "spool"
, "demon"
, "moody"
, "annex"
, "begin"
, "fuzzy"
, "patch"
, "water"
, "lumpy"
, "admin"
, "omega"
, "limit"
, "tabby"
, "macho"
, "aisle"
, "skiff"
, "basis"
, "plank"
, "verge"
, "botch"
, "crawl"
, "lousy"
, "slain"
, "cubic"
, "raise"
, "wrack"
, "guide"
, "foist"
, "cameo"
, "under"
, "actor"
, "revue"
, "fraud"
, "harpy"
, "scoop"
, "climb"
, "refer"
, "olden"
, "clerk"
, "debar"
, "tally"
, "ethic"
, "cairn"
, "tulle"
, "ghoul"
, "hilly"
, "crude"
, "apart"
, "scale"
, "older"
, "plain"
, "sperm"
, "briny"
, "abbot"
, "rerun"
, "quest"
, "crisp"
, "bound"
, "befit"
, "drawn"
, "suite"
, "itchy"
, "cheer"
, "bagel"
, "guess"
, "broad"
, "axiom"
, "chard"
, "caput"
, "leant"
, "harsh"
, "curse"
, "proud"
, "swing"
, "opine"
, "taste"
, "lupus"
, "gumbo"
, "miner"
, "green"
, "chasm"
, "lipid"
, "topic"
, "armor"
, "brush"
, "crane"
, "mural"
, "abled"
, "habit"
, "bossy"
, "maker"
, "dusky"
, "dizzy"
, "lithe"
, "brook"
, "jazzy"
, "fifty"
, "sense"
, "giant"
, "surly"
, "legal"
, "fatal"
, "flunk"
, "began"
, "prune"
, "small"
, "slant"
, "scoff"
, "torus"
, "ninny"
, "<NAME>"
, "viper"
, "taken"
, "moral"
, "vogue"
, "owing"
, "token"
, "entry"
, "booth"
, "voter"
, "chide"
, "<NAME>fin"
, "ebony"
, "neigh"
, "minim"
, "melon"
, "kneed"
, "decoy"
, "voila"
, "ankle"
, "arrow"
, "mushy"
, "tribe"
, "cease"
, "eager"
, "birth"
, "graph"
, "odder"
, "terra"
, "weird"
, "tried"
, "clack"
, "color"
, "rough"
, "weigh"
, "uncut"
, "ladle"
, "strip"
, "craft"
, "minus"
, "dicey"
, "titan"
, "lucid"
, "vicar"
, "dress"
, "ditch"
, "gypsy"
, "pasta"
, "taffy"
, "flame"
, "swoop"
, "aloof"
, "sight"
, "broke"
, "teary"
, "chart"
, "sixty"
, "wordy"
, "sheer"
, "leper"
, "nosey"
, "bulge"
, "savor"
, "clamp"
, "funky"
, "foamy"
, "toxic"
, "brand"
, "plumb"
, "dingy"
, "butte"
, "drill"
, "tripe"
, "bicep"
, "tenor"
, "krill"
, "worse"
, "drama"
, "hyena"
, "think"
, "ratio"
, "cobra"
, "basil"
, "scrum"
, "bused"
, "phone"
, "court"
, "camel"
, "proof"
, "heard"
, "angel"
, "petal"
, "pouty"
, "throb"
, "maybe"
, "fetal"
, "sprig"
, "spine"
, "<NAME>"
, "<NAME>"
, "macro"
, "dodgy"
, "satyr"
, "<NAME>arer"
, "binge"
, "trend"
, "nutty"
, "leapt"
, "<NAME>"
, "split"
, "myrrh"
, "width"
, "sonar"
, "tower"
, "baron"
, "fever"
, "waver"
, "spark"
, "belie"
, "sloop"
, "expel"
, "smote"
, "baler"
, "above"
, "north"
, "wafer"
, "scant"
, "<NAME>"
, "awash"
, "snack"
, "scowl"
, "frail"
, "drift"
, "limbo"
, "fence"
, "motel"
, "ounce"
, "wreak"
, "revel"
, "<NAME>"
, "prior"
, "<NAME>"
, "<NAME>"
, "flake"
, "debug"
, "anode"
, "<NAME>me"
, "salve"
, "scout"
, "imbue"
, "pinky"
, "stave"
, "vague"
, "chock"
, "fight"
, "video"
, "stone"
, "teach"
, "cleft"
, "frost"
, "<NAME>awn"
, "booty"
, "twist"
, "<NAME>nea"
, "stiff"
, "plaza"
, "ledge"
, "tweak"
, "board"
, "grant"
, "medic"
, "<NAME>acon"
, "cable"
, "brawl"
, "slunk"
, "raspy"
, "forum"
, "drone"
, "women"
, "<NAME>ucus"
, "boast"
, "<NAME>dy"
, "<NAME>ven"
, "tumor"
, "<NAME>uer"
, "wrath"
, "stall"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "berry"
, "co<NAME>"
, "<NAME>"
, "br<NAME>"
, "leg<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "sc<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "avoid"
, "quote"
, "<NAME>"
, "<NAME>"
, "gloss"
, "g<NAME>"
, "<NAME>"
, "noise"
, "gland"
, "dealt"
, "sling"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "tonga"
, "<NAME>"
, "wound"
, "<NAME>"
, "<NAME>"
, "etude"
, "horse"
, "<NAME>"
, "<NAME>"
, "inbox"
, "fizzy"
, "<NAME>ain"
, "<NAME>"
, "surge"
, "<NAME>"
, "belle"
, "<NAME>"
, "crush"
, "fruit"
, "sappy"
, "taker"
, "tract"
, "<NAME>ine"
, "spiky"
, "<NAME>"
, "reedy"
, "<NAME>th"
, "spasm"
, "<NAME>ave"
, "<NAME>"
, "right"
, "<NAME>ank"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>acht"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "state"
, "grasp"
, "milky"
, "<NAME>"
, "<NAME>"
, "sandy"
, "baste"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "blade"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "cloud"
, "cabal"
, "le<NAME>"
, "close"
, "tenth"
, "<NAME>"
, "<NAME>"
, "<NAME>ail"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>ee"
, "<NAME>"
, "<NAME>"
, "f<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "fully"
, "zonal"
, "metro"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "occur"
, "chain"
, "nasal"
, "gooey"
, "filer"
, "brace"
, "allay"
, "pubic"
, "raven"
, "plead"
, "gnash"
, "flaky"
, "munch"
, "dully"
, "eking"
, "thing"
, "slink"
, "hurry"
, "theft"
, "shorn"
, "pygmy"
, "ranch"
, "wring"
, "lemon"
, "shore"
, "mamma"
, "froze"
, "newer"
, "style"
, "moose"
, "antic"
, "drown"
, "vegan"
, "chess"
, "guppy"
, "union"
, "lever"
, "lorry"
, "image"
, "cabby"
, "druid"
, "exact"
, "truth"
, "dopey"
, "spear"
, "cried"
, "chime"
, "crony"
, "stunk"
, "timid"
, "batch"
, "gauge"
, "rotor"
, "crack"
, "curve"
, "latte"
, "witch"
, "bunch"
, "repel"
, "anvil"
, "soapy"
, "meter"
, "broth"
, "madly"
, "dried"
, "scene"
, "known"
, "magma"
, "roost"
, "woman"
, "thong"
, "punch"
, "pasty"
, "downy"
, "knead"
, "whirl"
, "rapid"
, "clang"
, "anger"
, "drive"
, "goofy"
, "email"
, "music"
, "stuff"
, "bleep"
, "rider"
, "mecca"
, "folio"
, "setup"
, "verso"
, "quash"
, "fauna"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "press"
, "<NAME>ose"
, "<NAME>"
, "<NAME>"
, "speak"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "sn<NAME>"
, "<NAME>"
, "<NAME>y"
, "<NAME>"
, "going"
, "leach"
, "mouth"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "piece"
, "bl<NAME>"
, "<NAME>"
, "sp<NAME>"
, "<NAME>id"
, "intro"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "hello"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "extra"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "adult"
, "judge"
, "<NAME>"
, "<NAME>"
, "<NAME>"
, "<NAME>"
]
length : Int
length =
List.length asList
| true | module Words exposing (asList, length)
asList : List String
asList =
[ "cigar"
, "rebut"
, "sissy"
, "humph"
, "awake"
, "blush"
, "focal"
, "evade"
, "naval"
, "serve"
, "heath"
, "dwarf"
, "model"
, "karma"
, "stink"
, "grade"
, "quiet"
, "bench"
, "abate"
, "feign"
, "major"
, "death"
, "fresh"
, "crust"
, "stool"
, "colon"
, "abase"
, "marry"
, "react"
, "batty"
, "pride"
, "floss"
, "helix"
, "croak"
, "staff"
, "paper"
, "unfed"
, "whelp"
, "trawl"
, "outdo"
, "adobe"
, "crazy"
, "sower"
, "repay"
, "digit"
, "crate"
, "cluck"
, "spike"
, "mimic"
, "pound"
, "maxim"
, "linen"
, "unmet"
, "flesh"
, "booby"
, "forth"
, "first"
, "stand"
, "belly"
, "ivory"
, "seedy"
, "print"
, "yearn"
, "drain"
, "bribe"
, "stout"
, "panel"
, "crass"
, "flume"
, "offal"
, "agree"
, "error"
, "swirl"
, "argue"
, "bleed"
, "delta"
, "flick"
, "totem"
, "wooer"
, "front"
, "shrub"
, "parry"
, "biome"
, "lapel"
, "start"
, "greet"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PIy"
, "loopy"
, "round"
, "audit"
, "lying"
, "gamma"
, "labor"
, "islet"
, "civic"
, "forge"
, "PI:NAME:<NAME>END_PI"
, "moult"
, "basic"
, "salad"
, "agate"
, "spicy"
, "spray"
, "essay"
, "fjord"
, "spend"
, "kebab"
, "guild"
, "aback"
, "motor"
, "alone"
, "hatch"
, "hyper"
, "thumb"
, "dowry"
, "ought"
, "belch"
, "dutch"
, "pilot"
, "tweed"
, "comet"
, "jaunt"
, "enema"
, "steed"
, "abyss"
, "growl"
, "fling"
, "dozen"
, "boozy"
, "erode"
, "world"
, "gouge"
, "click"
, "briar"
, "great"
, "altar"
, "pulpy"
, "blurt"
, "coast"
, "duchy"
, "groin"
, "fixer"
, "group"
, "rogue"
, "badly"
, "smart"
, "pithy"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "radio"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "retch"
, "wrote"
, "clock"
, "tilde"
, "store"
, "prove"
, "bring"
, "solve"
, "cheat"
, "grime"
, "exult"
, "usher"
, "epoch"
, "triad"
, "break"
, "rhino"
, "viral"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "sonic"
, "vital"
, "trace"
, "using"
, "peach"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "brake"
, "pluck"
, "craze"
, "PI:NAME:<NAME>END_PI"
, "weary"
, "picky"
, "acute"
, "PI:NAME:<NAME>END_PI"
, "aside"
, "tapir"
, "troll"
, "unify"
, "rebus"
, "boost"
, "truss"
, "siege"
, "tiger"
, "banal"
, "slump"
, "crank"
, "gorge"
, "query"
, "drink"
, "favor"
, "abbey"
, "tangy"
, "panic"
, "solar"
, "shire"
, "proxy"
, "point"
, "robot"
, "PI:NAME:<NAME>END_PIick"
, "PI:NAME:<NAME>END_PIince"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "sugar"
, "whack"
, "mount"
, "perky"
, "could"
, "wrung"
, "light"
, "those"
, "moist"
, "shard"
, "pleat"
, "aloft"
, "skill"
, "elder"
, "frame"
, "humor"
, "pause"
, "ulcer"
, "ultra"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "aroma"
, "PI:NAME:<NAME>END_PI"
, "shake"
, "pupal"
, "dodge"
, "swill"
, "tacit"
, "other"
, "thorn"
, "trove"
, "bloke"
, "vivid"
, "spill"
, "chant"
, "choke"
, "rupee"
, "nasty"
, "mourn"
, "ahead"
, "brine"
, "cloth"
, "hoard"
, "sweet"
, "month"
, "lapse"
, "watch"
, "today"
, "focus"
, "smelt"
, "tease"
, "cater"
, "movie"
, "lynch"
, "saute"
, "allow"
, "renew"
, "their"
, "slosh"
, "purge"
, "chest"
, "depot"
, "epoxy"
, "nymph"
, "found"
, "shall"
, "PI:NAME:<NAME>END_PIarry"
, "stove"
, "lowly"
, "snout"
, "trope"
, "fewer"
, "shawl"
, "natal"
, "fibre"
, "comma"
, "foray"
, "scare"
, "stair"
, "black"
, "squad"
, "royal"
, "chunk"
, "mince"
, "slave"
, "shame"
, "cheek"
, "ample"
, "flair"
, "PI:NAME:<NAME>END_PIyer"
, "cargo"
, "oxide"
, "plant"
, "olive"
, "inert"
, "PI:NAME:<NAME>END_PIew"
, "heist"
, "shown"
, "zesty"
, "hasty"
, "trash"
, "fella"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "story"
, "hairy"
, "train"
, "homer"
, "badge"
, "midst"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "butch"
, "farce"
, "slung"
, "tipsy"
, "metal"
, "yield"
, "delve"
, "being"
, "scour"
, "glass"
, "gamer"
, "scrap"
, "money"
, "hinge"
, "album"
, "vouch"
, "asset"
, "tiara"
, "crept"
, "bayou"
, "atoll"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "showy"
, "phase"
, "froth"
, "depth"
, "gloom"
, "flood"
, "trait"
, "girth"
, "piety"
, "payer"
, "goose"
, "float"
, "PI:NAME:<NAME>END_PI"
, "atone"
, "primo"
, "PI:NAME:<NAME>END_PI"
, "blown"
, "cacao"
, "loser"
, "input"
, "gloat"
, "awful"
, "brink"
, "smite"
, "beady"
, "rusty"
, "retro"
, "dPI:NAME:<NAME>END_PI"
, "gawPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "pinto"
, "PI:NAME:<NAME>END_PIaily"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "field"
, "fluff"
, "hydro"
, "flack"
, "PI:NAME:<NAME>END_PI"
, "wench"
, "voice"
, "stead"
, "stalk"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "night"
, "bland"
, "liver"
, "wedge"
, "PI:NAME:<NAME>END_PI"
, "roomy"
, "wacky"
, "flock"
, "angry"
, "PI:NAME:<NAME>END_PI"
, "trPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "tryst"
, "midge"
, "power"
, "elope"
, "cinch"
, "motto"
, "stomp"
, "upset"
, "bluff"
, "cramp"
, "quart"
, "coyly"
, "youth"
, "rhyme"
, "buggy"
, "alien"
, "smear"
, "unfit"
, "PI:NAME:<NAME>END_PIty"
, "cling"
, "glean"
, "label"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "poker"
, "PI:NAME:<NAME>END_PI"
, "twice"
, "twang"
, "shrug"
, "treat"
, "unlit"
, "waste"
, "merit"
, "woven"
, "octal"
, "needy"
, "clown"
, "widow"
, "irony"
, "ruder"
, "gauze"
, "chief"
, "onset"
, "prize"
, "fungi"
, "charm"
, "gully"
, "inter"
, "whoop"
, "taunt"
, "leery"
, "class"
, "theme"
, "lofty"
, "tibia"
, "booze"
, "alpha"
, "thyme"
, "eclat"
, "doubt"
, "parer"
, "chute"
, "stick"
, "trice"
, "alike"
, "sooth"
, "recap"
, "saint"
, "liege"
, "glory"
, "grate"
, "admit"
, "brisk"
, "soggy"
, "usurp"
, "scald"
, "scorn"
, "leave"
, "twine"
, "sting"
, "bough"
, "marsh"
, "sloth"
, "dandy"
, "vigor"
, "howdy"
, "enjoy"
, "valid"
, "ionic"
, "equal"
, "unset"
, "floor"
, "catch"
, "spade"
, "stein"
, "exist"
, "quirk"
, "denim"
, "grove"
, "spiel"
, "mummy"
, "fault"
, "foggy"
, "flout"
, "carry"
, "sneak"
, "libel"
, "waltz"
, "aptly"
, "piney"
, "inept"
, "aloud"
, "photo"
, "dream"
, "stale"
, "vomit"
, "ombre"
, "fanny"
, "unite"
, "snarl"
, "baker"
, "there"
, "glyph"
, "pooch"
, "hippy"
, "spell"
, "folly"
, "louse"
, "gulch"
, "vault"
, "godly"
, "threw"
, "fleet"
, "grave"
, "inane"
, "shock"
, "crave"
, "spite"
, "valve"
, "skimp"
, "claim"
, "rainy"
, "musty"
, "pique"
, "daddy"
, "quasi"
, "arise"
, "aging"
, "valet"
, "opium"
, "avert"
, "stuck"
, "recut"
, "mulch"
, "genre"
, "plume"
, "rifle"
, "count"
, "incur"
, "total"
, "wrest"
, "mocha"
, "deter"
, "study"
, "lover"
, "safer"
, "rivet"
, "funny"
, "smoke"
, "mound"
, "undue"
, "sedan"
, "pagan"
, "swine"
, "guile"
, "gusty"
, "equip"
, "tough"
, "canoe"
, "chaos"
, "covet"
, "human"
, "udder"
, "lunch"
, "blast"
, "stray"
, "manga"
, "melee"
, "lefty"
, "quick"
, "paste"
, "given"
, "octet"
, "risen"
, "groan"
, "leaky"
, "grind"
, "carve"
, "loose"
, "sadly"
, "spilt"
, "apple"
, "slack"
, "PI:NAME:<NAME>END_PI"
, "final"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PIarf"
, "spelt"
, "coach"
, "erupt"
, "PI:NAME:<NAME>END_PI"
, "price"
, "spawn"
, "fairy"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "stack"
, "chose"
, "sleep"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "niece"
, "woozy"
, "handy"
, "grace"
, "PI:NAME:<NAME>END_PIto"
, "stank"
, "cream"
, "usual"
, "diode"
, "valor"
, "angle"
, "ninja"
, "PI:NAME:<NAME>END_PI"
, "chase"
, "reply"
, "prone"
, "spoil"
, "heart"
, "shade"
, "diner"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "dowel"
, "couch"
, "pPI:NAME:<NAME>END_PI"
, "bowel"
, "smile"
, "evoke"
, "creek"
, "lance"
, "eagle"
, "idiot"
, "siren"
, "built"
, "embed"
, "award"
, "dPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "frown"
, "patio"
, "laden"
, "humid"
, "elite"
, "lymph"
, "edify"
, "might"
, "reset"
, "visit"
, "gusto"
, "purse"
, "vapor"
, "crock"
, "write"
, "sunny"
, "loath"
, "chaff"
, "slide"
, "queer"
, "venom"
, "stamp"
, "sorry"
, "still"
, "acorn"
, "aping"
, "pushy"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PIile"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "house"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "exPI:NAME:<NAME>END_PI"
, "about"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "cycle"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "place"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "stage"
, "decay"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "clean"
, "china"
, "ridge"
, "vowel"
, "gnome"
, "snPI:NAME:<NAME>END_PI"
, "icing"
, "spPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "snPI:NAME:<NAME>END_PI"
, "flowPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "track"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "doing"
, "ozone"
, "amply"
, "molar"
, "ovary"
, "beset"
, "queue"
, "cliff"
, "magic"
, "truce"
, "sport"
, "PI:NAME:<NAME>END_PI"
, "edict"
, "twirl"
, "verse"
, "llama"
, "eaten"
, "range"
, "whisk"
, "hovel"
, "rehab"
, "macaw"
, "sigma"
, "spout"
, "verve"
, "sushi"
, "dying"
, "fetid"
, "brain"
, "buddy"
, "thump"
, "scion"
, "PI:NAME:<NAME>END_PIandy"
, "chord"
, "basin"
, "march"
, "crowd"
, "arbor"
, "gayly"
, "musky"
, "stain"
, "PI:NAME:<NAME>END_PI"
, "bless"
, "PI:NAME:<NAME>END_PI"
, "stung"
, "title"
, "ruler"
, "kiosk"
, "blond"
, "PI:NAME:<NAME>END_PIui"
, "layer"
, "fluid"
, "tatty"
, "score"
, "cutie"
, "zebra"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PIy"
, "PI:NAME:<NAME>END_PI"
, "aider"
, "shook"
, "river"
, "privy"
, "betel"
, "PI:NAME:<NAME>END_PIisk"
, "bongo"
, "begun"
, "azure"
, "weave"
, "PI:NAME:<NAME>END_PIie"
, "sound"
, "glove"
, "braid"
, "scope"
, "wryly"
, "rover"
, "assay"
, "ocean"
, "bloom"
, "irate"
, "later"
, "woken"
, "silky"
, "wreck"
, "dwelt"
, "slate"
, "smack"
, "solid"
, "amaze"
, "hazel"
, "wrist"
, "jolly"
, "globe"
, "flint"
, "rouse"
, "civil"
, "vista"
, "relax"
, "cover"
, "alive"
, "beech"
, "jetty"
, "bliss"
, "vocal"
, "often"
, "dolly"
, "eight"
, "joker"
, "since"
, "event"
, "ensue"
, "shunt"
, "diver"
, "poser"
, "worst"
, "sweep"
, "alley"
, "creed"
, "anime"
, "leafy"
, "bosom"
, "dunce"
, "stare"
, "pudgy"
, "waive"
, "choir"
, "stood"
, "spoke"
, "outgo"
, "delay"
, "bilge"
, "ideal"
, "clasp"
, "seize"
, "hotly"
, "laugh"
, "sieve"
, "block"
, "meant"
, "grape"
, "noose"
, "hardy"
, "shied"
, "drawl"
, "daisy"
, "putty"
, "strut"
, "burnt"
, "tulip"
, "PI:NAME:<NAME>END_PIick"
, "idyll"
, "vixen"
, "furor"
, "geeky"
, "cough"
, "naive"
, "shoal"
, "stork"
, "bathe"
, "aunty"
, "check"
, "prime"
, "brass"
, "outer"
, "furry"
, "razor"
, "elect"
, "evict"
, "imply"
, "demur"
, "quota"
, "haven"
, "cavil"
, "swear"
, "crump"
, "dough"
, "gavel"
, "wagon"
, "salon"
, "nudge"
, "hPI:NAME:<NAME>END_PI"
, "pitch"
, "sworn"
, "pupil"
, "excel"
, "stony"
, "cabin"
, "unzip"
, "queen"
, "trout"
, "polyp"
, "earth"
, "storm"
, "until"
, "taper"
, "enter"
, "child"
, "adopt"
, "minor"
, "fatty"
, "husky"
, "brave"
, "filet"
, "slime"
, "glint"
, "tread"
, "steal"
, "regal"
, "guest"
, "every"
, "murky"
, "share"
, "spore"
, "hoist"
, "buxom"
, "inner"
, "otter"
, "dimly"
, "level"
, "sumac"
, "donut"
, "stilt"
, "arena"
, "sheet"
, "scrub"
, "fancy"
, "slimy"
, "pearl"
, "silly"
, "porch"
, "dingo"
, "sepia"
, "amble"
, "shady"
, "bread"
, "friar"
, "reign"
, "dairy"
, "quill"
, "cross"
, "brood"
, "tuber"
, "shear"
, "posit"
, "blank"
, "villa"
, "shank"
, "piggy"
, "freak"
, "which"
, "among"
, "fecal"
, "shell"
, "would"
, "algae"
, "large"
, "rabbi"
, "agony"
, "amuse"
, "bushy"
, "copse"
, "swoon"
, "knife"
, "pouch"
, "PI:NAME:<NAME>END_PI"
, "plane"
, "crown"
, "urban"
, "snide"
, "relay"
, "abide"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "straw"
, "PI:NAME:<NAME>END_PI"
, "crash"
, "PI:NAME:<NAME>END_PIass"
, "third"
, "PI:NAME:<NAME>END_PIick"
, "tutor"
, "PI:NAME:<NAME>END_PI"
, "blurb"
, "grief"
, "disco"
, "where"
, "sassy"
, "beach"
, "sauna"
, "comic"
, "clued"
, "creep"
, "PI:NAME:<NAME>END_PI"
, "graze"
, "snuff"
, "frock"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "steel"
, "halve"
, "buyer"
, "vinyl"
, "utile"
, "smell"
, "adage"
, "worry"
, "tasty"
, "local"
, "trade"
, "finch"
, "PI:NAME:<NAME>END_PI"
, "modal"
, "gaunt"
, "clove"
, "enact"
, "adorn"
, "roast"
, "speck"
, "sheik"
, "missy"
, "PI:NAME:<NAME>END_PI"
, "snoop"
, "party"
, "touch"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "array"
, "south"
, "vapid"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "angst"
, "tubal"
, "lower"
, "crest"
, "sweat"
, "cyber"
, "adore"
, "tardy"
, "swami"
, "notch"
, "groom"
, "roach"
, "hitch"
, "young"
, "align"
, "ready"
, "frond"
, "strap"
, "puree"
, "realm"
, "venue"
, "swarm"
, "offer"
, "seven"
, "dryer"
, "PI:NAME:<NAME>END_PIary"
, "dryly"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "heady"
, "theta"
, "PI:NAME:<NAME>END_PIunto"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PIoth"
, "bonus"
, "shalt"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "datum"
, "build"
, "piano"
, "shelf"
, "lodge"
, "suing"
, "rearm"
, "coral"
, "PI:NAME:<NAME>END_PI"
, "worth"
, "psalm"
, "infer"
, "overt"
, "mayor"
, "ovoid"
, "glide"
, "usage"
, "poise"
, "PI:NAME:<NAME>END_PIy"
, "chuck"
, "PI:NAME:<NAME>END_PI"
, "fishy"
, "tooth"
, "ether"
, "drove"
, "PI:NAME:<NAME>END_PIler"
, "PI:NAME:<NAME>END_PIath"
, "stint"
, "while"
, "begat"
, "apply"
, "slang"
, "tarot"
, "radar"
, "PI:NAME:<NAME>END_PI"
, "aware"
, "canon"
, "shift"
, "timer"
, "bylaw"
, "PI:NAME:<NAME>END_PIum"
, "three"
, "steak"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "blunt"
, "puppy"
, "penal"
, "joist"
, "PI:NAME:<NAME>END_PI"
, "shape"
, "beget"
, "wheel"
, "adept"
, "stunt"
, "stole"
, "topaz"
, "chore"
, "fluke"
, "afoot"
, "bloat"
, "bully"
, "dense"
, "caper"
, "sneer"
, "boxer"
, "jumbo"
, "lunge"
, "space"
, "avail"
, "short"
, "slurp"
, "loyal"
, "flirt"
, "pizza"
, "conch"
, "tempo"
, "droop"
, "plate"
, "bible"
, "plunk"
, "afoul"
, "savoy"
, "steep"
, "agile"
, "stake"
, "dwell"
, "knave"
, "beard"
, "arose"
, "motif"
, "smash"
, "broil"
, "glare"
, "shove"
, "baggy"
, "mammy"
, "swamp"
, "along"
, "rugby"
, "wager"
, "quack"
, "squat"
, "snaky"
, "debit"
, "mange"
, "skate"
, "ninth"
, "joust"
, "tramp"
, "spurn"
, "medal"
, "micro"
, "rebel"
, "flank"
, "learn"
, "PI:NAME:<NAME>END_PI"
, "maple"
, "comfy"
, "remit"
, "PI:NAME:<NAME>END_PIuff"
, "ester"
, "least"
, "mogul"
, "fetch"
, "cause"
, "oaken"
, "aglow"
, "meaty"
, "gaffe"
, "shyly"
, "PI:NAME:<NAME>END_PIacer"
, "prowl"
, "thief"
, "stern"
, "poesy"
, "rocky"
, "tweet"
, "waist"
, "spire"
, "grope"
, "havoc"
, "patsy"
, "truly"
, "forty"
, "deity"
, "uncle"
, "swish"
, "giver"
, "preen"
, "bevel"
, "lemur"
, "draft"
, "slope"
, "annoy"
, "lingo"
, "bleak"
, "ditty"
, "curly"
, "cedar"
, "dirge"
, "grown"
, "horde"
, "drool"
, "shuck"
, "crypt"
, "cumin"
, "stock"
, "gravy"
, "locus"
, "wider"
, "breed"
, "quite"
, "chafe"
, "cache"
, "blimp"
, "deign"
, "fiend"
, "logic"
, "cheap"
, "elide"
, "rigid"
, "false"
, "renal"
, "pence"
, "rowdy"
, "shoot"
, "blaze"
, "envoy"
, "posse"
, "brief"
, "never"
, "abort"
, "mouse"
, "mucky"
, "sulky"
, "fiery"
, "media"
, "trunk"
, "yeast"
, "clear"
, "skunk"
, "scalp"
, "bitty"
, "cider"
, "koala"
, "duvet"
, "segue"
, "creme"
, "super"
, "grill"
, "after"
, "owner"
, "ember"
, "reach"
, "nobly"
, "empty"
, "speed"
, "gipsy"
, "recur"
, "smock"
, "dread"
, "merge"
, "burst"
, "kappa"
, "amity"
, "shaky"
, "hover"
, "carol"
, "snort"
, "synod"
, "faint"
, "haunt"
, "flour"
, "chair"
, "detox"
, "shrew"
, "tense"
, "plied"
, "quark"
, "burly"
, "novel"
, "waxen"
, "stoic"
, "PI:NAME:<NAME>END_PIky"
, "blitz"
, "beefy"
, "PI:NAME:<NAME>END_PI"
, "hussy"
, "towel"
, "quilt"
, "below"
, "bingo"
, "wispy"
, "brash"
, "scone"
, "toast"
, "easel"
, "saucy"
, "value"
, "spice"
, "honor"
, "route"
, "sharp"
, "bawdy"
, "radii"
, "skull"
, "phony"
, "issue"
, "lager"
, "swell"
, "urine"
, "gassy"
, "trial"
, "flora"
, "upper"
, "latch"
, "wight"
, "brick"
, "retry"
, "holly"
, "decal"
, "grass"
, "shack"
, "dogma"
, "mover"
, "defer"
, "sober"
, "optic"
, "crier"
, "vying"
, "nomad"
, "flute"
, "hippo"
, "shark"
, "drier"
, "obese"
, "bugle"
, "tawny"
, "chalk"
, "feast"
, "ruddy"
, "pedal"
, "scarf"
, "cruel"
, "bleat"
, "tidal"
, "slush"
, "semen"
, "windy"
, "dusty"
, "sally"
, "igloo"
, "nerdy"
, "jewel"
, "shone"
, "whale"
, "hymen"
, "abuse"
, "fugue"
, "elbow"
, "crumb"
, "pansy"
, "welsh"
, "syrup"
, "terse"
, "suave"
, "gamut"
, "swung"
, "drake"
, "freed"
, "afire"
, "shirt"
, "grout"
, "oddly"
, "tithe"
, "plaid"
, "dummy"
, "broom"
, "blind"
, "torch"
, "enemy"
, "again"
, "tying"
, "pesky"
, "PI:NAME:<NAME>END_PI"
, "gPI:NAME:<NAME>END_PI"
, "noble"
, "ethos"
, "bride"
, "extol"
, "decor"
, "hobby"
, "beast"
, "idiom"
, "utter"
, "these"
, "sixth"
, "alarm"
, "erase"
, "elegy"
, "spunk"
, "PI:NAME:<NAME>END_PI"
, "scaly"
, "scold"
, "hefty"
, "chick"
, "sooty"
, "canal"
, "whiny"
, "slash"
, "quake"
, "joint"
, "swept"
, "prude"
, "heavy"
, "wield"
, "femme"
, "lasso"
, "maize"
, "shale"
, "screw"
, "spree"
, "smoky"
, "whiff"
, "scent"
, "glade"
, "spent"
, "prism"
, "stoke"
, "PI:NAME:<NAME>END_PI"
, "orbit"
, "cocoa"
, "guilt"
, "humus"
, "shush"
, "table"
, "smirk"
, "wrong"
, "noisy"
, "alert"
, "shiny"
, "elate"
, "resin"
, "whole"
, "hunch"
, "pixel"
, "polar"
, "hotel"
, "sword"
, "cleat"
, "mango"
, "rumba"
, "puffy"
, "filly"
, "billy"
, "leash"
, "clout"
, "dance"
, "ovate"
, "facet"
, "chili"
, "paint"
, "liner"
, "curio"
, "salty"
, "audio"
, "snake"
, "fable"
, "cloak"
, "navel"
, "spurt"
, "pesto"
, "balmy"
, "flash"
, "unwed"
, "early"
, "churn"
, "weedy"
, "stump"
, "lease"
, "witty"
, "wimpy"
, "spoof"
, "saner"
, "blend"
, "salsa"
, "thick"
, "warty"
, "manic"
, "blare"
, "squib"
, "spoon"
, "probe"
, "crepe"
, "knack"
, "force"
, "debut"
, "order"
, "haste"
, "teeth"
, "agent"
, "widen"
, "icily"
, "slice"
, "ingot"
, "clash"
, "juror"
, "blood"
, "abode"
, "throw"
, "unity"
, "pivot"
, "slept"
, "troop"
, "spare"
, "sewer"
, "parse"
, "morph"
, "cacti"
, "tacky"
, "spool"
, "demon"
, "moody"
, "annex"
, "begin"
, "fuzzy"
, "patch"
, "water"
, "lumpy"
, "admin"
, "omega"
, "limit"
, "tabby"
, "macho"
, "aisle"
, "skiff"
, "basis"
, "plank"
, "verge"
, "botch"
, "crawl"
, "lousy"
, "slain"
, "cubic"
, "raise"
, "wrack"
, "guide"
, "foist"
, "cameo"
, "under"
, "actor"
, "revue"
, "fraud"
, "harpy"
, "scoop"
, "climb"
, "refer"
, "olden"
, "clerk"
, "debar"
, "tally"
, "ethic"
, "cairn"
, "tulle"
, "ghoul"
, "hilly"
, "crude"
, "apart"
, "scale"
, "older"
, "plain"
, "sperm"
, "briny"
, "abbot"
, "rerun"
, "quest"
, "crisp"
, "bound"
, "befit"
, "drawn"
, "suite"
, "itchy"
, "cheer"
, "bagel"
, "guess"
, "broad"
, "axiom"
, "chard"
, "caput"
, "leant"
, "harsh"
, "curse"
, "proud"
, "swing"
, "opine"
, "taste"
, "lupus"
, "gumbo"
, "miner"
, "green"
, "chasm"
, "lipid"
, "topic"
, "armor"
, "brush"
, "crane"
, "mural"
, "abled"
, "habit"
, "bossy"
, "maker"
, "dusky"
, "dizzy"
, "lithe"
, "brook"
, "jazzy"
, "fifty"
, "sense"
, "giant"
, "surly"
, "legal"
, "fatal"
, "flunk"
, "began"
, "prune"
, "small"
, "slant"
, "scoff"
, "torus"
, "ninny"
, "PI:NAME:<NAME>END_PI"
, "viper"
, "taken"
, "moral"
, "vogue"
, "owing"
, "token"
, "entry"
, "booth"
, "voter"
, "chide"
, "PI:NAME:<NAME>END_PIfin"
, "ebony"
, "neigh"
, "minim"
, "melon"
, "kneed"
, "decoy"
, "voila"
, "ankle"
, "arrow"
, "mushy"
, "tribe"
, "cease"
, "eager"
, "birth"
, "graph"
, "odder"
, "terra"
, "weird"
, "tried"
, "clack"
, "color"
, "rough"
, "weigh"
, "uncut"
, "ladle"
, "strip"
, "craft"
, "minus"
, "dicey"
, "titan"
, "lucid"
, "vicar"
, "dress"
, "ditch"
, "gypsy"
, "pasta"
, "taffy"
, "flame"
, "swoop"
, "aloof"
, "sight"
, "broke"
, "teary"
, "chart"
, "sixty"
, "wordy"
, "sheer"
, "leper"
, "nosey"
, "bulge"
, "savor"
, "clamp"
, "funky"
, "foamy"
, "toxic"
, "brand"
, "plumb"
, "dingy"
, "butte"
, "drill"
, "tripe"
, "bicep"
, "tenor"
, "krill"
, "worse"
, "drama"
, "hyena"
, "think"
, "ratio"
, "cobra"
, "basil"
, "scrum"
, "bused"
, "phone"
, "court"
, "camel"
, "proof"
, "heard"
, "angel"
, "petal"
, "pouty"
, "throb"
, "maybe"
, "fetal"
, "sprig"
, "spine"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "macro"
, "dodgy"
, "satyr"
, "PI:NAME:<NAME>END_PIarer"
, "binge"
, "trend"
, "nutty"
, "leapt"
, "PI:NAME:<NAME>END_PI"
, "split"
, "myrrh"
, "width"
, "sonar"
, "tower"
, "baron"
, "fever"
, "waver"
, "spark"
, "belie"
, "sloop"
, "expel"
, "smote"
, "baler"
, "above"
, "north"
, "wafer"
, "scant"
, "PI:NAME:<NAME>END_PI"
, "awash"
, "snack"
, "scowl"
, "frail"
, "drift"
, "limbo"
, "fence"
, "motel"
, "ounce"
, "wreak"
, "revel"
, "PI:NAME:<NAME>END_PI"
, "prior"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "flake"
, "debug"
, "anode"
, "PI:NAME:<NAME>END_PIme"
, "salve"
, "scout"
, "imbue"
, "pinky"
, "stave"
, "vague"
, "chock"
, "fight"
, "video"
, "stone"
, "teach"
, "cleft"
, "frost"
, "PI:NAME:<NAME>END_PIawn"
, "booty"
, "twist"
, "PI:NAME:<NAME>END_PInea"
, "stiff"
, "plaza"
, "ledge"
, "tweak"
, "board"
, "grant"
, "medic"
, "PI:NAME:<NAME>END_PIacon"
, "cable"
, "brawl"
, "slunk"
, "raspy"
, "forum"
, "drone"
, "women"
, "PI:NAME:<NAME>END_PIucus"
, "boast"
, "PI:NAME:<NAME>END_PIdy"
, "PI:NAME:<NAME>END_PIven"
, "tumor"
, "PI:NAME:<NAME>END_PIuer"
, "wrath"
, "stall"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "berry"
, "coPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "brPI:NAME:<NAME>END_PI"
, "legPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "scPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "avoid"
, "quote"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "gloss"
, "gPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "noise"
, "gland"
, "dealt"
, "sling"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "tonga"
, "PI:NAME:<NAME>END_PI"
, "wound"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "etude"
, "horse"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "inbox"
, "fizzy"
, "PI:NAME:<NAME>END_PIain"
, "PI:NAME:<NAME>END_PI"
, "surge"
, "PI:NAME:<NAME>END_PI"
, "belle"
, "PI:NAME:<NAME>END_PI"
, "crush"
, "fruit"
, "sappy"
, "taker"
, "tract"
, "PI:NAME:<NAME>END_PIine"
, "spiky"
, "PI:NAME:<NAME>END_PI"
, "reedy"
, "PI:NAME:<NAME>END_PIth"
, "spasm"
, "PI:NAME:<NAME>END_PIave"
, "PI:NAME:<NAME>END_PI"
, "right"
, "PI:NAME:<NAME>END_PIank"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PIacht"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "state"
, "grasp"
, "milky"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "sandy"
, "baste"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "blade"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "cloud"
, "cabal"
, "lePI:NAME:<NAME>END_PI"
, "close"
, "tenth"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PIail"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PIee"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "fPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "fully"
, "zonal"
, "metro"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "occur"
, "chain"
, "nasal"
, "gooey"
, "filer"
, "brace"
, "allay"
, "pubic"
, "raven"
, "plead"
, "gnash"
, "flaky"
, "munch"
, "dully"
, "eking"
, "thing"
, "slink"
, "hurry"
, "theft"
, "shorn"
, "pygmy"
, "ranch"
, "wring"
, "lemon"
, "shore"
, "mamma"
, "froze"
, "newer"
, "style"
, "moose"
, "antic"
, "drown"
, "vegan"
, "chess"
, "guppy"
, "union"
, "lever"
, "lorry"
, "image"
, "cabby"
, "druid"
, "exact"
, "truth"
, "dopey"
, "spear"
, "cried"
, "chime"
, "crony"
, "stunk"
, "timid"
, "batch"
, "gauge"
, "rotor"
, "crack"
, "curve"
, "latte"
, "witch"
, "bunch"
, "repel"
, "anvil"
, "soapy"
, "meter"
, "broth"
, "madly"
, "dried"
, "scene"
, "known"
, "magma"
, "roost"
, "woman"
, "thong"
, "punch"
, "pasty"
, "downy"
, "knead"
, "whirl"
, "rapid"
, "clang"
, "anger"
, "drive"
, "goofy"
, "email"
, "music"
, "stuff"
, "bleep"
, "rider"
, "mecca"
, "folio"
, "setup"
, "verso"
, "quash"
, "fauna"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "press"
, "PI:NAME:<NAME>END_PIose"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "speak"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "snPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PIy"
, "PI:NAME:<NAME>END_PI"
, "going"
, "leach"
, "mouth"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "piece"
, "blPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "spPI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PIid"
, "intro"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "hello"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "extra"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "adult"
, "judge"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
, "PI:NAME:<NAME>END_PI"
]
length : Int
length =
List.length asList
| elm |
[
{
"context": "[ type' \"text\"\n , placeholder \"Github name\"\n , onInput SetLogin\n ",
"end": 1160,
"score": 0.9922652245,
"start": 1149,
"tag": "NAME",
"value": "Github name"
}
] | generators/app/templates/src/elm/Pages/Login/View.elm | Gizra/generator-elmlang | 67 | module Pages.Login.View exposing (view)
import RemoteData exposing (RemoteData(..), WebData)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput, onSubmit)
import User.Model exposing (..)
import Pages.Login.Model exposing (..)
import Pages.Login.Update exposing (..)
view : WebData User -> Model -> Html Msg
view user model =
let
spinner =
i [ class "notched circle loading icon" ] []
( isLoading, isError ) =
case user of
Loading ->
( True, False )
Failure _ ->
( False, True )
_ ->
( False, False )
inputClasses =
classList
[ ( "ui action input", True )
, ( "error", isError )
]
in
Html.form
[ onSubmit TryLogin
, action "javascript:void(0);"
, class "ui stacked segment"
]
[ div [ inputClasses ]
[ input
[ type' "text"
, placeholder "Github name"
, onInput SetLogin
, value model.login
]
[]
-- Submit button
, button
[ onClick TryLogin
, disabled (isLoading || isError)
, class "ui primary button"
]
[ span [ hidden <| not isLoading ] [ spinner ]
, span [ hidden isLoading ] [ text "Login" ]
]
]
]
| 42418 | module Pages.Login.View exposing (view)
import RemoteData exposing (RemoteData(..), WebData)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput, onSubmit)
import User.Model exposing (..)
import Pages.Login.Model exposing (..)
import Pages.Login.Update exposing (..)
view : WebData User -> Model -> Html Msg
view user model =
let
spinner =
i [ class "notched circle loading icon" ] []
( isLoading, isError ) =
case user of
Loading ->
( True, False )
Failure _ ->
( False, True )
_ ->
( False, False )
inputClasses =
classList
[ ( "ui action input", True )
, ( "error", isError )
]
in
Html.form
[ onSubmit TryLogin
, action "javascript:void(0);"
, class "ui stacked segment"
]
[ div [ inputClasses ]
[ input
[ type' "text"
, placeholder "<NAME>"
, onInput SetLogin
, value model.login
]
[]
-- Submit button
, button
[ onClick TryLogin
, disabled (isLoading || isError)
, class "ui primary button"
]
[ span [ hidden <| not isLoading ] [ spinner ]
, span [ hidden isLoading ] [ text "Login" ]
]
]
]
| true | module Pages.Login.View exposing (view)
import RemoteData exposing (RemoteData(..), WebData)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput, onSubmit)
import User.Model exposing (..)
import Pages.Login.Model exposing (..)
import Pages.Login.Update exposing (..)
view : WebData User -> Model -> Html Msg
view user model =
let
spinner =
i [ class "notched circle loading icon" ] []
( isLoading, isError ) =
case user of
Loading ->
( True, False )
Failure _ ->
( False, True )
_ ->
( False, False )
inputClasses =
classList
[ ( "ui action input", True )
, ( "error", isError )
]
in
Html.form
[ onSubmit TryLogin
, action "javascript:void(0);"
, class "ui stacked segment"
]
[ div [ inputClasses ]
[ input
[ type' "text"
, placeholder "PI:NAME:<NAME>END_PI"
, onInput SetLogin
, value model.login
]
[]
-- Submit button
, button
[ onClick TryLogin
, disabled (isLoading || isError)
, class "ui primary button"
]
[ span [ hidden <| not isLoading ] [ spinner ]
, span [ hidden isLoading ] [ text "Login" ]
]
]
]
| elm |
[
{
"context": "\" ) ]\n ]\n [ Html.h1 [] [ Html.text \"Yinsh\" ]\n , Html.h2 [] [ Html.text \"on the Web!\"",
"end": 2114,
"score": 0.9987252355,
"start": 2109,
"tag": "NAME",
"value": "Yinsh"
},
{
"context": "ml.p []\n [ Html.a [ href \"//github.com/jreut/elm-yinsh\" ]\n [ Html.text \"source ",
"end": 2234,
"score": 0.999522984,
"start": 2229,
"tag": "USERNAME",
"value": "jreut"
}
] | src/Main.elm | jreut/elm-yinsh | 4 | module Main exposing (main)
import Board exposing (Board)
import Game
import Html exposing (Html)
import Html.Attributes exposing (href, style)
import Marker exposing (Marker)
import Player exposing (Player)
import Svg exposing (Svg)
import View.Board as BoardView
import View.Occupant as OccupantView
import View.Score as ScoreView
main : Program Never Model Msg
main =
Html.program
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
init : ( Model, Cmd Msg )
init =
{ game = Game.init } ! []
--- MODEL
type alias Model =
{ game : Game.State }
--- VIEW
view : Model -> Html Msg
view { game } =
let
config =
BoardView.config
{ toSvg = toSvg game
, toMsg = toMsg game
}
boardView =
BoardView.view config (game |> Game.board |> Board.positions)
in
Html.main_
[ style
[ ( "backgroundColor", "lightblue" )
, ( "display", "flex" )
, ( "flex-direction", "row" )
, ( "width", "100%" )
, ( "width", "100vw" )
, ( "height", "100%" )
, ( "height", "100vh" )
]
]
[ Html.map (always NoOp) header
, boardView
, messagesView game
]
toSvg : Game.State -> Board.Position Player Marker -> Svg Msg
toSvg game position =
let
shouldHighlight =
Game.movesForCoordinate position.coordinate (Game.availableMoves game)
|> not
<< List.isEmpty
in
OccupantView.view shouldHighlight position
toMsg : Game.State -> Board.Position Player Marker -> Msg
toMsg game { coordinate } =
Game.movesForCoordinate coordinate (Game.availableMoves game)
|> List.head
|> Maybe.map MakeMove
|> Maybe.withDefault NoOp
header : Html Never
header =
Html.header
[ style [ ( "flex-basis", "20%" ) ]
]
[ Html.h1 [] [ Html.text "Yinsh" ]
, Html.h2 [] [ Html.text "on the Web!" ]
, Html.p []
[ Html.a [ href "//github.com/jreut/elm-yinsh" ]
[ Html.text "source code"
]
]
]
messagesView : Game.State -> Html Msg
messagesView game =
Html.div
[ Html.Attributes.style
[ ( "flex-basis", "20%" ) ]
]
[ Html.p [] [ Html.text (Game.message game) ]
, Html.p [] [ Html.em [] [ Html.text "Click on any highlighted position to move." ] ]
, Html.p []
[ Html.a [ href "http://www.gipf.com/yinsh/" ] [ Html.text "Learn more" ]
, Html.text " about the game."
]
, ScoreView.view (Game.scores game)
]
--- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions =
always Sub.none
--- UPDATE
type Msg
= NoOp
| MakeMove Game.Move
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
NoOp ->
model ! []
MakeMove move ->
{ model | game = Game.update move model.game } ! []
| 16122 | module Main exposing (main)
import Board exposing (Board)
import Game
import Html exposing (Html)
import Html.Attributes exposing (href, style)
import Marker exposing (Marker)
import Player exposing (Player)
import Svg exposing (Svg)
import View.Board as BoardView
import View.Occupant as OccupantView
import View.Score as ScoreView
main : Program Never Model Msg
main =
Html.program
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
init : ( Model, Cmd Msg )
init =
{ game = Game.init } ! []
--- MODEL
type alias Model =
{ game : Game.State }
--- VIEW
view : Model -> Html Msg
view { game } =
let
config =
BoardView.config
{ toSvg = toSvg game
, toMsg = toMsg game
}
boardView =
BoardView.view config (game |> Game.board |> Board.positions)
in
Html.main_
[ style
[ ( "backgroundColor", "lightblue" )
, ( "display", "flex" )
, ( "flex-direction", "row" )
, ( "width", "100%" )
, ( "width", "100vw" )
, ( "height", "100%" )
, ( "height", "100vh" )
]
]
[ Html.map (always NoOp) header
, boardView
, messagesView game
]
toSvg : Game.State -> Board.Position Player Marker -> Svg Msg
toSvg game position =
let
shouldHighlight =
Game.movesForCoordinate position.coordinate (Game.availableMoves game)
|> not
<< List.isEmpty
in
OccupantView.view shouldHighlight position
toMsg : Game.State -> Board.Position Player Marker -> Msg
toMsg game { coordinate } =
Game.movesForCoordinate coordinate (Game.availableMoves game)
|> List.head
|> Maybe.map MakeMove
|> Maybe.withDefault NoOp
header : Html Never
header =
Html.header
[ style [ ( "flex-basis", "20%" ) ]
]
[ Html.h1 [] [ Html.text "<NAME>" ]
, Html.h2 [] [ Html.text "on the Web!" ]
, Html.p []
[ Html.a [ href "//github.com/jreut/elm-yinsh" ]
[ Html.text "source code"
]
]
]
messagesView : Game.State -> Html Msg
messagesView game =
Html.div
[ Html.Attributes.style
[ ( "flex-basis", "20%" ) ]
]
[ Html.p [] [ Html.text (Game.message game) ]
, Html.p [] [ Html.em [] [ Html.text "Click on any highlighted position to move." ] ]
, Html.p []
[ Html.a [ href "http://www.gipf.com/yinsh/" ] [ Html.text "Learn more" ]
, Html.text " about the game."
]
, ScoreView.view (Game.scores game)
]
--- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions =
always Sub.none
--- UPDATE
type Msg
= NoOp
| MakeMove Game.Move
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
NoOp ->
model ! []
MakeMove move ->
{ model | game = Game.update move model.game } ! []
| true | module Main exposing (main)
import Board exposing (Board)
import Game
import Html exposing (Html)
import Html.Attributes exposing (href, style)
import Marker exposing (Marker)
import Player exposing (Player)
import Svg exposing (Svg)
import View.Board as BoardView
import View.Occupant as OccupantView
import View.Score as ScoreView
main : Program Never Model Msg
main =
Html.program
{ init = init
, update = update
, subscriptions = subscriptions
, view = view
}
init : ( Model, Cmd Msg )
init =
{ game = Game.init } ! []
--- MODEL
type alias Model =
{ game : Game.State }
--- VIEW
view : Model -> Html Msg
view { game } =
let
config =
BoardView.config
{ toSvg = toSvg game
, toMsg = toMsg game
}
boardView =
BoardView.view config (game |> Game.board |> Board.positions)
in
Html.main_
[ style
[ ( "backgroundColor", "lightblue" )
, ( "display", "flex" )
, ( "flex-direction", "row" )
, ( "width", "100%" )
, ( "width", "100vw" )
, ( "height", "100%" )
, ( "height", "100vh" )
]
]
[ Html.map (always NoOp) header
, boardView
, messagesView game
]
toSvg : Game.State -> Board.Position Player Marker -> Svg Msg
toSvg game position =
let
shouldHighlight =
Game.movesForCoordinate position.coordinate (Game.availableMoves game)
|> not
<< List.isEmpty
in
OccupantView.view shouldHighlight position
toMsg : Game.State -> Board.Position Player Marker -> Msg
toMsg game { coordinate } =
Game.movesForCoordinate coordinate (Game.availableMoves game)
|> List.head
|> Maybe.map MakeMove
|> Maybe.withDefault NoOp
header : Html Never
header =
Html.header
[ style [ ( "flex-basis", "20%" ) ]
]
[ Html.h1 [] [ Html.text "PI:NAME:<NAME>END_PI" ]
, Html.h2 [] [ Html.text "on the Web!" ]
, Html.p []
[ Html.a [ href "//github.com/jreut/elm-yinsh" ]
[ Html.text "source code"
]
]
]
messagesView : Game.State -> Html Msg
messagesView game =
Html.div
[ Html.Attributes.style
[ ( "flex-basis", "20%" ) ]
]
[ Html.p [] [ Html.text (Game.message game) ]
, Html.p [] [ Html.em [] [ Html.text "Click on any highlighted position to move." ] ]
, Html.p []
[ Html.a [ href "http://www.gipf.com/yinsh/" ] [ Html.text "Learn more" ]
, Html.text " about the game."
]
, ScoreView.view (Game.scores game)
]
--- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions =
always Sub.none
--- UPDATE
type Msg
= NoOp
| MakeMove Game.Move
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
NoOp ->
model ! []
MakeMove move ->
{ model | game = Game.update move model.game } ! []
| elm |
[
{
"context": " [ span\n []\n [ text \"Made by Gabriel Grinberg, \" ]\n , em\n []\n [ te",
"end": 2306,
"score": 0.9998700619,
"start": 2290,
"tag": "NAME",
"value": "Gabriel Grinberg"
}
] | frontend/EditorWrapper.elm | GabiGrin/ElmFiddle.io | 18 | module EditorWrapper (..) where
import Editor
import Router
import Signal
import Effects exposing (Effects)
import Html exposing (..)
import Html.Attributes exposing (..)
import Task exposing (..)
import WebAPI.Location exposing (location)
import Maybe exposing (..)
import String
import Api
import Time
type State
= Loading
| Ready
| NotFound
type alias Model =
{ state : State
, editor : Editor.Model
}
type Action
= EditorAction Editor.Action
| LoadCode String
initModel : Model
initModel =
{ state = Loading
, editor = Editor.initModel
}
getPath : Task x String
getPath =
Task.map (\l -> l.pathname) location
getIdFromUrl : Task x (Maybe String)
getIdFromUrl =
let
getId =
(\p ->
if (String.length p == 1) then
Nothing
else
(Just (String.dropLeft 6 p))
)
in
getPath
|> Task.map getId
|> (flip Task.onError) (\v -> Task.succeed Nothing)
getCodeFromIdInUrl : Effects Action
getCodeFromIdInUrl =
getIdFromUrl
|> (flip Task.andThen)
(\maybeId ->
case maybeId of
Just id ->
Api.getCode id
`Task.onError` (\str -> Task.succeed str)
|> Task.map (\code -> LoadCode code)
Nothing ->
let
im =
Editor.initModel
in
Task.succeed im.code
|> Task.map LoadCode
)
|> Effects.task
init : ( Model, Effects Action )
init =
( initModel
-- , Effects.map EditorAction fx
--, getCode "cim7osup20000xa083lxem4pu"
, getCodeFromIdInUrl
)
update : Action -> Model -> ( Model, Effects Action )
update action model =
case action of
EditorAction act ->
let
( editor, fx ) =
Editor.update act model.editor
in
( { model | editor = editor }
, Effects.map EditorAction fx
)
LoadCode code ->
let
( editor, fx ) =
Editor.update (Editor.UpdateCode code) model.editor
in
( { model | editor = editor, state = Ready }
, Effects.map EditorAction fx
)
appFooter : Html
appFooter =
footer
[]
[ div
[]
[ span
[]
[ text "Made by Gabriel Grinberg, " ]
, em
[]
[ text "(almost) " ]
, span
[]
[ text "entirely in Elm!" ]
]
, img
[ src "assets/github.png" ]
[]
]
appHeader : Html
appHeader =
header
[]
[ span
[ id "logo" ]
[ span
[ class "elm" ]
[ text "Elm" ]
, span
[ class "fiddle" ]
[ text "Fiddle." ]
, span
[ class "i" ]
[ text "i" ]
, span
[ class "o" ]
[ text "o" ]
]
, div
[ id "snippet-container" ]
[ input
[ id
"snippet-name"
, value
""
, placeholder
"New Snippet"
, maxlength 20
]
[]
]
, div
[ id "dummy" ]
[]
]
view : Signal.Address Action -> Model -> Html
view address model =
case model.state of
Ready ->
div [ id "main" ] [ appHeader, Editor.view (Signal.forwardTo address EditorAction) model.editor, appFooter ]
_ ->
div [] [ text "Loading" ]
everyHalfSecond = Time.every (Time.millisecond * 500)
loadingTicker = Signal.map (\a -> EditorAction Editor.Tick) everyHalfSecond
inputs = [loadingTicker]
| 9342 | module EditorWrapper (..) where
import Editor
import Router
import Signal
import Effects exposing (Effects)
import Html exposing (..)
import Html.Attributes exposing (..)
import Task exposing (..)
import WebAPI.Location exposing (location)
import Maybe exposing (..)
import String
import Api
import Time
type State
= Loading
| Ready
| NotFound
type alias Model =
{ state : State
, editor : Editor.Model
}
type Action
= EditorAction Editor.Action
| LoadCode String
initModel : Model
initModel =
{ state = Loading
, editor = Editor.initModel
}
getPath : Task x String
getPath =
Task.map (\l -> l.pathname) location
getIdFromUrl : Task x (Maybe String)
getIdFromUrl =
let
getId =
(\p ->
if (String.length p == 1) then
Nothing
else
(Just (String.dropLeft 6 p))
)
in
getPath
|> Task.map getId
|> (flip Task.onError) (\v -> Task.succeed Nothing)
getCodeFromIdInUrl : Effects Action
getCodeFromIdInUrl =
getIdFromUrl
|> (flip Task.andThen)
(\maybeId ->
case maybeId of
Just id ->
Api.getCode id
`Task.onError` (\str -> Task.succeed str)
|> Task.map (\code -> LoadCode code)
Nothing ->
let
im =
Editor.initModel
in
Task.succeed im.code
|> Task.map LoadCode
)
|> Effects.task
init : ( Model, Effects Action )
init =
( initModel
-- , Effects.map EditorAction fx
--, getCode "cim7osup20000xa083lxem4pu"
, getCodeFromIdInUrl
)
update : Action -> Model -> ( Model, Effects Action )
update action model =
case action of
EditorAction act ->
let
( editor, fx ) =
Editor.update act model.editor
in
( { model | editor = editor }
, Effects.map EditorAction fx
)
LoadCode code ->
let
( editor, fx ) =
Editor.update (Editor.UpdateCode code) model.editor
in
( { model | editor = editor, state = Ready }
, Effects.map EditorAction fx
)
appFooter : Html
appFooter =
footer
[]
[ div
[]
[ span
[]
[ text "Made by <NAME>, " ]
, em
[]
[ text "(almost) " ]
, span
[]
[ text "entirely in Elm!" ]
]
, img
[ src "assets/github.png" ]
[]
]
appHeader : Html
appHeader =
header
[]
[ span
[ id "logo" ]
[ span
[ class "elm" ]
[ text "Elm" ]
, span
[ class "fiddle" ]
[ text "Fiddle." ]
, span
[ class "i" ]
[ text "i" ]
, span
[ class "o" ]
[ text "o" ]
]
, div
[ id "snippet-container" ]
[ input
[ id
"snippet-name"
, value
""
, placeholder
"New Snippet"
, maxlength 20
]
[]
]
, div
[ id "dummy" ]
[]
]
view : Signal.Address Action -> Model -> Html
view address model =
case model.state of
Ready ->
div [ id "main" ] [ appHeader, Editor.view (Signal.forwardTo address EditorAction) model.editor, appFooter ]
_ ->
div [] [ text "Loading" ]
everyHalfSecond = Time.every (Time.millisecond * 500)
loadingTicker = Signal.map (\a -> EditorAction Editor.Tick) everyHalfSecond
inputs = [loadingTicker]
| true | module EditorWrapper (..) where
import Editor
import Router
import Signal
import Effects exposing (Effects)
import Html exposing (..)
import Html.Attributes exposing (..)
import Task exposing (..)
import WebAPI.Location exposing (location)
import Maybe exposing (..)
import String
import Api
import Time
type State
= Loading
| Ready
| NotFound
type alias Model =
{ state : State
, editor : Editor.Model
}
type Action
= EditorAction Editor.Action
| LoadCode String
initModel : Model
initModel =
{ state = Loading
, editor = Editor.initModel
}
getPath : Task x String
getPath =
Task.map (\l -> l.pathname) location
getIdFromUrl : Task x (Maybe String)
getIdFromUrl =
let
getId =
(\p ->
if (String.length p == 1) then
Nothing
else
(Just (String.dropLeft 6 p))
)
in
getPath
|> Task.map getId
|> (flip Task.onError) (\v -> Task.succeed Nothing)
getCodeFromIdInUrl : Effects Action
getCodeFromIdInUrl =
getIdFromUrl
|> (flip Task.andThen)
(\maybeId ->
case maybeId of
Just id ->
Api.getCode id
`Task.onError` (\str -> Task.succeed str)
|> Task.map (\code -> LoadCode code)
Nothing ->
let
im =
Editor.initModel
in
Task.succeed im.code
|> Task.map LoadCode
)
|> Effects.task
init : ( Model, Effects Action )
init =
( initModel
-- , Effects.map EditorAction fx
--, getCode "cim7osup20000xa083lxem4pu"
, getCodeFromIdInUrl
)
update : Action -> Model -> ( Model, Effects Action )
update action model =
case action of
EditorAction act ->
let
( editor, fx ) =
Editor.update act model.editor
in
( { model | editor = editor }
, Effects.map EditorAction fx
)
LoadCode code ->
let
( editor, fx ) =
Editor.update (Editor.UpdateCode code) model.editor
in
( { model | editor = editor, state = Ready }
, Effects.map EditorAction fx
)
appFooter : Html
appFooter =
footer
[]
[ div
[]
[ span
[]
[ text "Made by PI:NAME:<NAME>END_PI, " ]
, em
[]
[ text "(almost) " ]
, span
[]
[ text "entirely in Elm!" ]
]
, img
[ src "assets/github.png" ]
[]
]
appHeader : Html
appHeader =
header
[]
[ span
[ id "logo" ]
[ span
[ class "elm" ]
[ text "Elm" ]
, span
[ class "fiddle" ]
[ text "Fiddle." ]
, span
[ class "i" ]
[ text "i" ]
, span
[ class "o" ]
[ text "o" ]
]
, div
[ id "snippet-container" ]
[ input
[ id
"snippet-name"
, value
""
, placeholder
"New Snippet"
, maxlength 20
]
[]
]
, div
[ id "dummy" ]
[]
]
view : Signal.Address Action -> Model -> Html
view address model =
case model.state of
Ready ->
div [ id "main" ] [ appHeader, Editor.view (Signal.forwardTo address EditorAction) model.editor, appFooter ]
_ ->
div [] [ text "Loading" ]
everyHalfSecond = Time.every (Time.millisecond * 500)
loadingTicker = Signal.map (\a -> EditorAction Editor.Tick) everyHalfSecond
inputs = [loadingTicker]
| elm |
[
{
"context": " \"attributes\": {\n \"firstname\": \"John\",\n \"lastname\": \"Doe\",\n ",
"end": 1557,
"score": 0.9997053742,
"start": 1553,
"tag": "NAME",
"value": "John"
},
{
"context": "\"firstname\": \"John\",\n \"lastname\": \"Doe\",\n \"gender\": \"male\"\n },",
"end": 1592,
"score": 0.9996110201,
"start": 1589,
"tag": "NAME",
"value": "Doe"
},
{
"context": "thAttributes\n [ ( \"firstname\", string \"John\" )\n , ( \"lastname\", string \"Doe\" )\n ",
"end": 2092,
"score": 0.9998102784,
"start": 2088,
"tag": "NAME",
"value": "John"
},
{
"context": "ring \"John\" )\n , ( \"lastname\", string \"Doe\" )\n , ( \"gender\", string \"male\" )\n ",
"end": 2135,
"score": 0.9997782707,
"start": 2132,
"tag": "NAME",
"value": "Doe"
},
{
"context": "tributes\n [ ( \"firstname\", string \"John\" )\n , ( \"lastname\", string \"Doe\" )",
"end": 8843,
"score": 0.9988124371,
"start": 8839,
"tag": "NAME",
"value": "John"
},
{
"context": " \"John\" )\n , ( \"lastname\", string \"Doe\" )\n , ( \"gender\", string \"male\" )\n",
"end": 8890,
"score": 0.9959017038,
"start": 8887,
"tag": "NAME",
"value": "Doe"
}
] | src/JsonApi/Resource.elm | FabienHenon/jsonapi | 9 | module JsonApi.Resource exposing
( Resource, OneOrManyRelationships, OneOrMoreRelationshipData(..), RelationshipData, RelationshipDesc
, build, fromResource
, id, links, resType, getRelationshipsDesc
, withId, withLinks, withAttributes, withRelationship
, relationship, relationships
)
{-| JsonApi.Resource exposes the `Resource` type and functions to get and set information
for your resources.
# Type
@docs Resource, OneOrManyRelationships, OneOrMoreRelationshipData, RelationshipData, RelationshipDesc
# New resource
@docs build, fromResource
# Getter functions
@docs id, links, resType, getRelationshipsDesc
# Setter functions
@docs withId, withLinks, withAttributes, withRelationship
# Relationships
@docs relationship, relationships
-}
import Dict exposing (Dict)
import Json.Encode exposing (Value, object)
import JsonApi.Internal.ResourceInfo as Internal
{-| The `Resource` represents a resource. It is passed to your resource decoders, but you can also use it to encode resources to json api, via a `Document`.
It contains useful information for decoding and encoding your resource: resource `id`, `links`, `attributes`, `relationships`, ...
\_Example of json api <resource:_>
```json
{
"data": [
{
"type": "users",
"id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad",
"links": {
"self": "http://link-to-user",
"profile": "http://link-to-user-profile"
},
"attributes": {
"firstname": "John",
"lastname": "Doe",
"gender": "male"
},
"relationships": {}
}
]
}
```
And how to build it with the `JsonApi.Resource` module:
build "users"
|> withId "13608770-76dd-47e5-a1c4-4d0d9c2483ad"
|> withLinks
(Dict.fromList
[ ( "self", "http://link-to-user" )
, ( "profile", "http://link-to-user-profile" )
]
)
|> withAttributes
[ ( "firstname", string "John" )
, ( "lastname", string "Doe" )
, ( "gender", string "male" )
]
-}
type alias Resource =
Internal.ResourceInfo
{-| This type is used to represent either one or many relationships in your `Resource` object.
See `withRelationship` function for more information
-}
type alias OneOrManyRelationships =
Internal.OneOrManyRelationships
{-| Relationship's data object. It's a variant type because in a relationship
the `data` field can either: be null, have one relationship, have many relationships.
_See `getRelationshipsDesc` for more information_
-}
type OneOrMoreRelationshipData
= NoRelationship
| One RelationshipData
| Many (List RelationshipData)
{-| Description of the `data` object in a `relationship` object.
Contains the `id` of the relationship and it's `type`
_See `getRelationshipsDesc` for more information_
-}
type alias RelationshipData =
{ id : String
, type_ : String
}
{-| The description of a relationship in the `relationships` field of the jsonapi object.
For instance (in jsonapi):
"relationships": {
"creator": {
"data": {
"type": "creators",
"id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad"
},
"links": {
"related": "http://link-to-creator/1"
}
}
}
This type contains the links defined in the relationship and the `data` object of
the relationship
_See `getRelationshipsDesc` for more information_
-}
type alias RelationshipDesc =
{ data : OneOrMoreRelationshipData
, links : Dict String String
}
{-| Returns the `id` of your resource.
From the json example above, `id` will return `13608770-76dd-47e5-a1c4-4d0d9c2483ad`
-}
id : Resource -> String
id (Internal.ResourceInfo res) =
res.id |> Maybe.withDefault ""
{-| Returns the `type` of your resource.
From the json example above, `type_` will return `users`
-}
resType : Resource -> String
resType (Internal.ResourceInfo { type_ }) =
type_
{-| Returns the `links` of your resource.
From the json example above, `links` will return a `Dict` with this value:
[ ( "self", "http://link-to-user" )
, ( "profile", "http://link-to-user-profile" )
]
-}
links : Resource -> Dict String String
links (Internal.ResourceInfo res) =
res.links
{-| Returns the relationships description of your resource.
**This is not a way to decode a relationship, only a quick way to get the relationship ids and types**
type alias Post =
{ id : String
, links : Dict String String
, title : String
, content : String
, relationships : Dict String JsonApi.Resource.RelationshipDesc
}
decoder : Resource -> Decoder Post
decoder resourceInfo =
map5 Post
(succeed (JsonApi.Resource.id resourceInfo))
(succeed (JsonApi.Resource.links resourceInfo))
(field "title" string)
(field "content" string)
(succeed (JsonApi.Resource.getRelationshipsDesc resourceInfo))
Say the relationships for this post are:
"relationships": {
"creator": {
"data": {
"type": "creators",
"id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad"
},
"links": {
"related": "http://link-to-creator/1"
}
},
"comments": {
"links": {},
"data": [
{
"type": "comment",
"id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab"
},
{
"type": "comment",
"id": "cb0759b0-03ab-4291-b067-84a9017fea6f"
}
]
}
}
Then you will get these information:
Dict.get "creator" post.relationships
Just
{ links = [ ( "related", "http://link-to-creator/1" ) ]
, data =
JsonApi.Resource.One
{ id = "22208770-76dd-47e5-a1c4-4d0d9c2483ad"
, type_ = "creators"
}
}
Dict.get "comments" post.relationships
Just
{ links = []
, data =
JsonApi.Resource.Many
[ { id = "22208770-76dd-47e5-a1c4-4d0d9c2483ab"
, type_ = "comment"
}
, { id = "cb0759b0-03ab-4291-b067-84a9017fea6f"
, type_ = "comment"
}
]
}
-}
getRelationshipsDesc : Resource -> Dict String RelationshipDesc
getRelationshipsDesc (Internal.ResourceInfo res) =
res.relationships
|> Dict.map
(\k v ->
{ links = v.links
, data =
case v.data of
Internal.NoRelationship ->
NoRelationship
Internal.One e ->
One e
Internal.Many e ->
Many e
}
)
{-| Builds a new `Resource` with the specified type name
You can build your resources like this:
myResource : Post -> Resource
myResource post =
build "posts"
|> withId "post-1"
|> withLinks (Dict.fromList [ ( "self", "http://url-to-post/1" ) ])
-}
build : String -> Resource
build type_ =
Internal.ResourceInfo (Internal.build type_)
{-| Builds a new `Resource` from the specified `Resource` and with the specified type name
You can build your resources like this:
myResource : Resource -> Resource
myResource resource =
fromResource "posts" resource
-}
fromResource : String -> Resource -> Resource
fromResource type_ (Internal.ResourceInfo info) =
Internal.ResourceInfo { info | type_ = type_ }
{-| Sets the id of the `Resource` object
myResource : Post -> Resource
myResource post =
build "posts"
|> withId "post-1"
-}
withId : String -> Resource -> Resource
withId id_ (Internal.ResourceInfo info) =
Internal.ResourceInfo { info | id = Just id_ }
{-| Sets the links of the `Resource` object
myResource : Post -> Resource
myResource post =
build "posts"
|> withLinks (Dict.fromList [ ( "self", "http://url-to-post/1" ) ])
-}
withLinks : Dict String String -> Resource -> Resource
withLinks links_ (Internal.ResourceInfo info) =
Internal.ResourceInfo { info | links = links_ }
{-| Sets the attributes of the `Resource` object.
This is the payload of your resource.
myResource : Post -> Resource
myResource post =
build "posts"
|> withAttributes
[ ( "firstname", string "John" )
, ( "lastname", string "Doe" )
, ( "gender", string "male" )
]
-}
withAttributes : List ( String, Value ) -> Resource -> Resource
withAttributes attrs (Internal.ResourceInfo info) =
Internal.ResourceInfo { info | attributes = object attrs }
{-| Adds a relationship in the `Resource` object.
You have to pass it the name of the relationship and a description of the relationship resource (See `relationship` and `relationships`)
myResource : Post -> Resource
myResource post =
build "posts"
|> withRelationship "creators" (relationship creator.id (creatorResource creator))
-}
withRelationship : String -> OneOrManyRelationships -> Resource -> Resource
withRelationship type_ (Internal.OneOrManyRelationships oneOrMoreRelationships) (Internal.ResourceInfo info) =
Internal.ResourceInfo (Internal.addRelationship type_ oneOrMoreRelationships info)
{-| Defines a relationship that can then be added to its parent `Resource`.
It takes the `id` of the resource and the resource.
creatorResource : Creator -> Resource
creatorResource creator =
build "creator"
|> withAttributes [ ( "firstname", string creator.firstname ) ]
myResource : Post -> Resource
myResource post =
build "posts"
|> withRelationship "creators" (relationship creator.id (creatorResource creator))
-}
relationship : String -> Resource -> OneOrManyRelationships
relationship id_ =
withId id_ >> Internal.OneRelationship >> Internal.OneOrManyRelationships
{-| Defines a list of relationships that can then be added to a parent `Resource`.
It takes a `List` of `Tuple`s with the `id` of the resource and the resource.
commentResource : Comment -> Resource
commentResource comment =
build "comment"
|> withAttributes [ ( "content", string comment.content ) ]
myResource : Post -> Resource
myResource post =
build "posts"
|> withRelationship "comments" (relationships (List.map (\comment -> ( "comment", commentResource comment )) comments))
-}
relationships : List ( String, Resource ) -> OneOrManyRelationships
relationships =
List.map (\( id_, info ) -> info |> withId id_) >> Internal.ManyRelationships >> Internal.OneOrManyRelationships
| 28409 | module JsonApi.Resource exposing
( Resource, OneOrManyRelationships, OneOrMoreRelationshipData(..), RelationshipData, RelationshipDesc
, build, fromResource
, id, links, resType, getRelationshipsDesc
, withId, withLinks, withAttributes, withRelationship
, relationship, relationships
)
{-| JsonApi.Resource exposes the `Resource` type and functions to get and set information
for your resources.
# Type
@docs Resource, OneOrManyRelationships, OneOrMoreRelationshipData, RelationshipData, RelationshipDesc
# New resource
@docs build, fromResource
# Getter functions
@docs id, links, resType, getRelationshipsDesc
# Setter functions
@docs withId, withLinks, withAttributes, withRelationship
# Relationships
@docs relationship, relationships
-}
import Dict exposing (Dict)
import Json.Encode exposing (Value, object)
import JsonApi.Internal.ResourceInfo as Internal
{-| The `Resource` represents a resource. It is passed to your resource decoders, but you can also use it to encode resources to json api, via a `Document`.
It contains useful information for decoding and encoding your resource: resource `id`, `links`, `attributes`, `relationships`, ...
\_Example of json api <resource:_>
```json
{
"data": [
{
"type": "users",
"id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad",
"links": {
"self": "http://link-to-user",
"profile": "http://link-to-user-profile"
},
"attributes": {
"firstname": "<NAME>",
"lastname": "<NAME>",
"gender": "male"
},
"relationships": {}
}
]
}
```
And how to build it with the `JsonApi.Resource` module:
build "users"
|> withId "13608770-76dd-47e5-a1c4-4d0d9c2483ad"
|> withLinks
(Dict.fromList
[ ( "self", "http://link-to-user" )
, ( "profile", "http://link-to-user-profile" )
]
)
|> withAttributes
[ ( "firstname", string "<NAME>" )
, ( "lastname", string "<NAME>" )
, ( "gender", string "male" )
]
-}
type alias Resource =
Internal.ResourceInfo
{-| This type is used to represent either one or many relationships in your `Resource` object.
See `withRelationship` function for more information
-}
type alias OneOrManyRelationships =
Internal.OneOrManyRelationships
{-| Relationship's data object. It's a variant type because in a relationship
the `data` field can either: be null, have one relationship, have many relationships.
_See `getRelationshipsDesc` for more information_
-}
type OneOrMoreRelationshipData
= NoRelationship
| One RelationshipData
| Many (List RelationshipData)
{-| Description of the `data` object in a `relationship` object.
Contains the `id` of the relationship and it's `type`
_See `getRelationshipsDesc` for more information_
-}
type alias RelationshipData =
{ id : String
, type_ : String
}
{-| The description of a relationship in the `relationships` field of the jsonapi object.
For instance (in jsonapi):
"relationships": {
"creator": {
"data": {
"type": "creators",
"id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad"
},
"links": {
"related": "http://link-to-creator/1"
}
}
}
This type contains the links defined in the relationship and the `data` object of
the relationship
_See `getRelationshipsDesc` for more information_
-}
type alias RelationshipDesc =
{ data : OneOrMoreRelationshipData
, links : Dict String String
}
{-| Returns the `id` of your resource.
From the json example above, `id` will return `13608770-76dd-47e5-a1c4-4d0d9c2483ad`
-}
id : Resource -> String
id (Internal.ResourceInfo res) =
res.id |> Maybe.withDefault ""
{-| Returns the `type` of your resource.
From the json example above, `type_` will return `users`
-}
resType : Resource -> String
resType (Internal.ResourceInfo { type_ }) =
type_
{-| Returns the `links` of your resource.
From the json example above, `links` will return a `Dict` with this value:
[ ( "self", "http://link-to-user" )
, ( "profile", "http://link-to-user-profile" )
]
-}
links : Resource -> Dict String String
links (Internal.ResourceInfo res) =
res.links
{-| Returns the relationships description of your resource.
**This is not a way to decode a relationship, only a quick way to get the relationship ids and types**
type alias Post =
{ id : String
, links : Dict String String
, title : String
, content : String
, relationships : Dict String JsonApi.Resource.RelationshipDesc
}
decoder : Resource -> Decoder Post
decoder resourceInfo =
map5 Post
(succeed (JsonApi.Resource.id resourceInfo))
(succeed (JsonApi.Resource.links resourceInfo))
(field "title" string)
(field "content" string)
(succeed (JsonApi.Resource.getRelationshipsDesc resourceInfo))
Say the relationships for this post are:
"relationships": {
"creator": {
"data": {
"type": "creators",
"id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad"
},
"links": {
"related": "http://link-to-creator/1"
}
},
"comments": {
"links": {},
"data": [
{
"type": "comment",
"id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab"
},
{
"type": "comment",
"id": "cb0759b0-03ab-4291-b067-84a9017fea6f"
}
]
}
}
Then you will get these information:
Dict.get "creator" post.relationships
Just
{ links = [ ( "related", "http://link-to-creator/1" ) ]
, data =
JsonApi.Resource.One
{ id = "22208770-76dd-47e5-a1c4-4d0d9c2483ad"
, type_ = "creators"
}
}
Dict.get "comments" post.relationships
Just
{ links = []
, data =
JsonApi.Resource.Many
[ { id = "22208770-76dd-47e5-a1c4-4d0d9c2483ab"
, type_ = "comment"
}
, { id = "cb0759b0-03ab-4291-b067-84a9017fea6f"
, type_ = "comment"
}
]
}
-}
getRelationshipsDesc : Resource -> Dict String RelationshipDesc
getRelationshipsDesc (Internal.ResourceInfo res) =
res.relationships
|> Dict.map
(\k v ->
{ links = v.links
, data =
case v.data of
Internal.NoRelationship ->
NoRelationship
Internal.One e ->
One e
Internal.Many e ->
Many e
}
)
{-| Builds a new `Resource` with the specified type name
You can build your resources like this:
myResource : Post -> Resource
myResource post =
build "posts"
|> withId "post-1"
|> withLinks (Dict.fromList [ ( "self", "http://url-to-post/1" ) ])
-}
build : String -> Resource
build type_ =
Internal.ResourceInfo (Internal.build type_)
{-| Builds a new `Resource` from the specified `Resource` and with the specified type name
You can build your resources like this:
myResource : Resource -> Resource
myResource resource =
fromResource "posts" resource
-}
fromResource : String -> Resource -> Resource
fromResource type_ (Internal.ResourceInfo info) =
Internal.ResourceInfo { info | type_ = type_ }
{-| Sets the id of the `Resource` object
myResource : Post -> Resource
myResource post =
build "posts"
|> withId "post-1"
-}
withId : String -> Resource -> Resource
withId id_ (Internal.ResourceInfo info) =
Internal.ResourceInfo { info | id = Just id_ }
{-| Sets the links of the `Resource` object
myResource : Post -> Resource
myResource post =
build "posts"
|> withLinks (Dict.fromList [ ( "self", "http://url-to-post/1" ) ])
-}
withLinks : Dict String String -> Resource -> Resource
withLinks links_ (Internal.ResourceInfo info) =
Internal.ResourceInfo { info | links = links_ }
{-| Sets the attributes of the `Resource` object.
This is the payload of your resource.
myResource : Post -> Resource
myResource post =
build "posts"
|> withAttributes
[ ( "firstname", string "<NAME>" )
, ( "lastname", string "<NAME>" )
, ( "gender", string "male" )
]
-}
withAttributes : List ( String, Value ) -> Resource -> Resource
withAttributes attrs (Internal.ResourceInfo info) =
Internal.ResourceInfo { info | attributes = object attrs }
{-| Adds a relationship in the `Resource` object.
You have to pass it the name of the relationship and a description of the relationship resource (See `relationship` and `relationships`)
myResource : Post -> Resource
myResource post =
build "posts"
|> withRelationship "creators" (relationship creator.id (creatorResource creator))
-}
withRelationship : String -> OneOrManyRelationships -> Resource -> Resource
withRelationship type_ (Internal.OneOrManyRelationships oneOrMoreRelationships) (Internal.ResourceInfo info) =
Internal.ResourceInfo (Internal.addRelationship type_ oneOrMoreRelationships info)
{-| Defines a relationship that can then be added to its parent `Resource`.
It takes the `id` of the resource and the resource.
creatorResource : Creator -> Resource
creatorResource creator =
build "creator"
|> withAttributes [ ( "firstname", string creator.firstname ) ]
myResource : Post -> Resource
myResource post =
build "posts"
|> withRelationship "creators" (relationship creator.id (creatorResource creator))
-}
relationship : String -> Resource -> OneOrManyRelationships
relationship id_ =
withId id_ >> Internal.OneRelationship >> Internal.OneOrManyRelationships
{-| Defines a list of relationships that can then be added to a parent `Resource`.
It takes a `List` of `Tuple`s with the `id` of the resource and the resource.
commentResource : Comment -> Resource
commentResource comment =
build "comment"
|> withAttributes [ ( "content", string comment.content ) ]
myResource : Post -> Resource
myResource post =
build "posts"
|> withRelationship "comments" (relationships (List.map (\comment -> ( "comment", commentResource comment )) comments))
-}
relationships : List ( String, Resource ) -> OneOrManyRelationships
relationships =
List.map (\( id_, info ) -> info |> withId id_) >> Internal.ManyRelationships >> Internal.OneOrManyRelationships
| true | module JsonApi.Resource exposing
( Resource, OneOrManyRelationships, OneOrMoreRelationshipData(..), RelationshipData, RelationshipDesc
, build, fromResource
, id, links, resType, getRelationshipsDesc
, withId, withLinks, withAttributes, withRelationship
, relationship, relationships
)
{-| JsonApi.Resource exposes the `Resource` type and functions to get and set information
for your resources.
# Type
@docs Resource, OneOrManyRelationships, OneOrMoreRelationshipData, RelationshipData, RelationshipDesc
# New resource
@docs build, fromResource
# Getter functions
@docs id, links, resType, getRelationshipsDesc
# Setter functions
@docs withId, withLinks, withAttributes, withRelationship
# Relationships
@docs relationship, relationships
-}
import Dict exposing (Dict)
import Json.Encode exposing (Value, object)
import JsonApi.Internal.ResourceInfo as Internal
{-| The `Resource` represents a resource. It is passed to your resource decoders, but you can also use it to encode resources to json api, via a `Document`.
It contains useful information for decoding and encoding your resource: resource `id`, `links`, `attributes`, `relationships`, ...
\_Example of json api <resource:_>
```json
{
"data": [
{
"type": "users",
"id": "13608770-76dd-47e5-a1c4-4d0d9c2483ad",
"links": {
"self": "http://link-to-user",
"profile": "http://link-to-user-profile"
},
"attributes": {
"firstname": "PI:NAME:<NAME>END_PI",
"lastname": "PI:NAME:<NAME>END_PI",
"gender": "male"
},
"relationships": {}
}
]
}
```
And how to build it with the `JsonApi.Resource` module:
build "users"
|> withId "13608770-76dd-47e5-a1c4-4d0d9c2483ad"
|> withLinks
(Dict.fromList
[ ( "self", "http://link-to-user" )
, ( "profile", "http://link-to-user-profile" )
]
)
|> withAttributes
[ ( "firstname", string "PI:NAME:<NAME>END_PI" )
, ( "lastname", string "PI:NAME:<NAME>END_PI" )
, ( "gender", string "male" )
]
-}
type alias Resource =
Internal.ResourceInfo
{-| This type is used to represent either one or many relationships in your `Resource` object.
See `withRelationship` function for more information
-}
type alias OneOrManyRelationships =
Internal.OneOrManyRelationships
{-| Relationship's data object. It's a variant type because in a relationship
the `data` field can either: be null, have one relationship, have many relationships.
_See `getRelationshipsDesc` for more information_
-}
type OneOrMoreRelationshipData
= NoRelationship
| One RelationshipData
| Many (List RelationshipData)
{-| Description of the `data` object in a `relationship` object.
Contains the `id` of the relationship and it's `type`
_See `getRelationshipsDesc` for more information_
-}
type alias RelationshipData =
{ id : String
, type_ : String
}
{-| The description of a relationship in the `relationships` field of the jsonapi object.
For instance (in jsonapi):
"relationships": {
"creator": {
"data": {
"type": "creators",
"id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad"
},
"links": {
"related": "http://link-to-creator/1"
}
}
}
This type contains the links defined in the relationship and the `data` object of
the relationship
_See `getRelationshipsDesc` for more information_
-}
type alias RelationshipDesc =
{ data : OneOrMoreRelationshipData
, links : Dict String String
}
{-| Returns the `id` of your resource.
From the json example above, `id` will return `13608770-76dd-47e5-a1c4-4d0d9c2483ad`
-}
id : Resource -> String
id (Internal.ResourceInfo res) =
res.id |> Maybe.withDefault ""
{-| Returns the `type` of your resource.
From the json example above, `type_` will return `users`
-}
resType : Resource -> String
resType (Internal.ResourceInfo { type_ }) =
type_
{-| Returns the `links` of your resource.
From the json example above, `links` will return a `Dict` with this value:
[ ( "self", "http://link-to-user" )
, ( "profile", "http://link-to-user-profile" )
]
-}
links : Resource -> Dict String String
links (Internal.ResourceInfo res) =
res.links
{-| Returns the relationships description of your resource.
**This is not a way to decode a relationship, only a quick way to get the relationship ids and types**
type alias Post =
{ id : String
, links : Dict String String
, title : String
, content : String
, relationships : Dict String JsonApi.Resource.RelationshipDesc
}
decoder : Resource -> Decoder Post
decoder resourceInfo =
map5 Post
(succeed (JsonApi.Resource.id resourceInfo))
(succeed (JsonApi.Resource.links resourceInfo))
(field "title" string)
(field "content" string)
(succeed (JsonApi.Resource.getRelationshipsDesc resourceInfo))
Say the relationships for this post are:
"relationships": {
"creator": {
"data": {
"type": "creators",
"id": "22208770-76dd-47e5-a1c4-4d0d9c2483ad"
},
"links": {
"related": "http://link-to-creator/1"
}
},
"comments": {
"links": {},
"data": [
{
"type": "comment",
"id": "22208770-76dd-47e5-a1c4-4d0d9c2483ab"
},
{
"type": "comment",
"id": "cb0759b0-03ab-4291-b067-84a9017fea6f"
}
]
}
}
Then you will get these information:
Dict.get "creator" post.relationships
Just
{ links = [ ( "related", "http://link-to-creator/1" ) ]
, data =
JsonApi.Resource.One
{ id = "22208770-76dd-47e5-a1c4-4d0d9c2483ad"
, type_ = "creators"
}
}
Dict.get "comments" post.relationships
Just
{ links = []
, data =
JsonApi.Resource.Many
[ { id = "22208770-76dd-47e5-a1c4-4d0d9c2483ab"
, type_ = "comment"
}
, { id = "cb0759b0-03ab-4291-b067-84a9017fea6f"
, type_ = "comment"
}
]
}
-}
getRelationshipsDesc : Resource -> Dict String RelationshipDesc
getRelationshipsDesc (Internal.ResourceInfo res) =
res.relationships
|> Dict.map
(\k v ->
{ links = v.links
, data =
case v.data of
Internal.NoRelationship ->
NoRelationship
Internal.One e ->
One e
Internal.Many e ->
Many e
}
)
{-| Builds a new `Resource` with the specified type name
You can build your resources like this:
myResource : Post -> Resource
myResource post =
build "posts"
|> withId "post-1"
|> withLinks (Dict.fromList [ ( "self", "http://url-to-post/1" ) ])
-}
build : String -> Resource
build type_ =
Internal.ResourceInfo (Internal.build type_)
{-| Builds a new `Resource` from the specified `Resource` and with the specified type name
You can build your resources like this:
myResource : Resource -> Resource
myResource resource =
fromResource "posts" resource
-}
fromResource : String -> Resource -> Resource
fromResource type_ (Internal.ResourceInfo info) =
Internal.ResourceInfo { info | type_ = type_ }
{-| Sets the id of the `Resource` object
myResource : Post -> Resource
myResource post =
build "posts"
|> withId "post-1"
-}
withId : String -> Resource -> Resource
withId id_ (Internal.ResourceInfo info) =
Internal.ResourceInfo { info | id = Just id_ }
{-| Sets the links of the `Resource` object
myResource : Post -> Resource
myResource post =
build "posts"
|> withLinks (Dict.fromList [ ( "self", "http://url-to-post/1" ) ])
-}
withLinks : Dict String String -> Resource -> Resource
withLinks links_ (Internal.ResourceInfo info) =
Internal.ResourceInfo { info | links = links_ }
{-| Sets the attributes of the `Resource` object.
This is the payload of your resource.
myResource : Post -> Resource
myResource post =
build "posts"
|> withAttributes
[ ( "firstname", string "PI:NAME:<NAME>END_PI" )
, ( "lastname", string "PI:NAME:<NAME>END_PI" )
, ( "gender", string "male" )
]
-}
withAttributes : List ( String, Value ) -> Resource -> Resource
withAttributes attrs (Internal.ResourceInfo info) =
Internal.ResourceInfo { info | attributes = object attrs }
{-| Adds a relationship in the `Resource` object.
You have to pass it the name of the relationship and a description of the relationship resource (See `relationship` and `relationships`)
myResource : Post -> Resource
myResource post =
build "posts"
|> withRelationship "creators" (relationship creator.id (creatorResource creator))
-}
withRelationship : String -> OneOrManyRelationships -> Resource -> Resource
withRelationship type_ (Internal.OneOrManyRelationships oneOrMoreRelationships) (Internal.ResourceInfo info) =
Internal.ResourceInfo (Internal.addRelationship type_ oneOrMoreRelationships info)
{-| Defines a relationship that can then be added to its parent `Resource`.
It takes the `id` of the resource and the resource.
creatorResource : Creator -> Resource
creatorResource creator =
build "creator"
|> withAttributes [ ( "firstname", string creator.firstname ) ]
myResource : Post -> Resource
myResource post =
build "posts"
|> withRelationship "creators" (relationship creator.id (creatorResource creator))
-}
relationship : String -> Resource -> OneOrManyRelationships
relationship id_ =
withId id_ >> Internal.OneRelationship >> Internal.OneOrManyRelationships
{-| Defines a list of relationships that can then be added to a parent `Resource`.
It takes a `List` of `Tuple`s with the `id` of the resource and the resource.
commentResource : Comment -> Resource
commentResource comment =
build "comment"
|> withAttributes [ ( "content", string comment.content ) ]
myResource : Post -> Resource
myResource post =
build "posts"
|> withRelationship "comments" (relationships (List.map (\comment -> ( "comment", commentResource comment )) comments))
-}
relationships : List ( String, Resource ) -> OneOrManyRelationships
relationships =
List.map (\( id_, info ) -> info |> withId id_) >> Internal.ManyRelationships >> Internal.OneOrManyRelationships
| elm |
[
{
"context": " let\n testCase =\n \"@forename is Maksym and @surname is either Ivanov or Petrov\"\n in\n ",
"end": 284,
"score": 0.9997041821,
"start": 278,
"tag": "NAME",
"value": "Maksym"
},
{
"context": " \"@forename is Maksym and @surname is either Ivanov or Petrov\"\n in\n describe \"Tokenizer.run\"\n ",
"end": 314,
"score": 0.9982976913,
"start": 308,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "orename is Maksym and @surname is either Ivanov or Petrov\"\n in\n describe \"Tokenizer.run\"\n [ de",
"end": 324,
"score": 0.9993947744,
"start": 318,
"tag": "NAME",
"value": "Petrov"
},
{
"context": "e = WordTerm\n , value = \"Maksym\"\n , index = 13\n ",
"end": 1354,
"score": 0.9958011508,
"start": 1348,
"tag": "NAME",
"value": "Maksym"
},
{
"context": "e = WordTerm\n , value = \"Ivanov\"\n , index = 43\n ",
"end": 2602,
"score": 0.999209404,
"start": 2596,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "e = WordTerm\n , value = \"Petrov\"\n , index = 53\n ",
"end": 3222,
"score": 0.9991548657,
"start": 3216,
"tag": "NAME",
"value": "Petrov"
}
] | tests/tokenizer/Tokenizer_1_4_3.elm | maximoleinyk/atBox | 4 | module Tokenizer_1_4_3 exposing (..)
import Expect
import GlobalTypes exposing (TokenState(..))
import MockModel exposing (getDefaultModel)
import Test exposing (Test, describe, test)
import Tokenizer
suite : Test
suite =
let
testCase =
"@forename is Maksym and @surname is either Ivanov or Petrov"
in
describe "Tokenizer.run"
[ describe "and"
[ test testCase <|
\_ ->
let
( tokens, remainingStates ) =
Tokenizer.run testCase getDefaultModel
in
Expect.equal tokens
[ { state = KeywordTerm
, value = "@forename"
, index = 0
}
, { state = SpaceTerm
, value = " "
, index = 9
}
, { state = IsTerm
, value = "is"
, index = 10
}
, { state = SpaceTerm
, value = " "
, index = 12
}
, { state = WordTerm
, value = "Maksym"
, index = 13
}
, { state = SpaceTerm
, value = " "
, index = 19
}
, { state = AndTerm
, value = "and"
, index = 20
}
, { state = SpaceTerm
, value = " "
, index = 23
}
, { state = KeywordTerm
, value = "@surname"
, index = 24
}
, { state = SpaceTerm
, value = " "
, index = 32
}
, { state = IsEitherTerm
, value = "is either"
, index = 33
}
, { state = SpaceTerm
, value = " "
, index = 42
}
, { state = WordTerm
, value = "Ivanov"
, index = 43
}
, { state = SpaceTerm
, value = " "
, index = 49
}
, { state = EitherOrTerm
, value = "or"
, index = 50
}
, { state = SpaceTerm
, value = " "
, index = 52
}
, { state = WordTerm
, value = "Petrov"
, index = 53
}
]
]
]
| 22974 | module Tokenizer_1_4_3 exposing (..)
import Expect
import GlobalTypes exposing (TokenState(..))
import MockModel exposing (getDefaultModel)
import Test exposing (Test, describe, test)
import Tokenizer
suite : Test
suite =
let
testCase =
"@forename is <NAME> and @surname is either <NAME> or <NAME>"
in
describe "Tokenizer.run"
[ describe "and"
[ test testCase <|
\_ ->
let
( tokens, remainingStates ) =
Tokenizer.run testCase getDefaultModel
in
Expect.equal tokens
[ { state = KeywordTerm
, value = "@forename"
, index = 0
}
, { state = SpaceTerm
, value = " "
, index = 9
}
, { state = IsTerm
, value = "is"
, index = 10
}
, { state = SpaceTerm
, value = " "
, index = 12
}
, { state = WordTerm
, value = "<NAME>"
, index = 13
}
, { state = SpaceTerm
, value = " "
, index = 19
}
, { state = AndTerm
, value = "and"
, index = 20
}
, { state = SpaceTerm
, value = " "
, index = 23
}
, { state = KeywordTerm
, value = "@surname"
, index = 24
}
, { state = SpaceTerm
, value = " "
, index = 32
}
, { state = IsEitherTerm
, value = "is either"
, index = 33
}
, { state = SpaceTerm
, value = " "
, index = 42
}
, { state = WordTerm
, value = "<NAME>"
, index = 43
}
, { state = SpaceTerm
, value = " "
, index = 49
}
, { state = EitherOrTerm
, value = "or"
, index = 50
}
, { state = SpaceTerm
, value = " "
, index = 52
}
, { state = WordTerm
, value = "<NAME>"
, index = 53
}
]
]
]
| true | module Tokenizer_1_4_3 exposing (..)
import Expect
import GlobalTypes exposing (TokenState(..))
import MockModel exposing (getDefaultModel)
import Test exposing (Test, describe, test)
import Tokenizer
suite : Test
suite =
let
testCase =
"@forename is PI:NAME:<NAME>END_PI and @surname is either PI:NAME:<NAME>END_PI or PI:NAME:<NAME>END_PI"
in
describe "Tokenizer.run"
[ describe "and"
[ test testCase <|
\_ ->
let
( tokens, remainingStates ) =
Tokenizer.run testCase getDefaultModel
in
Expect.equal tokens
[ { state = KeywordTerm
, value = "@forename"
, index = 0
}
, { state = SpaceTerm
, value = " "
, index = 9
}
, { state = IsTerm
, value = "is"
, index = 10
}
, { state = SpaceTerm
, value = " "
, index = 12
}
, { state = WordTerm
, value = "PI:NAME:<NAME>END_PI"
, index = 13
}
, { state = SpaceTerm
, value = " "
, index = 19
}
, { state = AndTerm
, value = "and"
, index = 20
}
, { state = SpaceTerm
, value = " "
, index = 23
}
, { state = KeywordTerm
, value = "@surname"
, index = 24
}
, { state = SpaceTerm
, value = " "
, index = 32
}
, { state = IsEitherTerm
, value = "is either"
, index = 33
}
, { state = SpaceTerm
, value = " "
, index = 42
}
, { state = WordTerm
, value = "PI:NAME:<NAME>END_PI"
, index = 43
}
, { state = SpaceTerm
, value = " "
, index = 49
}
, { state = EitherOrTerm
, value = "or"
, index = 50
}
, { state = SpaceTerm
, value = " "
, index = 52
}
, { state = WordTerm
, value = "PI:NAME:<NAME>END_PI"
, index = 53
}
]
]
]
| elm |
[
{
"context": "\"notfound.svg\"\n , csrfToken = \"csrf_token\"\n , authToken = \"\"\n ",
"end": 872,
"score": 0.4142976701,
"start": 862,
"tag": "KEY",
"value": "csrf_token"
},
{
"context": "\"notfound.svg\"\n , csrfToken = \"csrf_token\"\n , authToken = \"\"\n ",
"end": 2279,
"score": 0.4109534025,
"start": 2275,
"tag": "KEY",
"value": "csrf"
},
{
"context": "ound.svg\"\n , csrfToken = \"csrf_token\"\n , authToken = \"\"\n ",
"end": 2285,
"score": 0.3967870176,
"start": 2280,
"tag": "KEY",
"value": "token"
}
] | web/elm/tests/DashboardCacheTests.elm | clarafu/concourse | 0 | module DashboardCacheTests exposing (all)
import Application.Application as Application
import Common
import Concourse.BuildStatus exposing (BuildStatus(..))
import Data
import Message.Callback exposing (Callback(..))
import Message.Effects exposing (Effect(..))
import Message.Message as Message
import Message.Subscription as Subscription exposing (Delivery(..))
import Message.TopLevelMessage as TopLevelMessage
import Test exposing (Test, describe, test)
import Test.Html.Query as Query
import Test.Html.Selector exposing (class, containing, text)
import Url
all : Test
all =
describe "dashboard cache tests"
[ test "requests the cached jobs on page load" <|
\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = "notfound.svg"
, csrfToken = "csrf_token"
, authToken = ""
, pipelineRunningKeyframes = ""
}
{ protocol = Url.Http
, host = ""
, port_ = Nothing
, path = "/"
, query = Nothing
, fragment = Nothing
}
|> Tuple.second
|> Common.contains LoadCachedJobs
, test "requests the cached pipelines on page load" <|
\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = "notfound.svg"
, csrfToken = "csrf_token"
, authToken = ""
, pipelineRunningKeyframes = ""
}
{ protocol = Url.Http
, host = ""
, port_ = Nothing
, path = "/"
, query = Nothing
, fragment = Nothing
}
|> Tuple.second
|> Common.contains LoadCachedPipelines
, test "requests the cached teams on page load" <|
\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = "notfound.svg"
, csrfToken = "csrf_token"
, authToken = ""
, pipelineRunningKeyframes = ""
}
{ protocol = Url.Http
, host = ""
, port_ = Nothing
, path = "/"
, query = Nothing
, fragment = Nothing
}
|> Tuple.second
|> Common.contains LoadCachedTeams
, test "subscribes to receive cached jobs" <|
\_ ->
Common.init "/"
|> Application.subscriptions
|> Common.contains Subscription.OnCachedJobsReceived
, test "subscribes to receive cached pipelines" <|
\_ ->
Common.init "/"
|> Application.subscriptions
|> Common.contains Subscription.OnCachedPipelinesReceived
, test "subscribes to receive cached teams" <|
\_ ->
Common.init "/"
|> Application.subscriptions
|> Common.contains Subscription.OnCachedTeamsReceived
, test "renders pipelines when receive cached pipelines delivery" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Common.queryView
|> Query.has [ class "pipeline-wrapper", containing [ text "pipeline-0" ] ]
, test "renders jobs in pipelines when receive cached jobs delivery" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleDelivery
(CachedJobsReceived <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "pipeline-wrapper" ]
|> Query.has [ class "parallel-grid" ]
, test "ignores the job cache after fetching successfully" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.first
|> Application.handleDelivery
(CachedJobsReceived <|
Ok <|
[]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "pipeline-wrapper" ]
|> Query.has [ class "parallel-grid" ]
, test "saves jobs to cache when fetched" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.second
|> Common.contains (SaveCachedJobs [ Data.job 0 ])
, test "removes build information from jobs when saving to cache" <|
\_ ->
let
jobWithoutBuild =
Data.job 0
jobWithBuild =
{ jobWithoutBuild
| finishedBuild = Just <| Data.jobBuild BuildStatusSucceeded
, transitionBuild = Just <| Data.jobBuild BuildStatusSucceeded
, nextBuild = Just <| Data.jobBuild BuildStatusSucceeded
}
in
Common.init "/"
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
[ jobWithBuild ]
)
|> Tuple.second
|> Common.contains (SaveCachedJobs [ jobWithoutBuild ])
, test "does not save jobs to cache when fetched with no change" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedJobsReceived <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.first
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.second
|> Common.notContains (SaveCachedJobs [ Data.job 0 ])
, test "bounds the number of cached jobs to 1000" <|
\_ ->
let
firstNJobs n =
List.range 0 (n - 1) |> List.map Data.job
in
Common.init "/"
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
firstNJobs 2000
)
|> Tuple.second
|> Common.contains (SaveCachedJobs <| firstNJobs 1000)
, test "saves pipelines to cache when fetched" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllPipelinesFetched <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.second
|> Common.contains (SaveCachedPipelines [ Data.pipeline "team" 0 ])
, test "ignores cached pipelines if we've already fetched from network" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllPipelinesFetched <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[]
)
|> Tuple.first
|> Common.queryView
|> Query.has [ class "pipeline-wrapper", containing [ text "pipeline-0" ] ]
, test "does not save pipelines to cache when fetched with no change" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleCallback
(AllPipelinesFetched <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.second
|> Common.notContains (SaveCachedPipelines [ Data.pipeline "team" 0 ])
, test "saves pipelines to cache when re-ordered" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllPipelinesFetched <|
Ok <|
[ Data.pipeline "team" 0, Data.pipeline "team" 1 ]
)
|> Tuple.first
|> Application.update
(TopLevelMessage.Update <| Message.DragStart "team" 0)
|> Tuple.first
|> Application.update
(TopLevelMessage.Update <| Message.DragOver "team" 2)
|> Tuple.first
|> Application.update
(TopLevelMessage.Update <| Message.DragEnd)
|> Tuple.second
|> Common.contains (SaveCachedPipelines [ Data.pipeline "team" 1, Data.pipeline "team" 0 ])
, test "saves teams to cache when fetched" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllTeamsFetched <|
Ok <|
[ { id = 0, name = "team-0" } ]
)
|> Tuple.second
|> Common.contains (SaveCachedTeams [ { id = 0, name = "team-0" } ])
, test "does not save teams to cache when fetched with no change" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedTeamsReceived <|
Ok <|
[ { id = 0, name = "team-0" } ]
)
|> Tuple.first
|> Application.handleCallback
(AllTeamsFetched <|
Ok <|
[ { id = 0, name = "team-0" } ]
)
|> Tuple.second
|> Common.notContains (SaveCachedPipelines [ Data.pipeline "team" 0 ])
, test "deletes cached pipelines on logged out" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(LoggedOut <| Ok ())
|> Tuple.second
|> Common.contains DeleteCachedPipelines
, test "deletes cached jobs on logged out" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(LoggedOut <| Ok ())
|> Tuple.second
|> Common.contains DeleteCachedJobs
, test "deletes cached teams on logged out" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(LoggedOut <| Ok ())
|> Tuple.second
|> Common.contains DeleteCachedTeams
]
| 7161 | module DashboardCacheTests exposing (all)
import Application.Application as Application
import Common
import Concourse.BuildStatus exposing (BuildStatus(..))
import Data
import Message.Callback exposing (Callback(..))
import Message.Effects exposing (Effect(..))
import Message.Message as Message
import Message.Subscription as Subscription exposing (Delivery(..))
import Message.TopLevelMessage as TopLevelMessage
import Test exposing (Test, describe, test)
import Test.Html.Query as Query
import Test.Html.Selector exposing (class, containing, text)
import Url
all : Test
all =
describe "dashboard cache tests"
[ test "requests the cached jobs on page load" <|
\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = "notfound.svg"
, csrfToken = "<KEY>"
, authToken = ""
, pipelineRunningKeyframes = ""
}
{ protocol = Url.Http
, host = ""
, port_ = Nothing
, path = "/"
, query = Nothing
, fragment = Nothing
}
|> Tuple.second
|> Common.contains LoadCachedJobs
, test "requests the cached pipelines on page load" <|
\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = "notfound.svg"
, csrfToken = "csrf_token"
, authToken = ""
, pipelineRunningKeyframes = ""
}
{ protocol = Url.Http
, host = ""
, port_ = Nothing
, path = "/"
, query = Nothing
, fragment = Nothing
}
|> Tuple.second
|> Common.contains LoadCachedPipelines
, test "requests the cached teams on page load" <|
\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = "notfound.svg"
, csrfToken = "<KEY>_<KEY>"
, authToken = ""
, pipelineRunningKeyframes = ""
}
{ protocol = Url.Http
, host = ""
, port_ = Nothing
, path = "/"
, query = Nothing
, fragment = Nothing
}
|> Tuple.second
|> Common.contains LoadCachedTeams
, test "subscribes to receive cached jobs" <|
\_ ->
Common.init "/"
|> Application.subscriptions
|> Common.contains Subscription.OnCachedJobsReceived
, test "subscribes to receive cached pipelines" <|
\_ ->
Common.init "/"
|> Application.subscriptions
|> Common.contains Subscription.OnCachedPipelinesReceived
, test "subscribes to receive cached teams" <|
\_ ->
Common.init "/"
|> Application.subscriptions
|> Common.contains Subscription.OnCachedTeamsReceived
, test "renders pipelines when receive cached pipelines delivery" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Common.queryView
|> Query.has [ class "pipeline-wrapper", containing [ text "pipeline-0" ] ]
, test "renders jobs in pipelines when receive cached jobs delivery" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleDelivery
(CachedJobsReceived <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "pipeline-wrapper" ]
|> Query.has [ class "parallel-grid" ]
, test "ignores the job cache after fetching successfully" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.first
|> Application.handleDelivery
(CachedJobsReceived <|
Ok <|
[]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "pipeline-wrapper" ]
|> Query.has [ class "parallel-grid" ]
, test "saves jobs to cache when fetched" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.second
|> Common.contains (SaveCachedJobs [ Data.job 0 ])
, test "removes build information from jobs when saving to cache" <|
\_ ->
let
jobWithoutBuild =
Data.job 0
jobWithBuild =
{ jobWithoutBuild
| finishedBuild = Just <| Data.jobBuild BuildStatusSucceeded
, transitionBuild = Just <| Data.jobBuild BuildStatusSucceeded
, nextBuild = Just <| Data.jobBuild BuildStatusSucceeded
}
in
Common.init "/"
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
[ jobWithBuild ]
)
|> Tuple.second
|> Common.contains (SaveCachedJobs [ jobWithoutBuild ])
, test "does not save jobs to cache when fetched with no change" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedJobsReceived <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.first
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.second
|> Common.notContains (SaveCachedJobs [ Data.job 0 ])
, test "bounds the number of cached jobs to 1000" <|
\_ ->
let
firstNJobs n =
List.range 0 (n - 1) |> List.map Data.job
in
Common.init "/"
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
firstNJobs 2000
)
|> Tuple.second
|> Common.contains (SaveCachedJobs <| firstNJobs 1000)
, test "saves pipelines to cache when fetched" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllPipelinesFetched <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.second
|> Common.contains (SaveCachedPipelines [ Data.pipeline "team" 0 ])
, test "ignores cached pipelines if we've already fetched from network" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllPipelinesFetched <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[]
)
|> Tuple.first
|> Common.queryView
|> Query.has [ class "pipeline-wrapper", containing [ text "pipeline-0" ] ]
, test "does not save pipelines to cache when fetched with no change" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleCallback
(AllPipelinesFetched <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.second
|> Common.notContains (SaveCachedPipelines [ Data.pipeline "team" 0 ])
, test "saves pipelines to cache when re-ordered" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllPipelinesFetched <|
Ok <|
[ Data.pipeline "team" 0, Data.pipeline "team" 1 ]
)
|> Tuple.first
|> Application.update
(TopLevelMessage.Update <| Message.DragStart "team" 0)
|> Tuple.first
|> Application.update
(TopLevelMessage.Update <| Message.DragOver "team" 2)
|> Tuple.first
|> Application.update
(TopLevelMessage.Update <| Message.DragEnd)
|> Tuple.second
|> Common.contains (SaveCachedPipelines [ Data.pipeline "team" 1, Data.pipeline "team" 0 ])
, test "saves teams to cache when fetched" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllTeamsFetched <|
Ok <|
[ { id = 0, name = "team-0" } ]
)
|> Tuple.second
|> Common.contains (SaveCachedTeams [ { id = 0, name = "team-0" } ])
, test "does not save teams to cache when fetched with no change" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedTeamsReceived <|
Ok <|
[ { id = 0, name = "team-0" } ]
)
|> Tuple.first
|> Application.handleCallback
(AllTeamsFetched <|
Ok <|
[ { id = 0, name = "team-0" } ]
)
|> Tuple.second
|> Common.notContains (SaveCachedPipelines [ Data.pipeline "team" 0 ])
, test "deletes cached pipelines on logged out" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(LoggedOut <| Ok ())
|> Tuple.second
|> Common.contains DeleteCachedPipelines
, test "deletes cached jobs on logged out" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(LoggedOut <| Ok ())
|> Tuple.second
|> Common.contains DeleteCachedJobs
, test "deletes cached teams on logged out" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(LoggedOut <| Ok ())
|> Tuple.second
|> Common.contains DeleteCachedTeams
]
| true | module DashboardCacheTests exposing (all)
import Application.Application as Application
import Common
import Concourse.BuildStatus exposing (BuildStatus(..))
import Data
import Message.Callback exposing (Callback(..))
import Message.Effects exposing (Effect(..))
import Message.Message as Message
import Message.Subscription as Subscription exposing (Delivery(..))
import Message.TopLevelMessage as TopLevelMessage
import Test exposing (Test, describe, test)
import Test.Html.Query as Query
import Test.Html.Selector exposing (class, containing, text)
import Url
all : Test
all =
describe "dashboard cache tests"
[ test "requests the cached jobs on page load" <|
\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = "notfound.svg"
, csrfToken = "PI:KEY:<KEY>END_PI"
, authToken = ""
, pipelineRunningKeyframes = ""
}
{ protocol = Url.Http
, host = ""
, port_ = Nothing
, path = "/"
, query = Nothing
, fragment = Nothing
}
|> Tuple.second
|> Common.contains LoadCachedJobs
, test "requests the cached pipelines on page load" <|
\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = "notfound.svg"
, csrfToken = "csrf_token"
, authToken = ""
, pipelineRunningKeyframes = ""
}
{ protocol = Url.Http
, host = ""
, port_ = Nothing
, path = "/"
, query = Nothing
, fragment = Nothing
}
|> Tuple.second
|> Common.contains LoadCachedPipelines
, test "requests the cached teams on page load" <|
\_ ->
Application.init
{ turbulenceImgSrc = ""
, notFoundImgSrc = "notfound.svg"
, csrfToken = "PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PI"
, authToken = ""
, pipelineRunningKeyframes = ""
}
{ protocol = Url.Http
, host = ""
, port_ = Nothing
, path = "/"
, query = Nothing
, fragment = Nothing
}
|> Tuple.second
|> Common.contains LoadCachedTeams
, test "subscribes to receive cached jobs" <|
\_ ->
Common.init "/"
|> Application.subscriptions
|> Common.contains Subscription.OnCachedJobsReceived
, test "subscribes to receive cached pipelines" <|
\_ ->
Common.init "/"
|> Application.subscriptions
|> Common.contains Subscription.OnCachedPipelinesReceived
, test "subscribes to receive cached teams" <|
\_ ->
Common.init "/"
|> Application.subscriptions
|> Common.contains Subscription.OnCachedTeamsReceived
, test "renders pipelines when receive cached pipelines delivery" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Common.queryView
|> Query.has [ class "pipeline-wrapper", containing [ text "pipeline-0" ] ]
, test "renders jobs in pipelines when receive cached jobs delivery" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleDelivery
(CachedJobsReceived <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "pipeline-wrapper" ]
|> Query.has [ class "parallel-grid" ]
, test "ignores the job cache after fetching successfully" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.first
|> Application.handleDelivery
(CachedJobsReceived <|
Ok <|
[]
)
|> Tuple.first
|> Common.queryView
|> Query.find [ class "pipeline-wrapper" ]
|> Query.has [ class "parallel-grid" ]
, test "saves jobs to cache when fetched" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.second
|> Common.contains (SaveCachedJobs [ Data.job 0 ])
, test "removes build information from jobs when saving to cache" <|
\_ ->
let
jobWithoutBuild =
Data.job 0
jobWithBuild =
{ jobWithoutBuild
| finishedBuild = Just <| Data.jobBuild BuildStatusSucceeded
, transitionBuild = Just <| Data.jobBuild BuildStatusSucceeded
, nextBuild = Just <| Data.jobBuild BuildStatusSucceeded
}
in
Common.init "/"
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
[ jobWithBuild ]
)
|> Tuple.second
|> Common.contains (SaveCachedJobs [ jobWithoutBuild ])
, test "does not save jobs to cache when fetched with no change" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedJobsReceived <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.first
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
[ Data.job 0 ]
)
|> Tuple.second
|> Common.notContains (SaveCachedJobs [ Data.job 0 ])
, test "bounds the number of cached jobs to 1000" <|
\_ ->
let
firstNJobs n =
List.range 0 (n - 1) |> List.map Data.job
in
Common.init "/"
|> Application.handleCallback
(AllJobsFetched <|
Ok <|
firstNJobs 2000
)
|> Tuple.second
|> Common.contains (SaveCachedJobs <| firstNJobs 1000)
, test "saves pipelines to cache when fetched" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllPipelinesFetched <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.second
|> Common.contains (SaveCachedPipelines [ Data.pipeline "team" 0 ])
, test "ignores cached pipelines if we've already fetched from network" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllPipelinesFetched <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[]
)
|> Tuple.first
|> Common.queryView
|> Query.has [ class "pipeline-wrapper", containing [ text "pipeline-0" ] ]
, test "does not save pipelines to cache when fetched with no change" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedPipelinesReceived <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.first
|> Application.handleCallback
(AllPipelinesFetched <|
Ok <|
[ Data.pipeline "team" 0 ]
)
|> Tuple.second
|> Common.notContains (SaveCachedPipelines [ Data.pipeline "team" 0 ])
, test "saves pipelines to cache when re-ordered" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllPipelinesFetched <|
Ok <|
[ Data.pipeline "team" 0, Data.pipeline "team" 1 ]
)
|> Tuple.first
|> Application.update
(TopLevelMessage.Update <| Message.DragStart "team" 0)
|> Tuple.first
|> Application.update
(TopLevelMessage.Update <| Message.DragOver "team" 2)
|> Tuple.first
|> Application.update
(TopLevelMessage.Update <| Message.DragEnd)
|> Tuple.second
|> Common.contains (SaveCachedPipelines [ Data.pipeline "team" 1, Data.pipeline "team" 0 ])
, test "saves teams to cache when fetched" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(AllTeamsFetched <|
Ok <|
[ { id = 0, name = "team-0" } ]
)
|> Tuple.second
|> Common.contains (SaveCachedTeams [ { id = 0, name = "team-0" } ])
, test "does not save teams to cache when fetched with no change" <|
\_ ->
Common.init "/"
|> Application.handleDelivery
(CachedTeamsReceived <|
Ok <|
[ { id = 0, name = "team-0" } ]
)
|> Tuple.first
|> Application.handleCallback
(AllTeamsFetched <|
Ok <|
[ { id = 0, name = "team-0" } ]
)
|> Tuple.second
|> Common.notContains (SaveCachedPipelines [ Data.pipeline "team" 0 ])
, test "deletes cached pipelines on logged out" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(LoggedOut <| Ok ())
|> Tuple.second
|> Common.contains DeleteCachedPipelines
, test "deletes cached jobs on logged out" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(LoggedOut <| Ok ())
|> Tuple.second
|> Common.contains DeleteCachedJobs
, test "deletes cached teams on logged out" <|
\_ ->
Common.init "/"
|> Application.handleCallback
(LoggedOut <| Ok ())
|> Tuple.second
|> Common.contains DeleteCachedTeams
]
| elm |
[
{
"context": "-\n Operations/Conversion/Alphabet.elm\n Author: Henrique da Cunha Buss\n Creation: October/2020\n This file contains f",
"end": 74,
"score": 0.9998630285,
"start": 52,
"tag": "NAME",
"value": "Henrique da Cunha Buss"
}
] | src/Operations/Conversion/Alphabet.elm | NeoVier/LFC01 | 0 | {-
Operations/Conversion/Alphabet.elm
Author: Henrique da Cunha Buss
Creation: October/2020
This file contains functions to convert Alphabets
-}
module Operations.Conversion.Alphabet exposing (nonDeterministicToDeterministic)
import Models.Alphabet as Alphabet
{- Convert a non deterministic alphabet to a deterministic alphabet -}
nonDeterministicToDeterministic :
Alphabet.NonDeterministicAlphabet
-> Alphabet.DeterministicAlphabet
nonDeterministicToDeterministic ndAlphabet =
case ndAlphabet of
Alphabet.NDA symbols epsilon ->
symbols
| 16245 | {-
Operations/Conversion/Alphabet.elm
Author: <NAME>
Creation: October/2020
This file contains functions to convert Alphabets
-}
module Operations.Conversion.Alphabet exposing (nonDeterministicToDeterministic)
import Models.Alphabet as Alphabet
{- Convert a non deterministic alphabet to a deterministic alphabet -}
nonDeterministicToDeterministic :
Alphabet.NonDeterministicAlphabet
-> Alphabet.DeterministicAlphabet
nonDeterministicToDeterministic ndAlphabet =
case ndAlphabet of
Alphabet.NDA symbols epsilon ->
symbols
| true | {-
Operations/Conversion/Alphabet.elm
Author: PI:NAME:<NAME>END_PI
Creation: October/2020
This file contains functions to convert Alphabets
-}
module Operations.Conversion.Alphabet exposing (nonDeterministicToDeterministic)
import Models.Alphabet as Alphabet
{- Convert a non deterministic alphabet to a deterministic alphabet -}
nonDeterministicToDeterministic :
Alphabet.NonDeterministicAlphabet
-> Alphabet.DeterministicAlphabet
nonDeterministicToDeterministic ndAlphabet =
case ndAlphabet of
Alphabet.NDA symbols epsilon ->
symbols
| elm |
[
{
"context": "{- Copyright (C) 2018 Mark D. Blackwell.\n All rights reserved.\n This program is distr",
"end": 39,
"score": 0.9998469353,
"start": 22,
"tag": "NAME",
"value": "Mark D. Blackwell"
}
] | src/front-end/Alert.elm | MarkDBlackwell/qplaylist-remember | 0 | {- Copyright (C) 2018 Mark D. Blackwell.
All rights reserved.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-}
module Alert exposing
( actionDescriptionRecent
, messageTextErrorHttpLogging
, messageTextErrorHttpScreen
, messageTextInit
, messageTextRequestLikeOrComment
, messageTextSend
, messageTextServerAwaitingElmCycle
)
import AlertType
exposing
( ActionDescription
, AlertMessageText
, AlertMessageTextMaybe
, DetailsText
, LikeOrCommentName
, PrefixSeparatorText
)
import ElmCycle
import FocusUpdate
import Http
import ModelType
exposing
( Model
)
-- MODEL
messageTextInit : AlertMessageTextMaybe
messageTextInit =
Nothing
-- UPDATE
actionDescriptionRecent : AlertMessageText
actionDescriptionRecent =
"access the latest few songs"
errorHttpText : Http.Error -> ( AlertMessageText, AlertMessageText )
errorHttpText httpError =
let
prefix : PrefixSeparatorText
prefix =
"HttpError"
in
case httpError of
Http.BadBody debuggingText ->
( prefix ++ prefixSeparator ++ "BadBody"
, debuggingText
)
Http.BadStatus status ->
( prefixSeparator ++ "BadStatus"
, String.fromInt status
)
Http.BadUrl urlText ->
( prefixSeparator ++ "BadUrl"
, urlText
)
Http.NetworkError ->
( prefix
, "NetworkError"
)
Http.Timeout ->
( prefix
, "Timeout"
)
messageTextErrorHttpLogging : Http.Error -> AlertMessageText
messageTextErrorHttpLogging httpError =
httpError
|> (errorHttpText >> Tuple.first)
messageTextErrorHttpScreen : Http.Error -> AlertMessageText
messageTextErrorHttpScreen httpError =
httpError
|> (errorHttpText >> Tuple.second)
messageTextRequestLikeOrComment : Http.Error -> LikeOrCommentName -> AlertMessageText
messageTextRequestLikeOrComment httpError likeOrCommentName =
let
prefix : String
prefix =
httpError
|> messageTextErrorHttpScreen
in
[ " (while attempting to send your "
, likeOrCommentName
, ")"
]
|> String.concat
|> String.append prefix
messageTextSend : ActionDescription -> DetailsText -> AlertMessageText
messageTextSend actionDescription detailsText =
[ "Unexpected error while attempting to "
, actionDescription
, prefixSeparator
, detailsText
]
|> String.concat
messageTextServerAwaitingElmCycle : Model -> ElmCycle.ElmCycle
messageTextServerAwaitingElmCycle model =
( { model
| alertMessageText = Just "Awaiting server"
}
, FocusUpdate.cmdFocusInputPossibly model
)
prefixSeparator : PrefixSeparatorText
prefixSeparator =
": "
| 57615 | {- Copyright (C) 2018 <NAME>.
All rights reserved.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-}
module Alert exposing
( actionDescriptionRecent
, messageTextErrorHttpLogging
, messageTextErrorHttpScreen
, messageTextInit
, messageTextRequestLikeOrComment
, messageTextSend
, messageTextServerAwaitingElmCycle
)
import AlertType
exposing
( ActionDescription
, AlertMessageText
, AlertMessageTextMaybe
, DetailsText
, LikeOrCommentName
, PrefixSeparatorText
)
import ElmCycle
import FocusUpdate
import Http
import ModelType
exposing
( Model
)
-- MODEL
messageTextInit : AlertMessageTextMaybe
messageTextInit =
Nothing
-- UPDATE
actionDescriptionRecent : AlertMessageText
actionDescriptionRecent =
"access the latest few songs"
errorHttpText : Http.Error -> ( AlertMessageText, AlertMessageText )
errorHttpText httpError =
let
prefix : PrefixSeparatorText
prefix =
"HttpError"
in
case httpError of
Http.BadBody debuggingText ->
( prefix ++ prefixSeparator ++ "BadBody"
, debuggingText
)
Http.BadStatus status ->
( prefixSeparator ++ "BadStatus"
, String.fromInt status
)
Http.BadUrl urlText ->
( prefixSeparator ++ "BadUrl"
, urlText
)
Http.NetworkError ->
( prefix
, "NetworkError"
)
Http.Timeout ->
( prefix
, "Timeout"
)
messageTextErrorHttpLogging : Http.Error -> AlertMessageText
messageTextErrorHttpLogging httpError =
httpError
|> (errorHttpText >> Tuple.first)
messageTextErrorHttpScreen : Http.Error -> AlertMessageText
messageTextErrorHttpScreen httpError =
httpError
|> (errorHttpText >> Tuple.second)
messageTextRequestLikeOrComment : Http.Error -> LikeOrCommentName -> AlertMessageText
messageTextRequestLikeOrComment httpError likeOrCommentName =
let
prefix : String
prefix =
httpError
|> messageTextErrorHttpScreen
in
[ " (while attempting to send your "
, likeOrCommentName
, ")"
]
|> String.concat
|> String.append prefix
messageTextSend : ActionDescription -> DetailsText -> AlertMessageText
messageTextSend actionDescription detailsText =
[ "Unexpected error while attempting to "
, actionDescription
, prefixSeparator
, detailsText
]
|> String.concat
messageTextServerAwaitingElmCycle : Model -> ElmCycle.ElmCycle
messageTextServerAwaitingElmCycle model =
( { model
| alertMessageText = Just "Awaiting server"
}
, FocusUpdate.cmdFocusInputPossibly model
)
prefixSeparator : PrefixSeparatorText
prefixSeparator =
": "
| true | {- Copyright (C) 2018 PI:NAME:<NAME>END_PI.
All rights reserved.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-}
module Alert exposing
( actionDescriptionRecent
, messageTextErrorHttpLogging
, messageTextErrorHttpScreen
, messageTextInit
, messageTextRequestLikeOrComment
, messageTextSend
, messageTextServerAwaitingElmCycle
)
import AlertType
exposing
( ActionDescription
, AlertMessageText
, AlertMessageTextMaybe
, DetailsText
, LikeOrCommentName
, PrefixSeparatorText
)
import ElmCycle
import FocusUpdate
import Http
import ModelType
exposing
( Model
)
-- MODEL
messageTextInit : AlertMessageTextMaybe
messageTextInit =
Nothing
-- UPDATE
actionDescriptionRecent : AlertMessageText
actionDescriptionRecent =
"access the latest few songs"
errorHttpText : Http.Error -> ( AlertMessageText, AlertMessageText )
errorHttpText httpError =
let
prefix : PrefixSeparatorText
prefix =
"HttpError"
in
case httpError of
Http.BadBody debuggingText ->
( prefix ++ prefixSeparator ++ "BadBody"
, debuggingText
)
Http.BadStatus status ->
( prefixSeparator ++ "BadStatus"
, String.fromInt status
)
Http.BadUrl urlText ->
( prefixSeparator ++ "BadUrl"
, urlText
)
Http.NetworkError ->
( prefix
, "NetworkError"
)
Http.Timeout ->
( prefix
, "Timeout"
)
messageTextErrorHttpLogging : Http.Error -> AlertMessageText
messageTextErrorHttpLogging httpError =
httpError
|> (errorHttpText >> Tuple.first)
messageTextErrorHttpScreen : Http.Error -> AlertMessageText
messageTextErrorHttpScreen httpError =
httpError
|> (errorHttpText >> Tuple.second)
messageTextRequestLikeOrComment : Http.Error -> LikeOrCommentName -> AlertMessageText
messageTextRequestLikeOrComment httpError likeOrCommentName =
let
prefix : String
prefix =
httpError
|> messageTextErrorHttpScreen
in
[ " (while attempting to send your "
, likeOrCommentName
, ")"
]
|> String.concat
|> String.append prefix
messageTextSend : ActionDescription -> DetailsText -> AlertMessageText
messageTextSend actionDescription detailsText =
[ "Unexpected error while attempting to "
, actionDescription
, prefixSeparator
, detailsText
]
|> String.concat
messageTextServerAwaitingElmCycle : Model -> ElmCycle.ElmCycle
messageTextServerAwaitingElmCycle model =
( { model
| alertMessageText = Just "Awaiting server"
}
, FocusUpdate.cmdFocusInputPossibly model
)
prefixSeparator : PrefixSeparatorText
prefixSeparator =
": "
| elm |
[
{
"context": "est =\n describe \"fuzzing whitespace (taken from rtfeldman/elm-validate, which crashed when this first ran)\"",
"end": 9443,
"score": 0.9985584617,
"start": 9434,
"tag": "USERNAME",
"value": "rtfeldman"
},
{
"context": " is valid\" <|\n \\() ->\n \"foo@bar.com\"\n |> Validate.isValidEmail\n ",
"end": 10560,
"score": 0.9998763204,
"start": 10549,
"tag": "EMAIL",
"value": "foo@bar.com"
},
{
"context": "Fail \"Validate.isValidEmail should have considered foo@bar.com a valid email address\"\n ]\n\n\nwhitespace : F",
"end": 10742,
"score": 0.9998750687,
"start": 10731,
"tag": "EMAIL",
"value": "foo@bar.com"
}
] | tests/src/FuzzerTests.elm | Razzeee/test | 0 | module FuzzerTests exposing (fuzzerTests)
import Expect
import Fuzz exposing (..)
import Helpers exposing (..)
import Random
import Test exposing (..)
import Test.Runner
import Validate
die : Fuzzer Int
die =
Fuzz.intRange 1 6
fuzzerTests : Test
fuzzerTests =
describe "Fuzzer methods that use Debug.crash don't call it"
[ describe "FuzzN (uses tupleN) testing string length properties"
[ fuzz2 string string "fuzz2" <|
\a b ->
testStringLengthIsPreserved [ a, b ]
, fuzz3 string string string "fuzz3" <|
\a b c ->
testStringLengthIsPreserved [ a, b, c ]
]
, fuzz
(intRange 1 6)
"intRange"
(Expect.greaterThan 0)
, fuzz
(frequency [ ( 1, intRange 1 6 ), ( 1, intRange 1 20 ) ])
"Fuzz.frequency"
(Expect.greaterThan 0)
, fuzz (result string int) "Fuzz.result" <| \r -> Expect.pass
, describe "Whitebox testing using Fuzz.Internal"
[ fuzz randomSeedFuzzer "the same value is generated with and without shrinking" <|
\seed ->
let
step gen =
Random.step gen seed
aFuzzer =
tuple3
( tuple ( list int, array float )
, tuple
( maybe bool
, result unit char
)
, tuple
( tuple3
( percentage
, map2 (+) int int
, frequency [ ( 1, constant True ), ( 3, constant False ) ]
)
, tuple3 ( intRange 0 100, floatRange -51 pi, map abs int )
)
)
|> Test.Runner.fuzz
valNoShrink =
aFuzzer |> Result.map (Random.map Tuple.first >> step >> Tuple.first)
valWithShrink =
aFuzzer |> Result.map (step >> Tuple.first >> Tuple.first)
in
Expect.equal valNoShrink valWithShrink
, shrinkingTests
, manualFuzzerTests
]
]
shrinkingTests : Test
shrinkingTests =
let
-- To test shrinking, we have to fail some tests so we can shrink their inputs.
-- The best place we found for storing the expected last state(s) of the shrinking procedure is the description field, which is why we have this function here.
-- Previously, we (ab)used Expect.true for this, but since that was removed, here we are.
expectTrueAndExpectShrinkResultToEqualString label a =
Expect.equal True a |> Expect.onFail label
in
testShrinking <|
describe "tests that fail intentionally to test shrinking"
[ fuzz2 int int "Every pair of ints has a zero" <|
\i j ->
(i == 0)
|| (j == 0)
|> expectTrueAndExpectShrinkResultToEqualString "(1,1)"
, fuzz3 int int int "Every triple of ints has a zero" <|
\i j k ->
(i == 0)
|| (j == 0)
|| (k == 0)
|> expectTrueAndExpectShrinkResultToEqualString "(1,1,1)"
, fuzz (list int) "All lists are sorted" <|
\aList ->
let
checkPair l =
case l of
a :: b :: more ->
if a > b then
False
else
checkPair (b :: more)
_ ->
True
in
checkPair aList |> expectTrueAndExpectShrinkResultToEqualString "[1,0]|[0,-1]"
]
type alias ShrinkResult a =
Maybe ( a, Test.Runner.Shrinkable a )
initialShrinkResult : Fuzzer a -> Random.Seed -> ShrinkResult a
initialShrinkResult fuzzer seed =
case Test.Runner.fuzz fuzzer of
Ok generator ->
Random.step generator seed
|> Tuple.first
|> Just
Err _ ->
Nothing
manualFuzzerTests : Test
manualFuzzerTests =
describe "Test.Runner.{fuzz, shrink}"
[ fuzz randomSeedFuzzer "Claim there are no even numbers" <|
\seed ->
let
-- fuzzer is guaranteed to produce an even number
fuzzer =
Fuzz.intRange 2 10000
|> Fuzz.map
(\n ->
if failsTest n then
n
else
n + 1
)
failsTest n =
(n |> modBy 2) == 0
pair =
initialShrinkResult fuzzer seed
unfold acc maybePair =
case maybePair of
Just ( valN, shrinkN ) ->
if failsTest valN then
unfold (valN :: acc) (Test.Runner.shrink False shrinkN)
else
unfold acc (Test.Runner.shrink True shrinkN)
Nothing ->
acc
in
unfold [] pair
|> Expect.all
[ List.all failsTest >> Expect.equal True >> Expect.onFail "Not all elements were even"
, List.head
>> Maybe.map (Expect.all [ Expect.lessThan 5, Expect.atLeast 0 ])
>> Maybe.withDefault (Expect.fail "Did not cause failure")
, List.reverse >> List.head >> Expect.equal (Maybe.map Tuple.first pair)
]
, fuzz randomSeedFuzzer "No strings contain the letter e" <|
\seed ->
let
-- fuzzer is guaranteed to produce a string with the letter e
fuzzer =
map2 (\pre suf -> pre ++ "e" ++ suf) string string
failsTest =
String.contains "e"
pair =
initialShrinkResult fuzzer seed
unfold acc maybePair =
case maybePair of
Just ( valN, shrinkN ) ->
if failsTest valN then
unfold (valN :: acc) (Test.Runner.shrink False shrinkN)
else
unfold acc (Test.Runner.shrink True shrinkN)
Nothing ->
acc
in
unfold [] pair
|> Expect.all
[ List.all failsTest >> Expect.equal True >> Expect.onFail "Not all contained the letter e"
, List.head >> Expect.equal (Just "e")
, List.reverse >> List.head >> Expect.equal (Maybe.map Tuple.first pair)
]
, fuzz randomSeedFuzzer "List shrinker finds the smallest counter example" <|
\seed ->
let
fuzzer : Fuzzer (List Int)
fuzzer =
Fuzz.list Fuzz.int
allEven : List Int -> Bool
allEven xs =
List.all (\x -> (x |> modBy 2) == 0) xs
initialShrink : ShrinkResult (List Int)
initialShrink =
initialShrinkResult fuzzer seed
shrink : Maybe (List Int) -> ShrinkResult (List Int) -> Maybe (List Int)
shrink shrunken lastShrink =
case lastShrink of
Just ( valN, shrinkN ) ->
shrink
(if allEven valN then
shrunken
else
Just valN
)
(Test.Runner.shrink (allEven valN) shrinkN)
Nothing ->
shrunken
in
case shrink Nothing initialShrink of
Just shrunken ->
Expect.equal [ 1 ] shrunken
Nothing ->
Expect.pass
]
whitespaceTest : Test
whitespaceTest =
describe "fuzzing whitespace (taken from rtfeldman/elm-validate, which crashed when this first ran)"
[ fuzz whitespace "whitespace characters are blank" <|
\str ->
str
|> Validate.isBlank
|> Expect.equal True
>> Expect.onFail "Validate.isBlank should consider whitespace blank"
, fuzz2 whitespace whitespace "non-whitespace characters mean it's not blank" <|
\prefix suffix ->
(prefix ++ "_" ++ suffix)
|> Validate.isBlank
|> Expect.equal False
>> Expect.onFail "Validate.isBlank shouldn't consider strings containing non-whitespace characters blank"
]
email : Test
email =
describe "email"
[ test "empty string is not a valid email" <|
\() ->
""
|> Validate.isValidEmail
|> Expect.equal False
>> Expect.onFail "Validate.isValidEmail should have considered empty string blank"
, test "valid email is valid" <|
\() ->
"foo@bar.com"
|> Validate.isValidEmail
|> Expect.equal True
>> Expect.onFail "Validate.isValidEmail should have considered foo@bar.com a valid email address"
]
whitespace : Fuzzer String
whitespace =
[ ' ', '\u{00A0}', '\t', '\n' ]
|> List.map Fuzz.constant
|> Fuzz.oneOf
|> Fuzz.list
|> Fuzz.map String.fromList
| 4756 | module FuzzerTests exposing (fuzzerTests)
import Expect
import Fuzz exposing (..)
import Helpers exposing (..)
import Random
import Test exposing (..)
import Test.Runner
import Validate
die : Fuzzer Int
die =
Fuzz.intRange 1 6
fuzzerTests : Test
fuzzerTests =
describe "Fuzzer methods that use Debug.crash don't call it"
[ describe "FuzzN (uses tupleN) testing string length properties"
[ fuzz2 string string "fuzz2" <|
\a b ->
testStringLengthIsPreserved [ a, b ]
, fuzz3 string string string "fuzz3" <|
\a b c ->
testStringLengthIsPreserved [ a, b, c ]
]
, fuzz
(intRange 1 6)
"intRange"
(Expect.greaterThan 0)
, fuzz
(frequency [ ( 1, intRange 1 6 ), ( 1, intRange 1 20 ) ])
"Fuzz.frequency"
(Expect.greaterThan 0)
, fuzz (result string int) "Fuzz.result" <| \r -> Expect.pass
, describe "Whitebox testing using Fuzz.Internal"
[ fuzz randomSeedFuzzer "the same value is generated with and without shrinking" <|
\seed ->
let
step gen =
Random.step gen seed
aFuzzer =
tuple3
( tuple ( list int, array float )
, tuple
( maybe bool
, result unit char
)
, tuple
( tuple3
( percentage
, map2 (+) int int
, frequency [ ( 1, constant True ), ( 3, constant False ) ]
)
, tuple3 ( intRange 0 100, floatRange -51 pi, map abs int )
)
)
|> Test.Runner.fuzz
valNoShrink =
aFuzzer |> Result.map (Random.map Tuple.first >> step >> Tuple.first)
valWithShrink =
aFuzzer |> Result.map (step >> Tuple.first >> Tuple.first)
in
Expect.equal valNoShrink valWithShrink
, shrinkingTests
, manualFuzzerTests
]
]
shrinkingTests : Test
shrinkingTests =
let
-- To test shrinking, we have to fail some tests so we can shrink their inputs.
-- The best place we found for storing the expected last state(s) of the shrinking procedure is the description field, which is why we have this function here.
-- Previously, we (ab)used Expect.true for this, but since that was removed, here we are.
expectTrueAndExpectShrinkResultToEqualString label a =
Expect.equal True a |> Expect.onFail label
in
testShrinking <|
describe "tests that fail intentionally to test shrinking"
[ fuzz2 int int "Every pair of ints has a zero" <|
\i j ->
(i == 0)
|| (j == 0)
|> expectTrueAndExpectShrinkResultToEqualString "(1,1)"
, fuzz3 int int int "Every triple of ints has a zero" <|
\i j k ->
(i == 0)
|| (j == 0)
|| (k == 0)
|> expectTrueAndExpectShrinkResultToEqualString "(1,1,1)"
, fuzz (list int) "All lists are sorted" <|
\aList ->
let
checkPair l =
case l of
a :: b :: more ->
if a > b then
False
else
checkPair (b :: more)
_ ->
True
in
checkPair aList |> expectTrueAndExpectShrinkResultToEqualString "[1,0]|[0,-1]"
]
type alias ShrinkResult a =
Maybe ( a, Test.Runner.Shrinkable a )
initialShrinkResult : Fuzzer a -> Random.Seed -> ShrinkResult a
initialShrinkResult fuzzer seed =
case Test.Runner.fuzz fuzzer of
Ok generator ->
Random.step generator seed
|> Tuple.first
|> Just
Err _ ->
Nothing
manualFuzzerTests : Test
manualFuzzerTests =
describe "Test.Runner.{fuzz, shrink}"
[ fuzz randomSeedFuzzer "Claim there are no even numbers" <|
\seed ->
let
-- fuzzer is guaranteed to produce an even number
fuzzer =
Fuzz.intRange 2 10000
|> Fuzz.map
(\n ->
if failsTest n then
n
else
n + 1
)
failsTest n =
(n |> modBy 2) == 0
pair =
initialShrinkResult fuzzer seed
unfold acc maybePair =
case maybePair of
Just ( valN, shrinkN ) ->
if failsTest valN then
unfold (valN :: acc) (Test.Runner.shrink False shrinkN)
else
unfold acc (Test.Runner.shrink True shrinkN)
Nothing ->
acc
in
unfold [] pair
|> Expect.all
[ List.all failsTest >> Expect.equal True >> Expect.onFail "Not all elements were even"
, List.head
>> Maybe.map (Expect.all [ Expect.lessThan 5, Expect.atLeast 0 ])
>> Maybe.withDefault (Expect.fail "Did not cause failure")
, List.reverse >> List.head >> Expect.equal (Maybe.map Tuple.first pair)
]
, fuzz randomSeedFuzzer "No strings contain the letter e" <|
\seed ->
let
-- fuzzer is guaranteed to produce a string with the letter e
fuzzer =
map2 (\pre suf -> pre ++ "e" ++ suf) string string
failsTest =
String.contains "e"
pair =
initialShrinkResult fuzzer seed
unfold acc maybePair =
case maybePair of
Just ( valN, shrinkN ) ->
if failsTest valN then
unfold (valN :: acc) (Test.Runner.shrink False shrinkN)
else
unfold acc (Test.Runner.shrink True shrinkN)
Nothing ->
acc
in
unfold [] pair
|> Expect.all
[ List.all failsTest >> Expect.equal True >> Expect.onFail "Not all contained the letter e"
, List.head >> Expect.equal (Just "e")
, List.reverse >> List.head >> Expect.equal (Maybe.map Tuple.first pair)
]
, fuzz randomSeedFuzzer "List shrinker finds the smallest counter example" <|
\seed ->
let
fuzzer : Fuzzer (List Int)
fuzzer =
Fuzz.list Fuzz.int
allEven : List Int -> Bool
allEven xs =
List.all (\x -> (x |> modBy 2) == 0) xs
initialShrink : ShrinkResult (List Int)
initialShrink =
initialShrinkResult fuzzer seed
shrink : Maybe (List Int) -> ShrinkResult (List Int) -> Maybe (List Int)
shrink shrunken lastShrink =
case lastShrink of
Just ( valN, shrinkN ) ->
shrink
(if allEven valN then
shrunken
else
Just valN
)
(Test.Runner.shrink (allEven valN) shrinkN)
Nothing ->
shrunken
in
case shrink Nothing initialShrink of
Just shrunken ->
Expect.equal [ 1 ] shrunken
Nothing ->
Expect.pass
]
whitespaceTest : Test
whitespaceTest =
describe "fuzzing whitespace (taken from rtfeldman/elm-validate, which crashed when this first ran)"
[ fuzz whitespace "whitespace characters are blank" <|
\str ->
str
|> Validate.isBlank
|> Expect.equal True
>> Expect.onFail "Validate.isBlank should consider whitespace blank"
, fuzz2 whitespace whitespace "non-whitespace characters mean it's not blank" <|
\prefix suffix ->
(prefix ++ "_" ++ suffix)
|> Validate.isBlank
|> Expect.equal False
>> Expect.onFail "Validate.isBlank shouldn't consider strings containing non-whitespace characters blank"
]
email : Test
email =
describe "email"
[ test "empty string is not a valid email" <|
\() ->
""
|> Validate.isValidEmail
|> Expect.equal False
>> Expect.onFail "Validate.isValidEmail should have considered empty string blank"
, test "valid email is valid" <|
\() ->
"<EMAIL>"
|> Validate.isValidEmail
|> Expect.equal True
>> Expect.onFail "Validate.isValidEmail should have considered <EMAIL> a valid email address"
]
whitespace : Fuzzer String
whitespace =
[ ' ', '\u{00A0}', '\t', '\n' ]
|> List.map Fuzz.constant
|> Fuzz.oneOf
|> Fuzz.list
|> Fuzz.map String.fromList
| true | module FuzzerTests exposing (fuzzerTests)
import Expect
import Fuzz exposing (..)
import Helpers exposing (..)
import Random
import Test exposing (..)
import Test.Runner
import Validate
die : Fuzzer Int
die =
Fuzz.intRange 1 6
fuzzerTests : Test
fuzzerTests =
describe "Fuzzer methods that use Debug.crash don't call it"
[ describe "FuzzN (uses tupleN) testing string length properties"
[ fuzz2 string string "fuzz2" <|
\a b ->
testStringLengthIsPreserved [ a, b ]
, fuzz3 string string string "fuzz3" <|
\a b c ->
testStringLengthIsPreserved [ a, b, c ]
]
, fuzz
(intRange 1 6)
"intRange"
(Expect.greaterThan 0)
, fuzz
(frequency [ ( 1, intRange 1 6 ), ( 1, intRange 1 20 ) ])
"Fuzz.frequency"
(Expect.greaterThan 0)
, fuzz (result string int) "Fuzz.result" <| \r -> Expect.pass
, describe "Whitebox testing using Fuzz.Internal"
[ fuzz randomSeedFuzzer "the same value is generated with and without shrinking" <|
\seed ->
let
step gen =
Random.step gen seed
aFuzzer =
tuple3
( tuple ( list int, array float )
, tuple
( maybe bool
, result unit char
)
, tuple
( tuple3
( percentage
, map2 (+) int int
, frequency [ ( 1, constant True ), ( 3, constant False ) ]
)
, tuple3 ( intRange 0 100, floatRange -51 pi, map abs int )
)
)
|> Test.Runner.fuzz
valNoShrink =
aFuzzer |> Result.map (Random.map Tuple.first >> step >> Tuple.first)
valWithShrink =
aFuzzer |> Result.map (step >> Tuple.first >> Tuple.first)
in
Expect.equal valNoShrink valWithShrink
, shrinkingTests
, manualFuzzerTests
]
]
shrinkingTests : Test
shrinkingTests =
let
-- To test shrinking, we have to fail some tests so we can shrink their inputs.
-- The best place we found for storing the expected last state(s) of the shrinking procedure is the description field, which is why we have this function here.
-- Previously, we (ab)used Expect.true for this, but since that was removed, here we are.
expectTrueAndExpectShrinkResultToEqualString label a =
Expect.equal True a |> Expect.onFail label
in
testShrinking <|
describe "tests that fail intentionally to test shrinking"
[ fuzz2 int int "Every pair of ints has a zero" <|
\i j ->
(i == 0)
|| (j == 0)
|> expectTrueAndExpectShrinkResultToEqualString "(1,1)"
, fuzz3 int int int "Every triple of ints has a zero" <|
\i j k ->
(i == 0)
|| (j == 0)
|| (k == 0)
|> expectTrueAndExpectShrinkResultToEqualString "(1,1,1)"
, fuzz (list int) "All lists are sorted" <|
\aList ->
let
checkPair l =
case l of
a :: b :: more ->
if a > b then
False
else
checkPair (b :: more)
_ ->
True
in
checkPair aList |> expectTrueAndExpectShrinkResultToEqualString "[1,0]|[0,-1]"
]
type alias ShrinkResult a =
Maybe ( a, Test.Runner.Shrinkable a )
initialShrinkResult : Fuzzer a -> Random.Seed -> ShrinkResult a
initialShrinkResult fuzzer seed =
case Test.Runner.fuzz fuzzer of
Ok generator ->
Random.step generator seed
|> Tuple.first
|> Just
Err _ ->
Nothing
manualFuzzerTests : Test
manualFuzzerTests =
describe "Test.Runner.{fuzz, shrink}"
[ fuzz randomSeedFuzzer "Claim there are no even numbers" <|
\seed ->
let
-- fuzzer is guaranteed to produce an even number
fuzzer =
Fuzz.intRange 2 10000
|> Fuzz.map
(\n ->
if failsTest n then
n
else
n + 1
)
failsTest n =
(n |> modBy 2) == 0
pair =
initialShrinkResult fuzzer seed
unfold acc maybePair =
case maybePair of
Just ( valN, shrinkN ) ->
if failsTest valN then
unfold (valN :: acc) (Test.Runner.shrink False shrinkN)
else
unfold acc (Test.Runner.shrink True shrinkN)
Nothing ->
acc
in
unfold [] pair
|> Expect.all
[ List.all failsTest >> Expect.equal True >> Expect.onFail "Not all elements were even"
, List.head
>> Maybe.map (Expect.all [ Expect.lessThan 5, Expect.atLeast 0 ])
>> Maybe.withDefault (Expect.fail "Did not cause failure")
, List.reverse >> List.head >> Expect.equal (Maybe.map Tuple.first pair)
]
, fuzz randomSeedFuzzer "No strings contain the letter e" <|
\seed ->
let
-- fuzzer is guaranteed to produce a string with the letter e
fuzzer =
map2 (\pre suf -> pre ++ "e" ++ suf) string string
failsTest =
String.contains "e"
pair =
initialShrinkResult fuzzer seed
unfold acc maybePair =
case maybePair of
Just ( valN, shrinkN ) ->
if failsTest valN then
unfold (valN :: acc) (Test.Runner.shrink False shrinkN)
else
unfold acc (Test.Runner.shrink True shrinkN)
Nothing ->
acc
in
unfold [] pair
|> Expect.all
[ List.all failsTest >> Expect.equal True >> Expect.onFail "Not all contained the letter e"
, List.head >> Expect.equal (Just "e")
, List.reverse >> List.head >> Expect.equal (Maybe.map Tuple.first pair)
]
, fuzz randomSeedFuzzer "List shrinker finds the smallest counter example" <|
\seed ->
let
fuzzer : Fuzzer (List Int)
fuzzer =
Fuzz.list Fuzz.int
allEven : List Int -> Bool
allEven xs =
List.all (\x -> (x |> modBy 2) == 0) xs
initialShrink : ShrinkResult (List Int)
initialShrink =
initialShrinkResult fuzzer seed
shrink : Maybe (List Int) -> ShrinkResult (List Int) -> Maybe (List Int)
shrink shrunken lastShrink =
case lastShrink of
Just ( valN, shrinkN ) ->
shrink
(if allEven valN then
shrunken
else
Just valN
)
(Test.Runner.shrink (allEven valN) shrinkN)
Nothing ->
shrunken
in
case shrink Nothing initialShrink of
Just shrunken ->
Expect.equal [ 1 ] shrunken
Nothing ->
Expect.pass
]
whitespaceTest : Test
whitespaceTest =
describe "fuzzing whitespace (taken from rtfeldman/elm-validate, which crashed when this first ran)"
[ fuzz whitespace "whitespace characters are blank" <|
\str ->
str
|> Validate.isBlank
|> Expect.equal True
>> Expect.onFail "Validate.isBlank should consider whitespace blank"
, fuzz2 whitespace whitespace "non-whitespace characters mean it's not blank" <|
\prefix suffix ->
(prefix ++ "_" ++ suffix)
|> Validate.isBlank
|> Expect.equal False
>> Expect.onFail "Validate.isBlank shouldn't consider strings containing non-whitespace characters blank"
]
email : Test
email =
describe "email"
[ test "empty string is not a valid email" <|
\() ->
""
|> Validate.isValidEmail
|> Expect.equal False
>> Expect.onFail "Validate.isValidEmail should have considered empty string blank"
, test "valid email is valid" <|
\() ->
"PI:EMAIL:<EMAIL>END_PI"
|> Validate.isValidEmail
|> Expect.equal True
>> Expect.onFail "Validate.isValidEmail should have considered PI:EMAIL:<EMAIL>END_PI a valid email address"
]
whitespace : Fuzzer String
whitespace =
[ ' ', '\u{00A0}', '\t', '\n' ]
|> List.map Fuzz.constant
|> Fuzz.oneOf
|> Fuzz.list
|> Fuzz.map String.fromList
| elm |
[
{
"context": "l | auth = Model.LoggedOut { formData | password = pwd, loginErr = Nothing } } ! []\n\n LoggedIn (E",
"end": 1510,
"score": 0.9978044033,
"start": 1507,
"tag": "PASSWORD",
"value": "pwd"
}
] | client/src/elm/Main.elm | javaBin/serenity | 0 | module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import View.LoginForm
import Model exposing (Model)
import Messages exposing (Msg(..))
import Ports
import Api.LoginAction exposing (loginAction)
import Api.UserInfoAction exposing (userInfoAction)
-- APP
main : Program Never Model Msg
main =
Html.program
{ view = view
, update = update
, init = Model.init
, subscriptions = sub
}
sub : Model -> Sub Msg
sub model =
Sub.batch
[ Ports.fetchedToken Messages.StoredToken
, Ports.loggedOut Messages.LoggedOut
]
-- UPDATE
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
LogIn ->
case model.auth of
Model.LoggedIn token ->
model ! []
Model.LoggedOut formData ->
model ! [ loginAction formData.username formData.password ]
UpdateUsername usr ->
case model.auth of
Model.LoggedIn token ->
model ! []
Model.LoggedOut formData ->
{ model | auth = Model.LoggedOut { formData | username = usr, loginErr = Nothing } } ! []
UpdatePassword pwd ->
case model.auth of
Model.LoggedIn token ->
model ! []
Model.LoggedOut formData ->
{ model | auth = Model.LoggedOut { formData | password = pwd, loginErr = Nothing } } ! []
LoggedIn (Err e) ->
case model.auth of
Model.LoggedIn token ->
{ model | auth = (Model.LoggedOut (Model.LoginFormData "" "" Nothing)) } ! []
Model.LoggedOut formData ->
{ model | auth = Model.LoggedOut { formData | loginErr = Just "login_failed" } } ! []
LoggedIn (Ok token) ->
{ model | auth = Model.LoggedIn token } ! [ Ports.login token, userInfoAction token ]
LogOut ->
model ! [ Ports.logout () ]
LoggedOut () ->
Model.initModel ! []
StoredToken mbyToken ->
case mbyToken of
Just token ->
{ model | auth = Model.LoggedIn token } ! [ userInfoAction token ]
Nothing ->
model ! []
UserInfo (Ok res) ->
{ model | userInfo = Just res } ! []
UserInfo (Err e) ->
model ! []
-- VIEW
view : Model -> Html Msg
view model =
div
[ style
[ ( "margin-top", "30px" )
, ( "text-align", "center" )
]
]
[ div []
[ div []
[ div []
[ View.LoginForm.view model
, p [] [ text ("javaBin membership frontend") ]
]
]
]
]
-- CSS STYLES
styles : { img : List ( String, String ) }
styles =
{ img =
[ ( "width", "33%" )
, ( "border", "4px solid #337AB7" )
]
}
| 40263 | module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import View.LoginForm
import Model exposing (Model)
import Messages exposing (Msg(..))
import Ports
import Api.LoginAction exposing (loginAction)
import Api.UserInfoAction exposing (userInfoAction)
-- APP
main : Program Never Model Msg
main =
Html.program
{ view = view
, update = update
, init = Model.init
, subscriptions = sub
}
sub : Model -> Sub Msg
sub model =
Sub.batch
[ Ports.fetchedToken Messages.StoredToken
, Ports.loggedOut Messages.LoggedOut
]
-- UPDATE
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
LogIn ->
case model.auth of
Model.LoggedIn token ->
model ! []
Model.LoggedOut formData ->
model ! [ loginAction formData.username formData.password ]
UpdateUsername usr ->
case model.auth of
Model.LoggedIn token ->
model ! []
Model.LoggedOut formData ->
{ model | auth = Model.LoggedOut { formData | username = usr, loginErr = Nothing } } ! []
UpdatePassword pwd ->
case model.auth of
Model.LoggedIn token ->
model ! []
Model.LoggedOut formData ->
{ model | auth = Model.LoggedOut { formData | password = <PASSWORD>, loginErr = Nothing } } ! []
LoggedIn (Err e) ->
case model.auth of
Model.LoggedIn token ->
{ model | auth = (Model.LoggedOut (Model.LoginFormData "" "" Nothing)) } ! []
Model.LoggedOut formData ->
{ model | auth = Model.LoggedOut { formData | loginErr = Just "login_failed" } } ! []
LoggedIn (Ok token) ->
{ model | auth = Model.LoggedIn token } ! [ Ports.login token, userInfoAction token ]
LogOut ->
model ! [ Ports.logout () ]
LoggedOut () ->
Model.initModel ! []
StoredToken mbyToken ->
case mbyToken of
Just token ->
{ model | auth = Model.LoggedIn token } ! [ userInfoAction token ]
Nothing ->
model ! []
UserInfo (Ok res) ->
{ model | userInfo = Just res } ! []
UserInfo (Err e) ->
model ! []
-- VIEW
view : Model -> Html Msg
view model =
div
[ style
[ ( "margin-top", "30px" )
, ( "text-align", "center" )
]
]
[ div []
[ div []
[ div []
[ View.LoginForm.view model
, p [] [ text ("javaBin membership frontend") ]
]
]
]
]
-- CSS STYLES
styles : { img : List ( String, String ) }
styles =
{ img =
[ ( "width", "33%" )
, ( "border", "4px solid #337AB7" )
]
}
| true | module Main exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import View.LoginForm
import Model exposing (Model)
import Messages exposing (Msg(..))
import Ports
import Api.LoginAction exposing (loginAction)
import Api.UserInfoAction exposing (userInfoAction)
-- APP
main : Program Never Model Msg
main =
Html.program
{ view = view
, update = update
, init = Model.init
, subscriptions = sub
}
sub : Model -> Sub Msg
sub model =
Sub.batch
[ Ports.fetchedToken Messages.StoredToken
, Ports.loggedOut Messages.LoggedOut
]
-- UPDATE
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
LogIn ->
case model.auth of
Model.LoggedIn token ->
model ! []
Model.LoggedOut formData ->
model ! [ loginAction formData.username formData.password ]
UpdateUsername usr ->
case model.auth of
Model.LoggedIn token ->
model ! []
Model.LoggedOut formData ->
{ model | auth = Model.LoggedOut { formData | username = usr, loginErr = Nothing } } ! []
UpdatePassword pwd ->
case model.auth of
Model.LoggedIn token ->
model ! []
Model.LoggedOut formData ->
{ model | auth = Model.LoggedOut { formData | password = PI:PASSWORD:<PASSWORD>END_PI, loginErr = Nothing } } ! []
LoggedIn (Err e) ->
case model.auth of
Model.LoggedIn token ->
{ model | auth = (Model.LoggedOut (Model.LoginFormData "" "" Nothing)) } ! []
Model.LoggedOut formData ->
{ model | auth = Model.LoggedOut { formData | loginErr = Just "login_failed" } } ! []
LoggedIn (Ok token) ->
{ model | auth = Model.LoggedIn token } ! [ Ports.login token, userInfoAction token ]
LogOut ->
model ! [ Ports.logout () ]
LoggedOut () ->
Model.initModel ! []
StoredToken mbyToken ->
case mbyToken of
Just token ->
{ model | auth = Model.LoggedIn token } ! [ userInfoAction token ]
Nothing ->
model ! []
UserInfo (Ok res) ->
{ model | userInfo = Just res } ! []
UserInfo (Err e) ->
model ! []
-- VIEW
view : Model -> Html Msg
view model =
div
[ style
[ ( "margin-top", "30px" )
, ( "text-align", "center" )
]
]
[ div []
[ div []
[ div []
[ View.LoginForm.view model
, p [] [ text ("javaBin membership frontend") ]
]
]
]
]
-- CSS STYLES
styles : { img : List ( String, String ) }
styles =
{ img =
[ ( "width", "33%" )
, ( "border", "4px solid #337AB7" )
]
}
| elm |
[
{
"context": " \"602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7\"\n\n\n{-| AssetName\n\nproviding context to string\n\n-}",
"end": 4211,
"score": 0.9592301846,
"start": 4192,
"tag": "KEY",
"value": "6b7b16cee7969282de7"
}
] | src/Neo.elm | jam-tech/elm-neo | 0 | module Neo
exposing
( BinaryPrivateKey
, HexPrivateKey
, Wif
, HexPublicKey
, BinaryPublicKey
, PublicKeyHash
, ProgramHash
, Address
, Account
, TransactionData
, Asset
, AssetName
, CoinData
, Transactions
, Transaction
, TransactionId
, AssetId
, SignatureData
, ContractData
, generateBinaryPrivateKey
, generateHexPrivateKey
, getWIFFromBinaryPrivateKey
, getWIFFromHexPrivateKey
, getBinaryPrivateKeyFromWIF
, getHexPrivateKeyFromWIF
, getAccountFromBinaryPrivateKey
, getAccountFromHexPrivateKey
, getAccountFromBinaryPublicKey
, getAccountFromHexPublicKey
, neoAssetId
, gasAssetId
, getTransferData
, getSignatureData
, getContractData
, getBinaryPublicKeyFromHexPrivateKey
, getBinaryPublicKeyFromBinaryPrivateKey
, getHexPublicKeyFromBinaryPrivateKey
, getHexPublicKeyFromHexPrivateKey
, isValidBinaryPublicKey
, isValidHexPublicKey
, isValidAddress
, isValidHexPrivateKey
, isValidBinaryPrivateKey
, isValidWif
, getBinaryPrivateKeyFromHexPrivateKey
, getHexPrivateKeyFromBinaryPrivateKey
, getBinaryPublicKeyFromHexPublicKey
, getHexPublicKeyFromBinaryPublicKey
, encrypt
, decrypt
, encryptAsJson
, decryptAsJson
)
{-| Elm Neo provides tools for the neo wallet and crypto.
@docs BinaryPrivateKey, HexPrivateKey, Wif, HexPublicKey, BinaryPublicKey, generateBinaryPrivateKey, generateHexPrivateKey, getWIFFromBinaryPrivateKey, getWIFFromHexPrivateKey, getBinaryPrivateKeyFromWIF,
PublicKeyHash, ProgramHash, Address, Account, TransactionData, getHexPrivateKeyFromWIF, getAccountFromBinaryPrivateKey, getAccountFromHexPrivateKey, getAccountFromBinaryPublicKey,
getAccountFromHexPublicKey, Asset, AssetName, CoinData, Transactions, Transaction, TransactionId, neoAssetId, gasAssetId, AssetId, getTransferData,
SignatureData, getSignatureData, ContractData, getContractData, getBinaryPublicKeyFromHexPrivateKey,getBinaryPublicKeyFromBinaryPrivateKey,getHexPublicKeyFromBinaryPrivateKey,getHexPublicKeyFromHexPrivateKey,
isValidBinaryPublicKey, isValidHexPublicKey, isValidAddress, isValidHexPrivateKey, isValidBinaryPrivateKey, isValidWif, getBinaryPrivateKeyFromHexPrivateKey, getHexPrivateKeyFromBinaryPrivateKey, getBinaryPublicKeyFromHexPublicKey, getHexPublicKeyFromBinaryPublicKey,
encrypt, decrypt, encryptAsJson, decryptAsJson
-}
import Native.Neo
import Task exposing (Task)
{-| BinaryPrivateKey
providing context to List Int
-}
type alias BinaryPrivateKey =
List Int
{-| HexPrivateKey
providing context to List Int
-}
type alias HexPrivateKey =
String
{-| Wif
providing context to String
-}
type alias Wif =
String
{-| HexPublicKey
providing context to String
-}
type alias HexPublicKey =
String
{-| BinaryPublicKey
providing context to List Int
-}
type alias BinaryPublicKey =
List Int
{-| PublicKeyHash
providing context to String
-}
type alias PublicKeyHash =
String
{-| ProgramHash
providing context to String
-}
type alias ProgramHash =
String
{-| Address
providing context to String
-}
type alias Address =
String
{-| TransactionData
providing context to String
-}
type alias TransactionData =
String
{-| SignatureData
providing context to String
-}
type alias SignatureData =
String
{-| ContractData
providing context to String
-}
type alias ContractData =
String
{-| Asset
providing context to asset
-}
type Asset
= Neo AssetId
| Gas AssetId
{-| AssetId
providing context to string
-}
type alias AssetId =
String
{-| neoAssetId
special assetId for NEO
-}
neoAssetId : AssetId
neoAssetId =
"c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b"
{-| gasAssetId
special assetId for GAS
-}
gasAssetId : AssetId
gasAssetId =
"602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"
{-| AssetName
providing context to string
-}
type alias AssetName =
String
{-| Transactions
cointainer for transactions
-}
type alias Transactions =
List Transaction
{-| TransactionId
providing context to string
-}
type alias TransactionId =
String
{-| Transaction
cointainer for Transaction
-}
type alias Transaction =
{ index : Int
, transactionId : TransactionId
, value : Float
}
{-| CoinData
cointainer for coin data
-}
type alias CoinData =
{ assetId : AssetId
, unspent : Transactions
, balance : Float
, name : AssetName
}
{-| Account
container for wallet info
-}
type alias Account =
{ binaryPrivateKey : BinaryPrivateKey
, hexPrivateKey : HexPrivateKey
, wifPrivateKey : Wif
, binaryPublicKey : BinaryPublicKey
, hexPublicKey : HexPublicKey
, publicKeyHash : PublicKeyHash
, programHash : ProgramHash
, address : Address
}
{-| generateBinaryPrivateKey
uses secure-random to generate a private key
-}
generateBinaryPrivateKey : Task x BinaryPrivateKey
generateBinaryPrivateKey =
Native.Neo.generateBinaryPrivateKey
{-| generateHexPrivateKey
uses secure-random to generate a private key
-}
generateHexPrivateKey : Task x HexPrivateKey
generateHexPrivateKey =
Native.Neo.generateHexPrivateKey
{-| getWIFFromBinaryPrivateKey
gets a WIF from a binary private key
-}
getWIFFromBinaryPrivateKey : BinaryPrivateKey -> Result String Wif
getWIFFromBinaryPrivateKey binaryPrivateKey =
Native.Neo.getWIFFromBinaryPrivateKey binaryPrivateKey
{-| getWIFFromHexPrivateKey
gets a WIF from a hex private key
-}
getWIFFromHexPrivateKey : HexPrivateKey -> Result String Wif
getWIFFromHexPrivateKey hexPrivateKey =
Native.Neo.getWIFFromHexPrivateKey hexPrivateKey
{-| getBinaryPrivateKeyFromWIF
gets a binary private key from a WIF
-}
getBinaryPrivateKeyFromWIF : Wif -> Result String BinaryPrivateKey
getBinaryPrivateKeyFromWIF wif =
Native.Neo.getBinaryPrivateKeyFromWIF wif
{-| getHexPrivateKeyFromWIF
gets a hex private key from a WIF
-}
getHexPrivateKeyFromWIF : Wif -> Result String HexPrivateKey
getHexPrivateKeyFromWIF wif =
Native.Neo.getHexPrivateKeyFromWIF wif
{-| getAccountFromBinaryPrivateKey
gets wallet info from a binary private key
-}
getAccountFromBinaryPrivateKey : BinaryPrivateKey -> Result String Account
getAccountFromBinaryPrivateKey binaryPrivateKey =
Native.Neo.getAccountFromBinaryPrivateKey binaryPrivateKey
{-| getAccountFromBinaryPrivateKey
gets wallet info from a binary private key
-}
getAccountFromHexPrivateKey : HexPrivateKey -> Result String Account
getAccountFromHexPrivateKey hexPrivateKey =
Native.Neo.getAccountFromHexPrivateKey hexPrivateKey
{-| getAccountFromBinaryPublicKey
gets wallet info from a binary public key
-}
getAccountFromBinaryPublicKey : BinaryPublicKey -> Result String Account
getAccountFromBinaryPublicKey binaryPublicKey =
Native.Neo.getAccountFromBinaryPublicKey binaryPublicKey
{-| getAccountFromHexPublicKey
gets wallet info from a hex public key
-}
getAccountFromHexPublicKey : HexPublicKey -> Result String Account
getAccountFromHexPublicKey hexPublicKey =
Native.Neo.getAccountFromHexPublicKey hexPublicKey
{-| getTransferData
gets transaction transfer data
-}
getTransferData : CoinData -> BinaryPublicKey -> Address -> Float -> Result String TransactionData
getTransferData coinData binaryPublicKey toAddress value =
Native.Neo.getTransferData coinData binaryPublicKey toAddress value
{-| getSignatureData
gets signature data
-}
getSignatureData : TransactionData -> BinaryPrivateKey -> Result String SignatureData
getSignatureData transactionData binaryPrivateKey =
Native.Neo.getSignatureData transactionData binaryPrivateKey
{-| getContractData
gets contract data
-}
getContractData : TransactionData -> SignatureData -> BinaryPublicKey -> Result String ContractData
getContractData transactionData signatureData binaryPublicKey =
Native.Neo.getContractData transactionData signatureData binaryPublicKey
{-| getBinaryPublicKeyFromHexPrivateKey
gets a binary public key from a hex private key
-}
getBinaryPublicKeyFromHexPrivateKey : HexPrivateKey -> Bool -> Result String BinaryPublicKey
getBinaryPublicKeyFromHexPrivateKey hexPrivateKey shouldEncode =
Native.Neo.getBinaryPublicKeyFromHexPrivateKey hexPrivateKey shouldEncode
{-| getBinaryPublicKeyFromBinaryPrivateKey
gets a binary public key from a binary private key
-}
getBinaryPublicKeyFromBinaryPrivateKey : BinaryPrivateKey -> Bool -> Result String BinaryPublicKey
getBinaryPublicKeyFromBinaryPrivateKey binaryPrivateKey shouldEncode =
Native.Neo.getBinaryPublicKeyFromBinaryPrivateKey binaryPrivateKey shouldEncode
{-| getHexPublicKeyFromBinaryPrivateKey
gets a hex public key from a binary private key
-}
getHexPublicKeyFromBinaryPrivateKey : BinaryPrivateKey -> Bool -> Result String HexPublicKey
getHexPublicKeyFromBinaryPrivateKey binaryPrivateKey shouldEncode =
Native.Neo.getHexPublicKeyFromBinaryPrivateKey binaryPrivateKey shouldEncode
{-| getHexPublicKeyFromHexPrivateKey
gets a hex public key from a hex private key
-}
getHexPublicKeyFromHexPrivateKey : HexPrivateKey -> Bool -> Result String HexPublicKey
getHexPublicKeyFromHexPrivateKey hexPrivateKey shouldEncode =
Native.Neo.getHexPublicKeyFromHexPrivateKey hexPrivateKey shouldEncode
{-| isValidBinaryPublicKey
checks if binary public key is valid
-}
isValidBinaryPublicKey : BinaryPublicKey -> Bool
isValidBinaryPublicKey binaryPublicKey =
Native.Neo.isValidBinaryPublicKey binaryPublicKey
{-| isValidHexPublicKey
checks if hex public key is valid
-}
isValidHexPublicKey : HexPublicKey -> Bool
isValidHexPublicKey hexPublicKey =
Native.Neo.isValidHexPublicKey hexPublicKey
{-| isValidAddress
check if address is valid
-}
isValidAddress : Address -> Bool
isValidAddress address =
Native.Neo.isValidAddress address
{-| isValidHexPrivateKey
check if address is valid
-}
isValidHexPrivateKey : HexPrivateKey -> Bool
isValidHexPrivateKey hexPrivateKey =
Native.Neo.isValidHexPrivateKey hexPrivateKey
{-| isValidBinaryPrivateKey
check if address is valid
-}
isValidBinaryPrivateKey : BinaryPrivateKey -> Bool
isValidBinaryPrivateKey binaryPrivateKey =
Native.Neo.isValidBinaryPrivateKey binaryPrivateKey
{-| isValidWif
check if wif is valid
-}
isValidWif : Wif -> Bool
isValidWif wif =
Native.Neo.isValidWif wif
{-| getBinaryPrivateKeyFromHexPrivateKey
convert hex private key to binary private key
-}
getBinaryPrivateKeyFromHexPrivateKey : HexPrivateKey -> Result String BinaryPrivateKey
getBinaryPrivateKeyFromHexPrivateKey hexPrivateKey =
Native.Neo.getBinaryPrivateKeyFromHexPrivateKey hexPrivateKey
{-| getHexPrivateKeyFromBinaryPrivateKey
convert binary private key to hex private key
-}
getHexPrivateKeyFromBinaryPrivateKey : BinaryPrivateKey -> Result String HexPrivateKey
getHexPrivateKeyFromBinaryPrivateKey binaryPrivateKey =
Native.Neo.getHexPrivateKeyFromBinaryPrivateKey binaryPrivateKey
{-| getBinaryPublicKeyFromHexPublicKey
convert hex public key to binary public key
-}
getBinaryPublicKeyFromHexPublicKey : HexPublicKey -> Result String BinaryPublicKey
getBinaryPublicKeyFromHexPublicKey hexPublicKey =
Native.Neo.getBinaryPublicKeyFromHexPublicKey hexPublicKey
{-| getHexPublicKeyFromBinaryPublicKey
convert binary public key to hex public key
-}
getHexPublicKeyFromBinaryPublicKey : BinaryPublicKey -> Result String HexPublicKey
getHexPublicKeyFromBinaryPublicKey binaryPublicKey =
Native.Neo.getHexPublicKeyFromBinaryPublicKey binaryPublicKey
{-| encrypt
encrypt a string
-}
encrypt : String -> String -> Result String String
encrypt value password =
Native.Neo.encryptIt value password
{-| decrypt
decrypt a string
-}
decrypt : String -> String -> Result String String
decrypt encrypted password =
Native.Neo.decryptIt encrypted password
{-| encryptAsJson
encryptAsJson a string
-}
encryptAsJson : String -> String -> Result String String
encryptAsJson value password =
Native.Neo.encryptAsJson value password
{-| decryptAsJson
decryptAsJson a string
-}
decryptAsJson : String -> String -> Result String String
decryptAsJson encrypted password =
Native.Neo.decryptAsJson encrypted password
| 786 | module Neo
exposing
( BinaryPrivateKey
, HexPrivateKey
, Wif
, HexPublicKey
, BinaryPublicKey
, PublicKeyHash
, ProgramHash
, Address
, Account
, TransactionData
, Asset
, AssetName
, CoinData
, Transactions
, Transaction
, TransactionId
, AssetId
, SignatureData
, ContractData
, generateBinaryPrivateKey
, generateHexPrivateKey
, getWIFFromBinaryPrivateKey
, getWIFFromHexPrivateKey
, getBinaryPrivateKeyFromWIF
, getHexPrivateKeyFromWIF
, getAccountFromBinaryPrivateKey
, getAccountFromHexPrivateKey
, getAccountFromBinaryPublicKey
, getAccountFromHexPublicKey
, neoAssetId
, gasAssetId
, getTransferData
, getSignatureData
, getContractData
, getBinaryPublicKeyFromHexPrivateKey
, getBinaryPublicKeyFromBinaryPrivateKey
, getHexPublicKeyFromBinaryPrivateKey
, getHexPublicKeyFromHexPrivateKey
, isValidBinaryPublicKey
, isValidHexPublicKey
, isValidAddress
, isValidHexPrivateKey
, isValidBinaryPrivateKey
, isValidWif
, getBinaryPrivateKeyFromHexPrivateKey
, getHexPrivateKeyFromBinaryPrivateKey
, getBinaryPublicKeyFromHexPublicKey
, getHexPublicKeyFromBinaryPublicKey
, encrypt
, decrypt
, encryptAsJson
, decryptAsJson
)
{-| Elm Neo provides tools for the neo wallet and crypto.
@docs BinaryPrivateKey, HexPrivateKey, Wif, HexPublicKey, BinaryPublicKey, generateBinaryPrivateKey, generateHexPrivateKey, getWIFFromBinaryPrivateKey, getWIFFromHexPrivateKey, getBinaryPrivateKeyFromWIF,
PublicKeyHash, ProgramHash, Address, Account, TransactionData, getHexPrivateKeyFromWIF, getAccountFromBinaryPrivateKey, getAccountFromHexPrivateKey, getAccountFromBinaryPublicKey,
getAccountFromHexPublicKey, Asset, AssetName, CoinData, Transactions, Transaction, TransactionId, neoAssetId, gasAssetId, AssetId, getTransferData,
SignatureData, getSignatureData, ContractData, getContractData, getBinaryPublicKeyFromHexPrivateKey,getBinaryPublicKeyFromBinaryPrivateKey,getHexPublicKeyFromBinaryPrivateKey,getHexPublicKeyFromHexPrivateKey,
isValidBinaryPublicKey, isValidHexPublicKey, isValidAddress, isValidHexPrivateKey, isValidBinaryPrivateKey, isValidWif, getBinaryPrivateKeyFromHexPrivateKey, getHexPrivateKeyFromBinaryPrivateKey, getBinaryPublicKeyFromHexPublicKey, getHexPublicKeyFromBinaryPublicKey,
encrypt, decrypt, encryptAsJson, decryptAsJson
-}
import Native.Neo
import Task exposing (Task)
{-| BinaryPrivateKey
providing context to List Int
-}
type alias BinaryPrivateKey =
List Int
{-| HexPrivateKey
providing context to List Int
-}
type alias HexPrivateKey =
String
{-| Wif
providing context to String
-}
type alias Wif =
String
{-| HexPublicKey
providing context to String
-}
type alias HexPublicKey =
String
{-| BinaryPublicKey
providing context to List Int
-}
type alias BinaryPublicKey =
List Int
{-| PublicKeyHash
providing context to String
-}
type alias PublicKeyHash =
String
{-| ProgramHash
providing context to String
-}
type alias ProgramHash =
String
{-| Address
providing context to String
-}
type alias Address =
String
{-| TransactionData
providing context to String
-}
type alias TransactionData =
String
{-| SignatureData
providing context to String
-}
type alias SignatureData =
String
{-| ContractData
providing context to String
-}
type alias ContractData =
String
{-| Asset
providing context to asset
-}
type Asset
= Neo AssetId
| Gas AssetId
{-| AssetId
providing context to string
-}
type alias AssetId =
String
{-| neoAssetId
special assetId for NEO
-}
neoAssetId : AssetId
neoAssetId =
"c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b"
{-| gasAssetId
special assetId for GAS
-}
gasAssetId : AssetId
gasAssetId =
"602c79718b16e442de58778e148d0b1084e3b2dffd5de<KEY>"
{-| AssetName
providing context to string
-}
type alias AssetName =
String
{-| Transactions
cointainer for transactions
-}
type alias Transactions =
List Transaction
{-| TransactionId
providing context to string
-}
type alias TransactionId =
String
{-| Transaction
cointainer for Transaction
-}
type alias Transaction =
{ index : Int
, transactionId : TransactionId
, value : Float
}
{-| CoinData
cointainer for coin data
-}
type alias CoinData =
{ assetId : AssetId
, unspent : Transactions
, balance : Float
, name : AssetName
}
{-| Account
container for wallet info
-}
type alias Account =
{ binaryPrivateKey : BinaryPrivateKey
, hexPrivateKey : HexPrivateKey
, wifPrivateKey : Wif
, binaryPublicKey : BinaryPublicKey
, hexPublicKey : HexPublicKey
, publicKeyHash : PublicKeyHash
, programHash : ProgramHash
, address : Address
}
{-| generateBinaryPrivateKey
uses secure-random to generate a private key
-}
generateBinaryPrivateKey : Task x BinaryPrivateKey
generateBinaryPrivateKey =
Native.Neo.generateBinaryPrivateKey
{-| generateHexPrivateKey
uses secure-random to generate a private key
-}
generateHexPrivateKey : Task x HexPrivateKey
generateHexPrivateKey =
Native.Neo.generateHexPrivateKey
{-| getWIFFromBinaryPrivateKey
gets a WIF from a binary private key
-}
getWIFFromBinaryPrivateKey : BinaryPrivateKey -> Result String Wif
getWIFFromBinaryPrivateKey binaryPrivateKey =
Native.Neo.getWIFFromBinaryPrivateKey binaryPrivateKey
{-| getWIFFromHexPrivateKey
gets a WIF from a hex private key
-}
getWIFFromHexPrivateKey : HexPrivateKey -> Result String Wif
getWIFFromHexPrivateKey hexPrivateKey =
Native.Neo.getWIFFromHexPrivateKey hexPrivateKey
{-| getBinaryPrivateKeyFromWIF
gets a binary private key from a WIF
-}
getBinaryPrivateKeyFromWIF : Wif -> Result String BinaryPrivateKey
getBinaryPrivateKeyFromWIF wif =
Native.Neo.getBinaryPrivateKeyFromWIF wif
{-| getHexPrivateKeyFromWIF
gets a hex private key from a WIF
-}
getHexPrivateKeyFromWIF : Wif -> Result String HexPrivateKey
getHexPrivateKeyFromWIF wif =
Native.Neo.getHexPrivateKeyFromWIF wif
{-| getAccountFromBinaryPrivateKey
gets wallet info from a binary private key
-}
getAccountFromBinaryPrivateKey : BinaryPrivateKey -> Result String Account
getAccountFromBinaryPrivateKey binaryPrivateKey =
Native.Neo.getAccountFromBinaryPrivateKey binaryPrivateKey
{-| getAccountFromBinaryPrivateKey
gets wallet info from a binary private key
-}
getAccountFromHexPrivateKey : HexPrivateKey -> Result String Account
getAccountFromHexPrivateKey hexPrivateKey =
Native.Neo.getAccountFromHexPrivateKey hexPrivateKey
{-| getAccountFromBinaryPublicKey
gets wallet info from a binary public key
-}
getAccountFromBinaryPublicKey : BinaryPublicKey -> Result String Account
getAccountFromBinaryPublicKey binaryPublicKey =
Native.Neo.getAccountFromBinaryPublicKey binaryPublicKey
{-| getAccountFromHexPublicKey
gets wallet info from a hex public key
-}
getAccountFromHexPublicKey : HexPublicKey -> Result String Account
getAccountFromHexPublicKey hexPublicKey =
Native.Neo.getAccountFromHexPublicKey hexPublicKey
{-| getTransferData
gets transaction transfer data
-}
getTransferData : CoinData -> BinaryPublicKey -> Address -> Float -> Result String TransactionData
getTransferData coinData binaryPublicKey toAddress value =
Native.Neo.getTransferData coinData binaryPublicKey toAddress value
{-| getSignatureData
gets signature data
-}
getSignatureData : TransactionData -> BinaryPrivateKey -> Result String SignatureData
getSignatureData transactionData binaryPrivateKey =
Native.Neo.getSignatureData transactionData binaryPrivateKey
{-| getContractData
gets contract data
-}
getContractData : TransactionData -> SignatureData -> BinaryPublicKey -> Result String ContractData
getContractData transactionData signatureData binaryPublicKey =
Native.Neo.getContractData transactionData signatureData binaryPublicKey
{-| getBinaryPublicKeyFromHexPrivateKey
gets a binary public key from a hex private key
-}
getBinaryPublicKeyFromHexPrivateKey : HexPrivateKey -> Bool -> Result String BinaryPublicKey
getBinaryPublicKeyFromHexPrivateKey hexPrivateKey shouldEncode =
Native.Neo.getBinaryPublicKeyFromHexPrivateKey hexPrivateKey shouldEncode
{-| getBinaryPublicKeyFromBinaryPrivateKey
gets a binary public key from a binary private key
-}
getBinaryPublicKeyFromBinaryPrivateKey : BinaryPrivateKey -> Bool -> Result String BinaryPublicKey
getBinaryPublicKeyFromBinaryPrivateKey binaryPrivateKey shouldEncode =
Native.Neo.getBinaryPublicKeyFromBinaryPrivateKey binaryPrivateKey shouldEncode
{-| getHexPublicKeyFromBinaryPrivateKey
gets a hex public key from a binary private key
-}
getHexPublicKeyFromBinaryPrivateKey : BinaryPrivateKey -> Bool -> Result String HexPublicKey
getHexPublicKeyFromBinaryPrivateKey binaryPrivateKey shouldEncode =
Native.Neo.getHexPublicKeyFromBinaryPrivateKey binaryPrivateKey shouldEncode
{-| getHexPublicKeyFromHexPrivateKey
gets a hex public key from a hex private key
-}
getHexPublicKeyFromHexPrivateKey : HexPrivateKey -> Bool -> Result String HexPublicKey
getHexPublicKeyFromHexPrivateKey hexPrivateKey shouldEncode =
Native.Neo.getHexPublicKeyFromHexPrivateKey hexPrivateKey shouldEncode
{-| isValidBinaryPublicKey
checks if binary public key is valid
-}
isValidBinaryPublicKey : BinaryPublicKey -> Bool
isValidBinaryPublicKey binaryPublicKey =
Native.Neo.isValidBinaryPublicKey binaryPublicKey
{-| isValidHexPublicKey
checks if hex public key is valid
-}
isValidHexPublicKey : HexPublicKey -> Bool
isValidHexPublicKey hexPublicKey =
Native.Neo.isValidHexPublicKey hexPublicKey
{-| isValidAddress
check if address is valid
-}
isValidAddress : Address -> Bool
isValidAddress address =
Native.Neo.isValidAddress address
{-| isValidHexPrivateKey
check if address is valid
-}
isValidHexPrivateKey : HexPrivateKey -> Bool
isValidHexPrivateKey hexPrivateKey =
Native.Neo.isValidHexPrivateKey hexPrivateKey
{-| isValidBinaryPrivateKey
check if address is valid
-}
isValidBinaryPrivateKey : BinaryPrivateKey -> Bool
isValidBinaryPrivateKey binaryPrivateKey =
Native.Neo.isValidBinaryPrivateKey binaryPrivateKey
{-| isValidWif
check if wif is valid
-}
isValidWif : Wif -> Bool
isValidWif wif =
Native.Neo.isValidWif wif
{-| getBinaryPrivateKeyFromHexPrivateKey
convert hex private key to binary private key
-}
getBinaryPrivateKeyFromHexPrivateKey : HexPrivateKey -> Result String BinaryPrivateKey
getBinaryPrivateKeyFromHexPrivateKey hexPrivateKey =
Native.Neo.getBinaryPrivateKeyFromHexPrivateKey hexPrivateKey
{-| getHexPrivateKeyFromBinaryPrivateKey
convert binary private key to hex private key
-}
getHexPrivateKeyFromBinaryPrivateKey : BinaryPrivateKey -> Result String HexPrivateKey
getHexPrivateKeyFromBinaryPrivateKey binaryPrivateKey =
Native.Neo.getHexPrivateKeyFromBinaryPrivateKey binaryPrivateKey
{-| getBinaryPublicKeyFromHexPublicKey
convert hex public key to binary public key
-}
getBinaryPublicKeyFromHexPublicKey : HexPublicKey -> Result String BinaryPublicKey
getBinaryPublicKeyFromHexPublicKey hexPublicKey =
Native.Neo.getBinaryPublicKeyFromHexPublicKey hexPublicKey
{-| getHexPublicKeyFromBinaryPublicKey
convert binary public key to hex public key
-}
getHexPublicKeyFromBinaryPublicKey : BinaryPublicKey -> Result String HexPublicKey
getHexPublicKeyFromBinaryPublicKey binaryPublicKey =
Native.Neo.getHexPublicKeyFromBinaryPublicKey binaryPublicKey
{-| encrypt
encrypt a string
-}
encrypt : String -> String -> Result String String
encrypt value password =
Native.Neo.encryptIt value password
{-| decrypt
decrypt a string
-}
decrypt : String -> String -> Result String String
decrypt encrypted password =
Native.Neo.decryptIt encrypted password
{-| encryptAsJson
encryptAsJson a string
-}
encryptAsJson : String -> String -> Result String String
encryptAsJson value password =
Native.Neo.encryptAsJson value password
{-| decryptAsJson
decryptAsJson a string
-}
decryptAsJson : String -> String -> Result String String
decryptAsJson encrypted password =
Native.Neo.decryptAsJson encrypted password
| true | module Neo
exposing
( BinaryPrivateKey
, HexPrivateKey
, Wif
, HexPublicKey
, BinaryPublicKey
, PublicKeyHash
, ProgramHash
, Address
, Account
, TransactionData
, Asset
, AssetName
, CoinData
, Transactions
, Transaction
, TransactionId
, AssetId
, SignatureData
, ContractData
, generateBinaryPrivateKey
, generateHexPrivateKey
, getWIFFromBinaryPrivateKey
, getWIFFromHexPrivateKey
, getBinaryPrivateKeyFromWIF
, getHexPrivateKeyFromWIF
, getAccountFromBinaryPrivateKey
, getAccountFromHexPrivateKey
, getAccountFromBinaryPublicKey
, getAccountFromHexPublicKey
, neoAssetId
, gasAssetId
, getTransferData
, getSignatureData
, getContractData
, getBinaryPublicKeyFromHexPrivateKey
, getBinaryPublicKeyFromBinaryPrivateKey
, getHexPublicKeyFromBinaryPrivateKey
, getHexPublicKeyFromHexPrivateKey
, isValidBinaryPublicKey
, isValidHexPublicKey
, isValidAddress
, isValidHexPrivateKey
, isValidBinaryPrivateKey
, isValidWif
, getBinaryPrivateKeyFromHexPrivateKey
, getHexPrivateKeyFromBinaryPrivateKey
, getBinaryPublicKeyFromHexPublicKey
, getHexPublicKeyFromBinaryPublicKey
, encrypt
, decrypt
, encryptAsJson
, decryptAsJson
)
{-| Elm Neo provides tools for the neo wallet and crypto.
@docs BinaryPrivateKey, HexPrivateKey, Wif, HexPublicKey, BinaryPublicKey, generateBinaryPrivateKey, generateHexPrivateKey, getWIFFromBinaryPrivateKey, getWIFFromHexPrivateKey, getBinaryPrivateKeyFromWIF,
PublicKeyHash, ProgramHash, Address, Account, TransactionData, getHexPrivateKeyFromWIF, getAccountFromBinaryPrivateKey, getAccountFromHexPrivateKey, getAccountFromBinaryPublicKey,
getAccountFromHexPublicKey, Asset, AssetName, CoinData, Transactions, Transaction, TransactionId, neoAssetId, gasAssetId, AssetId, getTransferData,
SignatureData, getSignatureData, ContractData, getContractData, getBinaryPublicKeyFromHexPrivateKey,getBinaryPublicKeyFromBinaryPrivateKey,getHexPublicKeyFromBinaryPrivateKey,getHexPublicKeyFromHexPrivateKey,
isValidBinaryPublicKey, isValidHexPublicKey, isValidAddress, isValidHexPrivateKey, isValidBinaryPrivateKey, isValidWif, getBinaryPrivateKeyFromHexPrivateKey, getHexPrivateKeyFromBinaryPrivateKey, getBinaryPublicKeyFromHexPublicKey, getHexPublicKeyFromBinaryPublicKey,
encrypt, decrypt, encryptAsJson, decryptAsJson
-}
import Native.Neo
import Task exposing (Task)
{-| BinaryPrivateKey
providing context to List Int
-}
type alias BinaryPrivateKey =
List Int
{-| HexPrivateKey
providing context to List Int
-}
type alias HexPrivateKey =
String
{-| Wif
providing context to String
-}
type alias Wif =
String
{-| HexPublicKey
providing context to String
-}
type alias HexPublicKey =
String
{-| BinaryPublicKey
providing context to List Int
-}
type alias BinaryPublicKey =
List Int
{-| PublicKeyHash
providing context to String
-}
type alias PublicKeyHash =
String
{-| ProgramHash
providing context to String
-}
type alias ProgramHash =
String
{-| Address
providing context to String
-}
type alias Address =
String
{-| TransactionData
providing context to String
-}
type alias TransactionData =
String
{-| SignatureData
providing context to String
-}
type alias SignatureData =
String
{-| ContractData
providing context to String
-}
type alias ContractData =
String
{-| Asset
providing context to asset
-}
type Asset
= Neo AssetId
| Gas AssetId
{-| AssetId
providing context to string
-}
type alias AssetId =
String
{-| neoAssetId
special assetId for NEO
-}
neoAssetId : AssetId
neoAssetId =
"c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b"
{-| gasAssetId
special assetId for GAS
-}
gasAssetId : AssetId
gasAssetId =
"602c79718b16e442de58778e148d0b1084e3b2dffd5dePI:KEY:<KEY>END_PI"
{-| AssetName
providing context to string
-}
type alias AssetName =
String
{-| Transactions
cointainer for transactions
-}
type alias Transactions =
List Transaction
{-| TransactionId
providing context to string
-}
type alias TransactionId =
String
{-| Transaction
cointainer for Transaction
-}
type alias Transaction =
{ index : Int
, transactionId : TransactionId
, value : Float
}
{-| CoinData
cointainer for coin data
-}
type alias CoinData =
{ assetId : AssetId
, unspent : Transactions
, balance : Float
, name : AssetName
}
{-| Account
container for wallet info
-}
type alias Account =
{ binaryPrivateKey : BinaryPrivateKey
, hexPrivateKey : HexPrivateKey
, wifPrivateKey : Wif
, binaryPublicKey : BinaryPublicKey
, hexPublicKey : HexPublicKey
, publicKeyHash : PublicKeyHash
, programHash : ProgramHash
, address : Address
}
{-| generateBinaryPrivateKey
uses secure-random to generate a private key
-}
generateBinaryPrivateKey : Task x BinaryPrivateKey
generateBinaryPrivateKey =
Native.Neo.generateBinaryPrivateKey
{-| generateHexPrivateKey
uses secure-random to generate a private key
-}
generateHexPrivateKey : Task x HexPrivateKey
generateHexPrivateKey =
Native.Neo.generateHexPrivateKey
{-| getWIFFromBinaryPrivateKey
gets a WIF from a binary private key
-}
getWIFFromBinaryPrivateKey : BinaryPrivateKey -> Result String Wif
getWIFFromBinaryPrivateKey binaryPrivateKey =
Native.Neo.getWIFFromBinaryPrivateKey binaryPrivateKey
{-| getWIFFromHexPrivateKey
gets a WIF from a hex private key
-}
getWIFFromHexPrivateKey : HexPrivateKey -> Result String Wif
getWIFFromHexPrivateKey hexPrivateKey =
Native.Neo.getWIFFromHexPrivateKey hexPrivateKey
{-| getBinaryPrivateKeyFromWIF
gets a binary private key from a WIF
-}
getBinaryPrivateKeyFromWIF : Wif -> Result String BinaryPrivateKey
getBinaryPrivateKeyFromWIF wif =
Native.Neo.getBinaryPrivateKeyFromWIF wif
{-| getHexPrivateKeyFromWIF
gets a hex private key from a WIF
-}
getHexPrivateKeyFromWIF : Wif -> Result String HexPrivateKey
getHexPrivateKeyFromWIF wif =
Native.Neo.getHexPrivateKeyFromWIF wif
{-| getAccountFromBinaryPrivateKey
gets wallet info from a binary private key
-}
getAccountFromBinaryPrivateKey : BinaryPrivateKey -> Result String Account
getAccountFromBinaryPrivateKey binaryPrivateKey =
Native.Neo.getAccountFromBinaryPrivateKey binaryPrivateKey
{-| getAccountFromBinaryPrivateKey
gets wallet info from a binary private key
-}
getAccountFromHexPrivateKey : HexPrivateKey -> Result String Account
getAccountFromHexPrivateKey hexPrivateKey =
Native.Neo.getAccountFromHexPrivateKey hexPrivateKey
{-| getAccountFromBinaryPublicKey
gets wallet info from a binary public key
-}
getAccountFromBinaryPublicKey : BinaryPublicKey -> Result String Account
getAccountFromBinaryPublicKey binaryPublicKey =
Native.Neo.getAccountFromBinaryPublicKey binaryPublicKey
{-| getAccountFromHexPublicKey
gets wallet info from a hex public key
-}
getAccountFromHexPublicKey : HexPublicKey -> Result String Account
getAccountFromHexPublicKey hexPublicKey =
Native.Neo.getAccountFromHexPublicKey hexPublicKey
{-| getTransferData
gets transaction transfer data
-}
getTransferData : CoinData -> BinaryPublicKey -> Address -> Float -> Result String TransactionData
getTransferData coinData binaryPublicKey toAddress value =
Native.Neo.getTransferData coinData binaryPublicKey toAddress value
{-| getSignatureData
gets signature data
-}
getSignatureData : TransactionData -> BinaryPrivateKey -> Result String SignatureData
getSignatureData transactionData binaryPrivateKey =
Native.Neo.getSignatureData transactionData binaryPrivateKey
{-| getContractData
gets contract data
-}
getContractData : TransactionData -> SignatureData -> BinaryPublicKey -> Result String ContractData
getContractData transactionData signatureData binaryPublicKey =
Native.Neo.getContractData transactionData signatureData binaryPublicKey
{-| getBinaryPublicKeyFromHexPrivateKey
gets a binary public key from a hex private key
-}
getBinaryPublicKeyFromHexPrivateKey : HexPrivateKey -> Bool -> Result String BinaryPublicKey
getBinaryPublicKeyFromHexPrivateKey hexPrivateKey shouldEncode =
Native.Neo.getBinaryPublicKeyFromHexPrivateKey hexPrivateKey shouldEncode
{-| getBinaryPublicKeyFromBinaryPrivateKey
gets a binary public key from a binary private key
-}
getBinaryPublicKeyFromBinaryPrivateKey : BinaryPrivateKey -> Bool -> Result String BinaryPublicKey
getBinaryPublicKeyFromBinaryPrivateKey binaryPrivateKey shouldEncode =
Native.Neo.getBinaryPublicKeyFromBinaryPrivateKey binaryPrivateKey shouldEncode
{-| getHexPublicKeyFromBinaryPrivateKey
gets a hex public key from a binary private key
-}
getHexPublicKeyFromBinaryPrivateKey : BinaryPrivateKey -> Bool -> Result String HexPublicKey
getHexPublicKeyFromBinaryPrivateKey binaryPrivateKey shouldEncode =
Native.Neo.getHexPublicKeyFromBinaryPrivateKey binaryPrivateKey shouldEncode
{-| getHexPublicKeyFromHexPrivateKey
gets a hex public key from a hex private key
-}
getHexPublicKeyFromHexPrivateKey : HexPrivateKey -> Bool -> Result String HexPublicKey
getHexPublicKeyFromHexPrivateKey hexPrivateKey shouldEncode =
Native.Neo.getHexPublicKeyFromHexPrivateKey hexPrivateKey shouldEncode
{-| isValidBinaryPublicKey
checks if binary public key is valid
-}
isValidBinaryPublicKey : BinaryPublicKey -> Bool
isValidBinaryPublicKey binaryPublicKey =
Native.Neo.isValidBinaryPublicKey binaryPublicKey
{-| isValidHexPublicKey
checks if hex public key is valid
-}
isValidHexPublicKey : HexPublicKey -> Bool
isValidHexPublicKey hexPublicKey =
Native.Neo.isValidHexPublicKey hexPublicKey
{-| isValidAddress
check if address is valid
-}
isValidAddress : Address -> Bool
isValidAddress address =
Native.Neo.isValidAddress address
{-| isValidHexPrivateKey
check if address is valid
-}
isValidHexPrivateKey : HexPrivateKey -> Bool
isValidHexPrivateKey hexPrivateKey =
Native.Neo.isValidHexPrivateKey hexPrivateKey
{-| isValidBinaryPrivateKey
check if address is valid
-}
isValidBinaryPrivateKey : BinaryPrivateKey -> Bool
isValidBinaryPrivateKey binaryPrivateKey =
Native.Neo.isValidBinaryPrivateKey binaryPrivateKey
{-| isValidWif
check if wif is valid
-}
isValidWif : Wif -> Bool
isValidWif wif =
Native.Neo.isValidWif wif
{-| getBinaryPrivateKeyFromHexPrivateKey
convert hex private key to binary private key
-}
getBinaryPrivateKeyFromHexPrivateKey : HexPrivateKey -> Result String BinaryPrivateKey
getBinaryPrivateKeyFromHexPrivateKey hexPrivateKey =
Native.Neo.getBinaryPrivateKeyFromHexPrivateKey hexPrivateKey
{-| getHexPrivateKeyFromBinaryPrivateKey
convert binary private key to hex private key
-}
getHexPrivateKeyFromBinaryPrivateKey : BinaryPrivateKey -> Result String HexPrivateKey
getHexPrivateKeyFromBinaryPrivateKey binaryPrivateKey =
Native.Neo.getHexPrivateKeyFromBinaryPrivateKey binaryPrivateKey
{-| getBinaryPublicKeyFromHexPublicKey
convert hex public key to binary public key
-}
getBinaryPublicKeyFromHexPublicKey : HexPublicKey -> Result String BinaryPublicKey
getBinaryPublicKeyFromHexPublicKey hexPublicKey =
Native.Neo.getBinaryPublicKeyFromHexPublicKey hexPublicKey
{-| getHexPublicKeyFromBinaryPublicKey
convert binary public key to hex public key
-}
getHexPublicKeyFromBinaryPublicKey : BinaryPublicKey -> Result String HexPublicKey
getHexPublicKeyFromBinaryPublicKey binaryPublicKey =
Native.Neo.getHexPublicKeyFromBinaryPublicKey binaryPublicKey
{-| encrypt
encrypt a string
-}
encrypt : String -> String -> Result String String
encrypt value password =
Native.Neo.encryptIt value password
{-| decrypt
decrypt a string
-}
decrypt : String -> String -> Result String String
decrypt encrypted password =
Native.Neo.decryptIt encrypted password
{-| encryptAsJson
encryptAsJson a string
-}
encryptAsJson : String -> String -> Result String String
encryptAsJson value password =
Native.Neo.encryptAsJson value password
{-| decryptAsJson
decryptAsJson a string
-}
decryptAsJson : String -> String -> Result String String
decryptAsJson encrypted password =
Native.Neo.decryptAsJson encrypted password
| elm |
[
{
"context": "lm\n-- Types used everywhere.\n-- Copyright (c) 2018 Bill St. Clair <billstclair@gmail.com>\n-- Some rights reserved.\n",
"end": 152,
"score": 0.9998701215,
"start": 138,
"tag": "NAME",
"value": "Bill St. Clair"
},
{
"context": "everywhere.\n-- Copyright (c) 2018 Bill St. Clair <billstclair@gmail.com>\n-- Some rights reserved.\n-- Distributed under th",
"end": 175,
"score": 0.9999332428,
"start": 154,
"tag": "EMAIL",
"value": "billstclair@gmail.com"
}
] | src/JSMaze/TwoDMath.elm | billstclair/elm-jsmaze | 6 | ----------------------------------------------------------------------
--
-- TwoDMath.elm
-- Types used everywhere.
-- Copyright (c) 2018 Bill St. Clair <billstclair@gmail.com>
-- Some rights reserved.
-- Distributed under the MIT License
-- See LICENSE.txt
--
----------------------------------------------------------------------
module JSMaze.TwoDMath
exposing
( Rectangle
, Vector
, combineVectors
, distanceToRectangle
, isVectorInRectangle
, makeRectangle
, makeSize
, makeVector
, positionToVector
, rectangleCenter
, rectangleCoordinates
, rectangleFromVectors
, sizeToVector
, vectorCoordinates
, vectorDifference
, vectorDistance
, vectorSum
, zeroRectangle
, zeroVector
)
import Mouse exposing (Position)
import Window exposing (Size)
type alias Vector =
{ x : Float
, y : Float
}
makeVector : Float -> Float -> Vector
makeVector x y =
{ x = x, y = y }
vectorCoordinates : Vector -> ( Float, Float )
vectorCoordinates vector =
( vector.x, vector.y )
sizeToVector : Size -> Vector
sizeToVector size =
makeVector (toFloat size.width) (toFloat size.height)
positionToVector : Position -> Vector
positionToVector pos =
makeVector (toFloat pos.x) (toFloat pos.y)
zeroVector : Vector
zeroVector =
makeVector 0 0
combineVectors : (Float -> Float -> Float) -> Vector -> Vector -> Vector
combineVectors f v1 v2 =
makeVector (f v1.x v2.x) (f v1.y v2.y)
vectorSum =
combineVectors (+)
vectorDifference =
combineVectors (-)
vectorDistance : Vector -> Vector -> Float
vectorDistance v1 v2 =
let
diff =
vectorDifference v1 v2
in
sqrt (diff.x ^ 2 + diff.y ^ 2)
type alias Rectangle =
{ pos : Vector --top-left corner
, size : Vector
}
{-| Result is (left, top, right bottom)
-}
rectangleCoordinates : Rectangle -> ( Float, Float, Float, Float )
rectangleCoordinates rect =
let
pos =
rect.pos
size =
rect.size
left =
pos.x
top =
pos.y
right =
left + size.x
bottom =
top + size.y
in
( left, top, right, bottom )
makeRectangle : Float -> Float -> Float -> Float -> Rectangle
makeRectangle left top width height =
rectangleFromVectors
(makeVector left top)
(makeVector width height)
rectangleFromVectors : Vector -> Vector -> Rectangle
rectangleFromVectors pos size =
{ pos = pos
, size = size
}
zeroRectangle : Rectangle
zeroRectangle =
rectangleFromVectors zeroVector zeroVector
rectangleCenter : Rectangle -> Vector
rectangleCenter rect =
let
( left, top, right, bottom ) =
rectangleCoordinates rect
in
makeVector ((left + right) / 2) ((top + bottom) / 2)
distanceToRectangle : Vector -> Rectangle -> Float
distanceToRectangle vect rect =
let
center =
rectangleCenter rect
in
vectorDistance vect center
isVectorInRectangle : Vector -> Rectangle -> Bool
isVectorInRectangle vect rect =
let
( left, top, right, bottom ) =
rectangleCoordinates rect
( x, y ) =
vectorCoordinates vect
in
x >= left && x <= right && y >= top && y <= bottom
makeSize : Int -> Int -> Size
makeSize w h =
{ width = w, height = h }
| 13415 | ----------------------------------------------------------------------
--
-- TwoDMath.elm
-- Types used everywhere.
-- Copyright (c) 2018 <NAME> <<EMAIL>>
-- Some rights reserved.
-- Distributed under the MIT License
-- See LICENSE.txt
--
----------------------------------------------------------------------
module JSMaze.TwoDMath
exposing
( Rectangle
, Vector
, combineVectors
, distanceToRectangle
, isVectorInRectangle
, makeRectangle
, makeSize
, makeVector
, positionToVector
, rectangleCenter
, rectangleCoordinates
, rectangleFromVectors
, sizeToVector
, vectorCoordinates
, vectorDifference
, vectorDistance
, vectorSum
, zeroRectangle
, zeroVector
)
import Mouse exposing (Position)
import Window exposing (Size)
type alias Vector =
{ x : Float
, y : Float
}
makeVector : Float -> Float -> Vector
makeVector x y =
{ x = x, y = y }
vectorCoordinates : Vector -> ( Float, Float )
vectorCoordinates vector =
( vector.x, vector.y )
sizeToVector : Size -> Vector
sizeToVector size =
makeVector (toFloat size.width) (toFloat size.height)
positionToVector : Position -> Vector
positionToVector pos =
makeVector (toFloat pos.x) (toFloat pos.y)
zeroVector : Vector
zeroVector =
makeVector 0 0
combineVectors : (Float -> Float -> Float) -> Vector -> Vector -> Vector
combineVectors f v1 v2 =
makeVector (f v1.x v2.x) (f v1.y v2.y)
vectorSum =
combineVectors (+)
vectorDifference =
combineVectors (-)
vectorDistance : Vector -> Vector -> Float
vectorDistance v1 v2 =
let
diff =
vectorDifference v1 v2
in
sqrt (diff.x ^ 2 + diff.y ^ 2)
type alias Rectangle =
{ pos : Vector --top-left corner
, size : Vector
}
{-| Result is (left, top, right bottom)
-}
rectangleCoordinates : Rectangle -> ( Float, Float, Float, Float )
rectangleCoordinates rect =
let
pos =
rect.pos
size =
rect.size
left =
pos.x
top =
pos.y
right =
left + size.x
bottom =
top + size.y
in
( left, top, right, bottom )
makeRectangle : Float -> Float -> Float -> Float -> Rectangle
makeRectangle left top width height =
rectangleFromVectors
(makeVector left top)
(makeVector width height)
rectangleFromVectors : Vector -> Vector -> Rectangle
rectangleFromVectors pos size =
{ pos = pos
, size = size
}
zeroRectangle : Rectangle
zeroRectangle =
rectangleFromVectors zeroVector zeroVector
rectangleCenter : Rectangle -> Vector
rectangleCenter rect =
let
( left, top, right, bottom ) =
rectangleCoordinates rect
in
makeVector ((left + right) / 2) ((top + bottom) / 2)
distanceToRectangle : Vector -> Rectangle -> Float
distanceToRectangle vect rect =
let
center =
rectangleCenter rect
in
vectorDistance vect center
isVectorInRectangle : Vector -> Rectangle -> Bool
isVectorInRectangle vect rect =
let
( left, top, right, bottom ) =
rectangleCoordinates rect
( x, y ) =
vectorCoordinates vect
in
x >= left && x <= right && y >= top && y <= bottom
makeSize : Int -> Int -> Size
makeSize w h =
{ width = w, height = h }
| true | ----------------------------------------------------------------------
--
-- TwoDMath.elm
-- Types used everywhere.
-- Copyright (c) 2018 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
-- Some rights reserved.
-- Distributed under the MIT License
-- See LICENSE.txt
--
----------------------------------------------------------------------
module JSMaze.TwoDMath
exposing
( Rectangle
, Vector
, combineVectors
, distanceToRectangle
, isVectorInRectangle
, makeRectangle
, makeSize
, makeVector
, positionToVector
, rectangleCenter
, rectangleCoordinates
, rectangleFromVectors
, sizeToVector
, vectorCoordinates
, vectorDifference
, vectorDistance
, vectorSum
, zeroRectangle
, zeroVector
)
import Mouse exposing (Position)
import Window exposing (Size)
type alias Vector =
{ x : Float
, y : Float
}
makeVector : Float -> Float -> Vector
makeVector x y =
{ x = x, y = y }
vectorCoordinates : Vector -> ( Float, Float )
vectorCoordinates vector =
( vector.x, vector.y )
sizeToVector : Size -> Vector
sizeToVector size =
makeVector (toFloat size.width) (toFloat size.height)
positionToVector : Position -> Vector
positionToVector pos =
makeVector (toFloat pos.x) (toFloat pos.y)
zeroVector : Vector
zeroVector =
makeVector 0 0
combineVectors : (Float -> Float -> Float) -> Vector -> Vector -> Vector
combineVectors f v1 v2 =
makeVector (f v1.x v2.x) (f v1.y v2.y)
vectorSum =
combineVectors (+)
vectorDifference =
combineVectors (-)
vectorDistance : Vector -> Vector -> Float
vectorDistance v1 v2 =
let
diff =
vectorDifference v1 v2
in
sqrt (diff.x ^ 2 + diff.y ^ 2)
type alias Rectangle =
{ pos : Vector --top-left corner
, size : Vector
}
{-| Result is (left, top, right bottom)
-}
rectangleCoordinates : Rectangle -> ( Float, Float, Float, Float )
rectangleCoordinates rect =
let
pos =
rect.pos
size =
rect.size
left =
pos.x
top =
pos.y
right =
left + size.x
bottom =
top + size.y
in
( left, top, right, bottom )
makeRectangle : Float -> Float -> Float -> Float -> Rectangle
makeRectangle left top width height =
rectangleFromVectors
(makeVector left top)
(makeVector width height)
rectangleFromVectors : Vector -> Vector -> Rectangle
rectangleFromVectors pos size =
{ pos = pos
, size = size
}
zeroRectangle : Rectangle
zeroRectangle =
rectangleFromVectors zeroVector zeroVector
rectangleCenter : Rectangle -> Vector
rectangleCenter rect =
let
( left, top, right, bottom ) =
rectangleCoordinates rect
in
makeVector ((left + right) / 2) ((top + bottom) / 2)
distanceToRectangle : Vector -> Rectangle -> Float
distanceToRectangle vect rect =
let
center =
rectangleCenter rect
in
vectorDistance vect center
isVectorInRectangle : Vector -> Rectangle -> Bool
isVectorInRectangle vect rect =
let
( left, top, right, bottom ) =
rectangleCoordinates rect
( x, y ) =
vectorCoordinates vect
in
x >= left && x <= right && y >= top && y <= bottom
makeSize : Int -> Int -> Size
makeSize w h =
{ width = w, height = h }
| elm |
[
{
"context": "{-\nCopyright 2020 Morgan Stanley\n\nLicensed under the Apache License, Version 2.0 (",
"end": 32,
"score": 0.9997752905,
"start": 18,
"tag": "NAME",
"value": "Morgan Stanley"
}
] | draft/DevBot/Scala/AST.elm | aszenz/morphir-elm | 6 | {-
Copyright 2020 Morgan Stanley
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module SlateX.DevBot.Scala.AST exposing (..)
type alias Name = String
type alias Path = List Name
type alias CompilationUnit =
{ dirPath : List String
, fileName : String
, packageDecl : PackageDecl
, imports : List ImportDecl
, typeDecls : List TypeDecl
}
type alias PackageDecl = List String
type alias ImportDecl =
{ isAbsolute : Bool
, packagePrefix : List String
, importNames : List ImportName
}
type ImportName
= ImportName String
| ImportRename String String
type Mod
= Sealed
| Final
| Case
| Val
| Package
| Implicit
type TypeDecl
= Trait
{ modifiers : List Mod
, name : Name
, typeArgs : List Type
, extends : List Type
, members : List MemberDecl
}
| Class
{ modifiers : List Mod
, name : Name
, typeArgs : List Type
, ctorArgs : List (List ArgDecl)
, extends : List Type
}
| Object
{ modifiers : List Mod
, name : Name
, extends : List Type
, members : List MemberDecl
}
type alias ArgDecl =
{ modifiers : List Mod
, tpe : Type
, name : Name
, defaultValue : Maybe Value
}
type alias ArgValue =
{ name : Maybe Name
, value : Value
}
type MemberDecl
= TypeAlias
{ alias : Name
, typeArgs : (List Type)
, tpe : Type
}
| FunctionDecl
{ modifiers : List Mod
, name : Name
, typeArgs : List Type
, args : List (List ArgDecl)
, returnType : Maybe Type
, body : Maybe Value
}
| MemberTypeDecl TypeDecl
type Type
= TypeVar Name
| TypeRef Path Name
| TypeApply Type (List Type)
| TupleType (List Type)
| StructuralType (List MemberDecl)
| FunctionType Type Type
| CommentedType Type String
type Value
= Literal Lit
| Var Name
| Ref Path Name
| Select Value Name
| Wildcard
| Apply Value (List ArgValue)
| UnOp String Value
| BinOp Value String Value
| Lambda (List Name) Value
| LetBlock (List ( Pattern, Value )) Value
| MatchCases (List ( Pattern, Value ))
| Match Value Value
| IfElse Value Value Value
| Tuple (List Value)
| CommentedValue Value String
type Pattern
= WildcardMatch
| AliasMatch Name
| LiteralMatch Lit
| UnapplyMatch Path Name (List Pattern)
| TupleMatch (List Pattern)
| ListItemsMatch (List Pattern)
| HeadTailMatch Pattern Pattern
| CommentedPattern Pattern String
type Lit
= BooleanLit Bool
| CharacterLit Char
| StringLit String
| IntegerLit Int
| FloatLit Float
nameOfTypeDecl : TypeDecl -> Name
nameOfTypeDecl typeDecl =
case typeDecl of
Trait data -> data.name
Class data -> data.name
Object data -> data.name
| 51402 | {-
Copyright 2020 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module SlateX.DevBot.Scala.AST exposing (..)
type alias Name = String
type alias Path = List Name
type alias CompilationUnit =
{ dirPath : List String
, fileName : String
, packageDecl : PackageDecl
, imports : List ImportDecl
, typeDecls : List TypeDecl
}
type alias PackageDecl = List String
type alias ImportDecl =
{ isAbsolute : Bool
, packagePrefix : List String
, importNames : List ImportName
}
type ImportName
= ImportName String
| ImportRename String String
type Mod
= Sealed
| Final
| Case
| Val
| Package
| Implicit
type TypeDecl
= Trait
{ modifiers : List Mod
, name : Name
, typeArgs : List Type
, extends : List Type
, members : List MemberDecl
}
| Class
{ modifiers : List Mod
, name : Name
, typeArgs : List Type
, ctorArgs : List (List ArgDecl)
, extends : List Type
}
| Object
{ modifiers : List Mod
, name : Name
, extends : List Type
, members : List MemberDecl
}
type alias ArgDecl =
{ modifiers : List Mod
, tpe : Type
, name : Name
, defaultValue : Maybe Value
}
type alias ArgValue =
{ name : Maybe Name
, value : Value
}
type MemberDecl
= TypeAlias
{ alias : Name
, typeArgs : (List Type)
, tpe : Type
}
| FunctionDecl
{ modifiers : List Mod
, name : Name
, typeArgs : List Type
, args : List (List ArgDecl)
, returnType : Maybe Type
, body : Maybe Value
}
| MemberTypeDecl TypeDecl
type Type
= TypeVar Name
| TypeRef Path Name
| TypeApply Type (List Type)
| TupleType (List Type)
| StructuralType (List MemberDecl)
| FunctionType Type Type
| CommentedType Type String
type Value
= Literal Lit
| Var Name
| Ref Path Name
| Select Value Name
| Wildcard
| Apply Value (List ArgValue)
| UnOp String Value
| BinOp Value String Value
| Lambda (List Name) Value
| LetBlock (List ( Pattern, Value )) Value
| MatchCases (List ( Pattern, Value ))
| Match Value Value
| IfElse Value Value Value
| Tuple (List Value)
| CommentedValue Value String
type Pattern
= WildcardMatch
| AliasMatch Name
| LiteralMatch Lit
| UnapplyMatch Path Name (List Pattern)
| TupleMatch (List Pattern)
| ListItemsMatch (List Pattern)
| HeadTailMatch Pattern Pattern
| CommentedPattern Pattern String
type Lit
= BooleanLit Bool
| CharacterLit Char
| StringLit String
| IntegerLit Int
| FloatLit Float
nameOfTypeDecl : TypeDecl -> Name
nameOfTypeDecl typeDecl =
case typeDecl of
Trait data -> data.name
Class data -> data.name
Object data -> data.name
| true | {-
Copyright 2020 PI:NAME:<NAME>END_PI
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module SlateX.DevBot.Scala.AST exposing (..)
type alias Name = String
type alias Path = List Name
type alias CompilationUnit =
{ dirPath : List String
, fileName : String
, packageDecl : PackageDecl
, imports : List ImportDecl
, typeDecls : List TypeDecl
}
type alias PackageDecl = List String
type alias ImportDecl =
{ isAbsolute : Bool
, packagePrefix : List String
, importNames : List ImportName
}
type ImportName
= ImportName String
| ImportRename String String
type Mod
= Sealed
| Final
| Case
| Val
| Package
| Implicit
type TypeDecl
= Trait
{ modifiers : List Mod
, name : Name
, typeArgs : List Type
, extends : List Type
, members : List MemberDecl
}
| Class
{ modifiers : List Mod
, name : Name
, typeArgs : List Type
, ctorArgs : List (List ArgDecl)
, extends : List Type
}
| Object
{ modifiers : List Mod
, name : Name
, extends : List Type
, members : List MemberDecl
}
type alias ArgDecl =
{ modifiers : List Mod
, tpe : Type
, name : Name
, defaultValue : Maybe Value
}
type alias ArgValue =
{ name : Maybe Name
, value : Value
}
type MemberDecl
= TypeAlias
{ alias : Name
, typeArgs : (List Type)
, tpe : Type
}
| FunctionDecl
{ modifiers : List Mod
, name : Name
, typeArgs : List Type
, args : List (List ArgDecl)
, returnType : Maybe Type
, body : Maybe Value
}
| MemberTypeDecl TypeDecl
type Type
= TypeVar Name
| TypeRef Path Name
| TypeApply Type (List Type)
| TupleType (List Type)
| StructuralType (List MemberDecl)
| FunctionType Type Type
| CommentedType Type String
type Value
= Literal Lit
| Var Name
| Ref Path Name
| Select Value Name
| Wildcard
| Apply Value (List ArgValue)
| UnOp String Value
| BinOp Value String Value
| Lambda (List Name) Value
| LetBlock (List ( Pattern, Value )) Value
| MatchCases (List ( Pattern, Value ))
| Match Value Value
| IfElse Value Value Value
| Tuple (List Value)
| CommentedValue Value String
type Pattern
= WildcardMatch
| AliasMatch Name
| LiteralMatch Lit
| UnapplyMatch Path Name (List Pattern)
| TupleMatch (List Pattern)
| ListItemsMatch (List Pattern)
| HeadTailMatch Pattern Pattern
| CommentedPattern Pattern String
type Lit
= BooleanLit Bool
| CharacterLit Char
| StringLit String
| IntegerLit Int
| FloatLit Float
nameOfTypeDecl : TypeDecl -> Name
nameOfTypeDecl typeDecl =
case typeDecl of
Trait data -> data.name
Class data -> data.name
Object data -> data.name
| elm |
[
{
"context": " Routing.HomeRoute ->\n ( { token = token\n , projects = AllDict.empty .fullNam",
"end": 793,
"score": 0.5787274241,
"start": 788,
"tag": "KEY",
"value": "token"
},
{
"context": "ng.DetailRoute fullName ->\n ( { token = token\n , projects = AllDict.empty .fullNam",
"end": 1042,
"score": 0.7119088769,
"start": 1037,
"tag": "KEY",
"value": "token"
}
] | src/elm/Model.elm | cjduncana/elm-panama-js | 0 | module Model
exposing
( Flags
, Model
, Msg
( GoToDetailPage
, GoToListPage
, Navigate
, ProjectsRecieved
, SetTab
, UpdatedProjectRecieved
)
, Page(ListPage, DetailPage)
, addProjectToDetailPage
, init
, getProjects
, setTabInDetailPage
)
import AllDict exposing (AllDict)
import Date
import Http exposing (Error)
import Navigation exposing (Location)
import Project exposing (Project, Projects)
import Routing exposing (Route)
import Task exposing (Task)
init : Flags -> Location -> ( Model, Cmd Msg )
init { token } location =
case Routing.fromLocation location of
Routing.HomeRoute ->
( { token = token
, projects = AllDict.empty .fullName
, projectList = []
, page = ListPage
}
, getProjects token
)
Routing.DetailRoute fullName ->
( { token = token
, projects = AllDict.empty .fullName
, projectList = []
, page = DetailPage Nothing 0
}
, getProject fullName token
)
type alias Flags =
{ token : String }
type alias Model =
{ token : String
, projects : AllDict Project
, projectList : Projects
, page : Page
}
type Msg
= ProjectsRecieved (Result Error Projects)
| UpdatedProjectRecieved (Result Error Project)
| Navigate Route
| GoToListPage
| GoToDetailPage String
| SetTab Int
type Page
= ListPage
| DetailPage (Maybe Project) Int
getProjects : String -> Cmd Msg
getProjects token =
Date.now
|> Task.andThen (Project.listProjectsTask token)
|> Task.attempt ProjectsRecieved
getProject : String -> String -> Cmd Msg
getProject fullName token =
Project.getProject fullName token
|> Task.andThen (Project.updateProjectTask token)
|> Task.attempt UpdatedProjectRecieved
addProjectToDetailPage : Page -> Project -> Page
addProjectToDetailPage page project =
case page of
ListPage ->
ListPage
DetailPage _ activeIndex ->
DetailPage (Just project) activeIndex
setTabInDetailPage : Page -> Int -> Page
setTabInDetailPage page activeIndex =
case page of
ListPage ->
ListPage
DetailPage project _ ->
DetailPage project activeIndex
| 5066 | module Model
exposing
( Flags
, Model
, Msg
( GoToDetailPage
, GoToListPage
, Navigate
, ProjectsRecieved
, SetTab
, UpdatedProjectRecieved
)
, Page(ListPage, DetailPage)
, addProjectToDetailPage
, init
, getProjects
, setTabInDetailPage
)
import AllDict exposing (AllDict)
import Date
import Http exposing (Error)
import Navigation exposing (Location)
import Project exposing (Project, Projects)
import Routing exposing (Route)
import Task exposing (Task)
init : Flags -> Location -> ( Model, Cmd Msg )
init { token } location =
case Routing.fromLocation location of
Routing.HomeRoute ->
( { token = <KEY>
, projects = AllDict.empty .fullName
, projectList = []
, page = ListPage
}
, getProjects token
)
Routing.DetailRoute fullName ->
( { token = <KEY>
, projects = AllDict.empty .fullName
, projectList = []
, page = DetailPage Nothing 0
}
, getProject fullName token
)
type alias Flags =
{ token : String }
type alias Model =
{ token : String
, projects : AllDict Project
, projectList : Projects
, page : Page
}
type Msg
= ProjectsRecieved (Result Error Projects)
| UpdatedProjectRecieved (Result Error Project)
| Navigate Route
| GoToListPage
| GoToDetailPage String
| SetTab Int
type Page
= ListPage
| DetailPage (Maybe Project) Int
getProjects : String -> Cmd Msg
getProjects token =
Date.now
|> Task.andThen (Project.listProjectsTask token)
|> Task.attempt ProjectsRecieved
getProject : String -> String -> Cmd Msg
getProject fullName token =
Project.getProject fullName token
|> Task.andThen (Project.updateProjectTask token)
|> Task.attempt UpdatedProjectRecieved
addProjectToDetailPage : Page -> Project -> Page
addProjectToDetailPage page project =
case page of
ListPage ->
ListPage
DetailPage _ activeIndex ->
DetailPage (Just project) activeIndex
setTabInDetailPage : Page -> Int -> Page
setTabInDetailPage page activeIndex =
case page of
ListPage ->
ListPage
DetailPage project _ ->
DetailPage project activeIndex
| true | module Model
exposing
( Flags
, Model
, Msg
( GoToDetailPage
, GoToListPage
, Navigate
, ProjectsRecieved
, SetTab
, UpdatedProjectRecieved
)
, Page(ListPage, DetailPage)
, addProjectToDetailPage
, init
, getProjects
, setTabInDetailPage
)
import AllDict exposing (AllDict)
import Date
import Http exposing (Error)
import Navigation exposing (Location)
import Project exposing (Project, Projects)
import Routing exposing (Route)
import Task exposing (Task)
init : Flags -> Location -> ( Model, Cmd Msg )
init { token } location =
case Routing.fromLocation location of
Routing.HomeRoute ->
( { token = PI:KEY:<KEY>END_PI
, projects = AllDict.empty .fullName
, projectList = []
, page = ListPage
}
, getProjects token
)
Routing.DetailRoute fullName ->
( { token = PI:KEY:<KEY>END_PI
, projects = AllDict.empty .fullName
, projectList = []
, page = DetailPage Nothing 0
}
, getProject fullName token
)
type alias Flags =
{ token : String }
type alias Model =
{ token : String
, projects : AllDict Project
, projectList : Projects
, page : Page
}
type Msg
= ProjectsRecieved (Result Error Projects)
| UpdatedProjectRecieved (Result Error Project)
| Navigate Route
| GoToListPage
| GoToDetailPage String
| SetTab Int
type Page
= ListPage
| DetailPage (Maybe Project) Int
getProjects : String -> Cmd Msg
getProjects token =
Date.now
|> Task.andThen (Project.listProjectsTask token)
|> Task.attempt ProjectsRecieved
getProject : String -> String -> Cmd Msg
getProject fullName token =
Project.getProject fullName token
|> Task.andThen (Project.updateProjectTask token)
|> Task.attempt UpdatedProjectRecieved
addProjectToDetailPage : Page -> Project -> Page
addProjectToDetailPage page project =
case page of
ListPage ->
ListPage
DetailPage _ activeIndex ->
DetailPage (Just project) activeIndex
setTabInDetailPage : Page -> Int -> Page
setTabInDetailPage page activeIndex =
case page of
ListPage ->
ListPage
DetailPage project _ ->
DetailPage project activeIndex
| elm |
[
{
"context": "downloaded from https://raw.githubusercontent.com/AdobeDocs/cloudmanager-api-docs/master/swagger-specs/api.ya",
"end": 506,
"score": 0.9983427525,
"start": 497,
"tag": "USERNAME",
"value": "AdobeDocs"
},
{
"context": "version of the OpenAPI document: 1.0.0\n Contact: opensource@shinesolutions.com\n\n NOTE: This file is auto generated by the open",
"end": 648,
"score": 0.9999163151,
"start": 619,
"tag": "EMAIL",
"value": "opensource@shinesolutions.com"
},
{
"context": "d by the openapi-generator.\n https://github.com/openapitools/openapi-generator.git\n Do not edit this file ma",
"end": 747,
"score": 0.9995167851,
"start": 735,
"tag": "USERNAME",
"value": "openapitools"
}
] | clients/elm/generated/src/Data/PipelineExecutionStepState.elm | shinesolutions/cloudmanager-api-clients | 3 | {-
Cloud Manager API
This API allows access to Cloud Manager programs, pipelines, and environments by an authorized technical account created through the Adobe I/O Console. The base url for this API is https://cloudmanager.adobe.io, e.g. to get the list of programs for an organization, you would make a GET request to https://cloudmanager.adobe.io/api/programs (with the correct set of headers as described below). This swagger file can be downloaded from https://raw.githubusercontent.com/AdobeDocs/cloudmanager-api-docs/master/swagger-specs/api.yaml.
The version of the OpenAPI document: 1.0.0
Contact: opensource@shinesolutions.com
NOTE: This file is auto generated by the openapi-generator.
https://github.com/openapitools/openapi-generator.git
Do not edit this file manually.
-}
module Data.PipelineExecutionStepState exposing (PipelineExecutionStepState, Status(..), decoder, encode, encodeWithTag, toString)
import DateTime exposing (DateTime)
import DateTime exposing (DateTime)
import Data.Object as Object exposing (Object)
import Data.PipelineExecutionStepStateLinks as PipelineExecutionStepStateLinks exposing (PipelineExecutionStepStateLinks)
import Dict exposing (Dict)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing (optional, required)
import Json.Encode as Encode
{-| Describes the status of a particular pipeline execution step for display purposes
-}
type alias PipelineExecutionStepState =
{ id : Maybe (String)
, stepId : Maybe (String)
, phaseId : Maybe (String)
, action : Maybe (String)
, repository : Maybe (String)
, branch : Maybe (String)
, environment : Maybe (String)
, environmentType : Maybe (String)
, startedAt : Maybe (DateTime)
, finishedAt : Maybe (DateTime)
, details : Maybe ((Dict String Object))
, status : Maybe (Status)
, links : Maybe (PipelineExecutionStepStateLinks)
}
type Status
= NOTSTARTED
| RUNNING
| FINISHED
| ERROR
| ROLLINGBACK
| ROLLEDBACK
| WAITING
| CANCELLED
| FAILED
decoder : Decoder PipelineExecutionStepState
decoder =
Decode.succeed PipelineExecutionStepState
|> optional "id" (Decode.nullable Decode.string) Nothing
|> optional "stepId" (Decode.nullable Decode.string) Nothing
|> optional "phaseId" (Decode.nullable Decode.string) Nothing
|> optional "action" (Decode.nullable Decode.string) Nothing
|> optional "repository" (Decode.nullable Decode.string) Nothing
|> optional "branch" (Decode.nullable Decode.string) Nothing
|> optional "environment" (Decode.nullable Decode.string) Nothing
|> optional "environmentType" (Decode.nullable Decode.string) Nothing
|> optional "startedAt" (Decode.nullable DateTime.decoder) Nothing
|> optional "finishedAt" (Decode.nullable DateTime.decoder) Nothing
|> optional "details" (Decode.nullable (Decode.dict Object.decoder)) Nothing
|> optional "status" (Decode.nullable statusDecoder) Nothing
|> optional "_links" (Decode.nullable PipelineExecutionStepStateLinks.decoder) Nothing
encode : PipelineExecutionStepState -> Encode.Value
encode =
Encode.object << encodePairs
encodeWithTag : ( String, String ) -> PipelineExecutionStepState -> Encode.Value
encodeWithTag (tagField, tag) model =
Encode.object <| encodePairs model ++ [ ( tagField, Encode.string tag ) ]
encodePairs : PipelineExecutionStepState -> List (String, Encode.Value)
encodePairs model =
[ ( "id", Maybe.withDefault Encode.null (Maybe.map Encode.string model.id) )
, ( "stepId", Maybe.withDefault Encode.null (Maybe.map Encode.string model.stepId) )
, ( "phaseId", Maybe.withDefault Encode.null (Maybe.map Encode.string model.phaseId) )
, ( "action", Maybe.withDefault Encode.null (Maybe.map Encode.string model.action) )
, ( "repository", Maybe.withDefault Encode.null (Maybe.map Encode.string model.repository) )
, ( "branch", Maybe.withDefault Encode.null (Maybe.map Encode.string model.branch) )
, ( "environment", Maybe.withDefault Encode.null (Maybe.map Encode.string model.environment) )
, ( "environmentType", Maybe.withDefault Encode.null (Maybe.map Encode.string model.environmentType) )
, ( "startedAt", Maybe.withDefault Encode.null (Maybe.map DateTime.encode model.startedAt) )
, ( "finishedAt", Maybe.withDefault Encode.null (Maybe.map DateTime.encode model.finishedAt) )
, ( "details", Maybe.withDefault Encode.null (Maybe.map (Encode.dict identity Object.encode) model.details) )
, ( "status", Maybe.withDefault Encode.null (Maybe.map encodeStatus model.status) )
, ( "_links", Maybe.withDefault Encode.null (Maybe.map PipelineExecutionStepStateLinks.encode model.links) )
]
toString : PipelineExecutionStepState -> String
toString =
Encode.encode 0 << encode
statusDecoder : Decoder Status
statusDecoder =
Decode.string
|> Decode.andThen
(\str ->
case str of
"NOT_STARTED" ->
Decode.succeed NOTSTARTED
"RUNNING" ->
Decode.succeed RUNNING
"FINISHED" ->
Decode.succeed FINISHED
"ERROR" ->
Decode.succeed ERROR
"ROLLING_BACK" ->
Decode.succeed ROLLINGBACK
"ROLLED_BACK" ->
Decode.succeed ROLLEDBACK
"WAITING" ->
Decode.succeed WAITING
"CANCELLED" ->
Decode.succeed CANCELLED
"FAILED" ->
Decode.succeed FAILED
other ->
Decode.fail <| "Unknown type: " ++ other
)
encodeStatus : Status -> Encode.Value
encodeStatus model =
case model of
NOTSTARTED ->
Encode.string "NOT_STARTED"
RUNNING ->
Encode.string "RUNNING"
FINISHED ->
Encode.string "FINISHED"
ERROR ->
Encode.string "ERROR"
ROLLINGBACK ->
Encode.string "ROLLING_BACK"
ROLLEDBACK ->
Encode.string "ROLLED_BACK"
WAITING ->
Encode.string "WAITING"
CANCELLED ->
Encode.string "CANCELLED"
FAILED ->
Encode.string "FAILED"
| 15699 | {-
Cloud Manager API
This API allows access to Cloud Manager programs, pipelines, and environments by an authorized technical account created through the Adobe I/O Console. The base url for this API is https://cloudmanager.adobe.io, e.g. to get the list of programs for an organization, you would make a GET request to https://cloudmanager.adobe.io/api/programs (with the correct set of headers as described below). This swagger file can be downloaded from https://raw.githubusercontent.com/AdobeDocs/cloudmanager-api-docs/master/swagger-specs/api.yaml.
The version of the OpenAPI document: 1.0.0
Contact: <EMAIL>
NOTE: This file is auto generated by the openapi-generator.
https://github.com/openapitools/openapi-generator.git
Do not edit this file manually.
-}
module Data.PipelineExecutionStepState exposing (PipelineExecutionStepState, Status(..), decoder, encode, encodeWithTag, toString)
import DateTime exposing (DateTime)
import DateTime exposing (DateTime)
import Data.Object as Object exposing (Object)
import Data.PipelineExecutionStepStateLinks as PipelineExecutionStepStateLinks exposing (PipelineExecutionStepStateLinks)
import Dict exposing (Dict)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing (optional, required)
import Json.Encode as Encode
{-| Describes the status of a particular pipeline execution step for display purposes
-}
type alias PipelineExecutionStepState =
{ id : Maybe (String)
, stepId : Maybe (String)
, phaseId : Maybe (String)
, action : Maybe (String)
, repository : Maybe (String)
, branch : Maybe (String)
, environment : Maybe (String)
, environmentType : Maybe (String)
, startedAt : Maybe (DateTime)
, finishedAt : Maybe (DateTime)
, details : Maybe ((Dict String Object))
, status : Maybe (Status)
, links : Maybe (PipelineExecutionStepStateLinks)
}
type Status
= NOTSTARTED
| RUNNING
| FINISHED
| ERROR
| ROLLINGBACK
| ROLLEDBACK
| WAITING
| CANCELLED
| FAILED
decoder : Decoder PipelineExecutionStepState
decoder =
Decode.succeed PipelineExecutionStepState
|> optional "id" (Decode.nullable Decode.string) Nothing
|> optional "stepId" (Decode.nullable Decode.string) Nothing
|> optional "phaseId" (Decode.nullable Decode.string) Nothing
|> optional "action" (Decode.nullable Decode.string) Nothing
|> optional "repository" (Decode.nullable Decode.string) Nothing
|> optional "branch" (Decode.nullable Decode.string) Nothing
|> optional "environment" (Decode.nullable Decode.string) Nothing
|> optional "environmentType" (Decode.nullable Decode.string) Nothing
|> optional "startedAt" (Decode.nullable DateTime.decoder) Nothing
|> optional "finishedAt" (Decode.nullable DateTime.decoder) Nothing
|> optional "details" (Decode.nullable (Decode.dict Object.decoder)) Nothing
|> optional "status" (Decode.nullable statusDecoder) Nothing
|> optional "_links" (Decode.nullable PipelineExecutionStepStateLinks.decoder) Nothing
encode : PipelineExecutionStepState -> Encode.Value
encode =
Encode.object << encodePairs
encodeWithTag : ( String, String ) -> PipelineExecutionStepState -> Encode.Value
encodeWithTag (tagField, tag) model =
Encode.object <| encodePairs model ++ [ ( tagField, Encode.string tag ) ]
encodePairs : PipelineExecutionStepState -> List (String, Encode.Value)
encodePairs model =
[ ( "id", Maybe.withDefault Encode.null (Maybe.map Encode.string model.id) )
, ( "stepId", Maybe.withDefault Encode.null (Maybe.map Encode.string model.stepId) )
, ( "phaseId", Maybe.withDefault Encode.null (Maybe.map Encode.string model.phaseId) )
, ( "action", Maybe.withDefault Encode.null (Maybe.map Encode.string model.action) )
, ( "repository", Maybe.withDefault Encode.null (Maybe.map Encode.string model.repository) )
, ( "branch", Maybe.withDefault Encode.null (Maybe.map Encode.string model.branch) )
, ( "environment", Maybe.withDefault Encode.null (Maybe.map Encode.string model.environment) )
, ( "environmentType", Maybe.withDefault Encode.null (Maybe.map Encode.string model.environmentType) )
, ( "startedAt", Maybe.withDefault Encode.null (Maybe.map DateTime.encode model.startedAt) )
, ( "finishedAt", Maybe.withDefault Encode.null (Maybe.map DateTime.encode model.finishedAt) )
, ( "details", Maybe.withDefault Encode.null (Maybe.map (Encode.dict identity Object.encode) model.details) )
, ( "status", Maybe.withDefault Encode.null (Maybe.map encodeStatus model.status) )
, ( "_links", Maybe.withDefault Encode.null (Maybe.map PipelineExecutionStepStateLinks.encode model.links) )
]
toString : PipelineExecutionStepState -> String
toString =
Encode.encode 0 << encode
statusDecoder : Decoder Status
statusDecoder =
Decode.string
|> Decode.andThen
(\str ->
case str of
"NOT_STARTED" ->
Decode.succeed NOTSTARTED
"RUNNING" ->
Decode.succeed RUNNING
"FINISHED" ->
Decode.succeed FINISHED
"ERROR" ->
Decode.succeed ERROR
"ROLLING_BACK" ->
Decode.succeed ROLLINGBACK
"ROLLED_BACK" ->
Decode.succeed ROLLEDBACK
"WAITING" ->
Decode.succeed WAITING
"CANCELLED" ->
Decode.succeed CANCELLED
"FAILED" ->
Decode.succeed FAILED
other ->
Decode.fail <| "Unknown type: " ++ other
)
encodeStatus : Status -> Encode.Value
encodeStatus model =
case model of
NOTSTARTED ->
Encode.string "NOT_STARTED"
RUNNING ->
Encode.string "RUNNING"
FINISHED ->
Encode.string "FINISHED"
ERROR ->
Encode.string "ERROR"
ROLLINGBACK ->
Encode.string "ROLLING_BACK"
ROLLEDBACK ->
Encode.string "ROLLED_BACK"
WAITING ->
Encode.string "WAITING"
CANCELLED ->
Encode.string "CANCELLED"
FAILED ->
Encode.string "FAILED"
| true | {-
Cloud Manager API
This API allows access to Cloud Manager programs, pipelines, and environments by an authorized technical account created through the Adobe I/O Console. The base url for this API is https://cloudmanager.adobe.io, e.g. to get the list of programs for an organization, you would make a GET request to https://cloudmanager.adobe.io/api/programs (with the correct set of headers as described below). This swagger file can be downloaded from https://raw.githubusercontent.com/AdobeDocs/cloudmanager-api-docs/master/swagger-specs/api.yaml.
The version of the OpenAPI document: 1.0.0
Contact: PI:EMAIL:<EMAIL>END_PI
NOTE: This file is auto generated by the openapi-generator.
https://github.com/openapitools/openapi-generator.git
Do not edit this file manually.
-}
module Data.PipelineExecutionStepState exposing (PipelineExecutionStepState, Status(..), decoder, encode, encodeWithTag, toString)
import DateTime exposing (DateTime)
import DateTime exposing (DateTime)
import Data.Object as Object exposing (Object)
import Data.PipelineExecutionStepStateLinks as PipelineExecutionStepStateLinks exposing (PipelineExecutionStepStateLinks)
import Dict exposing (Dict)
import Json.Decode as Decode exposing (Decoder)
import Json.Decode.Pipeline exposing (optional, required)
import Json.Encode as Encode
{-| Describes the status of a particular pipeline execution step for display purposes
-}
type alias PipelineExecutionStepState =
{ id : Maybe (String)
, stepId : Maybe (String)
, phaseId : Maybe (String)
, action : Maybe (String)
, repository : Maybe (String)
, branch : Maybe (String)
, environment : Maybe (String)
, environmentType : Maybe (String)
, startedAt : Maybe (DateTime)
, finishedAt : Maybe (DateTime)
, details : Maybe ((Dict String Object))
, status : Maybe (Status)
, links : Maybe (PipelineExecutionStepStateLinks)
}
type Status
= NOTSTARTED
| RUNNING
| FINISHED
| ERROR
| ROLLINGBACK
| ROLLEDBACK
| WAITING
| CANCELLED
| FAILED
decoder : Decoder PipelineExecutionStepState
decoder =
Decode.succeed PipelineExecutionStepState
|> optional "id" (Decode.nullable Decode.string) Nothing
|> optional "stepId" (Decode.nullable Decode.string) Nothing
|> optional "phaseId" (Decode.nullable Decode.string) Nothing
|> optional "action" (Decode.nullable Decode.string) Nothing
|> optional "repository" (Decode.nullable Decode.string) Nothing
|> optional "branch" (Decode.nullable Decode.string) Nothing
|> optional "environment" (Decode.nullable Decode.string) Nothing
|> optional "environmentType" (Decode.nullable Decode.string) Nothing
|> optional "startedAt" (Decode.nullable DateTime.decoder) Nothing
|> optional "finishedAt" (Decode.nullable DateTime.decoder) Nothing
|> optional "details" (Decode.nullable (Decode.dict Object.decoder)) Nothing
|> optional "status" (Decode.nullable statusDecoder) Nothing
|> optional "_links" (Decode.nullable PipelineExecutionStepStateLinks.decoder) Nothing
encode : PipelineExecutionStepState -> Encode.Value
encode =
Encode.object << encodePairs
encodeWithTag : ( String, String ) -> PipelineExecutionStepState -> Encode.Value
encodeWithTag (tagField, tag) model =
Encode.object <| encodePairs model ++ [ ( tagField, Encode.string tag ) ]
encodePairs : PipelineExecutionStepState -> List (String, Encode.Value)
encodePairs model =
[ ( "id", Maybe.withDefault Encode.null (Maybe.map Encode.string model.id) )
, ( "stepId", Maybe.withDefault Encode.null (Maybe.map Encode.string model.stepId) )
, ( "phaseId", Maybe.withDefault Encode.null (Maybe.map Encode.string model.phaseId) )
, ( "action", Maybe.withDefault Encode.null (Maybe.map Encode.string model.action) )
, ( "repository", Maybe.withDefault Encode.null (Maybe.map Encode.string model.repository) )
, ( "branch", Maybe.withDefault Encode.null (Maybe.map Encode.string model.branch) )
, ( "environment", Maybe.withDefault Encode.null (Maybe.map Encode.string model.environment) )
, ( "environmentType", Maybe.withDefault Encode.null (Maybe.map Encode.string model.environmentType) )
, ( "startedAt", Maybe.withDefault Encode.null (Maybe.map DateTime.encode model.startedAt) )
, ( "finishedAt", Maybe.withDefault Encode.null (Maybe.map DateTime.encode model.finishedAt) )
, ( "details", Maybe.withDefault Encode.null (Maybe.map (Encode.dict identity Object.encode) model.details) )
, ( "status", Maybe.withDefault Encode.null (Maybe.map encodeStatus model.status) )
, ( "_links", Maybe.withDefault Encode.null (Maybe.map PipelineExecutionStepStateLinks.encode model.links) )
]
toString : PipelineExecutionStepState -> String
toString =
Encode.encode 0 << encode
statusDecoder : Decoder Status
statusDecoder =
Decode.string
|> Decode.andThen
(\str ->
case str of
"NOT_STARTED" ->
Decode.succeed NOTSTARTED
"RUNNING" ->
Decode.succeed RUNNING
"FINISHED" ->
Decode.succeed FINISHED
"ERROR" ->
Decode.succeed ERROR
"ROLLING_BACK" ->
Decode.succeed ROLLINGBACK
"ROLLED_BACK" ->
Decode.succeed ROLLEDBACK
"WAITING" ->
Decode.succeed WAITING
"CANCELLED" ->
Decode.succeed CANCELLED
"FAILED" ->
Decode.succeed FAILED
other ->
Decode.fail <| "Unknown type: " ++ other
)
encodeStatus : Status -> Encode.Value
encodeStatus model =
case model of
NOTSTARTED ->
Encode.string "NOT_STARTED"
RUNNING ->
Encode.string "RUNNING"
FINISHED ->
Encode.string "FINISHED"
ERROR ->
Encode.string "ERROR"
ROLLINGBACK ->
Encode.string "ROLLING_BACK"
ROLLEDBACK ->
Encode.string "ROLLED_BACK"
WAITING ->
Encode.string "WAITING"
CANCELLED ->
Encode.string "CANCELLED"
FAILED ->
Encode.string "FAILED"
| elm |
[
{
"context": "orization_code\"\n\n Password ->\n \"password\"\n\n ClientCredentials ->\n \"clien",
"end": 6682,
"score": 0.9994908571,
"start": 6674,
"tag": "PASSWORD",
"value": "password"
}
] | src/OAuth.elm | lamdera/auth | 1 | module OAuth exposing
( Token(..), useToken, tokenToString, tokenFromString
, ErrorCode(..), errorCodeToString, errorCodeFromString
, ResponseType(..), responseTypeToString, GrantType(..), grantTypeToString
, TokenType, TokenString, makeToken, makeRefreshToken
)
{-| Utility library to manage client-side OAuth 2.0 authentications
The library contains a main OAuth module exposing types used accross other modules. In practice,
you'll only need to use one of the additional modules:
- OAuth.AuthorizationCode: The authorization code grant type is used to obtain both access tokens
and refresh tokens via a redirection-based flow and is optimized for confidential clients
[4.1](https://tools.ietf.org/html/rfc6749#section-4.1).
- OAuth.AuthorizationCode.PKCE: An extension of the original OAuth 2.0 specification to mitigate
authorization code interception attacks through the use of Proof Key for Code Exchange (PKCE).
- OAuth.Implicit: The implicit grant type is used to obtain access tokens (it does not support the
issuance of refresh tokens) and is optimized for public clients known to operate a particular
redirection URI [4.2](https://tools.ietf.org/html/rfc6749#section-4.2).
- OAuth.Password: The resource owner password credentials grant type is suitable in cases where the
resource owner has a trust relationship with the client, such as the device operating system or a
highly privileged application [4.3](https://tools.ietf.org/html/rfc6749#section-4.3)
- OAuth.ClientCredentials: The client can request an access token using only its client credentials
(or other supported means of authentication) when the client is requesting access to the protected
resources under its control, or those of another resource owner that have been previously arranged
with the authorization server (the method of which is beyond the scope of this specification)
[4.4](https://tools.ietf.org/html/rfc6749#section-4.3).
In practice, you most probably want to use the
[`OAuth.AuthorizationCode`](http://package.elm-lang.org/packages/truqu/elm-oauth2/latest/OAuth-AuthorizationCode).
If your authorization server supports it, you should look at the PKCE extension in a second-time!
which is the most commonly
used.
## Token
@docs Token, useToken, tokenToString, tokenFromString
## ErrorCode
@docs ErrorCode, errorCodeToString, errorCodeFromString
## Response & Grant types (Advanced)
The following section can be ignored if you're dealing with a very generic OAuth2.0 implementation. If however, your authorization server does implement some extra features on top of the OAuth2.0 protocol (e.g. OpenID Connect), you will require to tweak response parsers and possibly, response type to cope with these discrepancies. In short, unless you're planning on using `makeTokenRequestWith` or `makeAuthorizationUrlWith`, you most probably won't need any of the functions below.
@docs ResponseType, responseTypeToString, GrantType, grantTypeToString
## Decoders & Parsers Utils (advanced)
@docs TokenType, TokenString, makeToken, makeRefreshToken
-}
import Extra.Maybe as Maybe
import Http as Http
--
-- Token
--
{-| Describes the type of access token to use.
- Bearer: Utilized by simply including the access token string in the request
[rfc6750](https://tools.ietf.org/html/rfc6750)
- Mac: Not supported.
-}
type Token
= Bearer String
{-| Alias for readability
-}
type alias TokenType =
String
{-| Alias for readability
-}
type alias TokenString =
String
{-| Use a token to authenticate a request.
-}
useToken : Token -> List Http.Header -> List Http.Header
useToken token =
(::) (Http.header "Authorization" (tokenToString token))
{-| Create a token from two string representing a token type and
an actual token value. This is intended to be used in Json decoders
or Query parsers.
Returns `Nothing` when the token type is `Nothing`
, different from `Just "Bearer"` or when there's no token at all.
-}
makeToken : Maybe TokenType -> Maybe TokenString -> Maybe Token
makeToken =
Maybe.andThen2 tryMakeToken
{-| See `makeToken`, with the subtle difference that a token value may or
may not be there.
Returns `Nothing` when the token type isn't `"Bearer"`.
Returns `Just Nothing` or `Just (Just token)` otherwise, depending on whether a token is
present or not.
-}
makeRefreshToken : TokenType -> Maybe TokenString -> Maybe (Maybe Token)
makeRefreshToken tokenType mToken =
case ( mToken, Maybe.andThen2 tryMakeToken (Just tokenType) mToken ) of
( Nothing, _ ) ->
Just Nothing
( _, Just token ) ->
Just <| Just token
_ ->
Nothing
{-| Internal, attempt to make a Bearer token from a type and a token string
-}
tryMakeToken : TokenType -> TokenString -> Maybe Token
tryMakeToken tokenType token =
case String.toLower tokenType of
"bearer" ->
Just (Bearer token)
_ ->
Nothing
{-| Get the `String` representation of a `Token` to be used in an 'Authorization' header
-}
tokenToString : Token -> String
tokenToString (Bearer t) =
"Bearer " ++ t
{-| Parse a token from an 'Authorization' header string.
tokenFromString (tokenToString token) == Just token
-}
tokenFromString : String -> Maybe Token
tokenFromString str =
case ( String.left 6 str, String.dropLeft 7 str ) of
( "Bearer", t ) ->
Just (Bearer t)
_ ->
Nothing
--
-- ResponseType / GrandType
--
{-| Describes the desired type of response to an authorization. Use `Code` to ask for an
authorization code and continue with the according flow. Use `Token` to do an implicit
authentication and directly retrieve a `Token` from the authorization. If need be, you may provide a
custom response type should the server returns a non-standard response type.
-}
type ResponseType
= Code
| Token
| CustomResponse String
{-| Gets the `String` representation of a `ResponseType`.
-}
responseTypeToString : ResponseType -> String
responseTypeToString r =
case r of
Code ->
"code"
Token ->
"token"
CustomResponse str ->
str
{-| Describes the desired type of grant to an authentication.
-}
type GrantType
= AuthorizationCode
| Password
| ClientCredentials
| RefreshToken
| CustomGrant String
{-| Gets the `String` representation of a `GrantType`
-}
grantTypeToString : GrantType -> String
grantTypeToString g =
case g of
AuthorizationCode ->
"authorization_code"
Password ->
"password"
ClientCredentials ->
"client_credentials"
RefreshToken ->
"refresh_token"
CustomGrant str ->
str
--
-- Error
--
{-| Describes an OAuth error response [4.1.2.1](https://tools.ietf.org/html/rfc6749#section-4.1.2.1)
- `InvalidRequest`: The request is missing a required parameter, includes an invalid parameter value,
includes a parameter more than once, or is otherwise malformed.
- `UnauthorizedClient`: The client is not authorized to request an authorization code using this
method.
- `AccessDenied`: The resource owner or authorization server denied the request.
- `UnsupportedResponseType`: The authorization server does not support obtaining an authorization code
using this method.
- `InvalidScope`: The requested scope is invalid, unknown, or malformed.
- `ServerError`: The authorization server encountered an unexpected condition that prevented it from
fulfilling the request. (This error code is needed because a 500 Internal Server Error HTTP status
code cannot be returned to the client via an HTTP redirect.)
- `TemporarilyUnavailable`: The authorization server is currently unable to handle the request due to
a temporary overloading or maintenance of the server. (This error code is needed because a 503
Service Unavailable HTTP status code cannot be returned to the client via an HTTP redirect.)
- `Custom`: Encountered a 'free-string' or custom code not specified by the official RFC but returned
by the authorization server.
-}
type ErrorCode
= InvalidRequest
| UnauthorizedClient
| AccessDenied
| UnsupportedResponseType
| InvalidScope
| ServerError
| TemporarilyUnavailable
| Custom String
{-| Get the `String` representation of an `ErrorCode`.
-}
errorCodeToString : ErrorCode -> String
errorCodeToString err =
case err of
InvalidRequest ->
"invalid_request"
UnauthorizedClient ->
"unauthorized_client"
AccessDenied ->
"access_denied"
UnsupportedResponseType ->
"unsupported_response_type"
InvalidScope ->
"invalid_scope"
ServerError ->
"server_error"
TemporarilyUnavailable ->
"temporarily_unavailable"
Custom str ->
str
{-| Build a string back into an error code. Returns `Custom _`
when the string isn't recognized from the ones specified in the RFC
-}
errorCodeFromString : String -> ErrorCode
errorCodeFromString str =
case str of
"invalid_request" ->
InvalidRequest
"unauthorized_client" ->
UnauthorizedClient
"access_denied" ->
AccessDenied
"unsupported_response_type" ->
UnsupportedResponseType
"invalid_scope" ->
InvalidScope
"server_error" ->
ServerError
"temporarily_unavailable" ->
TemporarilyUnavailable
_ ->
Custom str
| 15574 | module OAuth exposing
( Token(..), useToken, tokenToString, tokenFromString
, ErrorCode(..), errorCodeToString, errorCodeFromString
, ResponseType(..), responseTypeToString, GrantType(..), grantTypeToString
, TokenType, TokenString, makeToken, makeRefreshToken
)
{-| Utility library to manage client-side OAuth 2.0 authentications
The library contains a main OAuth module exposing types used accross other modules. In practice,
you'll only need to use one of the additional modules:
- OAuth.AuthorizationCode: The authorization code grant type is used to obtain both access tokens
and refresh tokens via a redirection-based flow and is optimized for confidential clients
[4.1](https://tools.ietf.org/html/rfc6749#section-4.1).
- OAuth.AuthorizationCode.PKCE: An extension of the original OAuth 2.0 specification to mitigate
authorization code interception attacks through the use of Proof Key for Code Exchange (PKCE).
- OAuth.Implicit: The implicit grant type is used to obtain access tokens (it does not support the
issuance of refresh tokens) and is optimized for public clients known to operate a particular
redirection URI [4.2](https://tools.ietf.org/html/rfc6749#section-4.2).
- OAuth.Password: The resource owner password credentials grant type is suitable in cases where the
resource owner has a trust relationship with the client, such as the device operating system or a
highly privileged application [4.3](https://tools.ietf.org/html/rfc6749#section-4.3)
- OAuth.ClientCredentials: The client can request an access token using only its client credentials
(or other supported means of authentication) when the client is requesting access to the protected
resources under its control, or those of another resource owner that have been previously arranged
with the authorization server (the method of which is beyond the scope of this specification)
[4.4](https://tools.ietf.org/html/rfc6749#section-4.3).
In practice, you most probably want to use the
[`OAuth.AuthorizationCode`](http://package.elm-lang.org/packages/truqu/elm-oauth2/latest/OAuth-AuthorizationCode).
If your authorization server supports it, you should look at the PKCE extension in a second-time!
which is the most commonly
used.
## Token
@docs Token, useToken, tokenToString, tokenFromString
## ErrorCode
@docs ErrorCode, errorCodeToString, errorCodeFromString
## Response & Grant types (Advanced)
The following section can be ignored if you're dealing with a very generic OAuth2.0 implementation. If however, your authorization server does implement some extra features on top of the OAuth2.0 protocol (e.g. OpenID Connect), you will require to tweak response parsers and possibly, response type to cope with these discrepancies. In short, unless you're planning on using `makeTokenRequestWith` or `makeAuthorizationUrlWith`, you most probably won't need any of the functions below.
@docs ResponseType, responseTypeToString, GrantType, grantTypeToString
## Decoders & Parsers Utils (advanced)
@docs TokenType, TokenString, makeToken, makeRefreshToken
-}
import Extra.Maybe as Maybe
import Http as Http
--
-- Token
--
{-| Describes the type of access token to use.
- Bearer: Utilized by simply including the access token string in the request
[rfc6750](https://tools.ietf.org/html/rfc6750)
- Mac: Not supported.
-}
type Token
= Bearer String
{-| Alias for readability
-}
type alias TokenType =
String
{-| Alias for readability
-}
type alias TokenString =
String
{-| Use a token to authenticate a request.
-}
useToken : Token -> List Http.Header -> List Http.Header
useToken token =
(::) (Http.header "Authorization" (tokenToString token))
{-| Create a token from two string representing a token type and
an actual token value. This is intended to be used in Json decoders
or Query parsers.
Returns `Nothing` when the token type is `Nothing`
, different from `Just "Bearer"` or when there's no token at all.
-}
makeToken : Maybe TokenType -> Maybe TokenString -> Maybe Token
makeToken =
Maybe.andThen2 tryMakeToken
{-| See `makeToken`, with the subtle difference that a token value may or
may not be there.
Returns `Nothing` when the token type isn't `"Bearer"`.
Returns `Just Nothing` or `Just (Just token)` otherwise, depending on whether a token is
present or not.
-}
makeRefreshToken : TokenType -> Maybe TokenString -> Maybe (Maybe Token)
makeRefreshToken tokenType mToken =
case ( mToken, Maybe.andThen2 tryMakeToken (Just tokenType) mToken ) of
( Nothing, _ ) ->
Just Nothing
( _, Just token ) ->
Just <| Just token
_ ->
Nothing
{-| Internal, attempt to make a Bearer token from a type and a token string
-}
tryMakeToken : TokenType -> TokenString -> Maybe Token
tryMakeToken tokenType token =
case String.toLower tokenType of
"bearer" ->
Just (Bearer token)
_ ->
Nothing
{-| Get the `String` representation of a `Token` to be used in an 'Authorization' header
-}
tokenToString : Token -> String
tokenToString (Bearer t) =
"Bearer " ++ t
{-| Parse a token from an 'Authorization' header string.
tokenFromString (tokenToString token) == Just token
-}
tokenFromString : String -> Maybe Token
tokenFromString str =
case ( String.left 6 str, String.dropLeft 7 str ) of
( "Bearer", t ) ->
Just (Bearer t)
_ ->
Nothing
--
-- ResponseType / GrandType
--
{-| Describes the desired type of response to an authorization. Use `Code` to ask for an
authorization code and continue with the according flow. Use `Token` to do an implicit
authentication and directly retrieve a `Token` from the authorization. If need be, you may provide a
custom response type should the server returns a non-standard response type.
-}
type ResponseType
= Code
| Token
| CustomResponse String
{-| Gets the `String` representation of a `ResponseType`.
-}
responseTypeToString : ResponseType -> String
responseTypeToString r =
case r of
Code ->
"code"
Token ->
"token"
CustomResponse str ->
str
{-| Describes the desired type of grant to an authentication.
-}
type GrantType
= AuthorizationCode
| Password
| ClientCredentials
| RefreshToken
| CustomGrant String
{-| Gets the `String` representation of a `GrantType`
-}
grantTypeToString : GrantType -> String
grantTypeToString g =
case g of
AuthorizationCode ->
"authorization_code"
Password ->
"<PASSWORD>"
ClientCredentials ->
"client_credentials"
RefreshToken ->
"refresh_token"
CustomGrant str ->
str
--
-- Error
--
{-| Describes an OAuth error response [4.1.2.1](https://tools.ietf.org/html/rfc6749#section-4.1.2.1)
- `InvalidRequest`: The request is missing a required parameter, includes an invalid parameter value,
includes a parameter more than once, or is otherwise malformed.
- `UnauthorizedClient`: The client is not authorized to request an authorization code using this
method.
- `AccessDenied`: The resource owner or authorization server denied the request.
- `UnsupportedResponseType`: The authorization server does not support obtaining an authorization code
using this method.
- `InvalidScope`: The requested scope is invalid, unknown, or malformed.
- `ServerError`: The authorization server encountered an unexpected condition that prevented it from
fulfilling the request. (This error code is needed because a 500 Internal Server Error HTTP status
code cannot be returned to the client via an HTTP redirect.)
- `TemporarilyUnavailable`: The authorization server is currently unable to handle the request due to
a temporary overloading or maintenance of the server. (This error code is needed because a 503
Service Unavailable HTTP status code cannot be returned to the client via an HTTP redirect.)
- `Custom`: Encountered a 'free-string' or custom code not specified by the official RFC but returned
by the authorization server.
-}
type ErrorCode
= InvalidRequest
| UnauthorizedClient
| AccessDenied
| UnsupportedResponseType
| InvalidScope
| ServerError
| TemporarilyUnavailable
| Custom String
{-| Get the `String` representation of an `ErrorCode`.
-}
errorCodeToString : ErrorCode -> String
errorCodeToString err =
case err of
InvalidRequest ->
"invalid_request"
UnauthorizedClient ->
"unauthorized_client"
AccessDenied ->
"access_denied"
UnsupportedResponseType ->
"unsupported_response_type"
InvalidScope ->
"invalid_scope"
ServerError ->
"server_error"
TemporarilyUnavailable ->
"temporarily_unavailable"
Custom str ->
str
{-| Build a string back into an error code. Returns `Custom _`
when the string isn't recognized from the ones specified in the RFC
-}
errorCodeFromString : String -> ErrorCode
errorCodeFromString str =
case str of
"invalid_request" ->
InvalidRequest
"unauthorized_client" ->
UnauthorizedClient
"access_denied" ->
AccessDenied
"unsupported_response_type" ->
UnsupportedResponseType
"invalid_scope" ->
InvalidScope
"server_error" ->
ServerError
"temporarily_unavailable" ->
TemporarilyUnavailable
_ ->
Custom str
| true | module OAuth exposing
( Token(..), useToken, tokenToString, tokenFromString
, ErrorCode(..), errorCodeToString, errorCodeFromString
, ResponseType(..), responseTypeToString, GrantType(..), grantTypeToString
, TokenType, TokenString, makeToken, makeRefreshToken
)
{-| Utility library to manage client-side OAuth 2.0 authentications
The library contains a main OAuth module exposing types used accross other modules. In practice,
you'll only need to use one of the additional modules:
- OAuth.AuthorizationCode: The authorization code grant type is used to obtain both access tokens
and refresh tokens via a redirection-based flow and is optimized for confidential clients
[4.1](https://tools.ietf.org/html/rfc6749#section-4.1).
- OAuth.AuthorizationCode.PKCE: An extension of the original OAuth 2.0 specification to mitigate
authorization code interception attacks through the use of Proof Key for Code Exchange (PKCE).
- OAuth.Implicit: The implicit grant type is used to obtain access tokens (it does not support the
issuance of refresh tokens) and is optimized for public clients known to operate a particular
redirection URI [4.2](https://tools.ietf.org/html/rfc6749#section-4.2).
- OAuth.Password: The resource owner password credentials grant type is suitable in cases where the
resource owner has a trust relationship with the client, such as the device operating system or a
highly privileged application [4.3](https://tools.ietf.org/html/rfc6749#section-4.3)
- OAuth.ClientCredentials: The client can request an access token using only its client credentials
(or other supported means of authentication) when the client is requesting access to the protected
resources under its control, or those of another resource owner that have been previously arranged
with the authorization server (the method of which is beyond the scope of this specification)
[4.4](https://tools.ietf.org/html/rfc6749#section-4.3).
In practice, you most probably want to use the
[`OAuth.AuthorizationCode`](http://package.elm-lang.org/packages/truqu/elm-oauth2/latest/OAuth-AuthorizationCode).
If your authorization server supports it, you should look at the PKCE extension in a second-time!
which is the most commonly
used.
## Token
@docs Token, useToken, tokenToString, tokenFromString
## ErrorCode
@docs ErrorCode, errorCodeToString, errorCodeFromString
## Response & Grant types (Advanced)
The following section can be ignored if you're dealing with a very generic OAuth2.0 implementation. If however, your authorization server does implement some extra features on top of the OAuth2.0 protocol (e.g. OpenID Connect), you will require to tweak response parsers and possibly, response type to cope with these discrepancies. In short, unless you're planning on using `makeTokenRequestWith` or `makeAuthorizationUrlWith`, you most probably won't need any of the functions below.
@docs ResponseType, responseTypeToString, GrantType, grantTypeToString
## Decoders & Parsers Utils (advanced)
@docs TokenType, TokenString, makeToken, makeRefreshToken
-}
import Extra.Maybe as Maybe
import Http as Http
--
-- Token
--
{-| Describes the type of access token to use.
- Bearer: Utilized by simply including the access token string in the request
[rfc6750](https://tools.ietf.org/html/rfc6750)
- Mac: Not supported.
-}
type Token
= Bearer String
{-| Alias for readability
-}
type alias TokenType =
String
{-| Alias for readability
-}
type alias TokenString =
String
{-| Use a token to authenticate a request.
-}
useToken : Token -> List Http.Header -> List Http.Header
useToken token =
(::) (Http.header "Authorization" (tokenToString token))
{-| Create a token from two string representing a token type and
an actual token value. This is intended to be used in Json decoders
or Query parsers.
Returns `Nothing` when the token type is `Nothing`
, different from `Just "Bearer"` or when there's no token at all.
-}
makeToken : Maybe TokenType -> Maybe TokenString -> Maybe Token
makeToken =
Maybe.andThen2 tryMakeToken
{-| See `makeToken`, with the subtle difference that a token value may or
may not be there.
Returns `Nothing` when the token type isn't `"Bearer"`.
Returns `Just Nothing` or `Just (Just token)` otherwise, depending on whether a token is
present or not.
-}
makeRefreshToken : TokenType -> Maybe TokenString -> Maybe (Maybe Token)
makeRefreshToken tokenType mToken =
case ( mToken, Maybe.andThen2 tryMakeToken (Just tokenType) mToken ) of
( Nothing, _ ) ->
Just Nothing
( _, Just token ) ->
Just <| Just token
_ ->
Nothing
{-| Internal, attempt to make a Bearer token from a type and a token string
-}
tryMakeToken : TokenType -> TokenString -> Maybe Token
tryMakeToken tokenType token =
case String.toLower tokenType of
"bearer" ->
Just (Bearer token)
_ ->
Nothing
{-| Get the `String` representation of a `Token` to be used in an 'Authorization' header
-}
tokenToString : Token -> String
tokenToString (Bearer t) =
"Bearer " ++ t
{-| Parse a token from an 'Authorization' header string.
tokenFromString (tokenToString token) == Just token
-}
tokenFromString : String -> Maybe Token
tokenFromString str =
case ( String.left 6 str, String.dropLeft 7 str ) of
( "Bearer", t ) ->
Just (Bearer t)
_ ->
Nothing
--
-- ResponseType / GrandType
--
{-| Describes the desired type of response to an authorization. Use `Code` to ask for an
authorization code and continue with the according flow. Use `Token` to do an implicit
authentication and directly retrieve a `Token` from the authorization. If need be, you may provide a
custom response type should the server returns a non-standard response type.
-}
type ResponseType
= Code
| Token
| CustomResponse String
{-| Gets the `String` representation of a `ResponseType`.
-}
responseTypeToString : ResponseType -> String
responseTypeToString r =
case r of
Code ->
"code"
Token ->
"token"
CustomResponse str ->
str
{-| Describes the desired type of grant to an authentication.
-}
type GrantType
= AuthorizationCode
| Password
| ClientCredentials
| RefreshToken
| CustomGrant String
{-| Gets the `String` representation of a `GrantType`
-}
grantTypeToString : GrantType -> String
grantTypeToString g =
case g of
AuthorizationCode ->
"authorization_code"
Password ->
"PI:PASSWORD:<PASSWORD>END_PI"
ClientCredentials ->
"client_credentials"
RefreshToken ->
"refresh_token"
CustomGrant str ->
str
--
-- Error
--
{-| Describes an OAuth error response [4.1.2.1](https://tools.ietf.org/html/rfc6749#section-4.1.2.1)
- `InvalidRequest`: The request is missing a required parameter, includes an invalid parameter value,
includes a parameter more than once, or is otherwise malformed.
- `UnauthorizedClient`: The client is not authorized to request an authorization code using this
method.
- `AccessDenied`: The resource owner or authorization server denied the request.
- `UnsupportedResponseType`: The authorization server does not support obtaining an authorization code
using this method.
- `InvalidScope`: The requested scope is invalid, unknown, or malformed.
- `ServerError`: The authorization server encountered an unexpected condition that prevented it from
fulfilling the request. (This error code is needed because a 500 Internal Server Error HTTP status
code cannot be returned to the client via an HTTP redirect.)
- `TemporarilyUnavailable`: The authorization server is currently unable to handle the request due to
a temporary overloading or maintenance of the server. (This error code is needed because a 503
Service Unavailable HTTP status code cannot be returned to the client via an HTTP redirect.)
- `Custom`: Encountered a 'free-string' or custom code not specified by the official RFC but returned
by the authorization server.
-}
type ErrorCode
= InvalidRequest
| UnauthorizedClient
| AccessDenied
| UnsupportedResponseType
| InvalidScope
| ServerError
| TemporarilyUnavailable
| Custom String
{-| Get the `String` representation of an `ErrorCode`.
-}
errorCodeToString : ErrorCode -> String
errorCodeToString err =
case err of
InvalidRequest ->
"invalid_request"
UnauthorizedClient ->
"unauthorized_client"
AccessDenied ->
"access_denied"
UnsupportedResponseType ->
"unsupported_response_type"
InvalidScope ->
"invalid_scope"
ServerError ->
"server_error"
TemporarilyUnavailable ->
"temporarily_unavailable"
Custom str ->
str
{-| Build a string back into an error code. Returns `Custom _`
when the string isn't recognized from the ones specified in the RFC
-}
errorCodeFromString : String -> ErrorCode
errorCodeFromString str =
case str of
"invalid_request" ->
InvalidRequest
"unauthorized_client" ->
UnauthorizedClient
"access_denied" ->
AccessDenied
"unsupported_response_type" ->
UnsupportedResponseType
"invalid_scope" ->
InvalidScope
"server_error" ->
ServerError
"temporarily_unavailable" ->
TemporarilyUnavailable
_ ->
Custom str
| elm |
[
{
"context": "or <| initialSeed 0\n in\n { id = id, name = \"New Player\", role = None, party = Villagers, markers = [], a",
"end": 1274,
"score": 0.9569165111,
"start": 1264,
"tag": "NAME",
"value": "New Player"
}
] | src/Util/Player.elm | mafiakiel/gmtool | 1 | module Util.Player exposing
( hasId
, hasMarker
, hasParty
, hasRole
, initPlayer
, isAlive
, isInChurch
, isNominated
, playerById
)
import List exposing (any, filter, head, member)
import Random exposing (initialSeed)
import Types exposing (Marker(..), Party(..), Player, Role(..))
import Util.Marker exposing (isNominatedMarker)
import Uuid exposing (Uuid, uuidGenerator)
hasId : Uuid -> Player -> Bool
hasId id player =
player.id == id
hasRole : Role -> Player -> Bool
hasRole role player =
player.role == role
hasParty : Party -> Player -> Bool
hasParty party player =
player.party == party
hasMarker : Marker -> Player -> Bool
hasMarker marker player =
member marker player.markers
isInChurch : Player -> Bool
isInChurch player =
member Converted player.markers
|| player.role
== Pope
|| player.role
== Monk
|| player.role
== MonkInLove
isAlive : Player -> Bool
isAlive player =
player.alive
isNominated : Player -> Bool
isNominated player =
any isNominatedMarker player.markers
initPlayer : Player
initPlayer =
let
( id, _ ) =
Random.step uuidGenerator <| initialSeed 0
in
{ id = id, name = "New Player", role = None, party = Villagers, markers = [], alive = False }
playerById : List Player -> Uuid -> Maybe Player
playerById players id =
filter (\p -> p.id == id) players
|> head
| 883 | module Util.Player exposing
( hasId
, hasMarker
, hasParty
, hasRole
, initPlayer
, isAlive
, isInChurch
, isNominated
, playerById
)
import List exposing (any, filter, head, member)
import Random exposing (initialSeed)
import Types exposing (Marker(..), Party(..), Player, Role(..))
import Util.Marker exposing (isNominatedMarker)
import Uuid exposing (Uuid, uuidGenerator)
hasId : Uuid -> Player -> Bool
hasId id player =
player.id == id
hasRole : Role -> Player -> Bool
hasRole role player =
player.role == role
hasParty : Party -> Player -> Bool
hasParty party player =
player.party == party
hasMarker : Marker -> Player -> Bool
hasMarker marker player =
member marker player.markers
isInChurch : Player -> Bool
isInChurch player =
member Converted player.markers
|| player.role
== Pope
|| player.role
== Monk
|| player.role
== MonkInLove
isAlive : Player -> Bool
isAlive player =
player.alive
isNominated : Player -> Bool
isNominated player =
any isNominatedMarker player.markers
initPlayer : Player
initPlayer =
let
( id, _ ) =
Random.step uuidGenerator <| initialSeed 0
in
{ id = id, name = "<NAME>", role = None, party = Villagers, markers = [], alive = False }
playerById : List Player -> Uuid -> Maybe Player
playerById players id =
filter (\p -> p.id == id) players
|> head
| true | module Util.Player exposing
( hasId
, hasMarker
, hasParty
, hasRole
, initPlayer
, isAlive
, isInChurch
, isNominated
, playerById
)
import List exposing (any, filter, head, member)
import Random exposing (initialSeed)
import Types exposing (Marker(..), Party(..), Player, Role(..))
import Util.Marker exposing (isNominatedMarker)
import Uuid exposing (Uuid, uuidGenerator)
hasId : Uuid -> Player -> Bool
hasId id player =
player.id == id
hasRole : Role -> Player -> Bool
hasRole role player =
player.role == role
hasParty : Party -> Player -> Bool
hasParty party player =
player.party == party
hasMarker : Marker -> Player -> Bool
hasMarker marker player =
member marker player.markers
isInChurch : Player -> Bool
isInChurch player =
member Converted player.markers
|| player.role
== Pope
|| player.role
== Monk
|| player.role
== MonkInLove
isAlive : Player -> Bool
isAlive player =
player.alive
isNominated : Player -> Bool
isNominated player =
any isNominatedMarker player.markers
initPlayer : Player
initPlayer =
let
( id, _ ) =
Random.step uuidGenerator <| initialSeed 0
in
{ id = id, name = "PI:NAME:<NAME>END_PI", role = None, party = Villagers, markers = [], alive = False }
playerById : List Player -> Uuid -> Maybe Player
playerById players id =
filter (\p -> p.id == id) players
|> head
| elm |