Guest User

Untitled

a guest
Mar 16th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Pages.Tree exposing (..)
  2.  
  3. import Html exposing (Html, div, li, p, text, ul)
  4. import Http
  5. import Json.Decode exposing (Decoder, field, int, lazy, list, string)
  6. import Result as Http
  7.  
  8.  
  9. type  alias Tree
  10.     =   {
  11.           id: Int
  12.         , name: String
  13.         , parentId: Int
  14.         , text: String
  15.         , children: Childrens
  16.         }
  17. type Childrens = Childrens (List Tree)
  18.  
  19. type alias Model
  20.     = List Tree
  21.  
  22. type Msg =
  23.     GotTree (Http.Result Http.Error (List Tree))
  24.  
  25. init:  (Model, Cmd Msg)
  26. init  =
  27.     (
  28.         []
  29.         ,
  30.         Http.get
  31.         {
  32.           url = "http://localhost:8080/t.json"
  33.         , expect = Http.expectJson GotTree treeDataDecoder
  34.         }
  35.     )
  36.  
  37.  
  38. update: Msg -> (Model, Cmd Msg)
  39. update msg =
  40.     case msg of
  41.         GotTree result ->
  42.             case result of
  43.                 Ok text ->
  44.                     (text, Cmd.none)
  45.                 Err text ->
  46.                      Debug.log (Debug.toString text)
  47.                     ([], Cmd.none)
  48.  
  49. view: Model -> Html msg
  50. view tree =
  51.     ul[] (List.map viewTreeElement tree)
  52.  
  53.  
  54. viewTreeElement: Tree -> Html msg
  55. viewTreeElement tree =
  56.      li [] [
  57.         text tree.name
  58.         , ul [] (List.map viewTreeChildrens (getTreeChildren tree.children))
  59.     ]
  60.  
  61. viewTreeChildrens: Tree -> Html msg
  62. viewTreeChildrens children =
  63.     ul [] [
  64.         viewTreeElement children
  65.     ]
  66.  
  67. getTreeChildren: Childrens -> List Tree
  68. getTreeChildren child =
  69.     case child of
  70.         Childrens a ->
  71.             a
  72.  
  73. treeDataDecoder: Decoder (List Tree)
  74. treeDataDecoder =
  75.     Json.Decode.map5 Tree
  76.        (field "id" int)
  77.        (field "name" string)
  78.        (field "parent_id" int)
  79.        (field "text" string)
  80.        (field "children" (Json.Decode.map Childrens (lazy (\_ -> treeDataDecoder))))
  81.        |> Json.Decode.list
Advertisement
Add Comment
Please, Sign In to add comment