Skip to content

Instantly share code, notes, and snippets.

@kristian76
Last active June 20, 2016 13:52
Show Gist options
  • Save kristian76/11d5418720486c34ede6de8e8b16d14d to your computer and use it in GitHub Desktop.
Save kristian76/11d5418720486c34ede6de8e8b16d14d to your computer and use it in GitHub Desktop.
issuelist.elm for fetching issues from github
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.App as Html
import Html.Events exposing (..)
import Http
import Json.Decode as Json exposing ((:=))
import Json.Encode exposing (encode)
import Task
import Date exposing (Date)
import String
import List
import Debug exposing (..)
-- Main
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- Init
init : ( Model, Cmd Msg )
init =
( { issues = [], keyword = "" }, Cmd.none )
-- Model
type alias Model =
{ issues : List Issue
, keyword : String
}
type alias Issue =
{ title : String
, state : String
, id : Int
, created : Date
}
-- Update
type Msg =
Search
| ChangeKeyword String
| FetchSucceed (List Issue)
| FetchFail Http.Error
| Store
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg |> log "update msg" of
ChangeKeyword val ->
( { model | keyword = val }, Cmd.none )
Search ->
( model, fetchIssues model.keyword )
FetchSucceed l ->
( { model | issues = l }, Cmd.none )
FetchFail _ ->
( model, Cmd.none )
Store ->
( model, Cmd.none )
-- View
view : Model -> Html Msg
view model =
div []
[ header [][
input [ placeholder "Enter keyword", onInput ChangeKeyword ] [ text (toString model.keyword) ]
, button [ onClick Search ] [ text "Search" ]
]
, main' [][ issueList model.issues ]
, footer [][ text "footer" ]
]
issueList : List Issue -> Html Msg
issueList issues =
ul [ id "issue-list" ] (List.map (issueItem) issues)
issueItem : Issue -> Html Msg
issueItem issue =
li [ draggable "true", onClick Store ] [ span [] [ text issue.title ]
, span [] [ text (toString issue.created) ]
]
-- Subscriptions
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- Http
encodeTerm : String -> String
encodeTerm val =
(Http.uriEncode val)
fetchIssues : String -> Cmd Msg
fetchIssues term =
let url =
"https://api.github.com/search/issues?q="++ encodeTerm term ++"+language:elm&sort=stars&order=desc"
in
Task.perform FetchFail FetchSucceed (Http.get decodeIssueList url)
decodeIssueList : Json.Decoder (List Issue)
decodeIssueList =
("items" := Json.list decodeIssue)
date : Json.Decoder Date
date =
Json.customDecoder Json.string Date.fromString
decodeIssue : Json.Decoder Issue
decodeIssue =
Json.object4 Issue
("title" := Json.string)
("state" := Json.string)
("id" := Json.int)
("created_at" := date)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment