|
| 1 | +port module CustomElement exposing (init, update, view, subscriptions) |
| 2 | + |
| 3 | +import Html exposing (Html, div, text, h3) |
| 4 | + |
| 5 | + |
| 6 | +--import Html.Attributes exposing (class, classList) |
| 7 | +--import Html.Events exposing (onClick) |
| 8 | + |
| 9 | +import Json.Decode exposing (Value, decodeValue) |
| 10 | +import JsonValue exposing (decoder) |
| 11 | +import Json.Form |
| 12 | +import Json.Schema.Definitions |
| 13 | + |
| 14 | + |
| 15 | +type alias Model = |
| 16 | + { form : Json.Form.Model |
| 17 | + , editedValue : Maybe JsonValue.JsonValue |
| 18 | + } |
| 19 | + |
| 20 | + |
| 21 | +init : Value -> ( Model, Cmd Msg ) |
| 22 | +init v = |
| 23 | + let |
| 24 | + schema = v |
| 25 | + |> decodeValue (Json.Decode.at [ "schema" ] Json.Schema.Definitions.decoder) |
| 26 | + |> Result.withDefault Json.Schema.Definitions.blankSchema |
| 27 | + |
| 28 | + value = v |
| 29 | + |> decodeValue (Json.Decode.at [ "value" ] JsonValue.decoder) |
| 30 | + |> Result.toMaybe |
| 31 | + in |
| 32 | + { form = Json.Form.init schema value |
| 33 | + , editedValue = value |
| 34 | + } |
| 35 | + ! [ loadSnippet "traveller" ] |
| 36 | + |
| 37 | + |
| 38 | +type Msg |
| 39 | + = JsonFormMsg Json.Form.Msg |
| 40 | + | ChangeValue Value |
| 41 | + |
| 42 | + |
| 43 | +update : Msg -> Model -> ( Model, Cmd Msg ) |
| 44 | +update message model = |
| 45 | + case message of |
| 46 | + ChangeValue v -> |
| 47 | + { model | editedValue = v |> decodeValue JsonValue.decoder |> Result.toMaybe |
| 48 | + } |
| 49 | + ! [] |
| 50 | + |
| 51 | + JsonFormMsg msg -> |
| 52 | + let |
| 53 | + ( ( m, cmd ), exMsg ) = |
| 54 | + Json.Form.update msg model.form |
| 55 | + in |
| 56 | + { model |
| 57 | + | form = m |
| 58 | + , editedValue = |
| 59 | + case exMsg of |
| 60 | + Json.Form.UpdateValue v -> |
| 61 | + v |
| 62 | + |
| 63 | + _ -> |
| 64 | + model.editedValue |
| 65 | + } |
| 66 | + ! [ cmd |> Cmd.map JsonFormMsg ] |
| 67 | + |
| 68 | + |
| 69 | +view : Model -> Html Msg |
| 70 | +view model = |
| 71 | + model.form |
| 72 | + |> Json.Form.view |
| 73 | + |> Html.map JsonFormMsg |
| 74 | + |
| 75 | + |
| 76 | +port loadSnippet : String -> Cmd msg |
| 77 | + |
| 78 | + |
| 79 | +port valueChange : (Value -> msg) -> Sub msg |
| 80 | + |
| 81 | + |
| 82 | +subscriptions : Model -> Sub Msg |
| 83 | +subscriptions _ = |
| 84 | + valueChange ChangeValue |
0 commit comments