├── .gitignore ├── COPYING.md ├── LICENSE.md ├── README.md ├── elm-package.json ├── examples ├── 0-counter-part.elm ├── 0-counter.elm ├── 1-counter-pair-part.elm ├── 1-counter-pair.elm ├── 2-counter-list-part.elm ├── 2-counter-list.elm ├── Counter.elm └── elm-package.json └── src └── Parts.elm /.gitignore: -------------------------------------------------------------------------------- 1 | elm-stuff 2 | elm.js 3 | index.html 4 | todo 5 | .*.sw? 6 | docs.json 7 | -------------------------------------------------------------------------------- /COPYING.md: -------------------------------------------------------------------------------- 1 | 2 | Copyright 2016 Søren Debois 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # elm-parts 2 | 3 | The Elm Architecture (TEA) is conceptually very nice, but it forces us to write 4 | large amounts of boilerplate whenever we need to use a component. We must: 5 | 6 | 1. Retain the state of the component in our Model 7 | 2. Add the components actions to our Action 8 | 3. Dispatch those actions in our update 9 | 10 | None of these things have anything to do with what we want from the component, 11 | namely rendering it in our View function, and potentially reacting to some 12 | (but not all) of its actions---e.g., we want to react to a Click of a button, 13 | but we don't care when it updates its animation state. 14 | 15 | This module provides an extensible mechanism for lifting arbitrary 16 | (differently-typed) TEA components into components having the same type of Model 17 | and Action, all of which can be dispatched by the single `update` function in 18 | this module. We call such a lifted component a "part" (think "interchangeable 19 | parts".) 20 | 21 | # Drawbacks 22 | 23 | 1. Elm-parts moves work from component consumers to component authors. As a 24 | component author, you have to produce some elm-parts boilerplate. Producing 25 | this boilerplate is prone to sometimes difficult-to-debug type errors. 26 | 27 | 2. Elm-parts relies on sending functions in messages, in violation of the 28 | [recent guidelines](https://github.com/evancz/elm-sortable-table#usage-rules). 29 | This means consumers of components trying to debug parts messages with 30 | the idiomatic 31 | ```elm 32 | update msg model = 33 | case Debug.log "update" msg of 34 | ... 35 | ``` 36 | will see an unhelpful `Msg ` rather than the actual `Msg` being sent. 37 | 38 | 3. If component users need to access the `Model` of your component or send 39 | messages to its `update` function, you'll need to write additional boilerplate 40 | for the component, exacerbating (1) above. 41 | 42 | One appropriate use-case for elm-parts, where you can accept these drawbacks, 43 | is when writing a UI-component library. (Incidentally, its the only such 44 | use-case I know of.) As a library author, (1) you should be 45 | willing to take upon yourself the tediousness of (1) for your users. (2) Your 46 | users shouldn't care about your internal messages anyway. 47 | And (3) UI-components generally, but not always, can be written such that they 48 | are configured exclusively through view (3)---again, see [sortable table](https://github.com/evancz/elm-sortable-table/blob/master/examples/1-presidents.elm). 49 | 50 | Elm-parts was developed and is in active use as a supporting library for 51 | [elm-mdl](https://github.com/debois/elm-mdl). 52 | 53 | # Examples 54 | 55 | The 56 | [examples folder](https://github.com/debois/elm-parts/tree/master/examples) 57 | contains the first two steps of the 58 | [Elm Architecture Tutorial](https://github.com/evancz/elm-architecture-tutorial) 59 | where the Counter is implemented as a part. To build, e.g., step 1: 60 | 61 | elm-make examples/0-counter-part.elm 62 | 63 | Its instructive to see the diff between 64 | [0-counter-part.elm](https://github.com/debois/elm-parts/blob/master/examples/0-counter-part.elm) (1 counter) 65 | and 66 | [1-counter-pair-part.elm](https://github.com/debois/elm-parts/blob/master/examples/1-counter-pair-part.elm) 67 | (2 counters). It's just this: 68 | ```patch 69 | 60a61 70 | > , Counter.render CounterMsg [1] model 71 | ``` 72 | That is, additional instances of a single component require changes __only__ where you 73 | render them, in your `view` function. 74 | -------------------------------------------------------------------------------- /elm-package.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "5.0.0", 3 | "summary": "Reduce Elm Architecture boilerplate", 4 | "repository": "https://github.com/debois/elm-parts.git", 5 | "license": "Apache License, version 2.0", 6 | "source-directories": [ 7 | "src", 8 | "examples" 9 | ], 10 | "exposed-modules": [ 11 | "Parts" 12 | ], 13 | "dependencies": { 14 | "elm-lang/core": "5.0.0 <= v < 6.0.0" 15 | }, 16 | "elm-version": "0.18.0 <= v < 0.19.0" 17 | } 18 | -------------------------------------------------------------------------------- /examples/0-counter-part.elm: -------------------------------------------------------------------------------- 1 | module Main exposing (..) 2 | 3 | import Html exposing (Html, button, div, text) 4 | import Html.App as App 5 | import Html.Events exposing (onClick) 6 | import Dict 7 | import Counter 8 | import Parts 9 | 10 | 11 | main : Program Never 12 | main = 13 | App.program 14 | { init = init 15 | , subscriptions = always Sub.none 16 | , update = update 17 | , view = view 18 | } 19 | 20 | 21 | 22 | -- MODEL 23 | 24 | 25 | type alias Model = 26 | { counter : Counter.Indexed Counter.Model 27 | } 28 | 29 | 30 | init : ( Model, Cmd Msg ) 31 | init = 32 | ( { counter = Dict.empty } 33 | , Cmd.none 34 | ) 35 | 36 | 37 | 38 | -- UPDATE 39 | 40 | 41 | type Msg 42 | = Reset 43 | | CounterMsg (Parts.Msg Model Msg) 44 | 45 | 46 | update : Msg -> Model -> ( Model, Cmd Msg ) 47 | update msg model = 48 | case msg of 49 | Reset -> 50 | init 51 | 52 | CounterMsg msg_ -> 53 | Parts.update msg_ model 54 | 55 | 56 | 57 | -- VIEW 58 | 59 | 60 | view : Model -> Html Msg 61 | view model = 62 | div 63 | [] 64 | [ Counter.render CounterMsg [ 0 ] model 65 | , button [ onClick Reset ] [ text "RESET" ] 66 | ] 67 | -------------------------------------------------------------------------------- /examples/0-counter.elm: -------------------------------------------------------------------------------- 1 | module Main exposing (..) 2 | 3 | import Counter 4 | import Html exposing (Html, button, div, text) 5 | import Html.App as App 6 | import Html.Events exposing (onClick) 7 | 8 | 9 | main : Program Never 10 | main = 11 | App.program 12 | { init = init 0 13 | , update = update 14 | , view = view 15 | , subscriptions = always Sub.none 16 | } 17 | 18 | 19 | 20 | -- MODEL 21 | 22 | 23 | type alias Model = 24 | { counter : Counter.Model 25 | } 26 | 27 | 28 | init : Int -> ( Model, Cmd Msg ) 29 | init x = 30 | ( { counter = Counter.init x } 31 | , Cmd.none 32 | ) 33 | 34 | 35 | 36 | -- UPDATE 37 | 38 | 39 | type Msg 40 | = Reset 41 | | CounterMsg Counter.Msg 42 | 43 | 44 | update : Msg -> Model -> ( Model, Cmd Msg ) 45 | update message model = 46 | case message of 47 | Reset -> 48 | init 0 49 | 50 | CounterMsg msg -> 51 | let 52 | ( counter_, cmd ) = 53 | Counter.update msg model.counter 54 | in 55 | ( { model | counter = counter_ } 56 | , Cmd.map CounterMsg cmd 57 | ) 58 | 59 | 60 | 61 | -- VIEW 62 | 63 | 64 | view : Model -> Html Msg 65 | view model = 66 | div 67 | [] 68 | [ Counter.view CounterMsg model.counter 69 | -- We avoid Html.App.map because of 70 | -- https://github.com/elm-lang/html/issues/16 71 | , button [ onClick Reset ] [ text "RESET" ] 72 | ] 73 | -------------------------------------------------------------------------------- /examples/1-counter-pair-part.elm: -------------------------------------------------------------------------------- 1 | module Main exposing (..) 2 | 3 | import Html exposing (Html, button, div, text) 4 | 5 | import Html.Events exposing (onClick) 6 | import Dict 7 | import Counter 8 | import Parts 9 | 10 | 11 | main : Program Never 12 | main = 13 | App.program 14 | { init = init 15 | , subscriptions = always Sub.none 16 | , update = update 17 | , view = view 18 | } 19 | 20 | 21 | 22 | -- MODEL 23 | 24 | 25 | type alias Model = 26 | { counter : Counter.Indexed Counter.Model 27 | } 28 | 29 | 30 | init : ( Model, Cmd Msg ) 31 | init = 32 | ( { counter = Dict.empty } 33 | , Cmd.none 34 | ) 35 | 36 | 37 | 38 | -- UPDATE 39 | 40 | 41 | type Msg 42 | = Reset 43 | | CounterMsg (Parts.Msg Model Msg) 44 | 45 | 46 | update : Msg -> Model -> ( Model, Cmd Msg ) 47 | update msg model = 48 | case msg of 49 | Reset -> 50 | init 51 | 52 | CounterMsg msg_ -> 53 | Parts.update msg_ model 54 | 55 | 56 | 57 | -- VIEW 58 | 59 | 60 | view : Model -> Html Msg 61 | view model = 62 | div 63 | [] 64 | [ Counter.render CounterMsg [ 0 ] model 65 | , Counter.render CounterMsg [ 1 ] model 66 | , button [ onClick Reset ] [ text "RESET" ] 67 | ] 68 | -------------------------------------------------------------------------------- /examples/1-counter-pair.elm: -------------------------------------------------------------------------------- 1 | module Main exposing (..) 2 | 3 | import Counter 4 | import Html exposing (Html, button, div, text) 5 | import Html.App as App 6 | import Html.Events exposing (onClick) 7 | 8 | 9 | main : Program Never 10 | main = 11 | App.program 12 | { init = init 0 0 13 | , update = update 14 | , view = view 15 | , subscriptions = always Sub.none 16 | } 17 | 18 | 19 | 20 | -- MODEL 21 | 22 | 23 | type alias Model = 24 | { topCounter : Counter.Model 25 | , bottomCounter : Counter.Model 26 | } 27 | 28 | 29 | init : Int -> Int -> ( Model, Cmd Msg ) 30 | init top bottom = 31 | ( { topCounter = Counter.init top 32 | , bottomCounter = Counter.init bottom 33 | } 34 | , Cmd.none 35 | ) 36 | 37 | 38 | 39 | -- UPDATE 40 | 41 | 42 | type Msg 43 | = Reset 44 | | Top Counter.Msg 45 | | Bottom Counter.Msg 46 | 47 | 48 | update : Msg -> Model -> ( Model, Cmd Msg ) 49 | update message model = 50 | case message of 51 | Reset -> 52 | init 0 0 53 | 54 | Top msg -> 55 | let 56 | ( counter_, cmd ) = 57 | Counter.update msg model.topCounter 58 | in 59 | ( { model | topCounter = counter_ } 60 | , Cmd.map Top cmd 61 | ) 62 | 63 | Bottom msg -> 64 | let 65 | ( counter_, cmd ) = 66 | Counter.update msg model.bottomCounter 67 | in 68 | ( { model | bottomCounter = counter_ } 69 | , Cmd.map Bottom cmd 70 | ) 71 | 72 | 73 | 74 | -- VIEW 75 | 76 | 77 | view : Model -> Html Msg 78 | view model = 79 | div 80 | [] 81 | [ Counter.view Top model.topCounter 82 | , Counter.view Bottom model.bottomCounter 83 | -- We avoid Html.App.map because of 84 | -- https://github.com/elm-lang/html/issues/16 85 | , button [ onClick Reset ] [ text "RESET" ] 86 | ] 87 | -------------------------------------------------------------------------------- /examples/2-counter-list-part.elm: -------------------------------------------------------------------------------- 1 | module Main exposing (..) 2 | 3 | import Html exposing (Html, button, div, text) 4 | import Html.App as App 5 | import Html.Events exposing (onClick) 6 | import Dict 7 | import Counter 8 | import Parts 9 | 10 | 11 | main : Program Never 12 | main = 13 | App.program 14 | { init = ( init, Cmd.none ) 15 | , subscriptions = always Sub.none 16 | , update = update 17 | , view = view 18 | } 19 | 20 | 21 | 22 | -- MODEL 23 | 24 | 25 | type alias Model = 26 | { counter : Counter.Indexed Counter.Model 27 | , first : Int 28 | , last : Int 29 | } 30 | 31 | 32 | init : Model 33 | init = 34 | { counter = Dict.empty 35 | , first = 0 36 | , last = -1 37 | } 38 | 39 | 40 | 41 | -- UPDATE 42 | 43 | 44 | type Msg 45 | = Insert 46 | | Remove 47 | | CounterMsg (Parts.Msg Model Msg) 48 | 49 | 50 | reset : Int -> Model -> Model 51 | reset k model = 52 | .reset (Counter.find [ k ]) model 53 | 54 | 55 | update : Msg -> Model -> ( Model, Cmd Msg ) 56 | update msg model = 57 | case msg of 58 | Insert -> 59 | ( { model | last = model.last + 1 } |> reset (model.last + 1) 60 | , Cmd.none 61 | ) 62 | 63 | Remove -> 64 | ( { model | first = model.first + 1 } |> reset model.first 65 | , Cmd.none 66 | ) 67 | 68 | CounterMsg msg_ -> 69 | Parts.update msg_ model 70 | 71 | 72 | 73 | -- VIEW 74 | 75 | 76 | view : Model -> Html Msg 77 | view model = 78 | let 79 | remove = 80 | button [ onClick Remove ] [ text "Remove" ] 81 | 82 | insert = 83 | button [ onClick Insert ] [ text "Add" ] 84 | 85 | counters = 86 | List.range model.first model.last 87 | |> List.map 88 | (\idx -> Counter.render CounterMsg [ idx ] model) 89 | in 90 | div [] ([ remove, insert ] ++ counters) 91 | -------------------------------------------------------------------------------- /examples/2-counter-list.elm: -------------------------------------------------------------------------------- 1 | module Main exposing (..) 2 | 3 | import Counter 4 | import Html exposing (..) 5 | import Html.App as App 6 | import Html.Events exposing (..) 7 | 8 | 9 | main : Program Never 10 | main = 11 | App.beginnerProgram 12 | { model = init 13 | , update = update 14 | , view = view 15 | } 16 | 17 | 18 | 19 | -- MODEL 20 | 21 | 22 | type alias Model = 23 | { counters : List ( ID, Counter.Model ) 24 | , nextID : ID 25 | } 26 | 27 | 28 | type alias ID = 29 | Int 30 | 31 | 32 | init : Model 33 | init = 34 | { counters = [] 35 | , nextID = 0 36 | } 37 | 38 | 39 | 40 | -- UPDATE 41 | 42 | 43 | type Msg 44 | = Insert 45 | | Remove 46 | | Modify ID Counter.Msg 47 | 48 | 49 | update : Msg -> Model -> Model 50 | update msg model = 51 | case msg of 52 | Insert -> 53 | let 54 | newCounter = 55 | ( model.nextID, Counter.init 0 ) 56 | 57 | newCounters = 58 | model.counters ++ [ newCounter ] 59 | in 60 | Model newCounters (model.nextID + 1) 61 | 62 | Remove -> 63 | { model | counters = List.drop 1 model.counters } 64 | 65 | Modify id counterMsg -> 66 | let 67 | updateCounter ( counterID, counterModel ) = 68 | if counterID == id then 69 | ( counterID, Counter.update counterMsg counterModel |> Tuple.first ) 70 | else 71 | ( counterID, counterModel ) 72 | in 73 | { model | counters = List.map updateCounter model.counters } 74 | 75 | 76 | 77 | -- VIEW 78 | 79 | 80 | view : Model -> Html Msg 81 | view model = 82 | let 83 | remove = 84 | button [ onClick Remove ] [ text "Remove" ] 85 | 86 | insert = 87 | button [ onClick Insert ] [ text "Add" ] 88 | 89 | counters = 90 | List.map viewCounter model.counters 91 | in 92 | div [] ([ remove, insert ] ++ counters) 93 | 94 | 95 | viewCounter : ( ID, Counter.Model ) -> Html Msg 96 | viewCounter ( id, model ) = 97 | Counter.view (Modify id) model 98 | -------------------------------------------------------------------------------- /examples/Counter.elm: -------------------------------------------------------------------------------- 1 | module Counter exposing (Model, init, Msg, update, view, render, find, Index, Indexed) 2 | 3 | import Html exposing (..) 4 | import Html.Attributes exposing (..) 5 | import Html.Events exposing (onClick) 6 | import Parts 7 | 8 | 9 | -- MODEL 10 | 11 | 12 | type alias Model = 13 | Int 14 | 15 | 16 | init : Int -> Model 17 | init count = 18 | count 19 | 20 | 21 | 22 | -- UPDATE 23 | 24 | 25 | type Msg 26 | = Increment 27 | | Decrement 28 | 29 | 30 | update : Msg -> Model -> ( Model, Cmd Msg ) 31 | update msg model = 32 | case msg of 33 | Increment -> 34 | ( model + 1, Cmd.none ) 35 | 36 | Decrement -> 37 | ( model - 1, Cmd.none ) 38 | 39 | 40 | 41 | -- VIEW 42 | 43 | 44 | view : (Msg -> m) -> Model -> Html m 45 | view lift model = 46 | div 47 | [] 48 | [ button [ onClick (lift Decrement) ] [ text "-" ] 49 | , div [ countStyle ] [ text (toString model) ] 50 | , button [ onClick (lift Increment) ] [ text "+" ] 51 | ] 52 | 53 | 54 | countStyle : Attribute msg 55 | countStyle = 56 | style 57 | [ ( "font-size", "20px" ) 58 | , ( "font-family", "monospace" ) 59 | , ( "display", "inline-block" ) 60 | , ( "width", "50px" ) 61 | , ( "text-align", "center" ) 62 | ] 63 | 64 | 65 | 66 | -- PART 67 | 68 | 69 | type alias Indexed m = 70 | Parts.Indexed (List Int) m 71 | 72 | 73 | type alias Index = 74 | Parts.Index (List Int) 75 | 76 | 77 | type alias Container c = 78 | { c | counter : Indexed Model } 79 | 80 | 81 | set : Parts.Set (Indexed Model) (Container c) 82 | set x y = 83 | { y | counter = x } 84 | 85 | 86 | render : (Parts.Msg (Container c) m -> m) -> Index -> Container c -> Html m 87 | render = 88 | Parts.create view (Parts.generalize update) .counter set (init 0) 89 | 90 | 91 | find : Index -> Parts.Accessors Model (Container c) 92 | find = 93 | Parts.accessors .counter set (init 0) 94 | -------------------------------------------------------------------------------- /examples/elm-package.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.0.0", 3 | "summary": "Examples of The Elm Architecture", 4 | "repository": "https://github.com/elm-lang/elm-architecture-tutorial.git", 5 | "license": "BSD3", 6 | "source-directories": [ 7 | ".", 8 | "../src" 9 | ], 10 | "exposed-modules": [], 11 | "dependencies": { 12 | "elm-lang/core": "4.0.0 <= v < 5.0.0", 13 | "elm-lang/html": "1.0.0 <= v < 2.0.0", 14 | "elm-lang/svg": "1.0.0 <= v < 2.0.0", 15 | "elm-lang/websocket": "1.0.0 <= v < 2.0.0", 16 | "evancz/elm-http": "3.0.1 <= v < 4.0.0" 17 | }, 18 | "elm-version": "0.17.0 <= v < 0.18.0" 19 | } 20 | -------------------------------------------------------------------------------- /src/Parts.elm: -------------------------------------------------------------------------------- 1 | module Parts 2 | exposing 3 | ( Update 4 | , View 5 | , Get 6 | , Set 7 | , embedView 8 | , embedUpdate 9 | , Index 10 | , Indexed 11 | , indexed 12 | , Msg 13 | , partial 14 | , update 15 | , update_ 16 | , create 17 | , create1 18 | , accessors 19 | , Accessors 20 | , generalize 21 | , pack 22 | , pack1 23 | ) 24 | 25 | {-| 26 | 27 | Given a TEA component with model type `model` and message type `msg`, we construct 28 | a variant component which knows how to extract its model from a c model 29 | `c` and produces generic messages `Msg c`. The consuming component is assumed 30 | to have message type `obs` (for "observation"). 31 | 32 | # Lazyness 33 | 34 | Recall that `Html.Lazy` avoids re-computing views when the model doesn't change 35 | across updates. However, "doesn't change" does not mean `model == model'` but rather 36 | the stricter `model === model'` (in Javascript terms). That is, the old and new model 37 | must not only be structurally the same, they must be literally the same 38 | data-structure in memory. 39 | 40 | Parts generally do not achieve referential equality of no-op updates, since we 41 | are wrapping updates conceptually like this: 42 | 43 | let (submodel, submsgs) = SubComponent.update msg model.submodel 44 | model' = { model | submodel = submodel } 45 | in 46 | ... 47 | In the second line, even if `submodel == model.submodel` and so `model == 48 | model'`, we won't have (in Javascript terms) `model === model'`. 49 | 50 | For this reason, the result of `update` functions used in parts should be 51 | `Maybe (model, Cmd msg)` rather than the usual `(model, Cmd msg)`; the 52 | `Nothing` case signifies a no-op. 53 | 54 | # Communicating to the parent component 55 | 56 | Because parts wrap messages in an opaque type, the parent component loses the 57 | ability to inspect and maybe react to messages of the part. We recover this 58 | ability by requiring the `update` function to take as parameter a lifting 59 | function which lifts the parts messages to that of its parent. 60 | 61 | @docs Update, View 62 | 63 | # Model embeddings 64 | @docs Get, Set, embedView, embedUpdate 65 | @docs accessors, Accessors 66 | 67 | ## Indexed model embeddings 68 | @docs Index, Indexed, indexed 69 | 70 | # Message embeddings 71 | @docs Msg, update, update_, partial 72 | 73 | # Part construction 74 | @docs create, create1, generalize, pack, pack1 75 | -} 76 | 77 | import Dict exposing (Dict) 78 | 79 | 80 | -- TYPES 81 | 82 | 83 | {-| Update functions. 84 | 85 | TEA update function with explicit message lifting and no-op. You should have: 86 | 87 | fst (update f msg model) == Nothing -- No change to model 88 | fst (update f msg model) == Just model' -- Change to model' 89 | -} 90 | type alias Update model msg obs = 91 | (msg -> obs) -> msg -> model -> ( Maybe model, Cmd obs ) 92 | 93 | 94 | {-| Standard TEA view function type. 95 | -} 96 | type alias View model a = 97 | model -> a 98 | 99 | 100 | 101 | -- EMBEDDINGS 102 | 103 | 104 | {-| Type of "getter": fetch component model `m` from c model `c`. 105 | -} 106 | type alias Get model c = 107 | c -> model 108 | 109 | 110 | {-| Type of "setter": update component model `m` in c `c`. 111 | -} 112 | type alias Set model c = 113 | model -> c -> c 114 | 115 | 116 | {-| Lift a `view` to one which knows how to retrieve its `model` from 117 | a c model `c`. 118 | -} 119 | embedView : Get model c -> View model a -> View c a 120 | embedView get view = 121 | get >> view 122 | 123 | 124 | {-| Lift an `Update` from operating on `model` to a c model `c`. 125 | -} 126 | embedUpdate : 127 | Get model c 128 | -> Set model c 129 | -> Update model msg obs 130 | -> Update c msg obs 131 | embedUpdate get set update = 132 | \f msg c -> 133 | update f msg (get c) 134 | |> map1st (Maybe.map <| flip set c) 135 | 136 | 137 | 138 | -- INDEXED EMBEDDINGS 139 | 140 | 141 | {-| Type of indices. An index has to be `comparable` 142 | 143 | For example: 144 | An index can be a list of `Int` rather than just an `Int` to 145 | support nested dynamically constructed elements: Use indices `[0]`, `[1]`, ... 146 | for statically known top-level components, then use `[0,0]`, `[0,1]`, ... 147 | for a dynamically generated list of components. 148 | -} 149 | type alias Index comparable = 150 | comparable 151 | 152 | 153 | {-| Indexed families of things. 154 | -} 155 | type alias Indexed comparable a = 156 | Dict (Index comparable) a 157 | 158 | 159 | {-| Fix a getter and setter for an `Indexed comparable model` to a particular `Index comparable`. 160 | -} 161 | indexed : 162 | Get (Indexed comparable model) c 163 | -> Set (Indexed comparable model) c 164 | -> model 165 | -> ( Index comparable -> Get model c, Index comparable -> Set model c ) 166 | indexed get set model0 = 167 | ( \idx c -> Dict.get idx (get c) |> Maybe.withDefault model0 168 | , \idx model c -> set (Dict.insert idx model (get c)) c 169 | ) 170 | 171 | 172 | 173 | -- EMBEDDING MESSAGES 174 | 175 | 176 | {-| Similar to how embeddings enable collecting models of different type 177 | in a single model c, we collect messages in a single "master 178 | message" type. Messages exist exclusively to be dispatched by a corresponding 179 | `update` function; we can avoid distinguishing between different types of 180 | messages by dispatching not the `Msg` itself, but a partially applied update 181 | function `update msg`. 182 | 183 | It's instructive to compare `Msg` to the type of `update` partially applied to 184 | an actual carried message `m`: 185 | 186 | update : m -> c -> (c, Cmd m) 187 | (update m) : c -> (c, Cmd m) 188 | -} 189 | type Msg c obs 190 | = Msg (c -> ( Maybe c, Cmd obs )) 191 | 192 | 193 | {-| Generic update function for `Msg`. 194 | -} 195 | update : Msg c obs -> c -> ( c, Cmd obs ) 196 | update (Msg f) c = 197 | f c |> map1st (Maybe.withDefault c) 198 | 199 | 200 | {-| Generic update function for `Msg`, explicit no-op 201 | -} 202 | update_ : Msg c obs -> c -> ( Maybe c, Cmd obs ) 203 | update_ (Msg f) c = 204 | f c 205 | 206 | 207 | 208 | -- PARTS 209 | 210 | 211 | {-| Partially apply an `Update` function to a `msg`, producing 212 | a generic Msg. 213 | -} 214 | partial : (Msg c obs -> obs) -> Update c msg obs -> msg -> Msg c obs 215 | partial fwd upd msg = 216 | Msg 217 | (\c -> 218 | upd (partial fwd upd >> fwd) msg c 219 | ) 220 | 221 | 222 | {-| Pack up a an indexed component message `msg` in an `obs`. 223 | -} 224 | pack : 225 | Update model msg obs 226 | -> Get (Indexed comparable model) c 227 | -> Set (Indexed comparable model) c 228 | -> model 229 | -> (Msg c obs -> obs) 230 | -> Index comparable 231 | -> msg 232 | -> obs 233 | pack update get0 set0 model0 fwd = 234 | let 235 | ( get, set ) = 236 | indexed get0 set0 model0 237 | in 238 | \idx -> 239 | partial fwd (embedUpdate (get idx) (set idx) update) >> fwd 240 | 241 | 242 | {-| Pack up a singleton component message `msg` in an `obs`. 243 | -} 244 | pack1 : 245 | Update model msg obs 246 | -> Get model c 247 | -> Set model c 248 | -> (Msg c obs -> obs) 249 | -> msg 250 | -> obs 251 | pack1 update get set fwd = 252 | partial fwd (embedUpdate get set update) >> fwd 253 | 254 | 255 | {-| From `update` and `view` functions, produce a `view` function which (a) 256 | fetches its model from a `c` model, and (b) dispatches generic `Msg` 257 | messages. 258 | 259 | Its instructive to compare the types of the input `view` and `update` for a 260 | typical case. Notice that `create` transforms `model` -> `c` and 261 | `Html m` -> `Html obs`. 262 | 263 | {- Input -} 264 | view : (m -> obs) -> model -> List (Attributes obs) -> List (Html obs) -> Html obs 265 | update : (m -> obs) -> model -> (Maybe model, Cmd obs) 266 | 267 | {- Output -} 268 | view : Index comparable -> c -> List (Attributes obs) -> List (Html obs) -> Html obs 269 | 270 | Note that the input `view` function is assumed to take a function lifting its 271 | messages. 272 | -} 273 | create : 274 | ((msg -> obs) -> View model a) 275 | -> Update model msg obs 276 | -> Get (Indexed comparable model) c 277 | -> Set (Indexed comparable model) c 278 | -> model 279 | -> (Msg c obs -> obs) 280 | -> Index comparable 281 | -> View c a 282 | create view update get0 set0 model0 fwd = 283 | let 284 | get = 285 | Tuple.first (indexed get0 set0 model0) 286 | 287 | embeddedUpdate = 288 | pack update get0 set0 model0 fwd 289 | in 290 | \idx c -> 291 | (view (embeddedUpdate idx) (get idx c)) 292 | 293 | 294 | {-| Like `create`, but for components that are assumed to have only one 295 | instance. 296 | -} 297 | create1 : 298 | ((msg -> obs) -> View model a) 299 | -> Update model msg obs 300 | -> Get model c 301 | -> Set model c 302 | -> (Msg c obs -> obs) 303 | -> View c a 304 | create1 view update get set fwd = 305 | let 306 | embeddedUpdate = 307 | partial fwd (embedUpdate get set update) >> fwd 308 | in 309 | embedView get <| view embeddedUpdate 310 | 311 | 312 | {-| For components where consumers do care about the model of the 313 | component, use the `accessors` function below to generate suitable, 314 | well, accessors. 315 | -} 316 | type alias Accessors model c = 317 | { get : Get model c 318 | , set : Set model c 319 | , map : (model -> model) -> c -> c 320 | , reset : c -> c 321 | } 322 | 323 | 324 | {-| Generate accessors. 325 | -} 326 | accessors : 327 | Get (Dict comparable model) c 328 | -> Set (Dict comparable model) c 329 | -> model 330 | -> Index comparable 331 | -> Accessors model c 332 | accessors get0 set0 model0 idx = 333 | let 334 | ( get, set ) = 335 | indexed get0 set0 model0 336 | in 337 | { get = get idx 338 | , set = set idx 339 | , map = \f c -> (get idx) c |> f |> flip (set idx) c 340 | , reset = \c -> get0 c |> Dict.remove idx |> (\m -> set0 m c) 341 | } 342 | 343 | 344 | {-| Generalise a standard TEA `update` function to one fitting with 345 | parts (explicit lifter, explicit no-op). 346 | -} 347 | generalize : 348 | (msg -> model -> ( model, Cmd msg )) 349 | -> Update model msg obs 350 | generalize upd f m c = 351 | upd m c 352 | |> map1st Just 353 | |> map2nd (Cmd.map f) 354 | 355 | 356 | 357 | -- HELPERS 358 | 359 | 360 | map1st : (a -> c) -> ( a, b ) -> ( c, b ) 361 | map1st f ( x, y ) = 362 | ( f x, y ) 363 | 364 | 365 | map2nd : (b -> c) -> ( a, b ) -> ( a, c ) 366 | map2nd f ( x, y ) = 367 | ( x, f y ) 368 | --------------------------------------------------------------------------------